"""Ordinal GP regression via approximate inference."""
# Uncomment to enable double precision
from jax.config import config
config.update("jax_enable_x64", True)

from probit.utilities import (
    InvalidKernel, check_cutpoints,
    log_probit_likelihood, probit_predictive_distributions)
import numpy as np
import lab as B
import jax.numpy as jnp
import jax.random as random
from mlkernels import Kernel, Matern12, EQ
from varz import Vars, minimise_l_bfgs_b, parametrised, Positive
import matplotlib.pyplot as plt
import argparse
import cProfile
from io import StringIO
from pstats import Stats, SortKey
import pathlib
import matplotlib.cm as cm
from scipy.optimize import minimize
from jax import vmap, value_and_grad

# For plotting
BG_ALPHA = 1.0
MG_ALPHA = 1.0
FG_ALPHA = 0.3

write_path = pathlib.Path()

def plot(x, predictive_distributions, mean,
         variance, X_show, f_show, X_train, y_train, g_train,
         J, colors, fname="plot"):
    posterior_std = jnp.sqrt(variance)
    fig, ax = plt.subplots(1, 1)
    fig.patch.set_facecolor('white')
    fig.patch.set_alpha(BG_ALPHA)
    ax.set_xlim((-0.5, 1.5))
    ax.set_ylim(0.0, 1.0)
    ax.set_xlabel(r"$x$", fontsize=10)
    ax.set_ylabel("Cumulative probability", fontsize=10)
    ax.stackplot(x[:, 0], predictive_distributions.T, colors=colors,
        labels=(
            r"$p(y=0|\mathcal{D}, \theta)$",
            r"$p(y=1|\mathcal{D}, \theta)$",
            r"$p(y=2|\mathcal{D}, \theta)$"))
    val = 0.5  # where the data lies on the y-axis.
    plt.tight_layout()
    ax.legend()
    fig.savefig(
            "{}_contour.png".format(fname))
    plt.close()

    fig, ax = plt.subplots(1, 1)
    fig.patch.set_facecolor('white')
    fig.patch.set_alpha(BG_ALPHA)
    ax.plot(x[:, 0], mean, color='blue', label="Prediction", linestyle="--")
    ax.fill_between(
        x[:, 0], mean - 2*posterior_std,
        mean + 2*posterior_std,
        color='blue', alpha=FG_ALPHA)
    ax.set_ylim(-2.2, 2.2)
    ax.set_xlim(-0.5, 1.5)
    ax.set_xlabel('x', fontsize=10)
    ax.set_ylabel('y', fontsize=10)
    ax.scatter(X_train, g_train, color=[colors[i] for i in y_train], s=4, label="Observations")
    ax.plot(X_show, f_show, label="True", color='orange', alpha=FG_ALPHA)
    ax.grid(visible=True, which='major', linestyle='-')
    ax.legend()
    plt.tight_layout()
    fig.savefig("{}_mean_variance.png".format(fname),
        facecolor=fig.get_facecolor(), edgecolor='none')
    plt.close()

def plot_obj(x_hat, x_0, x, fs, gs, domain, xlabel, xscale, fname="plot"):
    # Calculate numerical derivatives wrt domain of plot
    if xscale == "log":
        log_x = jnp.log(x)
        dfsx = np.gradient(fs, log_x)
        gs *= x  # Jacobian
    elif xscale == "linear":
        dfsx = np.gradient(fs, x)
    fig = plt.figure()
    fig.patch.set_facecolor('white')
    fig.patch.set_alpha(BG_ALPHA)
    ax = fig.add_subplot(111)
    ax.grid()
    ax.plot(x, fs, 'g', label=r"$\mathcal{F}$ autodiff")
    ylim = ax.get_ylim()
    ax.set_xlim((10**domain[0][0], 10**domain[0][1]))
    ax.set_ylim(ylim)
    ax.vlines(x_hat, ylim[0], ylim[1], 'r',
        alpha=MG_ALPHA, label=r"$\hat\theta={:.2f}$".format(x_hat))
    ax.vlines(x_0, ylim[0], ylim[1], 'k',
        alpha=MG_ALPHA, label=r"$\theta={:.2f}$".format(x_0))
    ax.set_xlabel(xlabel, fontsize=10)
    ax.set_xscale(xscale)
    ax.set_ylabel(r"$\mathcal{F}$", fontsize=10)
    ax.set_title('Hyper-parameter optimisation objective')
    ax.legend()
    fig.savefig("readme_objective.png",
        facecolor=fig.get_facecolor(), edgecolor='none')
    plt.close()

    fig = plt.figure()
    fig.patch.set_facecolor('white')
    fig.patch.set_alpha(BG_ALPHA)
    ax = fig.add_subplot(111)
    ax.grid()
    ax.plot(
        x, gs, 'g', alpha=FG_ALPHA,
        label=r"$\frac{\partial \mathcal{F}}{\partial \theta}$ JAX autodiff")
    ax.set_ylim(ax.get_ylim())
    ax.set_xlim((10**domain[0][0], 10**domain[0][1]))
    ax.plot(
        x, dfsx, 'g--',
        label=r"$\frac{\partial \mathcal{F}}{\partial \theta}$ numerical")
    ylim = ax.get_ylim()
    ax.vlines(x_hat, ylim[0], ylim[1], 'r',
        alpha=MG_ALPHA, label=r"$\hat\theta={:.2f}$".format(x_hat))
    ax.vlines(x_0, ylim[0], ylim[1], 'k',
        alpha=MG_ALPHA, label=r"$\theta={:.2f}$".format(x_0))
    ax.set_xscale(xscale)
    ax.set_xlabel(xlabel, fontsize=10)
    ax.set_ylabel(r"$\frac{\partial \mathcal{F}}{\partial \theta}$", fontsize=10)
    ax.set_title('Hyper-parameter optimisation gradient')
    ax.legend()
    fig.savefig("readme_grad.png",
        facecolor=fig.get_facecolor(), edgecolor='none')
    plt.close()

def generate_data(
        key, N_train_per_class, N_test_per_class,
        J, kernel, noise_variance,
        N_show, jitter=1e-6):
    """
    Generate data from the GP prior, and choose some cutpoints that
    approximately divides data into equal bins.

    :arg key: JAX random key, a random seed.
    :arg int N_train_per_class: The number of data points per class.
    :arg int N_test_per_class: The number of data points per class.
    :arg int J: The number of bins/classes/quantiles.
    :arg kernel: The GP prior.
    :arg noise_variance: The noise variance.
    :arg int N_show: The number of data points to plot.
    :arg jitter: For making Gram matrix better conditioned,
        so that Cholesky decomposition can be performed.
        Try 1e-5 for single precision or 1e-10 for double
        precision.
    """
    # Generate input data from a linear grid
    X_show = jnp.linspace(-0.5, 1.5, N_show)
    # reshape X to make it (n, 1)
    X_show = X_show[:, None]

    N_train = int(J * N_train_per_class)
    N_test = int(J * N_test_per_class)
    N_total = N_train + N_test
    N_per_class = N_train_per_class + N_test_per_class

    # Sample from the real line, uniformly
    key, step_key = random.split(key, 2)
    X_data = random.uniform(key, minval=0.0, maxval=1.0, shape=(N_total, 1))

    # Concatenate X_data and X_show
    X = jnp.append(X_data, X_show, axis=0)

    # Sample from a multivariate normal
    K = B.dense(kernel(X))
    K = K + jitter * jnp.identity(jnp.shape(X)[0])
    L_K = jnp.linalg.cholesky(K)

    # Generate normal samples for both sets of input data
    key, step_key = random.split(key, 2)
    z = random.normal(key,
        shape=(jnp.shape(X_data)[0] + jnp.shape(X_show)[0],))
    f = L_K @ z

    # Store f_show
    f_data = f[:N_total]
    f_show = f[N_total:]

    assert jnp.shape(f_show) == (jnp.shape(X_show)[0],)

    # Generate the latent variables
    X = X_data
    f = f_data
    key, step_key = random.split(key, 2)
    epsilons = jnp.sqrt(noise_variance) * random.normal(key, shape=(N_total,))
    g = epsilons + f
    g = g.flatten()

    # Sort the responses
    idx_sorted = jnp.argsort(g)
    g = g[idx_sorted]
    f = f[idx_sorted]
    X = X[idx_sorted]
    X_js = []
    g_js = []
    f_js = []
    y_js = []
    cutpoints = jnp.empty(J + 1)
    for j in range(J):
        X_js.append(X[N_per_class * j:N_per_class * (j + 1), :1])
        g_js.append(g[N_per_class * j:N_per_class * (j + 1)])
        f_js.append(f[N_per_class * j:N_per_class * (j + 1)])
        y_js.append(j * jnp.ones(N_per_class, dtype=int))

    for j in range(1, J):
        # Find the cutpoints
        cutpoint_j_min = g_js[j - 1][-1]
        cutpoint_j_max = g_js[j][0]
        cutpoints = cutpoints.at[j].set(jnp.mean(jnp.array([cutpoint_j_max, cutpoint_j_min])))
    cutpoints = cutpoints.at[0].set(-jnp.inf)
    cutpoints = cutpoints.at[-1].set(jnp.inf)
    X_js = jnp.array(X_js)
    g_js = jnp.array(g_js)
    f_js = jnp.array(f_js)
    y_js = jnp.array(y_js, dtype=int)
    X = X.reshape(-1, X.shape[-1])
    g = g_js.flatten()
    f = f_js.flatten()
    y = y_js.flatten()
    y = jnp.array(y, dtype=int)

    g_train_js = []
    X_train_js = []
    y_train_js = []
    X_test_js = []
    y_test_js = []
    for j in range(J):
        data = jnp.c_[g_js[j], X_js[j], y_js[j]]
        key, step_key = random.split(key, 2)
        random.shuffle(key, data)
        g_j = data[:, :1]
        X_j = data[:, 1:1 + 1]
        y_j = data[:, -1]
        # split train vs test/validate
        g_train_j = g_j[:N_train_per_class]
        X_train_j = X_j[:N_train_per_class]
        y_train_j = y_j[:N_train_per_class]
        X_j = X_j[N_train_per_class:]
        y_j = y_j[N_train_per_class:]
        X_train_js.append(X_train_j)
        g_train_js.append(g_train_j)
        y_train_js.append(y_train_j)
        X_test_js.append(X_j)
        y_test_js.append(y_j)

    X_train_js = jnp.array(X_train_js)
    g_train_js = jnp.array(g_train_js)
    y_train_js = jnp.array(y_train_js, dtype=int)
    X_test_js = jnp.array(X_test_js)
    y_test_js = jnp.array(y_test_js, dtype=int)

    X_train = X_train_js.reshape(-1, X_train_js.shape[-1])
    g_train = g_train_js.flatten()
    y_train = y_train_js.flatten()
    X_test = X_test_js.reshape(-1, X_test_js.shape[-1])
    y_test = y_test_js.flatten()

    y_train = jnp.array(y_train, dtype=int)
    y_test = jnp.array(y_test, dtype=int)

    return (
        N_show, X, g, y, cutpoints,
        X_test, y_test,
        X_show, f_show)

def calculate_metrics(y_test, predictive_distributions):
    y_pred = jnp.argmax(predictive_distributions, axis=1)
    predictive_likelihood = predictive_distributions[:, y_test]
    mean_absolute_error = jnp.sum(jnp.abs(y_pred - y_test)) / len(y_test)
    print(jnp.sum(y_pred != y_test), "sum incorrect")
    print(jnp.sum(y_pred == y_test), "sum correct")
    print("mean_absolute_error={:.2f}".format(mean_absolute_error))
    log_predictive_probability = jnp.sum(jnp.log(predictive_likelihood))
    print("log_pred_probability={:.2f}".format(log_predictive_probability))
    mean_zero_one = jnp.sum(y_pred != y_test) / len(y_test)
    print("mean_zero_one_error={:.2f}".format(mean_zero_one))
    return (
        mean_zero_one,
        mean_absolute_error,
        log_predictive_probability,
        predictive_likelihood)

def main():
    """Make an approximation to the posterior, and optimise hyperparameters."""
    parser = argparse.ArgumentParser()
    # The --profile argument generates profiling information for the example
    parser.add_argument('--profile', action='store_const', const=True)
    args = parser.parse_args()
    if args.profile:
        profile = cProfile.Profile()
        profile.enable()

    approximate_inference_method = "Laplace"
    if approximate_inference_method=="Variational Bayes":
        from probit.approximators import VBGP as Approximator
    elif approximate_inference_method=="Laplace":
        from probit.approximators import LaplaceGP as Approximator

    J = 3
    cmap = plt.cm.get_cmap('PiYG', J)
    colors = []
    mapping = []
    for j in range(J):
        colors.append(cmap((j + 0.5)/J))
        mapping.append((j + 0.5)/J)
    print(colors)
    print(mapping)

    # Generate data
    key = random.PRNGKey(1)
    noise_variance = 0.4
    signal_variance = 1.0
    lengthscale = 1.0
    kernel = signal_variance * Matern12().stretch(lengthscale)
    (N_show, X, g_true, y, cutpoints,
    X_test, y_test,
    X_show, f_show) = generate_data(key,
        N_train_per_class=10, N_test_per_class=100,
        J=J, kernel=kernel, noise_variance=noise_variance,
        N_show=1000, jitter=1e-6)

    # Initiate a misspecified model, using a kernel
    # other than the one used to generate data
    def prior(prior_parameters):
        # Here you can define the kernel that defines the Gaussian process
        return signal_variance * EQ().stretch(prior_parameters)

    # Test prior
    if not (isinstance(prior(1.0), Kernel)):
        raise InvalidKernel(prior(1.0))

    # check that the cutpoints are in the correct format
    # for the number of classes, J
    cutpoints = check_cutpoints(cutpoints, J)
    print("cutpoints={}".format(cutpoints))

    classifier = Approximator(data=(X, y), prior=prior,
        log_likelihood=log_probit_likelihood,
        # grad_log_likelihood=grad_log_probit_likelihood,
        # hessian_log_likelihood=hessian_log_probit_likelihood,
        tolerance=1e-5  # tolerance for the jaxopt fixed-point resolution
        )
    negative_evidence_lower_bound = classifier.objective()

    vs = Vars(jnp.float32)

    def model(vs):
        p = vs.struct
        noise_std = jnp.sqrt(noise_variance)
        return (p.lengthscale.positive(1.2)), (noise_std, cutpoints)

    def objective(vs):
        return negative_evidence_lower_bound(model(vs))

    # Approximate posterior
    parameters = model(vs)
    weight, precision = classifier.approximate_posterior(parameters)
    mean, variance = classifier.predict(
        X_show,
        parameters,
        weight, precision)
    obs_variance = variance + noise_variance
    predictive_distributions = probit_predictive_distributions(
        parameters[1],
        mean, variance)
    plot(X_show, predictive_distributions, mean,
        obs_variance, X_show, f_show, X, y, g_true,
        J, colors, fname="readme_classification_before")

    # Evaluate model
    mean, variance = classifier.predict(
        X_test,
        parameters,
        weight, precision)
    predictive_distributions = probit_predictive_distributions(
        parameters[1],
        mean, variance)
    print("\nEvaluation of model:")
    calculate_metrics(y_test, predictive_distributions)

    print("Before optimization, \nparameters={}".format(parameters))
    minimise_l_bfgs_b(objective, vs)
    parameters = model(vs)
    print("After optimization, \nparameters={}".format(model(vs)))

    # Approximate posterior
    parameters = model(vs)
    weight, precision = classifier.approximate_posterior(parameters)
    mean, variance = classifier.predict(
        X_show,
        parameters,
        weight, precision)
    predictive_distributions = probit_predictive_distributions(
        parameters[1],
        mean, variance)
    plot(X_show, predictive_distributions, mean,
        obs_variance, X_show, f_show, X, y, g_true,
        J, colors, fname="readme_classification_after")

    # Evaluate model
    mean, variance = classifier.predict(
        X_test,
        parameters,
        weight, precision)
    obs_variance = variance + noise_variance
    predictive_distributions = probit_predictive_distributions(
        parameters[1],
        mean, variance)
    print("\nEvaluation of model:")
    calculate_metrics(y_test, predictive_distributions)

    nelbo = lambda x : negative_evidence_lower_bound(((x), (jnp.sqrt(noise_variance), cutpoints)))
    fg = vmap(value_and_grad(nelbo))

    domain = ((-2, 2), None)
    resolution = (50, None)
    x = jnp.logspace(
        domain[0][0], domain[0][1], resolution[0])
    xlabel = r"lengthscale, $\ell$"
    xscale = "log"
    phis = jnp.log(x)

    fgs = fg(x)
    fs = fgs[0]
    gs = fgs[1]
    plot_obj(vs.struct.lengthscale(), lengthscale, x, fs, gs, domain, xlabel, xscale)

    if args.profile:
        profile.disable()
        s = StringIO()
        stats = Stats(profile, stream=s).sort_stats(SortKey.CUMULATIVE)
        stats.print_stats(.05)
        print(s.getvalue())

if __name__ == "__main__":
    main()


def setZeroes(matrix):
    """
    :type matrix: List[List[int]]
    :rtype: None Do not return anything, modify matrix in-place instead.
    """
    rows = len(matrix)
    cols = len(matrix[0])
    for x in range(rows):
        #x = rows
        #y = cols
        for y in range(cols):
            if matrix[x][y] ==0:
                for a in range(cols):
                    if matrix[x][a] != 0:
                        matrix[x][a] = 'a'
                for b in range(rows):
                    if matrix[b][y] != 0:
                        matrix[b][y] = 'a'
    for x in range(rows):
        for y in range(cols):
            if matrix[x][y] =='a':
                matrix[x][y] =0

    return matrix

print(setZeroes([[0,1]]))


from hypothesis import (
    strategies as st,
)

from trie import (
    HexaryTrie,
)

@st.composite
def random_trie_strategy(draw):
    trie_items = draw(
        st.lists(
            st.tuples(
                # key
                st.binary(max_size=32),
                # value
                st.binary(min_size=1, max_size=64),
            ),
            unique=True,
            max_size=512,
        )
    )

    trie = HexaryTrie({})
    for key, value in trie_items:
        trie[key] = value
    return trie, dict(trie_items)

@st.composite
def trie_keys_with_extensions(draw, allow_empty_trie=True):
    """
    Build trie keys that tend to have lots of extension/branch/leaf nodes.
    Anecdotally, this was more likely to produce examples like the one
    in test_trie_walk_root_change_with_traverse() about TraversedPartialPath.
    """
    # Simplest possible trie: an empty trie
    # Test it about once, on average, per run of 200 tests (the default example count)
    # Also, this will shrink down to the empty trie as you shrink these integers.
    if allow_empty_trie and draw(st.integers(min_value=0, max_value=200)) == 0:
        return ()

    def build_up_from_children(children):
        # Branch out
        return st.tuples(
            st.binary(min_size=0, max_size=3),
            children,
            st.binary(min_size=0, max_size=3),
            children,
        )

    # build tree
    tree = draw(
        st.recursive(
            # key suffix
            st.tuples(
                st.binary(min_size=0, max_size=3),
            ),
            # branches/extensions
            build_up_from_children,
        )
    )

    def unroll_keys(node):
        if len(node) == 1:
            # leaf
            yield node[0]
        elif len(node) == 4:
            # branch
            for subkey in unroll_keys(node[1]):
                yield node[0] + subkey
            for subkey in unroll_keys(node[3]):
                yield node[2] + subkey

    # Use a hashable type here, to make uniqueness checks faster/possible
    return tuple(set(unroll_keys(tree)))

def trie_from_keys(keys, min_value_length=1):
    trie = HexaryTrie({})
    contents = {}
    with trie.squash_changes() as batch:
        for key in keys:
            # flood 3's at the end of the value to make it longer. b'3' is
            # encoded to 0x33, so the bytes and HexBytes representation
            # look the same. Just a convenience.
            value = (b"v" + key).ljust(min_value_length, b"3")
            batch[key] = value
            contents[key] = value

    return trie, contents


#単語をgoogleで検索して、サイトN件取得する。サイトのpタグを抽出し、結果を形態素解析する。
#品詞の上位N件取得。結果をmatplotlibに表示。

#例
# キーワード入力 SPY×FAMILY  最新刊
# 記事を何件検索したい？ 10
# 結果を上位何位まで表示したい？ 20
#
#  単語  出現回数
# ない 	 21
# 高い 	 6
# 早く 	 4
# 大きく 	 4
# 面白い 	 2
# 強く 	 2
# おもしろい 	 2
# 危うい 	 2
# しゃーない 	 2
# かわいい 	 2
# 欲しい 	 2
# いい 	 2
# 悪い 	 2
# 強 	 2
# なかっ 	 2
# すごい 	 2
# 高く 	 2
# なく 	 2
# こよなく 	 2
# 深 	 2

import MeCab,re,time,requests,bs4
from selenium import webdriver
from selenium.webdriver.common.by import By
import chromedriver_binary
from selenium.webdriver.chrome.options import Options
from selenium.webdriver.chrome import service as fs
from selenium.webdriver.support.ui import WebDriverWait

#googleで検索する文字
search_word = input('キーワード入力 ')
search_num = int(input('記事を何件検索したい？ '))
search_ranking = int(input('結果を上位何位まで表示したい？ '))#抽出し、形態素解析したときの結果

INTERVAL = 3
URL = "https://www.google.com/"
driver_path = '/Users/(My User Name))/Downloads/chromedriver'

options = Options()
options.add_argument('--headless')#ヘッドレスモード

chrome_service = fs.Service(executable_path=driver_path)
driver = webdriver.Chrome(service = chrome_service,options=options)

driver.maximize_window()
time.sleep(INTERVAL)

driver.get(URL)
time.sleep(INTERVAL)

#文字を入力して検索
driver.find_element(By.NAME, 'q').send_keys(search_word)
driver.find_elements(By.NAME,'btnK')[1].click() #btnKが2つあるので、その内の後の方、検索ボタンを押す
time.sleep(INTERVAL)

#検索結果の一覧を取得する
texts = []
results = []
flag = False
while True:
  g_list = driver.find_elements(By.CLASS_NAME,'g')
  for g in g_list:
      result = g.find_element(By.CLASS_NAME,'yuRUbf').find_element(By.TAG_NAME,'a').get_attribute('href')
      results.append(result)
      if(len(results) >= search_num):
          flag = True
          break
  if flag:
    break
  driver.find_element(By.ID,'pnnext').click() # ページ送りをクリックして次のページに移動
  time.sleep(INTERVAL)
driver.close() # 最後の行に移動

true_results = set(results)#重複をなくす
for true_result in true_results:
    res = requests.get(true_result)#重複なしURL取得
    res.raise_for_status()
    soup = bs4.BeautifulSoup(res.text, "html.parser")#テキストを取得
    pre_text = soup.find_all("p")
    text = re.sub("[0-9a-zA-Z]"," ", str(pre_text))#英数字を正規化
    texts.append(text)

tagger = MeCab.Tagger()
word_count = {}

for line in tagger.parse(str(texts)).splitlines():
    spl = line.split(',')#単語 \t 品詞,~,~,~
    if '形容詞' in spl[0]:
        words = spl[0].split('\t')#単語(0)、名詞、動詞(1)に分ける
        for word in words:
            if word in word_count:
                word_count[word] += 1
            else:
                word_count[word] = 1

term_list = []
count_list = []

#集計した単語の,出現回数を出力
for term, count in sorted(word_count.items(),key=lambda x:x[1], reverse=True):#降順にソート
    if(term != '形容詞'):
        #print(term,'\t',count)
        term_list.append(term)
        count_list.append(count)

#上位N件の単語と件数を表示
term_list = term_list[:search_ranking]
count_list = count_list[:search_ranking]
print('\n','単語  出現回数')

for term, count in zip(term_list, count_list):
    print(term, '\t', count)

for term, count in zip(term_list, count_list):
    print(term, '\t', count)

import matplotlib.pyplot as plt
plt.rcParams['font.family'] = 'Hiragino Sans'

plt.barh(term_list, count_list) # 横棒の棒グラフ
ticks = [*range(0, (max(count_list)//10+1)*10+1, 5)]
plt.xticks(ticks, [*map(str, ticks)])
plt.savefig('result.png')
plt.show()


# day15_2.py
from day15_1 import get_adjacencies, dijkstra

def get_risk_levels(filename: str):
    risk_levels = []
    with open(filename) as f:
        for y, line in enumerate(f):
            risk_levels.append(list(map(int, line.strip())))
    return risk_levels

def find_safe_path(filename: str):
    risk_level_map = get_risk_levels(filename)
    risk_level_map = expand_map(risk_level_map, 5, 5)
    add_positions_to_map(risk_level_map)
    adj = get_adjacencies(risk_level_map)
    target = (len(risk_level_map) - 1, len(risk_level_map[0]) - 1)
    parent, d = dijkstra(adj, (0, 0), target)
    print(f"parent: {parent}\nd: {d}")
    return d[target]

def expand_map(ex_map, mult_x, mult_y) -> list:
    dimension_x = len(ex_map[0])
    dimension_y = len(ex_map)

    for i in range(len(ex_map)):
        for j in range(mult_x - 1):
            ex_map[i] += (list(map(cycle_value_to_9, ex_map[i][-dimension_x:])))

    for i in range(len(ex_map) * (mult_y - 1)):
        ex_map.append(list(map(cycle_value_to_9, ex_map[-dimension_y])))
    return ex_map

def add_positions_to_map(rmap):
    for y, row in enumerate(rmap):
        for x, risk in enumerate(row):
            rmap[y][x] = ((y, x), risk)

def cycle_value_to_9(value):
    if value < 9:
        return value + 1
    else:
        return 1

if __name__ == "__main__":
    print(find_safe_path("input.txt"))


from os.path import join
import json
import os
import re
import argparse
import random

def _count_data(path):
    """ count number of data in the given path"""
    matcher = re.compile(r'[0-9]+\.json')
    match = lambda name: bool(matcher.match(name))
    names = os.listdir(path)
    n_data = len(list(filter(match, names)))
    return n_data

def shuffle_dataset(data_dir, out_dir, split):
    data_split_dir = join(data_dir, split)
    output_split_dir = join(out_dir, split)
    # make output split folder
    if not os.path.exists(output_split_dir):
        os.makedirs(output_split_dir)
    n_data = _count_data(data_split_dir)
    output_idx_list = list(range(n_data))
    random.shuffle(output_idx_list)

    for i in range(n_data):
        js = json.load(open(join(data_split_dir, '{}.json'.format(i))))
        with open(join(output_split_dir, '{}.json'.format(output_idx_list[i])), 'w') as f:
            json.dump(js, f, indent=4)
    return

def preprocess(args):
    # make output folder
    if not os.path.exists(args.out_dir):
        os.makedirs(args.out_dir)

    # process each split
    for split in ['train', 'val', 'test']:
        print("Process {}".format(split))
        shuffle_dataset(args.data_dir, args.out_dir, split)

if __name__ == "__main__":
    parser = argparse.ArgumentParser(
        description=('')
    )
    parser.add_argument('-seed', type=int, default=9527,
                        help="""Random seed used for the experiments
                                reproducibility.""")
    parser.add_argument('-data_dir', type=str, action='store',
                        help='The directory of the data.')
    parser.add_argument('-out_dir', type=str, action='store',
                        help='The directory of the data.')

    args = parser.parse_args()

    random.seed(args.seed)

    preprocess(args)


import pygame

class Map:
    """class to manage map related operation"""

    def __init__(self, level, tile_sprite, tile_count, tile_size=64):

        # level is 2D list to store map data
        self.level = level

        self.x = 0
        self.y = 0

        # width and height store map height and width in number of tiles
        self.width = len(level[0])
        self.height = len(level)

        # sprite for tiles
        self.tile_sprite = pygame.image.load(tile_sprite)

        # height and width of tile
        self.tile_size = tile_size

        # total no. of tiles
        self.tile_count = tile_count

        # Surface for map
        self.surf = pygame.surface.Surface((self.width * self.tile_size, self.width * self.tile_size))

        self.surf.fill((51, 51, 51))
        # List for storing tiles
        self.tile = []

        # Save Tile object in tile list
        self.__load_tiles()

    def draw_map(self):
        """method for drawing map on screen"""

        for j in range(0, self.height):
            for i in range(0, self.width):
                if self.level[j][i] == 1:
                    self.surf.blit(self.tile[0].tile_image, (i * self.tile_size, j * self.tile_size))
                elif self.level[j][i] == 2:
                    self.surf.blit(self.tile[1].tile_image, (i * self.tile_size, j * self.tile_size))
                elif self.level[j][i] == 3:
                    self.surf.blit(self.tile[2].tile_image, (i * self.tile_size, j * self.tile_size))

    def __load_tiles(self):
        """insert Tile in tile list """
        columns = int(self.tile_sprite.get_width() / self.tile_size)
        rows = int(self.tile_count / columns)

        index = 0
        for i in range(0, rows):
            for j in range(0, columns):

                x = self.tile_size * j
                y = self.tile_size * i

                tile_rect = pygame.Rect((x, y), (self.tile_size, self.tile_size))
                tile_image = self.tile_sprite.subsurface(tile_rect)

                if index == 0:
                    tile = Tile(tile_image, portal=True, collision=True)
                elif index == 1:
                    tile = Tile(tile_image, portal=False, collision=True)
                else:
                    tile = Tile(tile_image)

                self.tile.insert(index, tile)
                index += 1

class Tile:
    """class for tiles"""

    def __init__(self, image, portal=False, collision=False):
        self.tile_image = image

        # Flag for whether portal will work on tile or not
        self.portal = portal

        # Flag for collision check
        self.collision = collision


from toolbox import clean_filename, split_filename, strip_rich_str
from mailtool import *

class MailAttachment:
    def __init__(self, **kwargs):
        self.filename = ""
        self.payload = None
        self.size = 0
        for k, v in kwargs.items():
            if k in self.__dict__:
                self.__dict__[k] = v

    def __str__(self):
        s = self.colour_str()
        s = strip_rich_str(s)
        s = s.replace(":closed_book:", "[]")
        s = s.replace(":notebook_with_decorative_cover:", "[]")
        s = s.replace(":camera: ", "[]")
        s = s.replace(":calendar: ", "[]")
        s = s.replace(":compression: ", "[]")
        return s

    def colour_str(self):
        s = []
        if self.is_pdf:
            s.append(":closed_book: ")
        elif self.is_document:
            s.append(":notebook_with_decorative_cover: ")
        elif self.is_image:
            s.append(":camera:  ")
        elif self.is_archive:
            s.append(":compression:  ")
        elif self.is_cal:
            s.append(":calendar:  ")
        s.append(colour_file_str(self.filename, " "))
        s.append(colour_size_str(self.size))
        return "".join(s)

    @property
    def ext(self):
        if self.filename is not None:
            _, e = split_filename(self.filename)
            return e.replace(".", "").lower()
        return None

    @property
    def is_archive(self):
        return any([self.ext == x for x in "zip rar 7z tar xz".split()])

    @property
    def is_image(self):
        return any([self.ext == x for x in "png jpg jpeg gif bmp".split()])

    @property
    def is_document(self):
        return any([self.ext == x for x in "docx doc xls xlsx ppt pptx".split()])

    @property
    def is_pdf(self):
        return any([self.ext == x for x in "pdf".split()])

    @property
    def is_cal(self):
        return any([self.ext == x for x in "ics".split()])

    def write(self, fn=None):
        fn = fn if fn is not None else self.filename
        if self.payload is not None:
            with open(fn, "wb") as fp:
                fp.write(self.payload)

    @staticmethod
    def from_structure(s):
        a = MailAttachment()
        a.filename = MailAttachment.attach_filename(s)
        a.size = int(s[6])
        return a

    @staticmethod
    def attach_filename(s):
        def find_value(items, with_key):
            if items is None:
                return None
            item_count = len(items)
            for i, item in enumerate(items):
                if item.lower() == with_key and (i + 1) < item_count:
                    return str(items[i + 1], encoding="ascii")
            return None

        if len(s) < 10:
            return None
        fn = None
        for e in s:
            if isinstance(e, tuple):
                if e[0].lower() == b"attachment":
                    if e[1] is None:
                        fn = ""
                    else:
                        fn = find_value(e[1], b"filename")
                        fn = clean_filename(fn)
        if fn is not None and len(fn) == 0:
            for e in s:
                if isinstance(e, tuple):
                    if e[0].lower() == b"name":
                        fn = str(e[1], encoding="ascii")
                        fn = clean_filename(fn)
        if fn is not None and fn == "":
            return None
        return fn


from sklearn.datasets import make_blobs
from sklearn.model_selection import train_test_split
from sklearn.linear_model import LogisticRegression
from sklearn.svm import LinearSVC
import numpy as np
import matplotlib.pyplot as plt
from mpl_toolkits.mplot3d import Axes3D

if __name__ == '__main__':

    with open('plots/plot6.txt', 'r', encoding='utf-8') as f:
        lines = [line for line in str(f.read()).split('\n') if not line == '']

    fig = plt.figure()
    ax = fig.add_subplot(111, projection='3d')

    xs = []
    ys = []
    zs = []
    cs = []
    for line in lines:
        x, y, z, c = map(int, line.split(' '))
        xs.append(x)
        ys.append(y)
        zs.append(z)
        cs.append(c)

    X = np.arange(30000).reshape(10000, 3)
    X[:,0] = xs
    X[:,1] = ys
    X[:,2] = zs

    Y = np.array(cs)

    clf = LogisticRegression().fit(X, Y)

    Z = clf.predict(X)

    print(sum(Y == Z))

    def sigmoid(x):
        return 1 / (1 + np.exp(-x))

    print(clf.coef_)
    print(clf.intercept_)
    print(f'{clf.coef_[0][0]:.15f} {clf.coef_[0][1]:.15f} {clf.coef_[0][2]:.15f} {clf.intercept_[0]:.15f}')

    score = 0
    for x, y in zip(X, Y):
        z = np.sum(clf.coef_ * x) + clf.intercept_
        z = sigmoid(z)
        v = 0 if z < 0.5 else 1
        if y == v:
            score += 1

    print(score)


import logging

from onto_tool import onto_tool

def test_action_message(caplog):
    with caplog.at_level(logging.INFO):
        onto_tool.main([
            'bundle', 'tests/bundle/logging.yaml'
        ])

    logs = caplog.text
    assert 'Running from tests' in logs
    assert 'DEBUG' not in logs

def test_debug_log(caplog):
    with caplog.at_level(logging.DEBUG):
        onto_tool.main([
            'bundle', '--debug', 'tests/bundle/logging.yaml'
        ])

    logs = caplog.text
    assert 'Running from tests' in logs
    assert 'DEBUG' in logs


import asyncio
import discord
from subprocess import call
from discord.ext import commands
from cogs.checks import is_admin, prompt

class admin(commands.Cog):
    def __init__(self, bot):
        self.bot = bot
        self.last_eval_result = None
        self.previous_eval_code = None

    @is_admin("Bot-Admin")
    @commands.command(aliases = ['reboot', 'restart'])
    async def close(self, ctx):
        """Reboots the bot"""
        await ctx.channel.send("Ah shit, here we go again")
        await self.bot.close()

#    @commands.command(hidden=True)
#    @commands.has_role(575834911425167414)
#    async def fullclose(self, ctx):
#        await self.bot.async_call_shell("")

    @is_admin("GlaZy")
    @commands.command()
    async def guildleave(self, ctx, serverid: int):
        """Leaves a server"""
        server = self.bot.get_guild(serverid)
        await ctx.send(f"{server}")

        if server not in self.bot.guilds:
            await ctx.send("I'm not even in this server apparently")
            return
        else:
            if serverid is None:
                server = self.bot.get_guild(ctx.guild.id)

        if server != self.bot.get_guild(554178232531025940) and server != self.bot.get_guild(632566001980145675):
            await ctx.send(f"I'll be leaving {server}")

            if await prompt(self, ctx, "Continue?"):
                return
            await ctx.send(f"I have left {server}")
            await server.leave()

        else:
            await ctx.send(f"I cannot leave `{server}`\nIt's my home <:blobaww:569934894952611851>")

    @commands.command()
    async def prompttest(self, ctx):
        """Self explanatory"""
        if await prompt(self, ctx, "Am I a good bot?"):
            return
        await ctx.send("<:blobaww:569934894952611851>")

    @is_admin("Admin")
    @commands.command(hidden=True)
    async def invite(self, ctx, duration:int=0, uses:int=0, *, reason=""):
        """Generates an invite link
            - Duration (int)
            - Maximum uses (int)
            - Reason (str)"""
        msg = ""
        if duration == 0:
            duration = 0
        if uses == 0:
            uses = 0

        msg += str(await ctx.channel.create_invite(reason=reason,max_age=duration, max_uses=uses, temporary=False, unique=False))
        if reason is "":
            msg += "\nPlease add a reason next time"
        else:
            msg += f"\n{reason}"

        await ctx.send(msg)

    @is_admin("Bot-Admin")
    @commands.command(hidden=True)
#    @commands.has_role(575834911425167414)
    async def give(self, ctx, roles: commands.Greedy[discord.Role], *, users: discord.User):
        """Gives the specified role to a user(s)"""
        members = []

#        if len(roles) > 1:
#            for role in roles:
#                await users.add_roles(role)
#        else:
#            await users.add_roles(roles)
#            members.append(users.name)

        members.sort(key=str.casefold)
        msg = f"``The following roles:\n"

        if len(roles) > 1:
            for role in roles:
                await users.add_roles(role)
                msg += f"- {role.name}\n"
        else:
            await users.add_roles(roles)
            msg += f"- {roles}\n"

        msg += f"have been given to the following users:\n"
        for member in members:
            msg += f"{member}\n"
        else:
            msg += f"{users.name}"
        msg += "``"

        await ctx.send(msg)

def setup(bot):
    bot.add_cog(admin(bot))


#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Tue Oct 10 08:50:01 2017

@author: eareyanv
"""
import setup
import get_data
import networkx as nx
from progress import update_progress

def get_specific_profile_data(zip_suffix, numberWE, numberWF, specific_number_of_games, supply, demand, reserve = None):
    """
    Given numberWE, numberWF, specific_number_of_games, supply, demand;
    produces the profile data for numberWE playing numberWF specific_number_of_games
    times with supply and demand.
    """
    zip_location = setup.get_zip_location(zip_suffix, specific_number_of_games)
    dir_location = setup.get_agent_dir_location(specific_number_of_games, supply, demand)
    file_location = setup.get_file_location(numberWE, numberWF, reserve)
    mix = get_data.get_agent_data(zip_location, dir_location + file_location)
    mix = mix.dropna()
    WEdata = mix[mix.agent.str.contains('WEAgent')]
    WFdata = mix[mix.agent.str.contains('WFAgent')]
    """print('get_specific_profile_data (1) = ', file_name)
    print('get_specific_profile_data (2) = ', dir_location)
    print('get_specific_profile_data (3) = ', reserve)
    print('get_specific_profile_data (4) = ', file_location)"""
    return ('WE' * numberWE + 'WF' * numberWF, {'WE': {'n' : len(WEdata), 'mean' : WEdata.profit.mean(), 'var' : WEdata.profit.var()} ,
                                                'WF': {'n' : len(WFdata), 'mean' : WFdata.profit.mean(), 'var' : WFdata.profit.var()}})

def produce_specific_profile_data(zip_suffix, map_profile_to_numberofgames, number_of_agents, supply, demand, reserve = None):
    """
    Given a map:
        {Profile:number of games},
    (e.g. {'WEWE': path_to_data,'WEWF': path_to_data,'WFWF': path_to_data})
    produces a list of tuples:
        (Strategy profile, {WE : {n, mean profit WE, std profit WE}, WF : {n, mean profit WF, std profit WF})
    where the number of samples of each profile is given by the map_profile_to_numberofgames.
        An strategy profile indicates the strategy played by each
    player in the game, e.g., a profile WEWEWF indicates a
    game where two players play WE and one player plays WF.
    Note that this game is symmetric and thus, WEWEWF = WEWFWE= WFWEWE.
    For simplicity, we normalize by first indicating WEs and then WFs.
    """
    #print(map_profile_to_numberofgames)
    # Check that the map received is correct.
    # Correcteness means that the map contains all profiles.
    if(number_of_agents + 1 != len(map_profile_to_numberofgames)):
        raise ValueError('The number of agents and length of map_profile_to_numberofgames must coincide!')
    profile_data = []
    for i in range(0, number_of_agents + 1):
        profile = ('WE' * (number_of_agents - i) + 'WF' * i)
        if(profile not in map_profile_to_numberofgames):
            raise ValueError('The map does not contain profile: ' + ('WE' * (number_of_agents - i) + 'WF' * i) )
        specific_number_of_games = map_profile_to_numberofgames[profile]
        profile_data.append(get_specific_profile_data(zip_suffix, number_of_agents-i, i, specific_number_of_games, supply, demand, reserve))
    return profile_data

def produce_profile_data(number_of_games, number_of_agents, supply, demand, reserve = 0, include_reserve = False):
    """
    Given the number of games and agents, produces a list of tuples:
        (Strategy profile, {WE : {n, mean profit WE, std profit WE}, WF : {n, mean profit WF, std profit WF})
    BY calling produce_specific_profile_data with the right input.
    """
    return produce_specific_profile_data(dict(('WE' * (number_of_agents - i) + 'WF' * i, number_of_games) for i in range(0,number_of_agents + 1)), number_of_agents, supply, demand, reserve, include_reserve)

def produce_mean_best_response_graph(profile_data):
    """
    Given the data of the graph, produces a directed graph, DG,
    which is an object of the library networkx.
    """
    number_of_profiles = len(profile_data)
    DG = nx.DiGraph()
    DG.add_nodes_from([v[0] for v in profile_data])
    for i in range(1, number_of_profiles):
        DG.add_node(profile_data[i][0])
        # WE deviating to WF, i.e, is a WE making less or equal than a WF?
        #print(profile_data[i-1][1]['WE']['mean'], profile_data[i][1]['WF']['mean'])
        if profile_data[i-1][1]['WE']['mean'] <= profile_data[i][1]['WF']['mean']:
            DG.add_edge(profile_data[i-1][0], profile_data[i][0])
        # WF deviating to WE, i.e, is a WF making less or equal than a WE?
        if profile_data[i][1]['WF']['mean'] <= profile_data[i-1][1]['WE']['mean']:
            DG.add_edge(profile_data[i][0], profile_data[i-1][0])
    return DG

def get_pure_nash(DG):
    """Get all the pure Nash reduces to getting all the
    'sink' nodes (actually, leaf nodes, since this special
    graph is just a tree). This is a list of tuples (#WE,#WF)"""
    return [(i.count('WE'), i.count('WF')) for i in DG.nodes_iter() if DG.out_degree(i)==0]

def get_dict_of_pure_nash(number_of_games, demand_factor, impressions, dir_location):
    """
    This function calls the function that plots the best response graph
    for games with 2 to 20 players. It returns a dict of pure nash.
    """
    dict_of_pure_nash = {}
    for i in range(2, 21):
        update_progress(i/20)
        profile_data = produce_profile_data(number_of_games, dir_location, i)
        DG = produce_mean_best_response_graph(profile_data)
        dict_of_pure_nash[i] = get_pure_nash(DG)
    return dict_of_pure_nash


import csv
from surprise import Dataset, Reader
from surprise.model_selection import train_test_split
from surprise import SVD
from surprise import accuracy
import difflib
import json

class Recommendation:
    def __init__(self, rid, similarRatings):
        self.rid = rid
        #this will be a list of tuples with tuple[0] being other recipes as objects and tuple
        #[1] being a number that is the similarity between this recipe and the recipe in the tuple
        self.similarities = similarRatings
        self.allrankings = dict() #{'id': similarity rating}
        self.recipeData = json.load(open('./testrecipes.json'))

    def compute_similarity(self, input_string, reference_string):
    #The ndiff method returns a list of strings representing the differences between the two input strings.
        diff = difflib.ndiff(input_string, reference_string)
        diff_count = 0
        for line in diff:
        # a "-", indicating that it is a deleted character from the input string.
            if line.startswith("-"):
                diff_count += 1
    # calculates the similarity by subtracting the ratio of the number of deleted characters to the length of the input string from 1
        return 1 - (diff_count / len(input_string))

    #function that will retrieve all recipes in the current DB and determine a similarity between
    #them for user recommendations
    def defineSimilarities(self):
        #find current recipe in recipeData
        #get ingredients and steps
        this_recipe = None
        this_string = None
        for recipe in self.recipeData['recipes']:
            if recipe['id'] == self.rid:
                this_ingredient = "".join(recipe['ingredients'])
                this_steps = "".join(recipe['steps'])
                this_string = this_ingredient + this_steps
                this_recipe = recipe
                break
        if not this_recipe:
            return -1

        for recipe in self.recipeData['recipes']:
            if recipe == this_recipe:
                continue
            else:
                curr_ingredient = "".join(recipe['ingredients'])
                curr_steps = "".join(recipe['steps'])
                string_compare = curr_ingredient + curr_steps
                similarity = self.compute_similarity(this_string, string_compare)
                if not recipe['id'] in self.allrankings:
                    self.allrankings[recipe['id']] = []
                    self.allrankings[recipe['id']].append(similarity)
                    self.allrankings[recipe['id']].append(recipe['name'])
                print(similarity)

        return

#r1 = Recommendation(1, [])
#r1.defineSimilarities()
#print(r1.allrankings[2])
#r1.closeCSVFile()


import requests
from bs4 import BeautifulSoup
import openpyxl
import pandas as pd
import numpy as np
import time

aa=[]
bb=[]
headers={"User-Agent":"Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/86.0.4240.198 Safari/537.36 QIHU 360EE"}
url='http://m.zhuanzhuan.com/youpin/website/list.html?source=wuba&filter=pve_5461_101_pve_5462_2101018&from=old_yp_jg_maishouji'
r=requests.get(url,headers=headers)
r.encoding='UTF-8'
soup=BeautifulSoup(r.text,'lxml')

name=soup.findAll("div",{"class":"title"})
price=soup.findAll("div",{"class":"price"})
# url1=soup.findAll("a",{"class":"curr-shop hd-shopname"})
for n,p in zip(name,price):
    aa.append(n.get_text())
    bb.append(p.get_text())
    # dd.append(u.get("href"))
output=pd.DataFrame({"名称":aa,"价格":bb})
df=pd.DataFrame(output)
# df.to_excel('京东手机1.xlsx')
time.sleep(1)
print(df)


from handler import Handler
from models import Blogs

class NewPost(Handler):
    """Creates new post and stores in GDS"""
    def get(self):
        self.user_page("blogsubmit.html", "/signup", auth_user=self.user)

    def post(self):
        # Check user's auth status
        if self.user:
            title = self.request.get("title")
            content = self.request.get("content")

            params = dict(auth_user=self.user, title=title, content=content)

            if title and content:
                # Remove <div> tag from posting
                content = content.replace("<div>", "")
                content = content.replace("</div>", "")

                # Add to Blogs entity
                blog = Blogs(title=title,
                             content=content,
                             username=self.user,
                             likes=0,
                             dislikes=0)
                blog.put()

                # Redirect to home page
                self.redirect("/welcome")
            else:
                params['error'] = "We need both the title and the blog post."
                self.render("blogsubmit.html", **params)
        else:
            self.redirect("/signup")


#!/usr/bin/python

import os
import sys

sys.path.append("./packages")
from oauth2client.tools import argparser
from apiclient.errors import HttpError
from apiclient.discovery import build
import re
import requests
import random
import json

DEVELOPER_KEY = os.environ["DEVELOPER_KEY"]
YOUTUBE_API_SERVICE_NAME = "youtube"
YOUTUBE_API_VERSION = "v3"
CHANNEL_ID = "UCZx7esGXyW6JXn98byfKEIA"
WEBHOOK_URL = os.environ["WEBHOOK_URL"]

youtube = build(YOUTUBE_API_SERVICE_NAME,
                YOUTUBE_API_VERSION,
                developerKey=DEVELOPER_KEY)

VIDEOS = []

def get_random_video(page_token):
    # チャンネルの情報を取得
    response = (youtube.search().list(part="snippet",
                                      channelId=CHANNEL_ID,
                                      maxResults=50,
                                      pageToken=page_token).execute())

    # 結果から動画IDを配列に格納
    for result in response.get("items", []):
        if result["id"]["kind"] == "youtube#video":
            VIDEOS.append(result["id"]["videoId"])

    # nextPageTokenがある時は再帰的に実行
    try:
        next_page_token = response["nextPageToken"]
        get_random_video(next_page_token)
    except:
        print("VIDEOS:", VIDEOS)
        # ランダムで動画を選択して、IDを返す
        video_id = random.choice(VIDEOS)

        print("CHOICE_VIDEO_ID:", video_id)
        return get_video_info(video_id)

def get_video_info(video_id):
    # 動画の情報を取得
    response = youtube.videos().list(part="snippet, statistics",
                                     id=video_id).execute()

    print("RESPONSE:", response)
    return create_message(response)

def create_message(response):
    snippet = response["items"][0]["snippet"]
    statistics = response["items"][0]["statistics"]

    # メッセージ作成に必要な値を取得
    video_id = response["items"][0]["id"]
    title = snippet["title"]
    day = snippet["publishedAt"]
    day = day[0:10]
    description = snippet["description"]
    member = re.findall(r"(.*?)\n【Twitter】", description)
    member = list(map(lambda x: ({"value": x, "short": True}), member))
    view = "{:,}".format(int(statistics["viewCount"]))
    rate = [statistics["likeCount"], statistics["dislikeCount"]]
    url = "https://www.youtube.com/watch?v=" + video_id
    image = snippet["thumbnails"]["maxres"]["url"]

    # メッセージ作成
    context = {
        "attachments": [
            {
                "pretext": "今日のおすすめ",
                "title": title,
                "title_link": url,
                "text": url,
                "color": "#7CD197",
                "image_url": image,
            },
            {
                "title": "Member",
                "fields": member,
                "color": "#764FA5"
            },
            {
                "fallback":
                f"{title} {url}",
                "text":
                "",
                "fields": [
                    {
                        "title": "投稿日",
                        "value": day,
                        "short": True
                    },
                    {
                        "title": "再生回数",
                        "value": view,
                        "short": True
                    },
                    {
                        "title": "高評価",
                        "value": rate[0],
                        "short": True
                    },
                    {
                        "title": "低評価",
                        "value": rate[1],
                        "short": True
                    },
                ],
            },
        ]
    }

    print("MESSAGE:", context)
    return post_slack(context)

def post_slack(context):
    payload = context
    data = json.dumps(payload)
    # slackに投稿
    response = requests.post(WEBHOOK_URL, data)
    if response.status_code == 200:
        print("投稿完了")
    else:
        print("投稿失敗")

if __name__ == "__main__":
    try:
        get_random_video(page_token="")
    except HttpError as e:
        print("An HTTP error %d occurred:\n%s" % (e.resp.status, e.content))


# row1 = ["😀", "😍", "😁"]
# row2 = ["🤑", "😅", "😌"]
# row3 = ["😎", "😩", "🥱"]
#
# map = [row1, row2, row3]
# x = int(input("Select row :\n")) - 1
# y = int(input("Select column: \n")) - 1
#
# map[x][y] = "x"
#
# print(f"{row1}\n{row2}\n{row3}")

# A = [[1, 2, 3], [4, 5, 6], [7, 8, 9]]
# B = [[9, 8, 7], [6, 5, 4], [1, 2, 3]]
# c = []
# for i in range(len(A)):
#     s = []
#     for j in range(len(A[0])):
#         s.append(A[i][j] + B[i][j])
#     c.append(s)
#
# print(c)

work_hours = [int(x) for x in input("Enter hours per day in entire week, Separated by comma").split(",")]
wages = int(input("Enter Hourly Wage"))

total = sum(work_hours)

salary = total * wages
print("Salary is ", salary)


import base64
import hmac
import hashlib

with open('lorem.txt', 'rb') as f:
    body = f.read()

hash = hmac.new(
    b'secret-shared-key-goes-here',
    body,
    hashlib.sha1,
)

digest = hash.digest()
print(base64.encodestring(digest))

'''
The base64 encoded string ends in a newline, which frequently needs to be stripped off when
embedding the string in HTTP headers or other formatting-sensitive contexts.
$ python3 hmac_base64.py
b'MvqI7hYoulZYJevQA/srugy67cc=\n'
'''


# This is a sample Python script.

# Press ⌃R to execute it or replace it with your code.
# Press Double ⇧ to search everywhere for classes, files, tool windows, actions, and settings.

import torch
import torch.nn as nn
import torch.optim as optim
from PIL import Image
import torchvision.transforms as transforms
import torchvision.models as models
from torchvision.utils import save_image
import os

model = models.vgg19().features
print(model)

conv_layers = ['0', '5', '10', '19', '28']

class VGG(nn.Module):
    def __init__(self):
        super(VGG, self).__init__()
        self.chosen_features = conv_layers
        self.model = models.vgg19().features[:29]

    def forward(self, x):
        features = []

        for index, layer in enumerate(self.model):
            x = layer(x)
            if str(index) in self.chosen_features:
                features.append(x)

        return features

def load_image(image_name):
    image = Image.open(image_name)
    image = loader(image).unsqueeze(0)
    return image.to(device)

# a bunch of MPS stuff isn't supported :(
device = torch.device("mps" if torch.has_mps else "cpu")
# device = torch.device("cpu")
image_size = 512

loader = transforms.Compose([
    transforms.CenterCrop((image_size, image_size)),
    transforms.ToTensor()
    # transforms.Normalize(mean=[], std=[])
])

model = VGG().to(device).eval()

original_image = load_image("white.png")
style_image = load_image("style.png")

# generated_image = torch.randn(size=original_image.shape, device=device, requires_grad=True)
generated_image = original_image.clone().requires_grad_(True)

# Hyperparameters
steps = 4000
learning_rate = 0.01
alpha = 0.2
beta = 1

optimizer = optim.Adam([generated_image], lr=learning_rate)

epoch = 1

original_features = model(original_image)
style_features = model(style_image)

for step in range(steps):
    generated_features = model(generated_image)

    style_loss = original_loss = 0

    for gen_feature, orig_feature, style_feature in zip(generated_features, original_features, style_features):
        batch_size, channel, height, width = gen_feature.shape
        original_loss += torch.mean((gen_feature - orig_feature) ** 2)

        # Compute Gram Matrix
        G = gen_feature.view(channel, height * width).mm(
            gen_feature.view(channel, height*width).t())

        A = style_feature.view(channel, height*width).mm(
            style_feature.view(channel, height*width).t())

        style_loss += torch.mean((G-A) ** 2)

    total_loss = alpha*original_loss + beta*style_loss
    optimizer.zero_grad()
    total_loss.backward()
    optimizer.step()

    if step % 50 == 0:
        print(total_loss)
        save_image(generated_image, os.getcwd() + F"/GeneratedImages/generated{epoch}.png")
        epoch += 1

# Press the green button in the gutter to run the script.
# if __name__ == '__main__':
#     print("Done executing")


# -*- coding: utf-8 -*-
#harvest theses from TU Munich
#FS: 2019-09-24
#FS: 2022-11-24

import sys
import urllib.request, urllib.error, urllib.parse
from bs4 import BeautifulSoup
import re
import os
import ejlmod3
import time

publisher = 'Munich, Tech. U.'
jnlfilename = 'THESES-TUM-%s' % (ejlmod3.stampoftoday())
rpp = 100
years = 2
skipalreadyharvested = True

boring = ['Fakultät für Sport- und Gesundheitswissenschaften']
boring += ['CHE Chemie', 'BAU 550', 'BAU 650', 'BAU 650', 'UMW 300', 'BAU 651', 'BAU 900', 'BAU 950',
           'BAU Bauingenieurwesen, Vermessungswesen', 'GEO Geowissenschaften',
           'BAU Bauingenieurwesen, Vermessungswesen', 'BIO 110','BIO 250', 'BIO Biowissenschaften',
           'BRA 200', 'BRA Brauwesen', 'ERG Energietechnik, Energiewirtschaft', 'FER 000',
           'FER Fertigungstechnik', 'FOR 110', 'FOR Forstwissenschaften', 'IND 020',
           'LEB Lebensmitteltechnologie', 'MED 040', 'MED 535', 'MED 320', 'MED 410', 'MED 430',
           'MED 320', 'MED 430', 'MED 450', 'MED Medizin', 'VER 630', 'MAS 590',
           'VER Technik der Verkehrsmittel', 'WIR 531', 'WIR 700', 'WIR 800', 'WIR 895',
           'WIR Wirtschaftswissenschaften']
boring += ['ARC 045', 'ARC 165', 'ARC 279', 'ARC 370', 'ARC Architektur', 'BAU 005', 'BAU 050',
           'BAU 150', 'BAU 450', 'BAU 967', 'BIO 120', 'BIO 140', 'BIO 300', 'BIO 780', 'BIO 950',
           'CHE 140', 'CHE 167', 'CHE 513', 'CHE 800', 'CHE 880', 'CIT 001', 'CIT 200', 'CIT 280',
           'CIT 325', 'CIT 335', 'CIT 680', 'CIT 900', 'CIT 960',
           'CIT Chemie-Ingenieurwesen, Technische Chemie, Biotechnologie', 'EDU 640',
           'EDU Erziehungswissenschaften', 'GES Geschichte', 'IND Sonstige Industrien',
           'INF Informationswesen, Bibliotheks-, Dokumentations-, Archiv-, Museumswesen',
           'Ingenieurfakultät Bau Geo Umwelt', 'KUN 850', 'KUN Kunst', 'LAN 120', 'LAN 332',
           'LAN 490', 'LAN 610', 'LAN 640', 'LAN Landbauwissenschaft', 'LEB 020', 'LEB 050',
           'LEB 054', 'MAS 000', 'MAS 520', 'MAS 700', 'MAS Maschinenbau', 'MED 230', 'MED 280',
           'MED 370', 'MED 385', 'MED 403', 'MED 580', 'MED 600', 'MED 670', 'MTA 000', 'MTA 009',
           'MTA 300', 'MTA 309', 'MTA 600', 'MTA 900',
           'MTA Technische Mechanik, Technische Thermodynamik, Technische Akustik', 'OEK 100',
           'OEK 160', 'OEK Ökotrophologie, Ernährungswissenschaft', 'POL 650', 'POL Politologie',
           'PSY Psychologie', 'RPL 000', 'RPL 734', 'RPL 900', 'RPL Raumplanung, Raumordnung',
           'SOZ 700', 'SPO 570', 'SPO 600', 'SPO 610', 'SPO 617', 'SPO 630', 'SPO 650', 'SPO 680',
           'SPO 695', 'SPO 720', 'SPO Sport', 'UMW 028', 'UMW 200', 'UMW 350',
           'UMW Umweltschutz und Gesundheitsingenieurwesen', 'VER 020', 'VER 500', 'VER 505',
           'VER 600', 'VER 700', 'VER 800', 'WEH Wehrtechnik', 'WER 000', 'WER 440', 'WER 490',
           'WER 740', 'WER Werkstoffwissenschaften', 'WIR 006', 'WIR 523', 'WIR 527', 'WIR 780',
           'WIS 600', 'WIS Wissenschaftskunde']
hdr = {'User-Agent' : 'Magic Browser'}

alreadyharvested = []
if skipalreadyharvested:
    alreadyharvested = ejlmod3.getalreadyharvested(jnlfilename)

prerecs = []
links = []
reboring = re.compile('(Bachelorarbeit|Masterarbeit)')
#for (fc, dep, pages) in [('', '603847', 1), ('m', '603845', 1), ('c', '603842', 1), ('o', '603787', 10)]:
for (fc, dep, pages) in [('c', '1691132', 1), ('m', '1691133', 1), ('', '1688930', 5)]:
#                         ('m', '603815', 2), ('', '603821', '')]:
    tocurl = 'https://mediatum.ub.tum.de/' + dep + '?id=' + dep + '&sortfield0=-year&sortfield1=&nodes_per_page=' + str(rpp)
    for page in range(pages):
        ejlmod3.printprogress('=', [[dep], [page+1, pages], [tocurl]])
        req = urllib.request.Request(tocurl, headers=hdr)
        tocpage = BeautifulSoup(urllib.request.urlopen(req), features="lxml")
        for div in tocpage.body.find_all('div', attrs = {'class' : 'preview_list'}):
            for a in div.find_all('a'):
                keepit = True
                rec = {'tc' : 'T', 'keyw' : [], 'jnl' : 'BOOK', 'note' : [], 'supervisor' : []}
                rec['link'] = re.sub('.*=', 'https://mediatum.ub.tum.de/?id=', a['href'])
            for child in div.find_all('div', attrs = {'class' : 'mediatum-stylelist-div'}):
                if not reboring.search(child.text) and ejlmod3.checkinterestingDOI(rec['link']):
                    if not rec['link'] in links:
                        for br in child.find_all('br'):
                            br.replace_with('XXXXXX')
                        for part in re.split(' *XXXXXX *', child.text):
                            if re.search('^[12]\d\d\d$', part):
                                rec['year'] = part
                                if int(part) <= ejlmod3.year(backwards=years):
                                    keepit = False
                        if keepit:
                            prerecs.append(rec)
                            links.append(rec['link'])
        print('  %4i records so far' % (len(prerecs)))
        time.sleep(5)
        nextpage = tocpage.body.find_all('a', attrs = {'class' : 'page-nav-next'})
        if nextpage:
            tocurl = 'https://mediatum.ub.tum.de' + nextpage[0]['href']
        else:
            break

recs = []
for (i, rec) in enumerate(prerecs):
    i += 1
    keepit = True
    ejlmod3.printprogress('-', [[i, len(prerecs)], [rec['link']], [len(recs)]])
    req = urllib.request.Request(rec['link'] + '&change_language=de', headers=hdr)
    artpage = BeautifulSoup(urllib.request.urlopen(req), features="lxml")
    ejlmod3.metatagcheck(rec, artpage, ['citation_author', 'citation_publication_date',
                                        'citation_pdf_url'])
    #Metadata
    for dl in artpage.body.find_all('dl', attrs = {'class' : 'object_meta'}):
        for child in dl.children:
            try:
                childclass = child['class'][0]
            except:
                continue
            if childclass == 'mask_label':
                label = child.text.strip()
            elif childclass == 'mask_value':
                #Document type
                if label == 'Dokumenttyp:':
                    rec['documenttype'] = child.text.strip()
                    rec['note'].append(rec['documenttype'])
                #Author
                elif label == 'Autor:':
                    rec['autaff'] = [[ child.text.strip() ]]
                    for a in child.find_all('a'):
                        if a.has_attr('href') and a['href'][:6] == 'mailto':
                            rec['autaff'][-1].append(re.sub('mailto:', 'EMAIL:', a['href']))
                #title:
                elif label == 'Originaltitel:':
                    rec['tit'] = child.text.strip()
                elif label == 'Übersetzter Titel:':
                    rec['transtit'] = child.text.strip()
                #Abstract
                elif label == 'Kurzfassung:':
                    rec['origabs'] = child.text.strip()
                elif label == 'Übersetzte Kurzfassung:':
                    rec['transabs'] = child.text.strip()
                #classification
                elif label in ['Fachgebiet:', 'TU-Systematik:']:
                    for subject in re.split(' *; *', child.text.strip()):
                        if subject in boring:
                            keepit = False
                            #print('   skip "%s"' % (subject))
                        elif subject in ['DAT Datenverarbeitung, Informatik']:
                            rec['fc'] = 'c'
                        elif subject in ['MAT Mathematik']:
                            rec['fc'] = 'm'
                        elif subject in ['PHY 600']:
                            rec['fc'] = 'f'
                        elif subject in ['PHY 900']:
                            rec['fc'] = 'a'
                        elif subject in ['PHY 410']:
                            rec['fc'] = 'p'
                        elif subject in ['PHY 023', 'PHY 025', 'PHY 035', 'PHY 037']:
                            rec['fc'] = 't'
                        elif subject in ['PHY 040', 'PHY 041', 'PHY 042', 'PHY 043']:
                            rec['fc'] = 'g'
                        elif subject in ['PHY 402', 'PHY 403', 'PHY 404']:
                            rec['fc'] = 'b'
                        else:
                            rec['note'].append(subject)
                #DDC
                elif label == 'DDC:':
                    rec['ddc'] = []
                    for part in re.split('[,;]',  child.text.strip()):
                        ddc = re.sub('\D', '', part)
                        if len(ddc) == 3:
                            rec['ddc'].append(ddc)
                            if ddc[:2] == '00':
                                rec['fc'] = 'c'
                            elif ddc[:2] == '51':
                                rec['fc'] = 'm'
                            elif ddc[:2] == '52':
                                rec['fc'] = 'a'
                            elif not rec['ddc'][:2] in ['50', '53', '60', '62']:
                                keepit = False
                                #print('   skip "%s"' % (div2.text.strip()))
                #Supervisor
                elif label == 'Betreuer:':
                    rec['supervisor'].append([re.sub(' \(.*', '', child.text.strip())])
                #Faculty
                elif label in ['Institution:', 'Fakultät:']:
                    department = child.text.strip()
                    if department in boring:
                        keepit = False
                        #print('   skip "%s"' % (department))
                    elif department == 'Fakultät für Informatik':
                        rec['fc'] = 'm'
                    elif department == 'Fakultät für Informatik':
                        rec['fc'] = 'c'
                    else:
                        rec['note'].append(department)
                #Pages
                elif label == 'Seiten:':
                    if re.search('\d\d', child.text):
                        rec['pages'] = re.sub('.*?(\d\d+).*', r'\1', child.text.strip())
                #URN
                elif label in ['URN:', 'Urn (Zitierfähige URL):']:
                    rec['urn'] = re.sub('.*\?', '', child.text.strip())
                #Keywords
                elif label in ['Stichworte:', 'Übersetzte Stichworte:']:
                    rec['keyw'] += re.split(', ', child.text.strip())
                #language
                elif label == 'Sprache:':
                    rec['language'] = child.text.strip()
                #ISBN
                elif label == 'ISBN:':
                    rec['isbn'] = child.text.strip()
                #Hinweis
                elif label == 'Hinweis:':
                    rec['note'].append(child.text.strip())
                #
                #elif label == '':
                #    rec[''] = child.text.strip()
                elif not label in ['Jahr:', 'Gutachter:', 'Dateigröße:', 'WWW:', 'Eingereicht am:',
                                   'Mündliche Prüfung:', 'Letzte Änderung:',
                                   'Originaluntertitel:', 'Übersetzter Untertitel:']:
                    print('\n  - ', label, ':', child.text.strip() + '\n')
    #abstract
    if 'language' in rec and rec['language'] == 'de' and 'transabs' in rec:
        rec['abs'] = rec['transabs']
    elif 'origabs' in rec:
        rec['abs'] = rec['origabs']
    #title
    if 'language' in rec and rec['language'] == 'en' and 'transtit' in rec:
        del(rec['transtit'])
    #Habilitation
    if 'documenttype' in rec and rec['documenttype'] == 'Habilitation':
        year = re.sub('.*([12]\d\d\d).*', r'\1', rec['date'])
        rec['MARC'] = [('502', [('b', 'habilitation'), ('c', publisher), ('d', year)])]
    #PDF
    for div in artpage.body.find_all('div', attrs = {'class' : 'document_download'}):
        for a in div.find_all('a'):
            rec['hidden'] = 'https://mediatum.ub.tum.de' + a['href']
    if keepit:
        if 'urn' in rec and rec['urn'] in alreadyharvested:
            print('  already in backup')
        else:
            rec['autaff'][-1].append(publisher)
            ejlmod3.printrecsummary(rec)
            recs.append(rec)
    else:
        ejlmod3.adduninterestingDOI(rec['link'])
    time.sleep(5)

ejlmod3.writenewXML(recs, publisher, jnlfilename)


import time
import threading

balance = 0
look = threading.Lock()

def change_it(n):
	global balance  # ¹²Ïí±äÁ¿balance
	balance = balance + n
	balance = balance - n

def run_thread(n):
	for i in range(100000):
		look.acquire()
		try:
			change_it(n)
		finally:
			look.release()

t1 = threading.Thread(target=run_thread, args=(5,))
t2 = threading.Thread(target=run_thread, args=(8,))
t1.start()
t2.start()
t1.join()
t2.join()
print(balance)


from random import randint
cont = n = 0
while True:
    p = ' '
    while p not in 'PpIi':
        p = str(input('Par ou Ímpar? ')).strip().lower()[0]
    n = int(input('Escolha um número de 0 a 10: '))
    c = randint(0,10)
    s = c + n
    if s%2==0 and p == 'p':
        print(f'Você jogou {n} e o computador jogou {c}.')
        print('Você venceu!')
        cont += 1
    elif s%2!=0 and p == 'i':
        print(f'Você jogou {n} e o computador jogou {c}.')
        print('Você venceu!')
        cont += 1
    else:
        print(f'Você jogou {n} e o computador jogou {c}.')
        print('Você perdeu!')
        break
    print('Vamos jogar novamente...')
if cont > 0:
    print(f'Você teve {cont} vitória(s) consecutiva(s)!')
else:
    print('FIM')


#Embedded file name: /Users/versonator/Jenkins/live/output/Live/mac_64_static/Release/python-bundle/MIDI Remote Scripts/Push2/transmute.py
from __future__ import absolute_import, print_function, unicode_literals
from builtins import range
from ableton.v2.base import EventObject
from ableton.v2.control_surface import EnumWrappingParameter, IntegerParameter, LiveObjectDecorator, NotifyingList, get_parameter_by_name, WrappingParameter
from .device_decoration import DeviceOnOffOption, DeviceSwitchOption
from .device_component import ButtonRange, DeviceComponentWithTrackColorViewData
from .visualisation_settings import VisualisationGuides

class TransmuteDeviceDecorator(LiveObjectDecorator, EventObject):
    MIN_PITCH_BEND_RANGE = 0
    MAX_PITCH_BEND_RANGE = 24
    polyphony_values = (u'2', u'4', u'8', u'16')

    def __init__(self, *a, **k):
        super(TransmuteDeviceDecorator, self).__init__(*a, **k)
        self.frequency_dial_mode = EnumWrappingParameter(name=u'Frequency Dial Mode', parent=self, values_host=self._live_object, index_property_host=self, values_property=u'frequency_dial_mode_list', index_property=u'frequency_dial_mode_index')
        self.midi_gate = EnumWrappingParameter(name=u'Midi Gate', parent=self, values_host=self._live_object, index_property_host=self, values_property=u'midi_gate_list', index_property=u'midi_gate_index')
        self.mod_mode = EnumWrappingParameter(name=u'Mod Mode', parent=self, values_host=self._live_object, index_property_host=self, values_property=u'mod_mode_list', index_property=u'mod_mode_index')
        self.mono_poly = EnumWrappingParameter(name=u'Mono Poly', parent=self, values_host=self._live_object, index_property_host=self, values_property=u'mono_poly_list', index_property=u'mono_poly_index')
        self.pitch_mode = EnumWrappingParameter(name=u'Pitch Mode', parent=self, values_host=self._live_object, index_property_host=self, values_property=u'pitch_mode_list', index_property=u'pitch_mode_index')
        self.pitch_bend_range_parameter = IntegerParameter(name=u'Pitch Bend Range', parent=self, integer_value_host=self._live_object, integer_value_property_name=u'pitch_bend_range', min_value=self.MIN_PITCH_BEND_RANGE, max_value=self.MAX_PITCH_BEND_RANGE, show_as_quantized=False)
        self.polyphony_parameter = EnumWrappingParameter(name=u'Polyphony', parent=self, values_host=self, index_property_host=self, values_property=u'polyphony_values', index_property=u'polyphony')
        self._additional_parameters = (self.frequency_dial_mode,
         self.midi_gate,
         self.mod_mode,
         self.mono_poly,
         self.pitch_mode,
         self.pitch_bend_range_parameter,
         self.polyphony_parameter)
        self.freq_dial_mode_option = DeviceSwitchOption(name=u'frequency_dial_mode_opt', parameter=self.frequency_dial_mode, labels=[u'Hz', u'Note'])
        self.register_disconnectables(self._additional_parameters)
        self.register_disconnectables(self.options)

    @property
    def options(self):
        return (self.freq_dial_mode_option,)

    @property
    def parameters(self):
        return tuple(self._live_object.parameters) + self._additional_parameters


# coding: utf-8
"""
Set of utility function used throughout the app
"""
from uuid import uuid4
import hashlib
import re
from google.appengine.ext import ndb #pylint: disable=import-error
import config
from pydash import _
import itertools, operator

EMAIL_REGEX = r'^[-!#$%&\'*+\\.\/0-9=?A-Za-z^_`{|}~]+@([-0-9A-Za-z]+\.)+([0-9A-Za-z]){2,4}$'

# see: https://gist.github.com/dperini/729294 (PYTHON PORT)
URL_REGEX = r'^(?:(?:https?|ftp)://)(?:\S+(?::\S*)?@)?(?:(?!(?:10|127)(?:\.\d{1,3}){3})(?!(?:169\.254|192\.168)(?:\.\d{1,3}){2})(?!172\.(?:1[6-9]|2\d|3[0-1])(?:\.\d{1,3}){2})(?:[1-9]\d?|1\d\d|2[01]\d|22[0-3])(?:\.(?:1?\d{1,2}|2[0-4]\d|25[0-5])){2}(?:\.(?:[1-9]\d?|1\d\d|2[0-4]\d|25[0-4]))|(?:(?:[a-z\u00a1-\uffff0-9]-*)*[a-z\u00a1-\uffff0-9]+)(?:\.(?:[a-z\u00a1-\uffff0-9]-*)*[a-z\u00a1-\uffff0-9]+)*(?:\.(?:[a-z\u00a1-\uffff]{2,})))(?::\d{2,5})?(?:/\S*)?$'

def uuid():
    """Generates random UUID used as user token for verification, reseting password etc.

    Returns:
      string: 32 characters long string

    """
    return uuid4().hex

def create_name_from_email(email):
    """Function tries to recreate real name from email address

    Examples:
      >>> create_name_from_email('bobby.tables@email.com')
      Bobby Tables
      >>> create_name_from_email('bobby-tables@email.com')
      Bobby Tables

    Args:
      email (string): Email address

    Returns:
      string: Hopefully user's real name

    """
    return re.sub(r'_+|-+|\.+|\++', ' ', email.split('@')[0]).title()

def password_hash(password):
    """Hashes given plain text password with sha256 encryption
    Hashing is salted with salt configured by admin, stored in >>> model.Config

    Args:
        password (string): Plain text password

    Returns:
        string: hashed password, 64 characters

    """
    sha = hashlib.sha256()
    sha.update(password.encode('utf-8'))
    sha.update(config.CONFIG_DB.salt)
    return sha.hexdigest()

def list_to_dict(input_list):
    """Creates dictionary with keys from list values
    This function is primarily useful for converting passed data from Angular checkboxes,
     since angular ng-model can't return list of checked group of checkboxes, instead
     it returns something like {'a': True, 'b': True} for each checkbox

    Example:
        >>> list_to_dict(['a', 'b'])
        {'a': True, 'b': True}

    Args:
        input_list (list): List of any type

    Returns:
        dict: Dict with 'True' values
    """
    return _.zip_object(input_list, _.map(input_list, _.constant(True)))

def dict_to_list(input_dict):
    """Creates list from dictionary with true booloean values
    This function is primarily useful for converting passed data from Angular checkboxes,
     since angular ng-model can't return list of checked group of checkboxes, instead
     it returns something like {'a': True, 'b': True} for each checkbox

    Example:
        >>> dict_to_list({'a': True, 'b': True, 'c': False})
        ['a', 'b']

    Args:
        input_dict (dict): Dict with boolean values

    Returns:
        list: list of truthful values
    """
    return _.keys(_.pick(input_dict, _.identity))

def constrain_string(string, minlen, maxlen):
    """Validation function constrains minimal and maximal lengths of string.

    Args:
        string (string): String to be checked
        minlen (int): Minimal length
        maxlen (int): Maximal length

    Returns:
        string: Returns given string

    Raises:
        ValueError: If string doesn't fit into min/max constrains

    """

    if len(string) < minlen:
        raise ValueError('Input need to be at least %s characters long' % minlen)
    elif len(string) > maxlen:
        raise ValueError('Input need to be maximum %s characters long' % maxlen)
    return string

def constrain_regex(string, regex):
    """Validation function checks validity of string for given regex.

    Args:
        string (string): String to be checked
        regex (string): Regular expression

    Returns:
        string: Returns given string

    Raises:
        ValueError: If string doesn't match regex

    """
    regex_email = re.compile(regex, re.IGNORECASE)
    if not regex_email.match(string):
        raise ValueError('Incorrect regex format')
    return string

def create_validator(lengths=None, regex='', required=True):
    """This is factory function, which creates validator functions, which
    will then validate passed strings according to lengths or regex set at creation time

    Args:
        lengths (list): list of exact length 2. e.g [3, 7]
            indicates that string should be between 3 and 7 charactes
        regex (string): Regular expression
        required (bool): Wheter empty value '' should be accepted as valid,
            ignoring other constrains

    Returns:
        function: Function, which will be used for validating input
    """

    def validator_function(value, prop):
        """Function validates input against constraints given from closure function
        These functions are primarily used as ndb.Property validators

        Args:
            value (string): input value to be validated
            prop (string): ndb.Property name, which is validated

        Returns:
            string: Returns original string, if valid

        Raises:
            ValueError: If input isn't valid

        """
        # when we compare ndb.Property with equal operator e.g User.name == 'abc' it
        # passes arguments to validator in different order than as when e.g putting data,
        # hence the following parameters switch
        if isinstance(value, ndb.Property):
            value = prop
        if not required and value == '':
            return ''
        if regex:
            return constrain_regex(value, regex)
        return constrain_string(value, lengths[0], lengths[1])

    return validator_function

###############################################################################
# Request Parameters
###############################################################################
def param(name, cast=None):
    return None
    #value = None
    #if flask.request.json:
    #    return flask.request.json.get(name, None)

    #if value is None:
    #    value = flask.request.args.get(name, None)
    #if value is None and flask.request.form:
    #    value = flask.request.form.get(name, None)

    #if cast and value is not None:
    #    if cast is bool:
    #        return value.lower() in ['true', 'yes', 'y', '1', '']
    #    if cast is list:
    #        return value.split(',') if len(value) > 0 else []
    #    if cast is ndb.Key:
    #        return ndb.Key(urlsafe=value)
    #    return cast(value)
    #return value

###############################################################################
# Model manipulations
###############################################################################
def get_dbs(
    query, order=None, limit=None, cursor=None, keys_only=None, **filters
  ):
  limit = limit or config.DEFAULT_DB_LIMIT
  cursor = Cursor.from_websafe_string(cursor) if cursor else None
  model_class = ndb.Model._kind_map[query.kind]

  for prop in filters:
    if filters.get(prop, None) is None:
      continue
    if isinstance(filters[prop], list):
      for value in filters[prop]:
        query = query.filter(model_class._properties[prop] == value)
# new custom wodor app -------------
    elif isinstance(filters[prop], dict):
      if filters[prop]['test'] == '>':
        query = query.filter(model_class._properties[prop] > filters[prop]['value'])
      elif filters[prop]['test'] == '>=':
        query = query.filter(model_class._properties[prop] >= filters[prop]['value'])
      elif filters[prop]['test'] == '<':
        query = query.filter(model_class._properties[prop] < filters[prop]['value'])
      elif filters[prop]['test'] == '<=':
        query = query.filter(model_class._properties[prop] < filters[prop]['value'])
      elif filters[prop]['test'] == '==':
        query = query.filter(model_class._properties[prop] == filters[prop]['value'])
      elif filters[prop]['test'] == '!=':
        query = query.filter(model_class._properties[prop] != filters[prop]['value'])
      elif filters[prop]['test'] == 'IN':
        values = filters[prop]['value']
        if isinstance(values, list):
          values = filters[prop]['value']
        else:
           values = values.split(',')
        query = query.filter(model_class._properties[prop].IN(values))
        query = query.order(model_class._key)
      query = query.order(model_class._properties[prop]) # TODO does it work?
    else:
      query = query.filter(model_class._properties[prop] == filters[prop])
# ----------------------------------

  if order:
    for o in order.split(','):
      if o.startswith('-'):
        query = query.order(-model_class._properties[o[1:]])
      else:
        query = query.order(model_class._properties[o])
  model_dbs, next_cursor, more = query.fetch_page(
      limit, start_cursor=cursor, keys_only=keys_only,
    )
  next_cursor = next_cursor.to_websafe_string() if more else None
  return list(model_dbs), next_cursor

def sort_uniq(sequence,key_sort=None,key_group=None,reverse=False):
    sorted_seq = list(sorted(sequence,key=operator.itemgetter(key_sort), reverse=reverse))
    #return sorted_seq
    uniq_seq = {v[key_group]:v for v in sorted_seq}.values()
    return list(sorted(uniq_seq,key=operator.itemgetter(key_sort), reverse=not reverse))


import os
import torch
import torch.nn as nn
from VAE import VAE
import torch.optim as optim
import torch.nn.functional as F
import torch.backends.cudnn as cudnn
from torch.nn import DataParallel
from small_cnn import SmallCNN
import torchvision
import torchvision.utils as vutils
import torchvision.transforms as transforms
import torchvision.models as models
from torchvision.datasets import ImageFolder
import pdb
DATA_PATH = '~/data/'
import argparse
from tqdm import tqdm
from loguru import logger
from utils import get_args

def generate(vae, model, dataloader, device):
    model.eval()
    labels_cnt = [0] * 10
    with torch.no_grad():
        for batch_idx, (inputs, targets) in tqdm(enumerate(dataloader), total=len(dataloader), desc="testing"):
            inputs = inputs.to(device)
            recon, _, _ = vae(inputs.view(-1,28*28).to(device), device)
            recon_img = recon.view(-1, 1, 28 ,28)
            outputs = model(recon_img.to(device))
            _, predicted = outputs.max(1)
            label = int(targets.item())
            predicted = int(predicted.item())
            if label != predicted:
                label_cnt = labels_cnt[label]
                output_dir = f'hardimgs/{label}'
                if not os.path.exists(output_dir):
                   os.makedirs(output_dir)
                vutils.save_image(torch.cat([inputs.squeeze().cpu(), recon_img.squeeze().cpu()],dim=0),f'{output_dir}/{label_cnt}.png')
                labels_cnt[label] += 1

def main():
    args = get_args()

    log_file_name = args.log_file
    logger.add(log_file_name)
    logger.info('args:\n' + args.__repr__())

    batch_size = args.batch_size
    output_dir = args.save_path
    if not os.path.exists(output_dir):
        os.makedirs(output_dir)

    device = args.device
    best_acc = 0  # best test accuracy

    # Data
    logger.info('==> Preparing data..')
    if args.dataset == 'MNIST':
        transform=transforms.Compose([
            transforms.ToTensor()
        ])
        transform_train = transform
        tramsform_test = transform
    else:
        raise NotImplementedError

    epochs = args.epochs
    GEN_PATH = f'/home/linhw/myproject/Attack-Vae/gen_imgs-{epochs}'
    genset = torchvision.datasets.MNIST(DATA_PATH, train=False, transform=transforms.Compose(
        [
            transforms.ToTensor()
        ]
    ))
    genloader = torch.utils.data.DataLoader(genset, batch_size=1, shuffle=False, num_workers=8)
    # Model
    logger.info('==> Building model..')
    if args.model == 'smallCNN':
        model = SmallCNN()
    model = model.to(device)
    model.load_state_dict(torch.load(args.params, map_location=device)['state_dict'])
    vae = VAE()
    vae = vae.to(device)
    vae.load_state_dict(torch.load('/home/linhw/myproject/Attack-Vae/checkpoint/model/500epoch_model.pt', map_location=device))

    generate(vae, model, genloader, device)
    logger.info("generate finished")

if __name__ == '__main__':
    main()


import cv2
import time
print(cv2.__version__)

dispW = 640
dispH = 480

boxW = 10
boxH = 8
boxThickness = 2

boxX=0
boxY = 0

stageX = 1
stageY = 1

while True:

    print(boxY)

    if boxX >= dispW-boxW and stageX == 1:
        stageX = 2
    if boxX <= 0 and stageX == 2:
        stageX = 1

    if boxY >= dispH-boxH and stageY == 1:
        stageY = 2
    if boxY <= 0 and stageY == 2:
        stageY = 1

    if stageX == 1:
        boxX+=1
    if stageX == 2:
        boxX-=1

    if stageY == 1:
        boxY+=1
    if stageY == 2:
        boxY-=1

    time.sleep(1/30)

print("Quit")


'''
가중치의 최대값이 10이라고 해서 가중치들의 합이 10보다 작다는 보장이 되는 것은 아니다.
간선의 갯수가 최대 30만개이고 가중치가 최대 10이므로 사실상 INF라는 상수를 초기화할 때는 10*30,000보다 큰 수를 넣어야 한다.
'''

import heapq
import sys
ssr = sys.stdin.readline

INF = 3000001

def dijkstra(start):
    h = [(0, start)]
    dist[start] = 0
    while h:
        cur_dist, cur_node = heapq.heappop(h)
        if cur_dist > dist[cur_node]:
            continue
        for next_dist, next_node in routes[cur_node]:
            if dist[cur_node]+next_dist < dist[next_node]:
                dist[next_node] = dist[cur_node]+next_dist
                heapq.heappush(h, (dist[next_node], next_node))

v, e = map(int, ssr().split())
k = int(ssr())
routes = [[] for _ in range(v+1)]
dist = [INF for _ in range(v+1)]
for _ in range(e):
    a, b, c = map(int, ssr().split())
    routes[a].append((c, b))
dijkstra(k)
for i in range(1, v+1):
    print(dist[i] if dist[i] != INF else 'INF')


import speech_recognition as sr
import pyttsx3
import pywhatkit
import datetime
import wikipedia
import json
from test import ask_google
import googleSearch
import webbrowser
import time
import signal
import os

listener = sr.Recognizer()
engine = pyttsx3.init()
voice = engine.getProperty('voices')
engine.setProperty('voice', 'com.apple.speech.synthesis.voice.Alex')
engine.setProperty('rate',250)

class TimeoutException(Exception):   # Custom exception class
    pass

def break_after(seconds=2):
    def timeout_handler(signum, frame):   # Custom signal handler
        raise TimeoutException

    def function(function):
        def wrapper(*args, **kwargs):
            signal.signal(signal.SIGALRM, timeout_handler)
            signal.alarm(seconds)
            try:
                res = function(*args, **kwargs)
                signal.alarm(0)      # Clear alarm
                return res
            except TimeoutException:
                print('Oops, timeout: %s sec reached.' % seconds, function.__name__, args, kwargs)
            return
        return wrapper
    return function

#@break_after(10)
def talk(text):
    engine.say(text)
    engine.runAndWait()

def takeCommand():
    try:
        with sr.Microphone() as source:
            print("Listening.....")
            voices = listener.listen(source,timeout=5, phrase_time_limit=5)
            command = listener.recognize_google(voices).lower()
    except Exception as e:
        print(e)
    return command

def validate_input(input,commands):
    for cmd in commands:
        if cmd in input:
            return True

def launch(voice_command,launch_dict):
    for key,values in launch_dict.items():
        if key in voice_command:
            return values

def runAlexa():
    while True:
        command = takeCommand().strip().lower()
        print(command)
        quesWords = ['who', 'why']
        primeWords = ['minister', 'president']
        numerals = ['first', 'second', 'third', 'fourth', 'fifth', 'sixth', 'seventh', 'eighth', 'ninth', 'tenth']
        launch_cmd = ['open', 'launch', 'run']
        greeting_cmd = ['hello jarvis','hi jarvis','wake up jarvis']
        grateful_cmd = ['thank you jarvis','thanks jarvis','thank you very much jarvis','thanks','thank you']
        launch_dict = {'app store': '/Volumes/Omega/System/Applications/App\ Store.app', 'pycharm':'/Applications/PyCharm.app',
                       'downloads': '/Users/macedon/Downloads', 'library':'/Library','current directory':'.',
                       'youtube':"https://www.youtube.com",'clion':'/Applications/CLion.app'}

        if validate_input(command,greeting_cmd):
            talk("Hello Sir, how may I help you ?")
            continue
        elif validate_input(command,launch_cmd):
            path = launch(command,launch_dict)
            if os.uname().sysname == 'Darwin':
                cmd = 'open'
            else:
                cmd = 'explorer'
            cmd = cmd+" "+path
            talk("Opening Sir")
            os.system(cmd)
            continue
        elif validate_input(command,grateful_cmd):
            talk('It is my pleasure to serve you sir')
            continue
        elif 'play' in command:
            song = command.replace('play', '')
            talk('Playing ' + song)
            pywhatkit.playonyt(song)
            continue
        elif 'time' in command:
            time = datetime.datetime.now().strftime('%I:%M %p')
            talk("Current time is " + time)
            continue
        elif 'when' in command:
            answer = ask_google(command)
            talk(answer)
            continue
        elif not any(num in command for num in numerals):
            print('1')
            if any(word in command for word in primeWords):
                print('2')
                ind = command.index('the')
                s = command[0:ind + 4] + 'current ' + command[ind + 4:]
                answer = ask_google(s)
                talk(answer)
            elif any(word in command for word in quesWords):
                print('3')
                answer = ask_google(command)
                talk(answer)
                talk("Do you want additional information from web ?")
            else:
                print('4')
                answer = ask_google(command)
                talk(answer)
            continue
        elif any(num in command for num in numerals):
            print('5')
            if any(word in command for word in quesWords):
                print('6')
                if 'india' in command:
                    print('7')
                    answer = ask_google(command)
                    talk(answer)
                else:
                    print('8')
                    url = googleSearch.Search(command)
                    talk("Here is what I found on web ")
                    webbrowser.get().open(url)
            continue
        else:
            print("9")

runAlexa()


def sep_input():
    line = input()
    line = line.rstrip().split(' ')
    line = [int(x) for x in line]
    return line[0], line[1]

a, b = sep_input()
if (a * b) % 2:
    print("Odd")
else:
    print("Even")


import setuptools

with open("README.md", "r", encoding="utf-8") as fh:
    long_description = fh.read()

setuptools.setup(
    name="smoot",
    version="0.2.0",
    author="Nathalie Bartoli, Robin Grapin, Rémi Lafage",
    description="Surrogate based multi-objective optimization tool",
    long_description=long_description,
    long_description_content_type="text/markdown",
    license="BSD-3",
    url="https://github.com/OneraHub/smoot",
    classifiers=[
        "Programming Language :: Python :: 3",
        "License :: OSI Approved :: BSD License",
        "Operating System :: OS Independent",
    ],
    packages=["smoot"],
    python_requires=">=3.7",
    install_requires=["smt", "pymoo>=0.6.0"],
)


#problem 10
#olivia g 11/2/20
#setting constants - the cost rate and the weight of punnets etc.
RATE = 5
PUN = 0.25
BOX = 1.5
BUCK = 7
#input - how many punnets, etc.
pun_num = int(input("How many punnets did you pick? "))
box_num = int(input("How many boxes did you pick? "))
buck_num = int(input("How many buckets did you pick? "))
#process - calculating the weight and price
pun_weight = pun_num * PUN
box_weight = box_num * BOX
buck_weight = buck_num * BUCK
total_weight = pun_weight + box_weight + buck_weight
total_price = total_weight * RATE
#output - outputting the weights and the total price
print("-----------------")
print("Total punnet weight: {:.1f} kg".format(pun_weight))
print("Total box weight: {:.1f} kg".format(box_weight))
print("Total bucket weight: {:.1f} kg".format(buck_weight))
print("Total berry weight: {:.1f} kg".format(total_weight))
print("Price to charge: ${:.2f}".format(total_price))


#!/usr/bin/env python
# coding=utf-8
"""
Author: Deean
Date: 2022-02-12 15:42:08
LastEditTime: 2022-02-12 15:56:29
Description:
FilePath: 1865.找出和为指定值的下标对.py
"""
#
# @lc app=leetcode.cn id=1865 lang=python3
#
# [1865] 找出和为指定值的下标对
#

from collections import Counter
# @lc code=start
from typing import List

class FindSumPairs:

    def __init__(self, nums1: List[int], nums2: List[int]):
        self.nums2 = nums2
        self.dict1 = Counter(nums1)
        self.dict2 = Counter(nums2)

    def add(self, index: int, val: int) -> None:
        temp = self.nums2[index]
        self.nums2[index] += val
        self.dict2[temp] -= 1
        self.dict2[temp + val] += 1

    def count(self, tot: int) -> int:
        count = 0
        for k, v in self.dict1.items():
            count += v * self.dict2.get(tot - k, 0)
        return count

# Your FindSumPairs object will be instantiated and called as such:
# obj = FindSumPairs(nums1, nums2)
# obj.add(index,val)
# param_2 = obj.count(tot)
# @lc code=end

P1865. 找出和为指定值的下标对.py


#项目的初始化文件
from flask import Flask
from flask_sqlalchemy import SQLAlchemy
from flask_migrate import Migrate
from flask_wtf import CSRFProtect  #csrf保护
db=SQLAlchemy()
migrate=Migrate()
csrf=CSRFProtect()  #实例化
def createApp(obj):
    # 实例化app
    app = Flask(__name__)
    app.config.from_object(obj)
    db.init_app(app)  #惰性加载
    migrate.init_app(app,db)
    csrf.init_app(app)
    from blueprint.course import course_bl
    from blueprint.user import user_bl
    # 将申明好的蓝图注册进来
    app.register_blueprint(course_bl, url_prefix="/course")
    app.register_blueprint(user_bl, url_prefix="/user")
    #使用装饰器，注册一个要被执行的方法，请求钩子
    @app.before_first_request
    def first_request():
        print("before_first_request")
    @app.before_request
    def req():
        print(" before_request")
    # @app.after_request
    # def afger_req(response):
    #     print("after_request")
    # @app.teardown_request
    # def teardown_req(response):
    #     print("teardown_request")
    #     return response

    return app


import numpy as np
import pandas as pd
import matplotlib.pyplot as plt

class VehicleData:
    def __init__(self, filepath, columns=["index", "id", "x", "y"]) -> None:
        """Initialize the VehicleData instance with data provided in the path.

        Args:
            filepath (str): Path to the data file.
            columns (list): Column names of given data.
        """
        try:
            self.df = pd.DataFrame(
                np.load(filepath),
                columns=columns,
            )
        except Exception as e:
            print(f"An error occurred: {e}")
            self.df = None

    def segment_by_id(self, id):
        """Selects a subset from the data using a specific id.

        Args:
            id (int): To get all the samples associated with the id number.

        Returns:
            Dataframe: Subset of data associated with the id, Empty otherwise.
        """
        if self.df is not None:
            return self.df[self.df["id"] == id]
        return pd.DataFrame()

    def filter(self, fun, segment_id=0):
        """To filter based on input functions.

        Args:
            fun (function): Filter function.
            segment_id (int): To get the trajectory associated with the id number.

        Returns:
            Dataframe: List of latitudinal and longitudinal values of the trajectory, Empty otherwise.
        """
        return fun(self.df, segment_id)

    def plot(self, data):
        """Plots only filtered data segment.

        Args:
            data (Dataframe): Filtered segment data to plot.
        """
        plt.scatter(data["x"], data["y"])
        plt.show()


import pygame
from src.UI.Button import *

class Menu:

    def __init__(self, container, *btns):
        self.container = container
        self.btnList = []
        self.mainFont = ('freesansbold.ttf', 32)
        self.largeFont = ('freesansbold.ttf',50)

        self.hovered = None

        for btnId in range ( len(btns)): #init buttons
            self.btnList.append(Button(btns[btnId][0], btns[btnId][1]))
            self.placeBtn(btnId)

    def btnDefault(self, btnId): #reset selected button to its default state/font
        self.btnList[btnId].fontUpdate(self.mainFont, "white")
        self.placeBtn(btnId)

    def btnHovered(self, btnId):
        self.btnList[btnId].fontUpdate(self.largeFont, "white")
        self.placeBtn(btnId)

    def placeBtn(self, btnId):
        self.btnList[btnId].rect.center = (self.container.get_width() // 2, self.container.get_height() // 4 * (1 + (btnId * 0.4)))

    def isHovering(self, btnId, pos):
        if(self.btnList[btnId].rect.collidepoint(pos)):
            self.hovered = btnId
            return True

    def btnBlit(self, btnId):
        self.btnList[btnId].blitSelf(self.container)

    def blitAll(self):
        for btnId in range (len(self.btnList)):
            self.btnBlit(btnId)

#This function is called to check if a button is hovered or clicked and apply the different visual effects or return an action to call.
    def eventHandler(self, type, pos): #get event type and pos
        for btnId in range (len(self.btnList)): #iterate all the buttons of the menu
            if self.isHovering(btnId, pos): #if the iterated button is hovered
                if type == pygame.MOUSEBUTTONDOWN: #if the event type = mouse click
                    return self.btnList[btnId].command
                elif type == pygame.MOUSEMOTION: #if the event type = mouse motion
                    self.btnHovered(btnId)
                    return None

        if (self.hovered != None):
            self.btnDefault(self.hovered)
            self.hovered = None
        return None

tictactoe (with class objects)/app/client/src/UI/Menu.py


import os
from threading import Lock

class MetadataDict:

    def __init__(self):

        self.lock = Lock()
        self.metadata_dict = dict()

    def get(self, key):

        self.lock.acquire()
        metadata = self.metadata_dict[key]
        self.lock.release()

        return metadata

    def store(self, key, value):

        self.lock.acquire()
        self.metadata_dict[key] = value
        self.lock.release()

class Metadata:

    def __init__(self, filepath):

        with open(filepath, 'r') as fl:
            self.filename = os.path.split(filepath)[-1]
            self.column_names = fl.readline().split(',')
            self.num_rows = 0

            for _ in fl.readlines():
                self.num_rows += 1

    def to_dict(self):

        return {
            'filename': self.filename,
            'num_rows': self.num_rows,
            'column_names': self.column_names
        }