import pandas as pd

import openai
import json
import pathlib
import numpy as np
import Levenshtein as lev
from Levenshtein import ratio
from functools import partial

def get_edit_ratio(s1, s2):
    return lev.ratio(s1, s2)

def get_edit_distance(s1, s2):
    return lev.distance(s1, s2)

class OpenAI:

    def __init__(self, model="text-davinci-003", api_key=None, organization_id='org-7PVKrNOMnq1PvOkuHr1XJX88'):

        if api_key is None:
            path = pathlib.Path("openai_api_key.pkl")
            if path.exists():
                api_key = pd.read_pickle("openai_api_key.pkl")
            else:
                api_key = input("Please enter your OpenAI API key:")
                pd.to_pickle(api_key, "openai_api_key.pkl")

        self.model = model
        self.organization_id = organization_id
        self.api_key = api_key
        self.usage = {"prompt_tokens": 0,
                      "completion_tokens": 0,
                      "total_tokens": 0}

        self.chat_history = []

        openai.api_key = api_key
        openai.organization = organization_id
        self._models = None

    def update_usage(self, response):

        response = response['usage']

        self.usage["prompt_tokens"] += response["prompt_tokens"]
        self.usage["completion_tokens"] += response["completion_tokens"]
        self.usage["total_tokens"] += response["prompt_tokens"] + response["completion_tokens"]

    def chat(self, message, name=None, system=None, system_name=None, reset_chat=False, model=None, temperature=1,
             top_p=1, n=1, stream=False, stop=None, max_tokens=None, presence_penalty=0, frequency_penalty=0.0,
             logit_bias=None):

        '''

        :param name:
        :param system:
        :param system_name:
        :param reset_chat:
        :param temperature:
        :param top_p:
        :param n:
        :param stream:
        :param stop:
        :param max_tokens:
        :param presence_penalty:
        :param frequency_penalty:
        :param logit_bias:
        :return:
        '''

        if reset_chat:
            self.chat_history = []

        messages = []
        if system is not None:
            system = {'system': system}
            if system_name is not None:
                system['system_name'] = system_name
            messages.append(system)

        messages.extend(self.chat_history)

        message = {'role': 'user', 'content': message}
        if name is not None:
            message['name'] = name

        messages.append(message)

        kwargs = {}
        if logit_bias is not None:
            kwargs['logit_bias'] = logit_bias
        if max_tokens is not None:
            kwargs['max_tokens'] = max_tokens
        if stop is not None:
            kwargs['stop'] = stop

        if model is None:
            model = self.model

        response = openai.ChatCompletion.create(
            model=model,
            messages=messages,
            temperature=temperature,
            top_p=top_p,
            n=n,
            stream=stream,
            stop=stop,
            presence_penalty=presence_penalty,
            frequency_penalty=frequency_penalty,
            **kwargs
        )

        self.update_usage(response)
        response_message = response['choices'][0]['message']
        self.chat_history.append(response_message)

        return response

    @property
    def is_chat(self):
        chat_models = ['gpt-4', 'gpt-3.5-turbo']
        if any([m in self.model for m in chat_models]):
            return True
        return False

    def docstring(self, text, element_type, name=None, docstring_format=None, parent=None, parent_name=None,
                  parent_type=None, children=None, children_type=None, children_name=None, **kwargs):

        if docstring_format is None:
            docstring_format = f"in \"{docstring_format}\" format, "
        else:
            docstring_format = ""

        prompt = f"Task: write a full python docstring {docstring_format}for the following {element_type}\n\n" \
                 f"========================================================================\n\n" \
                 f"{text}\n\n" \
                 f"========================================================================\n\n"

        if parent is not None:
            prompt = f"{prompt}" \
                     f"where is parent {parent_type}: {parent_name}, has the following docstring\n\n" \
                     f"========================================================================\n\n" \
                     f"{parent}\n\n" \
                     f"========================================================================\n\n"

        if children is not None:
            for i, (c, cn, ct) in enumerate(zip(children, children_name, children_type)):
                prompt = f"{prompt}" \
                         f"and its #{i} child: {ct} named {cn}, has the following docstring\n\n" \
                         f"========================================================================\n\n" \
                         f"{c}\n\n" \
                         f"========================================================================\n\n"

        prompt = f"{prompt}" \
                 f"Response: \"\"\"\n{{docstring text here (do not add anything else)}}\n\"\"\""

        if self.is_chat:
            try:
                res = self.chat(prompt, **kwargs)
            except Exception as e:
                print(f"Error in response: {e}")
                try:
                    print(f"{name}: switching to gpt-4 model")
                    res = self.chat(prompt, model='gpt-4', **kwargs)
                except:
                    print(f"{name}: error in response")
                    res = None
        else:
            res = self.ask(prompt, **kwargs)

        # res = res.choices[0].text

        return res

    def file_list(self):
        return openai.File.list()

    def retrieve(self, model=None):
        if model is None:
            model = self.model
        return openai.Engine.retrieve(id=model)

    @property
    def models(self):
        if self._models is None:
            models = openai.Model.list()
            self._models = {m.id: m for m in models.data}
        return self._models

    def embedding(self, text, model=None):
        if model is None:
            model = self.model
        response = openai.Engine(model).embedding(input=text, model=model)
        embedding = np.array(response.data[1]['embedding'])
        return embedding

    def ask(self, question, max_tokens=1024, temperature=1, top_p=1, frequency_penalty=0.0,
            presence_penalty=0.0, stop=None, n=1, stream=False, logprobs=None, echo=False):
        """
        Ask a question to the model
        :param n:
        :param logprobs:
        :param stream:
        :param echo:
        :param question:
        :param max_tokens:
        :param temperature: 0.0 - 1.0
        :param top_p:
        :param frequency_penalty:
        :param presence_penalty:
        :param stop:
        :return:
        """
        response = openai.Completion.create(
          engine=self.model,
          prompt=question,
          temperature=temperature,
          max_tokens=max_tokens,
          top_p=top_p,
          frequency_penalty=frequency_penalty,
          presence_penalty=presence_penalty,
          stop=stop,
          n=n,
          stream=stream,
          logprobs=logprobs,
          echo=echo
        )

        self.update_usage(response)

        return response

    def summary(self, text, n_words=100, n_paragraphs=None, **kwargs):
        """
        Summarize a text
        :param text:  text to summarize
        :param n_words: number of words to summarize the text into
        :param n_paragraphs:   number of paragraphs to summarize the text into
        :param kwargs: additional arguments for the ask function
        :return: summary
        """
        if n_paragraphs is None:
            prompt = f"Task: summarize the following text into {n_words} words\nText: {text}\nResponse: \"\"\"\n{{text input here}}\n\"\"\""
        else:
            prompt = f"Task: summarize the following text into {n_paragraphs} paragraphs\nText: {text}\nResponse: \"\"\"\n{{text input here}}\n\"\"\""

        res = self.ask(prompt, **kwargs)
        return res.choices[0].text

    def question(self, text, question, **kwargs):
        """
        Answer a yes-no question
        :param text: text to answer the question from
        :param question: question to answer
        :param kwargs: additional arguments for the ask function
        :return: answer
        """
        prompt = f"Task: answer the following question\nText: {text}\nQuestion: {question}\nResponse: \"\"\"\n{{text input here}}\n\"\"\""

        res = self.ask(prompt, **kwargs)
        res = res.choices[0].text

        return res

    def yes_or_no(self, question, text=None, **kwargs):
        """
        Answer a yes or no question
        :param text: text to answer the question from
        :param question:  question to answer
        :param kwargs: additional arguments for the ask function
        :return: answer
        """

        if text is None:
            preface = ''
        else:
            preface = f"Text: {text}\n"

        prompt = f"{preface}Task: answer the following question with yes or no\nQuestion: {question}\nResponse: \"\"\"\n{{text input here}}\n\"\"\""

        res = self.ask(prompt, **kwargs)
        res = res.choices[0].text.lower().strip()
        res = res.split(" ")[0]

        i = pd.Series(['no', 'yes']).apply(partial(get_edit_ratio, s2=res)).idxmax()
        # print(res)
        return bool(i)

    def names_of_people(self, text, **kwargs):
        """
        Extract names of people from a text
        :param text: text to extract names from
        :param kwargs: additional arguments for the ask function
        :return: list of names
        """
        prompt = f"Task: extract names of people from the following text, return in a list of comma separated values\nText: {text}\nResponse: \"\"\"\n{{text input here}}\n\"\"\""

        res = self.ask(prompt, **kwargs)
        res = res.choices[0].text

        res = res.strip().split(",")

        return res

    def answer_email(self, input_email_thread, responder_from, receiver_to, **kwargs):
        """
        Answer a given email thread as an chosen entity
        :param input_email_thread_test: given email thread to answer to
        :param responder_from: chosen entity name which will answer the last mail from the thread
        :param receiver_to: chosen entity name which will receive the generated mail
        :param kwargs: additional arguments for the prompt
        :return: response mail
        """

        prompt = f"{input_email_thread}\n---generate message---\nFrom: {responder_from}To: {receiver_to}\n\n###\n\n"
        # prompt = f"Text: {text}\nTask: answer the following question with yes or no\nQuestion: {question}\nResponse: \"\"\"\n{{text input here}}\n\"\"\""

        res = self.ask(prompt, **kwargs)
        res = res.choices[0].text  # response email from model
        return res

    def classify(self, text, classes, **kwargs):
        """
        Classify a text
        :param text: text to classify
        :param classes: list of classes
        :param kwargs: additional arguments for the ask function
        :return: class
        """
        prompt = f"Task: classify the following text into one of the following classes\nText: {text}\nClasses: {classes}\nResponse: \"\"\"\n{{text input here}}\n\"\"\""

        res = self.ask(prompt, **kwargs)
        res = res.choices[0].text
        res = res.lower().strip()

        i = pd.Series(classes).str.lower().str.strip().apply(partial(get_edit_ratio, s2=res)).idxmax()

        return classes[i]

    def entities(self, text, humans=True, **kwargs):
        """
        Extract entities from a text
        :param humans:  if True, extract people, else extract all entities
        :param text: text to extract entities from
        :param kwargs: additional arguments for the ask function
        :return: entities
        """
        if humans:
            prompt = f"Task: extract people from the following text in a comma separated list\nText: {text}\nResponse: \"\"\"\n{{text input here}}\n\"\"\""
        else:
            prompt = f"Task: extract entities from the following text in a comma separated list\nText: {text}\nResponse: \"\"\"\n{{text input here}}\n\"\"\""

        res = self.ask(prompt, **kwargs)

        entities = res.choices[0].text.split(',')
        entities = [e.lower().strip() for e in entities]

        return entities

    def title(self, text, **kwargs):
        """
        Extract title from a text
        :param text: text to extract title from
        :param kwargs: additional arguments for the ask function
        :return: title
        """
        prompt = f"Task: extract title from the following text\nText: {text}\nResponse: \"\"\"\n{{text input here}}\n\"\"\""

        res = self.ask(prompt, **kwargs)
        res = res.choices[0].text

        return res

    def similar_keywords(self, text, keywords, **kwargs):
        """
        Find similar keywords to a list of keywords
        :param text: text to find similar keywords from
        :param keywords: list of keywords
        :param kwargs: additional arguments for the ask function
        :return: list of similar keywords
        """

        keywords = [e.lower().strip() for e in keywords]
        prompt = f"Keywords: {keywords}\nTask: find similar keywords in the following text\nText: {text}\n\nResponse: \"\"\"\n{{text input here}}\n\"\"\""

        res = self.ask(prompt, **kwargs)
        res = res.choices[0].text.split(',')
        res = [e.lower().strip() for e in res]

        res = list(set(res) - set(keywords))

        return res

    def is_keyword_found(self, text, keywords, **kwargs):
        """
        chek if one or more key words found in given text
        :param text: text to looks for
        :param keywords:  key words list
        :param kwargs: additional arguments for the ask function
        :return: yes if one of the keywords found else no
        """
        prompt = f"Text: {text}\nTask: answer with yes or no if Text contains one of the keywords \nKeywords: {keywords}\nResponse: \"\"\"\n{{text input here}}\n\"\"\""

        res = self.ask(prompt, **kwargs)
        res = res.choices[0].text.lower().strip().replace('"', "")

        i = pd.Series(['no', 'yes']).apply(partial(get_edit_ratio, s2=res)).idxmax()
        return bool(i)

    def get_similar_terms(self, keywords, **kwargs):
        """
        chek if one or more key words found in given text
        :param keywords:  key words list
        :param kwargs: additional arguments for the ask function
        :return: similar terms
        """
        prompt = f"keywords: {keywords}\nTask: return all semantic terms for given Keywords \nResponse: \"\"\"\n{{text input here}}\n\"\"\""

        res = self.ask(prompt, **kwargs)
        res = res.choices[0].text.lower().strip()
        return res

    #
    def build_dataset(self, data=None, question=None, answer=None, path=None) -> object:
        """
        Build a dataset for training a model
        :param data: dataframe with prompt and completion columns
        :param question: list of questions
        :param answer: list of answers
        :param path: path to save the dataset
        :return: path to the dataset
        """
        if data is None:
            data = pd.DataFrame(data={'prompt': question, 'completion': answer})

        records = data.to_dict(orient='records')

        if path is None:
            print('No path provided, using default path: dataset.jsonl')
            path = 'dataset.jsonl'

        # Open a file for writing
        with open(path, 'w') as outfile:
            # Write each data item to the file as a separate line
            for item in records:
                json.dump(item, outfile)
                outfile.write('\n')

        return path


class Solution:
    def maxEvents(self, e: List[List[int]]) -> int:
        a = [[] for i in range(100001)]
        q = []
        for x, y in e:
            a[x].append(y)
        z = 0
        for i in range(100001):
            for j in a[i]:
                heapq.heappush(q, j)
            while q and q[0] < i:
                heapq.heappop(q)
            if q:
                z += 1
                heapq.heappop(q)
        return z


#!/usr/bin/env python

from __future__ import print_function
import sys
import os.path
import collections
import matplotlib
matplotlib.use('Agg') # don't try to use $DISPLAY
import matplotlib.pyplot as plt
from matplotlib.backends.backend_pdf import PdfPages
import matplotlib.gridspec as gridspec
import numpy as np

def parse_input(args):
    ylists = collections.defaultdict(list)
    with open(args.infile) as f:
        while args.skip > 0:
            next(f)
            args.skip -= 1
        for line in f:
            fields = line.split()
            if len(fields) < max(args.horiz_column, args.vert_column):
                continue
            x = float(fields[args.horiz_column-1])
            y = float(fields[args.vert_column-1])
            if (np.isnan(x) or np.isinf(x)) or (np.isnan(y) or np.isinf(y)):
                continue
            ylists[x].append(y)

    return sorted(ylists.keys()), ylists

def parse_args():
    import argparse
    parser = argparse.ArgumentParser(description="plot histogram for 1 column of input file")
    parser.add_argument("-x", "--horiz-column", type=int, required=True, help="1-based column to plot on horizontal axis")
    parser.add_argument("-y", "--vert-column", type=int, required=True, help="1-based column to plot on vertical axis")
    parser.add_argument("-s", "--skip", type=int, default=0, help="number of input lines to skip [%(default)s]")
    parser.add_argument("-w", "--wide", action="store_true", default=False, help="plot widescreen ratio (16x9) [%(default)s]")
    parser.add_argument("--logx", action="store_true", default=False, help="plot x-axis on log scale [%(default)s]")
    parser.add_argument("--logy", action="store_true", default=False, help="plot y-axis on log scale [%(default)s]")
    parser.add_argument("--title", type=str, help="plot title")
    parser.add_argument("--xlabel", type=str, help="x axis label")
    parser.add_argument("--ylabel", type=str, help="y axis label")
    parser.add_argument("-o", "--opdf", type=str, default="out.pdf", help="output filename [%(default)s]")
    parser.add_argument("infile", help="input file")
    args = parser.parse_args()

    return args

if __name__ == "__main__":

    args = parse_args()
    x, y = parse_input(args)

    pdf = PdfPages(args.opdf)
    if args.wide:
        fig_w, fig_h = plt.figaspect(9.0/16.0)
    else:
        fig_w, fig_h = plt.figaspect(3.0/4.0)
    fig1 = plt.figure(figsize=(fig_w, fig_h))
    gs1 = gridspec.GridSpec(1, 1)
    ax1 = fig1.add_subplot(gs1[0])

    if not args.title:
        args.title = os.path.basename(args.infile)

    if not args.ylabel:
        if args.logy:
            args.ylabel = "log(column {})".format(args.vert_column)
        else:
            args.ylabel = "column {}".format(args.vert_column)

    if not args.xlabel:
        if args.horiz_column > 0:
            if args.logx:
                args.xlabel = "log(column {})".format(args.horiz_column)
            else:
                args.xlabel = "column {}".format(args.horiz_column)
        else:
            if args.logx:
                args.xlabel = "log(line number)"
            else:
                args.xlabel = "line number"

    ax1.violinplot([y[i] for i in x], x, points=60, widths=0.7, showmedians=True, bw_method=0.5)

    ax1.set_title(args.title)
    ax1.set_xlabel(args.xlabel)
    ax1.set_ylabel(args.ylabel)

    if args.logx:
        plt.xscale('log', nonposy='clip')
    if args.logy:
        plt.yscale('log', nonposy='clip')

    plt.tight_layout()
    pdf.savefig()
    pdf.close()


import numpy as np
from scipy import stats

import lib_detect as lib

def calculate_fdr_threshold_vector(chrom, cfg, **kwargs):
    '''
    Compute vector of FDR-controlling detection thresholds by region.

    Parameters
    ----------
        - chrom : int
            Index of chromosome to analyze
        - cfg : dictionary
            Dictionary of configuration information, formatted as documented
            elsewhere.
        - **kwargs
            Optional arguments to avoid reloading data

    Returns
    -------
        Dictionary containing:
        - thresh_vec : ndarray
            Vector of detection thresholds by region
        - region_ids : integer ndarray
            Vector of region identifiers
        - alpha : float
            FDR
    '''
    # Extract commonly-used data from cfg
    alpha       = cfg['detection_params']['alpha']
    n_proc      = cfg['detection_params']['n_proc']
    maxima      = cfg['detection_params']['compute_maxima_only']
    method      = cfg['detection_params']['method_fdr']
    verbose     = cfg['detection_params']['verbose']

    # Load null coefficients
    if 'null' in kwargs.keys():
        null = kwargs['null']
    else:
        null_path = cfg['estimation_output']['null_coef_pattern']
        null_path = null_path.format(**cfg).strip()
        null_path = null_path % chrom
        null = np.loadtxt(null_path)

    # Load nonnull coefficients
    if 'nonnull' in kwargs.keys():
        nonnull = kwargs['nonnull']
    else:
        nonnull_path = cfg['estimation_output']['coef_pattern']
        nonnull_path = nonnull_path.format(**cfg).strip()
        nonnull_path = nonnull_path % chrom
        nonnull = np.loadtxt(nonnull_path)

    # Load region type information
    if 'region_types' in kwargs.keys() and 'region_ids' in kwargs.keys():
        region_types = kwargs['region_types']
        region_ids = kwargs['region_ids']
    else:
        with open(cfg['data']['regions_path'], 'rb') as f:
            lines_read = 0
            for line in f:
                lines_read += 1
                if lines_read == chrom:
                    region_types = np.fromstring(line.strip(), sep=' ',
                                                 dtype=int)
                    break

        region_types = region_types[:null.size]
        region_types -= region_types.min()
        region_ids = np.unique(region_types)

    if 'region_list' in kwargs.keys() and 'region_lengths' in kwargs.keys():
        region_list = kwargs['region_list']
        region_lengths = kwargs['region_lengths']
    else:
        region_list = []
        region_lengths = []
        for id in region_ids:
            region_list.append( np.where(region_types==id)[0] )
            region_lengths.append( np.sum(region_types==id) )

        region_lengths = np.array(region_lengths)

    # Calculate threshold for given FDR
    if method.lower() == 'bh':
        thresh_vec = lib.get_fdr_threshold_bh(null=null, nonnull=nonnull,
                                              region_list=region_list,
                                              alpha=alpha, maxima=maxima,
                                              n_proc=n_proc, verbose=verbose)
    elif method.lower() == 'direct':
        thresh_vec = lib.get_fdr_threshold_estimate(null, nonnull, region_list,
                                                    alpha, maxima=maxima,
                                                    n_proc=n_proc,
                                                    verbose=verbose)
    else:
        thresh_vec = lib.get_fdr_threshold(null, nonnull, region_list, alpha,
                                           maxima=maxima)

    result = {'thresh_vec' : thresh_vec,
              'region_ids' : region_ids,
              'alpha' : alpha}

    return result

def write_fdr_thresholds(result, cfg, chrom=1):
    '''
    Output FDR threshold vector to appropriate file.

    Parameters
    ----------
        - result : ndarray
            Dictionary as returned by calculate_fdr_threshold_vector.
        - cfg : dictionary
            Dictionary containing at least detection_output section wth
            appropriate parameters.

    Returns
    -------
        None
    '''
    # Output detection threshold by region to appropriate path
    out_path = cfg['detection_output']['fdr_pattern'].format(**cfg).strip()
    out_path = out_path % chrom

    n_regions = result['region_ids'].size

    np.savetxt(out_path, np.vstack((result['alpha']*np.ones(n_regions),
                                    result['region_ids'],
                                    result['thresh_vec'])).T,
               fmt="%.15g")

def detect(cfg, chrom=1):
    '''
    Coordinate detection procedure.

    Parameters
    ----------
        - cfg : dictionary
            Dictionary of parameters containing at least those relevant for
            detection.
        - chrom : int
            Index of chromosome to analyze
    '''

    # Load nonnull coefficients
    coef_path = cfg['estimation_output']['coef_pattern']
    coef_path = coef_path.format(**cfg).strip()
    coef_path = coef_path % chrom
    coef = np.loadtxt(coef_path)

    # Load region_types
    with open(cfg['data']['regions_path'], 'rb') as f:
        lines_read = 0
        for line in f:
            lines_read += 1
            if lines_read == chrom:
                region_types = np.fromstring(line.strip(), sep=' ',
                                             dtype=int)
                break

    region_types = region_types[:coef.size]
    region_types -= region_types.min()
    region_ids = np.unique(region_types)

    # Obtain FDR-based detection thresholds
    results_fdr = calculate_fdr_threshold_vector(chrom=chrom, cfg=cfg,
                                                 nonnull=coef,
                                                 region_types=region_types,
                                                 region_ids=region_ids)

    # Output FDR thresholds
    write_fdr_thresholds(results_fdr, cfg, chrom=chrom)

    if cfg['detection_params']['use_bayes_se']:
        # Load standard errors
        se_path = cfg['estimation_output']['se_pattern']
        se_path = se_path.format(**cfg).strip()
        se_path = se_path % chrom
        se = np.loadtxt(se_path)

        # Load parameters
        param_path = cfg['estimation_output']['param_pattern']
        param_path = param_path.format(**cfg).strip()
        param_path = param_path % chrom
        mu, sigmasq = np.loadtxt(param_path, unpack=True, skiprows=1)[1:]

        mu = np.ravel(mu)
        sigmasq = np.ravel(sigmasq)

        # Compute n_se for detection
        n_se = -stats.norm.ppf(cfg['detection_params']['alpha'])

        # Detect positions based upon both FDR and Bayes criteria
        detected = np.where((coef > results_fdr['thresh_vec'][region_types]) &
                            (np.log(coef) - n_se*se > mu[region_types]))[0]
    else:
        detected = np.arange(coef.size, dtype=np.integer)

    # Restrict to local maxima if request
    if cfg['detection_params']['detect_maxima_only']:
        detected = np.intersect1d(lib.find_maxima(coef), detected)

    # Output detected positions
    detected_path = cfg['detection_output']['detected_pattern'].format(**cfg)
    detected_path = detected_path.strip() % chrom
    np.savetxt(detected_path, detected, fmt='%d')


# /usr/bin/python
from API import *

class Pokemon(API):
    def __init__(self):
        self._categories = {
            "pokemons": {
                "method": self._get_pokemon,
                "questionTypes": {
                    "height": self._get_pokemon_height,
                    "weight": self._get_pokemon_weight,
                    "number": self._get_pokemon_number
                }
            }
        }
        API.__init__(self)

    def _get_pokemon(self):
        poke_id = random.randint(1, 251)  # first and second generations
        species = get_dict_from_request(f'https://pokeapi.co/api/v2/pokemon-species/{poke_id}')
        stats = get_dict_from_request(f'https://pokeapi.co/api/v2/pokemon/{poke_id}')
        if species is None or stats is None:
            return None
        self._success = True
        for lang in species["names"]:
            if lang["language"]["name"] == "de":
                name = lang["name"]
        self._data = {
            "no": poke_id, "name": name, "height": stats["height"] / 10, "weight": stats["weight"] / 10
        }

    def _get_pokemon_height(self):
        self._question = f'Wie viel Meter (auf eine Nachkommastelle genau) ist das Pokémon {self._data["name"]} groß?'
        ans = self._data["height"]
        self._answer = {
            "value": ans, "fmt": "\d+([,\.]\d)?",
            "text": f'{germanize_number(ans)} m ist {self._data["name"]} groß.',
            "reaction": "{} {} um {} m von dem richtigen Wert ab."
        }

    def _get_pokemon_weight(self):
        self._question = f'Wie viel Kilogramm (auf eine Nachkommastelle genau) wiegt das Pokémon {self._data["name"]}?'
        ans = self._data["weight"]
        self._answer = {
            "value": ans, "fmt": "\d+([,\.]\d)?",
            "text": f'{germanize_number(ans)} kg wiegt {self._data["name"]}.',
            "reaction": "{} {} um {} kg von dem richtigen Wert ab."
        }

    def _get_pokemon_number(self):
        self._question = f'Welche Nummer hat das Pokémon {self._data["name"]} im NationalDex?'
        ans = self._data["no"]
        self._answer = {
            "value": ans, "fmt": "\d+",
            "text": f'{ans} ist die Nummer von {self._data["name"]}.',
            "reaction": "{} {} um {} von der richtigen Nummer ab."
        }


import random
import matplotlib.pyplot as plt
import numpy as np

def diagrama_barras_calificaciones(notas,color,alumno):
    """
    Dibujar la grafica de barras con las calificaciones
    """
    plt.bar(notas.keys(),notas.values(),color = color)
    plt.title("Calificaciones de " + alumno)

calificaciones = {
    "Programacion": 3,
    "Español": 6.5,
    "Calculo": 4,
    "Historia": 8,
    "Biologia": 10,
    "Ingles": 3
}

alumno = input("Nombre del alumno: ")
diagrama_barras_calificaciones(calificaciones, "red", alumno)

plt.show()


#!/usr/bin/env python3
#
#   This file is part of MiniFluxDiv.

#   MiniFluxDiv is free software: you can redistribute it and/or modify
#   it under the terms of the GNU General Public License as published by
#   the Free Software Foundation, either version 3 of the License, or
#   any later version.

#   MiniFluxDiv is distributed in the hope that it will be useful,
#   but WITHOUT ANY WARRANTY; without even the implied warranty of
#   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
#   GNU General Public License for more details.
#
#   You should have received a copy of the GNU General Public License
#   along with MiniFluxDiv. If not, see <http://www.gnu.org/licenses/>.
#

import os
import sys
import math
import subprocess as sub
import traceback as tb
import argparse as ap

DEBUG = False #True

def ncpus():
    import multiprocessing
    return multiprocessing.cpu_count()

def run(args, vars={}, stream=None):
    output = ''

    for key in vars:
        os.environ[key] = vars[key]

    try:
        data = sub.check_output(args, env=os.environ, stderr=sub.STDOUT)
        output = data.decode()
    except Exception as e:
        eprint(str(e))

    if stream is not None:
        stream.write(output)

    return output

def eprint(*args, **kwargs):
    print(*args, file=sys.stderr, **kwargs)

def parseArgs():
    parser = ap.ArgumentParser('runMiniFluxDiv', description='Execute miniFluxDiv test cases.')
    parser.add_argument('-e', '--exec', default='', help='Executable to run.')
    parser.add_argument('-l', '--legend', default='', help='Chart legend for output table.')
    parser.add_argument('-b', '--boxes', default='32', help='List of box sizes.')
    parser.add_argument('-c', '--cells', default='128', help='List of cell sizes.')
    parser.add_argument('-p', '--threads', default='1', help='List of thread counts.')
    parser.add_argument('-n', '--runs', default='3', help='Number of runs.')
    parser.add_argument('-d', '--delim', default=',', help='List delimiter.')
    parser.add_argument('-v', '--verify', default='0', help='Perform verification.')

    return parser.parse_known_args()

def main():
    if len(sys.argv) < 2:
        sys.argv.append('-h')

    (args, unknowns) = parseArgs()

    executable = args.exec
    delim = args.delim

    boxStr = args.boxes.split(delim)
    boxList = [int(val) for val in boxStr]

    cellStr = args.cells.split(delim)
    cellList = [int(val) for val in cellStr]

    maxThreads = ncpus()
    thrStr = args.threads.split(delim)

    thrList = []
    for val in thrStr:
        val = int(val)
        if val > 0 and val <= maxThreads:
            thrList.append(val)

    nRuns = int(args.runs)
    doVerify = int(args.verify) > 0

    program = executable.split('/')[-1]
    vars = {'OMP_SCHEDULE': 'static'}

    legend = args.legend
    if len(legend) < 1:
        legend = program.replace('miniFluxdiv-', '')

    header = 'Program,Legend,nBoxes,nCells,nThreads,'
    for i in range(nRuns):
        header += 'Time' + str(i) + ','
    header += 'MeanTime,MedianTime,StdevTime'

    print(header)

    nPairs = len(boxList)
    for threads in thrList:
        for i in range(nPairs):
            nBoxes = boxList[i]
            nCells = cellList[i]

            args = [executable, '-B', '%d' % nBoxes, '-C', '%d' % nCells, '-p', '%d' % threads]
            if doVerify and i == 0:     # Only verify first run...
                args.append('-v')

            cmd = ' '.join(args)

            times = []
            tsum = 0.0
            tsumsq = 0.0

            for i in range(nRuns):
                output = run(args, vars)
                isValid = len(output) > 0

                if isValid:
                    lines = output.rstrip().split("\n")
                    line = lines[-1].rstrip(',')
                    items = line.split(',')

                    dct = {}
                    for item in items:
                        (key, val) = item.split(':')
                        dct[key] = val

                    if doVerify and 'verification' in dct and 'FAIL' in dct['verification']:
                        print("VERIFICATION FAILED: on '%s' with '%s'" % (cmd, lines[0]))
                        isValid = False
                        break
                    else:
                        rtime = float(dct['RunTime'])
                        times.append(rtime)
                        tsum += rtime
                        tsumsq += (rtime * rtime)

            if isValid:
                tList = ['%lf' % time for time in times]

                # Calc mean & stdev
                fRuns = float(nRuns)
                mean = tsum / fRuns
                stdev = math.sqrt((tsumsq - (tsum * tsum) / fRuns) / float(nRuns - 1))

                # Calc median
                times = sorted(times)
                mid = int(nRuns / 2)
                if nRuns % 2 == 1:
                    median = times[mid]
                else:
                    median = (times[mid] + times[mid + 1]) / 2.0

                line = '%s,%s,%d,%d,%d,%s,%lf,%lf,%lf' % (program, legend, nBoxes, nCells, threads, ','.join(tList), mean, median, stdev)
                print(line)
                sys.stdout.flush()

if __name__ == '__main__':
    try:
        main()

    except KeyboardInterrupt as e: # Ctrl-C
        print("Closing gracefully on keyboard interrupt...")

    except Exception as e:
        print('Unexpected Exception: ' + str(e))
        tb.print_exc()
        os._exit(1)


l = (input("ingrese varios elementos separados por una ',' : "))
li = list(l.split(","))
for i in range(len(li)):
    if type(li[i]) == str:
        li[i] = int(li[i])
li.sort()
mayor = max(li)
menor = min(li)
print(f"La lista contiene los siguientes numeros: {li}")
print(f"El numero mas grande es {mayor}")
print(f"El numero mas chico es {menor}")


from __future__ import print_function
from dircache import listdir
import re
import fnmatch
import os.path

# These fnmatch expressions are used by default to prune the directory tree
# while doing the recursive traversal in the glob_impl method of glob function.
prune_dirs = '.git .bzr .hg .svn _MTN _darcs CVS SCCS '

# These fnmatch expressions are used by default to exclude files and dirs
# while doing the recursive traversal in the glob_impl method of glob function.
##exclude_pats = prune_pats + '*~ #*# .#* %*% ._* .gitignore .cvsignore vssver.scc .DS_Store'.split()

# These ant_glob expressions are used by default to exclude files and dirs and also prune the directory tree
# while doing the recursive traversal in the glob_impl method of glob function.
default_excludes = '''
**/*~
**/#*#
**/.#*
**/%*%
**/._*
**/CVS
**/CVS/**
**/.cvsignore
**/SCCS
**/SCCS/**
**/vssver.scc
**/.svn
**/.svn/**
**/.git
**/.git/**
**/.gitignore
**/.bzr
**/.bzr/**
**/.hg
**/.hg/**
**/_MTN
**/_MTN/**
**/_darcs
**/_darcs/**
**/.DS_Store '''

DIR = 1
FILE = 2
DIR_LINK = 4
FILE_LINK = 8
LINKS = DIR_LINK | FILE_LINK
ALL_NO_LINK = DIR | FILE
ALL = DIR | FILE | LINKS

_ANT_RE = re.compile(r'(/\*\*/)|(\*\*/)|(/\*\*)|(\*)|(/)|([^\*/]*)')

def ant_pattern_to_re(ant_pattern):
    """Generates a regular expression from the ant pattern.
    Matching convention:
    **/a: match 'a', 'dir/a', 'dir1/dir2/a'
    a/**/b: match 'a/b', 'a/c/b', 'a/d/c/b'
    *.py: match 'script.py' but not 'a/script.py'
    """
    rex = ['^']
    next_pos = 0
    sep_rex = r'(?:/|%s)' % re.escape(os.path.sep)
##    print 'Converting', ant_pattern
    for match in _ANT_RE.finditer(ant_pattern):
##        print 'Matched', match.group()
##        print match.start(0), next_pos
        if match.start(0) != next_pos:
            raise ValueError("Invalid ant pattern")
        if match.group(1): # /**/
            rex.append(sep_rex + '(?:.*%s)?' % sep_rex)
        elif match.group(2): # **/
            rex.append('(?:.*%s)?' % sep_rex)
        elif match.group(3): # /**
            rex.append(sep_rex + '.*')
        elif match.group(4): # *
            rex.append('[^/%s]*' % re.escape(os.path.sep))
        elif match.group(5): # /
            rex.append(sep_rex)
        else: # somepath
            rex.append(re.escape(match.group(6)))
        next_pos = match.end()
    rex.append('$')
    return re.compile(''.join(rex))

def _as_list(l):
    if isinstance(l, basestring):
        return l.split()
    return l

def glob(dir_path,
         includes = '**/*',
         excludes = default_excludes,
         entry_type = FILE,
         prune_dirs = prune_dirs,
         max_depth = 25):
    include_filter = [ant_pattern_to_re(p) for p in _as_list(includes)]
    exclude_filter = [ant_pattern_to_re(p) for p in _as_list(excludes)]
    prune_dirs = [p.replace('/',os.path.sep) for p in _as_list(prune_dirs)]
    dir_path = dir_path.replace('/',os.path.sep)
    entry_type_filter = entry_type

    def is_pruned_dir(dir_name):
        for pattern in prune_dirs:
            if fnmatch.fnmatch(dir_name, pattern):
                return True
        return False

    def apply_filter(full_path, filter_rexs):
        """Return True if at least one of the filter regular expression match full_path."""
        for rex in filter_rexs:
            if rex.match(full_path):
                return True
        return False

    def glob_impl(root_dir_path):
        child_dirs = [root_dir_path]
        while child_dirs:
            dir_path = child_dirs.pop()
            for entry in listdir(dir_path):
                full_path = os.path.join(dir_path, entry)
##                print 'Testing:', full_path,
                is_dir = os.path.isdir(full_path)
                if is_dir and not is_pruned_dir(entry): # explore child directory ?
##                    print '===> marked for recursion',
                    child_dirs.append(full_path)
                included = apply_filter(full_path, include_filter)
                rejected = apply_filter(full_path, exclude_filter)
                if not included or rejected: # do not include entry ?
##                    print '=> not included or rejected'
                    continue
                link = os.path.islink(full_path)
                is_file = os.path.isfile(full_path)
                if not is_file and not is_dir:
##                    print '=> unknown entry type'
                    continue
                if link:
                    entry_type = is_file and FILE_LINK or DIR_LINK
                else:
                    entry_type = is_file and FILE or DIR
##                print '=> type: %d' % entry_type,
                if (entry_type & entry_type_filter) != 0:
##                    print ' => KEEP'
                    yield os.path.join(dir_path, entry)
##                else:
##                    print ' => TYPE REJECTED'
    return list(glob_impl(dir_path))

if __name__ == "__main__":
    import unittest

    class AntPatternToRETest(unittest.TestCase):
##        def test_conversion(self):
##            self.assertEqual('^somepath$', ant_pattern_to_re('somepath').pattern)

        def test_matching(self):
            test_cases = [ ('path',
                             ['path'],
                             ['somepath', 'pathsuffix', '/path', '/path']),
                           ('*.py',
                             ['source.py', 'source.ext.py', '.py'],
                             ['path/source.py', '/.py', 'dir.py/z', 'z.pyc', 'z.c']),
                           ('**/path',
                             ['path', '/path', '/a/path', 'c:/a/path', '/a/b/path', '//a/path', '/a/path/b/path'],
                             ['path/', 'a/path/b', 'dir.py/z', 'somepath', 'pathsuffix', 'a/somepath']),
                           ('path/**',
                             ['path/a', 'path/path/a', 'path//'],
                             ['path', 'somepath/a', 'a/path', 'a/path/a', 'pathsuffix/a']),
                           ('/**/path',
                             ['/path', '/a/path', '/a/b/path/path', '/path/path'],
                             ['path', 'path/', 'a/path', '/pathsuffix', '/somepath']),
                           ('a/b',
                             ['a/b'],
                             ['somea/b', 'a/bsuffix', 'a/b/c']),
                           ('**/*.py',
                             ['script.py', 'src/script.py', 'a/b/script.py', '/a/b/script.py'],
                             ['script.pyc', 'script.pyo', 'a.py/b']),
                           ('src/**/*.py',
                             ['src/a.py', 'src/dir/a.py'],
                             ['a/src/a.py', '/src/a.py']),
                           ]
            for ant_pattern, accepted_matches, rejected_matches in list(test_cases):
                def local_path(paths):
                    return [ p.replace('/',os.path.sep) for p in paths ]
                test_cases.append((ant_pattern, local_path(accepted_matches), local_path(rejected_matches)))
            for ant_pattern, accepted_matches, rejected_matches in test_cases:
                rex = ant_pattern_to_re(ant_pattern)
                print('ant_pattern:', ant_pattern, ' => ', rex.pattern)
                for accepted_match in accepted_matches:
                    print('Accepted?:', accepted_match)
                    self.assertTrue(rex.match(accepted_match) is not None)
                for rejected_match in rejected_matches:
                    print('Rejected?:', rejected_match)
                    self.assertTrue(rex.match(rejected_match) is None)

    unittest.main()


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

# =============================================================================
# Imports
# =============================================================================

import pandas as pd

from positions.parser import GameFile
from adjudicator.variant import Variant
from lib.errors import OrderInputError

# =============================================================================
# Class
# =============================================================================

class PositionsDB():
    """ An instance stores and loads information about positions that has
    occurred in a game, into a pandas dataframe.

    Parameters are expected to be added, as this class is used in the
    future.

    """

    def __init__(self, variant, folder, host, cols=None):
        """ Constructor.

        """
        self.variant = Variant(variant)
        self.variant.load()
        self.folder = folder
        self.host = host
        self.powers = [power.name for power in self.variant.powers]
        self.data = pd.read_csv(f'scraping/data/{folder}.csv', index_col = 'GameID')
        self.__clean_data__(cols)

    def __clean_data__(self, cols):
        """ Cleans the data loaded from the scraping-folder, removing
        unnecessary columns and discarded games. Also adds the 'Loaded'
        column.

        """
        self.data = self.data[~self.data.Discarded]
        if cols is None:
            ENDINGS = ['S1', 'RS1', 'A1', 'RA1', 'W1', 'User']
            cols = [power + end for power in self.powers for end in ENDINGS]
            cols += ['Page', 'Manual', 'Discarded']
        self.data = self.data.drop(cols, axis=1)
        self.data['Loaded'] = False

    def load_centers(self, bound=None):
        """ Loads games, plays them through until the end, and records what
        power owned what center in the dataframe.

        """
        j = 1
        for k in self.data.index[~self.data.Loaded]:
            try:
                game = GameFile(self.variant.name, self.folder, self.host, str(k))
                try:
                    game.run()
                    centers = game.game.current_position()['centers']
                    for key in centers:
                        self.data.loc[k, centers[key]] = key
                    self.data.loc[k, 'Loaded'] = True
                except (OrderInputError, ValueError):
                    print(f'Skipping game {k} due to an adjudication error.')
                if bound is not None:
                    if j >= bound:
                        break
                j += 1
            except FileNotFoundError:
                pass

    def save_csv(self):
        """ Saves the dataframe as a csv file in the sub data folder.

        """
        self.data.to_csv(f'positions/data/{self.folder}.csv')

    def load_csv(self):
        """ Loads the dataframe from a csv file int he sub data folder.
        This overwrites any changes stored in the current dataframe.

        """
        self.data = pd.read_csv(f'positions/data/{self.folder}.csv', index_col = 'GameID')


from django.template import Library
from django.urls import resolve, reverse, translate_url
from django.utils.translation import activate, get_language

register = Library()

@register.simple_tag(takes_context=True)
def change_lang(context, lang=None, *args, **kwargs):
    """
    Get active page's url by a specified language
    Usage: {% change_lang 'en' %}
    """
    path = context['request'].path
    url_parts = resolve(path)

    url = path
    cur_language = get_language()
    try:
        activate(lang)
        url = reverse(url_parts.view_name, kwargs=url_parts.kwargs)
    finally:
        activate(cur_language)
    return "%s" % url

@register.simple_tag(takes_context=True)
def set_global_context(context, key, value):
    """
    Sets a value to the global template context, so it can
    be accessible across blocks.

    Note that the block where the global context variable is set must appear
    before the other blocks using the variable IN THE BASE TEMPLATE.  The order
    of the blocks in the extending template is not important.

    Usage::
        {% extends 'base.html' %}

        {% block first %}
            {% set_global_context 'foo' 'bar' %}
        {% endblock %}

        {% block second %}
            {{ foo }}
        {% endblock %}
    """
    context.dicts[0][key] = value
    return ''


#Problem Link :- https://leetcode.com/submissions/detail/378915676/

"""You are given an integer array nums sorted in ascending order, and an integer target.
Suppose that nums is rotated at some pivot unknown to you """

class Solution:
    def search(self,nums, target) -> int:
        l, r = 0, len(nums) - 1
        while l <= r:
            mid = (l + r) // 2
            if target == nums[mid]:
                return mid
            if nums[l] <= nums[mid]:
                if target > nums[mid] or target < nums[l]:
                    l = mid + 1
                else:
                    r = mid - 1
            else:
                if target < nums[mid] or target > nums[r]:
                    r = mid - 1
                else:
                    l = mid + 1
        return -1


""" This program will delete items only from a sorted lists"""
list1 = [4, 5, 100, 105, 109, 110, 125, 135, 142, 146, 150, 155, 165, 168, 172, 178, 180, 190, 200, 205, 300, 306]
max_val = 200
min_val = 100
stop = -1
#to delete the small elements
for index, value in enumerate(list1):
    if value >= min_val:
        stop = index
        break
print(stop)
if stop != -1:
    del list1[:stop]
print(list1)
#to delete the larger elements
stop = -1
for index, value in enumerate(list1):
    if value >= max_val:
        stop = index +1
        break
print(stop)
if stop != -1:
    del list1[stop:]
print(list1)


from primaires.interpreteur.commande.commande import Commande
from .creer import PrmCreer
from .editer import PrmEditer
from .liste import PrmListe
from .supprimer import PrmSupprimer

class CmdFlottantes(Commande):

    """Commande 'flottantes'"""

    def __init__(self):
        """Constructeur de la commande"""
        Commande.__init__(self, "flottantes", "floating")
        self.groupe = "administrateur"
        self.nom_categorie = "batisseur"
        self.aide_courte = "manipule les descriptions flottantes"
        self.aide_longue = \
            "Cette commande permet de créer, éditer, lister " \
            "et supprimer les descriptions flottantes. Les descriptions " \
            "flottantes sont des descriptions \"standards\" de l'univers, " \
            "mais à la différence de celles manipulées d'ordinaire " \
            "(descriptions d'objets, de salles, de PNJ), les descriptions " \
            "flottantes n'ont par défaut aucun lien avec l'univers. Pour les " \
            "utiliser, il faut les inclure dans une autre description. Créez " \
            "d'abord une description flottante avec une clé explicite (si il " \
            "s'agit d'une description de plusieurs salles, par exemple, " \
            "faites comme si c'était une clé de salle, le nom de la zone, " \
            "le signe deux points et un mnémonique imaginaire). Ensuite, dans " \
            "les descriptions où vous voulez importer cette description " \
            "flottante, utilisez l'abréviation " \
            "|cmd|@cle_de_la_description_flottante|ff|. Cette commande peut " \
            "se trouver dans un paragraphe isolé de la description ou au " \
            "milieu d'un paragraphe (veillez à être cohérent dans le " \
            "résultat attendu). Les descriptions dynamiques peuvent être " \
            "utilisées conjointement avec les descriptions flottantes, " \
            "consultez la documentation des descriptions dynamiques à " \
            "l'adresse " \
        "http://redmine.kassie.fr/projects/documentation/wiki/DescriptionDynamique " \
            "pour plus d'informations."

    def ajouter_parametres(self):
        """Ajout des paramètres."""
        self.ajouter_parametre(PrmCreer())
        self.ajouter_parametre(PrmEditer())
        self.ajouter_parametre(PrmListe())
        self.ajouter_parametre(PrmSupprimer())


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

# # Lab 0: Warmup

# In this lab exercise, you will warm up / refresh your Python skills by analyzing some real data inside of a Jupyter notebook environment. You should write whatever **Python** code you like to solve these problems. You can search on the web for documentation and techniques to help you solve the problem (see especially the course website resources https://sites.duke.edu/compsci216s2020/resources-and-help/ and the official Python documentation: https://docs.python.org/3.7/).
#
# You may find some of the following packages to be useful in completing the problems in this lab. You are not required to use any of them, but you can import them in the subsequent cell if desired.
#
# - [numpy](https://docs.scipy.org/doc/numpy/): functions and objects for scientific computing with Python
# - [csv](https://docs.python.org/3/library/csv.html):  classes to read and write tabular data in CSV format.

# In[1]:

# Run this cell to import some useful packages
import numpy as np
import csv

# In[ ]:

#Rebecca Luner

# ## Uber Rides
#
# The [boston.csv](boston.csv) file contains data on weekday Uber rides in the Boston, Massachusetts metropolitan areas from the [Uber Movement](https://movement.uber.com) project. The `sourceid` and `dstid` columns contain codes corresponding to start and end locations of each ride. The `hod` column contains codes corresponding to the hour of the day the ride took place. The `ride time` column contains the length of the ride, in minutes.
#
# The code below will open the file and print every line. Run the cell below to see the result.

# In[2]:

f = open('boston.csv')
for line in f:
    print(line)
f.close()

# **Question 1**
# How many rides are listed in the the file?

# In[3]:

f = open('boston.csv')
f.readline() #Getting rid of the header line

numRides = 0
for line in f:
    numRides+= 1
f.close()
print(numRides)

# **Question 2**
# What is the average length of a ride?

# In[4]:

import math

f = open('boston.csv')
totalLength = 0
numRides = 0
f.readline() #Getting rid of the header line

for line in f:
    time = float(line.split(",")[3])
    totalLength += time
    numRides += 1
f.close()

print(totalLength/numRides)

# **Question 3**
# What percentage of rides are under 10 minutes?

# In[5]:

import math

f = open('boston.csv')
under10 = 0
numRides = 0
f.readline() #Getting rid of the header line

for line in f:
    time = float(line.split(",")[3])
    if time < 10:
        under10 += 1
    numRides += 1
f.close()

print((under10/numRides)* 100)

# **Question 4**
# What are the top three **start** locations (`sourceid`) for rides in the dataset?

# In[6]:

import math

f = open('boston.csv')
f.readline() #Getting rid of the header line
startLoc = {}

for line in f:
    start = float(line.split(",")[0])
    if start not in startLoc:
        startLoc[start] = 1
    startLoc[start] += 1
f.close()

startLoc = sorted(startLoc.items(), key=lambda num:(num[1]), reverse = True)
for elem in startLoc[:3]:
    print(elem[0])

# **Question 5**
# What are the top three **destination** locations (`dstid`) for rides in the dataset?

# In[7]:

import math

f = open('boston.csv')
f.readline() #Getting rid of the header line
endLoc = {}

for line in f:
    end = float(line.split(",")[1])
    if end not in endLoc:
        endLoc[end] = 1
    endLoc[end] += 1
f.close()

endLoc = sorted(endLoc.items(), key=lambda num:(num[1]), reverse = True)
for elem in endLoc[:3]:
    print(elem[0])

# ** Question 6** How many rides begin at the most popular location (`sourceid`) and time (`hod`) to start rides (e.g, 3 rides start at 3am from sourceid 435) in Boston? You will need to determine what start location and hour of day is the most popular location and time to begin rides and then count how many rides originate there.

# In[8]:

import math

f = open('boston.csv')
f.readline() #Getting rid of the header line

#Finding the most popular starting location
startLoc = {}
for line in f:
    start = float(line.split(",")[0])
    if start not in startLoc:
        startLoc[start] = 1
    startLoc[start] += 1
f.close()

startLoc = sorted(startLoc.items(), key=lambda num:(num[1]), reverse = True)
popularLoc = startLoc[0][0]

#Finding the most popular hour of day
f = open('boston.csv')
f.readline()
hodTimes = {}
for line in f:
    hod = float(line.split(",")[2])
    if hod not in hodTimes:
        hodTimes[hod] = 1
    hodTimes[hod] += 1
f.close()

hodTimes = sorted(hodTimes.items(), key=lambda num:(num[1]), reverse = True)
popularHod = hodTimes[0][0]

#Finding the number of rides with the most popular starting location and time
f = open('boston.csv')
f.readline()
totRides = 0

for line in f:
    start = float(line.split(",")[0])
    currHod = float(line.split(",")[2])
    if start == popularLoc:
        if currHod == popularHod:
            totRides += 1
print(totRides)

# ## Submitting
#
# You should make sure any code that you write to answer the questions is included in this notebook. Save your work. When you finish, or when lab is over, submit your assignment at http://gradescope.com/ (if you have not already enrolled in the course on gradescope, do so with the code MGZZW3). Before you submit:
#
# 1. Double check that your entire notebook runs correctly and generates the expected output. To do so, you can simply select Kernel -> Restart and Run All.
# 2. Download two versions of your notebook, .pdf and .py. You can do this by selecting File -> Download as -> PDF via LaTeX (.pdf) and File -> Download as -> Python (.py).
# 3. Upload the .pdf to gradescope under lab0 report and the .py to gradescope under lab0 code. For the report, make sure to indicate the pages where your answers to individual questions are located. For the code, you can ignore the text about an autograder. Only submit one of each for your group, but *Make sure to use the group submission feature* to indicate your group members.
#
# Note that labs are graded for effort, not correctness, so you will receive full credit if you made a serious attempt at the above questions.
#
#


# -*- coding:utf-8 -*-
class Solution:
    def jumpFloor(self, number):
        # write code here
        if number==1:
            return 1
        if number==2:
            return 2
        res=[i+1 for i in range(number)]
        res[0]=1
        res[1]=2
        for x in range(2,number):
            res[x]=res[x-1]+res[x-2]
        return res[-1]


from PIL import Image
from tqdm import tqdm
# import tensorflow as tf
import binascii
import glob
import os

import numpy as np

dataCnt = 0
dataNum = 9000
width = 100
height = 100
channels = 3
dataset = np.zeros(shape=(dataNum, height, width, channels), dtype=np.float32)

def main():
    global dataCnt
    malware_path = './bytes'
    malware_categories = os.listdir(malware_path + '/')
    print(malware_categories)

    dataCnt = 0
    cnt = 0

    for malware_family in tqdm(malware_categories):
        print(malware_family)
        malware_files = glob.glob(malware_path + '/' + malware_family + '/*.txt')
        for malware_file in tqdm(malware_files):
            if not malware_file:
                continue
            try:
                f = open(malware_file, 'r')
                #                 print("FILE OPEN")
                code = f.readlines()
                one_line = ''
                for line in code:
                    line = line.replace("+", "")
                    line = line.replace("\n", "")

                    if len(line) != 2:
                        print(str(len(line)) + "### " + line)
                    one_line = one_line + line

                BinarySrcCode = binascii.unhexlify(one_line)
                code_len = len(BinarySrcCode)
                padLen = width * height * 3 - code_len

                if code_len == 0:
                    continue
                if padLen < 0:
                    print("file is over")
                    cnt += 1
                    continue

                zeroPad = bytes(padLen)
                image = bytearray(BinarySrcCode) + bytes(zeroPad)
                img = Image.frombytes("RGB", (height, width), bytes(list(image)))
                #                 print("READY TO SAVE")
                img.save("./malware_images/" + malware_family + "/" + malware_file[17:-4] + ".PNG", 'PNG')
                dataCnt += 1

            except Exception as ex:
                #                 print("FILE NOT OPENED")
                print(malware_file)
                print(ex)
                return

        print("num of exceeded sol :", cnt)
        print("num of total vul :", dataCnt)

    return

main()

from keras.preprocessing.image import ImageDataGenerator
import tensorflow as tf

data_dir = './malware_images/'
datagen = ImageDataGenerator(rescale=1. / 255, validation_split=0.2)

train_it = datagen.flow_from_directory(
    data_dir,
    class_mode='categorical',
    target_size=(100, 100),
    batch_size=32)

val_it = validation_generator = datagen.flow_from_directory(
    data_dir,
    target_size=(100, 100),
    batch_size=32,
    subset='validation')

cnn_model = tf.keras.models.Sequential([
    tf.keras.layers.Conv2D(32, (3, 3), activation='relu', input_shape=(100, 100, 1)),
    tf.keras.layers.MaxPooling2D((2, 2)),
    tf.keras.layers.Conv2D(64, (3, 3), activation='relu'),
    tf.keras.layers.MaxPooling2D((2, 2)),
    tf.keras.layers.Conv2D(64, (3, 3), activation='relu'),
    tf.keras.layers.Flatten(),
    tf.keras.layers.Dense(64, activation='relu'),
    tf.keras.layers.Dense(9, activation='softmax')
])

cnn_model.compile(optimizer='adam',
                  loss='sparse_categorical_crossentropy',
                  metrics=['accuracy'])

cnn_model.fit(train_it, epochs=10)
test_eval_result = cnn_model.evaluate(val_it)
print(test_eval_result)

converter = tf.lite.TFLiteConverter.from_keras_model(cnn_model)
tflite_model = converter.convert()

with open('./keras_model_cnn_malware.tflite', 'wb') as f:
    f.write(tflite_model)


import os
from typing import final
from werkzeug.utils import secure_filename
from os.path import join, isfile, islink
from screen1_backend_functions import read_specific_file, remove_files, write_file

PATH = os.getcwd()
UPLOAD_FOLDER = os.path.join(PATH, 'uploads')
PRE_PROCESSED_FOLDER = os.path.join(PATH, 'pre_processed')
REMOVED_QUERY_FOLDER = os.path.join(PATH, 'removed_queries')
ALTER_COMMENT_FOLDER = os.path.join(PATH, 'alter_comment_queries')

def alter_comment_query_only(query_type,single_query):
    '''
    Keeping the ALTER and COMMENT queries seperate from main script as there is no much changes
    from ORACLE to SNOWFLAKE for those queries.
    '''
    # query_split = single_query.split(" ")
    result=""
    # if str(query_split[0]).lower() == 'alter' or str(query_split[0]).lower() == 'comment':
    if query_type.lower() == 'alter' or query_type.lower() == 'comment':
        if single_query!="":
            file_save_path = os.path.join(ALTER_COMMENT_FOLDER, "alter_comment_oracle_queries.txt")
            text_file = open(file_save_path, "a")
            text_file.write(single_query+";\n")
            text_file.close()
    else:
        result = single_query
    return result

def remove_check_constraint(query_type, single_query):
    '''
    Removing the Check constraint Alter quueries for ORACLE, as those are not defined in SNOWFLAKE.
    '''
    new_query=""
    deleted_check_constraint_queries=""
    if query_type.lower() == 'create':   # for check constraint in CREATE queries
        # split using comma
        split_query = []
        splitted_query = single_query.split(",")
        for i in splitted_query:   #here i is each constraint add in query
            #print()
            s = i.split()
            # print("list of spilit",s)
            if "check" in s or "CHECK" in s:
                deleted_check_constraint_queries=deleted_check_constraint_queries+i
                new_query=""
            else:
                # print("else",i)
                split_query.append(i)
        new_query= ",".join(split_query)

    else:               # for check constraint in ALTER queries
        s = single_query.split()
        #print("list of spilit",s)
        if "check" in s or "CHECK" in s:
            deleted_check_constraint_queries=deleted_check_constraint_queries+single_query
            new_query=""
        else:
            #print("else")
            new_query=single_query
    # write_file(PATH, deleted_check_constraint_queries, "removed_check_constraint_queries.txt")

    file_save_path = os.path.join(REMOVED_QUERY_FOLDER, "removed_check_constraint_queries.txt")
    text_file = open(file_save_path, "a")
    text_file.write(deleted_check_constraint_queries)
    text_file.close()

    return new_query

def remove_index(single_query):
    new_query=""
    removed_index_queries=""
    s = single_query.split()
    # print("list of INDEX split"," ".join(s[:2]))
    first_two_words=" ".join(s[:2])
    first_three_words=" ".join(s[:3])
    if first_two_words == "CREATE INDEX" or first_three_words == "CREATE UNIQUE INDEX" :
        removed_index_queries=removed_index_queries+single_query
        new_query=""
    else:
        # print("else")
        new_query=single_query

    file_save_path = os.path.join(REMOVED_QUERY_FOLDER, "removed_index_queries.txt")
    text_file = open(file_save_path, "a")
    text_file.write(removed_index_queries)
    text_file.close()

    return new_query

def oracle_preprocessing(DIRECTORY):

    # Make directory if foldes  not exists and removing it before creating new.
    if not os.path.isdir(PRE_PROCESSED_FOLDER):
        os.mkdir(PRE_PROCESSED_FOLDER)
    else:
        remove_files(PRE_PROCESSED_FOLDER)

    if not os.path.isdir(REMOVED_QUERY_FOLDER):
        os.mkdir(REMOVED_QUERY_FOLDER)
    else:
        remove_files(REMOVED_QUERY_FOLDER)

    if not os.path.isdir(ALTER_COMMENT_FOLDER):
        os.mkdir(ALTER_COMMENT_FOLDER)
    else:
        remove_files(ALTER_COMMENT_FOLDER)

    result=""

    for file in os.listdir(DIRECTORY):          #looping Files in a directory
        filename = os.path.join(DIRECTORY, file)
        file_opened=open(filename,"r")
        file_read = file_opened.read()
        q=''
        q = q + file_read
        # print("q\n",q)
        file_opened.close()
        q_split = q.split(";")
        final_query_list=[]

        for query in q_split:                   # looping single query in that file
            # for each single query pre- processing for oracle database
            # print("single query",type(query),query)

            # Cleaning query
            query_cleaned = query.lstrip().rstrip()
            # query_cleaned = query_cleaned.replace("\n","")
            print("before",query_cleaned)
            query_cleaned = query_cleaned.replace("LOGGING","")
            print("after",query_cleaned)

            # calculating "query_type" to pass to later functions
            query_split= query_cleaned.split()
            query_type=""
            if query_cleaned!="":
                if query_split[0].upper()=='CREATE':
                    query_type = 'CREATE'
                elif query_split[0].upper()=='ALTER':
                    query_type = 'ALTER'
                elif query_split[0].upper()=='COMMENT':
                    query_type = 'COMMENT'
                else:
                    pass
            else:
                pass
            # print("query_type\n",query_type)
            processed_query1 = remove_check_constraint(query_type, query_cleaned)
            processed_query2 = remove_index(processed_query1)

            # saving alter and comment files seperateley in folder and returning rest queries.
            updated_query= alter_comment_query_only(query_type,processed_query2)
            # print("updated_query\n",updated_query)

            if updated_query!="":
                final_query_list.append(updated_query+";")
                print("updated_query",updated_query)
            # else:
            #     final_query_list.append("")
            #     print("final_query_list_else",updated_query)
        new_query=""
        if len(final_query_list)!=0:
            #print("final_query_list",final_query_list)
            new_query="".join(final_query_list)
            print("final_query",new_query)
            # Saving the processed file in seperate folder
            file_save_path = os.path.join(PRE_PROCESSED_FOLDER, file)
            text_file = open(file_save_path, "w")
            text_file.write(new_query)
            text_file.close()
            result = "All query saved on lan"
        else:
            print("list if blank")

    return result

def replace_name_alter_comment_queries(changes):
    '''
    Replace component names in files in "Alter_comment_queries" folder as per changes made by user in front end

    '''
    q=""
    DIRECTORY = ALTER_COMMENT_FOLDER
    filename = os.path.join(DIRECTORY,"alter_comment_oracle_queries.txt")

    # reading alter comments files in this folder.
    if len(os.listdir(DIRECTORY))!=0:          #looping Files in a directory
        file_opened=open(filename,"r")
        file_read = file_opened.read()
        q = q + file_read
        print("q\n",q)
        file_opened.close()
    query_cleaned = q.lstrip().rstrip()
    q_split = query_cleaned.split(";")

    old_names = changes['old_table']
    new_names = changes['new_change_table']
    new_query = ""
    final_query_list=[]

    for query in q_split:
        if query!="" and len(old_names)!=0 and len(new_names)!=0:
            for i in old_names:
                old_ind = old_names.index(i)
                print("q",query)
                new_query = query.replace(i,new_names[old_ind],1)
        else:
            new_query=query
        final_query_list.append(new_query)
        # print("final_query_list",final_query_list)

    if len(final_query_list)!=0:
        updated_query=";\n".join(final_query_list)
        print("updated_query",updated_query)
        file_save_path = os.path.join(ALTER_COMMENT_FOLDER, filename)
        text_file = open(file_save_path, "w")
        text_file.write(updated_query)
        text_file.close()
    else:
        print("list if blank")

    print("new_replaced_query",updated_query)
    return updated_query

# query='''CREATE TABLE EMPLOYEES
#     (      EMPLOYEE_ID NUMBER (6)  NOT NULL ,
#      FIRST_NAME VARCHAR2 (20 BYTE) ,
#      LAST_NAME VARCHAR2 (25 BYTE)  NOT NULL ,
#      EMAIL VARCHAR2 (25 BYTE)  NOT NULL ,
#      PHONE_NUMBER VARCHAR2 (20 BYTE) ,
#      HIRE_DATE DATE  NOT NULL ,
#      JOB_ID VARCHAR2 (10 BYTE)  NOT NULL ,
#      SALARY NUMBER (8,2) ,
#      COMMISSION_PCT NUMBER (2,2) ,
#      MANAGER_ID NUMBER (6) ,
#      DEPARTMENT_ID NUMBER (4), CONSTRAINT EMP_EMP_ID_PK PRIMARY KEY ( EMPLOYEE_ID ) ,
#       CONSTRAINT EMP_EMP_ID_PK check sale>0 ( EMPLOYEE_ID ) ,
# CONSTRAINT EMP_EMAIL_UK UNIQUE ( EMAIL ),
# CONSTRAINT EMP_SALARY_MIN
#     CHECK ( salary > 0) ,
# CONSTRAINT EMP_DEPT_FK FOREIGN KEY
#     (
#      DEPARTMENT_ID
#     )
#     REFERENCES DEPARTMENTS
#     (
#      DEPARTMENT_ID
#     )
#     NOT DEFERRABLE  ,
# CONSTRAINT EMP_MANAGER_FK FOREIGN KEY
#     (
#      MANAGER_ID
#     )
#     REFERENCES EMPLOYEES
#     (
#      EMPLOYEE_ID
#     )
#     NOT DEFERRABLE
#     '''

# def ext(quer,ph,sc):
#     ext_dat=extract_tables(quer,'ALTER',sc)
#     ph.append(ext_dat)
#     print(ph)
#     return ext_dat

# tab=[]
# ip=ext(query,tab,t)
# query = '''
# CREATE TABLE COUNTRIES
#     (
#      COUNTRY_ID CHAR (2 BYTE)  NOT NULL ,
#      COUNTRY_NAME VARCHAR2 (40 BYTE) ,
#      REGION_ID NUMBER
#     ) LOGGING
# ;
# '''
query2='''
COMMENT ON COLUMN COUNTRIES.COUNTRY_ID IS 'Primary key of countries table.'
;
'''
changes =  {'old_table': ['COUNTRIES'], 'new_change_table': ['COUNTRY'], 'old_view': [], 'new_change_view': [], 'old_schema': [], 'new_schema': [], 'old_database': [], 'new_change_db': [], 'removed_table': [], 'removed_view': [], 'removed_database': [], 'removed_schema': []}
# alter_comment_query_only(query2)
#oracle_preprocessing(UPLOAD_FOLDER)

# replace_name_alter_comment_queries(changes)


"""Median calculator."""
"""ENTER YOUR SOLUTION HERE!"""
def median(numbers):
    try:
        numbers.sort()
        length = len(numbers)
        if len(numbers) % 2 == 0:
            return (numbers[length // 2] + numbers[length // 2 - 1]) / 2
        else:
            return numbers[length // 2]
    except TypeError:
        print("Please enter a list of numbers.")
        return None

while True:
    try:
        print("Enter a list of numbers separated by commas: ")
        numbers = [float(value) for value in input().split(",")]
    except ValueError:
        print("Some input could not be converted to a number!")
    else:
        break

print(numbers)
print("The median is", median(numbers))


import inspect
from flask_swagger_generator.components.swagger_models import SwaggerModel
from flask_swagger_generator.utils import UrlVariableType

class SwaggerPathParameter(SwaggerModel):

    def __init__(
            self,
            input_type: str = None,
            name: str = None,
            description: str = None,
            required: bool = True
    ):
        super(SwaggerPathParameter, self).__init__()
        self.input_type = UrlVariableType.from_string(input_type)
        self.name = name
        self.description = description
        self.required = required

    def perform_write(self, file):
        parameter_entry = inspect.cleandoc(
            """
                - in: path
                  name: {name}
                  schema:
                    type: {input_type}
                  description: {description}
                  required: {required}
            """.format(
                name=self.name,
                required=self.required,
                description=self.description,
                input_type=self.input_type.get_swagger_url_path_variable_type()
            )
        )

        param = self.indent(parameter_entry, 3 * self.TAB)
        file.write(param)
        file.write("\n")


import pytest

from lispy.context import ExecutionContext
from lispy.interpreter import IterativeInterpreter
from lispy.utils import eval_expr, parse_expr
from lispy.globals import GLOBALS
from lispy.tokenizer import Token

def test_balanced_parentheses():
    parse_expr('(()()((())())())')

    with pytest.raises(SyntaxError):
        parse_expr('(((())')

    with pytest.raises(SyntaxError):
        parse_expr('(())))')

def test_operations():
    inpr = IterativeInterpreter()
    assert eval_expr('(+ 1 1)', inpr) == 2
    assert eval_expr('(- 1 1)', inpr) == 0
    assert eval_expr('(/ 2 1)', inpr) == 2
    assert eval_expr('(* 2 2)', inpr) == 4

def test_nested_call():
    inpr = IterativeInterpreter()
    assert eval_expr('(+ (+ 1 1) 1)', inpr) == 3

def test_conditional():
    inpr = IterativeInterpreter()
    assert eval_expr('(if (= 0 (- 1 1)) 1 -1)', inpr) == 1

def test_let():
    inpr = IterativeInterpreter()
    assert eval_expr('(let (x 1 y 3) (+ x y))', inpr) == 4

def test_defn():
    inpr = IterativeInterpreter()
    assert eval_expr('(defn double (x) (+ x x)) (double 2)', inpr) == 4
    assert 'double' in inpr.ctx

def test_do():
    inpr = IterativeInterpreter()
    assert eval_expr('(do (+ 1 1) (- 1 1))', inpr) == 0

    assert eval_expr('(do (defn inc (x) (+ x 1)) (inc 1))', inpr) == 2
    assert 'inc' in inpr.ctx

    assert eval_expr('(do 3 & (list (+ 1 1) (- 1 1)))', inpr) == 0

def test_recursion():
    inpr = IterativeInterpreter()
    assert eval_expr(
        '(defn fact (x) (if (< x 2) 1 (* x (fact (- x 1))))) (fact 4)',
        inpr
    ) == 24

def test_varargs():
    inpr = IterativeInterpreter()
    assert eval_expr('(defn sum (& args) (+ &args)) (sum 1 2 3 4)', inpr) == 10
    assert eval_expr('(defn f (x y z) (+ x y z)) (f 1 & (list 2 3))', inpr) == 6

def test_import():
    inpr = IterativeInterpreter()
    eval_expr('(pyimport json)', inpr)

    import json
    assert inpr.ctx.get('json') == json
    assert eval_expr('(json.loads "[1, 2, 3]")', inpr) == [1, 2, 3]

def test_import_from():
    inpr = IterativeInterpreter()
    eval_expr('(pyimport_from json.decoder JSONArray)', inpr)

    from json.decoder import JSONArray
    assert inpr.ctx.get('JSONArray') == JSONArray

def test_member():
    ctx = ExecutionContext(None)
    ctx['s'] = '  abc  '
    inpr = IterativeInterpreter(ctx)
    assert eval_expr(r'(. strip s)', inpr) == ctx['s'].strip

def test_def():
    inpr = IterativeInterpreter()
    assert eval_expr('(def x 1 y (+ x 1))', inpr) == 2
    assert 'x' in inpr.ctx and 'y' in inpr.ctx
    assert eval_expr('(+ x y)', inpr) == 3

def test_str_names():
    inpr = IterativeInterpreter()
    with pytest.raises(NameError):
        eval_expr('(+ x y)', inpr)

def test_call():
    inpr = IterativeInterpreter()
    assert eval_expr('((. strip " abc "))', inpr) == 'abc'

def test_and():
    inpr = IterativeInterpreter()
    eval_expr('(def calls (list)) (defn canary (x) (do ((. append calls) x) x))', inpr)
    assert not eval_expr('(and (canary 0) (canary 1) (canary 2))', inpr)
    assert inpr.ctx['calls'] == [0]

    assert not eval_expr('(and 1 & (list 2 0 3))', inpr)

def test_or():
    inpr = IterativeInterpreter()
    eval_expr('(def calls (list)) (defn canary (x) (do ((. append calls) x) x))', inpr)
    assert eval_expr('(or (canary 0) (canary 1) (canary 2))', inpr)
    assert inpr.ctx['calls'] == [0, 1]

    assert eval_expr('(or 0 & (list 0 2 3))', inpr)

def test_anonymous_functions():
    inpr = IterativeInterpreter()
    assert eval_expr('((# * %0 2) 2)', inpr) == 4

def test_quote():
    inpr = IterativeInterpreter()

    def t(val):
        return Token(val, Token.guess_token_type(str(val)[0]))

    assert eval_expr('(quote + 1 2)', inpr) == [t('+'), t(1), t(2)]
    assert eval_expr('(quote 1 2 (3 (4 5) 6) 7)', inpr) == [
        t(1), t(2), [t(3), [t(4), t(5)], t(6)], t(7)
    ]
    assert eval_expr('(quote + 1 ~(+ 1 1))', inpr) == [t('+'), t(1), 2]

    with pytest.raises(RuntimeError):
        eval_expr('(+ ~(= 1 0) 2)', inpr)

def test_macro():
    inpr = IterativeInterpreter()
    eval_expr('(defmacro infix (args) (list (nth args 1) (nth args 0) (nth args 2)))', inpr)
    assert eval_expr('(let (i 1) (infix (i + 1)))', inpr) == 2

    assert eval_expr('(macroexpand infix (1 + 1))', inpr) == [
        Token('+', Token.TOKEN_OTHER), Token(1, Token.TOKEN_LITERAL), Token(1, Token.TOKEN_LITERAL)
    ]

    assert eval_expr('(infix (1 + 1))', inpr) == 2

def test_dynamic_bindings():
    inpr = IterativeInterpreter()
    assert eval_expr('(defn f (x) (+ x y)) (let (y 1) (f 2))', inpr) == 3

def test_dollar():
    inpr = IterativeInterpreter()
    assert eval_expr('(let (x 3) ($ "x"))', inpr) == 3

def test_function_arg_unpack():
    inpr = IterativeInterpreter()
    eval_expr('(defn f (a (b c) (d (e (f g)))) (+ a b c d e f g))', inpr)
    assert eval_expr(
        '(let (a 1 b 1 c 1 d 1 x (list 1 (list 1 1))) (f a (list b c) (list d x)))',
        inpr
    ) == 7

    with pytest.raises(SyntaxError):
        eval_expr('(defn g (a & (b c)) (+ a b c))', inpr)

def test_let_unpack():
    inpr = IterativeInterpreter()
    assert eval_expr('(let ((a b c) (list 1 2 3)) (+ a b c))', inpr) == 6

    with pytest.raises(RuntimeError):
        eval_expr('(let ((a b c) (list 1)) 3)', inpr)

    with pytest.raises(RuntimeError):
        eval_expr('(let ((a) (list 1 2 3)) 3)', inpr)

def test_in():
    inpr = IterativeInterpreter()
    assert eval_expr('(in 4 (list 1 2 3))', inpr) == False
    assert eval_expr('(in 2 (set (list 1 2 3)))', inpr) == True

def test_filter():
    inpr = IterativeInterpreter()
    assert eval_expr('(filter (defn even (x) (= 0 (% x 2))) (range 10))', inpr) == [0, 2, 4, 6, 8]
    assert eval_expr('(filter (defn even (x) (= 0 (% x 2))) (list))', inpr) == []

def test_map():
    inpr = IterativeInterpreter()
    res = eval_expr('(map (defn double (x) (* 2 x)) (range 5))', inpr)
    assert res == [0, 2, 4, 6, 8]

def test_match():
    inpr = IterativeInterpreter()

    match = '(match %s ((a) 1) ((a b) 2) ((a b c) 3) (a -1))'

    assert eval_expr(match % '(list 1)', inpr) == 1
    assert eval_expr(match % '(list 1 2)', inpr) == 2
    assert eval_expr(match % '(list 1 2 3)', inpr) == 3
    assert eval_expr(match % '4', inpr) == -1

    with pytest.raises(RuntimeError):
        eval_expr('(match (list 1 2) ((a) 1))', inpr)


import os
import csv

# Set the path to the CSV file
csv_path = os.path.join("/Users", "peijuwu", "Desktop", "python-challenge", "PyBank", "Resources", "budget_data.csv")

# Open the CSV file
with open(csv_path, "r") as f:
    csv_reader = csv.reader(f)
    header= next(csv_reader)  # Store the header row

    total_months = 0
    total = 0
    pre_profit_loss = 0
    changes = []
    dates = []

    # Iterate over each line in the CSV file
    for line in csv_reader:
        total_months += 1 # Increment the total number of months
        total += int(line[1]) # Accumulate the total profit/loss
        dates.append(line[0]) # Collect the dates from each line

        # Calculate changes in profit/loss between months
        if pre_profit_loss != 0:
            current_profit_loss = int(line[1])
            change = current_profit_loss - pre_profit_loss
            changes.append(change)

        #Update the previous profit/loss value for the next iteration
        pre_profit_loss = int(line[1])

    # Calculate average change, maximum increase, and maximum decrease
    average_change = round(sum(changes) / len(changes), 2)
    max_increase = max(changes)
    max_increase_index = changes.index(max_increase)
    max_increase_date = dates[max_increase_index + 1]
    max_decrease = min(changes)
    max_decrease_index = changes.index(max_decrease)
    max_decrease_date = dates[max_decrease_index + 1]

    # Print the financial analysis results
    print("Financial Analysis")
    print("------------------")
    print(f"Total Months: {str(total_months)}")
    print(f"Total: ${str(total)}")
    print(f"Average Change: ${str(average_change)}")
    print(f"Greatest Increase in Profits: {str(max_increase_date)} (${str(max_increase)})")
    print(f"Greatest Decrease in Profits: {str(max_decrease_date)} (${str(max_decrease)})")

# Set the path for the output file
file_path = os.path.join("/Users", "peijuwu", "Desktop", "python-challenge", "PyBank", "analysis", "Financial_Analysis.txt")

# Write the financial analysis results to a text file
with open(file_path, "w") as new_f:
    new_f.write("Financial Analysis\n")
    new_f.write("---------------------------------\n")
    new_f.write(f"Total Months: {str(total_months)}\n")
    new_f.write(f"Total: ${str(total)}\n")
    new_f.write(f"Average Change: ${str(average_change)}\n")
    new_f.write(f"Greatest Increase in Profits: {str(max_increase_date)} (${str(max_increase)})\n")
    new_f.write(f"Greatest Decrease in Profits: {str(max_decrease_date)} (${str(max_decrease)})\n")


from random import randint
from sys import argv
answer = randint(1,10)

while True:
    try:
        print(answer)
        guess = input('guess a number 1 to 10:  ')
        if int(guess)>0 and int(guess)<11:
            if int(guess) == answer:
                print('you are a genius!')
                break
        else:
            print('hey bozo, I said 1 to 10')
    except ValueError:
        print('please enter a number')
        continue


#!/usr/bin/env python
import itertools
import networkx as nx
import matplotlib.pyplot as plt

from networkx.algorithms.community.centrality import girvan_newman as nx_girvan_newman
from girvan_newman import girvan_newman as our_girvan_newman

from networkx.algorithms.centrality import edge_betweenness_centrality as nx_edge_betweenness_centrality
from girvan_newman import edge_betweenness_centrality as our_edge_betweenness_centrality

from tools import Timer

def benchmark_girvan_newman(G):
    print("Starting benchmark_girvan_newman...")
    max_iteration_level = 10

    Y_our = []
    Y_nx = []

    our_it = our_girvan_newman(G)
    nx_it = nx_girvan_newman(G)

    our_it = itertools.islice(our_it, max_iteration_level)
    nx_it = itertools.islice(nx_it, max_iteration_level)

    i = 0
    while True:
        try:
            with Timer(f"Starting iteration {i} on our girvan newman") as t:
                next(our_it)
                Y_our.append(t.get_time())
            with Timer(f"Starting iteration {i} on nx girvan newman") as t:
                next(nx_it)
                Y_nx.append(t.get_time())
        except StopIteration:
            break
        i += 1

    X = list(range(len(Y_our)))
    plt.figure()
    plt.title("Time over iteration for executing girvan newman")
    plt.xlabel("Iteration level []")
    plt.ylabel("Time [s]")
    plt.plot(X, Y_our, label="Our implementation")
    plt.plot(X, Y_nx, label="Networkx implementation")
    plt.legend()
    plt.savefig("benchmark_girvan_newman.png")

    Y_our_cumulative = get_cumulative_array(Y_our)
    Y_nx_cumulative = get_cumulative_array(Y_nx)

    plt.figure()
    plt.title("Cumulative time over iteration for executing girvan newman")
    plt.xlabel("Iteration level []")
    plt.ylabel("Time [s]")
    plt.plot(X, Y_our_cumulative, label="Our implementation")
    plt.plot(X, Y_nx_cumulative, label="Networkx implementation")
    plt.legend()
    plt.savefig("benchmark_girvan_newman_cumulative.png")

def benchmark_edge_betweenness_centrality(G):
    print("Starting benchmark_edge_betweenness_centrality...")

    X = list(range(0, len(G.nodes), 5))
    Y_our = []
    Y_nx = []

    for i in X:
        sub_G = G.subgraph(list(G.nodes)[0:i])
        with Timer("Starting our edge_betweenness_centrality") as t:
            our_edge_betweenness_centrality(sub_G)
            Y_our.append(t.get_time())
        with Timer("Starting nx edge_betweenness_centrality") as t:
            nx_edge_betweenness_centrality(sub_G)
            Y_nx.append(t.get_time())

    plt.figure()
    plt.title("Time over graph size for executing edge_betweenness_centrality")
    plt.xlabel("Iteration level []")
    plt.ylabel("Time [s]")
    plt.plot(X, Y_our, label="Our implementation")
    plt.plot(X, Y_nx, label="Networkx implementation")
    plt.legend()
    plt.savefig("benchmark_edge_betweenness_centrality.png")

def get_cumulative_array(a):
    sum = 0
    b = []
    for i in a:
        b.append(i + sum)
        sum += i
    return b

def main():
    G = nx.read_edgelist("subgraph.gz")
    # from tools import lecture_graph
    # G = lecture_graph()
    benchmark_girvan_newman(G)
    benchmark_edge_betweenness_centrality(G)

    plt.show()

if __name__ == "__main__":
    main()


from basf2 import set_log_level, LogLevel, create_path, process, register_module, statistics

# suppress messages and during processing:
set_log_level(LogLevel.INFO)

main = create_path()

# event info setter
main.add_module("EventInfoSetter", expList=0, runList=1, evtNumList=100)

# generator
aafh = register_module('AafhInput')
aafh.param({
    # decay mode to generate.
    # 1: e+e- -> mu+mu-L+L- where L is a user defined particle (default: tau)
    # 2: e+e- -> mu+mu-mu+mu-
    # 3: e+e- -> e+e-mu+mu-
    # 4: e+e- -> e+e-L+L- where L is a user defined particle (default: tau)
    # 5: e+e- -> e+e-e+e-
    'mode': 5,
    # to set the particle for modes 1 and 4 use set parameter "particle"
    # rejection scheme to generate unweighted events
    # 1: use rejection once for the final event weight
    # 2: use rejection per sub generator and then for the final event
    'rejection': 2,
    # max subgenerator event weight, only used if rejection is set to 2
    # (default). If this value is to low the generation will produce errors. If
    # it is to high generation runs slower.
    'maxSubgeneratorWeight': 1.0,
    # max final event weight which is always used. If this value is to low the
    # generation will produce errors. If it is to high generation runs slower.
    # ==> should be around 2-4
    'maxFinalWeight': 3.0,
    # adjust subgenerator weights so that each sub generator has same
    # probability to be called and the maximum weight is equal as well. These
    # values are printed at the end of generation when output level is set to
    # INFO. These weights strongly depend on the mode
    'subgeneratorWeights': [
        1.0,
        7.986e+01,
        5.798e+04,
        3.898e+05,
        1.0,
        1.664e+00,
        2.812e+00,
        7.321e-01,
    ],
    # set to awfully precise
    'suppressionLimits': [1e100] * 4,
    # minimum invariant mass of the secondary pair
    'minMass': 0.50,
})
aafh.logging.log_level = LogLevel.INFO

# preselection to reject no tag events
generatorpreselection = register_module('GeneratorPreselection')
generatorpreselection.param('nChargedMin', 1)
# generatorpreselection.param('nChargedMax', 999)
generatorpreselection.param('MinChargedP', 0.25)
generatorpreselection.param('MinChargedPt', 0.1)
generatorpreselection.param('MinChargedTheta', 17.)
generatorpreselection.param('MaxChargedTheta', 150.)
generatorpreselection.param('nPhotonMin', 1)
# generatorpreselection.param('nPhotonMax', 999)
generatorpreselection.param('MinPhotonEnergy', 0.50)
generatorpreselection.param('MinPhotonTheta', 15.)
generatorpreselection.param('MaxPhotonTheta', 170.)

# print generated particles
mcparticleprinter = register_module('PrintMCParticles')
mcparticleprinter.logging.log_level = LogLevel.INFO

output = register_module('RootOutput')
output.param('outputFileName', './aafh_out.root')

# creating the path for the processing
main.add_module(aafh)
main.add_module(generatorpreselection)
# create an empty path and check the return value of the the preselection
emptypath = create_path()
generatorpreselection.if_value('<1', emptypath)
# continue the main path otherwise (e.g. call detector simulation)
main.add_module(mcparticleprinter)
main.add_module(output)

# process the events
process(main)

# show call statistics
print(statistics)


# -*- coding: utf-8 -*-
import scrapy
from doubleScrapy.items import DoublescrapyItem

class DoubanSpiderSpider(scrapy.Spider):
    name = 'douban_spider'  #爬虫名字
    allowed_domains = ['movie.douban.com']  # 允许的域名
    start_urls = ['https://movie.douban.com/top250'] # 入口url，丢到调度里去

    def parse(self, response):
        """对请求回来的信息进行解析"""
        movieList = response.xpath("//div[@class='article']//ol[@class='grid_view']/li")
        for item in movieList:
            douban_item = DoublescrapyItem()
            douban_item['serial_number'] = item.xpath(".//div[@class='item']//em/text()").extract_first()
            douban_item['movie_name'] = item.xpath(".//div[@class='info']/div[@class='hd']/a/span[1]/text()").extract_first()
            douban_item['introduce'] = item.xpath(".//div[@class='item']//em/text()").extract_first()
            douban_item['star'] = item.xpath(".//div[@class='item']//em/text()").extract_first()
            douban_item['evaluate'] = item.xpath(".//div[@class='item']//em/text()").extract_first()
            douban_item['describe'] = item.xpath(".//div[@class='item']//em/text()").extract_first()

            print(douban_item)


#!/usr/bin/env python2
__author__ = 'Will Rowe'
__mail__ = "will.rowe@liverpool.ac.uk"

# Install a project in editable mode
# pip install -e . --user

from setuptools import setup

setup(
    name = "rnaseq",
    version = '0.1.0',
    packages = ["rnaseq"],
    author = 'Will Rowe',
    author_email = 'will.rowe@liverpool.ac.uk',
    url = 'http://will-rowe.github.io/',
    description = 'RNA-seq analysis pipeline for the Hinton Lab, Liverpool, UK',
    long_description = open('README.md').read(),
    package_dir = {'rnaseq': 'scripts'},
    scripts = ['scripts/dupRadar.sh'
    ],
    entry_points = {
        "console_scripts": ['rnaseq = rnaseq.rnaseq:main']
        },
    license = 'license.txt',
    install_requires = [
        "numpy == 1.7.0",
        "matplotlib == 1.5.3",
        "Jinja2 == 2.7.3",
        "MarkupSafe == 0.23",
        # the commandline executable multiqc needs to be installed and in path
        #"multiqc == 0.8",
    ],
)


SERVO_COUNT=5
ARM_STEP=1
ARM_DELAY=0.2

ARDUINO_LINUX_PORT='/dev/ttyACM0'
ARDUINO_WINDOWS_PORT='COM4'

ARM_BASE = 4
ARM_SHOULDER = 5
ARM_ELBOW = 6
ARM_WRIST = 7
ARM_GRIPPER = 8

BASE_START=150
SHOULDER_START = 80
ELBOW_START = 140
WRIST_START = 145
GRIPPER_START = 0

DIRECT_STEP=2


import pytest

from ldndctools.misc.calculations import calc_hydraulic_properties
from ldndctools.misc.errors import ParameterMissingError
from ldndctools.misc.types import LayerData

def test_basic_computation():
    ld = LayerData(sand=0.1, clay=0.3, corg=0.05, bd=1.2)
    ld = calc_hydraulic_properties(ld)
    assert ld.wcmin == pytest.approx(295.35934)
    assert ld.wcmax == pytest.approx(472.21525)

def test_raise_for_missing_parameter():
    ld = LayerData(sand=0.1, clay=0.3, corg=0.05)
    with pytest.raises(ParameterMissingError):
        calc_hydraulic_properties(ld)

@pytest.mark.skip(
    reason="no way of currently testing this, wcmin corrected atm (check with David)"
)
def test_raise_for_bad_wcmin_wcmax():
    ld = LayerData(sand=0.1, clay=0.3, corg=1.0, bd=1.2)
    with pytest.raises(ValueError):
        calc_hydraulic_properties(ld)


import h5py
import numpy as np

from mvpa2.base.collections import SampleAttributesCollection, \
     DatasetAttributesCollection, FeatureAttributesCollection

from pyitab.utils.bids import get_dictionary
from scipy.io import loadmat

def load_hcp_motor(filename, **kwargs):

    targets = {
        1: 'LH',
        2: 'LF',
        4: 'RH',
        5: 'RF',
        6: 'FIX'
    }

    mat = h5py.File(filename)
    data = mat['powerbox'][:]
    data /= np.nanmean(data)
    # Trials x Sources x Times
    data = np.float32(data.swapaxes(1, 2))

    labels = [targets[t] for t in mat['trialvec'][:][0]]
    limb = [t[1] for t in labels]
    side = [t[0] for t in labels]

    times = mat['timevec'][:].squeeze()
    rt = mat['trailinfo'][:][5]
    subject = kwargs['subject']

    sa_dict = get_dictionary(filename)
    sa_dict.pop('extension')
    sa_dict.pop('filename')
    sa = {k: [v for _ in range(rt.shape[0])] for k, v in sa_dict.items()}

    sa.update({'targets': labels,
               'chunks': np.arange(rt.shape[0]),
               'limb': limb,
               'side': side,
               'rt': rt,
               'subject': [subject for _ in range(rt.shape[0])],
               'file':   [filename for _ in range(rt.shape[0])]
               })

    sa = SampleAttributesCollection(sa)

    a = DatasetAttributesCollection({'times': times})
    fa = FeatureAttributesCollection({'matrix_values': np.ones(data.shape[1])})

    mat.close()

    return data, sa, a, fa

def load_hcp_blp(filename, **kwargs):
    mat = loadmat(filename)
    data = mat['data']

    parcels = data.shape[0]

    data = data[np.triu_indices(data.shape[0], k=1)]
    data = np.expand_dims(data, axis=0)

    subject = kwargs['subject']

    sa_dict = get_dictionary(filename)
    sa_dict.pop('extension')
    sa_dict.pop('filename')
    sa = {k: [v for _ in range(data.shape[0])] for k, v in sa_dict.items()}

    mainbands = ['alpha', 'beta', 'gamma']
    sa['mainband'] = np.zeros_like(sa['band'])
    for band in mainbands:
        mask = [band in dsband for dsband in sa['band']]
        sa['mainband'][mask] = band

    maintask = {'task1':  'LH',
                'task2':  'LF',
                'task4':  'RH',
                'task5':  'RF',
                'task14': 'AH',
                'task25': 'AF',
                'rest':   'NN'
                }

    for i, k in enumerate(['side', 'maintask']):
        sa[k] = [maintask[t][i] for t in sa['task']]

    sa.update({
               'subject': [subject for _ in range(data.shape[0])],
               'file':   [filename for _ in range(data.shape[0])]
               })

    idx_from, idx_to = np.triu_indices(parcels, k=1)

    labels = np.recfromcsv("/media/robbis/DATA/meg/viviana-hcp/atlas.csv")
    args = np.argsort(labels['node'])
    labels = labels[args]

    nodes_from = [labels[i]['abbr'].decode().strip() for i in idx_from]
    nodes_to = [labels[i]['abbr'].decode().strip() for i in idx_to]
    networks = ["%s+%s" %(nodes_from[i], nodes_to[i]) for i in range(len(nodes_to))]

    fa = dict(
        nodes_1=nodes_from,
        nodes_2=nodes_to,
        networks=networks,
        matrix_values=np.ones(data.shape[1])
    )

    fa = FeatureAttributesCollection(fa)
    a = DatasetAttributesCollection({})

    return data, sa, a, fa


# Python Script Created by MRS
import json
from typing import Tuple

async def japan_ship(
        name: str
    ) -> Tuple[str, str, str]:
    """
    重樱船名对照
    :param name:船名
    :return:和谐名,中文原名,拼音
    """
    with open("./data/azurlane/data/japan_ship_name.json", "r", encoding="utf-8") as f:
        cot: dict = json.load(f)
    if(cot.get(name) is not None):
        return (name, cot.get(name)["ori"], cot.get(name)["pinyin"])
    else:
        for v in cot.keys():
            if(cot.get(v)["ori"] == name):
                return (v, cot.get(v)["ori"], cot.get(v)["pinyin"])
        raise Exception("未找到该船名信息")