class LinkedListNode:
    def __init__(self, data, next):
        self.data = data
        self.next = next

    def __repr__(self):
        cursor = self
        computedString = ""
        while cursor:
            if cursor.next:
                computedString = f"{computedString}{cursor.data} -> "
            else:
                computedString = f"{computedString}{cursor.data} -> NULL"
            cursor = cursor.next
        return computedString

def sumLinkedListBigEndian(la, lb):
    if not la:
        if not lb:
            return 0
        else:
            return lb
    elif not lb:
        if not la:
            return 0
        else:
            return la

    stackA = []
    stackB = []

    ca = la
    cb = lb

    while ca or cb:
        if ca:
            stackA.append(ca.data)
            ca = ca.next
        if cb:
            stackB.append(cb.data)
            cb = cb.next

    localResultStack = []
    carry = 0
    while len(stackA) > 0 or len(stackB):
        cavalue = stackA.pop() if len(stackA) > 0 else 0
        cbvalue = stackB.pop() if len(stackB) > 0 else 0

        localSum = cavalue + cbvalue + carry
        if localSum > 10:
            carry = 1
            localSum = localSum % 10
        else:
            carry = 0

        localResultStack.append(localSum)

    if carry > 0:
        localResultStack.append(carry)

    head = None
    for i in range(len(localResultStack)):
        head = LinkedListNode(localResultStack[i], head)
    return head

def sumLinkedListLittleEndian(la, lb):
    if not la:
        if not lb:
            return 0
        else:
            return lb
    elif not lb:
        if not la:
            return 0
        else:
            return la

    cursorA = la
    cursorB = lb
    carry = 0

    resultList = []
    while cursorA or cursorB:
        currentAVal = cursorA.data if cursorA else 0
        currentBVal = cursorB.data if cursorB else 0

        localSum = currentAVal + currentBVal + carry

        if localSum >= 10:
            carry = localSum // 10
            localSum = localSum % 10
        else:
            carry = 0

        resultList.append(localSum)

        if cursorA:
            cursorA = cursorA.next
        if cursorB:
            cursorB = cursorB.next
    if carry > 0:
        resultList.append(carry)

    head = None
    while len(resultList) > 0:
        head = LinkedListNode(resultList.pop(), head)

    return head

listA = LinkedListNode(7, LinkedListNode(1, LinkedListNode(6, None)))
listB = LinkedListNode(5, LinkedListNode(9, LinkedListNode(2, None)))

littleSum = sumLinkedListLittleEndian(listA, listB)

print(littleSum)

listABig = LinkedListNode(6, LinkedListNode(1, LinkedListNode(7, None)))
listBBig = LinkedListNode(2, LinkedListNode(9, LinkedListNode(5, None)))

bigSum = sumLinkedListBigEndian(listABig, listBBig)

print(bigSum)


# 导包
import requests

# path = 'https://www.sogou.com/web?query=是小李同学&'
path = 'https://www.sogou.com/web'

# 动态输入参数
kw = input("please input you query word:")
# 处理url携带的参数，封装到字典中
params = {'query':kw}
# 对指定的url发起请求对应的url是携带参数的，并且请求过程中处理了参数
response = requests.get(url=path,params=kw)
content = response.text
print(content)

# 结果存储
filename = kw + '.html'
with open(filename,'w',encoding='utf-8') as f:
    f.write(content)


# Автор Тютин Руслан
# Цикл
#
# Создать список из десяти целых чисел.
# Вывести на экран каждое число, увеличенное на 1.

list_lines = [x for x in range(10)]
for list_line in list_lines:
    print(list_line + 1)


from tigerapps.rooms.models import *
from django.core.mail import send_mail

    # Mark a collection of rooms as taken and notify people as necessary
def updateavail(roomset):
    # Mark as taken
    roomset.update(avail=False)

    for room in roomset:
        notify(room)

def notify(room):
    qids = QueueToRoom.objects.filter(room=room).values_list('queue_id',flat=True)
    queues = Queue.objects.filter(id__in=qids)
    users = User.objects.filter(queues__in=queues).distinct()
    #self.stdout.write('%s\n' % users)
    for user in users:
        if user.do_email:
            email(user, room)
        if user.do_text and user.confirmed:
            text(user, room)

def email(user, room):
    subject = 'Rooms: %s Taken' % room
    content = '''%s was on your room draw queue, and was taken.

You are receiving this message because you have email queue notifications turned on.
To disable, go to rooms.tigerapps.org.
Please do not respond to this email, it is from an unmonitored email address.

Thanks,
The Rooms Team
''' % room
    send_mail(subject, content, 'rooms@tigerapps.org',
              ['%s@princeton.edu' % user.netid], fail_silently=False)

def text(user, room):
    content = "The room %s is no longer available. Oh no!" % room
    send_mail("", content, 'room@tigerapps.org',
              ['%s@%s' % (user.phone, user.carrier.address)], fail_silently=False)


from dash import html, dcc # importing dash html components as dcc so can use python code with html actions
import dash_bootstrap_components as dbc #importing bootstrap components to style the dashboard

# creating the class Layout to use within the main main.py
class Layout:
    def __init__(self) -> None:

        # This attribute is a dictionary to return what the titles in the first dropdown is and the value to return to the input callbacks
        self.GB_stats = [
            {"label": "Sports Great Britain won the most medals in", "value": "medals"},
            {"label": "Amount of medals won per Olympic Games", "value": "medals_os"},
            {"label": "Age distribution of Athletes representing Great Britain", "value": "age"},
            {"label": "Height and Weight averages of Different sports in Great Britain Team", "value":"height_weight"}
        ]
        # This is the attribute is for the world stats drop down on the second tab
        self.world_stats = [
            {"label": "Top ranking countries medal count", "value": "top_ten_medals"},
            {"label": "Distribution of Winners in Art competitions", "value": "art_comp"},
            {"label": "Distribution of Winners in Ice Hockey", "value": "ice_hockey"}
        ]

    # This is now the layout function that will contain all the style, positioning and functions of the app
    def layout(self):

        return dbc.Container([ # Container is where the whole layout has to be contained in.

            html.Div( # use of a div tag to group sets or sections of functions of the app
                children=[
                html.H1(children='Olympic Games Statistics'), # This shows the title bar of the Dashboard

                # now adding in tab decorator
                dcc.Tabs([
                    dcc.Tab(label='Team Great Britain',children=[ # This is the first tab on the right
                            dcc.Dropdown( # adding a drop down decorator
                                id='gb-dropdown', # this is its id which will be recognized in the callbacks
                                options=self.GB_stats, # This is the dictionary of the dropdown menu it will select the required drop down
                                value="medals" # This will return the value to the callback to activate the output
                            ),
                            dcc.Graph(id='graph'), # This is the graph decorator which allows a graph to be shown
                            ], style={'width': '50%', 'display': 'inline-block'}), # This sets the width and styling of the tab menu

                    dcc.Tab(label='World Olympics', children=[ # The code is the same with the next tab, however the values and ids will be different

                        dcc.Dropdown(
                            id='world-dropdown', # change of id
                            options=self.world_stats, # chamge of option
                            value="top_ten_medals" # change of value
                        ),
                        dcc.Graph(id='graph-down')
                    ], style={'width': '50%', 'display': 'inline-block'}),

                ]),

            ])
        ])


#!/usr/bin/env python3
import os
import os.path
import subprocess
from collections import namedtuple

class RobinInstance(object):
    def __init__(self, output_dir, batcmd, schedcmd, simulation_timeout, ready_timeout, success_timeout, failure_timeout):
        self.output_dir = output_dir
        self.batcmd = batcmd
        self.schedcmd = schedcmd
        self.simulation_timeout = simulation_timeout
        self.ready_timeout = ready_timeout
        self.success_timeout = success_timeout
        self.failure_timeout = failure_timeout

    def to_yaml(self):
        # Manual dump to avoid dependencies
        return f'''output-dir: '{self.output_dir}'
batcmd: "{self.batcmd}"
schedcmd: "{self.schedcmd}"
simulation-timeout: {self.simulation_timeout}
ready-timeout: {self.ready_timeout}
success-timeout: {self.success_timeout}
failure-timeout: {self.failure_timeout}
'''

    def to_file(self, filename):
        create_dir_rec_if_needed(os.path.dirname(filename))
        write_file(filename, self.to_yaml())

def gen_batsim_cmd(platform, workload, output_dir, more_flags):
    return f"batsim -p '{platform}' -w '{workload}' -e '{output_dir}' {more_flags}"

def write_file(filename, content):
    file = open(filename, "w")
    file.write(content)
    file.close()

def create_dir_rec_if_needed(dirname):
    if not os.path.exists(dirname):
            os.makedirs(dirname)

def run_robin(filename):
    return subprocess.run(['robin', filename])

def init_instance(test_name):
    output_dir = os.path.abspath(f'test-out/{test_name}')
    robin_filename = os.path.abspath(f'test-instances/{test_name}.yaml')
    schedconf_filename = f'{output_dir}/schedconf.json'

    create_dir_rec_if_needed(output_dir)

    return (output_dir, robin_filename, schedconf_filename)


import sys
import pandas as pd
from pathlib import Path
from utils import create_sample, _convert_to_ffm

MAX_NULL = 50000
MAX_PRICE_USD = 5000

encoder = {"currentcode": 0,
           "catdict": {},
           "catcodes": {}
           }

from config import (
                train_csv_path,
                test_csv_path,
                sample_train_csv_path,
                sample_test_csv_path,
                processed_train_csv_path,
                processed_test_csv_path,
                train_ffm_path,
                test_ffm_path
)

def change_data_type(df):
    target = 'click_bool'
    numerics = ['prop_review_score', 'prop_location_score1', 'prop_log_historical_price', 'price_usd']
    categories = []

    for cols in df.columns:
        if not cols in numerics:
            categories.append(cols)
    categories.remove('click_bool')

    for col in categories:
        df[col] = df[col].astype('category')

    for col in numerics:
        df[col] = df[col].astype('float16')

    df[target] = df[target].astype('int8')

    return target, numerics, categories, df

def cleaning_csv_data(sampled_csv_path, processed_csv_path):
    '''

    :param sampled_csv_path, processed_csv_path:
    :return: target, numerics, categories, df
    '''

    if not Path(processed_csv_path).exists():
        df = pd.read_csv(sampled_csv_path)
        df = df.drop(['Unnamed: 0', 'date_time'], axis=1)
        if sampled_csv_path == sample_test_csv_path:
            df['click_bool'] = 0
        else:
            df = df.drop(['position', 'booking_bool'], axis=1)
        null_counts = df.isnull().sum()
        null_counts_df = null_counts[null_counts < MAX_NULL]

        refined_cols = []
        for col in null_counts_df.keys():
            refined_cols.append(col)
        df = df.filter(refined_cols, axis=1)

        pd.to_numeric(df['prop_review_score'], errors='coerce')
        df['prop_review_score'].fillna((df['prop_review_score'].median()), inplace=True)
        df = df[df.price_usd < MAX_PRICE_USD]
        target, numerics, categories, new_df = change_data_type(df)
        new_df.to_csv(processed_csv_path)
        return target, numerics, categories, new_df

    else:
        df = pd.read_csv(processed_csv_path)
        df = df.drop('Unnamed: 0', axis=1)
        target, numerics, categories, new_df = change_data_type(df)
        return target, numerics, categories, new_df

if __name__ == '__main__':
    if not Path(train_csv_path).exists() or not Path(test_csv_path).exists() :
        print('train.csv or test.csv does not exist in datasets/data')
        sys.exit()

    print('Creating train_sample if does not exist')
    create_sample(train_csv_path, sample_train_csv_path)
    print('Creating test_sample if does not exist')
    create_sample(test_csv_path, sample_test_csv_path)

    print("Creating processed_train.csv if does not exist")
    target_train, numerics_train, categories_train, df_train = cleaning_csv_data(sample_train_csv_path, processed_train_csv_path)
    print('Creating train_ffm.txt if does not exist')
    encoded_train = _convert_to_ffm(
        path=train_ffm_path,
        df= df_train,
        target=target_train,
        numerics=numerics_train,
        categories=categories_train,
        encoder=encoder
    )

    print("Creating processed_test.csv if does not exist")
    target_test, numerics_test, categories_test, df_test = cleaning_csv_data(sample_test_csv_path, processed_test_csv_path)
    print('Creating test_ffm.txt if does not exist')
    encoded_test = _convert_to_ffm(
        path=test_ffm_path,
        df= df_test,
        target=target_test,
        numerics=numerics_test,
        categories=categories_test,
        encoder=encoder
    )


'''
    Author: Dasu Srinivas
    Description : Implement a queue using double linked list
'''

class Node:
    def __init__(self, value):
        self.value = value
        self.next = None
        self.prev = None

class Queue:
    def __init__(self):
        self.head = None
        self.last = None

    def enQueue(self, data):
        if self.last is None:
            self.head = Node(data)
            self.last = self.head
        else:
            self.last.next = Node(data)
            self.last.next.prev = self.last
            self.last = self.last.next

    def deQueue(self):
        if self.head is None:
            return
        else:
            temp = self.head.value
            self.head = self.head.next
            self.head.prev = None
            return temp

    def firstEle(self):
        return self.head.value

    def sizeOf(self):
        temp = self.head
        count = 0
        while temp is not None:
            count += 1
            temp = temp.next
        return count

    def isEmpty(self):
        if self.head is None:
            return True
        else:
            return False

    def printqueue(self):
        print("queue elements are:")
        temp = self.head
        while temp is not None:
            print(temp.value, end="->")
            temp = temp.next

queue = Queue()
queue.enQueue(4)
queue.enQueue(5)
queue.enQueue(6)
queue.enQueue(7)
print("First element is :", queue.firstEle())
queue.printqueue()
queue.deQueue()
queue.printqueue()

Interviewquestions/Stack and queue/queue using double linked list.py


# Suppose an array sorted in ascending order is rotated at some pivot unknown to you beforehand.
#
# (i.e.,  [0,1,2,4,5,6,7] might become  [4,5,6,7,0,1,2]).
#
# Find the minimum element.
#
# You may assume no duplicate exists in the array.
#
# Example 1:
#
# Input: [3,4,5,1,2]
# Output: 1
# Example 2:
#
# Input: [4,5,6,7,0,1,2]
# Output: 0

from typing import List

class Solution:
    def findMin(self, nums: List[int]) -> int:
        left, right = 0, len(nums) - 1
        while left <= right:
            if nums[left] <= nums[right]:  # [left, right] is in sorted order
                return nums[left]
            mid = left + (right - left) // 2
            # then, we must have nums[left]>nums[right]
            # nums[left] is definitely not the min value since at least nums[right] is less than it
            if nums[left] > nums[mid]:
                right = mid
                # if mid==right, then interval [left, right] will not shrink
                # however, interval [left, right] definitely shrinks since only when left==right we have mid==right
                # if left==right, the loop has already terminated since we returned nums[left] in the previous line
            else:
                left = mid + 1

print(Solution().findMin([2, 1]))


from __future__ import annotations

import yaml

from airflow_breeze.utils.path_utils import AIRFLOW_PROVIDERS_ROOT, AIRFLOW_SOURCES_ROOT

def get_suspended_providers_folders() -> list[str]:
    """
    Returns a list of suspended providers folders that should be
    skipped when running tests (without any prefix - for example apache/beam, yandex, google etc.).
    """
    suspended_providers = []
    for provider_path in AIRFLOW_PROVIDERS_ROOT.rglob("provider.yaml"):
        provider_yaml = yaml.safe_load(provider_path.read_text())
        if provider_yaml.get("suspended"):
            suspended_providers.append(
                provider_path.parent.relative_to(AIRFLOW_SOURCES_ROOT)
                .as_posix()
                .replace("airflow/providers/", "")
            )
    return suspended_providers

def get_suspended_provider_ids() -> list[str]:
    """
    Yields the ids of suspended providers.
    """
    suspended_provider_ids = []
    for provider_path in AIRFLOW_PROVIDERS_ROOT.rglob("provider.yaml"):
        provider_yaml = yaml.safe_load(provider_path.read_text())
        if provider_yaml.get("suspended"):
            suspended_provider_ids.append(
                provider_yaml["package-name"][len("apache-airflow-providers-") :].replace("-", ".")
            )
    return suspended_provider_ids


""" Main module to predict binding affinity or to train the model"""

import argparse
import sys

import deepdta.DTI as models
from deepdta.dataset import load_process_davis
from deepdta.utils import (
    data_process,
    generate_config,
    is_valid_smiles,
    is_valid_protein,
)

DRUG_ENCODING = "CNN"
TARGET_ENCODING = "CNN"

def train_model():
    """Train the model"""
    var_x_drug, var_x_target, var_y = load_process_davis("./data/")
    train, val, test = data_process(
        var_x_drug,
        var_x_target,
        var_y,
        DRUG_ENCODING,
        TARGET_ENCODING,
        split_method="random",
        frac=[0.7, 0.1, 0.2],
    )

    # use the parameters setting provided in the paper: https://arxiv.org/abs/1801.10193
    config = generate_config(
        drug_encoding=DRUG_ENCODING,
        target_encoding=TARGET_ENCODING,
        cls_hidden_dims=[1024, 1024, 512],
        train_epoch=100,
        LR=0.001,
        batch_size=256,
        cnn_drug_filters=[32, 64, 96],
        cnn_target_filters=[32, 64, 96],
        cnn_drug_kernels=[4, 6, 8],
        cnn_target_kernels=[4, 8, 12],
    )

    model = models.model_initialize(**config)
    model.train(train, val, test)
    model.save_model("./weights/")

def predict_dta(var_x_drug, var_x_target):
    """Predict binding affinity"""
    var_y = [0] * (len(var_x_drug) * len(var_x_target))
    var_x_pred = data_process(
        var_x_drug,
        var_x_target,
        var_y,
        DRUG_ENCODING,
        TARGET_ENCODING,
        split_method="no_split",
    )
    model = models.model_pretrained("./weights/")
    y_pred = model.predict(var_x_pred)
    return y_pred

def arg_parser():
    """Read arguments from command line"""

    parser = argparse.ArgumentParser(
        description="""DeepDTA: Deep Drug-Target Binding Affinity Prediction"""
    )
    parser.add_argument("--drug", type=str, help="Drug SMILES", required=True)
    parser.add_argument(
        "--target", type=str, help="Target(protein) sequence", required=True
    )
    return parser

def main():
    """Entrypoint function"""
    parser = arg_parser()
    var_x_drug = parser.parse_args().drug
    var_x_target = parser.parse_args().target
    if not var_x_drug:
        print("Please provide a drug SMILES")
        sys.exit(0)
    if not var_x_target:
        print("Please provide a target(protein) sequence")
        sys.exit(0)
    if not is_valid_smiles(var_x_drug):
        print(f"Invalid drug SMILES - {var_x_drug}")
        sys.exit(0)
    if not is_valid_protein(var_x_target):
        print(f"Invalid protein sequence - {var_x_target}")
        sys.exit(0)
    try:
        y_pred = predict_dta([var_x_drug], [var_x_target])
        print(f"Predicted affinity: {y_pred[0]}")
    except Exception as err:
        print(err)
        sys.exit(0)

if __name__ == "__main__":
    main()


import numpy as np
from numpy import exp, log, dot, zeros, outer, random, dtype, float32 as REAL,\
    double, uint32, seterr, array, uint8, vstack, fromstring, sqrt, newaxis,\
    ndarray, empty, sum as np_sum, prod, ones, ascontiguousarray, vstack
from gensim import utils, matutils  # utility fnc for pickling, common scipy operations etc
from collections import defaultdict
import math
import argparse
from binarypredictor import BinaryPredictor
import sys

class SkipGram(BinaryPredictor):
    def __init__(self, filename, window=10, size=600, decay=5, balanced=False, prior=True,
                 dataset="ucsd", model="org"):
        self._window = window
        self._size = size
        self._decay = decay
        self._prior_pred = prior
        self._stopwordslist = []
        self._dataset = dataset
        self._props = {"window": window, "size": size, "decay": decay, "prior": prior,
                       "balanced": balanced, "dataset": dataset, "model": model}
        super(SkipGram, self).__init__(filename)

    def train(self, filename):
        print(filename)
        #import pdb; pdb.set_trace()
        self.base_train(filename, skipgram=1)
        #self.base_train(filename)

    def predict(self, feed_events):
        #import pdb; pdb.set_trace()
        te = len(feed_events)
        #weighted_events = [(e,  math.exp(self._decay*(i-te+1)/te))
        #Henry
        weighted_events = [(e,  math.exp(self._decay*(i-te+1)/float(te)))
                           for i, e in enumerate(feed_events) if e in self._model.vocab]
        ###old method
#        try:
#        #import pdb; pdb.set_trace()
#            predictions = defaultdict(
#                lambda: 1, {d: sim * (sim > 0) for d, sim in self._model.most_similar(
#                    weighted_events, topn=self._nevents)})
#
#        #predictions ={d: sim * (sim > 0) for d, sim in self._model.most_similar(weighted_events, topn=self._nevents)}
#
#
#        except:
#            #import pdb; pdb.set_trace()
#            predictions = defaultdict(lambda: 0, {d:0  for d in self._diags})
#

        #### NEW method ####
        self._model.syn0norm = (self._model.syn0 / np.sqrt((self._model.syn0 ** 2).sum(-1))[..., np.newaxis]).astype(REAL)

        predictions = {}

        for diag in self._diags:
            ##original method same as above
            #sub_feed_events = feed_events[:]

            #HEnry's prediction (1) deleting diag from history but using the rest of history
            sub_feed_events = [event for event in feed_events if event != diag]

            ##HEnry's prediction (2) deleting diag from history and the rest of history
            #sub_feed_events = []
            #for event in feed_events:
            #    if event != diag:
            #        sub_feed_events.append(event)
            #    else:
            #        break

            te = len(sub_feed_events)
            weighted_events = [(e,  math.exp(self._decay*(i-te+1)/float(te)))
                               for i, e in enumerate(sub_feed_events) if e in self._model.vocab]

            all_words, mean = set(), []
            for word, weight in weighted_events:
                #if word != diag:
                if word in self._model.vocab:
                    #import pdb; pdb.set_trace()
                    mean.append(weight * self._model.syn0norm[self._model.vocab[word].index])
                    all_words.add(self._model.vocab[word].index)
                else:
                    raise KeyError("ERRORRRR word '%s' not in vocabulary" % word)
            if not mean:
                #import pdb; pdb.set_trace()
                #raise ValueError("ERRORRRR cannot compute similarity with no input")
                predictions[diag] = 0
                continue

            mean = matutils.unitvec(array(mean).mean(axis=0)).astype(REAL)

            try:
                dists = dot(matutils.unitvec(self._model[diag]), mean)
                predictions[diag] = dists
            except:
                #print "can't find diag", diag
                predictions[diag] = 0

        # henry addition for two sites, not neccessary in original Wael model
        #for each in feed_events:
        #    if not each.endswith('_m'):
        #        predictions[each+'_m'] = 1
        #    if each.endswith('_m'):
        #        predictions[each[:-2]] = 1
            #predictions[each] = 1

        #import pdb; pdb.set_trace()
        return predictions

    def word_vector_graph(self, filename):
        from matplotlib import pyplot as plt
        # import seaborn
        self.counts = defaultdict(lambda: 0)
        with open(filename) as f:
            for s in f:
                sentense = s.split("|")[2].split(" ") + s.split("|")[3].replace("\n", "").split(" ")
                for e in sentense:
                    self.counts[e] += 1

        fig = plt.figure(figsize=(14, 14), dpi=180)
        colors = {"d": "black", "p": "blue", "l": "red", "s": "green", "c": "orange"}
        plt.plot()
        ax = fig.add_subplot(111)

        events = []
        for t in ["c", "s", "p", "d", "l"]:
            evs = {e: c for e, c in self.counts.items() if e.startswith(t)}
            events += [x for x, y in sorted(evs.items(), key=lambda k: k[1], reverse=True)[:100]]

        for e in events:
            if e in ["c_V3000", "c_V053", "c_V502", "c_V3001", "c_290", "c_V290"]:
                continue
            if e in self._model.vocab:
                v = self._model[e]
                plt.plot(v[0], v[1])
                ax.annotate(e, xy=v, fontsize=10, color=colors[e[0]])

        p = ax.bar(0, [0], 0, color='blue')
        d = ax.bar(0, [0], 0, color='black')
        c = ax.bar(0, [0], 0, color='orange')
        s = ax.bar(0, [0], 0, color='green')
        l = ax.bar(0, [0], 0, color='red')
        ax.legend((d[0], p[0], l[0], c[0], s[0]), ('Diagnosis', 'Prescription', 'Lab test',
                                                   'Condition', 'Symptom'), loc=4)
        plt.savefig('../Results/Plots/event_'+self._props["dataset"]+'_colored.png')
        sys.exit(0)

if __name__ == '__main__':
    parser = argparse.ArgumentParser(description='SkipGram Similarity')
    parser.add_argument('-w', '--window', action="store", default=10, type=int,
                        help='Set max skip length between words (default: 10)')
    parser.add_argument('-s', '--size', action="store", default=600, type=int,
                        help='Set size of word vectors (default: 600)')
    parser.add_argument('-d', '--decay', action="store", default=5, type=float,
                        help='Set exponential decay through time (default: 5)')
    parser.add_argument('-p', '--prior', action="store", default=0, type=int,
                        help='Add prior probability (0 for False, 1 for True) default 0')
    parser.add_argument('-b', '--balanced', action="store", default=0, type=int,
                        help='Whether to use balanced or not blanaced datasets (0 or 1) default 0')
    parser.add_argument('-ds', '--dataset', action="store", default="ucsd", type=str,
                        help='Which dataset to use "ucsd" or "mimic", default "ucsd"')
    parser.add_argument('-m', '--model', action="store", default="org", type=str,
                        help='Which model to use "org" or "chao", default "org"')
    args = parser.parse_args()

    ds = "ucsd"
    if args.dataset == "mimic":
        ds = "mimic"

    data_path = "../Data/" + ds + "_seq/"
    if args.balanced:
        data_path = "../Data/" + ds + "_balanced/"

    prior = False if args.prior == 0 else True
    bal = False if args.balanced == 0 else True
    model = SkipGram(data_path + 'vocab', args.window, args.size, args.decay, bal, prior, ds,
                     args.model)

    train_files = []
    valid_files = []
    test_files = []
    #for i in range(10):
    #for i in range(1):
    #    train_files.append(data_path + 'trainv_'+str(i))
    #    valid_files.append(data_path + 'test_'+str(i))
    ##model.train('trainv_0')
    ##model.train('ucsd_tv0')

    model.train('../Data/mimic_seq/trainv_2')
    ##model.train('../Data/mimic_seq/test_0')
    model.valid('../Data/mimic_seq/test_2')
    model.outname = 'org2'
    model.write_stats()

    model.train('/Users/henry/Desktop/SequentialPhenotypePredictor/Prediction/nmdsExp_mtv2/diabetes_cohorts/d_715/deleteWord')
    ##model.train('../Data/mimic_seq/test_0')
    model.valid('../Data/mimic_seq/test_2')
    model.outname = 'deletedW'
    model.write_stats()

    #model.outname = 'per1'
    #model.write_stats()
    #model.train('ucsd_tv0')

    #model.cross_validate(train_files, valid_files)
    #model.write_stats()
    #print(model.accuracy)
    #model.plot_roc()


import requests
from bs4 import BeautifulSoup
import time
class League:
    def __init__(self, name,links,date):
        self.name = name
        self.links = links
        self.date = date # the date is the split date instead of starting date of the tournament

def links_creater(link,pages):
    links = []
    links.append(link)
    i = 2
    while i != (pages + 1):
        links.append(link + "&page=" + str(i))
        i = i + 1
    return links

def date_compare(date1,date2):
    date1_list = date1.split("-")
    date2_list = date2.split("-")
    i = 0
    while i < 3:
        if date1_list[i] == date2_list[i]:
            i = i + 1
            continue
        if date1_list[i] > date2_list[i]:
            return 0
        else:
            return 1

    raise Exception('the split date should not equal to any actual match date.')

def get_matchid_of_league(league):
    match_table = {}
    qualifier = []
    main_event = []
    for link in league.links:
        target = link
        # fake UA to bypass Dotabuff's anti spider mechanism
        headers = {
            'User-Agent':'Mozilla/5.0 (Windows; U; Windows NT 6.1; en-US; rv:1.9.1.6) Gecko/20091201 Firefox/3.5.6'
        }
        r = requests.get(url = target, headers = headers)
        html = r.text
        #print(html)
        bf = BeautifulSoup(html,features="html.parser")
        list_match = []
        for entry in bf.find_all('td',class_ = "cell-mediumlarge"):
            list_match.append(entry)
        #print( len(list_match))
        for match in list_match:
            bf_sub = BeautifulSoup(str(match),features="html.parser")
            match_id = str(bf_sub.a.contents[0])
            date_list = bf_sub.time['datetime'].split('T')
            date = date_list[0]
            match_table[match_id] = date
            if date_compare(date,league.date) == 1:
                qualifier.append(match_id)
            else:
                main_event.append(match_id)

        time.sleep(1) # limit request rate to prevent unusual traffic toward Dotabuff
        # If code runs normally, we should only request each page once

    return match_table, qualifier, main_event

def differed_id(league_name):
    league = None
    if league_name == "Bucharest Minor":
        links_b = links_creater("https://www.dotabuff.com/esports/leagues/10452-the-bucharest-minor-2019/matches?original_slug=10452-the-bucharest-minor-2019",7)
        league = League('Bucharest Minor',links_b,"2019-01-08")
    if league_name == "DreamLeague S10":
        links_b = links_creater("https://www.dotabuff.com/esports/leagues/10326-dreamleague-season-10/matches?original_slug=10326-dreamleague-season-10",8)
        league = League('DreamLeague S10',links_b,"2018-10-28")
    if league_name == "DreamLeague S11":
        links_b = links_creater("https://www.dotabuff.com/esports/leagues/10681-dreamleague-season-11/matches?original_slug=10681-dreamleague-season-11",23)
        league = League('DreamLeague S11',links_b,"2019-03-12")
    if league_name == "SL-i Minor":
        links_b = links_creater("https://www.dotabuff.com/esports/leagues/10733-starladder-imbatv-dota2-minor/matches?original_slug=10733-starladder-imbatv-dota2-minor",7)
        league = League('SL-i Minor',links_b,"2019-03-05")
    if league_name == "Kuala Lumpur Major":
        links_b = links_creater("https://www.dotabuff.com/esports/leagues/10296-the-kuala-lumpur-major/matches?original_slug=10296-the-kuala-lumpur-major",20)
        league = League('Kuala Lumpur Major',links_b,"2018-11-07")
    if league_name == "Chongqing Major":
        links_b = links_creater("https://www.dotabuff.com/esports/leagues/10482-the-chongqing-major/matches?original_slug=10482-the-chongqing-major",15)
        league = League('Chongqing Major',links_b,"2019-01-17")
    if league_name == "Paris Major":
        links_b = links_creater("https://www.dotabuff.com/esports/leagues/10810-mdl-disneyland-paris-major/matches?original_slug=10810-mdl-disneyland-paris-major",12)
        league = League('Paris Major',links_b,"2019-05-02")
    if league_name == "PIT Minor":
        links_b = links_creater("https://www.dotabuff.com/esports/leagues/10869-amd-sapphire-dota-pit-minor-2019/matches?original_slug=10869-amd-sapphire-dota-pit-minor-2019",6)
        league = League('PIT Minor',links_b,"2019-04-20")

    table,qualifier,main_event = get_matchid_of_league(league)
    return table, qualifier, main_event


from django.shortcuts import render
from django.contrib import messages
from .models import MessagesList
# Create your views here.

def contact(request):

    if request.method == 'POST':
        try:
            name = request.POST['name']
            email = request.POST['email']
            subject = request.POST['subject']
            message = request.POST['message']

            new_message =  MessagesList(
                        name = name,
                        email =email,
                        subject = subject,
                        message = message)
            new_message.save()
            messages.success(
                request, f'Your Message has been sent')
        except:
            messages.warning(
                request, f'An unknown error occurred, please contact us in another way')
    return render(request, 'contact/contact.html', )


try:
    # This is built by setuptools_scm
    from .version import version as __version__  # noqa: F401
except ImportError:
    __version__ = "1.7.0rc"

__title__ = "decisionengine_modules"
__description__ = "The HEPCloud Decision Engine Framework"
__author__ = "Fermi Research Alliance LLC"
__license__ = "Fermitools Software Legal Information (Modified BSD License)"
__url__ = "http://hepcloud.fnal.gov"


# { 'dictionary' : value }
city = {'Seoul' : 0, 'Busan' : 1}
print(city['Seoul'])
print(city['Busan'])
city['Bucheon'] = 2
print(city)

# for loop
for k in [1,2,3,4,5]:
    print("Hello Everyone!")

# Without for loop
print("Hello Everyone!")
print("Hello Everyone!")
print("Hello Everyone!")
print("Hello Everyone!")
print("Hello Everyone!")

# the range function
for k in range(1,6):
    print(k, "squared is", k*k)

for x in range(5, 0, -1):
    print(x)

# cumulative loops : summaion
sum = 0
for i in range(1, 21):
    sum = sum + (i*i)
print("sum of first 20 squares is", sum)  #2870

#DIY 20!
fac = 1
for k in range(2,101):
    fac= fac*k
print('100!=', fac)

# while loop
sum = 0
k = 1
while k < 21:
    sum = sum + k*k
    k = k+1
print(sum)

# if / else
score = 50
if score < 60:
    print("Your credit is F")
else:
    print("Your credit is A+")

# if / elif 효율적

# DIY
import matplotlib.pyplot as plt
a = -2
b = 2
n = 401
dx = (b-a)/(n-1)
x_list = []
y_list = []

for i in range(0,n):
    x = a + i*dx
    y = x**5-5*x**3+4*x
    x_list.append(x)
    y_list.append(y)

plt.plot(x_list, y_list)
plt.show()


def guess_the_word(n, words):
    words = words.split()
    max_length = 0
    max_word = ""
    for word in words:
        if len(word) % 2 == 1 and len(word) > max_length:
            max_length = len(word)
            max_word = word
    if max_word:
        return max_word
    else:
        return "Better luck next time"

n = 5
words = "Hello Good Morning Welcome You"

print(guess_the_word(n, words))

December - 09/Day 9 - Kochouseph Konundrum!.py


import pickle
import numpy as np
import glob
import torch
import torch
import torchvision.transforms as transforms

def cifarUnpickle(file):
    with open(file, 'rb') as fo:
        dict = pickle.load(fo, encoding = 'bytes')
        return dict

def cifar10Data(datasetPath, select = None):
    trainFile = glob.glob(datasetPath + '/data*')
    trainLabel = []
    trainImage = []
    testFile = glob.glob(datasetPath + '/test*')

    for f in trainFile:
        current = cifarUnpickle(f)
        currentLabel = current[b'labels']
        currentLabel = torch.tensor(currentLabel)
        currentImage = current[b'data']
        currentImage = torch.from_numpy(currentImage)
        trainLabel.append(currentLabel)
        trainImage.append(currentImage)
    trainLabel = tuple(trainLabel)
    trainImage = tuple(trainImage)
    trainLabel = torch.cat(trainLabel, dim = 0)
    trainImage = torch.cat(trainImage, dim = 0)

    testFile = cifarUnpickle(testFile[0])
    testLabel = torch.tensor(testFile[b'labels'])
    testImage = torch.from_numpy(testFile[b'data'])

    trainImage = trainImage.reshape(trainImage.shape[0], 3, 32, 32)
    testImage = testImage.reshape(testImage.shape[0], 3, 32, 32)
    trainImage = trainImage.permute(0, 2, 3, 1).numpy()
    testImage = testImage.permute(0, 2, 3, 1).numpy()

    return trainLabel, trainImage, testLabel, testImage

def cifar100Data(datasetPath, select = None):
    trainFile = datasetPath + '/train'
    testFile = datasetPath + '/test'

    trainFile = cifarUnpickle(trainFile)
    testFile = cifarUnpickle(testFile)

    trainLabel = trainFile[b'fine_labels']
    trainLabel = torch.tensor(trainLabel)
    trainImage = trainFile[b'data']

    testLabel = testFile[b'fine_labels']
    testLabel = torch.tensor(testLabel)
    testImage = testFile[b'data']

    trainImage = torch.from_numpy(trainImage)
    testImage = torch.from_numpy(testImage)
    trainImage = trainImage.reshape(trainImage.shape[0], 3, 32, 32)
    testImage = testImage.reshape(testImage.shape[0], 3, 32, 32)
    trainImage = trainImage.permute(0, 2, 3, 1).numpy()
    testImage = testImage.permute(0, 2, 3, 1).numpy()

    return trainLabel, trainImage, testLabel, testImage

def prepareData10(datasetPath, workPath, vecLabel = False):
    data = cifar10Data(datasetPath, vecLabel)

    torch.save(data[0],workPath + '/trainLabel')
    torch.save(data[1], workPath + '/trainImage')
    torch.save(data[2], workPath + '/testLabel')
    torch.save(data[3], workPath + '/testImage')
    torch.save(data[2], workPath + '/valLabel')
    torch.save(data[3], workPath + '/valImage')

def prepareData100(datasetPath, workPath, vecLabel = False):
    data = cifar100Data(datasetPath, vecLabel)

    torch.save(data[0],workPath + '/trainLabel')
    torch.save(data[1], workPath + '/trainImage')
    torch.save(data[2], workPath + '/testLabel')
    torch.save(data[3], workPath + '/testImage')
    torch.save(data[2], workPath + '/valLabel')
    torch.save(data[3], workPath + '/valImage')

class CifarSet(torch.utils.data.Dataset):
    def __init__(self, workPath, mode = 'train', vecLabel = False, nbClass = 10):
        super(CifarSet, self).__init__()
        self.mode = mode
        self.image = torch.load(workPath + '/{}Image'.format(mode))
        self.label = torch.load(workPath + '/{}Label'.format(mode))
        self.vecLabel = vecLabel
        self.nbClass = nbClass
        self.transform = transforms.Compose(
            [transforms.ToPILImage(),
            transforms.Resize([224, 224]),
            transforms.ToTensor(),
            transforms.Normalize(mean = [0.485, 0.456, 0.406], std = [0.229, 0.224, 0.225])])
    def __getitem__(self, index):
        x = self.image[index]
        x = self.transform(x)
        y = self.label[index]
        if(self.vecLabel):
            t = torch.zeros(self.nbClass)
            t[y] = 1
            y = t
        return x, y, index

    def __len__(self):
        assert self.label.shape[0] == self.image.shape[0]
        return self.label.shape[0]

if __name__ == '__main__':
    pass


'''
Created on 6/07/2015

@author: EJArizaR
'''

from scrapy.crawler import CrawlerProcess
from spiders.Dane import DaneSpider

class SpiderLauncher:
    def run(self, linksFilePath):
        settings = {"LOG_LEVEL": "WARNING",
                    "FEED_FORMAT": "json",
                    "FEED_URI": "file:///" + linksFilePath}
        process = CrawlerProcess(settings)
        spider = DaneSpider()
        process.crawl(spider)
        process.start()


# coding=utf-8

from projection import projection_by_random
from predictor import Predictor
from metrics import mean_reciprocal_rank, mean_average_precision
from tqdm import tqdm
import numpy as np
from random import random

def dueling_bandits(x_dict, y_dict, weight, dims, delta, ganma, metric):
    """ Update function for DBGD.
    Params:
        x_dict(dict): dict of csr_matrix of feature vectors.
        y_dict(dict): dict of np.ndarray of labels corresponding to each feature vector
        weight(csr_matrix): weight vector
        dims(int): # of dimensions of weight vector
        delta(float): exploration parameter
        ganma(float): exploitation parameter
        metric(str): metric for optimization (MAP or MRR)
    Returns:
        weight: updated weight

    Note that
    """

    if metric == "MRR":
        calc_metric = mean_reciprocal_rank
    elif metric == "MAP":
        calc_metric = mean_average_precision

    for qid, features in tqdm(x_dict.items()):
        cand_w, u = projection_by_random(weight, dims, delta)
        # If you would like to use your own duel function,
        # you need to replace "duel_by_offline_data" with your duel function.
        if duel_by_offline_data(features, y_dict[qid], cand_w, weight, calc_metric):
            weight, _ = projection_by_random(weight, dims, ganma, u=u) # update weight

    return weight

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

def is_cand_beats_curr(prob):
    if prob > random():
        return True
    else:
        return False

def duel_by_offline_data(features, true_labels, cand_w, current_w, calc_metric):
    """ Duel function to compare candidate weight with current weight by offline data.
    Note that, this offline duel might be not standard settings for dueling bandit gradient descent (DBGD).
    In DBGD, models should be trained based on real-time user feedback data using some interleaved lists.
    If you would like to train models based on such setting,
    you need to implement your own duel function and compare candidate weight with current weight.

    Args:
        features(csr_matrix): csr_matrix of feature vectors. Each vector is represented by np.ndarray
        true_labels(list): List of true labels
        cand_w(csr_matrix): candidate weight vector
        current_w(csr_matrix): current weight vector
        calc_metric(function): function that calculate ranking metric
    Returns:
        bool: booling value whether candidate weight wins current weight or not .
    """
    C = 10.0

    # make rankings
    predictor = Predictor()
    current_rank = [gold for (gold, _, _) in predictor.predict_and_ranks(features, true_labels, current_w)]
    cand_rank = [gold for (gold, _, _) in predictor.predict_and_ranks(features, true_labels, cand_w)]

    v_curr = C * calc_metric([current_rank])  # value for current weight
    v_cand = C * calc_metric([cand_rank])  # value for candidate weight
    prob_cand_beats_curr = 1.0 - sigmoid(v_curr - v_cand)
    if is_cand_beats_curr(prob_cand_beats_curr):
        # candidate weight wins current weight
        return True

    return False


# -*- coding: utf-8 -*-
# flake8: noqa
# pylint: skip-file
from ._kb import query

__version__ = '0.0.1'

__plugin_author__ = 'willemjan'
__plugin_description__ = 'Metadata for books from the National Library of the Netherlands'
__plugin_homepage__ = 'github.com/kbNLresearch/isbnlib-kb'
__plugin_service_language__ = 'nl'
__plugin_service_name__ = 'kb'
__plugin_type__ = 'metadata'


from courtrecords.security.acl import ACL
from courtrecords.models import DBSession, Users, Cases, Entities, ActionTypes, Counties, Roles, Prefixs, Suffixs
from courtrecords.utilities.utility import has_interface
from courtrecords.views import BaseView
from pyramid.view import view_config
import transaction

class ManageEntities(BaseView):

    @view_config(route_name='manage_entities', renderer='../themes/templates/admin/entities.pt', permission=ACL.EDITOR)
    def manage_entities(self):
        return self.response

    @view_config(route_name='manage_entities_get', renderer='json', permission=ACL.EDITOR)
    def manage_entities_get(self):

        order_headings = ['entities.id',
                          'entities.case_id',
                          'entities.entity',
                          'entities.prefix',
                          'entities.lastname',
                          'entities.middlename',
                          'entities.firstname',
                          'entities.suffix',
                          'entities.alternatename',
                          'entities.role'
                          ]

        # Determine Order
        order_index = int(self.request.params.get('order[0][column]', 0))
        order = order_headings[order_index] + ' ' + self.request.params.get('order[0][dir]', 'asc')
        limit = int(self.request.params.get('length', 15))
        offset = int(self.request.params.get('start',0))

        query = DBSession.query(Entities,Roles,Prefixs,Suffixs).filter(Entities.role == Roles.id) \
                                                               .filter(Entities.suffix == Suffixs.id) \
                                                               .filter(Entities.prefix == Prefixs.id)
        count = query.count() # get total number of records
        objs = query.order_by(order).offset(offset).limit(limit).all()

        results = {"recordsTotal": count,
                   "recordsFiltered": count,
                   "data": []
        }
        for obj in objs:
            results['data'].append([
                obj.Entities.id,
                obj.Entities.case_id,
                obj.Entities.entity,
                obj.Prefixs.prefix,
                obj.Entities.lastname,
                obj.Entities.middlename,
                obj.Entities.firstname,
                obj.Suffixs.suffix,
                obj.Entities.alternatename,
                obj.Roles.role,
                'Delete'
            ])

        return results


import scipy.ndimage as nd
import scipy.ndimage.filters as filters
from keras import losses
import tensorflow as tf
import numpy as np

def hfenn_loss(ori, res):
    '''
    HFENN-based loss
    ori, res - batched images with 3 channels
    See metrics.hfenn
    '''
    fnorm = 0.325 # norm of l_o_g operator, estimated numerically
    sigma = 1.5 # parameter from HFEN metric
    truncate = 4 # default parameter from filters.gaussian_laplace
    wradius = int(truncate * sigma + 0.5)
    eye = np.zeros((2*wradius+1, 2*wradius+1), dtype=np.float32)
    eye[wradius, wradius] = 1.
    ker_mat = filters.gaussian_laplace(eye, sigma)
    with tf.name_scope('hfenn_loss'):
        chan = 3
        ker = tf.constant(np.tile(ker_mat[:, :, None, None], (1, 1, chan, 1)))
        filtered = tf.nn.depthwise_conv2d(ori - res, ker, [1, 1, 1, 1], 'VALID')
        loss = tf.reduce_mean(tf.square(filtered))
        loss = loss / (fnorm**2)
    return loss

def ae_loss(input_img, decoder):
    mse = losses.mean_squared_error(input_img, decoder) # MSE
    weight = 10.0 # weight
    return mse + weight * hfenn_loss(input_img, decoder) # MSE + weight * HFENN

def ssim_loss(y_true, y_pred):
    return tf.reduce_mean(tf.image.ssim(y_true, y_pred, 2.0))

def psnr_loss(y_true, y_pred):
    return tf.reduce_mean(tf.image.psnr(y_true, y_pred, 2.0))


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

n, m = map(int, si().rstrip().split())
mmap = [list(map(int, si().rstrip().split())) for _ in range(n)]
answer = [[-1 for _ in range(m)] for _ in range(n)]

# answer에서 0인 부분 0으로 초기화
def answer_init():
    global answer
    for i in range(n):
        for j in range(m):
            if mmap[i][j] == 0:
                answer[i][j] = 0

# 목표지점(2인 점) 반환
def find_target():
    global mmap
    for i in range(n):
        for j in range(m):
            if mmap[i][j] == 2:
                return i, j

def in_range(x, y):
    global n, m
    return 0 <= x and x < n and 0 <= y and y < m

# 범위를 안 벗어나고 갈 수 있는 곳(mmap->1) 중 아직 안 간 곳(answer->-1)인지
def can_go(x, y):
    global mmap
    return in_range(x, y) and mmap[x][y] == 1 and answer[x][y] == -1

def bfs(start_x, start_y):
    global mmap, answer
    q = deque()
    dxs, dys = [-1, 1, 0, 0], [0, 0, -1, 1]

    answer[start_x][start_y] = 0
    q.append((start_x, start_y, 0))

    while q:
        x, y, step = q.popleft()

        for dx, dy in zip(dxs, dys):
            new_x, new_y = x + dx, y + dy
            if can_go(new_x, new_y):
                answer[new_x][new_y] = step + 1
                q.append((new_x, new_y, step + 1))

answer_init()
target_x, target_y = find_target()
bfs(target_x, target_y)
for i in range(n):
    for j in range(m):
        print(answer[i][j], end=' ')
    print()


import platform
import pytest
import dartpy as dart

def collision_groups_tester(cd):
    size = [1, 1, 1]
    pos1 = [0, 0, 0]
    pos2 = [0.5, 0, 0]

    simple_frame1 = dart.dynamics.SimpleFrame()
    simple_frame2 = dart.dynamics.SimpleFrame()

    sphere1 = dart.dynamics.SphereShape(1)
    sphere2 = dart.dynamics.SphereShape(1)

    simple_frame1.setShape(sphere1)
    simple_frame2.setShape(sphere2)

    cd = dart.collision.FCLCollisionDetector()
    group = cd.createCollisionGroup()
    group.addShapeFrame(simple_frame1)
    group.addShapeFrame(simple_frame2)

    #
    #    ( s1,s2 )              collision!
    # ---+---|---+---+---+---+--->
    #   -1   0  +1  +2  +3  +4
    #
    assert group.collide()

    #
    #    (  s1   )   (  s2   )  no collision
    # ---+---|---+---+---+---+--->
    #   -1   0  +1  +2  +3  +4
    #
    simple_frame2.setTranslation([3, 0, 0])
    assert not group.collide()

    option = dart.collision.CollisionOption()
    result = dart.collision.CollisionResult()

    group.collide(option, result)
    assert not result.isCollision()
    assert result.getNumContacts() is 0

    option.enableContact = True
    simple_frame2.setTranslation([1.99, 0, 0])

    group.collide(option, result)
    assert result.isCollision()
    assert result.getNumContacts() is not 0

def test_collision_groups():
    cd = dart.collision.FCLCollisionDetector()
    collision_groups_tester(cd)

    cd = dart.collision.DARTCollisionDetector()
    collision_groups_tester(cd)

    if hasattr(dart.collision, "BulletCollisionDetector"):
        cd = dart.collision.BulletCollisionDetector()
        collision_groups_tester(cd)

    if hasattr(dart.collision, "OdeCollisionDetector"):
        cd = dart.collision.OdeCollisionDetector()
        collision_groups_tester(cd)

if __name__ == "__main__":
    pytest.main()


from random import randint

w = randint(5,9)
gameOn = 1
grid = [[0 for i in range(w)]for i in range(w)]
fakeGrid = [["█" for i in range(w)]for i in range(w)]
mineCount = randint(w//2,w*w//5)
moveJ = [-1,-1,0,1,1,1,0,-1]
moveI = [0,1,1,1,0,-1,-1,-1]

# placing mines
for i in range(mineCount) :
    grid[randint(0,w-1)][randint(0,w-1)] = "M"

# determining how many mines are adjacent to that tile
for i in range(w) :
    for j in range(w) :
        counter = 0
        if (grid[j][i] == 0) :
            for k in range(len(moveI)) :
                if (i + moveI[k] < w and i + moveI[k] >= 0 and j + moveJ[k] < w and j + moveJ[k] >= 0) :
                    if (grid[j + moveJ[k]][i + moveI[k]] == "M") :
                        counter += 1
            grid[j][i] = counter

def printGrid(fakeGrid, w) :
    print("  ",end="")
    for i in range(w) :
        print("  " + str(i+1) + " " , end="")
    print()
    print("  ┌", end="")
    for i in range((w*3)+w-1) :
        print("─", end="")
    print("┐")
    for i in range(w) :
        print(str(i+1) + " ",end="")
        for k in range(w) :
            print("│ " + str(fakeGrid[k][i]), end=" ")
        print("│")
        if (i != w-1) :
            print("  │", end="")
            for k in range((w*3)+w-1) :
                print("─", end="")
            print("│")
        elif (i == w-1) :
            print("", end="")
            print("  └", end="")
            for i in range((w*3)+w-1) :
                print("─", end="")
            print("┘")

# checks your choices
def isRevealed(grid, fakeGrid, choice, moveJ, moveI, w, gameOn) :
    x,y = int(choice.split(None, 1)[0]) - 1, int(choice.split(None, 1)[1]) - 1
    """
    if (grid[x][y] == 0) :
        fakeGrid[x][y] = " "
        for k in range(len(moveI)) :
            if (y + moveI[k] < 5 and y + moveI[k] >= 0 and x + moveJ[k] < 5 and x + moveJ[k] >= 0) :
                choice = str(x + moveJ[k]) + " " + str(y + moveI[k])
                if (grid [int(choice.split(None, 2)[0])][int(choice.split(None, 2)[1])] == 0) :
                    fakeGrid [int(choice.split(None, 2)[0])][int(choice.split(None, 2)[1])] == " "
                isRevealed(grid, fakeGrid, choice, moveJ, moveI, w, gameOn)
        gameOn = 0
        return gameOn
    """
    for i in range(w) :
        for k in range(w) :
            if (grid[k][i] == 0) :
                fakeGrid[i][k] = " "

    if (grid[x][y] == "M") :
        fakeGrid[x][y] == "M"
        gameOn = 0
        return gameOn
    else :
        fakeGrid[x][y] = grid[x][y]
        gameOn = 1
        return gameOn

def isWin(grid, fakeGrid, w) :
    for i in range(w) :
        for k in range(w) :
            if (grid[k][i] != "M" and fakeGrid[k][i] == "█") :
                return False
    return True

printGrid(fakeGrid, w)
print("Example input: " + str(randint(1,w)) + " " + str(randint(1,w)))
while gameOn == 1 :
    choice = input("Input: ")
    gameOn = isRevealed(grid, fakeGrid, choice, moveJ, moveI, w, gameOn)
    printGrid(fakeGrid, w)
    if (gameOn == 0) :
        print("Game Over. Mine found.")
        printGrid(grid, w)
    if (isWin(grid, fakeGrid, w)) :
        print("You won.")
        printGrid(grid, w)
        gameOn = 0


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

import time
import os
import json
from cv2 import split
from celery.result import AsyncResult, ResultBase
from celery import app as app_celery
from flask import render_template, Blueprint, jsonify, request, redirect, url_for, flash, send_file
from project.server.tasks import upload_task
from werkzeug.utils import secure_filename
from project.server.sign import sign
import uuid
from datetime import datetime, timedelta
import glob
import sqlite3
from sqlite3 import Error

DATABASE = '/usr/src/app/project/db/db.db'

def get_db_connection():
    """ create a database connection to the SQLite database
        specified by db_file
    :param db_file: database file
    :return: Connection object or None
    """
    conn = None
    try:
        conn = sqlite3.connect(DATABASE)
        return conn
    except Error as e:
        print(e)

    return conn

def create_record(conn, record):
    sql = ''' INSERT INTO records(fid,tid,token,active,fname,fext, created)
              VALUES(?,?,?,?,?,?,?) '''
    cur = conn.cursor()
    cur.execute(sql, record)
    conn.commit()

    return cur.lastrowid

main_blueprint = Blueprint("main", __name__, )

def allowed_file(filename):
    return '.' in filename and \
        filename.rsplit('.', 1)[1].lower() in {'pdf', 'jpeg', 'jpg', 'png'}

@main_blueprint.route("/", methods=["GET"])
def home():
    return render_template("main/home.html")

@main_blueprint.route("/my/<id>", methods=["GET"])
def my(id):
    conn = get_db_connection()
    data = conn.execute(
        'SELECT tid, fid, token FROM records WHERE token LIKE \'' + id + '\' AND active = 1 AND created > datetime(\'now\', \'+2 hour\') ORDER BY created DESC').fetchall()
    conn.close()

    ids = []
    for i in data:
        ids.append((i[0], i[1]))

    return jsonify({"ids": ids}), 202

@main_blueprint.route("/detail/<task_id>", methods=["GET"])
def detail(task_id):
    conn = get_db_connection()
    data = conn.execute('SELECT * FROM records WHERE tid LIKE \'' + task_id + '\'').fetchone()
    conn.close()

    return jsonify({"task": data}), 202

@main_blueprint.route('/delete/<task_id>', methods=['GET'])
def delete_file(task_id):
    sql = 'UPDATE records SET active = 0 WHERE tid LIKE \'' + task_id + '\''
    conn = get_db_connection()

    try:
        conn.execute(sql)
        conn.commit()
    except Error:
        return jsonify({"task": ""}), 202,
    finally:
        conn.close()

    return jsonify({"task": task_id}), 202,

@main_blueprint.route('/upload', methods=['GET', 'POST'])
def upload_file():

    directory = '/usr/src/app/project/uploads/main'

    if not os.path.exists(directory):
        os.mkdir(directory, 777)

    if request.method == 'POST':

        if 'file' not in request.files:
            flash('No file part')
            return redirect(request.url)

        file = request.files['file']
        form = request.form

        if 'user' not in form:
            flash('No user part')
            return redirect(request.url)

        user = form['user']

        name = ""
        if 'fname' in form:
            name = form['fname']

        if file.filename == '':
            flash('No selected file')
            return redirect(request.url)

        if file and allowed_file(file.filename):

            filename = secure_filename(file.filename)
            flash(filename)
            unique = str(uuid.uuid4())
            ext = str(os.path.splitext(filename)[1])
            secure = unique + ext

            if not os.path.exists(directory + '/' + unique):
                os.mkdir(directory + '/' + unique, 777)

            path = os.path.join(directory, unique, secure)
            file.save(path)

            task = upload_task.delay(path, unique, ext)

            conn = get_db_connection()
            created = datetime.now() + timedelta(hours=3)
            record = (unique, task.id, user, 1, name, ext, created)
            create_record(conn, record)
            conn.close()

            return jsonify({"task_id": task.id, "file_id": unique}), 202, {
                'Location': url_for('main.get_status', task_id=task.id, file_id=unique)}

@main_blueprint.route('/download/<file_id>', methods=['GET'])
def download_file(file_id):

    directory = '/usr/src/app/project/uploads/goal'

    if not os.path.exists(directory):
        os.mkdir(directory, 777)

    response = {
        "error": "Missing file"
    }

    if request.method == 'GET':
        dir = os.path.join(directory, file_id)
        files = glob.glob(dir + "/*.pdf")

        if len(files) == 1:

            return send_file(files[0], as_attachment=True)
        if len(files) == 0:

            return jsonify(response), 404

    return jsonify(response), 404

@main_blueprint.route("/tasks/<task_id>/<file_id>", methods=["GET"])
def get_status(task_id, file_id):
    conn = get_db_connection()
    data = conn.execute(
        'SELECT tid, fid, token, fname, fext, created FROM records WHERE tid LIKE \'' + task_id + '\' AND active = 1').fetchone()
    conn.close()

    if not data:
        return jsonify({"error": "miss_data"}), 202

    task = upload_task.AsyncResult(task_id, app=app_celery)

    if not task:
        return jsonify({"error": "miss_task"}), 202

    task_now = datetime.now() + timedelta(hours=3)
    x = data[5].split(".")
    task_created = datetime.strptime(x[0], r'%Y-%m-%d %H:%M:%S')
    minutes = (task_now - task_created).total_seconds() // 60.0
    if task.state == 'PENDING':
        response = {
            "task_id": task_id,
            "file_id": file_id,
            "task_status": 'обработка...',
            "task_result": task.result,
            "task_info": task.info,
            "task_state": task.state,
            "task_real_name": data[3],
            "task_created": minutes,
            "error": "not"
        }
    elif task.state != 'FAILURE':
        response = {
            "task_id": task_id,
            "file_id": file_id,
            "task_status": 'обработен',
            "task_result": task.result,
            "task_info": task.info,
            "task_state": task.state,
            "task_real_name": data[3],
            "task_created": minutes,
            "error": "not"
        }
    elif task.state == 'FAILURE':
        response = {
            "task_id": task_id,
            "file_id": file_id,
            "task_status": 'грешка',
            "task_result": task.result,
            "task_info": task.info,
            "task_state": task.state,
            "task_real_name": data[3],
            "task_created": minutes,
            "error": "not"
        }
    else:
        response = {
            "task_id": task_id,
            "file_id": file_id,
            "task_status": 'грешка',
            "task_result": task.result,
            "task_info": task.info,
            "task_state": task.state,
            "task_real_name": data[3],
            "task_created": minutes,
            "error": "not"
        }
    return jsonify(response), 202


import json
import requests
from flask import Blueprint, request, jsonify, session, current_app
from app.db import get_db

user = Blueprint('user', __name__)

@user.route('/', methods=['GET'])
def get_user_info():
    code = request.args.get('code')
    appid = current_app.config['APPID']
    secret = current_app.config['SECRET']
    url = 'https://api.weixin.qq.com/sns/jscode2session?appid=%s&secret=%s&js_code=%s&grant_type=authorization_code' \
          % (appid, secret, code)
    r = requests.get(url)
    result = json.loads(r.text)
    if not result.get('errcode'):
        openid = result.get('openid')
        session_key = result.get('session_key')
        db = get_db()
        u = db.user.find_one({'openid': openid})
        if not u:
            db.user.insert_one({
                'openid': openid,
                'session_key': session_key
            })
        return jsonify({'token': openid})
    print(result)
    return result


import re

from jsonschema import SchemaError

# Examine:
# end date < start date
# date not in 01/01/1901 & 31/12/2999

day_in_month = [31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31]

def parse_date(date):
    day, month, year = map(lambda val: int(val), date.split("/"))
    return day, month, year

def validate_date(date, start=False):
    if not re.match(r"\d\d\/\d\d\/\d\d\d\d", date):
        raise ValueError("Input date is invalid in format! Please input in format DD/MM/YYYY")

    else:
        day, month, year = parse_date(date)
        if day <= 0 or month <= 0 or year <= 0:
            raise ValueError("Date value should be positive")
        if month == 2 and day > 29:
            raise ValueError("Day value invalid for Februrary")
        elif month > 12 or day > 31:
            raise ValueError("Month and Day value is invalid")

        if start:
            if year < 1901:
                raise ValueError("Start date should be earlier than 01/01/1901")
        else:
            if year > 2999:
                raise ValueError("End date should before 31/12/2999")

def cnt_date_diff(start_dt, end_dt):

    cnt = 0
    str_d, str_m, str_yr = parse_date(start_dt)
    end_d, end_m, end_yr = parse_date(end_dt)

    cnt += (end_yr - str_yr - 1) * 365
    cnt += sum(day_in_month[str_m:]) + (day_in_month[str_m - 1] - str_d)

    cnt += sum(day_in_month[: end_m - 1]) + end_d

    if cnt > 0:
        cnt -= 1

    return abs(cnt)

if __name__ == "__main__":
    print("Please input start date (Format DD/MM/YYYY):")

    start_day = str(input())

    validate_date(start_day, start=True)

    print("Please input end date (Format DD/MM/YYYY):")

    end_day = str(input())

    validate_date(end_day, start=False)

    date_diff = cnt_date_diff(start_day, end_day)
    print("Date difference: ", date_diff)


# Jake Wakerley

"""
Create a function that receives a list of strings that are arithmetic problems and returns the problems arranged vertically and side-by-side.
The function should optionally take a second argument. When the second argument is set to True, the answers should be displayed.
"""
import re

def arithmetic_arranger(problems, solve = False):
    if len(problems) > 5:
        return "Error: Too many problems."
    first = ""
    second = ""
    lines = ""
    sumx = ""
    string = ""
    for problem in problems:
        if(re.search("[^\s0-9.+-]", problem)): # Searches for values that are not whitespace
            if (re.search("[/]", problem) or re.search("[*]", problem)):
                return "Error: Operator must be '+' or '-'."
            return "Error: Numbers must only contain digits."

        firstNumber = problem.split(" ")[0]
        operator = problem.split(" ")[1]
        secondNumber = problem.split(" ")[2]

        if (len(firstNumber) >= 5 or len(secondNumber) >= 5):
            return "Error: Numbers cannot be more than four digits."

        sum = ""
        if (operator == "+"):
            sum = str(int(firstNumber) + int(secondNumber))
        elif (operator == "-"):
            sum = str(int(firstNumber) - int(secondNumber))

        length = max(len(firstNumber), len(secondNumber)) + 2
        top = str(firstNumber).rjust(length)
        bottom = operator + str(secondNumber).rjust(length - 1)
        line = ""
        res = (str(sum).rjust(length))
        for s in range(length):
            line += "-"

        if problem != problems[-1]:
            first += top + "    "
            second += bottom + "    "
            lines += line + "    "
            sumx += res + "    "
        else:
            first += top
            second += bottom
            lines += line
            sumx += res

    if solve:
        string = first + "\n" + second + "\n" + lines + "\n" + sumx
    else:
        string = first = first + "\n" + second + "\n" + lines
    return string

print(arithmetic_arranger(["32 + 698", "3801 - 2", "45 + 43", "123 + 49"]))


x ,y = map(int,input().split())

a = '0'
for i in range(1,50):
    a += (','+str(i))*i

numlist = a.split(',')
numlist = list(map(int, numlist))
numlist = numlist[x:y+1]
print(sum(numlist))


import unittest
import os

from simple_encryption.encryption import Encryptor as encryptor

class TestEncryption(unittest.TestCase):
    def test_key_create(self):
        demo_key_val = b'C0JMjOk24fFZTz4Fqm_y6m0iaLSVR_9HOPlf0BSgthI'
        encrypt = encryptor()
        key = encrypt.key_create()
        self.assertIs(type(key), type(demo_key_val), "Test key create")

    def test_key_write(self):
        encrypt = encryptor()
        demo_key_val = b'C0JMjOk24fFZTz4Fqm_y6m0iaLSVR_9HOPlf0BSgthI'
        if(os.path.exists('./.secrets') == False):
            os.mkdir('./.secrets')
        encrypt.key_write(demo_key_val, './.secrets/test_key')

        fd = os.open('./.secrets/test_key', os.O_RDWR)
        read_bytes = os.read(fd, 45)

        os.remove('./.secrets/test_key')
        self.assertAlmostEqual(demo_key_val, read_bytes)


# Enter your code here. Read input from STDIN. Print output to STDOUT
t=int(input())
while t:
    t-=1
    s=input()
    delc=0
    # recc=0
    for i in range(1,len(s)):
        if s[i]=='A' and s[i-1]=='A':
            delc+=1
        elif s[i]=='B' and s[i-1]=='B':
            delc+=1
    print(delc)


"""
Tests of the clients using a mock Job Queue service

No network access is needed.

"""

import unittest
from nmpi import nmpi_user

SERVER = "https://mock.hbpneuromorphic.eu"
ENTRYPOINT = SERVER + "/api/v2"
TESTUSERID = "999999"
TESTCOLLAB = "98765"
EMPTYCOLLAB = "54321"
NOTMYCOLLAB = "123456"
cache = {}
SCHEMA = {
    "dataitem": {"list_endpoint": "/api/v2/dataitem", "schema": "/api/v2/dataitem/schema"},
    "log": {"list_endpoint": "/api/v2/log", "schema": "/api/v2/log/schema"},
    "queue": {"list_endpoint": "/api/v2/queue", "schema": "/api/v2/queue/schema"},
    "results": {"list_endpoint": "/api/v2/results", "schema": "/api/v2/results/schema"},
}
JOB42 = {
    'code': 'this is the code',
    'collab_id': TESTCOLLAB,
    'command': 'run.py',
    'hardware_config': {},
    'hardware_platform': 'TESTPLATFORM',
    'input_data': [],
    'user_id': TESTUSERID,
    'resource_uri': "/api/v2/queue/42",
    'id': 42,
    'status': 'submitted'
}
DATAFILE1 = "foo.jpg"
DATAFILE2 = "results.h5"
JOB43 = {
    'code': 'this is the code',
    'collab_id': TESTCOLLAB,
    'command': 'run.py',
    'hardware_config': {},
    'hardware_platform': 'TESTPLATFORM',
    'input_data': [],
    'output_data': [{"url": "https://mockdatastore.humanbrainproject.eu/data/" + DATAFILE1},
                    {"url": "https://mockdatastore.humanbrainproject.eu/data/" + DATAFILE2}],
    'user_id': TESTUSERID,
    'resource_uri': "/api/v2/queue/43",
    'id': 43,
    'status': 'submitted'
}

class MockResponse(object):
    ok = True

    def __init__(self, return_value, headers=None, status_code=200):
        self.return_value = return_value
        self.headers = headers
        self.status_code = status_code
        if status_code >= 400:
            self.ok = False

    def json(self):
        return self.return_value

class MockRequestsModule(object):

    def get(self, url, auth=None, cert=None, verify=True):
        response_map = {
            nmpi_user.IDENTITY_SERVICE_V1 + "/user/me": MockResponse({"username": "testuser",
                                                      "id": TESTUSERID}),
            ENTRYPOINT: MockResponse(SCHEMA),
            ENTRYPOINT + "/queue?id=42": MockResponse({"objects": [JOB42]}),
            ENTRYPOINT + "/queue?id=43": MockResponse({"objects": []}),
            ENTRYPOINT + "/results?id=43": MockResponse({"objects": [JOB43]}),
            ENTRYPOINT + "/queue/42": MockResponse(JOB42),
            ENTRYPOINT + "/queue/43": MockResponse(JOB43),
            ENTRYPOINT + "/results/42": MockResponse({"error_message": "no such job"}, status_code=404),
            ENTRYPOINT + "/results/43": MockResponse({"error_message": "no such job"}, status_code=404),
            ENTRYPOINT + "/queue/submitted/?user_id=" + TESTUSERID: MockResponse([JOB42]),
            ENTRYPOINT + "/results?collab_id=" + TESTCOLLAB: MockResponse([JOB43]),
            ENTRYPOINT + "/results?collab_id=" + EMPTYCOLLAB: MockResponse([]),
            SERVER + "/copydata/collab/43": MockResponse([DATAFILE1, DATAFILE2]),
            ENTRYPOINT + "/queue/44?collab_id=" + NOTMYCOLLAB: MockResponse(
                                     {"error_message": "You are not a member of this Collab"}),
        }
        return response_map[url]

    def post(self, url, data, auth=None, cert=None, verify=True, headers=None):
        if url == SERVER + SCHEMA["queue"]["list_endpoint"]:
            return MockResponse({}, {'Location': 'NEW_JOB_URL'})
        else:
            raise Exception("invalid url: {}".format(url))

    def delete(self, url, auth=None, cert=None, verify=True):
        if url == ENTRYPOINT + "/queue/42":
            return MockResponse("", status_code=204)
        elif url == ENTRYPOINT + "/results/43":
            return MockResponse("", status_code=204)
        else:
            raise Exception("invalid url: {}".format(url))

def mock_urlretrieve(url, local_dir):
    pass

def setUp():
    """Replace modules/functions that access the network or
    filesystem with mock versions."""
    cache['requests'] = nmpi_user.requests
    cache['urlretrieve'] = nmpi_user.urlretrieve
    cache['_mkdir_p'] = nmpi_user._mkdir_p
    nmpi_user.__dict__['requests'] = MockRequestsModule()
    nmpi_user.urlretrieve = mock_urlretrieve
    nmpi_user._mkdir_p = lambda dir: None

def tearDown():
    """Restore the real versions of modules/functions that access
     the network or filesystem"""
    nmpi_user.__dict__['requests'] = cache['requests']
    nmpi_user.urlretrieve = cache['urlretrieve']
    nmpi_user._mkdir_p = cache['_mkdir_p']

class UserClientTest(unittest.TestCase):

    def setUp(self):
        self.client = nmpi_user.Client("testuser", job_service=ENTRYPOINT, token="TOKEN", verify=True)

    def test_create_client(self):
        self.assertEqual(self.client.username, "testuser")
        self.assertEqual(self.client.verify, True)
        self.assertEqual(self.client.token, "TOKEN")
        self.assertEqual(self.client.job_server, "https://mock.hbpneuromorphic.eu")
        self.assertEqual(self.client.auth.token, nmpi_user.HBPAuth("TOKEN").token)
        self.assertEqual(self.client.user_info["username"],
                         "testuser")
        self.assertEqual(self.client.user_info["id"],
                         TESTUSERID)

    def test_submit_job_string_no_inputs(self):
        response = self.client.submit_job("import foo", "TESTPLATFORM", "COLLAB_ID")
        self.assertEqual(response, 'NEW_JOB_URL')

    def test_job_status_integer(self):
        response = self.client.job_status(42)
        self.assertEqual(response, "submitted")

    def test_job_status_uri(self):
        response = self.client.job_status("/api/v2/queue/42")
        self.assertEqual(response, "submitted")

    def test_get_job(self):
         response = self.client.get_job(42)
         self.assertIsInstance(response, dict)
         self.assertEqual(response['id'], 42)

    def test_remove_completed_job(self):
         response = self.client.remove_completed_job(43)
         self.assertIsNone(response)

    def test_remove_queued_job(self):
         response = self.client.remove_queued_job(42)
         self.assertIsNone(response)

    def test_queued_jobs(self):
        response = self.client.queued_jobs()
        self.assertIsInstance(response, list)
        self.assertEqual(len(response), 1)

    def test_completed_jobs(self):
        response = self.client.completed_jobs(TESTCOLLAB)
        self.assertIsInstance(response, list)
        self.assertEqual(len(response), 1)

    def test_completed_jobs_empty_collab(self):
        response = self.client.completed_jobs(EMPTYCOLLAB)
        self.assertIsInstance(response, list)
        self.assertEqual(len(response), 0)

    def test_download_data(self):
        job = self.client.get_job(43)
        response = self.client.download_data(job, local_dir="testfoo")
        self.assertEqual(response, ["testfoo/job_43/" + DATAFILE1,
                                    "testfoo/job_43/" + DATAFILE2])

    def test_copy_data_to_storage(self):
        response = self.client.copy_data_to_storage(43, destination="collab")
        # todo: check the response


from bs4 import BeautifulSoup
from datetime import datetime
from collections import deque

def updater(csv_path, html_path):
    try:
        with open(csv_path, 'r', buffering=1, encoding='utf-8') as file:
            qdata = deque(file, 5)
        data = []
        for row in qdata:
            data.append(row.split(','))
    except FileNotFoundError as err:
        print(f"Error: {err}, path CSV incorrecto.")
        return

    try:
        with open(html_path) as inf:
            soup = BeautifulSoup(inf.read(), features="html.parser")
            tables = soup.find_all('table')
            entries = len(data)
            for table in tables:
                rows = table.find_all('tr')
                for i, row in enumerate(rows):
                    cols = row.find_all('td')
                    for ii, elem in enumerate(cols):
                        elem.string.replace_with(data[i][ii])
                    if i == entries - 1:
                        break
            footer = soup.find('footer')
            timestamp = footer.find('pre')
            timestamp.string.replace_with(datetime.now().strftime("%H:%M:%S"))
        with open(html_path, 'w') as outf:
            outf.write(str(soup))
        return
    except FileNotFoundError as err:
        print(f"Error: {err}, path HTML incorrecto.")
        return


import logging
from Core.Conf import *

class Logger:

    def __init__(self, filename):
        print("Logging to: ", filename)
        self._filename = filename
        self.loggers = {}

    @property
    def filename(self):
        return self._filename

    @filename.setter
    def filename(self, f):
        print("Logging to: ", f)
        self._filename = f

    def attach(self, name, filename = None):
        print("Attaching Logger: " + str(name))
        if name in self.loggers:
            return self.loggers[name]

        logger = logging.getLogger(name)
        if filename is None:
            fh = logging.FileHandler(self.filename + ".log")
        else:
            fh = logging.FileHandler(filename + ".log")
        logger.setLevel(logging.DEBUG)
        formatter = logging.Formatter('%(asctime)s : %(levelname)s : %(name)s : %(message)s')
        fh.setFormatter(formatter)
        logger.addHandler(fh)
        self.loggers[name] = logger
        return logger

#IO.verify(cfg["IO"]["log_path"])
log_path = cfg["IO"]["log_path"] + cfg["LOGGING"].get("file_name", "log") + "_" + cfg["GENERAL"]["MODE"][0]
LOGGER = Logger(log_path)