import time
import torch
from torch import nn, optim

import sys
#sys.path.append("..")
import utils as d2l
device = torch.device('cuda' if torch.cuda.is_available() else 'cpu')
import torch.nn.functional as F

def scale(x, y):#x:(B*C*T*H*W);y=(B*C)
    x = x.permute(2, 3, 4, 0, 1)
    y = y.squeeze()
    z = x * y
    z = z.permute(3, 4, 0, 1, 2)
    return z

class GlobalAvgPool3d(nn.Module):
    # 全局平均池化层可通过将池化窗口形状设置成输入的高和宽实现
    def __init__(self):
        super(GlobalAvgPool3d, self).__init__()
    def forward(self, x):
        return F.avg_pool3d(x, kernel_size=x.size()[2:])

class FlattenLayer(torch.nn.Module):
    def __init__(self):
        super(FlattenLayer, self).__init__()
    def forward(self, x): # x shape: (batch, *, *, ...)
        return x.view(x.shape[0], -1)

class MRST(nn.Module):
    def __init__(self, in_channels, mid_channels, out_channels, use_conv_x=False, stride=1):
        super(MRST, self).__init__()
        self.bottleneck_1 = nn.Conv3d(in_channels, mid_channels, kernel_size=1, padding=0, stride=1)
        self.conv_s = nn.Conv3d(mid_channels, mid_channels, kernel_size=(1,3,3), padding=(0,1,1), stride=stride)
        self.conv_t = nn.Conv3d(mid_channels, mid_channels, kernel_size=(3,1,1), padding=(1,0,0), stride=stride)
        self.conv_ss = nn.Conv3d(mid_channels, mid_channels, kernel_size=1, padding=0)
        self.conv_st = nn.Conv3d(mid_channels, mid_channels, kernel_size=1, padding=0)
        self.conv_ts = nn.Conv3d(mid_channels, mid_channels, kernel_size=1, padding=0)
        self.conv_tt = nn.Conv3d(mid_channels, mid_channels, kernel_size=1, padding=0)
        self.bottleneck_2 = nn.Conv3d(mid_channels, out_channels, kernel_size=1, padding=0, stride=1)
        if use_conv_x:
            self.conv_x = nn.Conv3d(in_channels, out_channels, kernel_size=1, stride=stride)
        else:
            self.conv_x = None

        self.bn_s = nn.BatchNorm3d(mid_channels)
        self.bn_t = nn.BatchNorm3d(mid_channels)

    def forward(self, X):
        X_ = F.relu(self.bottleneck_1(X))
        S = F.relu(self.bn_s(self.conv_s(X_)))
        T = F.relu(self.bn_t(self.conv_t(X_)))
        S_m = self.conv_ss(S) + self.conv_ts(T)
        T_m = self.conv_ts(S) + self.conv_tt(T)
        s_a = torch.sigmoid(F.avg_pool3d(S_m, kernel_size= S_m.size()[2:]))
        t_a = torch.sigmoid(F.avg_pool3d(T_m, kernel_size= T_m.size()[2:]))
        S = scale(S, s_a)
        T = scale(T, t_a)
        Y = self.bottleneck_2(F.relu(S + T))
        if self.conv_x:
            X = self.conv_x(X)
        return F.relu(Y + X)

def resnet_block(in_channels, mid_channels, out_channels, num_residuals):
    blk = []
    for i in range(num_residuals):
        if i == 0:
            blk.append(MRST(in_channels, mid_channels, out_channels, use_conv_x=True, stride=2))
        else:
            blk.append(MRST(out_channels, mid_channels, out_channels))
    return nn.Sequential(*blk)

net = nn.Sequential(
        nn.Conv3d(1, 64, kernel_size=(3,7,7), stride=(1,2,2), padding=(1,3,3)),
        nn.BatchNorm3d(64),
        nn.ReLU(),
        nn.MaxPool3d(kernel_size=(3,3,3), stride=(1,2,2), padding=(1,1,1)))

net.add_module("resnet_block1", resnet_block(64, 64, 256, 3))
net.add_module("resnet_block2", resnet_block(256, 128, 512, 4))
net.add_module("resnet_block3", resnet_block(512, 256, 1024, 6))
net.add_module("resnet_block4", resnet_block(1024, 512, 2048, 3))

net.add_module("global_avg_pool", GlobalAvgPool3d()) # GlobalAvgPool2d的输出: (Batch, 512, 1, 1)
net.add_module("fc", nn.Sequential(FlattenLayer(), nn.Linear(2048, 10)))

X = torch.rand((2, 1, 16, 224, 224))
for name, layer in net.named_children():
    X = layer(X)
    print(name, ' output shape:\t', X.shape)


# Definition for singly-linked list.
# class ListNode:
#     def __init__(self, x):
#         self.val = x
#         self.next = None

class Solution:
    def hasCycle(self, head: ListNode) -> bool:

        fast=head
        slow=head

        if head==None or head.next==None or head.next.next==None:
            return False
        else:
            while(fast.next!=None and fast!=None and fast.next.next!=None):
                fast=fast.next.next
                slow=slow.next

                if fast==slow:
                    return True
            return False


# 햄버거 만들기 문제

# 스택 자료구조 활용

def solution(ingredient):
    answer = 0
    stack = []
    make_order = [1,2,3,1]

    for ing in ingredient:
        stack.append(ing) # 스택에 값을 하나씩 넣어준다.
        if stack[-len(make_order):] == make_order: # LIFO - 맨 뒤에서부터 역순으로 읽었을 때 값이 동일한지 확인
            # stack = stack[:-4]는 해당 인덱스만큼 자른 뒤, 배열을 새로 할당해야하기 때문에 시간 초과가 발생한다.
            del stack[-4:] # del은 있는 stack의 길이에서 뒤에 4개만 자르기 때문에 O(N) 만큼 소요
            # stack.pop() # pop() - 뒤에서 꺼내는 경우 O(1) 시간 복잡도 - 즉 O(N)만큼의 시간이 소요된다.
            # stack.pop()
            # stack.pop()
            # stack.pop()
            answer += 1 # 햄버거 추가

    return answer

# 다른 풀이 방식

# def solution(ingredients):
#     answer = 0
#     stack = []

#     for ingredient in ingredients:
#         if ingredient == 1 and stack[-3:] == [1, 2, 3]:
#             # del stack[-3:]
#             stack.pop()
#             stack.pop()
#             stack.pop()

#             answer += 1
#         else:
#             stack.append(ingredient)

#     return answer

print(solution([2, 1, 1, 2, 3, 1, 2, 3, 1]))
print(solution([1, 3, 2, 1, 2, 1, 3, 1, 2]))


import pandas as pd
from apps.cities.controlers import get_big_cities
from apps.cities.models import City
from apps.cities.utils import alter_insee_city_district
from settings import SCHOOL_FILE

from .models import School

def store_school_results():
    # On ouvre le fichier des résultats scolaires
    school_results = (
        alter_insee_city_district(
            pd.read_csv(
                SCHOOL_FILE,
                error_bad_lines=False,
                sep=";",
                low_memory=False,
                usecols=["Taux Brut de Réussite Total séries", "Taux_Mention_brut_toutes_series", "Code commune"],
            ),
            "Code commune",
        )
        .groupby(["Code commune"])
        .mean()
        .reset_index()
    )

    # Fusionne le tableau des résultats avec les grandes villes
    school_df = pd.merge(get_big_cities(), school_results, left_on="ville_code_commune", right_on="Code commune")

    # Calcule le score global (moyenne du taux de réussite et taux de mentions)
    school_df["school_score"] = (
        school_df["Taux_Mention_brut_toutes_series"] + school_df["Taux Brut de Réussite Total séries"]
    ) / 2

    school_df = school_df.rename(
        columns={
            "Code commune": "city_id",
            "school_score": "score",
            "Taux_Mention_brut_toutes_series": "taux_mention",
            "Taux Brut de Réussite Total séries": "taux_reussite",
        }
    )[["city_id", "score", "taux_mention", "taux_reussite"]]

    School.delete().execute()
    school_df = school_df.sort_values(by=["score"], ascending=False)[school_df["score"].notnull()]
    School.insert_many(list(school_df.to_dict("records"))).execute()

def get_school_results():
    return pd.DataFrame(School.select(City, School).join(City).dicts()).sort_values(by=["score"], ascending=False)


import operator
from functools import reduce
from operator import eq

class FairnessUtils:

    @classmethod
    def calculate_cond_probability(cls, data, ofs, givens):
        """ calculate conditional probability of 'ofs' given 'givens' """
        givens_conditions = []
        ofs_conditions = []
        for of in ofs:
            ofs_conditions.append(eq(data.df[of[0]], of[1]))
        for given in givens:
            givens_conditions.append(eq(data.df[given[0]], given[1]))
            ofs_conditions.append(eq(data.df[given[0]], given[1]))

        ofs_logical_conditions = reduce(operator.and_, ofs_conditions)
        givens_logical_conditions = reduce(operator.and_, givens_conditions)

        set_ofs_inter_givens = data.df.loc[ofs_logical_conditions]
        card_ofs_inter_givens = len(set_ofs_inter_givens.index)
        set_givens = data.df.loc[givens_logical_conditions]
        card_givens = len(set_givens.index)
        result = card_ofs_inter_givens / card_givens
        return result


"""
Created on Thu Oct 24 11:44:50 2019

@author: Julia
"""

import pandas as pd
import numpy as np
from collections import defaultdict, Counter
import logging

from pyteomics import mass
try:
    from pyteomics import cmass
except ImportError:
    cmass = mass
import string
from . import utils, io

logger = logging.getLogger(__name__)

def get_theor_spectrum(peptide, acc_frag, ion_types=('b', 'y'), maxcharge=1,
    aa_mass=mass.std_aa_mass, modifications=None, **kwargs):
    """
    Calculates theoretical spectra in two ways: usual one and in integer format (mz / frag_acc).

    Parameters
    ----------
    peptide : list
        Peptide sequence.
    acc_frag : float
        Fragment mass accuracy in Da.
    ion_types : tuple
        Fragment ion types. ('b', 'y')
    maxcharge: int
        Maximum charge of fragment ion.
    aa_mass: dict
        Amino acid masses
    modifications : dict or None
        Dict of modifications applied to peptide (int position -> float mass shift)

    Returns
    -------
    Returns spectrum in two ways (usual, integer). Usual is a dict with key [ion type, charge] and m/z as a value.
    Integer is a dict, where key is ion type and value is a set of integers (m/z / fragment accuracy).
    """
    if not isinstance(peptide, list):
        raise Exception('peptide is not a list: {!r}'.format(peptide))

    peaks = defaultdict(list)
    theor_set = defaultdict(list)
    aa_mass = aa_mass.copy()
    H = mass.nist_mass['H'][0][0]
    nterm_mod = aa_mass.pop('H-', H)
    OH = H + mass.nist_mass['O'][0][0]
    cterm_mod = aa_mass.pop('-OH', OH)
    if modifications is None:
        modifications = {}
    for ind, pep in enumerate(peptide[:-1]):
        for ion_type in ion_types:
            nterminal = ion_type[0] in 'abc'
            for charge in range(1, maxcharge + 1):
                if ind == 0:
                    if nterminal:
                        mz = cmass.fast_mass2(
                            pep, ion_type=ion_type, charge=charge,
                            aa_mass=aa_mass, **kwargs) + (nterm_mod - H + modifications.get(1, 0.)) / charge
                    else:
                        mz = cmass.fast_mass2(''.join(peptide[1:]), ion_type=ion_type, charge=charge,
                                             aa_mass=aa_mass, **kwargs) + (cterm_mod - OH) / charge + sum(
                                             val for key, val in modifications.items() if key > 1) / charge
                else:
                    if nterminal:
                        mz = peaks[ion_type, charge][-1] + (modifications.get(ind + 1, 0.) + aa_mass[pep]) / charge
                    else:
                        mz = peaks[ion_type, charge][-1] - (modifications.get(ind + 1, 0.) + aa_mass[pep]) / charge
                peaks[ion_type, charge].append(mz)
                theor_set[ion_type].append(int(mz / acc_frag))
    theor_set = {k: set(v) for k, v in theor_set.items()}
    # if modifications:
    #     utils.internal('aa_mass: %s', aa_mass)
    #     utils.internal('Theoretical spectrum with modifications: %s, %s, %s', peptide, modifications, peaks)
    return peaks, theor_set

def RNHS_fast(spectrum_idict, theoretical_set, min_matched, ion_types=('b', 'y')):
    """
    Matches experimental and theoretical spectra in int formats.

    Parameters
    ----------

    spectrum_idict : list
        Experimental spectrum in integer format.  Output of preprocess_spectrum.
    theoretical_set: dict
        A dict where key is ion type and value is a set of integers (m/z / fragment accuracy).
        Output of get_theor_spec function.
    min_matched : int
        Minumum peaks to be matched.
    ion_types : tuple
        Fragment ion types. ('b', 'y')

    Returns
    -------

    Number of matched peaks, score.

    """
    matched = []
    isum = 0
    for ion_type in ion_types:
        match = 0
        for ion in theoretical_set[ion_type]:
            if ion in spectrum_idict:
                match += 1
                isum += spectrum_idict[ion]
        matched.append(match)
    matched_approx = sum(matched)
    if matched_approx >= min_matched:
        return matched_approx, np.prod([np.math.factorial(m) for m in matched]) * isum
    else:
        return 0, 0

_preprocessing_cache = {}
def preprocess_spectrum(reader, spec_id, kwargs, acc=0.01):
    """
    Prepares experimental spectrum for matching, converts experimental spectrum to int format.
    Default settings for preprocessing : maximum peaks is 100, dynamic range is 1000.

    Parameters
    ----------
    reader : file reader
        Spectrum file reader
    spec_id : str
        Spectrum id.

    Returns
    -------
    List of experimental mass spectrum in integer format.
    """
    spectrum = _preprocessing_cache.setdefault((reader, spec_id), {})
    if spectrum:
        # logger.debug('Returning cached spectrum %s', spec_id)
        return spectrum
    # logger.debug('Preprocessing new spectrum %s', spec_id)
    original = reader[spec_id]
    maxpeaks = kwargs.get('maxpeaks', 100)
    dynrange = kwargs.get('dynrange', 1000)

    mz_array = original['m/z array']
    int_array = original['intensity array']
    int_array = int_array.astype(np.float32)

    if dynrange:
        i = int_array > int_array.max() / dynrange
        int_array = int_array[i]
        mz_array = mz_array[i]

    if maxpeaks and int_array.size > maxpeaks:
        i = np.argsort(int_array)[-maxpeaks:]
        j = np.argsort(mz_array[i])
        int_array = int_array[i][j]
        mz_array = mz_array[i][j]

    tmp = (mz_array / acc).astype(int)
    for idx, mt in enumerate(tmp):
        i = int_array[idx]
        spectrum[mt] = max(spectrum.get(mt, 0), i)
        spectrum[mt - 1] = max(spectrum.get(mt - 1, 0), i)
        spectrum[mt + 1] = max(spectrum.get(mt + 1, 0), i)
    return spectrum

def peptide_isoforms(peptide, m, sites, prev_aa, next_aa):
    """
    Parameters
    ----------
    peptide : list
        Peptide sequence
    m: modification label to apply
    sites : set
        Amino acids eligible for modification

    Returns
    -------
    set of lists

    """
    isoforms = []
    if ('N-term' in sites or 'Protein N-term' in sites and prev_aa == '-') and len(peptide[0]) == 1 and peptide[0] not in sites:
        isoforms.append((m + peptide[0],) + tuple(peptide[1:]))
    if ('C-term' in sites or 'Protein C-term' in sites and next_aa == '-') and len(peptide[-1]) == 1 and peptide[-1] not in sites:
        isoforms.append(tuple(peptide[:-1]) + (m + peptide[-1],))
    for ind, a in enumerate(peptide):
        if a in sites:
            isoforms.append(tuple(peptide[:ind]) + (m + a,) + tuple(peptide[ind + 1:]))
    return isoforms

def get_candidates_from_aastat(mass_shifts_table, labels, threshold=1.5):
    """
    Get localization candidates from amono acid statistics.

    Parameters
    ----------
    mass_shifts_table : DataFrame
        DF with amino acid statistics for all mass shifts.
    labels : list
        List of amino acids that should be considered.
    threshold : float
        Threshold to be considered as significantly changed.

    Results
    -------
    Series with mass shift as index and list of candidates as value.
    """

    df = mass_shifts_table.loc[:, labels]
    ms, aa = np.where(df > threshold)
    out = {ms: [] for ms in mass_shifts_table.index}
    for i, j in zip(ms, aa):
        out[df.index[i]].append(df.columns[j])
    return pd.Series(out)

def get_full_set_of_candidates(locmod_df):
    """
    Build list of dicts from all_candidates column taking into account the sums of modification.

    Parameters
    ----------
    locmod_df : DataFrame
        DF with candidates for mass shifts.
    Returns
    -------
    Series
    """
    out = defaultdict(list)
    for ind in locmod_df.index:
        out[ind].append({ind: locmod_df.at[ind, 'all candidates']})
        if isinstance(locmod_df.at[ind, 'sum of mass shifts'], list):
            for pair in locmod_df.at[ind, 'sum of mass shifts']:
                tmp_dict = {}
                tmp_dict[pair[0]] = locmod_df.at[pair[0], 'all candidates']
                if len(pair) > 1:
                    tmp_dict[pair[1]] = locmod_df.at[pair[1], 'all candidates']
                out[ind].append(tmp_dict)
    return pd.Series(out)

def localization_of_modification(ms_label, row, loc_candidates, params_dict, spectra_dict, mass_shift_dict):
    """
    Localizes modification for mass shift in a peptide.
    If two peptides isoforms have the same score, modification counts as 'non-localized'.

    Parameters
    ----------
    ms_label : str
        Label for considered mass shift.
    row : DataFrame row
        Data Frame row for filtered PSMs data.
    loc_candidates : list
        List of dicts with candidates for localization. locmod_df['loc candidates']
    params_dict : dict
        Dict with all parameters.
    spectra_dict : dict
        Keys are filenames and values are Pyteomics readers.
    sum_mod : bool
        True if sum of codifications should be considered.

    Returns
    -------
    Counter of localizations, top isoform, score difference
    """
    mass_dict_0 = mass.std_aa_mass.copy()
    mass_dict_0.update(params_dict['fix_mod'])
    peptide = params_dict['peptides_column']
    prev_aa = params_dict['prev_aa_column']
    next_aa = params_dict['next_aa_column']
    charge = row[params_dict['charge_column']]
    modif_labels = string.ascii_lowercase

    mod_dict = utils.get_var_mods(row, params_dict)
    loc_stat_dict = Counter()

    if params_dict['mzml_files']:
        scan = row[params_dict['spectrum_column']].split('.')[1].lstrip('0')
        spectrum_id = 'controllerType=0 controllerNumber=1 scan=' + scan
    else:
        spectrum_id = row[params_dict['spectrum_column']]
    exp_dict = preprocess_spectrum(spectra_dict[row['file']], spectrum_id, {}, acc=params_dict['frag_acc'],)

    top_score, second_score = 0, 0
    top_isoform = None
    top_terms = None
    for terms in loc_candidates:
        scores = []
        mass_dict = mass_dict_0.copy()
        isoform_part = []
        new_isoform_part = []
        i = 0
        isoforms = []
        sequences = []
        for _ms in terms:
            mod_aa = {modif_labels[i] + aa: mass_shift_dict[_ms] + mass_dict[aa] for aa in params_dict['labels']}
            mass_dict.update(mod_aa)
            mass_dict[modif_labels[i]] = mass_shift_dict[_ms]

            if not isoform_part:  # first modification within this shift (or whole shift)
                isoform_part += peptide_isoforms(list(row[peptide]), modif_labels[i], terms[_ms], row[prev_aa], row[next_aa])
                if _ms == ms_label:
                    # this is the whole-shift modification
                    isoforms += isoform_part
                elif len(terms) == 1:
                    # two equal mass shifts form this mass shift. Apply the second half
                    for p in isoform_part:
                        new_isoform_part += peptide_isoforms(p, modif_labels[i], terms[_ms], row[prev_aa], row[next_aa])
            else:
                # second mass shift
                for p in isoform_part:
                    new_isoform_part += peptide_isoforms(p, modif_labels[i], terms[_ms], row[prev_aa], row[next_aa])
            i += 1
        isoforms += new_isoform_part
        sequences = [list(x) for x in isoforms]
        # utils.internal('Generated %d isoforms for terms %s at shift %s', len(sequences), terms.keys(), ms_label)
        for seq in sequences:
            # utils.internal('seq = %s', seq)
            theor_spec = get_theor_spectrum(seq,
                params_dict['frag_acc'], maxcharge=charge, aa_mass=mass_dict, ion_types=params_dict['ion_types'], modifications=mod_dict)
            scores.append(RNHS_fast(exp_dict, theor_spec[1], params_dict['min_spec_matched'], ion_types=params_dict['ion_types'])[1])
        scores = np.array(scores)
        i = np.argsort(scores)[::-1]
        scores = scores[i]
        sequences = np.array(sequences)[i]
        if scores.size:
            if scores[0] > top_score:
                second_score = top_score
                top_score = scores[0]
                top_isoform = sequences[0]
                top_terms = terms
            if scores.size > 1 and scores[1] > second_score:
                second_score = scores[1]

    if top_isoform is None:
        return loc_stat_dict, None, None, None, None

    if any(all(sites <= {'C-term', 'N-term'} for sites in terms.values())
        for terms in loc_candidates):
        # utils.internal('Injecting unmodified spectra for %s', ms)
        unmod_spec = get_theor_spectrum(list(row[peptide]), params_dict['frag_acc'], maxcharge=charge,
            aa_mass=mass_dict_0, ion_types=params_dict['ion_types'], modifications=mod_dict)
        unmod_score = RNHS_fast(exp_dict, unmod_spec[1], params_dict['min_spec_matched'], ion_types=params_dict['ion_types'])[1]
    else:
        unmod_score = 0

    if top_score == second_score or top_score <= unmod_score:
        utils.internal('top score = %f, second score = %f, unmod score = %f', top_score, second_score, unmod_score)
        loc_stat_dict['non-localized'] += 1
        return loc_stat_dict, None, None, None, None

    mass_dict = mass_dict_0.copy()
    # utils.internal('Top isoform is %s for terms %s (shift %s)', top_isoform, top_terms, ms_label)
    i = 0
    for _ms in top_terms:
        mod_aa = {modif_labels[i] + aa: mass_shift_dict[_ms] + mass_dict[aa] for aa in params_dict['labels']}
        mass_dict.update(mod_aa)
        mass_dict[modif_labels[i]] = mass_shift_dict[_ms]
        i += 1
    for ind, a in enumerate(top_isoform):
        if len(a) > 1:
            if ind == 0:
                loc_stat_dict[utils.format_localization_key('N-term', mass_dict[a[0]])] += 1
            elif ind == len(top_isoform) - 1:
                loc_stat_dict[utils.format_localization_key('C-term', mass_dict[a[0]])] += 1
            loc_stat_dict[utils.format_localization_key(a[1], mass_dict[a[0]])] += 1

    scorediff = (top_score - second_score) / top_score
    top_i = ''.join(top_isoform)
    ret = loc_stat_dict, top_i, top_terms, scorediff, utils.loc_positions(top_isoform)
    utils.internal('Returning: %s', ret)

    return ret

def localization(data, ms_label, locations_ms, params_dict, spectra_dict):
    """
    Localizes modification or sum of modifications for mass shift and repeat localization if there are redundant candidates.
    If two peptide isoforms have the same max score, modification counts as 'non-localized'.

    Parameters
    ----------
    df : DataFrame
        DF with filtered peptides for considered mass shift.
    ms: float
        mass shift
    ms_label : str
        Considered mass shift label
    locations_ms :
       locmod_df['loc candidates']
    params_dict : dict
        Dict with all paramenters.
    spectra_dict : dict
        Keys are filenames and values are Pyteomics readers.

    Returns
    -------
    Counter of localizations.
    """
    logger.info('Localizing %s...', ms_label)
    logger.debug('Localizations: %s', locations_ms)
    df = data.mass_shift(ms_label)
    mass_shift_dict = {k: v[0] for k, v in data.ms_stats().items()}
    if len(locations_ms) < 2 and list(locations_ms[0].values())[0] == set():
        df['localization_count'], df['top isoform'], df['top_terms'], df['localization score'], df['loc_position'] = None, None, None, None, None
    else:
        z = list(zip(*df.apply(lambda x: localization_of_modification(
                    ms_label, x, locations_ms, params_dict, spectra_dict, mass_shift_dict), axis=1)))
        utils.internal('z: %s', z)
        names = ['localization_count', 'top isoform', 'top_terms', 'localization score', 'loc_position']
        dt = {'localization score': np.float32}
        for c, v in zip(names, z):
            t = dt.get(c, np.object_)
            # utils.internal('Saving %s as %s...', c, t)
            shape = (len(v), )
            value = np.empty(shape, t)
            value[:] = v
            # utils.internal('Value: %s', value)
            df[c] = value
    fname = io.table_path(params_dict['output directory'], ms_label)
    peptide = params_dict['peptides_column']

    mod_aa = string.ascii_lowercase
    mod_dicts = {}
    for pair in locations_ms:
        labels_mod = {}
        i = 0
        for m in pair:
            labels_mod[mod_aa[i]] = m
            i += 1
        mod_dicts[tuple(sorted(pair))] = labels_mod
    columns = ['top isoform', 'localization score', params_dict['spectrum_column']]
    df['top isoform'] = df['top isoform'].fillna(df[peptide])
    df.loc[df.top_terms.notna(), 'mod_dict'] = df.loc[df.top_terms.notna(), 'top_terms'].apply(lambda t: mod_dicts[tuple(sorted(t))])
    df['top isoform'] = df.apply(utils.format_isoform, axis=1, args=(params_dict,))
    df[columns].to_csv(fname, index=False, sep='\t')
    data.set_ms_data(ms_label, df)
    result = df['localization_count'].sum() or Counter()
    logger.debug('Localization result for %s: %s', ms_label, result)
    return {ms_label: result}


# https://leetcode.com/problems/find-numbers-with-even-number-of-digits/

def evenDigit(arr):
    count = 0
    for ele in arr:
        if len(str(ele)) % 2 == 0:
            count += 1
    return count

nums = [12, 345, 21, 6, 7896]
print(evenDigit(nums))


from flask import json, Flask, render_template, url_for, request, session, redirect, make_response, flash, jsonify
from flask_socketio import SocketIO
from flaskext.mysql import MySQL

import bcrypt
from flask_pymongo import PyMongo
from pymongo import MongoClient

app = Flask(__name__, static_url_path='/static')

app.config['SECRET_KEY'] = 'jsbcfsbfjefebw237u3gdbdc'
socketio = SocketIO(app)
app.secret_key = "super secret key"
mysql = MySQL()

app.config['MYSQL_DATABASE_USER'] = 'root'
app.config['MYSQL_DATABASE_PASSWORD'] = '1234'
app.config['MYSQL_DATABASE_DB'] = 'Postlist'
app.config['MYSQL_DATABASE_HOST'] = 'localhost'
mysql.init_app(app)

connection = MongoClient('mongodb://localhost:27017/')
dbs = connection.chatbot
col_traindata = dbs.questiondata
col_answerdata = dbs.answerdata
col_user = dbs.users

app.config['MONGO_DBNAME'] = 'chatbot'
app.config['MONGO_URI'] = 'mongodb://localhost:27017/chatbot'

mongo = PyMongo(app)

@app.route('/index')
def index():
    list = mongo.db.questiondata.find().limit(10)
    return render_template('a.html', list = list)
app.run(debug=True)


from pprint import pprint
from math import sqrt

import matplotlib.pyplot as plt
import seaborn as sns

import pandas as pd
from pydataset import data
from statsmodels.formula.api import ols

def plot_residuals(x, y):
    '''
    Plots the residuals of a model that uses x to predict y. Note that we don't
    need to make any predictions ourselves here, seaborn will create the model
    and predictions for us under the hood with the `residplot` function.
    '''
    return sns.residplot(x, y)

def regression_errors(y, yhat):
    '''
    Returns a dictionary containing various regression error metrics.
    '''
    n = y.size
    residuals = yhat - y
    ybar = y.mean()

    sse = sum(residuals**2)

    ess = ((yhat - ybar)**2).sum()

    return {
        'sse': sse,
        'mse': sse / n,
        'rmse': sqrt(sse / n),
        'ess': ess,
        'tss': ess + sse,
    }

def baseline_mean_errors(y):
    '''
    Returns a dictionary containing various regression error metrics for a
    baseline model, that is, a model that uses the mean of y as the prediction.
    '''
    yhat = y.mean()
    n = y.size
    residuals = yhat - y

    sse = sum(residuals**2)

    return {
        'sse': sse,
        'mse': sse / n,
        'rmse': sqrt(sse / n),
    }

def better_than_baseline(y, yhat):
    '''
    Given the actual and predicted values, returns a boolean value indicating if
    the model's predictions are better than the baseline model.
    '''
    sse_baseline = baseline_mean_errors(y)['sse']
    sse_model = regression_errors(y, yhat)['sse']
    return sse_model < sse_baseline

def model_significance(model):
    '''
    Given a fitted OLS model from statsmodels, return the model's expanied
    variance, and the p-value indicating whether the relationship is
    significant.
    '''
    return {'r^2': model.rsquared, 'f p-value': model.f_pvalue}

if __name__ == '__main__':
    print('----> Loading tips data')
    tips = data('tips')

    print('----> Fitting OLS model')
    regr = ols('tip ~ total_bill', data=tips).fit()
    tips['yhat'] = regr.predict()

    print('----> Showing ressiduals for tip ~ total_bill')
    plot_residuals(tips.total_bill, tips.tip)
    plt.show()

    print('----> Error metrics for our model')
    pprint(regression_errors(tips.tip, tips.yhat))

    print('----> Baseline model error metrics')
    pprint(baseline_mean_errors(tips.total_bill))

    print('----> Is our model better than the baseline?')
    pprint(better_than_baseline(tips.total_bill, tips.yhat))

    print('----> Model significance metrics')
    regr = ols('tip ~ total_bill', tips).fit()
    pprint(model_significance(regr))


import csv
import os
import time
from datetime import datetime
from threading import Timer

import psutil

import Constants

class Logger:

    # Returns A List Of Programs Using A Memory threshold
    def get_active(self, threshold=None) -> list:
        if threshold is None:
            threshold = 1

        active_list = []
        skip_list = Constants.ignore_list

        for i in psutil.process_iter():

            # If An Important Program Is Assumed To Be Actively Running
            if i.memory_percent() > threshold and i.name() not in skip_list:
                active_list.append(i)

        # print(active_list)
        return active_list

    # Saves The Data Filtered From Dynamic or Threshold Functions To CSV Files
    def save_data(self, active_list):

        data_path = os.getcwd() + "//Data"  # CWD = Current Working Directory

        # Create The Data Folders And Files If They Don't Exist
        if not os.path.exists(data_path):
            try:
                os.mkdir(data_path)
            except (PermissionError, FileExistsError):
                pass

        csv_fields = ["Date", "Time"]  # Name Isn't Mentioned Here As It's In the File Name

        for i in active_list:

            program_path = data_path + "//" + i.name().split('.')[0] + ".csv"

            try:
                # Creates The CSV File If It Doesn't Exist
                if not os.path.exists(program_path):
                    with open(program_path, 'w') as temp_file:
                        writer = csv.writer(temp_file)
                        writer.writerow(csv_fields)
                        temp_file.close()

                # Lock The File Then Write The Data To The CSV File
                with open(program_path, 'a') as csv_file:
                    writer = csv.writer(csv_file, lineterminator='\n')
                    date = datetime.now().strftime('%Y-%m-%d')
                    time = datetime.now().strftime('%H:%M')
                    writer.writerow([date, time])
                    csv_file.close()
            except PermissionError:
                pass

    # The Thing That Get Called By Center Control
    def run(self):
        Timer(interval=60, function=self.run)
        self.save_data(self.get_active(threshold=0.25))

Logger().run()

while True:
    time.sleep(1)


import pandas as pd
import subprocess
import math

#INPUT_FILE = './flexABle/aba-tests/framework_goals.csv'
INPUT_FILE =  '/home/piotr/test/newest_ubuntu_data/Dresden/flexABle/aba-experiments-new/instances/benchmarks.csv'
OUTPUT_FILE = '/home/piotr/test/newest_ubuntu_data/Dresden/flexABle/aba-tests/aspforaba_results2.csv'

BASE_INSTANCES_PATH = ''
ADM_COLUMN_NAME = 'adm_result'
STB_COLUMN_NAME = 'stb_result'
BASH_SCRIPT = '/home/piotr/test/newest_ubuntu_data/Dresden/flexABle/aba-tests/solvers/aspforaba/run_asp.sh'

def get_asp_result(instance, goal, semantics):
    output = subprocess.check_output(
        args=[f'bash {BASH_SCRIPT} {instance} {goal} {semantics} 0'], shell=True, stderr=subprocess.STDOUT)
    split = output.decode().split()
    result = 'yes' if split[0] == 'SATISFIABLE' else 'no'
    duration = float(split[-1][:-1])
    return result, duration

def get_bar_text(sem, duration, res_str, satisfiable_count, i):
    sat_perc = int(float(satisfiable_count) / (i) * 100)
    return f'{sem}: Last: {duration}s\tResult: {res_str}\tSat. count: {satisfiable_count}/{i} [{sat_perc}%]'

if __name__ == '__main__':
    # input_df = pd.read_csv(INPUT_FILE)
    # total_size = len(input_df)
    # input_df.set_index(['instance','goal'], inplace=True)
    output_df = pd.DataFrame(columns=['instance', 'goal', 'adm_result', 'adm_duration', 'stb_result', 'stb_duration'])

    counter = 1
    with open(INPUT_FILE, 'r') as f:
        for line in f:
            line = ''.join(line.split())

            instance, stmts = line.split(',')
            for goal in stmts.split(';'):
                # print(f'{counter}/6800')
                counter += 1
                # admissible semantics
                adm_result, adm_duration = get_asp_result(
                    instance, goal, 'adm')

                # stable semantics
                stb_result, stb_duration = get_asp_result(
                    instance, goal, 'stb')

                row_to_append = pd.DataFrame({
                    'instance': [instance],
                    'goal': [goal],
                    'adm_result': [adm_result],
                    'adm_duration': [adm_duration],
                    'stb_result': [adm_result],
                    'stb_duration': [adm_duration]
                })

                output_df = pd.concat([output_df, row_to_append], ignore_index=True)
        output_df.to_csv(OUTPUT_FILE)


import datetime
import uuid
from typing import Generator, List
from unittest import mock

import pytest
from pymongo.collection import Collection

from sched_slack_bot.data.mongo.mongo_schedule_access import MongoScheduleAccess
from sched_slack_bot.model.schedule import Schedule

@pytest.fixture()
def mocked_collection() -> mock.MagicMock:
    return mock.MagicMock(spec=Collection)

@pytest.fixture(autouse=True)
def mocked_mongo_client(mocked_collection: mock.MagicMock) -> Generator[mock.MagicMock, None, None]:
    with mock.patch("sched_slack_bot.data.mongo.mongo_schedule_access.MongoClient") as mocked_client:
        mocked_client.return_value.get_database.return_value.get_collection.return_value = mocked_collection
        yield mocked_client

@pytest.fixture()
def mongo_schedule_access() -> MongoScheduleAccess:
    return MongoScheduleAccess(mongo_url="mongodb://someUrl")

@pytest.fixture()
def schedules() -> List[Schedule]:
    return [
        Schedule(
            id=str(uuid.uuid4()),
            display_name="Rotation Schedule",
            members=["U1", "U2"],
            next_rotation=datetime.datetime.now().replace(microsecond=0) + datetime.timedelta(seconds=100),
            time_between_rotations=datetime.timedelta(hours=2),
            channel_id_to_notify_in="C1",
            created_by="creator",
        ),
        Schedule(
            id=str(uuid.uuid4()),
            display_name="Rotation Schedule 2",
            members=["U3", "U4"],
            next_rotation=datetime.datetime.now().replace(microsecond=0) + datetime.timedelta(seconds=200),
            time_between_rotations=datetime.timedelta(hours=4),
            channel_id_to_notify_in="C2",
            created_by="creator2",
        ),
    ]

def test_get_available_schedules(
    mocked_collection: mock.MagicMock, mongo_schedule_access: MongoScheduleAccess, schedules: List[Schedule]
) -> None:
    mocked_collection.find.return_value = [s.as_json() for s in schedules]
    assert mongo_schedule_access.get_available_schedules() == schedules

def test_get_schedule(
    mocked_collection: mock.MagicMock, mongo_schedule_access: MongoScheduleAccess, schedules: List[Schedule]
) -> None:
    mocked_collection.find_one.return_value = schedules[0].as_json()
    assert mongo_schedule_access.get_schedule(schedule_id=schedules[0].id) == schedules[0]

def test_get_schedule_none(
    mocked_collection: mock.MagicMock, mongo_schedule_access: MongoScheduleAccess, schedules: List[Schedule]
) -> None:
    mocked_collection.find_one.return_value = None
    assert mongo_schedule_access.get_schedule(schedule_id=schedules[0].id) is None

def test_update_schedule(
    mocked_collection: mock.MagicMock, mongo_schedule_access: MongoScheduleAccess, schedules: List[Schedule]
) -> None:
    mongo_schedule_access.update_schedule(schedule_id_to_update=schedules[0].id, new_schedule=schedules[0])

    mocked_collection.replace_one.assert_called_once_with(filter={"id": schedules[0].id}, replacement=schedules[0].as_json())

def test_delete_schedule(
    mocked_collection: mock.MagicMock, mongo_schedule_access: MongoScheduleAccess, schedules: List[Schedule]
) -> None:
    mongo_schedule_access.delete_schedule(schedule_id=schedules[0].id)

    mocked_collection.delete_one.assert_called_once_with({"id": schedules[0].id})

def test_save_schedule(
    mocked_collection: mock.MagicMock, mongo_schedule_access: MongoScheduleAccess, schedules: List[Schedule]
) -> None:
    mongo_schedule_access.save_schedule(schedule=schedules[0])

    mocked_collection.insert_one.assert_called_once_with(schedules[0].as_json())


import pygame
import pygame_gui
from game_board import CoordinatePlane
from User import User
from gui import GUIManager

WINDOW_WIDTH = 1000
WINDOW_HEIGHT = 1000

# Initialize Pygame, create a screen surface, and other necessary variables

pygame.init()
screen = pygame.display.set_mode((WINDOW_WIDTH, WINDOW_HEIGHT))
clock = pygame.time.Clock()

# Create instances of CoordinatePlane, User, and GUIManager
coordinate_plane = CoordinatePlane()
user = User("Player1")
gui_manager = GUIManager(WINDOW_WIDTH, WINDOW_HEIGHT)

# Assign cells to the user
coordinate_plane.assign_user_cells(user)

running = True
while running:
    time_delta = clock.tick(60) / 1000.0
    for event in pygame.event.get():
        if event.type == pygame.QUIT:
            running = False

        gui_manager.process_events(event)

        if event.type == pygame.MOUSEBUTTONDOWN:
            pos = pygame.mouse.get_pos()
            button = pygame.mouse.get_pressed()
            coordinate_plane.handle_mouse_down(
                pos, button[0], gui_manager, user)

    coordinate_plane.update(time_delta)
    gui_manager.update(time_delta)

    screen.fill((0, 0, 0))
    coordinate_plane.draw(screen)
    gui_manager.draw(screen)

    pygame.display.update()

pygame.quit()


import torch
import torch.nn as nn

def init(module, weight_init, bias_init, gain=1):
    weight_init(module.weight.data, gain=gain)
    bias_init(module.bias.data)
    return module

class FCGenerator(nn.Module):
    def __init__(self, init_var=0.1, num_p=2000):
        super(FCGenerator, self).__init__()
        init_ = lambda m: init(m, nn.init.orthogonal_, lambda x: nn.init.
                               uniform(x, -init_var / 2, init_var / 2), nn.init.calculate_gain('relu'))

        self.gen = nn.Sequential(
            init_(nn.Linear(1, num_p * 3)))

        self.input_data = torch.ones((1, 1)).cuda()

    def forward(self, input=None):
        x = self.gen(self.input_data)
        x = x.view(x.size(0), -1, 3)

        return x


#!/usr/bin/python

import serial
import time
import requests
import json
import sys

job_limit = 16
max_job = job_limit - 1

token = sys.argv[1]
url = 'https://circleci.com/api/v1.1/recent-builds?circle-token=' + token + '&limit=' + str(job_limit) + '&offset=0'
request_frequency = 15

s = None

color_map = {
              "running": "ltblue|breathe",
              "success": "green",
             "finished": "green",
                "fixed": "seafoam",
               "failed": "red",
             "no_tests": "gray",
              "retried": "yellow",
             "timedout": "yellow|blink",
             "canceled": "gray",
              "not_run": "gray",
               "queued": "purple|breathe",
            "scheduled": "purple",
          "not_running": "pink",
              "missing": "gray",
               "spacer": "black",
         "masterfailed": "red|blink",
          "masterfixed": "green|blink",
  "infrastructure_fail": "pink"
}

inter_command_delay = 0.02

def command(cmd_text):
  s.write((cmd_text + '|').encode())
  time.sleep(inter_command_delay)

def get_color_cmd(color_cmd_text):
  if color_cmd_text is None:
    return "missing"
  else:
    return color_map.get(color_cmd_text, "black")

def color_command(color_cmd_text):
  color_cmd = get_color_cmd(color_cmd_text)
  command(color_cmd)

def color_command3(color_cmd_text):
  color_cmd = get_color_cmd(color_cmd_text)
  for i in range(0, 3):
    command(color_cmd)

def spacer():
  color_command("spacer")

def fix_missing(value):
  if value is None:
    return "missing"
  else:
    return value

def setup():
  global s
  s = serial.Serial("/dev/ttyS0", 57600)
  command("erase")

def loop():
  r = requests.get(url)
  r = r.text.encode('utf-8')
  j = json.loads(r)

  command("pause");

  for x in range(0, job_limit):
    st = fix_missing(j[x]['status'])
    lc = fix_missing(j[x]['lifecycle'])
    oc = fix_missing(j[x]['outcome'])
    br = j[x]['branch']
    rp = j[x]['reponame']
    master = br == 'master'
    orders = rp == 'orders'
    orders_master = master and orders
#    print "st:\t" + st + "\tlc:\t" + lc + "\toc:\t" + oc + "\tbr:\t" + br + "\trp:\t" + rp

    if st == 'failed':
      if orders_master:
        color_command3('masterfailed')
      else:
        color_command3('failed')
    elif st == 'success':
      color_command3('success')
    elif st == 'running':
      color_command3('running')
    elif st == 'fixed':
      if orders_master:
        color_command3('masterfixed')
      else:
        color_command3('fixed')
    elif oc == 'infrastructure_fail':
      color_command3('infrastructure_fail')
    else:
        color_command(st)
        color_command(oc)
        color_command(lc)
    spacer()

  command("continue");
  command("flush");
  time.sleep(request_frequency)

if __name__ == '__main__':
  setup()
  while True:
    loop()


from django.urls import path
from . import views

urlpatterns = [
    # здесь должен быть path(), который
    # при обращении к странице /useful/
    # вызовет функцию useful_function_list() из views.py
    # # [примечание] при include запрошенный URL в присоединяемом файле
    # указывается не полностью
    path('', views.useful_functions_list),
    path('ReplaceIt', views.replaceit),
    path('Magic', views.magic),
]


import selenium
from selenium import webdriver
from time import sleep

class YoutubeBot:

    def __init__(self, driver_name):

        if driver_name.lower() == "firefox":
                # driver for firefox
                self.driver = webdriver.Firefox()

        sleep(0.5)
        self.driver.get("https://www.youtube.com")

    def search(self, name):

        search_box = self.driver.find_element_by_xpath("//input[@id='search']")
        search_box.send_keys(name)

        sleep(0.5)
        search_btn = self.driver.find_element_by_xpath("//button[contains(@id, 'search')]")
        search_btn.click()

    # this method is cap-sensitive and only choose the first one that matches xpath query
    # there's stil some problems with xpath queries using the the hyphen ("-") character
    def click_on_vid(self, video_name, channel_name=""):

        try:

            if channel_name == "":
                video = self.driver.find_element_by_xpath(f"//a[contains(@aria-label, '{video_name}')]")
            else:
                video = self.driver.find_element_by_xpath(f"//a[contains(@aria-label, '{video_name} by {channel_name}')]")
            video.click()

        except(selenium.common.exceptions.NoSuchElementException):
            print("The video specified is not found")

    def refresh(self):
        self.driver.refresh()


import discord
import asyncio
from datetime import datetime,timedelta
from discord.utils import get
from discord.ext import commands
from bfunc import roleArray, calculateTreasure, timeConversion

class Apps(commands.Cog):
    def __init__ (self, bot):
        self.bot = bot

    @commands.group()
    async def app(self, ctx):
        pass

    @app.command()
    @commands.has_any_role('Mod Friend', 'A d m i n')
    async def edit(self, ctx, num, *, editString=""):
        # The Bot
        botUser = self.bot.get_user(566024681824452619)
        # App Logs channel
        channel = self.bot.get_channel(388591318814949376)

        msgFound = False
        async with channel.typing():
            async for message in channel.history(oldest_first=False):
                if int(num) == message.id and message.author == botUser:
                    editMessage = message
                    msgFound = True
                    break

        if not msgFound:
            delMessage = await ctx.channel.send(content=f"I couldn't find message {num}. Please try again. I will delete your message and this one in 10 seconds.")
            await asyncio.sleep(10)
            await delMessage.delete()
            await ctx.message.delete()
            return

        botEmbed = editMessage.embeds[0]
        botEmbed.set_footer(text=f"Application Message ID: {editMessage.id}\nMod: {ctx.author}")

        await editMessage.edit(content=editString, embed=botEmbed)
        delMessage = await ctx.channel.send(content=f"I have edited the message {num}.\n```{editString}```\nPlease double check that the edit is correct. I will now delete your message and this one in 30 seconds.")
        await asyncio.sleep(30)
        await delMessage.delete()
        await ctx.message.delete()
        await editMessage.clear_reactions()

    @commands.Cog.listener()
    async def on_message(self,msg):
        def msgCheck(m):
            sameMessage = False
            appDict = botMsg.embeds[0].to_dict()
            appNum = appDict['title'].split('#')[1]
            if appNum in m.content:
                sameMessage = True

            return ('approve #' in m.content.lower() or 'deny #' in m.content.lower() or 'under17 #' in m.content.lower()) and sameMessage

        # appchannel
        channelID = 388591318814949376
        channel = self.bot.get_channel(channelID)
        guild = msg.guild
        if channel and channel.id == channelID and msg.author.name == 'Application Bot Friend':
            botEmbed = msg.embeds[0]
            botMsg = await channel.send(embed=botEmbed)
            await msg.delete()

            mMessage = await self.bot.wait_for("message", check=msgCheck)

            appDict = botMsg.embeds[0].to_dict()
            appNum = appDict['title'].split('#')[1]
            appDiscord = appDict['fields'][0]['value']
            appHash = appDiscord.split('#')[1]
            appAge = appDict['fields'][1]['value']
            appMember = guild.get_member_named(appDiscord)
            botEmbed.set_footer(text=f"Application Message ID: {botMsg.id}\nMod: {mMessage.author}")

            if appMember is None:
                ctx.channel.send(content=f"Something went wrong. The application could not find the discord name {appDiscord} for application {appNum}. Please delete this message once this is resolved.")
                return

            if 'approve' in mMessage.content:
                # Session Channel
                sessionChannel = self.bot.get_channel(382045698931294208)
                await botMsg.edit(embed=botEmbed, content=f"{appNum}. {appMember.mention} #{appHash} - **Approved**")
                await botMsg.clear_reactions()
                await mMessage.delete()

                if int(appAge) < 18:
                    kidRole = get(guild.roles, name = 'Under-18 Friendling')
                    await appMember.add_roles(kidRole, reason="Approved application - the user is under 18.")

                limit = 100
                playedGame = False
                async for message in sessionChannel.history(limit=limit, oldest_first=False):
                    if appMember.mentioned_in(message):
                        playedGame = True
                        juniorRole = get(guild.roles, name = 'Junior Friend')

                        await appMember.add_roles(juniorRole, reason=f"Approved application - the user has played at least one quest. I have checked the last {limit} session logs.")
                        break

                newRole = get(guild.roles, name = 'D&D Friend')
                await appMember.add_roles(newRole, reason=f"Approved application - the user has been given the base role.")

                await appMember.send(f"Hello, {appMember.name}!\n\nThank you for applying to **D&D Friends**! The Mod team has approved your application and you have been assigned the appropriate roles.\n\nIf you have any further questions then please don't hesitate to ask in our #help-for-players channel or message a Mod Friend!")

            elif 'deny' in mMessage.content:
                await botMsg.edit(embed=botEmbed, content=f"{appNum}. {guild.get_member_named(appDiscord).mention} #{appHash} - **Denied** (Did not read server rules)")
                await botMsg.clear_reactions()
                await mMessage.delete()
                await appMember.send(f"Hello, {appMember.name}!\n\nThank you for applying to **D&D Friends**! Unfortunately, the Mod team has declined your application since you did not read the server rules or did not agree to abide by them. If you have any questions or inquiries, please direct them to our Reddit or Twitter accounts:\nReddit - <https://www.reddit.com/user/DnDFriends/>\nTwitter - <https://twitter.com/DnD_Friends>\n\nWe hope you find other like-minded people to play D&D with. Good luck!")

            elif 'under17' in mMessage.content:
                await botMsg.edit(embed=botEmbed, content=f"{appNum}. {guild.get_member_named(appDiscord).mention} #{appHash} - **Denied** (Under 17)")
                await botMsg.clear_reactions()
                await mMessage.delete()
                await appMember.send(f"Hello, {appMember.name}!\n\nThank you for applying to **D&D Friends**! Unfortunately, the **D&D Friends** Mod team has declined your application since you did not meet the cut-off age. If you have any questions or inquiries, please direct them to our Reddit or Twitter accounts:\nReddit - <https://www.reddit.com/user/DnDFriends/>\nTwitter - <https://twitter.com/DnD_Friends>\n\nWe hope you find other like-minded people to play D&D with. Good luck!")

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


#!/usr/bin/env python3

import sys

## Quick sort - pivot
## Recursive algo
## A pivot is simply one of the elements - usually the first or last element
## Select a "low" and "high" - usually the second element and the last element respectively
## Increment "low" till you find a value greater than pivot and stop it there
## Decrement "high" till you find a value lower than pivot
## Swap the position of values for both low and high and continue
## Once the high < low, swap high with pivot and then break into partitions
### In this exercise, during the initial iteration:
####  arr[0] - pivot, arr[1] - low, len(arr)-1: high

def partition(elements, low, high, pivot_element):
  if pivot_element == "first":
    pivot = low - 1
  elif pivot_element == "last":
    pivot = high + 1

  while True:

    ## Move low until you find a number greater than pivot
    while elements[low] < elements[pivot]:
      low = low + 1
      if low >= high: break

    ## Move high until you find a number less than pivot
    ## high>low is required so as to not decrement when low
    ## and high are the same
    while elements[high] > elements[pivot]:
      if (pivot_element == "last" and high > low) or (pivot_element == "first"):
        high = high - 1
      if high <= low: break

    if high <= low:
      elements[high], elements[pivot] = elements[pivot], elements[high]
      return high
    else:
      elements[high], elements[low] = elements[low], elements[high]

def quick_sort(elements, low, high, pivot_element):
  if low <= high:
    pivot_position = partition(elements, low, high, pivot_element)

    if pivot_element == "first":
      quick_sort(elements, low, pivot_position-1, pivot_element)
      quick_sort(elements, pivot_position+2, high, pivot_element)
    elif pivot_element == "last":
      quick_sort(elements, low, pivot_position-2, pivot_element)
      quick_sort(elements, pivot_position+1, high, pivot_element)

if __name__=="__main__":
  elements = [ int(x) for x in sys.argv[1:] ]
  #print(elements)
  #quick_sort(elements, 1, len(elements)-1, "first")
  quick_sort(elements, 0, len(elements)-2, "last")
  print("After sorting:", elements)


import collections
import functools
import xml.dom.minidom

import dbus

import qui.models.base
from typing import Any, Callable, Dict, Union

OBJECT_MANAGER_INTERFACE = 'org.freedesktop.DBus.ObjectManager'
PROPERTIES_INTERFACE = 'org.freedesktop.DBus.Properties'
PROPERTIES_CHANGED = 'PropertiesChanged'

_DictKey = Union[str, dbus.String]  # pylint: disable=invalid-name,no-member

class Interface(qui.models.base.Interface):
    ''' Represents a D-Bus Interface '''

    # pylint: disable=too-few-public-methods
    def __init__(self, node: xml.dom.minidom.Element) -> None:
        name = _name(node)
        signals = {
            _attr(signal_node, 'name'): qui.models.base.Signal(signal_node)
            for signal_node in _children(node, 'signal')
        }
        methods = {
            _attr(method_node, 'name'): qui.models.base.Method(method_node)
            for method_node in _children(node, 'method')
        }
        super(Interface, self).__init__(name, methods, signals)

class Model(qui.models.base.Model):
    ''' Wrapper around the `dbus.proxies.ProxyObject`.  '''

    # pylint: disable=too-few-public-methods

    def __init__(self, proxy: dbus.proxies.ProxyObject) -> None:  # pylint: disable=no-member
        self.proxy = proxy
        super(Model, self).__init__(self._init_interfaces())

    def _setup_methods(self):
        for iface_name, iface in self.interfaces.items():
            for method in iface.methods.keys():
                func = self._wrap_dbus_method(iface_name, method)
                partial_function = functools.partial(func, self.proxy)
                setattr(self, method, partial_function)

    def _init_interfaces(self) -> Dict[str, Interface]:
        ''' Initialize the `Interface` objects '''
        xml_str = str(self.proxy.Introspect())
        doc = xml.dom.minidom.parseString(xml_str)

        root = doc.childNodes[1]  # skip doctype
        assert root.nodeName == 'node'

        return {
            _name(iface): Interface(iface)
            for iface in root.getElementsByTagName('interface')
        }

    def _wrap_dbus_method(self, iface_name: str, func_name: str) -> Callable:
        ''' Wrapper around a lambda calling
            `dbus.proxies.ProxyObject.get_dbus_method()` with the right
            interface and executing it.
        '''
        return lambda obj, *args, **kwargs: \
            self.proxy.get_dbus_method(func_name, dbus_interface=iface_name)(*args, **kwargs)

class Method(qui.models.base.Method):
    ''' Represents a D-Bus Method '''

    # pylint: disable=too-few-public-methods
    def __init__(self, method: xml.dom.minidom.Element) -> None:
        args = [
            _attr(arg, 'type') for arg in _children(method, 'arg')
            if _attr(arg, 'direction') == 'in'
        ]
        super(Method, self).__init__(name=_name(method), *args)

class Signal(qui.models.base.Signal):
    ''' Represents a D-Bus Signal '''

    def __init__(self, signal: xml.dom.minidom.Element) -> None:
        kwargs = {
            _name(arg): _attr(arg, 'type')
            for arg in _children(signal, 'arg')
        }
        super(Signal, self).__init__(name=_name(signal), **kwargs)

class Properties(Model, collections.MutableMapping):
    ''' Provides dictionary access to a `org.freedesktop.DBus.Properties` object
    ''' # pylint: disable=too-few-public-methods,too-many-ancestors

    def __init__(self,
                 proxy: dbus.proxies.ProxyObject,  # pylint: disable=no-member
                 data: dbus.Dictionary=None,  # pylint: disable=no-member
                 *args, **kwargs) -> None:
        super(Properties, self).__init__(proxy, *args, **kwargs)
        assert PROPERTIES_INTERFACE in self.interfaces
        if data is None:
            # pylint: disable=no-member
            self._data = self.GetAll('')  # type: ignore
        else:
            self._data = data

        def _update(interface, changed_properties, invalidated):
            ''' Update the internal dictionary when a property changes '''
            # pylint: disable=unused-argument
            for key, value in changed_properties.items():
                self._data[key] = value

        proxy.connect_to_signal(PROPERTIES_CHANGED, _update,
                                dbus_interface=PROPERTIES_INTERFACE)

    def __getitem__(self, key: _DictKey):
        return self._data[key]

    def __setitem__(self, key: _DictKey, value: Any) -> None:
        self.proxy.Set('', key, value)  # type: ignore

    def __delitem__(self, key: _DictKey):
        msg = 'It is not possible to delete D-Bus properties'
        raise NotImplementedError(msg)

    def __len__(self):
        return len(self._data)

    def __iter__(self):
        return iter(self._data)

class ObjectManager(Model):
    ''' A Model which has child models. '''

    # pylint: disable=too-few-public-methods
    def __init__(self,
                 proxy: dbus.proxies.ProxyObject,  # pylint: disable=no-member
                 cls:type=Properties) -> None:
        super(ObjectManager, self).__init__(proxy)
        assert OBJECT_MANAGER_INTERFACE in self.interfaces
        child_data = self.GetManagedObjects()
        self.children = {}  # type: Dict[dbus.ObjectPath, Properties]
        bus = dbus.SessionBus()  # pylint: disable=no-member
        for child_path, _kwargs in child_data.items():
            _data = list(_kwargs.values())[0]
            child_proxy = bus.get_object(bus_name=proxy.bus_name,
                                         object_path=child_path,
                                         follow_name_owner_changes=True)
            self.children[child_proxy.object_path] = cls(child_proxy, _data)

    def GetManagedObjects(self):
        ''' Wrapper around
            'org.freedesktop.DBus.ObjectManager.GetManagedObjects'. This wrapper
            is used to keep mypy and pylint happy.
        '''  # pylint: disable=useless-super-delegation
        # type:ignore pylint: disable=no-member,invalid-name
        return super(ObjectManager, self).GetManagedObjects()

def _name(elem: xml.dom.minidom.Element) -> str:
    ''' Returns the name attribute from a `xml.dom.minidom.Element`. '''
    return str(elem.getAttribute('name'))

def _children(elem: xml.dom.minidom.Element,
              name: str) -> xml.dom.minidom.NodeList:
    ''' Returns children with specified name elements of a
        `xml.dom.minidom.Element`.
    '''
    return elem.getElementsByTagName(name)

def _attr(elem: xml.dom.minidom.Element, name: str) -> str:
    ''' Shorthand for `str(elem.getAttribute(name))`. '''
    return str(elem.getAttribute(name))


#import modules
import os
import csv

#set local pc path to data csv file
csvpath = os.path.join("resources", "election_data.csv")

#create votes dictionary
candidates_list = {}
counter = 0

# open and read csv
with open(csvpath) as csv_file:
    csv_reader = csv.reader(csv_file, delimiter=",")

    # skip header row
    next(csv_reader, None)

    # begin loop
    for row in csv_reader:
        #define candidate column
        candidate = row[2]

        #if candidate not in dictionary, add with first vote
        if candidate not in candidates_list:
            candidates_list[candidate] = 1

        #if candidate already in dictionary, add a vote
        else:
            candidates_list[candidate] += 1

#for key, value in votes.items():
    #print(f'{key} : {value}')

# add values in dictionary to get total votes
votes = candidates_list.values()
Total_Votes = sum(votes)

# use max function to identify winning candidate
# def get_max(Total_Votes):
#     votemax = 0
#     for votemax in candidate:
#         if votemax < candidates_list
#     return votemax
#     maxcandidate = get_max(candidates)
    #print(maxcandidate)

# print summary table
print(f'Election Results')
print(f'Total Votes: {Total_Votes}')
#for key, value in candidates_list.items():
#    print(f'{candidate}: {votes / Total_Votes: 3%} ({Total_Votes})")

# write summary table to output file
# specify file to write to
output_path = os.path.join("analysis", "PyPoll_Summary.txt")


# F - Make Them Odd

def choices(x):
    ch = []
    while x % 2 == 0:
        ch.append(x)
        x /= 2
    return ch

for i in range(int(input())):
    input()
    ns = map(int, input().split())
    ch = set()
    for j in ns:
            ch = ch.union(set(choices(j)))
    print(len(ch))


arrayequals = []
with open("rucksack.txt","r") as f:
    data = f.readlines()

for value in data:
    wholeString = [*value]
    wholeString.pop()
    length = (len(wholeString))/2
    intlength = int(length)
    string1 = wholeString[:intlength]
    string2 = wholeString[intlength:]
    for value in string1:
        if(value in string2):
            arrayequals.append(value)
            break
pointsarray = []
for val in arrayequals:
    if(val.isupper() == True):
        point = ord(val) - 65 + 27
        pointsarray.append(point)
    if(val.islower() == True):
        point = ord(val) - 97 + 1
        pointsarray.append(point)

print(sum(pointsarray))


import unittest
import pandas as pd
import numpy as np
from statlibs import AutoPairedTest

class AutoPairedTestTests(unittest.TestCase):

    def setUp(self):
        array_rand = np.random.randint(100, size=(5, 2))
        array_rand_diff = np.subtract.reduce(array_rand, axis=1).reshape(-1, 1)
        array = np.hstack((array_rand, array_rand_diff))
        column = ['before', 'after', 'diff']
        self.df = pd.DataFrame(data=array, columns=column)

    def test_run_test(self):
        auto_paired_test = AutoPairedTest(self.df, "diff", "before", "after")
        result = auto_paired_test.run_test()
        self.assertIsNotNone(result)

if __name__ == '__main__':
    unittest.main()


#!/usr/bin/env python
# -*- coding: utf-8 -*-
# Date ：2020/10/25 20:14
# Author：Lydia
"""
使用cookie 登录企业微信，完成导入联系人，加上断言验证
"""
import shelve
from time import sleep

from selenium import webdriver
from selenium.webdriver.chrome.options import Options
from selenium.webdriver.common.by import By

# cookie 实现浏览器复用
class TestDemo:
    def setup_method(self, method):
        options = Options()
        options.debugger_address = "127.0.0.1:9222"
        # self.driver = webdriver.Chrome(options=options)
        self.driver = webdriver.Chrome()
        self.driver.implicitly_wait(5)

    def teardown_method(self, method):
        self.driver.quit()

    # def test_weixin(self):
    #     self.driver.find_element(By.ID, 'menu_contacts').click()
    #     sleep(3)

    def test_cookie(self):
        # get_cookies()获取当前打开页面的cookies
        # add_cookie()把cookie添加到当前的页面中去
        # cookies = self.driver.get_cookies()
        # print(cookies)
        cookies = [
            {'domain': '.work.weixin.qq.com', 'httpOnly': False, 'name': 'wwrtx.vid', 'path': '/', 'secure': False,
             'value': '1688853304123940'},
            {'domain': '.work.weixin.qq.com', 'httpOnly': True, 'name': 'wwrtx.sid', 'path': '/', 'secure': False,
             'value': 'wMhdD3cvfBsLjqjULSsioNvCJDe7qs1oRxYxGfAyxiKiXlgTRXUaWPIbQ8czueQz'},
            {'domain': '.work.weixin.qq.com', 'httpOnly': False, 'name': 'wwrtx.d2st', 'path': '/', 'secure': False,
             'value': 'a4095947'},
            {'domain': '.work.weixin.qq.com', 'httpOnly': False, 'name': 'wxpay.corpid', 'path': '/', 'secure': False,
             'value': '1970324968162766'},
            {'domain': '.work.weixin.qq.com', 'httpOnly': False, 'name': 'wxpay.vid', 'path': '/', 'secure': False,
             'value': '1688853304123940'},
            {'domain': 'work.weixin.qq.com', 'expiry': 1603637936, 'httpOnly': True, 'name': 'ww_rtkey', 'path': '/',
             'secure': False, 'value': '2e5caih'},
            {'domain': '.qq.com', 'expiry': 1603715461, 'httpOnly': False, 'name': '_gid', 'path': '/', 'secure': False,
             'value': 'GA1.2.788847587.1603606404'},
            {'domain': '.work.weixin.qq.com', 'httpOnly': False, 'name': 'Hm_lpvt_9364e629af24cb52acc78b43e8c9f77d',
             'path': '/', 'secure': False, 'value': '1603628413'},
            {'domain': '.work.weixin.qq.com', 'httpOnly': True, 'name': 'wwrtx.refid', 'path': '/', 'secure': False,
             'value': '3697623621212132'},
            {'domain': '.qq.com', 'expiry': 1666701061, 'httpOnly': False, 'name': '_ga', 'path': '/', 'secure': False,
             'value': 'GA1.2.1188152275.1603335017'},
            {'domain': '.work.weixin.qq.com', 'expiry': 1666407027, 'httpOnly': False, 'name': '__utma', 'path': '/',
             'secure': False, 'value': '135912439.1188152275.1603335017.1603335017.1603335017.1'},
            {'domain': '.work.weixin.qq.com', 'expiry': 1634871017, 'httpOnly': False, 'name': 'wwrtx.c_gdpr',
             'path': '/', 'secure': False, 'value': '0'},
            {'domain': '.work.weixin.qq.com', 'httpOnly': True, 'name': 'wwrtx.vst', 'path': '/', 'secure': False,
             'value': '8Osue6FDKpXyqBBudvlSq0Fu6yBFVEzK2W3XyTg7IQVysM3_AC4NSHG-EPCUItakWx_oDcqWmeplZ32Wnfa_FkEjNX2lbAUo4YG6nrbeUS23QKHDUIAig40pEmiMvzYpuR_it8dFJEjjwqktTgOjQHt6OEHlclbveP15UnnoBR5CTDyUWLQLfJt-IYb0VnJyyvQ6LFRag7RnBEZHTKgn7CXzHMJFTyjHapBqJcoGPaqrW-ZPlxW_T0kFQCj5WZWsPKZJbL7FuIGbgCPxUDNh0Q'},
            {'domain': '.work.weixin.qq.com', 'expiry': 1634871027, 'httpOnly': False,
             'name': 'Hm_lvt_f2ba645ba13636ba52b0234381f51cbc', 'path': '/', 'secure': False, 'value': '1603335018'},
            {'domain': '.work.weixin.qq.com', 'expiry': 1619103027, 'httpOnly': False, 'name': '__utmz', 'path': '/',
             'secure': False,
             'value': '135912439.1603335017.1.1.utmcsr=google|utmccn=(organic)|utmcmd=organic|utmctr=(not%20provided)'},
            {'domain': '.work.weixin.qq.com', 'httpOnly': True, 'name': 'wwrtx.ltype', 'path': '/', 'secure': False,
             'value': '1'},
            {'domain': '.work.weixin.qq.com', 'httpOnly': True, 'name': 'wwrtx.ref', 'path': '/', 'secure': False,
             'value': 'direct'}, {'domain': '.work.weixin.qq.com', 'expiry': 1635164413, 'httpOnly': False,
                                  'name': 'Hm_lvt_9364e629af24cb52acc78b43e8c9f77d', 'path': '/', 'secure': False,
                                  'value': '1603335033,1603606404,1603628413'},
            {'domain': '.work.weixin.qq.com', 'expiry': 1606221064, 'httpOnly': False, 'name': 'wwrtx.i18n_lan',
             'path': '/', 'secure': False, 'value': 'zh'}]

        self.driver.get("https://work.weixin.qq.com/wework_admin/frame#index")
        for cookie in cookies:
            self.driver.add_cookie(cookie)
        # # 第一种方法：再次打开页面
        # self.driver.get("https://work.weixin.qq.com/wework_admin/frame#index")
        # 第二种方法：刷新
        self.driver.refresh()
        # sleep(3)


import numpy as np
from scipy.optimize import minimize
from typing import Callable
import cma
from scipy.stats import t
import sys
import os

sys.path.insert(1, os.path.join(os.path.dirname(sys.path[0]), 'environments'))
sys.path.insert(1, os.path.join(os.path.dirname(sys.path[0]), 'optimizers'))
sys.path.insert(1, os.path.dirname(sys.path[0]))

from .optimizer import Optimizer

"""
This file contains some black box optimizers from different libraries CMA, Powell and BFGS
"""

class Powell(Optimizer):

    def __init__(self, theta, evaluationFunction):
        self.name = "Powell"
        self.theta = theta
        self.evaluationFunction = evaluationFunction
        print(self.name)

    def name(self):
        return self.name

    def run_optimizer(self, verbose=True) -> np.ndarray:
        minimizer_method = 'Powell'
        minimizer_options = {'disp': False, 'maxfev': 1000, 'maxiter':1000}

        # Use Powell to get a candidate solution that tries to maximize candidateObjective
        res = minimize(self.evaluationFunction, x0=self.theta, method=minimizer_method, options=minimizer_options, tol=0.001)

        # Return the candidate solution we believe will pass the safety test
        print(f'x_min inside powell {res.x}')
        print(f'function value at x_min is {self.evaluationFunction(res.x)}, Message is {res.message}')
        return res.x

class BFGS(Optimizer):

    def __init__(self, theta, evaluationFunction):
        self.name = "BFGS"
        self.theta = theta
        self.evaluationFunction = evaluationFunction
        print(self.name)

    def name(self):
        return self.name

    def run_optimizer(self, verbose=True) -> np.ndarray:
        # Chooses the black-box optimizer we will use (Powell)
        minimizer_method = 'BFGS'
        minimizer_options = {'disp': True, 'maxfev': 5, 'maxiter':5}
        res = minimize(self.evaluationFunction, x0=self.theta, method=minimizer_method, options=minimizer_options, tol=0.001)

        print(f'x_min inside bfgs {res.x}')
        print(f'function value at x_min is {self.evaluationFunction(res.x)}, Message is {res.message}')
        return res.x

class CMA(Optimizer):

    def __init__(self, theta, evaluationFunction):
        self.name = "CMA"
        self.theta = theta
        self.evaluationFunction = evaluationFunction
        self.sigma = 0.5
        self.iterations = 10
        print(self.name)

    def name(self):
        return self.name

    def run_optimizer(self, verbose=True) -> np.ndarray:
        candidate_solution = cma.fmin(self.evaluationFunction, self.theta.flatten(), self.sigma, options={'maxiter': self.iterations})[0]
        print(f'x_min inside cma {candidate_solution}')
        print(f'function value at x_min is {self.evaluationFunction(candidate_solution)}')
        return candidate_solution

def func(x):
    f = x * x + 4
    return np.squeeze(f)

def test():
    # pass
    cem = Powell(5.0, func)
    cem.run_optimizer()

if __name__ == "__main__":
    test()


#!/usr/bin/env python
from flask.ext.admin.contrib.sqla import ModelView
from flask.ext.admin import Admin
from models import (
    Users,
    Format,
    Sameas,
    Torrent,
    Datasets,
    Role,
    Provider,
    License,
    db
)
from flask import session
from xmlrpclib import ServerProxy
from makeTorrent import makeTorrent
from os import path
from requests import get, post

admin = Admin()

class Models(ModelView):

    def is_accessible(self):
        if session.get('username', None):
            if session.get('is_admin', 'False') == 'True':
                return True
            else:
                return False
        else:
            return False

    def index(self):
        return self.render('admindex.html')

def is_allowed(roles):
    print('Allowed: %s got %s' % (roles, session['role']))
    if session['role'] not in roles:
        return False
    if session['role'] in roles:
        return True

class DatasetsView(ModelView):

    def is_accessible(self):
        if session.get('username', None):
            if session.get('is_admin', 'False') == 'True':
                return True
            else:
                return False
        else:
            return False

    inline_model = (Format,)
    column_list = ('type', 'name', 'description', 'license', 'path', 'url')
    column_filter = ('type', 'name', 'description', 'license', 'path', 'url')
    form_columns = (
        'type', 'name',
        'description', 'license',
        'path', 'url', 'provider',
        'formats', 'sameas'
    )

    def __init__(self, session):
        super(DatasetsView, self).__init__(Datasets, db.session)

class UserView(ModelView):

    def is_accessible(self):
        if session.get('username', None):
            if session.get('is_admin', 'False') == 'True':
                return True
            else:
                return False
        else:
            return False

    def __init__(self, session):
        super(UserView, self).__init__(Users, db.session)
    form_columns = ('username', 'role')

class TorrentView(ModelView):

    def is_accessible(self):
        if session.get('username', None):
            if session.get('is_admin', 'False') == 'True':
                return True
            else:
                return False
        else:
            return False

    def __init__(self, session):
        super(TorrentView, self).__init__(Torrent, db.session)
    column_list = ('torrent', 'updated_at')
    form_columns = ('torrent', )

    def on_model_delete(self, model):
        appConf = admin.app.config
        infoHash = model.infoHash
        headers = {
            'Accept': 'application/json',
            'Authorization': 'Bearer %s' % appConf.get('DATASETKEY')
        }
        if appConf.get('SUNET', False):
            try:
                r = get(
                    'https://datasets.sunet.se'
                    '/api/dataset/%s/delete' % infoHash,
                    headers=headers,
                    verify=appConf.get('VERIFY_SSL', True)
                )
                r.raise_for_status()
            except Exception as e:
                print("Could not delete torrent %s" % e)
        if appConf.get('RTORRENT', False):
            try:
                rtorrent = ServerProxy(appConf.get('XMLRPC_URI'))
                rtorrent.d.erase(infoHash)
            except Exception as e:
                print("Could not remove torrent: %s" % e)

    def on_model_change(self, form, model, is_created):
        datasetID = form.data['torrent'].datasetID
        if is_created:
            dataset = Datasets.query.filter(
                Datasets.datasetID == datasetID
            ).first()
            appConf = admin.app.config
            mk = makeTorrent(announce=appConf.get('ANNOUNCE'))
            mk.multi_file(path.join(appConf.get('DATASET_ROOT'), dataset.path))
            torrentData = mk.getBencoded()
            headers = {
                'Accept': 'application/json',
                'Authorization': 'Bearer %s' % appConf.get('DATASETKEY')
            }
            tData = {'torrent': torrentData}
            if appConf.get('SUNET', False):
                try:
                    r = post(
                        'https://datasets.sunet.se/api/dataset',
                        headers=headers,
                        files=tData,
                        verify=appConf.get('VERIFY_SSL', True)
                    )
                    r.raise_for_status()
                except Exception as e:
                    print("Could not upload torrent: %s" % e)
            model.infoHash = mk.info_hash()
            model.torrentData = torrentData
            torrentFile = path.join(
                appConf.get('TORRENT_WATCH_DIR'),
                model.infoHash + '.torrent'
            )
            with open(torrentFile, 'w') as tf:
                tf.write(torrentData)
            if appConf.get('RTORRENT'):
                try:
                    rtorrent = ServerProxy(appConf.get('XMLRPC_URI'))
                    rtorrent.load(torrentFile)
                    downloadPath = path.dirname(
                        path.join(
                            appConf.get('DATASET_ROOT'),
                            dataset.path
                        )
                    )
                    rtorrent.d.set_directory(model.infoHash, downloadPath)
                except Exception as e:
                    print("Could not add torrent to rtorrent: %s" % e)

        return

admin.add_view(UserView(db.session))
admin.add_view(Models(Role, db.session))
admin.add_view(Models(Provider, db.session))
admin.add_view(Models(License, db.session))
admin.add_view(Models(Format, db.session))
admin.add_view(DatasetsView(db.session))
admin.add_view(TorrentView(db.session))
admin.add_view(Models(Sameas, db.session))


#!/usr/bin/env python
"""start iLifeSlideshows screensaver"""
import click
import mac_slideshow

MODULE_NAME = "mac_slideshow.start"
PROG_NAME = 'python -m %s' % MODULE_NAME
USAGE = 'python -m %s [path]' % MODULE_NAME

@click.command()
@click.argument('path', required=False)
def _cli(path):
    mac_slideshow.start(path)

if __name__ == '__main__':
    _cli(prog_name=PROG_NAME)


#
# @lc app=leetcode.cn id=34 lang=python3
#
# [34] 在排序数组中查找元素的第一个和最后一个位置
#

# @lc code=start
class Solution:
    def searchRange(self, nums: List[int], target: int) -> List[int]:
        n = len(nums)
        if n<1:
            return [-1,-1]
        ans = []
        def help(i,j):
            if i==j and nums[i]==target:
                return [i]
            elif nums[i]<=target and nums[j]>=target:
                a = help(i,(i+j)//2)
                b = help((i+j)//2+1,j)
                return a+b

            return []
        ans = help(0,n-1)
        if ans == []:
            return [-1,-1]
        return [min(ans),max(ans)]

# @lc code=end

leetcode/34.在排序数组中查找元素的第一个和最后一个位置.py

34.在排序数组中查找元素的第一个和最后一个位置.py


import sys
input = sys.stdin.readline
from collections import deque

T = int(input())
for _ in range(T):
    p = input().rstrip()
    n = int(input())
    tmp = input().rstrip()[1:-1].split(",")
    q = deque(tmp)
    if not n:
        q = deque()

    cnt = 0
    flag = False
    for i in p:
        if i == "R":
            # q.reverse()
            cnt += 1
        else:
            if q:
                # 현재까지 뒤집는 횟수가 홀수면 뒤집어서 popleft => pop()
                # 짝수면 안 뒤집어도 됨 => popleft()
                if cnt % 2:
                    q.pop()
                else:
                    q.popleft()
            else:
                print("error")
                flag = True
                break
    if flag:
        continue

    # R 횟수가 홀수면 뒤집기
    if cnt % 2:
        q.reverse()

    result = "["
    result += ",".join(list(q))
    result += "]"
    print(result)


""" main variables to be updated daily """

# asset_price : underlying price
# sigma       : implied volatility to insert for the BS model
# dt          : time to expiration
# rf          : risk free rate (30 day LIBOR rate)
# nContract1  : number of contracts
# K1          : strike price option 1
# K2          : strike price option 2
# K3          : strike price option 3

# underlying
asset_price = 543

# input BS
sigma = 0.53
dt = 30/365
rf = .015

# option 1
nContract1 = -1000
K1 = 545

# option 2
K2 = 550

# option 3
K3 = 555


#Parameters of our building

floors = int(7)
aptsPerFloor = int(5)

#2D array defining apartment names and wether if they have mail or not

apartments = str([floors, aptsPerFloor])
hasMail = bool([floors, aptsPerFloor])

#Initialize values with a nested for loop
arr = []

for i in range(0, floors):
    for j in range(0, aptsPerFloor):
        apartments = [i,j]
        hasMail = False

        arr.append(apartments)

#Some algorithm that tracks mail and updates 'hasMail'...
for x in arr:
    hasMail = False

    #Check mail in all apartments
    if x == [3,2]:
        hasMail = True
    elif x == [6,0]:
        hasMail = True

    print(x, hasMail)


from tools import *

# Código para LFU (Least Frequently Used)
LFU_cacheFreqTable = dict()  # Planilha para associar o número dos arquivos com a frequência deles
LFU_cache = dict()  # Cache do programa

# Reinicializa as variáveis do cache
def LFU_restartCache():
  global LFU_cacheFreqTable, LFU_cache
  LFU_cacheFreqTable = dict()
  LFU_cache = dict()

# Retorna se o arquivo está no cache
def LFU_isFileInCache(index):
  if index in LFU_cache.keys():  # CACHE HIT
    return True
  else:  # CACHE MISS
    return False

# Retorna o arquivo no cache
def LFU_getFileInCache(index):
  LFU_cacheFreqTable[index] += 1
  return LFU_cache[index]

# Adiciona o arquivo ao cache
def LFU_addFileInCache(index, file):
  if len(LFU_cache) >= MAX_CACHE_SIZE:
    m = min(LFU_cacheFreqTable.values())
    for k, v in LFU_cacheFreqTable.items():
      if v == m:
        LFU_cacheFreqTable.pop(k)
        LFU_cache.pop(k)
        break

  LFU_cacheFreqTable[index] = 1
  LFU_cache[index] = file

# Retorna o arquivo diretamente do cache ou resgata ele do disco
def LFU_getFile(index, debug=False):
  curFileName = createFileName(index)
  text = ""
  isCacheMiss = False
  if not LFU_isFileInCache(index):
    with open(curFileName, "r", encoding="UTF-8") as file:
      text = file.read()
      file.close()
    LFU_addFileInCache(index, text)
    isCacheMiss = True
  else:
    text = LFU_getFileInCache(index)
  return text, isCacheMiss

Atividade Prática 1 - Caches - 2023-1/LFU.py


import pandas as pd
import numpy as np
import random

from pathlib import Path
from itertools import combinations
from collections import defaultdict
from functools import lru_cache

def calc_stats(part2pop, parts):
    """counts mean amount of wins for a real population"""
    for part in parts:
        populations = sorted(part2pop[part])
        d = {pop: [] for pop in populations}
        d['part'] = []
        file_path = f'../features_part{part}.csv'
        df = pd.read_csv(file_path, index_col='SAMPLE')
        d['part'].append(part)
        win_counts = pd.Series(np.zeros(len(df)), index=df.index.values)

        for index, row in df.iterrows():
            n = 0
            pop = row['REAL']
            for i, value in row.items():
                if i.startswith(pop) and value >= 0.5:
                    n += 1
                elif i.endswith(pop) and value <= 0.5:
                    n += 1
            win_counts[index] = n / 4

        df['WINS'] = win_counts
        for pop in populations:
            pop_df = df[df['REAL'] == pop][['WINS']]
            d[pop].append(pop_df['WINS'].mean())

    res = pd.DataFrame(d)
    return res

class BaseAnalyser:

    name = 'BaseAnalyser'

    def __init__(self, populations, part):
        self.populations = sorted(populations)
        self.part = part
        self.comb = list(combinations(self.populations, 2))

    @property
    def _path(self):
        return f'../features_part{self.part}.csv'

    def _score(self, score):
        """
        Return a tuple of scores for population1 and population2
        if in mutual comparison population1 got value score
        """
        if score > 0.5:
            return 1, 0
        else:
            return 0, 1

    def winner_for_sample(self, row):
        scores = {pop: 0 for pop in self.populations}
        for a, b in self.comb:
            column = f'{a}_{b}'
            s1, s2 = self._score(row[column])
            scores[a] += s1
            scores[b] += s2
        winner = sorted(self.populations, key=lambda x: scores[x])[len(self.populations) - 1]
        return winner

    @lru_cache(1)
    def calc(self):
        df = pd.read_csv(self._path, index_col='SAMPLE')
        s = pd.Series(['' for _ in range(len(df))], index=df.index.values)

        for index, row in df.iterrows():
            s[index] = self.winner_for_sample(row)

        df['WINNER'] = s
        df['MATCH'] = df['REAL'] == df['WINNER']
        return df[['REAL', 'WINNER', 'MATCH']]

    def n_correctly_classified(self):
        df = self.calc()
        return len(df[df['MATCH']])

    def correct_classifications(self):
        d = {}
        for pop in self.populations:
            df = self.calc()
            d[pop] = len(df[(df['REAL'] == pop) & (df['WINNER'] == pop)]) / (1 + len(df[df['WINNER'] == pop]))
        return d

    def n_pop(self):
        df = self.calc()
        d = {pop: len(df[df['WINNER'] == pop]) for pop in self.populations}
        return d

class WinsCountAnalyser(BaseAnalyser):
    name = 'WinsCountAnalyser'

class WinsCountAnalyserWithThreshold(BaseAnalyser):
    name = 'WinsCountAnalyserWithThreshold'
    threshold = 0.3

    def _score(self, score):
        if score > 1 - self.threshold:
            return 1, 0
        elif score < self.threshold:
            return 0, 1
        else:
            return 0.5, 0.5

class ScoreAnalyserWithThreshold(BaseAnalyser):
    name = 'ScoreAnalyserWithThreshold'
    threshold = 0.2

    def _score(self, score):
        if score > 1 - self.threshold:
            return score, 0
        elif score < self.threshold:
            return 0, score
        else:
            return 0.5, 0.5

class ScoreAnalyser(BaseAnalyser):
    name = 'ScoreAnalyser'

    def _score(self, score):
        return score, 1 - score

class BinaryTreeAnalyser(BaseAnalyser):

    name = 'BinaryTreeAnalyser'

    def vs(self, pair, row):
        pair = sorted(pair)
        a, b = pair
        if a == b:
            return a
        else:
            col = "_".join(pair)
            return a if row[col] > 0.5 else b

    def tree_compare(self, pops, row):
        if len(pops) == 2:
            return self.vs(pops, row)

        start = pops[:-2]
        prelast = [pops[-2]]
        last = [pops[-1]]
        return self.vs((self.tree_compare(start + prelast, row), self.tree_compare(start + last, row)), row)

    def winner_for_sample(self, row):

        winner = self.tree_compare(self.populations, row)
        return winner

class SymmetricalBinaryTreeAnalyser(BinaryTreeAnalyser):

    name = 'SymmetricalBinaryTreeAnalyser'

    def tree_compare(self, pops, row):
        if len(pops) == 1:
            return pops[0]

        elif len(pops) == 2:
            return self.vs(pops, row)

        odd = pops[::2]
        even = pops[1::2]
        return self.vs((self.tree_compare(odd, row), self.tree_compare(even, row)), row)

res = defaultdict(list)
parts = (102, 207, 312, 413)

part_to_pops = {
    102: ('ESN', 'GBR', 'JPT', 'LWK', 'PEL'),
    207: ('CEU', 'ESN', 'GBR', 'MSL', 'PEL'),
    312: ('FIN', 'GWD', 'LWK', 'MXL', 'PEL'),
    413: ('GBR', 'KHV', 'MSL', 'PEL', 'YRI'),
}

stats = calc_stats(part_to_pops, parts)
print(stats)

for p in parts:
    # pops = part_to_pops[p]
    pops = sorted([
        'GBR', 'FIN', 'CHS', 'PUR', 'CDX', 'CLM', 'IBS', 'PEL', 'PJL', 'KHV', 'ACB', 'GWD', 'ESN',
        'BEB', 'MSL', 'STU', 'ITU', 'CEU', 'YRI', 'CHB', 'JPT', 'LWK', 'ASW', 'MXL', 'TSI', 'GIH'
    ])
    print('ON PART: ', p, 'with populations: ', pops)

    for Analyser in (WinsCountAnalyserWithThreshold, WinsCountAnalyser,
                     ScoreAnalyserWithThreshold, ScoreAnalyser,
                     SymmetricalBinaryTreeAnalyser):  # BinaryTreeAnalyser,

        analyser = Analyser(pops, p)
        t = analyser.calc()
        output_dir = Path(f'predictions/part{p}/')
        output_dir.mkdir(parents=True, exist_ok=True)

        output_file = output_dir / f'{analyser.name}.csv'
        t.to_csv(str(output_file))
        print(analyser.correct_classifications())
        res[analyser.name].append(analyser.n_correctly_classified())

print(res)
for key, val in res.items():
    print(key, sum(val) / 495 / len(parts))
df = pd.DataFrame(res)
df.to_csv('analyser_comparison.csv')


import error_reporter
from post_processing.plex import Plexify
from post_processing.kodi import Kodi
from post_processing.series_mover import SeriesMover

class PostProcessor:
    def __init__(self, logger, config):
        self.logger = logger
        self.config = config
        self.plex = Plexify(self.logger, self.config)
        self.kodi = Kodi(self.logger, self.config)
        self.seriemover = SeriesMover(self.logger, self.config)
        self.class_instances = [self.plex, self.kodi, self.seriemover]

    def new_processed_file(self, watcher_uid):
        for class_instance in self.class_instances:
            if self.config.get_config_watcher(watcher_uid, class_instance.config_param) == 1:
                self.logger.info('Notifier', '{} is next to be updated now that we had a successful file operation'
                                 .format(class_instance.name))
                try:
                    class_instance.update(watcher_uid)
                except Exception as e:
                    self.logger.error('Notifier', 'Error in updating {}. Please check your config'
                                      .format(class_instance.name))
                    error_file = error_reporter.print_error_file(e)
                    self.logger.error('Notifier', 'Complete stacktrace can be found in {}'.format(error_file))


import os
import subprocess

def is_git_repository(directory):
    # Kiểm tra xem có tồn tại thư mục .git trong thư mục được chỉ định hay không
    return os.path.isdir(os.path.join(directory, ".git"))

def init_temp_git_repo(directory):
    subprocess.run(["git", "init"], cwd=directory)
    subprocess.run(["git", "add", "."], cwd=directory)
    subprocess.run(["git", "commit", "-m", "temp commit"], cwd=directory)
    # subprocess.run(["git", "config", "--global", "user.email", "you@example.com"], cwd=directory)
    # subprocess.run(["git", "config", "--global", "user.name", "Your Name"], cwd=directory)
    subprocess.run(["git", "config", "--global", "user.email", "18520058@gm.uit.edu.vn"], cwd=directory)
    subprocess.run(["git", "config", "--global", "user.name", "brandon"], cwd=directory)

def detect_languages_with_linguist(directory):
    init_temp_git_repo(directory)
    # Chạy github-linguist và lấy output
    result = subprocess.run(["github-linguist", directory], capture_output=True, text=True)
    if result.returncode != 0:
        raise Exception("Error running linguist: " + result.stderr)

    return result.stdout

def analyze_projects_in_directory(root_directory):
    project_languages = {}

    # Duyệt qua tất cả các thư mục con trong root_directory
    for subdir in os.listdir(root_directory):
        full_path = os.path.join(root_directory, subdir)
        if os.path.isdir(full_path):
            languages = detect_languages_with_linguist(full_path)
            if languages:  # Chỉ thêm vào nếu không phải là None
                project_languages[subdir] = languages

    return project_languages

# Ví dụ sử dụng
root_directory = "/home/brandon/detectors/project"
projects = analyze_projects_in_directory(root_directory)
for project, languages in projects.items():
    print(f"Project: {project}")
    print(languages)
    print("--------")