from playwright.sync_api import sync_playwright

def on_new_page(page):
    print("New page opened:", page.url)
    page.wait_for_load_state("load")

    # Wait for page to finish loading
    page.wait_for_timeout(1000)

    # Get page title
    title = page.title()
    print("Page title:", title)

    # Perform actions on the new page
    # ...
    # Close the page after you're done
    # try:
    #     page.close()
    # except Exception as e:
    #     print("Error closing page:", e)

def main():
    with sync_playwright() as p:
        # Launch a browser
        browser = p.chromium.launch()
        # Create a context
        context = browser.new_context()

        # Set up event listener for new pages
        context.on("page", on_new_page)

        # Open an initial page
        page = context.new_page()
        page.goto("https://example.com")
        # Simulate clicking a link that opens in a new tab
        page.evaluate("window.open('https://google.com', '_blank')")

        # Wait for a while to let the new tab open and perform actions
        page.wait_for_timeout(5000)

        # Close the browser
        browser.close()

main()


import os
import warnings
import numpy as np
import pandas as pd

from typing import List, Dict, Union

from tqdm import tqdm
from summarizer import Summarizer
from sklearn.decomposition import PCA
from jinja2 import Environment, FileSystemLoader
from transformers import AutoModel, AutoTokenizer, AutoConfig

from covid_encoding import encode_texts, train_doc2vec_model
from covid_preprocessing import clean_text
from covid_clustering import get_cluster_labels
from covid_keywords import extract_common_phrases
from covid_visualisation import noninteractive_visualisation

INPUT_FILE = "../datasets/covid_articles/covid19_articles.csv"

class ArticleClustering():
    def __init__(self, clustering_method: str = "hdbscan", encoding_method: str = "roberta",
                 keyword_extraction_method: str = "lda", num_keywords: int = 20,
                 verbose: bool = True, doc2vec_model: Union[None, str] = None, use_summary: bool = False,
                 report_filename: str = "report.html"):
        self.clustering_method = clustering_method
        self.encoding_method = encoding_method
        self.keyword_extraction_method = keyword_extraction_method
        self.num_keywords = num_keywords
        self.verbose = verbose
        self.doc2vec_model = doc2vec_model
        self.use_summary = use_summary
        self.report_filename = report_filename

    def analyze(self, input_file: str, n_samples: Union[int, None] = None) -> None:
        self.n_samples = n_samples
        if self.encoding_method == "doc2vec" and not self.doc2vec_model:
            print("No doc2vec model detected")
            exit(1)
        article_data = self.open_csv_file(input_file, n_samples=n_samples, verbose=self.verbose)
        texts = list(article_data["content"].to_numpy())
        if self.use_summary:
            texts = self.get_summary(texts)

        texts = clean_text(texts, verbose=self.verbose)
        article_data["filtered_content"] = texts
        embeddings = encode_texts(texts, self.encoding_method, verbose=self.verbose)
        embeddings = self.dimensionality_reduction(embeddings, 300, verbose=self.verbose)

        cluster_labels = get_cluster_labels(embeddings, method=self.clustering_method)
        article_data["cluster_label"] = cluster_labels

        noninteractive_visualisation(embeddings, cluster_labels, verbose=self.verbose)

        if self.verbose:
            print("Clustering finished\nKeyword extraction started")
            with warnings.catch_warnings():
                warnings.filterwarnings(action="ignore", category=FutureWarning)
                tqdm.pandas()
            article_data_clustered = article_data.groupby("cluster_label").progress_apply(self.dataframe_regroup)
        else:
            article_data_clustered = article_data.groupby("cluster_label").apply(self.dataframe_regroup)
        article_data_clustered = article_data_clustered.sort_values(by=["cluster_size"], ascending=False)
        self.generate_html_report(article_data_clustered)

    @staticmethod
    def open_csv_file(path: str, *, n_samples: Union[None, int] = None, verbose: bool = False) -> pd.DataFrame:
        dataframe = pd.read_csv(path)
        if n_samples:
            dataframe = dataframe.sample(n=n_samples)
        if verbose:
            if n_samples:
                print(f"Chosen {n_samples} random samples from articles dataset")
            else:
                print(f"Articles dataset opened. Length: {dataframe.shape[0]}")
        return dataframe

    def train_doc2vec_model(self, model_name: str, dataset_path: str) -> None:
        train_doc2vec_model(dataset_path, self.verbose, model_name)
        self.doc2vec_model = model_name

    def get_summary(self, texts: List[str]) -> List[str]:
        config = AutoConfig.from_pretrained('allenai/biomed_roberta_base')
        config.output_hidden_states = True
        tokenizer = AutoTokenizer.from_pretrained('allenai/biomed_roberta_base')
        model = AutoModel.from_pretrained('allenai/biomed_roberta_base', config=config)
        summarizer = Summarizer(custom_model=model, custom_tokenizer=tokenizer)
        if self.verbose:
            print("Summary extraction started:")
            texts = tqdm(texts)
        result = [summarizer(text) for text in texts]
        return result

    def dimensionality_reduction(self, embeddings: np.ndarray, max_pca_components: int = 300, verbose: bool = False) -> np.ndarray:
        pca = PCA(n_components=(min(self.n_samples or max_pca_components, max_pca_components)))
        result = pca.fit_transform(embeddings)
        if verbose and len(embeddings[0]) != result.shape[1]:
            print(f"Dimensionality reduction: {len(embeddings)}x{len(embeddings[0])} -> {result.shape[0]}x{result.shape[1]}")
        return result

    def dataframe_regroup(self, dataframe: pd.DataFrame) -> Dict:
        titles = dataframe["title"].to_numpy()
        size = dataframe.shape[0]
        texts = dataframe["filtered_content"].to_list()
        common_phrases = extract_common_phrases(texts, self.keyword_extraction_method, n_keywords=self.num_keywords)

        return pd.Series({'titles': titles,
                          'cluster_size': size,
                          'common_phrases': common_phrases})

    def generate_html_report(self, dataframe: pd.DataFrame) -> None:
        env = Environment(loader=FileSystemLoader(os.path.join(os.path.dirname(__file__))))
        template = env.get_template("template.html")
        original_list = dataframe.to_dict('records')
        new_list = [{key: values for key, values in record.items()
                    if key in ['cluster_size', 'titles', 'common_phrases']}
                    for record in original_list]
        template_vars = {"values": new_list}
        html_out = template.render(template_vars)
        with open(self.report_filename, "w", encoding="utf-8") as f:
            f.write(html_out)

def main():
    pipeline = ArticleClustering(encoding_method="doc2vec",
                                 doc2vec_model="doc2vec.model",
                                 keyword_extraction_method="rake")
    pipeline.analyze(INPUT_FILE, 1000)

if __name__ == "__main__":
    main()


import matplotlib.pyplot as plt;
import numpy as np;
import glob;
import os;
import sys;

if len(sys.argv) == 1:
  print("Usage -- python3 plotData.py <list of filenames>")

if os.path.isdir("./plots_data")==False:
  os.mkdir("./plots_data");

# Get all the data files
sim_files = [];
for i in range(1, len(sys.argv)):
  sim_files.append(glob.glob(sys.argv[i]));

# We need to flatten the array.
sim_flat = [];
for l in sim_files:
  for item in l:
    sim_flat.append(item);

n = len(sim_flat);

# Find the maximum and minimum values across all plots.
max_y = 0;
min_y = 0;
for i in range(0,n):
  data = np.genfromtxt(fname=sim_flat[i], delimiter=",");
  ydata = data[:,2];
  tmax = np.amax(ydata);
  tmin = np.amin(ydata);
  if tmax > max_y:
    max_y = tmax;
  if tmin > min_y:
    min_y = tmin;

# Now that we have a min and a max range, let's plot our data.

for i in range(0,n):
  data = np.genfromtxt(fname=sim_flat[i], delimiter=",");

  # Get the head of the file name.
  name = os.path.split(sim_flat[i])[1];
  name = os.path.splitext(name)[0];

  # Make the plots
  plt.plot(data[:,1], data[:,2],'.');
  plt.ylim(min_y,max_y);
  plt.xlabel('x');
  plt.ylabel(name);
  plt.tight_layout();

  plt.savefig('./plots_data/' + name + '.png');
  plt.clf();


import tensorflow as tf
import copy
import numpy as np
import pointer_net
from flask import request, Response
from flask import Flask
from gevent.pywsgi import WSGIServer
import time
import os
import random
import sys
import json
import glob
from copy import deepcopy

tf.app.flags.DEFINE_integer("batch_size", 1,"Batch size.")
tf.app.flags.DEFINE_integer("max_input_sequence_len", 1000, "Maximum input sequence length.")
tf.app.flags.DEFINE_integer("max_output_sequence_len", 50, "Maximum output sequence length.")
tf.app.flags.DEFINE_integer("rnn_size", 1024, "RNN unit size.")
tf.app.flags.DEFINE_integer("attention_size", 64, "Attention size.")
tf.app.flags.DEFINE_integer("num_layers", 2, "Number of layers.")
tf.app.flags.DEFINE_integer("beam_width", 10, "Width of beam search .")
tf.app.flags.DEFINE_float("learning_rate", 0.001, "Learning rate.")
tf.app.flags.DEFINE_float("max_gradient_norm", 5.0, "Maximum gradient norm.")
tf.app.flags.DEFINE_boolean("forward_only", True, "Forward Only.")
tf.app.flags.DEFINE_string("models_dir", "./models/model1/solid", "Log directory")
tf.app.flags.DEFINE_string("data_path", "", "Training Data path.")
tf.app.flags.DEFINE_string("test_data_path", "", "Test Data path.")
tf.app.flags.DEFINE_string("pred_out_path", "", "Test Data path.")

FLAGS = tf.app.flags.FLAGS

class EntityLinker(object):
    def __init__(self, forward_only):
        self.forward_only = True
        self.epoch = 0
        self.bestf1 = 0
        self.testgraph = tf.Graph()
        with self.testgraph.as_default():
            config = tf.ConfigProto()
            config.gpu_options.allow_growth = True
            config.operation_timeout_in_ms=6000
            self.testsess = tf.Session(config=config)
            self.build_model()

    def build_model(self):
        self.testmodel = None
        with self.testgraph.as_default():
            self.testmodel = pointer_net.PointerNet(batch_size=1,
                    max_input_sequence_len=FLAGS.max_input_sequence_len,
                    max_output_sequence_len=FLAGS.max_output_sequence_len,
                    rnn_size=FLAGS.rnn_size,
                    attention_size=FLAGS.attention_size,
                    num_layers=FLAGS.num_layers,
                    beam_width=FLAGS.beam_width,
                    learning_rate=FLAGS.learning_rate,
                    max_gradient_norm=FLAGS.max_gradient_norm,
                    forward_only=True)
            self.testsess.run(tf.global_variables_initializer())
            ckpt = tf.train.get_checkpoint_state(FLAGS.models_dir)
            print(ckpt, FLAGS.models_dir)
            if ckpt and tf.train.checkpoint_exists(ckpt.model_checkpoint_path):
                print("Load model parameters from %s" % ckpt.model_checkpoint_path)
                self.testmodel.saver.restore(self.testsess, ckpt.model_checkpoint_path)

    def getvector(self,d):
        inputs = []
        enc_input_weights = []
        for question in d:
            questioninputs = []
            enc_input_len = len(question)
            if enc_input_len > FLAGS.max_input_sequence_len:
                print("Length too long, skip")
                continue
            #qemb = question[0][0][1:769]
            for idx,word in enumerate(question):
                questioninputs.append(word[0])
            for i in range(FLAGS.max_input_sequence_len-enc_input_len):
                questioninputs.append([0]*969)
            inputs.append(questioninputs)
            weight = np.zeros(FLAGS.max_input_sequence_len)
            weight[:enc_input_len]=1
            enc_input_weights.append(weight)
        self.test_inputs = np.stack(inputs)
        self.test_enc_input_weights = np.stack(enc_input_weights)

linker = EntityLinker(FLAGS.forward_only)
app = Flask(__name__)
print("serving api ...")

@app.route('/erlinker', methods=['POST'])
def erlinker():
    d = request.get_json(silent=True)
    citem = copy.deepcopy(d)
    inputvecs = []
    linkedvecs = []
    sepseencount = 0
    for cans,canv in zip(d['candidatestring'],d['candidatevectors']):
        inputvecs.append([canv,cans])
        if cans == '[SEP]':
            sepseencount += 1
        if sepseencount < 2:
            linkedvecs.append([canv,cans])
    linkedvecs.append([969*[-1.0],'[SEP]']) # This for now only holds thhe question token + [SEP]. The linked ents and rels will be appended shortly.

    batch = [inputvecs]
    vector = linker.getvector(batch)
    try:
        print(linker.test_inputs.shape)
        predicted,_ = linker.testmodel.step(linker.testsess, linker.test_inputs, linker.test_enc_input_weights, update=False)
        predentrels = set()
        for entrelnum in list(predicted[0][0]):
            if entrelnum <= 0:
                continue
            predentrels.add(inputvecs[entrelnum-1][1])
            linkedvecs.append([inputvecs[entrelnum-1][0],inputvecs[entrelnum-1][1]])
        print(predentrels)
        citem['predentrels'] = list(predentrels)
        del citem['candidatevectors']
        citem['linkedentrelvecs'] = linkedvecs
        citem['linkedentrelstring'] = [x[1] for x in linkedvecs]
        return json.dumps(citem, indent=4, sort_keys=True)
    except Exception as err:
        print("ERROR:",err)
        citem['predentrels'] = []
        del citem['candidatevectors']
        citem['linkedentrelvecs'] = linkedvecs
        citem['linkedentrelstring'] = [x[1] for x in linkedvecs]
        return json.dumps(citem, indent=4, sort_keys=True)

if __name__ == '__main__':
    http_server = WSGIServer(('', 2223), app)
    http_server.serve_forever()


#110107

def king_position(king, board):
    for i, row in enumerate(board):
        j = row.find(king)
        if j > -1:
            return (i, j)
    return (-1, -1)

def move(position, direction, *commands):
    for c in commands:
        if c == 'go':
            x, y = 0, 0
            if direction == 'north':
                x = -1
            elif direction == 'east':
                y = 1
            elif direction == 'south':
                x = 1
            elif direction == 'west':
                y = -1
            position = (position[0] + x, position[1] + y)

        elif c == 'right':
            if direction == 'north':
                direction = 'east'
            elif direction == 'east':
                direction = 'south'
            elif direction == 'south':
                direction = 'west'
            elif direction == 'west':
                direction = 'north'

        elif c == 'left':
            if direction == 'north':
                direction = 'west'
            elif direction == 'west':
                direction = 'south'
            elif direction == 'south':
                direction = 'east'
            elif direction == 'east':
                direction = 'north'
    return position

def feasible(position):
    la = (0, 0)
    rb = (7, 7)
    feasible_row = la[0] <= position[0] and position[0] <= rb[0]
    feasible_col = la[1] <= position[1] and position[1] <= rb[1]
    return feasible_row and feasible_col

def capture(piece, position, board):
    output = []
    i, j = position
    if piece.lower() == 'p':
        if piece == 'p':
            for c in ['right', 'left']:
                pos = move(position, 'south', 'go', c, 'go')
                if feasible(pos):
                    output.append(pos)
        else:
            for c in ['right', 'left']:
                pos = move(position, 'north', 'go', c, 'go')
                if feasible(pos):
                    output.append(pos)

    elif piece.lower() == 'n':
        for direction in ['north', 'east', 'south', 'west']:
            for c in ['right', 'left']:
                pos = move(position, direction, 'go', 'go', c, 'go')
                if feasible(pos):
                    output.append(pos)

    elif piece.lower() == 'b':
        for direction in ['north', 'south']:
            for c in ['right', 'left']:
                pos = move(position, direction, 'go', c, 'go')
                while feasible(pos):
                    output.append(pos)
                    pos = move(pos, direction, 'go', c, 'go')

    elif piece.lower() == 'r':
        for direction in ['north', 'east', 'south', 'west']:
            pos = move(position, direction, 'go')
            while feasible(pos):
                output.append(pos)
                pos = move(pos, direction, 'go')

    elif piece.lower() == 'q':
        output = capture('b', position, board) + capture('r', position, board)

    return output

def king_check(king, board):
    pos = king_position(king, board)
    for i, row in enumerate(board):
        for j, piece in enumerate(row):
            if king == 'k':
                white = piece != piece.lower()
                if white and pos in capture(piece, (i, j), board):
                    return True
            elif king == 'K':
                black = piece == piece.lower()
                if black and pos in capture(piece, (i, j), board):
                    return True
    return False

def read_data(input):
    output = [[]]
    board = 0
    with open(input, 'r') as file:
        for line in file:
            line_content = line.split()
            if len(line_content) > 0:
                output[board].append(line_content[0])
            else:
                output.append([])
                board += 1
    output.pop()
    return output

def write_data(data, output):
    with open(output, 'w') as file:
        file.write(data.strip())

data_in = read_data('input.txt')

data_out = ''
for i, board in enumerate(data_in):
    data_out += 'Game #{}: '.format(i + 1)
    black_in_check = king_check('k', board)
    white_in_check = king_check('K', board)
    if black_in_check:
        data_out += 'black king is in check.\n'
    elif white_in_check:
        data_out += 'white king is in check.\n'
    else:
        data_out += 'no king is in check.\n'

write_data(data_out, 'output.txt')


import unittest
import cdms2
import numpy
import os
import cdat_info

class TestCDMSInFileUnlimtedDimAlter(unittest.TestCase):
    def testInFileUnlimitedDimAlter(self):

        fnm = os.path.join(cdat_info.get_sampledata_path(),"clt.nc")
        f=cdms2.open(fnm)
        s=f("clt")
        f.close()
        cdms2.setNetcdfDeflateFlag(0)
        cdms2.setNetcdfDeflateLevelFlag(0)
        cdms2.setNetcdfShuffleFlag(0)
        cdms2.setNetcdf4Flag(1)
        cdms2.setNetcdfClassicFlag(1)
        f=cdms2.open("nc4.nc","w")
        f.write(s)
        f.close()

        timesValues = s.getTime()[:]
        f=cdms2.open("nc4.nc","r+")
        t=f["time"]
        t[:]=t[:]*100.
        f.close()

        f=cdms2.open("nc4.nc")
        s=f("clt")
        t = s.getTime()
        self.assertEqual(len(t),len(timesValues))
        self.assertTrue(numpy.allclose(t[:],timesValues*100.))
        os.remove("nc4.nc")

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


for i in range(3):
    arr = list(map(int,input().split()))
    h = arr[3] - arr[0]
    m = arr[4] - arr[1]
    s = arr[5] - arr[2]
    while True:
        if m<0:
            m+=60
            h-=1
        elif s<0:
            s+=60
            m-=1
        else:
            break
    print(h,m,s)


# Написать функцию, возвращающую два введеных с клавиатуры числа

def get_num():
    """Функция возвращает введенные с клавиатуры числа"""
    x = int(input('Число A: '))
    y = int(input('Число B: '))
    return x, y

try:
    print(get_num())
except ValueError:
    print('Введены некорректные числа')


import decisionlib
from typing import List, Optional, Dict, Any, Callable
from gha import GithubAction, GithubActionScript
from typing import List
from decisionlib import CONFIG

BUILD_ARTIFACTS_EXPIRE_IN = "1 week"
PAHKAT_REPO = "https://pahkat.uit.no/"

def linux_build_task(name, bundle_dest="repo", with_secrets=True):
    task = (
        decisionlib.DockerWorkerTask(name)
        .with_worker_type("linux")
        .with_provisioner_id("divvun")
        .with_docker_image("ubuntu:hirsute")
        # https://docs.taskcluster.net/docs/reference/workers/docker-worker/docs/caches
        .with_scopes("docker-worker:cache:divvun-*")
        .with_scopes("queue:get-artifact:private/*")
        .with_scopes("queue:get-artifact:public/*")
        .with_scopes("object:upload:divvun:*")
        .with_scopes("secrets:get:divvun" * with_secrets)
        .with_features("taskclusterProxy")
        .with_caches(
            **{
                "divvun-cargo-registry": "/root/.cargo/registry",
                "divvun-cargo-git": "/root/.cargo/git",
                "divvun-rustup": "/root/.rustup",
            }
        )
        .with_index_and_artifacts_expire_in(BUILD_ARTIFACTS_EXPIRE_IN)
        .with_max_run_time_minutes(60)
        .with_script("mkdir -p $HOME/tasks/$TASK_ID")
        .with_script("mkdir -p $HOME/tasks/$TASK_ID/_temp")
        .with_apt_update()
        .with_apt_install("curl", "git", "python3", "python3-pip")
        .with_pip_install("taskcluster", "pyYAML")
        .with_apt_install("wget", "nodejs", "awscli")
        .with_repo_bundle("repo", bundle_dest)
        .with_repo_bundle("ci", "ci")
        .with_script(f"cd $HOME/tasks/$TASK_ID/{bundle_dest}")
    )
    return task

def macos_task(name):
    return (
        decisionlib.MacOsGenericWorkerTask(name)
        .with_worker_type("macos")
        .with_scopes("queue:get-artifact:private/*")
        .with_scopes("queue:get-artifact:public/*")
        .with_scopes("object:upload:divvun:*")
        .with_scopes("secrets:get:divvun")
        .with_index_and_artifacts_expire_in(BUILD_ARTIFACTS_EXPIRE_IN)
        .with_max_run_time_minutes(60)
        .with_provisioner_id("divvun")
        .with_features("taskclusterProxy")
        .with_script("mkdir -p $HOME/tasks/$TASK_ID")
        .with_script("mkdir -p $HOME/tasks/$TASK_ID/_temp")
        .with_repo_bundle("ci", "ci")
        .with_repo_bundle("repo", "repo")
        .with_script("cd $HOME/tasks/$TASK_ID/repo")
    )

def windows_task(name):
    return (
        decisionlib.WindowsGenericWorkerTask(name)
        .with_worker_type("windows")
        .with_provisioner_id("divvun")
        .with_scopes("queue:get-artifact:private/*")
        .with_scopes("queue:get-artifact:public/*")
        .with_scopes("object:upload:divvun:*")
        .with_scopes("secrets:get:divvun")
        .with_index_and_artifacts_expire_in(BUILD_ARTIFACTS_EXPIRE_IN)
        .with_max_run_time_minutes(60)
        .with_script("mkdir %HOMEDRIVE%%HOMEPATH%\\%TASK_ID%")
        .with_script("mkdir %HOMEDRIVE%%HOMEPATH%\\%TASK_ID%\\_temp")
        .with_features("taskclusterProxy")
        .with_repo_bundle("ci", "ci")
        .with_repo_bundle("repo", "repo")
        .with_python3()
        .with_script("pip install --user taskcluster")
        .with_script("cd %HOMEDRIVE%%HOMEPATH%\\%TASK_ID%\\repo")
    )

def gha_setup():
    return GithubAction("Eijebong/divvun-actions/setup", {}).with_secret_input(
        "key", "divvun", "DIVVUN_KEY"
    )

def gha_pahkat(packages: List[str]):
    return GithubAction(
        "Eijebong/divvun-actions/pahkat/init",
        {
            "repo": "https://pahkat.uit.no/devtools/",
            "channel": "nightly",
            "packages": ",".join(packages),
        },
    )

def _generic_rust_build_upload_task(
    os_,
    task_name,
    cargo_toml_path,
    package_id,
    target_dir,
    bin_name,
    env,
    setup_uploader,
    rename_binary,
    features,
    version_action
):
    if os_ == "windows":
        target_dir = "\\".join(target_dir.split("/"))
        task_new = windows_task
        install_rust = GithubAction(
            "actions-rs/toolchain",
            {
                "toolchain": "stable",
                "profile": "minimal",
                "override": "true",
                "components": "rustfmt",
                "target": "i686-pc-windows-msvc",
            },
        )
        build = GithubAction(
            "actions-rs/cargo",
            {
                "command": "build",
                "args": f"--release {features} --manifest-path {cargo_toml_path} --target i686-pc-windows-msvc",
            },
        )
        dist = GithubActionScript(
            f"mkdir dist\\bin && move {target_dir}\\i686-pc-windows-msvc\\release\\{bin_name}.exe dist\\bin\\{rename_binary}.exe"
        )
        sign = GithubAction(
            "Eijebong/divvun-actions/codesign",
            {"path": f"dist/bin/{rename_binary}.exe"},
        )
        deploy = GithubAction(
            "Eijebong/divvun-actions/deploy",
            {
                "package-id": package_id,
                "type": "TarballPackage",
                "platform": "windows",
                "arch": "i686",
                "repo": PAHKAT_REPO + "devtools/",
                "version": "${{ steps.version.outputs.version }}",
                "channel": "${{ steps.version.outputs.channel }}",
                "payload-path": "${{ steps.tarball.outputs['txz-path'] }}",
            },
        )
    elif os_ == "macos":
        task_new = macos_task
        install_rust = GithubAction(
            "actions-rs/toolchain",
            {
                "toolchain": "stable",
                "profile": "minimal",
                "override": "true",
                "components": "rustfmt",
            },
        )
        build = GithubAction(
            "actions-rs/cargo",
            {
                "command": "build",
                "args": f"--release {features} --manifest-path {cargo_toml_path}",
            },
        )
        dist = GithubActionScript(
            f"mkdir -p dist/bin && mv {target_dir}/release/{bin_name} dist/bin/{rename_binary}"
        )
        sign = GithubAction(
            "Eijebong/divvun-actions/codesign", {"path": f"dist/bin/{rename_binary}"}
        )
        deploy = GithubAction(
            "Eijebong/divvun-actions/deploy",
            {
                "package-id": package_id,
                "type": "TarballPackage",
                "platform": "macos",
                "arch": "x86_64",
                "repo": PAHKAT_REPO + "devtools/",
                "version": "${{ steps.version.outputs.version }}",
                "channel": "${{ steps.version.outputs.channel }}",
                "payload-path": "${{ steps.tarball.outputs['txz-path'] }}",
            },
        )
    elif os_ == "linux":
        task_new = lambda name: linux_build_task(name).with_gha(
            "setup_linux", GithubActionScript("apt install -y musl musl-tools")
        )
        install_rust = GithubAction(
            "actions-rs/toolchain",
            {
                "toolchain": "stable",
                "profile": "minimal",
                "override": "true",
                "components": "rustfmt",
                "target": "x86_64-unknown-linux-musl",
            },
        )
        build = GithubAction(
            "actions-rs/cargo",
            {
                "command": "build",
                "args": f"--release {features} --manifest-path {cargo_toml_path}",
            },
        )
        dist = GithubActionScript(
            f"mkdir -p dist/bin && mv {target_dir}/release/{bin_name} dist/bin/{rename_binary}"
        )
        sign = GithubActionScript('echo "No code signing on linux"')
        deploy = GithubAction(
            "Eijebong/divvun-actions/deploy",
            {
                "package-id": package_id,
                "type": "TarballPackage",
                "platform": "linux",
                "arch": "x86_64",
                "repo": PAHKAT_REPO + "devtools/",
                "version": "${{ steps.version.outputs.version }}",
                "channel": "${{ steps.version.outputs.channel }}",
                "payload-path": "${{ steps.tarball.outputs['txz-path'] }}",
            },
        )
    else:
        raise NotImplementedError

    return (
        task_new(f"{task_name}: {os_}")
        .with_env(**env)
        .with_script(
            r'call "C:\Program Files (x86)\Microsoft Visual Studio\2017\BuildTools\Common7\Tools\VsDevCmd.bat"'
            if os_ == "windows"
            else ""
        )
        .with_gha("setup", gha_setup())
        # The actions-rs action is broken on windows
        .with_gha(
            "install_rustup",
            GithubActionScript(
                "choco install -y --force rustup.install && echo ::add-path::${HOME}/.cargo/bin"
            ),
            enabled=(os_ == "windows"),
        )
        .with_gha("version", version_action)
        .with_gha("install_rust", install_rust)
        .with_gha("build", build)
        .with_gha("dist", dist)
        .with_gha("sign", sign)
        .with_gha(
            "tarball",
            GithubAction("Eijebong/divvun-actions/create-txz", {"path": "dist"}),
        )
        .with_gha("setup_uploader", setup_uploader)
        .with_gha(
            "deploy",
            deploy.with_secret_input("GITHUB_TOKEN", "divvun", "GITHUB_TOKEN"),
        )
        .with_prep_gha_tasks()
        .find_or_create(f"build.{bin_name}.{os_}.{CONFIG.git_sha}")
    )

def generic_rust_build_upload_task(
    task_name: str,
    cargo_toml_path: str,
    package_id: str,
    target_dir: str,
    bin_name: str,
    env: Dict[str, Any],
    setup_uploader: Callable[[str], GithubAction],
    rename_binary: Optional[str]=None,
    get_features: Optional[Callable[[str], GithubAction]]=None,
    version_action: Optional[GithubAction]=None,
    only_os: Optional[List[str]]=None
):
    if rename_binary is None:
        rename_binary = bin_name
    if version_action is None:
        version_action = GithubAction("Eijebong/divvun-actions/version", {"cargo": cargo_toml_path, "nightly": "main, develop"}).with_secret_input("GITHUB_TOKEN", "divvun", "GITHUB_TOKEN")
    if only_os is None:
        only_os = ["macos", "windows", "linux"]

    for os_ in only_os:
        if get_features is not None:
            features = get_features(os_)
        else:
            features = ""
        _generic_rust_build_upload_task(
            os_,
            task_name,
            cargo_toml_path,
            package_id,
            target_dir,
            bin_name,
            env,
            setup_uploader(os_),
            rename_binary,
            features,
            version_action
        )


import pandas as pd

def readData(dataDf, targetStart, targetEnd, windowEnd):

    dataDf.anchor_time = dataDf.anchor_time.apply(lambda x: pd.to_datetime(x, format='%Y-%m-%d %H:%M:%S'))
    dataDf.death_datetime = dataDf.death_datetime.apply(lambda x: pd.to_datetime(x, format='%Y-%m-%d %H:%M:%S'))

    if dataDf.empty:
        return None

    dataDf['target'] = (dataDf['death_datetime'] > (dataDf['anchor_time'] + pd.Timedelta(days=targetStart))) & (dataDf['death_datetime'] < (dataDf['anchor_time'] + pd.Timedelta(days=targetEnd)))
    dataDf.fillna({'target': False}, inplace=True)

    dropCols = [
        'person_id',
        'age',
        'gender',
        'ethnicity_WHITE',
        'ethnicity_BLACK',
        'ethnicity_UNKNOWN',
        'ethnicity_OTHER',
        'ethnicity_HISPANIC',
        'ethnicity_ASIAN',
        'ethnicity_UNABLE_TO_OBTAIN',
        'ethnicity_AMERICAN_INDIAN',
        'anchor_time',
        'death_datetime',
        'target',
    ]

    vitalsCols = ['heartrate', 'sysbp', 'diabp', 'meanbp', 'resprate', 'tempc', 'spo2', 'gcseye', 'gcsverbal', 'gcsmotor']
    labsCols = ['chloride_serum', 'creatinine', 'sodium_serum', 'hemoglobin', 'platelet_count', 'urea_nitrogen', 'glucose_serum', 'bicarbonate', 'potassium_serum', 'anion_gap', 'leukocytes_blood_manual', 'hematocrit']

    X = dataDf.drop(dropCols, axis = 1)
    XVitalsMin = dataDf[[vitalCol + '_min' for vitalCol in vitalsCols if vitalCol + '_min' in dataDf.columns]]
    XVitalsMax = dataDf[[vitalCol + '_max' for vitalCol in vitalsCols if vitalCol + '_max' in dataDf.columns]]
    XVitalsAvg = dataDf[[vitalCol + '_avg' for vitalCol in vitalsCols if vitalCol + '_avg' in dataDf.columns]]
    XVitalsSd = dataDf[[vitalCol + '_stddev' for vitalCol in vitalsCols if vitalCol + '_stddev' in dataDf.columns]]
    XVitalsFirst = dataDf[[vitalCol + '_first' for vitalCol in vitalsCols if vitalCol + '_first' in dataDf.columns]]
    XVitalsLast = dataDf[[vitalCol + '_last' for vitalCol in vitalsCols if vitalCol + '_last' in dataDf.columns]]
    XLabsMax = dataDf[[labsCol + '_min' for labsCol in labsCols if labsCol + '_min' in dataDf.columns]]
    XLabsMin = dataDf[[labsCol + '_max' for labsCol in labsCols if labsCol + '_max' in dataDf.columns]]
    XLabsAvg = dataDf[[labsCol + '_avg' for labsCol in labsCols if labsCol + '_avg' in dataDf.columns]]
    XLabsSd = dataDf[[labsCol + '_stddev' for labsCol in labsCols if labsCol + '_stddev' in dataDf.columns]]
    XLabsFirst = dataDf[[labsCol + '_first' for labsCol in labsCols if labsCol + '_first' in dataDf.columns]]
    XLabsLast = dataDf[[labsCol + '_last' for labsCol in labsCols if labsCol + '_last' in dataDf.columns]]
    y = dataDf["target"]

    return X, XVitalsMax, XVitalsMin, XVitalsAvg, XVitalsSd, XVitalsFirst, XVitalsLast, XLabsMax, XLabsMin, XLabsAvg, XLabsSd, XLabsFirst, XLabsLast, y


import ee
import time
from datetime import datetime
from google.cloud import storage
import os
import rasterio

TASK_FINISHED_STATES = (ee.batch.Task.State.COMPLETED,
                        ee.batch.Task.State.FAILED,
                        ee.batch.Task.State.CANCELLED)

class getJsonEnv():
    """
    Grabs .env
    """
    def __init__(self):

        with open('gcsPrivatekey.json','w') as f:
            f.write(os.getenv('GCS_JSON'))

        with open('geePrivatekey.json','w') as f:
            f.write(os.getenv('GEE_JSON'))

class assetManagement(object):
    ## Connects to bucket, upload the image and once it is ready transfers it to GEE associated collection.
    """
    ImageObject:
    {
    'sources':['/Users/alicia/Downloads/results%2Fhistorical%2Fdecadal_test_historical_1991_2000_hdds.tiff'],
    'gcsBucket':'gee-image-transfer',
    'collectionAsset':'users/Aliciaarenzana/testcollection',
    'assetName':'t2000',
    'bandNames':[{'id': 'R'}, {'id': 'G'}, {'id': 'B'}],
    'pyramidingPolicy':'MODE',
    'properties':{
        'my_imageProperties':'to add to the collection'
        }
    }
    """
    def __init__(self,imageObject):
        """checks the image and sets up the properties """
        getJsonEnv()
        self.meta=imageObject
        self.imageNames=self.getImageName()
        self.gcsBucket=self.setUpCredentials()
        self.sources = []

    def getImageName(self):
        """gets the listof names from sources"""
        return [os.path.basename(name) for name in self.meta['sources']]

    def checksImages(self):
        """Checks the images that we will compose have the same n bands as they are going to become one image and part of the image collection"""
        metadata=[]
        for image in self.meta['sources']:
            with rasterio.open(image) as src:
                metaData=src.meta

                assert metaData['driver'] == 'GTiff', "Driver is not supported: {0}".format(metaData['driver'])
                assert metaData['count'] == len(self.meta['bandNames']), "Nbands incorrect, expected: {0}, {1} provided".format(metaData['count'],len(self.meta['bandNames']))

                metadata.append({'dtype': metaData['dtype'], 'driver': metaData['driver'], 'nodata': metaData['nodata'], 'nBands': metaData['count'],'crs': src.crs.to_string()})

        assert len(set([item['dtype'] for item in metadata])) == 1, "Images list dtypes aren't compatibles. Expected: 1, {1} provided".format(metaData['count'],len(set([item['dtype'] for item in metadata])))
        assert len(set([item['driver'] for item in metadata])) == 1, "Images list drivers aren't compatibles. Expected: 1, 1 provided".format(metaData['count'],len(set([item['driver'] for item in metadata])))
        assert len(set([item['nodata'] for item in metadata])) == 1, "Images list nodata values aren't compatibles. Expected: 1, {1} provided".format(metaData['count'],len(set([item['nodata'] for item in metadata])))
        assert len(set([item['nBands'] for item in metadata])) == 1, "Images list nBands number aren't compatibles. Expected: 1, {1} provided".format(metaData['count'],len(set([item['nBands'] for item in metadata])))
        assert len(set([item['crs'] for item in metadata])) == 1, "Images list crs aren't compatibles. Expected: 1, {1} provided".format(metaData['count'],len(set([item['crs'] for item in metadata])))
        return metadata[0]

    def setUpCredentials(self):
        """Sets up the credentials"""
        credentials = ee.ServiceAccountCredentials(os.getenv('GEE_SACCOUNT'), 'geePrivatekey.json')
        ee.Initialize(credentials)
        storage_client=storage.Client.from_service_account_json('gcsPrivatekey.json')
        return storage_client.get_bucket(self.meta['gcsBucket'])

    def setUpGeeAsset(self):
        aclSet='{"all_users_can_read" : true}'
        collectionAsset=self.meta['collectionAsset'].split('/')
        assetHome ="{0}/{1}".format(collectionAsset[0],collectionAsset[1])
        if ee.data.getInfo(assetHome) == None:
            ee.data.createAssetHome(assetHome)
        if ee.data.getInfo(self.meta['collectionAsset']) == None:
            ee.data.createAsset({'type': 'ImageCollection'}, self.meta['collectionAsset'])
            ee.data.setAssetAcl(self.meta['collectionAsset'],aclSet)

    def uploadGCS(self, imageName):
        """Upload the image to google cloud storage"""
        imageIndex = self.imageNames.index(imageName)
        blob = self.gcsBucket.blob('{0}/{1}'.format(self.meta['collectionAsset'],imageName))
        blob.upload_from_filename(self.meta['sources'][imageIndex])
        blob.make_public()

        return {'primaryPath': 'gs://{gcsBucket}/{collectionName}/{imageNa}'.format(gcsBucket=self.meta['gcsBucket'],collectionName=self.meta['collectionAsset'],imageNa=imageName)}

    def transferGEE(self):
        """Transfers the images from google cloud storage to gee asset"""
        task_id = ee.data.newTaskId()[0]
        time = self.meta['properties']['system:time_start']

        self.meta['properties']['system:time_start'] = ee.Date(time).getInfo()['value']

        request = {
            'id':'{collectionAsset}/{assetName}'.format(collectionAsset= self.meta['collectionAsset'],assetName =self.meta['assetName']),
            'properties':self.meta['properties'],
            'tilesets': [{'sources': self.sources}],
            'pyramidingPolicy':self.meta['pyramidingPolicy'].upper(),
            'bands':self.meta['bandNames']
        }
        ee.data.startIngestion(task_id, request, True)
        return task_id

    def taskStatus(self, task_id, timeout=90, log_progress=True):
        """Waits for the specified task to finish, or a timeout to occur. (thanks to gee cli)"""
        start = time.time()
        elapsed = 0
        last_check = 0
        while True:
            elapsed = time.time() - start
            status = ee.data.getTaskStatus(task_id)[0]
            state = status['state']
            if state in TASK_FINISHED_STATES:
              error_message = status.get('error_message', None)
              print('Task %s ended at state: %s after %.2f seconds'
                    % (task_id, state, elapsed))
              if error_message:
                raise ValueError(error_message)
              return
            if log_progress and elapsed - last_check >= 30:
              print('[{:%H:%M:%S}] Current state for task {}: {}'
                    .format(datetime.now(), task_id, state))
              last_check = elapsed
            remaining = timeout - elapsed
            if remaining > 0:
              time.sleep(min(10, remaining))
            else:
              break
        print('Wait for task %s timed out after %.2f seconds' % (task_id, elapsed))

    def execute(self):
        #Checks if the images are correct
        self.checksImages()

        #sets up credentials and assets

        self.setUpGeeAsset()

        #Uploads file/s to GCS
        self.sources = list(map(self.uploadGCS, self.imageNames))

        #Transfers it from GCS to GEE
        task_id = self.transferGEE()

        print('TaskID: {0}'.format(task_id))
        print('Status: {0}'.format(ee.data.getTaskStatus(task_id)[0]))
        self.taskStatus(task_id)


#Consider two variables 'a' and 'b' in Python such that a = 4 and b = 5. Swap the values of 'a' and 'b' without using a temporary variable. Print the values of 'a' and 'b' before and after swapping.

a = 4
b = 5
print("before Swapping: a =",a ," b =", b);

# Code to swap 'a' and 'b'
# a now becomes 9
a = a + b
# b becomes 4
b = a - b
# a becomes 5
a = a - b
print("After Swapping: a =",a ," b =", b);

'''
output::
PrashantWalunj@PrashantWalunj:/mnt/e/Prashant/infosys/fp5.0_prashantwalunj/module_1/assg_11$ python3 1.py
before Swapping: a = 4  b = 5
After Swapping: a = 5  b = 4
PrashantWalunj@PrashantWalunj:/mnt/e/Prashant/infosys/fp5.0_prashantwalunj/module_1/assg_11$

'''


from sudoku_generator import SudokuGenerator
import sudoku_generator

game = 0
start = 0

def update_visuals():
    """
    :return: visual sudoku board (string) that contains sudoku                 puzzle numbers
    """
    global game
    all_digits = []
    for i in range(9):
        all_digits.extend(game.board[i])
    for index, num in enumerate(all_digits):
        if num == 0:
            all_digits[index] = ' '

    board_visual = ''
    space_row = ''
    i = 0
    while i < len(all_digits):
        if i != 0:
            if i % 3 == 0:
                board_visual += '  '
            if i % 9 == 0:
                board_visual += '\n'
            if i % 27 == 0:
                board_visual += f'\n{space_row}'
        board_visual += f'[{all_digits[i]}]'
        i += 1
    return board_visual

def solution_visual():
    global game
    all_digits = []
    for i in range(9):
        all_digits.extend(game.solution[i])
    for index, num in enumerate(all_digits):
        if num == 0:
            all_digits[index] = ' '

    board_visual = ''
    space_row = ''
    i = 0
    while i < len(all_digits):
        if i != 0:
            if i % 3 == 0:
                board_visual += '  '
            if i % 9 == 0:
                board_visual += '\n'
            if i % 27 == 0:
                board_visual += f'\n{space_row}'
        board_visual += f'[{all_digits[i]}]'
        i += 1
    return board_visual

def original_visual():
    global game
    all_digits = []
    for i in range(9):
        all_digits.extend(game.original[i])
    for index, num in enumerate(all_digits):
        if num == 0:
            all_digits[index] = ' '

    board_visual = ''
    space_row = ''
    i = 0
    while i < len(all_digits):
        if i != 0:
            if i % 3 == 0:
                board_visual += '  '
            if i % 9 == 0:
                board_visual += '\n'
            if i % 27 == 0:
                board_visual += f'\n{space_row}'
        board_visual += f'[{all_digits[i]}]'
        i += 1
    return board_visual

def check_results():
    win = False
    # print(game.board)
    # print(game.solution)
    if game.board == game.solution:
        win = True
    return win

def game_start():
    # Start screen
    global game
    global start
    print('Game modes:')
    print('1. Easy')
    print('2. Medium')
    print('3. Hard')
    print('Select a option:', end=' ')
    option = int(input())
    if option == 1:
        game = SudokuGenerator(30, 9)
        game.fill_values()
        start = game.board
        endboard = start
        game.remove_cells()
        print(update_visuals())
    elif option == 2:
        game = SudokuGenerator(40, 9)
        game.fill_values()
        start = game.board
        game.remove_cells()
        print(update_visuals())
    elif option == 3:
        game = SudokuGenerator(50, 9)
        game.fill_values()
        start = game.board
        game.remove_cells()
        print(update_visuals())

    return game.board

def select_cell():
    print('What number would you like to insert?')
    number = input()
    if number == "0":
        print("Pick another number")
        select_cell()
    print('In which box?')
    box_num = input()
    print('In which cell?')
    cell_num = input()
    if box_num == "1":
        box = game.get_box(0, 0)
    elif box_num == "2":
        box = game.get_box(0, 4)
    elif box_num == "3":
        box = game.get_box(0, 7)
    elif box_num == "4":
        box = game.get_box(4, 0)
    elif box_num == "5":
        box = game.get_box(4, 4)
    elif box_num == "6":
        box = game.get_box(4, 7)
    elif box_num == "7":
        box = game.get_box(7, 0)
    elif box_num == "8":
        box = game.get_box(7, 4)
    elif box_num == "9":
        box = game.get_box(7, 7)
    x_val = 0
    y_val = 0
    if cell_num == "1":
        coordinates = box[0]
        x_val = coordinates[1]
        y_val = coordinates[4]
        coordinates = [x_val, y_val]
    elif cell_num == "2":
        coordinates = box[1]
        x_val = coordinates[1]
        y_val = coordinates[4]
        coordinates = [x_val, y_val]
    elif cell_num == "3":
        coordinates = box[2]
        x_val = coordinates[1]
        y_val = coordinates[4]
        coordinates = [x_val, y_val]
    elif cell_num == "4":
        coordinates = box[3]
        x_val = coordinates[1]
        y_val = coordinates[4]
        coordinates = [x_val, y_val]
    elif cell_num == "5":
        coordinates = box[4]
        x_val = coordinates[1]
        y_val = coordinates[4]
        coordinates = [x_val, y_val]
    elif cell_num == "6":
        coordinates = box[5]
        x_val = coordinates[1]
        y_val = coordinates[4]
        coordinates = [x_val, y_val]
    elif cell_num == "7":
        coordinates = box[6]
        x_val = coordinates[1]
        y_val = coordinates[4]
        coordinates = [x_val, y_val]
    elif cell_num == "8":
        coordinates = box[7]
        x_val = coordinates[1]
        y_val = coordinates[4]
        coordinates = [x_val, y_val]
    elif cell_num == "9":
        coordinates = box[8]
        x_val = coordinates[1]
        y_val = coordinates[4]
    coordinates = [x_val, y_val]
    if game.board[int(x_val)][int(y_val)] == 0:
        game.board[int(x_val)][int(y_val)] = int(number)
    else:
        print('This cell is full.')
        select_cell()

def game_won():
    # Game won screen
    print('Game won!')
    print('Press 0 to exit')

def game_lost():
    # Game lost screen
    print('Game over!')
    print('Press 1 to restart')

def main():
    global game
    print(update_visuals())

def won_game(board):
    won = False
    print(board)
    print(start)
    if board == start:
        won = True

    return won

if __name__ == "__main__":
    print('Welcome to Sudoku')
    # print(update_visuals())
game_start()
running = True
print("Input 0 after entering a value to end playing:")
select_cell()
print(update_visuals())
print('To exit press 0.')
print('To continue playing press 1.')
print('To reset the board, press 2')
print("To reset the game, press 3")
choice = input()
while running == True:
    if choice == "0":
        if not check_results():
            print("You lose")
        else:
            print("You win")
        print("Winning Board")
        print(solution_visual())
        print("Have a nice day")
        running = False
    elif choice == "1":
        select_cell()
        print(update_visuals())
        print('To exit press 0.')
        print('To continue playing press 1.')
        print('To reset the board, press 2')
        print("To reset the game, press 3")
        choice = input()
    elif choice == "2":
        game.board = game.original
        print(original_visual())
        print('To exit press 0.')
        print('To continue playing press 1.')
        print('To reset the board, press 2')
        print("To reset the game, press 3")
        choice = input()
    elif choice == "3":
        game_start()
        print('To exit press 0.')
        print('To continue playing press 1.')
        print('To reset the board, press 2')
        print("To reset the game, press 3")
        choice = input()

    else:
        print('To exit press 0.')
        print('To continue playing press 1.')
        print('To reset the board, press 2')
        print("To reset the game, press 3")
        choice = input()


import pandas as pd
from main import dateTransform
import pandas as pd
from matplotlib import pyplot as plt

df_BL = pd.read_csv("BL_2017-2022_cleaned.csv")
df_BL = dateTransform(df_BL)
date_column = 'Buchungsdatum (BL)_datetime'

s3 = df_BL.groupby([df_BL[date_column].dt.strftime('%Y-%m'),"Kundengruppe","Baureihe VT", "Umsatzgebiet"]).agg({'ST': 'sum'})#.reset_index()
s3df = s3.reset_index()
print(s3df)

s3df['Kundengruppe']=s3df['Kundengruppe'].astype('category').cat.codes
s3df['Baureihe VT']=s3df['Baureihe VT'].astype('category').cat.codes
s3df['Umsatzgebiet']=s3df['Umsatzgebiet'].astype('category').cat.codes
s3df[date_column]=s3df[date_column].astype('category').cat.codes

print(s3df)
corr = s3df.corr()
print(corr)

years = ["all"] #,"2017","2018","2019","2020","2021","2022"]

for startyear in years:
    if startyear != "all":
        df_BL = df_BL.loc[df_BL[date_column] >= "%s-01" % startyear]
        df_BL = df_BL.loc[df_BL[date_column] <= "%s-01"% (int(startyear)+1)]

    groups = ["Kundengruppe","Baureihe VT", "Umsatzgebiet"]
    for grouping in groups:
        print("nach %s" % grouping)

        s3 = df_BL.groupby([df_BL[date_column].dt.strftime('%Y-%m'), df_BL[grouping]]).agg({'ST': 'sum'})#.reset_index()
        s3df = s3.reset_index()

        s3df.to_csv(f"groupby_month_{grouping}_year_{startyear}.csv")
        print("s3: ", s3)

        s4 = df_BL.groupby([grouping]).agg({"ST" : "sum"})
        s4["ST [%]"] = s4["ST"]/s4["ST"].sum() * 100
        s4=s4.sort_values("ST [%]",ascending=False)
        print(s4)
        s3df.to_csv(f"groupby_month_percent_{grouping}_year_{startyear}.csv")
        print(s4["ST [%]"].sum())


import argparse
import ntpath
import os
import time

import camkifu.core
import ckmain
import test.objects

"""
Script that helps with running successive detection tests in one go. To be called on a directory containing
video files and reference sgf files.

For each sgf reference (supposed to contain the expected results), look for a file with the same name but a
different extension, and run the vision algorithms on that file. Stop when all references have been processed.

Expand / modify the Report class depending on the kind of information needed.

"""

def list_bench(refdir, vid_dir) -> dict:
    """
    Map each sgf reference to the first matching "video" file (if found) in a dict.
    The "video" file is the first file with a matching name, the extension is not checked.

    refdir -- the directory containing the sgf files
    vid_dir -- the directory containing the video files

    """
    # step 0: arrange paths
    if not vid_dir.endswith("/"):
        vid_dir += "/"
    if refdir is None:
        refdir = vid_dir
    elif not refdir.endswith("/"):
        refdir += "/"

    # step 1: list video candidates (all files that are not sgf)
    vid_files = []
    for f in os.listdir(vid_dir):
        if not f.endswith('.sgf'):
            vid_files.append(f)

    # step 2: match sgf references to video candidates
    bench = {}
    unmatched = []
    for sgf in os.listdir(refdir):
        if sgf.endswith('.sgf'):
            matched = False
            key = ntpath.basename(sgf)[:-4]
            for vf in vid_files:
                if ntpath.basename(vf).startswith(key):
                    matched = True
                    if sgf not in bench:
                        bench[refdir + sgf] = vid_dir + vf
                    else:
                        msg_base = "Benchmark warning: multiple video candidates for reference file {}.sgf : {}"
                        print(msg_base.format(key, [ntpath.basename(bench[sgf]), vf]))
                        break  # at least one warning should be enough to get attention
            if not matched:
                unmatched.append(ntpath.basename(sgf))
    if len(unmatched):
        print("Benchmark warning: unmatched reference files {}".format(unmatched))
    return bench

def main(vid_dir, refdir=None, bf=None, sf=None):
    """
    vid_dir -- the directory containing the videos on which to run the benchmark. May also contain the reference sgf(s).

    """
    bench = list_bench(refdir, vid_dir)
    reports = []
    for i, (sgf, vid) in enumerate(bench.items()):
        msg_base = "{} ({}/{}) ----------------------------------------------------------------"
        print(msg_base.format(ntpath.basename(vid), i+1, len(bench)))
        controller = test.objects.ControllerVTest(sgf, video=vid)
        vmanager = camkifu.core.VManager(controller, imqueue=DummyQueue(), bf=bf, sf=sf)
        stop_condition = lambda: vmanager.hasrun and not vmanager.is_processing()
        test.objects.ProcessKiller(vmanager, stop_condition).start()
        start = time.time()
        vmanager.run()
        reports.append(Report(vmanager, time.time() - start))
    for r in reports:
        print(r)

class Report:

    def __init__(self, vmanager, duration):
        self.vmanager = vmanager
        self.sgf = vmanager.controller.kifu.ref.sgffile
        self.video = vmanager.controller.video
        self.matcher = vmanager.controller.kifu.check()
        self.duration = duration

    def __repr__(self):
        name = ntpath.basename(self.sgf)[:-4]
        percent = round(100*self.matcher.ratio(), 1)
        return "[{}: {}% in {} s]".format(name, percent, int(round(self.duration)))

class DummyQueue:
    def put(self, x):
        pass

    def put_nowait(self, x):
        pass

def get_argparser() -> argparse.ArgumentParser:
    parser = argparse.ArgumentParser()
    ckmain.add_finder_args(parser)

    # compulsory argument
    parser.add_argument("dir", help="Directory containing the videos on which to run the benchmark.")

    # optional arguments
    refdir_help = "Directory containing the reference sgfs associated with each video (matched on filename)." \
                  " Defaults to \"dir\" if omitted."
    parser.add_argument("--refdir", help=refdir_help)

    return parser

if __name__ == '__main__':
    args = get_argparser().parse_args()
    main(args.dir, refdir=args.refdir, bf=args.bf, sf=args.sf)


def reverse_str(str_a):
    list_a = ' '.join(str).split()
    for i in range(len(list_a)//2):
        list_a[i], list_a[-i] = list_a[-i], list_a[i]
    return ''.join(list_a)

print(reverse_str('abc'))

def strcpm(str1, str2):
    i = 0
    if len(str1) != len(str2):
        return False
    else:
        while i < len(str1) and i < len(str2):
            if str1[i] != str2[i]:
                return False
            i += 1
    return True

def atoi(string):
    value = 0
    i = 0
    while (i < len(string)):
        c = string[i]
        if c >= '0' and c <= '9':
            digit = ord(c) - ord('0')
        else:
            break
        value = (value * 10) + digit
        i += 1
    return value

a = '123'
print(type(a))
b = atoi(a)
print(type(b))

str1 = "abc 1,2 ABC"
print(str1)
str1 = str1.replace("1,2", "one, two")
print(str1)

def itoa(intN):
    lists = []
    while intN in list(range(10)):
        lists.insert(intN % 10)
        intN = intN//10
    return ''.join(lists)

def itoa(x):
    str = list()
    y = 0


import subprocess

results = []
max = 0
maxA = [[]]
cmdAns = ''
with open('results.txt', 'a') as f:
    for num_epoch in range(100, 1001, 100):
        for num_hidden in [32, 64, 128, 256, 512, 1024]:
            for l2_reg_const in [0.0, 0.001, 0.005, 0.01]:
                for num_shadows in range(10, 201, 10):
                    nn_desc = "simple,{},{}".format(num_hidden, l2_reg_const)
                    cmd = "python3 hw.py problem4 {} {} {}".format(nn_desc, num_epoch, num_shadows)
                    # execute the command and capture the output
                    output = subprocess.check_output(cmd.split())
                    output_lines = output.decode().strip().split('\n')
                    print(output_lines)
                    # write the output lines to the file
    #                 f.write(f"Command: {cmd}\n")
    #                 for line in output_lines:
    #                     f.write(f"{line}\n")
    #                 f.write('\n')
    # f.write(f"FINAL ANS\n")
    # f.write(f"{cmdAns}\n")
    # f.write(f"{maxA}\n")
    # f.write('\n')


"""Shutil file extractor module"""
import logging
import shutil

from tools.triage.utils.extraction import ExtractorInterface

class ShutilExtractor(ExtractorInterface):
    """Responsible for handling the extraction of supported files using shutil"""

    def __init__(self):
        self.logger = logging.getLogger(__name__)

    def can_handle_file(self, filename: str) -> bool:
        """Overrides ExtractorInterface.can_handle_file()"""
        if not super().can_handle_file(filename):
            return False

        # Check to see if shutil supports the file extension
        supported_extensions = []
        for format in shutil.get_unpack_formats():
            supported_extensions.extend(format[1])
        for ext in supported_extensions:
            if filename.endswith(ext):
                return True
        return False

    def extract(self, filename, destination_directory) -> str:
        """Overrides ExtractorInterface.extract()"""
        if not self.can_handle_file(filename):
            message = f"This extractor does not support the file {filename}"
            self.logger.error(message)
            return
        try:
            shutil.unpack_archive(filename, destination_directory)
            return destination_directory
        except Exception as e:
            message = f"An error was encountered during shutil extraction of {filename} to {destination_directory}, the error was {e}"
            self.logger.error(message)


import requests
import pandas as pd
from dingtalkchatbot.chatbot import DingtalkChatbot
from apscheduler.schedulers.background import BackgroundScheduler
import time
import datetime
from config import config

class Bigdata():
    def __init__(self):
        self.path_coin = 'C:\\Users\\Administrator\\Desktop\\research\\10\\rank\\data\\'
        self.path_defi = 'C:\\Users\\Administrator\\Desktop\\research\\10\\rank\\defi\\'
        self.path_concept = 'C:\\Users\\Administrator\\Desktop\\research\\10\\rank\\concept\\'

        self.scheduler = BackgroundScheduler()
        """
        self.header = {'User-Agent' :"Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_6) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/92.0.4515.131 Safari/537.36",
                  "Referer": "https: // www.feixiaohao.cc/",
                  "Sec - Fetch - Site": "cross - site",
                  "Host": "dncapi.bqrank.net",
                  "Origin": "https: // www.feixiaohao.cc",
                  "Referer": "https: // www.feixiaohao.cc/",

                  }
        """
        self.header = {'User-Agent' :"Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_6) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/92.0.4515.131 Safari/537.36"

                  }
        self.dingding = DingtalkChatbot(config.webhook)

    def get_rank_list(self):
        print("get_rank_list")

        #signal = 0
        try:
            res = requests.get(url = 'https://dncapi.soulbab.com/api/coin/web-coinrank?page=1&type=-1&pagesize=100&webp=1', headers = self.header, timeout=10)
            #print(res)
            signal = 1

        except:
            signal = 0

        print("signal: ", signal)
        if signal == 1:
            i = 1
            rank_df = pd.DataFrame(columns=['rank', 'name', 'current_price_usd', 'market_value_usd', 'supply', 'turnoverrate'])
            for coin in res.json()['data']:

                new = pd.DataFrame({'rank': coin['rank'], 'name': coin['name'], 'current_price_usd': coin['current_price_usd'], 'market_value_usd': coin['market_value_usd'], 'supply': coin['supply'], 'turnoverrate': coin['turnoverrate']}, index = [i])
                i+=1
                rank_df = rank_df.append(new, ignore_index=True)
            #print(rank_df)
            rank_df.to_csv(self.path_coin + time.strftime('%Y%m%d') + '.csv')
            #self.dingding.send_text(msg=f"成功下载市值排名数据, {time.strftime('%Y%m%d %H:%M:%S')}", is_at_all=False)

        else:
            print("error in getting rank")
            #self.dingding.send_text(msg=f"下载市值排名数据出现错误, {time.strftime('%Y%m%d %H:%M:%S')}", is_at_all=False)

            #rank_df = 0

    def get_defi_rank_list(self):

        rank_df = pd.DataFrame(columns=['rank', 'code', 'volume', 'changerate', 'percentage', 'typename'])

        try:
            res = requests.get(url = 'https://dncapi.bqrank.net/api/v2/Defi/newlockup/list/page?per_page=100&typeid=1&webp=1', headers = self.header, timeout=10)

            signal = 1
        except:

            signal = 0

        if signal == 1:
            data = res.json()['data']['list']
            rank = 0
            for coin in data[0]['lockupitem']:
        # print(coin)
                new = pd.DataFrame({'rank': rank+1, 'code': coin['code'], 'volume': coin['volume'],
                            'changerate': coin['changerate'], 'percentage': coin['percentage'],
                            'typename': coin['typename']}, index=[rank])
                rank += 1
                rank_df = rank_df.append(new, ignore_index=True)
            rank_df.to_csv(self.path_defi + time.strftime('%Y%m%d')+'.csv')
            self.dingding.send_text(msg=f"成功下载DEFI锁仓量排名数据, {time.strftime('%Y%m%d %H:%M:%S')}", is_at_all=False)

        else:
            print("error in getting defi data")
            #self.dingding.send_text(msg=f"下载DEFI锁仓量排名数据出现错误, {time.strftime('%Y%m%d %H:%M:%S')}", is_at_all=False)

    def get_hot_races(self):

        rank_df = pd.DataFrame(columns=['rank', 'name', 'change'])

        try:
            res = requests.get(url = 'https://dncapi.bqrank.net/api/concept/conceptapplies?pagesize=10&type=1&webp=1', headers = self.header, timeout=10)
            #print(res)
            signal = 1
        except:

            signal = 0
        #print(res.json()['data'])
        if signal == 1:
            print(res.json()['data'])
            message = []
            data = res.json()['data']
            rank = 0
            for concept in data:
        # print(coin)
                new = pd.DataFrame({'rank': rank+1, 'concpet': concept['name'], 'change': concept['change']}, index=[rank])
                message.append((concept['name'], concept['change']))
                rank += 1
                rank_df = rank_df.append(new, ignore_index=True)
            rank_df.to_csv(self.path_concept + time.strftime('%Y%m%d')+'.csv')
            self.dingding.send_text(msg=f"概念板块排名:{message}, {time.strftime('%Y%m%d')}", is_at_all=False)

        else:
            print("error in getting concept data")
        #    self.dingding.send_text(msg=f"下载概念板块排名数据出现错误, {time.strftime('%Y%m%d %H:%M:%S')}", is_at_all=False)

    def get_defi_tvl_rank(self):
        hearder = { "User-Agent": "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_6) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/93.0.4577.63 Safari/537.36",}
        try:
            res = requests.get(url='https://defi-tracker.dappradar.com/api/ethereum/defi/all?currency=USD&limit=25&page=1&sort=tvlInFiat&order=desc',
                           headers=hearder, timeout=10)
            print(res)
        except:
            print("no response")
        #print(res.json())

    def monitor(self):
        self.scheduler.add_job(self.get_rank_list, 'cron', hour='17', minute='19', second='01')
        self.scheduler.add_job(self.get_defi_rank_list, 'cron', hour='17', minute='10', second='01')
        self.scheduler.start()
        while True:
            time.sleep(5)

def func():
    print("yes")

if __name__ == '__main__':
    # 创建后台执行的 schedulers
    bigdata = Bigdata()
    #bigdata.monitor()
    #bigdata.get_hot_races()
    #bigdata.get_defi_chain_rank()
    #bigdata.get_defi_rank_list()
    bigdata.get_rank_list()
    #bigdata.get_defi_tvl_rank()

    #bigdata.get_rank_list()
    #bigdata.get_defi_rank_list()
    #scheduler = BackgroundScheduler()
    #scheduler.add_job(bigdata.get_rank_list, 'cron', hour='17', minute='07', second='01')
    #scheduler.add_job(bigdata.get_rank_list, 'cron', hour='17', minute='11', second='01')
    #scheduler.add_job(bigdata.get_defi_rank_list, 'cron', hour='17', minute='30', second='00')
    #scheduler.start()
    #while True:
    #    time.sleep(5)
#get_rank_list()

#https://dncapi.bqrank.net/api/concept/conceptapplies?pagesize=10&type=1&webp=1


#!/usr/bin/python3

# requirements
from tornado import websocket, web, ioloop
import datetime
import logging
import json
import os

class StatsManager:

    # general attributes
    bootTime = None

    # attributes for requests
    requests = {}
    requests["total"] = 0
    requests["failed"] = 0
    requests["successful"] = 0
    requests["avg_time"] = 0
    requests["paths"] = {}

    def __init__(self, conf):
        self.bootTime = datetime.datetime.now()
        self.conf = conf

    def getStats(self):
        return {"bootTime": str(self.bootTime),
                "upTime": str(datetime.datetime.now() - self.bootTime),
                "requests": self.requests,
                "config": self.conf.tools
        }

    def reset(self):
        self.total_requests = 0
        self.failed_requests = 0
        self.successful_requests = 0

class StatsProcessor():

    def __init__(self, stats):
        self.stats = stats
        self.logger = logging.getLogger("mediatorLogger")
        self.template = os.path.join(os.path.dirname(__file__), "templates/stats.html")

    def getStats(self):

        # get stats
        return self.stats.getStats()

    def get(self):

        if self.request.path == "/stats":

            # debug print
            self.logger.debug("Stats request")

            # get stats
            res = self.stats.getStats()

            # json or html?
            key = self.get_argument('format', None)
            if key == "json":

                # return a json dict
                self.set_header("Content-Type", "application/json")
                self.write(json.dumps(res))

            else:

                # render a web page
                self.render(self.template, stats=res)

        elif self.request.path == "/clearStats":

            # reset stats
            self.stats.reset()

            # return the stats
            res = self.stats.getStats()
            self.set_header("Content-Type", "application/json")
            self.write(json.dumps(res))


# https://leetcode.com/problems/check-if-all-the-integers-in-a-range-are-covered/
import pytest

class Solution:
    def isCovered(self, ranges: list[list[int]], left: int, right: int) -> bool:
        dict_nums = {i: 0 for i in range(left, right + 1)}

        for (i, j) in ranges:
            while i <= j:
                dict_nums[i] = 1
                i += 1

        return all(dict_nums.values())

@pytest.mark.parametrize(
    ("ranges", "left", "right", "result"),
    [
        ([[1, 2], [3, 4], [5, 6]], 2, 5, True),
        ([[1, 50]], 1, 50, True),
        ([[1, 2], [5, 6]], 2, 5, False),
    ],
)
def test_isCovered(
    ranges: list[list[int]], left: int, right: int, result: bool
) -> None:
    assert result == Solution().isCovered(ranges, left, right)

print(Solution().isCovered([[1, 2], [3, 4], [5, 6]], 2, 5))


from Vaccum.Environment import Environment
from Vaccum.VacuumCleaner import VacuumCleaner

"""
	Vacuum Cleaner Agent
	Dirty Rooms = 1
	Clean Rooms = 0

	Environment Class Builds The Rooms Randomly With 10% Chance Of The Room Being Dirty!
	Vacuum Will Traverse Each Room Sequentially,
	If The Room Is Dirty -> Cleans The Room
	If The Room Is Clean -> Keeps Moving
	Each Movement( Cleaning/ Moving) Will Cost The Vacuum 1sec Of Time
"""

def seed_env(n: int, m: int) -> None:

	print("\n\n*** A Randomly Created Dirty/Clean {}*{} Environment ***".format(n, m))

	room = Environment(n, m)    # Creates Room of n-rows & m - columns

	room.build_room()   # Builds The Room With Randomly Selected Dirty Squares

	vacuum_agent = VacuumCleaner(room.get_rows(), room.get_cols())  # Creates The Vacuum Agent

	vacuum_agent.percepts(room)     # Feeds The Agent Perception Of The Room

	print("Number Of Tiles Cleaned : {}".format(vacuum_agent.get_tiles_cleaned()))

	distances = vacuum_agent.get_dirty_distances()

	if len(distances) > 0:

		print("\n*********Distance Traveled To The Next Dirty Room********\n")
		for distance in distances:

			print("A={}\nB={}\nDistance={}\n".format(distance.get("A"), distance.get("B"), distance.get("distance")))
	else:
		print("*** No Tiles Cleaned -> No Distance Calculated Between Dirty Tiles")

	print("\n***** TIME METRICS *****")
	start_time = float(vacuum_agent.get_time().get("start"))
	end_time = float(vacuum_agent.get_time().get("end"))
	time_diff = end_time - start_time
	# print("Start Time : {}".format(vacuum_agent.get_time().get("start")))
	# print("End Time   : {}".format(vacuum_agent.get_time().get("end")))
	print("Time Taken : {} seconds".format(time_diff))
	print("\n************************************************************************")

# seed_env(100, 100)

seed_env(1, 2)  # Demonstrates The Example From The Slides

# Increases The Number Of Rooms To Clean

seed_env(3, 3)

seed_env(3, 5)

# Your Own Environment!...


import cv2
import os
from PIL import Image
provinces = [
    "zh_cuan", "川",
    "zh_e", "鄂",
    "zh_gan", "赣",
    "zh_gan1", "甘",
    "zh_gui", "贵",
    "zh_gui1", "桂",
    "zh_hei", "黑",
    "zh_hu", "沪",
    "zh_ji", "冀",
    "zh_jin", "津",
    "zh_jing", "京",
    "zh_jl", "吉",
    "zh_liao", "辽",
    "zh_lu", "鲁",
    "zh_meng", "蒙",
    "zh_min", "闽",
    "zh_ning", "宁",
    "zh_qing", "靑",
    "zh_qiong", "琼",
    "zh_shan", "陕",
    "zh_su", "苏",
    "zh_sx", "晋",
    "zh_wan", "皖",
    "zh_xiang", "湘",
    "zh_xin", "新",
    "zh_yu", "豫",
    "zh_yu1", "渝",
    "zh_yue", "粤",
    "zh_yun", "云",
    "zh_zang", "藏",
    "zh_zhe", "浙"
]
PROVINCES = ("京", "闽", "粤", "苏", "沪", "浙", "川", "鄂", "赣", "甘", "贵", "桂", "黑", "冀", "津", "吉", "辽", "鲁", "蒙"
             , "宁", "青", "琼", "陕", "晋", "皖", "湘", "新", "豫", "渝", "云", "藏")
# 图像放大原来的两倍
# img = cv2.imread("/home/python/Desktop/opencv_test/opencv_test1/train_shouxie/Validation/#/__0_121440.png", 0)
# height, width = img.shape[:2]
# res = cv2.resize(img, (2 * width, 2 * height), interpolation=cv2.INTER_CUBIC)
# cv2.imshow("res", res)
# gray_img = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
# cv2.imshow("img", img)
# cv2.imshow("gray_img", gray_img)
# cv2.waitKey(0)
# cv2.destroyAllWindows()

# path = "/home/python/Desktop/opencv_test/opencv_demo/opencv_test1/chinese_test/jpg/car9zheF77777.jpg"
# img = cv2.imread(path)
# img = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
# img = cv2.resize(img, (32, 40), interpolation=cv2.INTER_AREA)
# a = path.split(".")
# new_path = a[0] + ".bmp"
# cv2.imwrite(path, img)
# image = Image.open(path)
# new_pic = image.convert("L")
# new_pic.save(new_path)
# # os.remove(path)
# print("图片{}修改格式成功".format(os.path.basename(path)))
# cv2.imshow("img", img)
# # os.remove("/home/python/Desktop/opencv_test/opencv_test1/test_pic/car1.jpg")
# cv2.waitKey(0)

# tensorflow格式图片
# for root, dirs, files in os.walk("/home/python/Desktop/charsChinese3"):
#     if not os.path.basename(root).startswith("zh_"):
#         continue
#     if os.path.basename(root) in ["charsChinese1"]:
#         continue
#     for j, filename in enumerate(files):
#         filepath = os.path.join(root, filename)
#         a = filename.split(".")
#         new_filename = a[0] + ".bmp"
#         new_filepath = os.path.join(root, new_filename)
#         digit_img = cv2.imread(filepath)
#         img = cv2.resize(digit_img, (32, 40), interpolation=cv2.INTER_AREA)
#         cv2.imwrite(new_filepath, img)
#         digit_img = Image.open(new_filepath)
#         new_pic = digit_img.convert("L")
#         new_pic.save(new_filepath)
#         os.remove(filepath)
#         print("改写完一张{}".format(filename))

img = cv2.imread("/home/python/Desktop/opencv_test/opencv_demo/opencv_test1/chinese_test/jpg/car_100ganH3B386.jpg")
img = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
img = cv2.resize(img, (20, 20), interpolation=cv2.INTER_AREA)
cv2.imwrite("/home/python/Desktop/opencv_test/opencv_demo/opencv_test1/chinese_test/jpg/car_100ganH3B386_1.jpg", img)


# Ввести несколько строк одинаковой длины, состоящих из символов '#' и '.'.
# Первый и последний символ каждой строки — '.', а первая и последняя строки состоят целиком из '-'.
# Известно (проверять не надо), что на получившемся поле изображены только прямоугольника, причём они не соприкасаются
# даже углами. Вывести количество этих прямоугольников.

count_of_rect = 0
tmp = set({})
indexes = set({})

input()
while 1:
    line = list(input())
    if line[0] == '-':
        count_of_rect += len(indexes)
        break

    tmp = indexes.copy()
    indexes.clear()
    is_rectangle = False
    start = 0

    for i, j in enumerate(line):
        if j == '#' and not is_rectangle:
            is_rectangle = True
            start = i
        elif is_rectangle and j != '#':
            is_rectangle = False
            indexes.add((start, i - 1))

    count_of_rect += len(tmp - indexes)

print(count_of_rect)


import xlrd
import pandas as pd
import matplotlib.pyplot as plt
from sklearn import linear_model
from sklearn.metrics import  mean_squared_error, r2_score
from mpl_toolkits.mplot3d import axes3d
import numpy as np
data=pd.read_excel('BI_Alumnos08.xlsx')
lista=pd.DataFrame()
alt=data['Altura']
ed=data['Edad']
lista['Altura']=alt
lista['Edad']=ed

XY=np.array(lista)
Z=data['Peso'].values
regLM=linear_model.LinearRegression()
regLM.fit(XY,Z)
z_pred=regLM.predict(XY)
print('Coeficientes de R',regLM.coef_)
print('error cuadrado medio: %.2f '% mean_squared_error(Z,z_pred))
print('puntaje de varianza: %.2f' % r2_score(Z,z_pred))
arreglo=np.array(data['Altura'])
arreglo2=np.array(data['Edad'])

for i in arreglo:
    for o in arreglo2:
        predPeso = regLM.predict([[i, o]])
        print("|  ",i," | ", o," |    ", int(predPeso),"   |")

arreglo3=np.array([int(predPeso)])

# Creamos la figura
fig = plt.figure()
# Agrrgamos un plano 3D
ax1 = fig.add_subplot(111,projection='3d')
ax1.scatter(arreglo3, arreglo2, arreglo, c='g', marker='o')
ax1.set_xlabel('Peso Predictivo')
ax1.set_ylabel('Edad')
ax1.set_zlabel('Altura')
ax1.set_title('Regresión Lineal con Múltiples Variables')
# Mostramos el gráfico
plt.show()


import numpy as np
import pandas as pd
import datetime
import pickle

def to_hour(x):
    if not pd.isnull(x):
        x = int(x)
        if x < 60:
            return 0
        else:
            return int(str(x)[:-2])

print("Load Month: 1")
df = pd.read_csv("../dataset/lighted/2016_01_light.csv")
for i in range(2, 13):
    print("Load Month:", i)
    df2 = pd.read_csv("../dataset/lighted/2016_{:02d}_light.csv".format(i))
    df = df.append(df2)

print("Selecting features")
df["FL_HOUR"] = df["CRS_DEP_TIME"].apply(to_hour)
df = df[["FL_DATE", "DAY_OF_WEEK", "UNIQUE_CARRIER", "ORIGIN_AIRPORT_ID", "DEP_DELAY", "FL_HOUR"]]

print("Saving ...")
df.to_csv("../dataset/merged/model3_dataset.csv", index=False)

print("Done")


from prettytable import PrettyTable
class Schedule:
    def __init__(self):
        # A lista 'dias' contém os dias da semana
        self.dias = ['Segunda', 'Terça', 'Quarta', 'Quinta', 'Sexta', 'Sábado', 'Domingo']

        # O dicionário 'tarefas' armazena as tarefas por dia da semana
        self.tarefas = {}

    def adicionar_tarefa(self, dia, descricao, prioridade):
        # Verifica se o dia informado está presente na lista 'dias'
        if dia not in self.dias:
            raise ValueError("Dia inválido")

        # Se o dia não está presente no dicionário 'tarefas', cria uma nova lista vazia
        if dia not in self.tarefas:
            self.tarefas[dia] = []

        # Adiciona a nova tarefa no dia correspondente do dicionário 'tarefas'
        self.tarefas[dia].append({'descricao': descricao, 'prioridade': prioridade})

    def imprimir_agenda(self):
        # Itera pelos dias da semana
        for dia in self.dias:
            # Imprime o dia da semana
            print(f"{dia}:")

            # Se o dia da semana tem tarefas, itera pelas tarefas ordenadas por prioridade
            if dia in self.tarefas:
                tarefas_dia = self.tarefas[dia]
                for tarefa in sorted(tarefas_dia, key=lambda x: x['prioridade']):
                    descricao = tarefa['descricao']
                    prioridade = tarefa['prioridade']
                    # Imprime a descrição e prioridade da tarefa
                    print(f"- {descricao} (prioridade {prioridade})")

            # Se o dia da semana não tem tarefas, imprime uma mensagem indicando que não há tarefas
            else:
                print("- Sem tarefas")


from panda3d.core import TextNode
from direct.gui.DirectButton import DirectButton
from direct.gui.OnscreenText import OnscreenText
from direct.task.Task import Task
from toontown.toonbase import ToontownGlobals
from toontown.toonbase import TTLocalizer
from toontown.parties import PartyUtils
from toontown.parties import PartyGlobals

class TeamActivityGui:
    COUNTDOWN_TASK_NAME = 'updateCountdownTask'
    timer = None
    statusText = None
    countdownText = None
    exitButton = None
    switchButton = None

    def __init__(self, activity):
        self.activity = activity

    def load(self):
        buttonModels = loader.loadModel('phase_3.5/models/gui/inventory_gui')
        upButton = buttonModels.find('**//InventoryButtonUp')
        downButton = buttonModels.find('**/InventoryButtonDown')
        rolloverButton = buttonModels.find('**/InventoryButtonRollover')
        self.exitButton = DirectButton(relief=None, text=TTLocalizer.PartyTeamActivityExitButton, text_fg=(1, 1, 0.65, 1), text_pos=(0, -0.15), text_scale=0.5, image=(upButton, downButton, rolloverButton), image_color=(1, 0, 0, 1), image_scale=(14.5, 1, 9), pos=(0, 0, 0.8), scale=0.15, command=self.handleExitButtonClick)
        self.exitButton.hide()
        if self.activity.toonsCanSwitchTeams():
            self.switchButton = DirectButton(relief=None, text=TTLocalizer.PartyTeamActivitySwitchTeamsButton, text_fg=(1, 1, 1, 1), text_pos=(0, 0.1), text_scale=0.5, image=(upButton, downButton, rolloverButton), image_color=(0, 1, 0, 1), image_scale=(15, 1, 15), pos=(0, 0, 0.5), scale=0.15, command=self.handleSwitchButtonClick)
            self.switchButton.hide()
        else:
            self.switchButton = None
        buttonModels.removeNode()
        self.countdownText = OnscreenText(text='', pos=(0.0, -0.2), scale=PartyGlobals.TeamActivityTextScale * 1.2, fg=(1.0, 1.0, 0.65, 1.0), align=TextNode.ACenter, font=ToontownGlobals.getSignFont(), mayChange=True)
        self.countdownText.hide()
        self.statusText = OnscreenText(text='', pos=(0.0, 0.0), scale=PartyGlobals.TeamActivityTextScale, fg=PartyGlobals.TeamActivityStatusColor, align=TextNode.ACenter, font=ToontownGlobals.getSignFont(), mayChange=True)
        self.statusText.hide()
        self.timer = PartyUtils.getNewToontownTimer()
        self.timer.hide()
        return

    def unload(self):
        self.hideWaitToStartCountdown()
        if self.exitButton is not None:
            self.exitButton.destroy()
            self.exitButton = None
        if self.switchButton is not None:
            self.switchButton.destroy()
            self.switchButton = None
        if self.countdownText is not None:
            self.countdownText.destroy()
            self.countdownText.removeNode()
            self.countdownText = None
        if self.statusText is not None:
            self.statusText.destroy()
            self.statusText.removeNode()
            self.statusText = None
        if self.timer is not None:
            self.timer.destroy()
            del self.timer
        return

    def showStatus(self, text):
        self.statusText.setText(text)
        self.statusText.show()

    def hideStatus(self):
        self.statusText.hide()

    def enableExitButton(self):
        self.exitButton.show()

    def disableExitButton(self):
        self.exitButton.hide()

    def handleExitButtonClick(self):
        self.disableExitButton()
        self.disableSwitchButton()
        self.activity.d_toonExitRequest()

    def enableSwitchButton(self):
        self.switchButton.show()

    def disableSwitchButton(self):
        if self.switchButton is not None:
            self.switchButton.hide()
        return

    def handleSwitchButtonClick(self):
        self.disableSwitchButton()
        self.disableExitButton()
        self.activity.d_toonSwitchTeamRequest()

    def showWaitToStartCountdown(self, duration, waitToStartTimestamp, almostDoneCallback = None):
        self._countdownAlmostDoneCallback = almostDoneCallback
        currentTime = globalClock.getRealTime()
        waitTimeElapsed = currentTime - waitToStartTimestamp
        if duration - waitTimeElapsed > 1.0:
            countdownTask = Task(self._updateCountdownTask)
            countdownTask.duration = duration - waitTimeElapsed
            self.countdownText.setText(str(int(countdownTask.duration)))
            self.countdownText.show()
            taskMgr.remove(TeamActivityGui.COUNTDOWN_TASK_NAME)
            taskMgr.add(countdownTask, TeamActivityGui.COUNTDOWN_TASK_NAME)

    def hideWaitToStartCountdown(self):
        taskMgr.remove(TeamActivityGui.COUNTDOWN_TASK_NAME)
        self._countdownAlmostDoneCallback = None
        if self.countdownText is not None:
            self.countdownText.hide()
        return

    def _updateCountdownTask(self, task):
        countdownTime = int(task.duration - task.time)
        seconds = str(countdownTime)
        if self.countdownText['text'] != seconds:
            self.countdownText['text'] = seconds
            if countdownTime == 3 and self._countdownAlmostDoneCallback is not None:
                self._countdownAlmostDoneCallback()
                self._countdownAlmostDoneCallback = None
        if task.time >= task.duration:
            return Task.done
        else:
            return Task.cont
        return

    def showTimer(self, duration):
        self.timer.setTime(duration)
        self.timer.countdown(duration, self._handleTimerExpired)
        self.timer.show()

    def hideTimer(self):
        self.timer.hide()
        self.timer.stop()

    def _handleTimerExpired(self):
        self.activity.handleGameTimerExpired()


from machine import I2C, Pin
from pca9685 import PCA9685
from motor import DCMotors
from ibus import IBus
import utime

PCA_ADDR = 0x41
SDA = Pin(0)
SCL = Pin(1)
#Frequency = 500
i2c=machine.I2C(0,sda=SDA, scl=SCL, freq=125000)
ibus_in = IBus(1)
I2C_PCA = I2C(id=0, sda=SDA, scl=SCL)
print("device found at address:", hex(I2C_PCA.scan()[0]))
# PCA = PCA9685(i2c=I2C_PCA,address=PCA_ADDR)
# PCA.freq(50)
Motor = DCMotors(i2c=I2C_PCA, address=PCA_ADDR, freq=1500)
I2C_PCA.writeto_mem(PCA_ADDR, 0x00, b'\x21')
I2C_PCA.writeto_mem(PCA_ADDR, 0x01, b'\x04')
I2C_PCA.writeto_mem(PCA_ADDR, 0xFE, b'\x79')

def map(x, i_min, i_max, o_min, o_max):
    return max(min(o_max, (x - i_min) * (o_max - o_min) // (i_max - i_min) + o_min), o_min)

def convert(X, Y, RL, RR):
    if X or Y:
        w_R = int(55*((-0.5*X)+(0.5*Y)))  # speed of LEFT WHEEL
        w_L = int(55*((-0.5*X)+(-0.5*Y)))  # speed of RIGHT WHEEL
        w_B = int(55*((1*X)+(0*Y)))  # speed of BACK WHEEL

        Motor.speed(0, map(w_L, -4000, 4000, -4095, 4095))  # wheel left
        Motor.speed(1, map(w_R, -4000, 4000, -4095, 4095))  # wheel right
        Motor.speed(2, map(w_B, -4000, 4000, -4095, 4095))  # wheel back
        print("WHEEL L: {}, WHEEL R: {}, WHEEL B: {}".format(w_L, w_R, w_B))
    elif RL==1:
        Motor.speed(0, -1000)  # wheel left
        Motor.speed(1, -1000)  # wheel right
        Motor.speed(2, -1000)  # wheel back
    elif RR==1:
        Motor.speed(0, 1000)  # wheel left
        Motor.speed(1, 1000)  # wheel right
        Motor.speed(2, 1000)  # wheel back
    else:
        Motor.brake(0)
        Motor.brake(1)
        Motor.brake(2)
while True:
    res = ibus_in.read()
    # if signal then display immediately
    if (res[0]):
        x_val = IBus.normalize(res[1])
        y_val = IBus.normalize(res[2])
        rl_val = IBus.normalize(res[5], type="dial")
        rr_val = IBus.normalize(res[8], type="dial")
        # print("Y-AXIS {} X-AXIS {}".format(rl_val,rr_val, end=""))
        convert(x_val, y_val, rl_val, rr_val)
    utime.sleep_ms(10)

Rabbit Robot/Flysky - Pico - PCA9685/Testing/Drive.py


import boto3
import datetime
from datetime import date
import time
import csv
from pprint import pprint
from botocore.exceptions import ClientError

client = boto3.client('iam')
users=client.list_users()['Users']

final_data_from_raw_filter = []
result = []
for user in users:
    # print(user)
    Username=user['UserName']
    AccessKeyList_Username=client.list_access_keys(UserName=Username)
    raw_data=AccessKeyList_Username['AccessKeyMetadata']
    final_data_from_raw_filter.append(raw_data)

#print(final_data_from_raw_filter)

for each_list in final_data_from_raw_filter:
    for each in each_list:
        result.append(each['UserName'])

#print(result)

with open("C:/Temp/iam_tagging.csv", newline='') as csv_file:
    reader = csv.DictReader(csv_file)
    for row in reader:
#        print(row)
        for each_user in users:
            if each_user['UserName'] == row['Iam_Username']:
#                print(row['Iam_Username'], row['E-Mail'], row['E-Mail_Value'], row['ServiceAccount'])
#                Tags_var={row['E-Mail']:row['E-Mail_Value'], row['ServiceAccount']:row['ServiceAccount_Value'], row['Owner']:row['Owner_Value']}
                response = client.tag_user(
                    UserName=row['Iam_Username'], Tags = [
                    {
                        'Key': row['E-Mail'],
                        "Value": row['E-Mail_Value']
                    },
                    {
                        'Key': row['ServiceAccount'],
                        "Value": row['ServiceAccount_Value']
                    },
                    {
                        'Key': row['Owner'],
                        "Value": row['Owner_Value']
                    },
                    {
                        'Key': row['Environment'],
                        "Value": row['Environment_Value']
                    },
                    {
                        'Key': row['EngineerContact'],
                        "Value": row['EngineerContact_Value']
                    },
                    {
                        'Key': row['EngineeringTeam'],
                        "Value": row['EngineeringTeam_Value']
                    }
                ]
                )
                print("Tags Applied for the user account:", row['Iam_Username'])


"""
Helper functions for the render scripts.
"""

import os
import shlex

def set_cpus(n_cpus):
    """Set environment variables for numba and numpy """
    n_cpus = str(n_cpus)
    os.environ["MKL_THREADING_LAYER"] = "GNU"
    os.environ["MKL_NUM_cpus"] = n_cpus
    os.environ["NUMEXPR_NUM_cpus"] = n_cpus
    os.environ["OMP_NUM_cpus"] = n_cpus
    os.environ["NUMBA_NUM_cpus"] = n_cpus

def parse_params(params):
    """Parse a comma-separated key-value list into a dictionary"""
    return dict(token.split("=") for token in shlex.split(params))


from abc import ABC, abstractmethod
from typing import Optional

import torch
import torchbiggraph.model
from torchbiggraph.operators import AbstractDynamicOperator, AbstractOperator
from torchbiggraph.plugin import PluginRegistry
from torchbiggraph.types import FloatTensorType, LongTensorType

class AbstractRegularizer(ABC):
    """
    Computes a weighted penalty for embeddings involved in score computations.
    """

    def __init__(self, weight):
        self.weight = weight

    @abstractmethod
    def forward_dynamic(
        self,
        src_pos: FloatTensorType,
        dst_pos: FloatTensorType,
        src_operators: Optional[FloatTensorType],
        dst_operators: Optional[FloatTensorType],
    ) -> FloatTensorType:
        pass

    @abstractmethod
    def forward(
        self,
        src_pos: FloatTensorType,
        dst_pos: FloatTensorType,
        src_operators: Optional[FloatTensorType],
        dst_operators: Optional[FloatTensorType],
    ) -> FloatTensorType:
        pass

REGULARIZERS = PluginRegistry[AbstractRegularizer]()

@REGULARIZERS.register_as("N3")
class N3Regularizer(AbstractRegularizer):
    """N3 regularizer described in https://arxiv.org/pdf/1806.07297.pdf"""

    def reg_embs(
        self, src_pos: FloatTensorType, dst_pos: FloatTensorType
    ) -> FloatTensorType:
        a, b, rank = torchbiggraph.model.match_shape(src_pos, -1, -1, -1)
        torchbiggraph.model.match_shape(dst_pos, a, b, rank)
        total = 0
        for x in (src_pos, dst_pos):
            total += torch.sum(self.modulus(x, rank // 2) ** 3)
        return total * self.weight

    def forward_dynamic(
        self,
        src_pos: FloatTensorType,
        dst_pos: FloatTensorType,
        operator: AbstractDynamicOperator,
        rel_idxs: LongTensorType,
    ) -> FloatTensorType:
        total = 0
        operator_params = operator.get_operator_params_for_reg(rel_idxs)
        if operator_params is not None:
            operator_params = operator_params.to(src_pos.device)
            total += torch.sum(operator_params**3)
        for x in (src_pos, dst_pos):
            total += torch.sum(operator.prepare_embs_for_reg(x) ** 3)
        total *= self.weight
        return total

    def forward(
        self,
        src_pos: FloatTensorType,
        dst_pos: FloatTensorType,
        operator: AbstractOperator,
    ) -> FloatTensorType:
        total = 0
        operator_params = operator.get_operator_params_for_reg()
        if operator_params is not None:
            operator_params = operator_params.to(src_pos.device)
            batch_size = len(src_pos)
            total += torch.sum(operator_params**3) * batch_size
        for x in (src_pos, dst_pos):
            total += torch.sum(operator.prepare_embs_for_reg(x) ** 3)
        total *= self.weight
        return total


from .plugin import CredentialPlugin

from django.conf import settings
from django.utils.translation import gettext_lazy as _
from delinea.secrets.vault import PasswordGrantAuthorizer, SecretsVault

dsv_inputs = {
    'fields': [
        {
            'id': 'tenant',
            'label': _('Tenant'),
            'help_text': _('The tenant e.g. "ex" when the URL is https://ex.secretsvaultcloud.com'),
            'type': 'string',
        },
        {
            'id': 'tld',
            'label': _('Top-level Domain (TLD)'),
            'help_text': _('The TLD of the tenant e.g. "com" when the URL is https://ex.secretsvaultcloud.com'),
            'choices': ['ca', 'com', 'com.au', 'eu'],
            'default': 'com',
        },
        {
            'id': 'client_id',
            'label': _('Client ID'),
            'type': 'string',
        },
        {
            'id': 'client_secret',
            'label': _('Client Secret'),
            'type': 'string',
            'secret': True,
        },
    ],
    'metadata': [
        {
            'id': 'path',
            'label': _('Secret Path'),
            'type': 'string',
            'help_text': _('The secret path e.g. /test/secret1'),
        },
        {
            'id': 'secret_field',
            'label': _('Secret Field'),
            'help_text': _('The field to extract from the secret'),
            'type': 'string',
        },
    ],
    'required': ['tenant', 'client_id', 'client_secret', 'path', 'secret_field'],
}

if settings.DEBUG:
    dsv_inputs['fields'].append(
        {
            'id': 'url_template',
            'label': _('URL template'),
            'type': 'string',
            'default': 'https://{}.secretsvaultcloud.{}',
        }
    )

def dsv_backend(**kwargs):
    tenant_name = kwargs['tenant']
    tenant_tld = kwargs.get('tld', 'com')
    tenant_url_template = kwargs.get('url_template', 'https://{}.secretsvaultcloud.{}')
    client_id = kwargs['client_id']
    client_secret = kwargs['client_secret']
    secret_path = kwargs['path']
    secret_field = kwargs['secret_field']

    tenant_url = tenant_url_template.format(tenant_name, tenant_tld.strip("."))

    authorizer = PasswordGrantAuthorizer(tenant_url, client_id, client_secret)
    dsv_secret = SecretsVault(tenant_url, authorizer).get_secret(secret_path)

    return dsv_secret['data'][secret_field]

dsv_plugin = CredentialPlugin(name='Thycotic DevOps Secrets Vault', inputs=dsv_inputs, backend=dsv_backend)


'''
给你一个字符串 s ，请你去除字符串中重复的字母，使得每个字母只出现一次。需保证 返回结果的字典序最小（要求不能打乱其他字符的相对位置）。
注意：该题与 1081 https://leetcode-cn.com/problems/smallest-subsequence-of-distinct-characters 相同
示例 1：
输入：s = "bcabc"
输出："abc"
示例 2：
输入：s = "cbacdcbc"
输出："acdb"
'''
import collections

class Solution(object):
    # 时间复杂度O(n)，空间复杂度O(n)
    def removeDuplicateLetters(self, s):
        if not s:
            return s
        stack = []
        count = collections.Counter(s)
        for c in s:
            if c not in stack:
                while stack and c < stack[-1] and count[stack[-1]] > 0:
                    stack.pop()
                stack.append(c)
            count[c] -= 1
        return ''.join(stack)

if __name__ == '__main__':
    u = Solution()
    print(u.removeDuplicateLetters("bcabc"))  # abc
    print(u.removeDuplicateLetters("cbacdcbc"))  # acdb

Hot100之外的高频面试题/316-去除重复字母.py