#!/usr/bin/env python
# license removed for brevity
import rospy
import tf
from std_msgs.msg import String, Header, ColorRGBA
from tf2_msgs.msg import TFMessage
from geometry_msgs.msg import TransformStamped, Point, Transform, Pose

import visualization_msgs.msg as vis_msg

def talker():
    rospy.init_node('kitti_tf_pub', anonymous=True)

    listener = tf.TransformListener()

    marker_pub_ = rospy.Publisher('viz_msgs_marker_publisher', vis_msg.Marker, latch=True, queue_size=10)

    pub = rospy.Publisher('kitti/transformStamped', TransformStamped, queue_size=10)
    rate = rospy.Rate(10) # 10hz
    while not rospy.is_shutdown():

        try:
            (trans,rot) = listener.lookupTransform('/world', '/camera_left', rospy.Time(0))

        except (tf.LookupException, tf.ConnectivityException, tf.ExtrapolationException):
            continue

        xform = TransformStamped()

        now = rospy.Time.now()
        xform.header = Header()

        xform.header.frame_id = '/world'
        xform.header.stamp = now
        xform.child_frame_id = '/camera_left'
        xform.transform.translation.x = trans[2]
        xform.transform.translation.y = trans[0]
        xform.transform.translation.z = trans[1]

        xform.transform.rotation.x = rot[0]
        xform.transform.rotation.y = rot[1]
        xform.transform.rotation.z = rot[2]
        xform.transform.rotation.w = rot[3]

        # hello_str = "hello world %s" % rospy.get_time()

        # rospy.loginfo(hello_str)

        pub.publish(xform)
        marker = vis_msg.Marker(type=vis_msg.Marker.SPHERE, ns='xyz', action=vis_msg.Marker.ADD, id = 0)
        marker.header.frame_id = '/world'
        marker.header.stamp = now
        marker.scale.x = 1000
        marker.scale.y = 1000
        marker.scale.z = 100
        marker.colors = [ColorRGBA(1.0 ,1.0 ,1.0 ,1.0)]
        # XYZ

        marker.pose.position = xform.transform.translation
        marker.pose.orientation = xform.transform.rotation
        marker.lifetime = rospy.Duration()
        marker_pub_.publish(marker)

        rate.sleep()

if __name__ == '__main__':
    try:
        talker()
    except rospy.ROSInterruptException:
        pass


n=121
temp=n
r=0
pal=0
while n>0:
    r=n%10
    pal=pal*10+r
    n=n/10

if r==temp:
    print ("This is palindrome.")
else:
    print ("Not palindrome.")


import sys
import re
import random
import torch
import torch.nn as nn
from torchtext.legacy import data
from torchtext.legacy import datasets
from transformers import BertTokenizer, BertModel

tokenizer = BertTokenizer.from_pretrained('bert-base-uncased')
print(len(tokenizer.vocab))

max_input_length = tokenizer.max_model_input_sizes['bert-base-uncased']
print(max_input_length)

# New Tokenizer
def new_tokenizer(sentence):
    tokens = tokenizer.tokenize(sentence)
    tokens = tokens[:max_input_length-2] # [CLS], [SEP] Special Token 2자리 미리 빼두기
    return tokens

# Data Cleansing
def PreProcessingText(input_sentence):
    input_sentence = input_sentence.lower()
    input_sentence = re.sub('<[^>]*>', repl=' ', string=input_sentence) # '<br />' 처리
    input_sentence = re.sub('[!"#%&\\()*+,-./:;<=>?@[\\\\]^_`{\}~]', repl=' ', string=input_sentence) # 특수 문자 처리
    input_sentence = re.sub('\\s+', repl=' ', string=input_sentence) # 연속된 띄어쓰기 처리
    if input_sentence:
        return input_sentence

def PreProc(list_sentence):
    return [tokenizer.convert_tokens_to_ids(PreProcessingText(x)) for x in list_sentence]

# Data Setting
TEXT = data.Field(batch_first=True,
                  use_vocab=False,
                  tokenize=new_tokenizer,
                  preprocessing=PreProc,
                  init_token=tokenizer.cls_token_id,
                  eos_token=tokenizer.sep_token_id,
                  pad_token=tokenizer.pad_token_id,
                  unk_token=tokenizer.unk_token_id)

LABEL = data.LabelField(dtype=torch.float)

train_data, test_data = datasets.IMDB.splits(text_field=TEXT, label_field=LABEL)

# Making vocab
LABEL.build_vocab(train_data)

# Splitting Valid set
train_data, valid_data = train_data.split(random_state=random.seed(0), split_ratio=0.8)

model_config = {'batch_size': 10}
device = torch.device('cuda' if torch.cuda.is_available() else 'cpu')
train_iterator, valid_iterator, test_iterator = data.BucketIterator.splits(datasets=(train_data, valid_data, test_data),
                                                                           batch_size=model_config['batch_size'],
                                                                           device=device)

# Model
bert = BertModel.from_pretrained('bert-base-uncased')
model_config['emb_dim'] = bert.config.to_dict()['hidden_size']
model_config['output_dim'] = 1
print(model_config['emb_dim'])

class SentenceClassification(nn.Module):
    def __init__(self, **model_config):
        super(SentenceClassification, self).__init__()
        self.bert = bert
        self.fc = nn.Linear(model_config['emb_dim'], model_config['output_dim'])

    def forward(self, x):
        pooled_cls_output = self.bert(x)[1] # [CLS] Pooled_output 사용
        return self.fc(pooled_cls_output)

# Accuracy Function
def binary_accuracy(preds, y):
    rounded_preds = torch.round(torch.sigmoid(preds))
    correct = (rounded_preds == y).float()
    acc = correct.sum() / len(correct)
    return acc

# Train Function
def train(model, iterator, optimizer, loss_fn, idx_Epoch, **model_params):
    Epoch_loss = 0
    Epoch_acc = 0

    model.train()
    batch_size = model_params['batch_size']

    for idx, batch in enumerate(iterator):
        # Initializing
        optimizer.zero_grad()

        # Forward
        predictions = model(batch.text).squeeze()
        loss = loss_fn(predictions, batch.label)
        acc = binary_accuracy(predictions, batch.label)

        sys.stdout.write('\r' + f'[Train] Epoch: {idx_Epoch:^3}'\
            f'[{(idx + 1) * batch_size} / {len(iterator) * batch_size}({100. * (idx + 1) / len(iterator) :.4}%)]'\
            f'  Loss: {loss.item():.4}'\
            f'  Acc: {acc.item():.4}')

        # Backward
        loss.backward()
        optimizer.step()

        # Update Epoch Performance
        Epoch_loss += loss.item()
        Epoch_acc += acc.item()

    return Epoch_loss/len(iterator), Epoch_acc/len(iterator)

# Evaluate Function
def evaluate(model, iterator, loss_fn):
    Epoch_loss = 0
    Epoch_acc = 0

    # Evaluation mode
    model.eval()
    with torch.no_grad():
        for batch in iterator:
            predictions = model(batch.text).squeeze(1)
            loss = loss_fn(predictions, batch.label)
            acc = binary_accuracy(predictions, batch.label)

            Epoch_loss += loss.item()
            Epoch_acc += acc.item()

    return Epoch_loss / len(iterator), Epoch_acc / len(iterator)

model = SentenceClassification(**model_config)
optimizer = torch.optim.Adam(model.parameters(), lr=3e-5)
loss_fn = nn.BCEWithLogitsLoss().to(device)
model = model.to(device)

def count_parameters(model):
    return sum(p.numel() for p in model.parameters() if p.requires_grad)

# count_parameters(model) # 109483009

# Train
N_EPOCH = 5

best_valid_loss = float('inf')
model_name = 'BERT'

print('----------------------------------------')
print(f'Model name: {model_name}')
print('----------------------------------------')

for Epoch in range(N_EPOCH):
    train_loss, train_acc = train(model, train_iterator, optimizer, loss_fn, Epoch, **model_config)
    valid_loss, valid_acc = evaluate(model, valid_iterator, loss_fn)
    print('')

    if valid_loss < best_valid_loss:
        best_valid_loss = valid_loss
        torch.save(model.state_dict(), f'./{model_name}.pt')
        print(f'\t Saved at {Epoch}-Epoch')

    print(f'\t Epoch: {Epoch} | Train Loss: {train_loss:.4} | Train Acc: {train_acc:.4}')
    print(f'\t Epoch: {Epoch} | Valid Loss: {valid_loss:.4} | Valid Acc: {valid_acc:.4}')

# Test set
model.load_state_dict(torch.load(f'./{model_name}.pt'))
test_loss, test_acc = evaluate(model, test_iterator, loss_fn)
print(f'Test Loss: {test_loss:.4} | Test Acc: {test_acc:.4}')


# HJ40 统计字符

while True:
    try:
        s=input()
        l=[0,0,0]
        for i in s:
            l[0]+=int(i.isalpha())
            l[1]+=int(i==' ')
            l[2]+=int(i.isnumeric())
        print(l[0])
        print(l[1])
        print(l[2])
        print(len(s)-l[0]-l[1]-l[2])
    except:
        break

'''

简单  通过率：44.71%  时间限制：1秒  空间限制：32M
知识点
字符串
哈希
warning 校招时部分企业笔试将禁止编程题跳出页面，为提前适应，练习时请使用在线自测，而非本地IDE。
描述
输入一行字符，分别统计出包含英文字母、空格、数字和其它字符的个数。

数据范围：输入的字符串长度满足 1 \le n \le 1000 \1≤n≤1000

输入描述：
输入一行字符串，可以有空格

输出描述：
统计其中英文字符，空格字符，数字字符，其他字符的个数

示例1
输入：
1qazxsw23 edcvfr45tgbn hy67uj m,ki89ol.\\/;p0-=\\][
复制
输出：
26
3
10
12
'''


import pytest
import pandas
import json
from python.main.preprocessing.dataframe_filtrartion import DataFramePreprocessor
from pandas.testing import assert_frame_equal

with open("./python/test/preprocessing/test_cases.json", "r") as json_file:
    test_data = json_file.read()
test_cases = json.loads(test_data)

test_case_get_fuel_data = test_cases["get_fuel_data"]
test_case_remove_not_required_columns = test_cases["remove_not_required_columns"]
test_case_replace_nan_values = test_cases["replace_nan_values"]

@pytest.mark.parametrize("dataframe,result", test_case_get_fuel_data)
def test_get_fuel_data(dataframe, result):
    if result is None:
        with pytest.raises(AttributeError):
            DataFramePreprocessor(dataframe)
    else:
        dataframe_filter = DataFramePreprocessor(pandas.DataFrame(dataframe))
        assert_frame_equal(pandas.DataFrame(result), dataframe_filter.get_fuel_data())

@pytest.mark.parametrize("dataframe,result", test_case_remove_not_required_columns)
def test_remove_not_required_columns(dataframe, result):
    dataframe_filter = DataFramePreprocessor(pandas.DataFrame(dataframe))
    dataframe_filter.remove_not_required_columns()
    assert_frame_equal(dataframe_filter.get_fuel_data(), pandas.DataFrame(result))

@pytest.mark.parametrize("dataframe,result", test_case_replace_nan_values)
def test_replace_nan_values(dataframe, result):
    dataframe_filter = DataFramePreprocessor(pandas.DataFrame(dataframe))
    dataframe_filter.replace_nan_values()
    assert_frame_equal(dataframe_filter.get_fuel_data(), pandas.DataFrame(result))


#!/usr/bin/python3
"""new view for City objects"""
from models.city import City
from models import storage
from models.state import State
from flask import Flask, abort, request, jsonify
from api.v1.views import app_views

@app_views.route('/states/<state_id>/cities', methods=['GET'],
                 strict_slashes=False)
def get_cities(state_id):
    """Retrieves the list of all city objects"""
    list_cities = []
    all_cities = storage.all("City")
    state = storage.get("State", state_id)
    if state is None:
        abort(404)
    for item in all_cities.values():
        if item.state_id == state_id:
            list_cities.append(item.to_dict())
    return jsonify(list_cities)

@app_views.route('/cities/<city_id>', methods=['GET'], strict_slashes=False)
def obj_city(city_id):
    """Retrieves the State object"""
    city = storage.get("City", city_id)
    if city is None:
        abort(404)
    return jsonify(city.to_dict())

@app_views.route('/cities/<city_id>', methods=['DELETE'], strict_slashes=False)
def delete_city(city_id):
    """Deletes an object"""
    city = storage.get("City", city_id)
    if city is None:
        abort(404)
    city.delete()
    storage.save()
    storage.close()
    return jsonify({}), 200

@app_views.route('/states/<state_id>/cities', methods=['POST'],
                 strict_slashes=False)
def create_city(state_id):
    """Creates a City"""
    body_dict = request.get_json()
    if not request.is_json:
        abort(400, "Not a JSON")

    name = body_dict.get('name')
    if not name:
        abort(400, "Missing name")

    state = storage.get("State", state_id)
    if state is None:
        abort(404)
    upd_city = City(**body_dict)
    upd_city.state_id = state_id
    storage.new(upd_city)
    upd_city.save()
    storage.close()
    return jsonify(upd_city.to_dict()), 201

@app_views.route('/cities/<city_id>', methods=['PUT'], strict_slashes=False)
def update_city(city_id):
    """Updates a city object"""
    body_dict = request.get_json()
    if not request.is_json:
        abort(400, "Not a JSON")
    city = storage.get("City", city_id)
    if city is None:
        abort(404)

    ignore_keys = ["id", "state_id", "created_at", "updated_at"]
    for key, value in body_dict.items():
        if key not in ignore_keys:
            setattr(city, key, value)
    city.save()
    storage.close()
    return jsonify(city.to_dict()), 200


from All import *
##################################################################################
Gmain = nx.Graph()
isInitialG = True
stateCounterG = 1

def constructFirstState():
    global stateCounter
    global Gmain
    global isInitialG
    global firstState
    stateCounter = 1
    isInitialG = True
    waitedActions1= []
    Gmain.clear()
    firstState = myState(stateCounter, cellDict, isInitialG, waitedActions1)
    Gmain.add_node(stateCounterG,data = firstState)
    isInitialG = False

def printCellDict(inputCellDic):
    print('\nList of cells in dictionary:')
    for keys, values in inputCellDic.items():
        #print(keys)
        print(values)
############################################################################

def MainLoop(inputState):
	global nextState
	global stateCounter
	global queue1
	#constructFirstState()
	queue1                = []                        # main queue for the algorithm
	queue2                = []                               # temporary queue for the algorithm
	actionList            = []
	waitingActionList     = []
	currentState          = copy.deepcopy(inputState)	 # testing
	#currentState          = copy.deepcopy(firstState)        # begin at the first state
	print('currentState is %s' %currentState)
	print('its dictionary is')
	printCellDict(currentState.ScellDict)
	queue1.append(currentState)

	for rule in ruleList:					 # try to check if there are fulfilled rules on currentState
		bool = checkingRule(rule, currentState)
		if(bool == True and rule.ruleAction.isApplicable() == True):    # isApplicable() checks if the time is 1 or not):
			newAction = copy.deepcopy(rule.ruleAction)
			actionList.append(newAction)

		elif(bool == True and rule.ruleAction.isApplicable() == False):
			newAction = copy.deepcopy(rule.ruleAction)
			newAction.decreaseTime()			# decrease the time with 1
			waitingActionList.append(newAction)

	print('actionList contains')
	for action in actionList:
		print(action)
	print('waitingActionList contains')
	for action in waitingActionList:
		print(action)
	# important algorithm
	index = 0
	while(index < len(actionList)):
		action = actionList[index]
		index += 1
		print('action to apply: %s' %action)
		while(queue1):                                          # while queue1 is not empty
			nextState = queue1.pop(0)			# pop the first element
			print(nextState)
			# this is creating 2 branches part
			NotOccuredCellDict = nextState.ScellDict
			OccuredCellDict    = performAction(nextState.ScellDict,action)
			stateCounter      += 1
			tmpStateOccured    = myState(stateCounter, OccuredCellDict, isInitialG, waitingActionList)
			stateCounter      += 1
			tmpStateNotOccured = myState(stateCounter, NotOccuredCellDict, isInitialG, waitingActionList)
			#
			queue2.append(tmpStateOccured)
			queue2.append(tmpStateNotOccured)
		queue1 = copy.deepcopy(queue2)                          # if queue1 = queue2  we will get stuck in while(queue1)
		queue2 = copy.deepcopy([])				# emptying queue2

	actionList = copy.deepcopy([])					# emptying the actionList
	#

	for state in queue1:
		currentState.childList.append(state)
	#print('currentState is %s' %currentState)
	#print('childlist has')
	#for state in currentState.childList:
	#	print(state)
	#if(currentState.waitedActions):		  # if there are waited actions
	#	for action in currentState.waitedActions:
	#		if(action.isApplicable()):               # if the time is 1
	#			actionList.append(action)        # put the action in the actionList
	#			print(action)

	#print(currentState.childList[4])
	#printCellDict(currentState.childList[4].ScellDict)
	#for waitedaction in currentState.childList[4].waitedActions:
	#	print(waitedaction)

	for state in currentState.childList:
		Gmain.add_node(state.stateID)
		Gmain.add_edge(currentState.stateID, state.stateID)

	#nx.draw_spring(Gmain)
	#plt.show()

############################################################################   Execution part
constructFirstState()
currentState          = copy.deepcopy(firstState)        # begin at the first state
MainLoop(currentState)
for state in queue1:
	MainLoop(state)
nx.draw_spring(Gmain)
plt.show()


import os

import nltk
import streamlit as st

from model import Model

def main():
    st.title('Sentiment Analysis')

    st.write("""
    # What sentiment in your text?
    """)

    text = st.sidebar.text_area(
        'Your text',
    )

    clf = Model.load_model()

    def get_text(string):
        return Model.clean_text(string)

    x_test = get_text(text)

    if x_test:
        y_pred = clf.predict([x_test])

        decoder = {
            0: 'Positive',
            1: 'Negative'
        }

        st.write(f'Sentiment = {decoder[y_pred[0]]}')

if __name__ == '__main__':
    if os.getenv('APP', '') != 'heroku':
        nltk.download('averaged_perceptron_tagger_ru')
        nltk.download('wordnet')
        nltk.download('punkt')
        nltk.download('stopwords')
    main()


import json
import time
from decimal import Decimal
from hashlib import sha256

import boto3

class DecimalEncoder(json.JSONEncoder):
    def default(self, obj):
        if isinstance(obj, Decimal):
            return int(obj)
        return super(DecimalEncoder, self).default(obj)

dynamodb = boto3.resource('dynamodb')
table = dynamodb.Table('notes')

def lambda_handler(event, context):
    #get parameters
    queryStringParameters =  event.get('queryStringParameters') or {}
    key = {
        'pk': queryStringParameters['pk'],
        'sk': queryStringParameters['sk']
    }
    #get note
    note = table.get_item(Key=key).get('Item')
    #if note exists, check if it should be available
    if note:
        if float(note['untilTimestamp'])-time.time()*1000 < 0:
            note = None
            table.delete_item(Key=key)
    #respond
    return {
        'statusCode': 200,
        'headers': {
            'Access-Control-Allow-Origin': '*'
        },
        'body': json.dumps({'note': note}, cls=DecimalEncoder)
    }


#2 Program to add two numbers

#Solution 1:Using Predefined Variables

num1 = 30
num2 = 40
sum =num1+num2
print("The Sum of Given 2 numbers is ",sum)

#Solution 2:Using user inputs
num1    = float(input("Enter number  : "))
num2    = float(input("Enter another number :"))
sum = num1+num2
print("Sum of provided two numbers is : ", sum)


# -*- coding: utf-8 -*-
''' Shear checking of a reinforced concrete section.
    Some results are compared with those of the exercise ER-CS-01 from
    www.areadecalculo.com. According to EHE-08».
'''
from __future__ import division
from __future__ import print_function

from misc import scc3d_testing_bench
from materials.sections.fiber_section import def_simple_RC_section

from materials.ehe import EHE_materials
from materials.ehe import EHE_limit_state_checking
import xc
from solution import predefined_solutions
from model import predefined_spaces
import math

__author__= "Luis C. Pérez Tato (LCPT) and Ana Ortega (AOO)"
__copyright__= "Copyright 2015, LCPT and AOO"
__license__= "GPL"
__version__= "3.0"
__email__= "l.pereztato@gmail.com"

width= 0.3 # Section width expressed in meters.
depth= 0.4 # Section depth expressed in meters.
cover= 0.05 # Concrete cover expressed in meters.

NDato= -400e3 # Axial force for shear checking.
MyDato= 1e5 # Bending moment for shear checking.
MzDato= 1e3 # Bending moment for shear checking.

rebarArea= 4e-4
rebarDiam= 2.0*math.sqrt(rebarArea/math.pi)
numOfRebars= 3
lowerRow= def_simple_RC_section.ReinfRow(areaRebar= rebarArea, width= width, nRebars= numOfRebars, nominalCover= cover-rebarDiam/2.0, nominalLatCover= cover-rebarDiam/2.0)
upperRow= def_simple_RC_section.ReinfRow(areaRebar= rebarArea, width= width, nRebars= numOfRebars, nominalCover= cover-rebarDiam/2.0, nominalLatCover= cover-rebarDiam/2.0)

feProblem= xc.FEProblem()
preprocessor=  feProblem.getPreprocessor
# Materials definition
concr= EHE_materials.HA25
concr.alfacc=0.85    # f_maxd= 0.85*fcd concrete long term compressive strength factor (normally alfacc=1)
steel= EHE_materials.B500S

# Section geometry
section= def_simple_RC_section.RCRectangularSection(name='test', width= width, depth= depth, concrType= concr, reinfSteelType= steel)
section.positvRebarRows= def_simple_RC_section.LongReinfLayers([lowerRow])
section.negatvRebarRows= def_simple_RC_section.LongReinfLayers([upperRow])
# section.shReinfY= shearReinf

section.defRCSection(preprocessor,matDiagType= 'd')
zlElement, nodA, nodB= scc3d_testing_bench.sectionModel(preprocessor, section.name)

# Constraints
modelSpace= predefined_spaces.getStructuralMechanics3DSpace(preprocessor)
modelSpace.fixNode000_000(nodA.tag)

# Loads definition
lp0= modelSpace.newLoadPattern(name= '0')
lp0.newNodalLoad(nodB.tag,xc.Vector([NDato,0,0,0,MyDato,MzDato]))
lp1= modelSpace.newLoadPattern(name= '1')
lp1.newNodalLoad(nodB.tag,xc.Vector([NDato,0,0,0,MzDato/10.0,MyDato/10.0]))
lp2= modelSpace.newLoadPattern(name= '2')
lp2.newNodalLoad(nodB.tag,xc.Vector([NDato,0,0,0,0,0]))

# We add the load case to domain.
modelSpace.addLoadCaseToDomain(lp0.name)

# Solution procedure
analysis= predefined_solutions.plain_newton_raphson(feProblem)
analOk= analysis.analyze(10)
if(analOk!=0):
    print("Error!; failed to converge.")
    exit()

shearController= EHE_limit_state_checking.ShearController('ULS_shear')

scc= zlElement.getSection()
rcSets= shearController.extractFiberData(scc, EHE_materials.HA25, EHE_materials.B500S)
shearController.calcVuEHE08(scc,"",EHE_materials.HA25,EHE_materials.B500S,NDato,math.sqrt(MyDato**2+MzDato**2),0,0, rcSets= rcSets)

Vu2A= shearController.Vu2

loadHandler= preprocessor.getLoadHandler.removeFromDomain("0") # Remove this load.
preprocessor.resetLoadCase()
loadHandler= preprocessor.getLoadHandler.addToDomain("1") # Add the other one.

analOk= analysis.analyze(10)
if(analOk!=0):
    print("Error!; failed to converge.")
    exit()

shearController.calcVuEHE08(scc,"",EHE_materials.HA25,EHE_materials.B500S, 0,0,0,0, rcSets= rcSets)

Vu2B= shearController.Vu2

loadHandler= preprocessor.getLoadHandler.removeFromDomain("1") # Remove this load.
preprocessor.resetLoadCase()
loadHandler= preprocessor.getLoadHandler.addToDomain("2") # Add another one.

analOk= analysis.analyze(10)
if(analOk!=0):
    print("Error!; failed to converge.")
    exit()

shearController.calcVuEHE08(scc,"",EHE_materials.HA25,EHE_materials.B500S, 0,0,0,0, rcSets= rcSets)

Vu2C= shearController.Vu2

''' Instead of taking Vu2= 127.638 kN as stated in the reference
document, we take 117.052 kN, that's because here we take into account
the axial force in the reinforcement so average stress in the web
is smaller. '''
Vu2ATeor= 117.052e3
ratio1= ((Vu2A-Vu2ATeor)/Vu2ATeor)
Vu2BTeor= 84630.2
ratio2= ((Vu2B-Vu2BTeor)/Vu2BTeor)
Vu2CTeor= 92301.8
ratio3= ((Vu2C-Vu2CTeor)/Vu2CTeor)

'''
section.plot(preprocessor) # Display section geometry
print("Vu2A= ",Vu2A/1e3," kN")
print("Vu2ATeor= ",Vu2ATeor/1e3," kN")
print("ratio1= ",ratio1)
print("\nVu2B= ",Vu2B/1e3," kN")
print("Vu2BTeor= ",Vu2BTeor/1e3," kN")
print("ratio2= ",ratio2)
print("\nVu2C= ",Vu2C/1e3," kN")
print("Vu2CTeor= ",Vu2CTeor/1e3," kN")
print("ratio3= ",ratio3)
 '''

import os
from misc_utils import log_messages as lmsg
fname= os.path.basename(__file__)
if (abs(ratio1)<1e-5) & (abs(ratio2)<0.03) & (abs(ratio3)<1e-5):
    print('test '+fname+': ok.')
else:
    lmsg.error(fname+' ERROR.')


def selectTest(q3, ffd1, ffd2):
    type1 = ffd1['valuetype']
    type2 = ffd2['valuetype']
    if type1 == 'FLOAT' and type2 == 'FLOAT':
        q4 = spearmans(q3, ffd1, ffd2)
    else:
        q4 = 'ERROR: you have failed at pairwise.'
    return(q4)

# spearman's correlation
# for float vs float

def spearmans(q3, ffd1, ffd2):
    # first rank the data
    thisq =  'ranktable AS (\nSELECT \n '
    thisq += ffd1['groupby2'] + ',\n'
    thisq += ffd2['groupby2'] + ',\n'
    thisq += '  DENSE_RANK() OVER (PARTITION BY ' + ffd1['groupby2'] + ' ORDER BY ' + ffd1['valuevar2'] + ' ASC) as rankvar1,  \n'
    thisq += '  DENSE_RANK() OVER (PARTITION BY ' + ffd2['groupby2'] + ' ORDER BY ' + ffd2['valuevar2'] + ' ASC) as rankvar2  \n'
    thisq += 'FROM\nmainjoin \n'
    thisq += ')\n'
    # then correlate the ranks
    thisq += 'SELECT \n'
    thisq += ffd1['groupby2'] + ',\n'
    thisq += ffd2['groupby2'] + ',\n'
    thisq += '  CORR( rankvar1, rankvar2 ) as Spearmans \n'
    thisq += 'FROM\n '
    thisq += '  ranktable \n'
    thisq += 'GROUP BY \n'
    thisq += ffd1['groupby2'] + ',\n'
    thisq += ffd2['groupby2'] + '\n'
    thisq += 'ORDER BY \n Spearmans DESC \n'
    return(q3 + thisq)

# t-test
# for float vs binary

# anova
# for float vs. more than one

 # Chi-sq or fisher's ?
 # for categorical vs categorical


import subprocess

def update_vscode():
    # Run the system command to update VS Code
    command = "sudo apt update && sudo apt upgrade code"
    process = subprocess.Popen(command, shell=True)
    process.wait()

if __name__ == "__main__":
    update_vscode()
    print("VS Code has been updated.")


import pandas as pd

def preprocess(df,region_df):

    # filltering for the summer olympics
    df = df[df['Season'] == 'Summer']

    # merge with the region_df

    df = df.merge(region_df, on = 'NOC', how = 'left')

    #dropping duplicates
    df.drop_duplicates(inplace = True)

    # ONe hot encoding medals
    df = pd.concat([df, pd.get_dummies(df['Medal'])], axis = 1)
    df = df.loc[~df.index.duplicated(),:].copy()
    return df


from discord.ext import commands
import asyncio, aiohttp
import discord
from collections import namedtuple
import json
import urllib3

class Armory:
    """Commands that allow the user to interact with the Raider.IO API."""

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

    @commands.command(name='affixes', hidden=True)
    async def affixes(self):
        """Shows the weekly Mythic+ affixes and their description"""

        http = urllib3.PoolManager
        r = http().request(
            'GET',
            'https://raider.io/api/v1/mythic-plus/affixes?region=us',
            fields = {},
            headers = {}
            )
        data = json.loads(r.data.decode('utf-8'))
        msg = 'This week: **' +data['title'] + '**\n'
        for i in data['affix_details']:
            msg = msg + '*' + i['description'] + '*\n'

        await self.client.say(msg)

    @commands.command(name='armory', hidden=True)
    async def armory(self, *, query : str):
        """Syntax: !armory eu draenor suurikarhu"""

        args = query.split(" ")
        if len(args) < 3:
            await self.client.say('Please provide the region, realm, and name (Example: !armory eu draenor suurikarhu).')
            return
        http = urllib3.PoolManager
        r = http().request(
            method = 'GET',
            url = 'https://raider.io/api/v1/characters/profile',
            fields={'region': args[0],
                    'realm': args[1],
                    'name': args[2],
                    'fields': 'gear,raid_progression,mythic_plusscores'},
            headers={})
        data = json.loads(r.data.decode('utf-8'))
        await self.client.say('__{0} - {1} {2} ({3}/{4})__'.format(data['name'], data['active_spec_name'], data['class'], data['gear']['item_level_equipped'], data['gear']['item_level_total']))
        await self.client.say('Raid Progress \nEN: {0}, TOV: {1}, NH: {2}, TOS: {3}'.format(data['raid_progression']['the-emerald-nightmare']['summary'], data['raid_progression']['trial-of-valor']['summary'], data['raid_progression']['the-nighthold']['summary'], data['raid_progression']['tomb-of-sargeras']['summary']))

def setup(client):
    client.add_cog(Armory(client))


def solution(triangle):
    lst = [ [0]*i for i in range(1,len(triangle)+1)]

    lst[0][0] = triangle[0][0]
    for j in range(len(triangle)-1): # j = 1
        for k in range(j+1): # k = 0 ~ 1, k = 1
            for i in range(k,k+2): # i = 1 ~ 2
                if lst[j][k] + triangle[j+1][i] > lst[j+1][i]:
                    lst[j+1][i] = lst[j][k] + triangle[j+1][i]

    answer = max(lst[-1])
    return answer

# def solution(triangle):
#     dp = [[0]*i for i in range(1,len(triangle)+1)]
#     dp[0][0] = triangle[0][0]
#     for i in range(len(triangle)):
#         for j in range(i):
#             dp[i][j] = max(dp[i][j],dp[i-1][j] + triangle[i][j])
#             dp[i][j+1] = dp[i-1][j] + triangle[i][j+1]
#     return max(dp[-1])

print(solution([[7], [3, 8], [8, 1, 0], [2, 7, 4, 4], [4, 5, 2, 6, 5]]))


'''
16236번
간선을 직접 생성하는 방법으로는 구현했는데, 시간복잡도가 높음.
때문에 BFS에 조건문을 추가해서 하는 방법으로 바꿀려니까
While문의 탈출 조건을 못 정하겠음..
'''

import sys
from collections import deque

N = int(input())
board = [list(map(int, sys.stdin.readline().strip().split()))
        for _ in range(N)]
shark_size = 2

breaker = False
for i in range(N):
    for j in range(N):
        if board[i][j] == 9:
            y, x = i, j
            board[i][j] = 0
            breaker = True
            break
    if breaker: break

def bfs(visited, y, x, shark_size):
    q = deque([(y, x, 0)])

    min_dis = 10**9
    target = (y, x, 0)
    origin = (y, x)

    while q:
        y, x, distance = q.popleft()
        visited[y][x] = True

        if min_dis < distance:
            break

        if 0 < board[y][x] and distance <= min_dis:
            flag = False
            if y < target[0]:
                flag = True

            elif y == target[0] and x < target[1]:
                flag = True

            if flag:
                min_dis = distance
                target = (y, x, distance)

        for dy, dx in [(-1,0),(0,-1),(0,1),(1,0)]:
            ny, nx = y+dy, x+dx
            if 0<=ny<N and 0<=nx<N:
                if visited[ny][nx] == False:
                    # 자기 자신과 같거나 작으면 이동 가능
                    if board[ny][nx] <= shark_size:
                        q.append((ny, nx, distance +1))

    return target

cnt = 0
time = 0
while True:

    print(*board, sep='\n')
    print()
    # bfs로 이동 가능한 가장 가까운 칸을 return
    visited = [[False] * N for _ in range(N)]
    target = bfs(visited, y, x, shark_size)

    if target[:2] == (y, x): break
    # target 방문하고 다시 반복
    time += target[2]
    print(target[2])
    (y, x, _) = target
    board[y][x] = 0
    cnt += 1

    if cnt == shark_size:
        shark_size += 1
        cnt = 0
    print(shark_size)
print(time)


class A:
    def __init__(self, val1: int, val2: int):
        self.val1 = val1
        self.val2 = val2

    #def showA(self):
    #   return f"{self.val1}, {self.val2}"

class B:
    def __init__(self, val1: int, a: A):
        self.val1 = val1
        self.a = a

    def showB(self):
        #return f"{self.val1}, {self.a.showA()}"
        return f"{self.val1}, {self.a.val1}, {self.a.val2}" #też działa <- i teraz to zgłupiałem czemu to mi nie działało ???!!!!

newA = A(1,2) #tworzę obiekt instancją klasy A o nazwie newA z parametrami 1,2

newB = B(3,newA) # tworzę obiekt instancję klasy B o nazwie newB z parametrami 3 i obiektem newA klasy A

#print(newA.showA()) # mogę odwołąć się do metody w klasie A przy czym co jeśli nie chcę mieć do tego dostępu
# ponieważ dostęp ma mieć tylko klasa B, czy będzie to później omówione w następnych lrekcjach ? odp. chyba chodzi o enkapsulację
# czyli ukrywanie przed niepowołanym dostępem więc raczej się zagalopowałęm w myśleniu i coś pomyliłem :-(
print(newB.showB()) # mam dostęp do metody z clasy B która w sobie ma dostęp do metody a klasy A
# a co jeżeli chciałbym w showB mieć dostęp do self.a.val1 <- o dziwo nie wiem co było nie tak że to nie działało ?
print(newB.a.val1) # po dopisaniu tej linijki już kompletnie nic nie rozumiem !!! nie mogę znaleźć błedu w moim myśleniu
# co robiłem do tej pory niewłaściwie bo nie mogłem uzyskać -> obiektKlasyB.ObiektKlasyA.WłaściwośćPolaXzKlasyA
# drugi dzień nad tym siedzę :-( a teraz nagle nie wiedzić czemu napisałem no i uzyskałem to co chciałem i jest to zgodne z tym
# w jaki sposób sobie to wyobrażałem w głowie tzn. myślałem, że tak to ma działać ale nie działało ?

meeting1 = ('a', 1)
meeting2 = "spotkanie"
meetings = {}

meetings[0] = meeting1
meetings["2020-01-01"] = meeting1
meetings[23] = meeting2

print(meetings)


import random
from vue.view import TournoiView
from modeles.joueurs import Joueurs
from tinydb import TinyDB, Query

class Tour:

    def __init__(self):
        self.db = TinyDB('database/database_joueurs.json')
        self.dbclassement = TinyDB('database/dbclassement.json')
        db = self.db.all()
        dbclassement = self.dbclassement.all()
        self.joueurs = Joueurs(db, dbclassement)

        self.tournoi = TournoiView()

    # on génère le tour 1 automatiquement
    def generate_tour(self):
        result = self.joueurs.get_all_joueurs()
        round = 4
        groupe1 = result[:4]
        groupe2 = result[4:]
        matchs = []
        for i in range(round):
            print(i)
            groupe1[i].points = random.randint(0, 20)
            groupe2[i].points = random.randint(0, 20)
        if groupe1[i].points > groupe2[i].points:
            groupe1[i]["score"] += 1
            print(groupe1[i]["nom"] + " gagne")
        elif groupe2[i].points > groupe1[i].points:
            groupe2[i]["score"] += 1
            print(groupe2[i]["nom"] + " gagne")
        else:
            groupe1[i]["score"] += 0.5
            groupe2[i]["score"] += 0.5

        match = ((groupe1[i]["nom"], groupe2[i]["nom"]),
                (groupe1[i]["score"], groupe2[i]["score"]))
        matchs.append(match)

        for match in matchs:
            print(match)

        playerslists = groupe1 + groupe2
        playerslists_ordering = sorted(playerslists,
                                key=lambda x: x["score"], reverse=True)

        # - # ------------------ ROUND 1 -----------------
        matchs = []
        # génération des rounds suivants
        for i in range(round):
            groupe1[i].points = random.randint(0, 20)
            groupe2[i].points = random.randint(0, 20)
            if groupe1[i].points > groupe2[i].points:
                groupe1[i]["score"] += 1
                print(groupe1[i]["nom"] + " gagne")
            elif groupe2[i].points > groupe1[i].points:
                groupe2[i]["score"] += 1
                print(groupe2[i]["nom"] + " gagne")
            else:
                groupe1[i]["score"] += 0.5
                groupe2[i]["score"] += 0.5
            match = ((groupe1[i]["nom"], groupe2[i]["nom"]),
                        (groupe1[i]["score"], groupe2[i]["score"]))
            matchs.append(match)
        for match in matchs:
            print(match)

        # gestion du tour par tour
        playerslists = groupe1 + groupe2
        playerslists_ordering = sorted(playerslists,
                                        key=lambda x: x["score"], reverse=True)
        compteur = 1
        reponse = input("1.Oui\n2.Non\n")
        if reponse == "1":
            reponse_utilisateur = True
        if reponse == "2":
            reponse_utilisateur = False
        print(reponse_utilisateur)

        while compteur < 9 and reponse_utilisateur == True:
            print(f" ------------------ ROUND {compteur+1} -----------------")
            current_round = []
            playerslists_ordering = sorted(playerslists,
                                        key=lambda x: x["score"],
                                        reverse=True)

            for i in range(0, 8):
                p1 = playerslists_ordering[i]["nom"]
                for j in range(i+1, 8):
                    p2 = playerslists_ordering[j]["nom"]
                    print(p1, p2)
                    match = ((playerslists_ordering[i]["nom"],
                    playerslists_ordering[j]["nom"]),
                    (playerslists_ordering[i]["score"],
                    playerslists_ordering[j]["score"]))
                    if self.check_match(p1, p2, matchs) == False:
                        if self.check_player(p1, p2, current_round) == False:
                            current_round.append(match)
                            matchs.append(match)
                            self.update_score(playerslists_ordering[i],
                            playerslists_ordering[j])
                            break
            print(matchs)
            compteur += 1
            if len(current_round) == 0:
                print("plus de matchs possibles")

            match_sauvegarde = self.serialize_matchs(matchs)
            database = self.dbclassement
            database.insert(match_sauvegarde)
            reponse = input("1.Oui\n2.Non\n")

            if reponse == "1":
                reponse_utilisateur = True
            if reponse == "2":
                reponse_utilisateur = False
            print(reponse_utilisateur)

    def check_match(self, p1, p2, matchs):
        for item in matchs:
            if (p1 == item[0][0] and p2 == item[0][1]) or (
                            p1 == item[0][1] and p2 == item[0][0]):
                return True
        return False

    def check_player(self, p1, p2, match_round2):
        for item in match_round2:
            if (p1 == item[0][0] or p1 == item[0][1]) or (
                            p2 == item[0][0] or p2 == item[0][1]):
                return True
        return False

    # update du score des joueurs
    def update_score(self, p1, p2):

        score_p1 = self.tournoi.display_score_joueur(p1)

        if score_p1 == 1:
            p1["score"] += 1
            p2["score"] += 0
        elif score_p1 == 0:
            p1["score"] += 0
            p2["score"] += 1
        else:
            p1["score"] += 0.5
            p2["score"] += 0.5
        self.joueurs.update_score_joueur(p1, p2)

    def serialize_matchs(self, match):
        resultat = {"match": match}
        return resultat


from django.contrib import admin
from .models import Student, Course, Instructor

class CourseInline(admin.TabularInline):
    model = Course
    extra = 3

class InstructorAdmin(admin.ModelAdmin):
    fieldsets = [
        ('Instructor Name',          {'fields': ['i_name']}),
        ('Instructor ID',    {'fields': ['i_id']}),
    ]
    inlines = [CourseInline]
    list_display = ('i_name', 'i_id')
    search_fields = ['i_name']

admin.site.register(Student)
admin.site.register(Course)
admin.site.register(Instructor, InstructorAdmin)


import os
import shutil
import itertools
import numpy as np
import torch
import torch.nn as nn
import torchvision
import torchvision.datasets as datasets
import torchvision.transforms as transforms
import skimage
import tqdm
from collections import defaultdict

def get_covariance(examples):
    mean, std = examples.mean(dim=0), examples.std(dim=0)
    outer = mean.unsqueeze(0) * mean.unsqueeze(1)
    cov =  (examples.t() @ examples / len(examples) - outer)
    return cov

def calc_weight_alignments(model):
    alignments = {'layers':[]}
    b = model.dfa.feedback_matrix
    bs = []
    for l in range(1,len(model.layers)):
        w = model.state_dict()['layers.{}.weight'.format(l)].view(-1)
        if l == len(model.layers)-1:
            v = b[-1].view(-1)
        else:
            v = (b[l].t()@b[l-1]).view(-1)
        bs.append(v)
        a = v @ w / w.norm() / v.norm()
        alignments['layers'].append(a.item())
    ws = torch.cat([w.view(-1) for w in list(model.state_dict().values())[1:]])
    bs = torch.cat(bs)
    total =  ws @ bs / ws.norm() / bs.norm()
    alignments['total'] = total.item()
    return dict(alignments)

def shuffle_labels(labels, label_noise, num_classes):
    for i in range(len(labels)):
        if np.random.rand()<label_noise:
            labels[i] = np.random.randint(0, num_classes)
    return labels

def get_data(dataset, dataset_path, batch_size, test_batch_size, num_classes=None, input_dim=None, datasize=0, label_noise=0.):

    input_sizes = {'MNIST':28, 'FashionMNIST':28, 'CIFAR10':32, 'CIFAR100':32}
    output_sizes = {'MNIST':10, 'FashionMNIST':10, 'CIFAR10':10, 'CIFAR100':100}
    input_channels = {'MNIST':1, 'FashionMNIST':1, 'CIFAR10':3, 'CIFAR100':3}
    input_size = input_sizes[dataset]
    output_size = output_sizes[dataset]
    input_channels = input_channels[dataset]

    dataclass = eval('Fast'+dataset)
    train_data = dataclass(dataset_path, train=True, download=True)
    test_data = dataclass(dataset_path, train=False, download=True)

    if num_classes:
        output_size = num_classes
        train_data.targets = train_data.targets%num_classes
        test_data.targets = test_data.targets%num_classes

    if datasize is not None:
        train_data.data = train_data.data[:datasize]
        train_data.targets = train_data.targets[:datasize]

    # resizing
    if input_dim is not None:
        input_size = input_dim
        print('Starting the resizing')
        for dataset in [train_data, test_data]:
            size, channels, _, _, = dataset.data.size()
            new_data = torch.empty(size, channels, input_size, input_size)
            for i, img in enumerate(dataset.data):
                for c, img_channel in enumerate(dataset.data[i]):
                    new_data[i,c] = torch.from_numpy(skimage.transform.resize(img_channel, (input_size, input_size)))
            dataset.data = new_data
        print('Finished the resizing')

    if label_noise:
        for dataset in [train_data, test_data]:
            dataset.targets = shuffle_labels(dataset.targets, label_noise, output_size)

    train_loader = torch.utils.data.DataLoader(train_data, batch_size=batch_size, shuffle=True)
    train_loader_log = torch.utils.data.DataLoader(train_data, batch_size=batch_size, shuffle=False)
    test_loader  = torch.utils.data.DataLoader(test_data, batch_size=test_batch_size, shuffle=True)

    return train_loader, train_loader_log, test_loader, input_size, output_size, input_channels

def get_random_data(batch_size, test_batch_size, num_classes=None, input_dim=None, datasize=0, label_noise=0., beta=1., alpha=1, task= 'CLASSIFICATION', use_teacher=False):

    assert input_dim**.5 == int(input_dim**.5)
    with torch.no_grad():
        n_batches = max(1,datasize // batch_size)
        n_batches_test = max(1,datasize // test_batch_size)
        train_loader = []
        test_loader = []
        if use_teacher:
            teacher = nn.Sequential(nn.Linear(input_dim, num_classes))
        else:
            if num_classes==2:
                dist = torch.distributions.MultivariateNormal(torch.zeros(2), torch.Tensor([[1, alpha*(1-beta)],[alpha*(1-beta), alpha**2]]))
            else:
                raise NotImplementedError
        for i in range(n_batches):
            x = torch.randn(batch_size, input_dim)
            if task=='REGRESSION':
                if use_teacher: y = teacher(x)
                else: y = dist.sample((batch_size,))
                y += label_noise * torch.randn(y.size())
            elif task=='CLASSIFICATION':
                if use_teacher: y = teacher(x).max(1)[1]
                else: raise NotImplementedError
                y = shuffle_labels(y, label_noise, num_classes)
            train_loader.append([x,y])
        for i in range(n_batches_test):
            x = torch.randn(test_batch_size, input_dim)
            if task=='REGRESSION':
                if use_teacher: y = teacher(x)
                else: y = dist.sample((test_batch_size,))
                y += label_noise * torch.randn(y.size())
            elif task=='CLASSIFICATION':
                if use_teacher: y = teacher(x).max(1)[1]
                else: raise NotImplementedError
                y = shuffle_labels(y, label_noise, num_classes)
            test_loader.append([x,y])
    return train_loader, train_loader, test_loader, int(input_dim**.5), num_classes, 1

class FastMNIST(datasets.MNIST):
    def __init__(self, *args, **kwargs):
        super().__init__(*args, **kwargs)

        if torch.cuda.is_available():
            self.device = torch.device('cuda')
        else:
            self.device = torch.device('cpu')

        self.data = self.data.unsqueeze(1).float().div(255)
        self.data = self.data.sub_(self.data.mean()).div_(self.data.std())
        self.data, self.targets = self.data.to(self.device), self.targets.to(self.device)

    def __getitem__(self, index):
        img, target = self.data[index], self.targets[index]
        return img, target

class FastFashionMNIST(datasets.FashionMNIST):
    def __init__(self, *args, **kwargs):
        super().__init__(*args, **kwargs)

        if torch.cuda.is_available():
            self.device = torch.device('cuda')
        else:
            self.device = torch.device('cpu')

        self.data = self.data.unsqueeze(1).float().div(255)
        self.data = self.data.sub_(self.data.mean()).div_(self.data.std())
        self.data, self.targets = self.data.to(self.device), self.targets.to(self.device)

    def __getitem__(self, index):
        img, target = self.data[index], self.targets[index]
        return img, target

class FastCIFAR10(datasets.CIFAR10):
    def __init__(self, *args, **kwargs):
        super().__init__(*args, **kwargs)
        if torch.cuda.is_available():
            self.device = torch.device('cuda')
        else:
            self.device = torch.device('cpu')
        self.data = np.transpose(self.data, (0, 3, 1, 2))
        self.data = torch.from_numpy(self.data).float().div(255)
        self.data = self.data.sub_(self.data.mean()).div_(self.data.std())
        self.data, self.targets = self.data.to(self.device), torch.LongTensor(self.targets).to(self.device)

    def __getitem__(self, index):
        img, target = self.data[index], self.targets[index]
        return img, target

class FastCIFAR100(datasets.CIFAR100):
    def __init__(self, *args, **kwargs):
        super().__init__(*args, **kwargs)

        if torch.cuda.is_available():
            self.device = torch.device('cuda')
        else:
            self.device = torch.device('cpu')

        self.data = np.transpose(self.data, (0, 3, 1, 2))
        self.data = torch.from_numpy(self.data).float().div(255)
        self.data = self.data.sub_(self.data.mean()).div_(self.data.std())
        self.data, self.targets = self.data.to(self.device), torch.LongTensor(self.targets).to(self.device)

    def __getitem__(self, index):
        img, target = self.data[index], self.targets[index]
        return img, target

#helpers
def copy_py(dst_folder):
    # and copy all .py's into dst_folder
    if not os.path.exists(dst_folder):
        print("Folder doesn't exist!")
        return
    for f in os.listdir():
        if f.endswith('.py'):
            shutil.copy2(f, dst_folder)
def dict_product(d):
    keys = d.keys()
    for element in itertools.product(*d.values()):
        yield dict(zip(keys, element))


import numpy as np

def prod_non_zero_diag(x):
    """Compute product of nonzero elements from matrix diagonal.

    input:
    x -- 2-d numpy array
    output:
    product -- integer number

    Vectorized implementation.
    """

    diag = np.diag(x)
    return diag[diag != 0].prod()

def are_multisets_equal(x, y):
    """Return True if both vectors create equal multisets.

    input:
    x, y -- 1-d numpy arrays
    output:
    True if multisets are equal, False otherwise -- boolean

    Vectorized implementation.
    """

    return np.array_equal(np.sort(x), np.sort(y))

def max_after_zero(x):
    """Find max element after zero in array.

    input:
    x -- 1-d numpy array
    output:
    maximum element after zero -- integer number

    Vectorized implementation.
    """

    ind = np.argmax(x)
    max_val = x[ind]

    if x[ind-1] == 0 and ind != 0:
        return max_val
    else:
        new_x = np.delete(x, ind)
        return max_after_zero(new_x)

def convert_image(img, coefs):
    """Sum up image channels with weights from coefs array

    input:
    img -- 3-d numpy array (H x W x 3)
    coefs -- 1-d numpy array (length 3)
    output:
    img -- 2-d numpy array

    Vectorized implementation.
    """

    len_img = len(img[0][0])
    len_coefs = len(coefs)

    if len_img != len_coefs:
        dif = len_img - len_coefs
        zeros = np.zeros(dif)
        coefs = np.concatenate((coefs, zeros), axis=None)
    return np.dot(img, coefs)

def run_length_encoding(x):
    """Make run-length encoding.

    input:
    x -- 1-d numpy array
    output:
    elements, counters -- integer iterables

    Vectorized implementation.
    """

    ia = np.array(x)
    n = len(ia)
    if n == 0:
        return (None, None, None)
    else:
        y = np.array(ia[1:] != ia[:-1])
        i = np.append(np.where(y), n - 1)
        z = np.diff(np.append(-1, i))
        return( ia[i], z)

def pairwise_distance(x, y):
    """Return pairwise object distance.

    input:
    x, y -- 2d numpy arrays
    output:
    distance array -- 2d numpy array

    Vctorized implementation.
    """

    pass


"""
# Sample code to perform I/O:

name = input()                  # Reading input from STDIN
print('Hi, %s.' % name)         # Writing output to STDOUT

# Warning: Printing unwanted or ill-formatted data to output will cause the test cases to fail
"""

# Write your code here
n = int(input())
a = list(map(int, input().strip().split()))
exist = False
for i in range(n - 1, 0, -1):
    j = 0
    while not exist and j < n - i:
        if a[j] == a[j + i]:
            print(i + 1)
            exist = True
        else:
            j += 1
    if exist:
        break
else:
    print(0)

hackerearth/Algorithms/Mathison and the funny subarray/solution.py


# UI:

SCREEN_WIDTH = 1140
SCREEN_HEIGHT = 550
SCREEN_GEOMETRY = (SCREEN_WIDTH, SCREEN_HEIGHT)

# Palette from https://www.colorion.co/palette/87411:
PALETTE_BLACK = (0x01, 0x01, 0x01)
PALETTE_LIGHTGRAY = (0xD8, 0xD8, 0xD8)
PALETTE_SPRINGGREEN = (0x56, 0xF5, 0x69)
PALETTE_DIMGRAY = (0x60, 0x60, 0x60)
PALETTE_DARKGRAY = (0xA3, 0xA9, 0xA4)

BACKGROUND_COLOR = PALETTE_BLACK
PRIMARY_COLOR = PALETTE_LIGHTGRAY
HIGHLIGHT_COLOR = PALETTE_SPRINGGREEN
SECONDARY_COLOR = PALETTE_DARKGRAY

FONT_FAMILY = 'monospace'
FONT_SIZE = 16
FONT_WIDTH = 10

MARGIN = 10

FRAMES_PER_SECOND = 60

# CHIP-8:

CHIP8_STEPS_PER_SECOND = 720
CHIP8_TIMER_UPDATES_PER_SECOND = 60

# GameScreen:

PIXEL_SIZE = 10
PIXEL_ON_COLOR = PALETTE_SPRINGGREEN
PIXEL_OFF_COLOR = PALETTE_DIMGRAY


from rdkit import Chem
from mmpdblib import environment
import sqlite3

def get_envsmi(constant_smi, radius):
    centers = environment.find_centers(constant_smi)
    res = []
    for atom_id in centers.atom_ids:
        env = Chem.FindAtomEnvironmentOfRadiusN(centers.mol, radius, atom_id)
        submol = Chem.PathToSubmol(centers.mol, env)
        smi = Chem.MolToSmiles(submol)
        res.append(smi)
    return ".".join(res)

def make_environment_smi(mmpdb_con, medchem_move_con, radi=3):
    mmpdb_cur = mmpdb_con.cursor()
    medchem_move_cur = medchem_move_con.cursor()
    sql = f"""SELECT DISTINCT constant_smiles.Smiles
             FROM rule_environment,
                           pair,
                           constant_smiles
             WHERE rule_environment.id = pair.rule_environment_id
             AND pair.constant_id = constant_smiles.id
             AND rule_environment.radius = {radi}
             ;"""
    res = mmpdb_cur.execute(sql)
    for idx, row in enumerate(res.fetchall()):
        env_smi = get_envsmi(row[0], radi)
        try:
            medchem_move_cur.execute("INSERT INTO environment_smi values({env_smi});")
        except:
            print(f"{env_smi} is already exist")
        if idx % 10000 == 0:
            print(f"{idx} mol proceeded")
    medchem_move_con.commit()
    print("done environment_smi")

def make_environment_fp(mmpdb_con, medchem_move_con, radi=3):
    mmpdb_cur = mmpdb_con.cursor()
    medchem_move_cur = medchem_move_con.cursor()
    sql = f"""SELECT DISTINCT environment_fingerprint.id, environment_fingerprint.fingerprint
              FROM rule_environment, environment_fingerprint
              WHERE rule_environment.environment_fingerprint_id = environment_fingerprint.id
              AND rule_environment.radius = {radi}
              ;"""
    fp_info = mmpdb_cur.execute(sql).fetchall()
    for row in fp_info:
        medchem_move_con.execute(f"INSERT INTO environment_fp values({row[0]}, {row[1]});")
    medchem_move_con.commit()
    print("done environment_fp")

def make_fragment_smi(mmpdb_con, medchem_move_con):
    mmpdb_cur = mmpdb_con.cursor()
    medchem_move_cur = medchem_move_con.cursor()
    sql = "SELECT id, smiles FROM rule_smiles;"
    for row in mmpdb_cur.execute(sql).fetchall():
        medchem_move_cur.execute(f"INSERT INTO fragment_smi VALUES(row[0], row[1]);")
    medchem_move_con.commit()
    print("done fragment_smi")

def make_transformations(mmpdb_con, medchem_move_con):
    mmpdb_cur = mmpdb_con.cursor()
    medchem_move_cur = medchem_move_con.cursor()
    sql = """"""


#!/usr/bin/env python3
from __future__ import print_function
import sys
sys.path.append('./method')
import os
import numpy as np
import matplotlib
matplotlib.use('Agg')
import matplotlib.pyplot as plt

import model as m

savedir = './fig'
if not os.path.isdir(savedir):
    os.makedirs(savedir)

# Get all input variables
import importlib
sys.path.append('./mmt-model-files')
info_ida = 'model_A'
infoa = importlib.import_module(info_ida)
info_idb = 'model_B'
infob = importlib.import_module(info_idb)
info_idc = 'model_C'
infoc = importlib.import_module(info_idc)

modela = m.Model(infoa.model_file,
        variables=infoa.parameters,
        current_readout=infoa.current_list,
        set_ion=infoa.ions_conc,
        temperature=273.15 + infoa.temperature,  # K
        )
modelb = m.Model(infob.model_file,
        variables=infob.parameters,
        current_readout=infob.current_list,
        set_ion=infob.ions_conc,
        temperature=273.15 + infob.temperature,  # K
        )
modelc = m.Model(infoc.model_file,
        variables=infoc.parameters,
        current_readout=infoc.current_list,
        set_ion=infoc.ions_conc,
        temperature=273.15 + infoc.temperature,  # K
        )

#
# Activation step protocol
#
# Load protocol
test_prt = [-80, 200, 20, 500, -40, 500, -80, 200]
dt = 0.1
test_t = np.arange(0, np.sum(test_prt[1::2]), dt)

# Update protocol
modela.set_voltage_protocol(test_prt)
modelb.set_voltage_protocol(test_prt)
modelc.set_voltage_protocol(test_prt)

# Plot
plt.figure(figsize=(8, 6))
plt.subplot(211)
plt.plot(test_t, modela.voltage(test_t), c='#7f7f7f')
plt.plot(test_t, modelb.voltage(test_t), c='#7f7f7f')
plt.plot(test_t, modelc.voltage(test_t), c='#7f7f7f')
plt.ylabel('Voltage (mV)')

plt.subplot(212)
plt.plot(test_t, modela.simulate(infoa.base_param, test_t), label='Model A')
plt.plot(test_t, modelb.simulate(infob.base_param, test_t), label='Model B')
plt.plot(test_t, modelc.simulate(infoc.base_param, test_t), label='Model C')
plt.legend()
plt.xlabel('Time (ms)')
plt.ylabel('Current (pA)')

plt.subplots_adjust(hspace=0)
plt.savefig('%s/test-models-activation.png' % (savedir), bbox_inches='tight')
plt.close()

#
# Sine wave protocol
#
# Load protocol
test_prt = np.loadtxt('./protocol-time-series/sinewave.csv', skiprows=1,
        delimiter=',')
test_t = test_prt[:, 0]
test_prt = test_prt[:, 1]

# Update protocol
modela.set_fixed_form_voltage_protocol(test_prt, test_t)
modelb.set_fixed_form_voltage_protocol(test_prt, test_t)
modelc.set_fixed_form_voltage_protocol(test_prt, test_t)

# Plot
plt.figure(figsize=(8, 6))
plt.subplot(211)
plt.plot(test_t, modela.voltage(test_t), c='#7f7f7f')
plt.plot(test_t, modelb.voltage(test_t), c='#7f7f7f')
plt.plot(test_t, modelc.voltage(test_t), c='#7f7f7f')
plt.ylabel('Voltage (mV)')

plt.subplot(212)
plt.plot(test_t, modela.simulate(infoa.base_param, test_t), label='Model A')
plt.plot(test_t, modelb.simulate(infob.base_param, test_t), label='Model B')
plt.plot(test_t, modelc.simulate(infoc.base_param, test_t), label='Model C')
plt.legend()
plt.xlabel('Time (ms)')
plt.ylabel('Current (pA)')

plt.subplots_adjust(hspace=0)
plt.savefig('%s/test-models-sinewave.png' % (savedir), bbox_inches='tight')
plt.close()

#
# AP protocols
#
# Load protocol
test_prt = np.loadtxt('./protocol-time-series/ap.csv', skiprows=1,
        delimiter=',')
test_t = test_prt[:, 0]
test_prt = test_prt[:, 1]

# Update protocol
modela.set_fixed_form_voltage_protocol(test_prt, test_t)
modelb.set_fixed_form_voltage_protocol(test_prt, test_t)
modelc.set_fixed_form_voltage_protocol(test_prt, test_t)

# Plot
plt.figure(figsize=(8, 6))
plt.subplot(211)
plt.plot(test_t, modela.voltage(test_t), c='#7f7f7f')
plt.plot(test_t, modelb.voltage(test_t), c='#7f7f7f')
plt.plot(test_t, modelc.voltage(test_t), c='#7f7f7f')
plt.ylabel('Voltage (mV)')

plt.subplot(212)
plt.plot(test_t, modela.simulate(infoa.base_param, test_t), label='Model A')
plt.plot(test_t, modelb.simulate(infob.base_param, test_t), label='Model B')
plt.plot(test_t, modelc.simulate(infoc.base_param, test_t), label='Model C')
plt.legend()
plt.xlabel('Time (ms)')
plt.ylabel('Current (pA)')

plt.subplots_adjust(hspace=0)
plt.savefig('%s/test-models-ap.png' % (savedir), bbox_inches='tight')
plt.close()


import pandas as pd
import matplotlib.pyplot as plt

dfMember2020 = pd.read_csv("Data/西武ライオンズ_打撃成績/2020年.csv", index_col='選手')
dfMember2019 = pd.read_csv("Data/西武ライオンズ_打撃成績/2019年.csv", index_col='選手')
dfMember2018 = pd.read_csv("Data/西武ライオンズ_打撃成績/2018年.csv", index_col='選手')
dfMember2017 = pd.read_csv("Data/西武ライオンズ_打撃成績/2017年.csv", index_col='選手')
dfMember2016 = pd.read_csv("Data/西武ライオンズ_打撃成績/2016年.csv", index_col='選手')
dfMember2015 = pd.read_csv("Data/西武ライオンズ_打撃成績/2015年.csv", index_col='選手')

# 2020年に100試合以上出場した選手
#print(dfMember2019 [dfMember2019 ['試合'] > 100][['選手', '試合']])

# mergeを用いた方法
members1920 = pd.merge(dfMember2019, dfMember2020, left_index=True, right_index=True, how='outer', suffixes=('_2019', '_2020'))
members1718 = pd.merge(dfMember2017, dfMember2018, left_index=True, right_index=True, how='outer', suffixes=('_2017', '_2018'))
members1516 = pd.merge(dfMember2015, dfMember2016, left_index=True, right_index=True, how='outer', suffixes=('_2015', '_2016'))
members = pd.merge(members1920, members1718, left_index=True, right_index=True, how='outer')
members = pd.merge(members1516, members, left_index=True, right_index=True, how='outer')

members100over = members [members['試合_2020'] > 80][members['試合_2019'] > 80][members['試合_2018'] > 80][members['試合_2017'] > 80][members['試合_2016'] > 80][members['試合_2015'] > 80]
print(members100over.loc[:, ['試合_2015', '試合_2016', '試合_2017', '試合_2018', '試合_2019', '試合_2020']])

# concatを用いた方法
dfMembers = pd.concat({'2020':dfMember2020, '2019':dfMember2019, '2018':dfMember2018}, axis=1)
dfMembers100Over =  dfMembers[dfMembers['2020', '試合'] > 100][dfMembers['2019', '試合'] > 100][dfMembers['2018', '試合'] > 100]
print(dfMembers100Over.loc[:, [('2020', '試合'), ('2019', '試合'), ('2018', '試合')]])


import pandas as pd
from typing import Callable, Dict, Union, Iterable, Any
from functools import partial
from itertools import product
from joblib import Parallel, delayed
import matplotlib.pyplot as plt
import seaborn as sns
from PIL import Image
from importlib import resources

from factorlab.factor_analysis import Factor
from factorlab.performance import Performance

def feat_partial(feature: Callable,
                 df: pd.DataFrame,
                 **kwargs: Dict,
                 ) -> Callable:
    """
    Creates a partial function for a factor (feature) by fixing specified arguments.

    Parameters
    ----------
    feature: callable
        Alpha or risk factor to construct, e.g. Trend, Value, Carry, etc.
    df: pd.DataFrame - pd.MultiIndex
        DataFrame with DatetimeIndex (level 0), tickers (level 1) and raw data (cols).
    kwargs: dict
        Keyword arguments for the factor (feature).

    Returns
    -------
    feat_part: callable
        Partial function for factor.
    """
    feat_part = partial(feature, df, **kwargs)()

    return feat_part

def algo_partial(feat_part: Callable,
                 algo: str,
                 **kwargs: Dict
                 ) -> Union[pd.Series, pd.DataFrame]:
    """
    Calls the method/algorithm for the specified factor, e.g. for the Trend factor
    we can call the 'price_mom' method/algorithm.

    Parameters
    ----------
    feat_part: callable
        Partial function created for factor (feat_partial).
    algo: str
        Method/algorithm to use with the factor (feat_part).
    kwargs: dict
        Keyword arguments for the method/algorithm.

    Returns
    -------
    feature: pd.Series or pd.DataFrame - pd.MultiIndex
        Series or Dataframe with DatetimeIndex (level 0), ticker (level 1), and factor values (cols).
    """
    feature = getattr(feat_part, algo)(**kwargs)

    return feature

def feat(df: pd.DataFrame,
         feature: Callable,
         algo: str,
         feat_args: Dict,
         algo_args: Dict
         ) -> Union[pd.Series, pd.DataFrame]:
    """
    Constructs an alpha/risk factor (feature) from the specified parameters.

    Parameters
    ----------
    df: pd.DataFrame - pd.MultiIndex
        DataFrame with DatetimeIndex (level 0), tickers (level 1) and raw data (cols).
    feature: callable
        Alpha or risk factor to construct, e.g. Trend, Value, Carry, etc.
    algo: str
        Method/algorithm to use with the factor (feature).
    feat_args: dict
        Keyword arguments for the factor (feature).
    algo_args: dict
        Keyword arguments for the method/algorithm.

    Returns
    -------
    feature: pd.Series or pd.DataFrame - pd.MultiIndex
        Series or Dataframe with DatetimeIndex (level 0), ticker (level 1), and factor values (cols).
    """
    # compute partial fcn
    feat_part = feat_partial(feature, df, **feat_args)
    # compute factor with specified algo/method
    feature = algo_partial(feat_part, algo, **algo_args)

    return feature

def factor_partial(*args: Union[pd.Series, pd.DataFrame],
                   **kwargs: Dict
                   ) -> Callable:
    """
    Creates a partial function/callable for a factor strategy while specified arguments.

    Parameters
    ----------
    args: pd.Series or pd.DataFrame
        Factor dataframe and forward return series.
    kwargs: dict
        Keyword arguments for the factor strategy.

    Returns
    -------
    fact_part: callable
        Partial function for factor strategy.
    """
    factor_part = partial(Factor, *args)
    fact_part = factor_part(**kwargs)

    return fact_part

def ret_partial(factor_part: Callable,
                **kwargs: Dict
                ) -> Union[pd.Series, pd.DataFrame]:
    """
    Calls the return method/algorithm for the specified factor strategy, e.g. for a long/short factor strategy
    we can call the 'returns' method/algorithm to get factor returns.

    Parameters
    ----------
    factor_part: callable
        Partial function/callable created for factor strategy (factor_partial)
    kwargs: any
        Keyword arguments for the returns' method/algorithm.

    Returns
    -------
    ret: pd.Series or pd.DataFrame - pd.MultiIndex
        Factor returns series or Dataframe with DatetimeIndex (level 0), ticker (level 1),
        and factor returns (cols).
    """
    ret = getattr(factor_part, 'returns')(**kwargs)

    return ret

def factor_ret(factors: Union[pd.Series, pd.DataFrame],
               fwd_ret: Union[pd.Series, pd.DataFrame],
               factor_args: Dict,
               ret_args: Dict
               ) -> Union[pd.Series, pd.DataFrame]:

    """
    Computes factor returns with factor and return arguments.

    Parameters
    ----------
    factors: pd.Series or pd.DataFrame
        Series or dataframe with DatetimeIndex (level 0), ticker (level 1) and factor values (cols).
    fwd_ret: pd.Series or pd.DataFrame
        Series or dataframe with DatetimeIndex (level 0), ticker (level 1) and forward returns (cols).
    factor_args: dict
        Keyword arguments for computation of factor-based strategy.
    ret_args: dict
        Keyword arguments for computation of factor-based returns.

    Returns
    -------
    ret: pd.Series or pd.DataFrame
        Factor returns series or dataframe with DatetimeIndex (level 0), ticker (level 1) and factor returns (cols).
    """
    # get factor partial fcn/callable
    factor_part = factor_partial(factors, fwd_ret, **factor_args)
    # compute factor returns
    ret = ret_partial(factor_part, **ret_args)

    return ret

def grid_parameters(parameters: dict[str, Iterable[Any]]) -> Iterable[dict[str, Any]]:
    """
    Yields all parameter combinations/pairs.

    Parameters
    ----------
    parameters: dict
        Parameter space.

    Yields
    -------
    Iterable
        Parameter pairs.
    """
    for params in product(*parameters.values()):
        yield dict(zip(parameters.keys(), params))

def compute_metric(
        factor: Union[pd.Series, pd.DataFrame],
        fwd_ret: Union[pd.Series, pd.DataFrame],
        factor_args: Dict,
        ret_args: Dict,
        metric: str
):
    """
    Compute performance metric to be used in grid search.

    Parameters
    ----------
    factor: pd.Series or pd.DataFrame
        Factor to compute factor returns.
    fwd_ret: pd.Series or DataFrame
        Forward returns.
    factor_args: dict
        Keyword arguments for computation of factor-based strategy.
    ret_args: dict
        Keyword arguments for computation of factor-based returns.
    metric: str, {'cumulative_ret', 'sharpe_ratio', 'sortino_ratio', 'calmar_ratio', 'omega_ratio'},
            default sharpe_ratio
        Performance metric to compute.

    Returns
    -------
    val: pd.Series
        Performance metric value.
    """
    val = getattr(Performance(factor_ret(factor, fwd_ret, factor_args, ret_args)), metric)()

    return val

def factor_param_grid_search(
        df: Union[pd.Series, pd.DataFrame],
        fwd_ret: Union[pd.Series, pd.DataFrame],
        feature: Callable,
        algo: str,
        feat_args: Dict,
        algo_args: Dict,
        factor_args: Dict,
        ret_args: Dict,
        metric: str = 'sharpe_ratio'
):
    """
    Factor parameter grid search. Computes metric across all pairs/combinations
    of parameter values for factor (feature) and method/algorithms.

    Parameters
    ----------
    df: pd.DataFrame - pd.MultiIndex
        DataFrame with DatetimeIndex (level 0), tickers (level 1) and raw data (cols).
    fwd_ret: pd.Series or DataFrame
        Forward returns.
    feature: callable
        Alpha or risk factor to construct, e.g. Trend, Value, Carry, etc.
    algo: str
        Method/algorithm to use with the factor (feature).
    feat_args: dict
        Keyword arguments for the factor (feature).
    algo_args: dict
        Keyword arguments for the method/algorithm.
    factor_args: dict
        Keyword arguments for computation of factor-based strategy.
    ret_args: dict
        Keyword arguments for computation of factor-based returns.
    metric: str, {'cumulative_ret', 'sharpe_ratio', 'sortino_ratio', 'calmar_ratio', 'omega_ratio'},
            default sharpe_ratio
        Performance metric to compute.

    Returns
    -------
    df: pd.DataFrame
        Dataframe with parameter and metric values for all alpha/risk factor parameter combinations.
    """
    # loop through params and compute metrics
    metrics = Parallel(n_jobs=8)(delayed(compute_metric)(feat(df, feature, algo, feat_param, algo_param),
                                                         fwd_ret,
                                                         factor_args,
                                                         ret_args,
                                                         metric)
                                 for feat_param in grid_parameters(feat_args) for algo_param in
                                 grid_parameters(algo_args))

    # convert vals to list
    metrics = [i[0] for i in metrics]

    # create param values
    params = [(feat_param | algo_param) for feat_param in grid_parameters(feat_args) for algo_param in
              grid_parameters(algo_args)]
    df = pd.DataFrame(params, metrics).reset_index().rename(columns={'index': metric}).sort_values(by=metric,
                                                                                ascending=False)

    return df

def strategy_param_grid_search(
        factor: Union[pd.Series, pd.DataFrame],
        fwd_ret: Union[pd.Series, pd.DataFrame],
        factor_args: Dict,
        ret_args: Dict,
        metric: str = 'sharpe_ratio',
):
    """
    Factor strategy parameter grid search. Computes metric across all pairs/combinations
    of parameter values for strategy and returns method.

    Parameters
    ----------
    factor: pd.Series or pd.DataFrame
        Factor to compute factor returns.
    fwd_ret: pd.Series or DataFrame
        Forward returns.
    factor_args: dict
        Keyword arguments for computation of factor-based strategy.
    ret_args: dict
        Keyword arguments for computation of factor-based returns.
    metric: str, {'cumulative_ret', 'sharpe_ratio', 'sortino_ratio', 'calmar_ratio', 'omega_ratio'},
            default sharpe_ratio
        Performance metric to compute.

    Returns
    -------
    df: pd.DataFrame
        Dataframe with parameter and metric values for all factor strategy parameter combinations.

    """
    if not isinstance(factor, pd.Series):
        raise TypeError("Factor must be a series for parameter grid search.")

    metrics = Parallel(n_jobs=8)(delayed(compute_metric)(factor, fwd_ret, factor_param, ret_param, metric)
                                 for factor_param in grid_parameters(factor_args) for ret_param in
                                 grid_parameters(ret_args))
    metrics = [i[0] for i in metrics]

    params = [(factor_param | ret_param) for factor_param in grid_parameters(factor_args) for ret_param in
              grid_parameters(ret_args)]
    df = pd.DataFrame(params, metrics).reset_index().rename(columns={'index': metric}).sort_values(by=metric,
                                                                                ascending=False)

    return df

def param_heatmap(
        param_df: pd.DataFrame,
        metric: str,
        fixed_params: Dict,
        plot_params: Dict
):
    """
    Creates a parameter heatmap for the performance metric across all combinantions/pairs of parameter values
    computed in the parameter grid search.

    Parameters
    ----------
    param_df: pd.DataFrame
        Dataframe with parameter and metric values for all factor strategy parameter combinations.
    metric: str
        Performance metric.
    fixed_params: dict
        Dictionary with parameters to keep fixed.
    plot_params: dict
        Dictionary with parameters to visualize.

    """
    # more than 3 params
    if param_df.shape[1] > 3:

        # fix params
        for param, val in fixed_params.items():
            param_df = param_df[getattr(param_df, param) == val]

    # compare params
    plot_params.append(metric)
    param_df = param_df[plot_params]

    # drop duplicates
    param_df = param_df[~ param_df.duplicated()]
    # create heatmap
    param_matrix = param_df.pivot(*tuple(plot_params))

    # plot heatmap
    plt.style.use('seaborn')
    plt.rcParams['font.family'] = 'serif'
    fig, ax = plt.subplots(figsize=(param_matrix.shape[0] * 5, param_matrix.shape[1] * 5))
    sns.set(font_scale=min(param_matrix.shape[0], param_matrix.shape[1]) / 3)
    # plot heatmap
    sns.heatmap(param_matrix, cmap="vlag_r", center=0, cbar=False, annot=True,
                annot_kws={"fontsize": min(param_matrix.shape[0], param_matrix.shape[1]) * 5}, square=True)

    # add systamental logo
    with resources.path("factorlab", "systamental_logo.png") as f:
        img_path = f
    img = Image.open(img_path)
    plt.figimage(img, origin='upper')

    # Adding title
    ax.set_title('Parameter Heatmap', loc='left', weight='bold', pad=20, fontsize=14, family='georgia')
    ax.text(x=0, y=-0.05, s=f"{metric.title()}", ha='left', fontsize=12, alpha=.8, fontdict=None, family='georgia')


import sqlite3
import genanki
import requests
from tkinter import ttk

lang_names = {'en': 'English'}

class MainFrame(ttk.Frame):
    def __init__(self, parent, *args, **kwargs):
        ttk.Frame.__init__(self, parent, *args, **kwargs)
        self.root = parent
        self.init_gui()

    def init_gui(self):
        """Builds GUI."""
        self.root.title('Kindle to Anki')

        self.grid(column=0, row=0, sticky='nsew')

        # Load vocabulary file

        ttk.Label(self, text='Vocabulary file').grid(column=0, row=0)

        self.db_entry = ttk.Entry(self, width=30)
        self.db_entry.grid(column=1, row = 0)

        self.loaddb_button = ttk.Button(self, text='Load',
                                      command=self.load_words)
        self.loaddb_button.grid(column=2, row=0)

        # Choose language

#        ttk.Label(self, text='Language').grid(column=0, row=1)
#        self.lang_entry = ttk.Combobox(self, width=15)
#        self.lang_entry.grid(column=1, row = 1)
#        self.lang_entry['values'] = ('en')
#        self.lang_entry.state(['readonly'])

        # Load from OED

        ttk.Label(self, text='App id').grid(column=0, row=2)
        self.appid_entry = ttk.Entry(self, width=30)
        self.appid_entry.grid(column=1, row = 2)

        ttk.Label(self, text='App key').grid(column=0, row=3)
        self.keyid_entry = ttk.Entry(self, width=30)
        self.keyid_entry.grid(column=1, row = 3)

        self.loadOED_button = ttk.Button(self, text='Load definitions from OED',
                                      command=self.load_OED)
        self.loadOED_button.grid(column=2, row=2, columnspan = 2, rowspan = 2)
        self.loadOED_button.state(['disabled'])

        # Create vocabulary file

        ttk.Label(self, text='Anki deck location:').grid(column=0, row=4)

        self.deck_entry = ttk.Entry(self, width=30)
        self.deck_entry.grid(column=1, row = 4)

        self.create_button = ttk.Button(self, text='Create Anki Deck',
                                      command=self.create_deck)
        self.create_button.grid(column=2, row=4)
        self.create_button.state(['disabled'])

        for child in self.winfo_children():
            child.grid_configure(padx=5, pady=5)

    def load_words(self):
        dbfile = self.db_entry.get()
        lang = 'en'
        self.words = load_words(dbfile, lang)
        if self.words.keys():
            self.loadOED_button.state(['!disabled'])
            self.create_button.state(['!disabled'])

    def load_OED(self):
        lang = 'en'
        app_id = self.appid_entry.get()
        app_key = self.keyid_entry.get()
        load_ODE(self.words, lang, app_id, app_key)

    def create_deck(self):
        deckfile = self.deck_entry.get()
        lang = 'en'
        create_deck(self.words, lang, deckfile)

def load_words(dbfile, lang):
    vocab = sqlite3.connect(dbfile)
    q = '''select WORDS.stem, LOOKUPS.usage, WORDS.timestamp from WORDS
        inner join LOOKUPS on WORDS.id=LOOKUPS.word_key
        where WORDS.lang=\'{}\''''.format(lang)
    cursor = vocab.execute(q)

    words = {}
    for w in cursor:
        stem = w[0]
        usage = w[1]
        timestamp = w[2]
        if stem not in words.keys():
            words[stem] = {'usage':usage}
    return words

def load_ODE(words, lang, app_id, app_key):
    headers = {'app_id': app_id, 'app_key': app_key}
    url = 'https://od-api.oxforddictionaries.com:443/api/v1/entries/'
    for w in words:
        stem = w.lower()
        r = requests.get(url  + lang + '/' + stem, headers=headers)
        entries = r.json()['results'][0]['lexicalEntries'][0]['entries']
        words[w]['definition'] = entries[0]['senses'][0]['definitions'][0]
    return words

def create_deck(words, lang, deckfile):
    name = "Kindle " + lang_names[lang] + " words"
    deck = genanki.Deck(2059400110, name)
    model = genanki.Model(
        1607392319,
        'Word',
        fields=[
            {'name': 'Question'},
            {'name': 'Answer'},
            {'name': 'Usage'}
            ],
        templates=[
            {
                'name': 'Card 1',
                'qfmt': '{{Question}}',
                'afmt': '{{FrontSide}}: {{Answer}}
{{Usage}}'
            }]
    )

    for w in words:
            note = genanki.Note(
                model=model,
                fields=[w, words[w]['definition'], words[w]['usage']]
                )
            deck.add_note(note)

    genanki.Package(deck).write_to_file(deckfile)

if __name__ == '__main__':
    root = tkinter.Tk()
    MainFrame(root)
    root.mainloop()


from backend.utils.database import Database

class LaptopTDG:

    owner = None

    @staticmethod
    def findAll():

        with Database() as cursor:
            query = """
                    SELECT * FROM laptop WHERE modelNumber NOT IN (SELECT modelNumber FROM deleteFlag);
                """

            try:
                cursor.execute(query)

                result = cursor.fetchall()
                return result
            except Exception as error:
                print(error)
                return None

    @staticmethod
    def find(modelNumber):

        with Database() as cursor:
            query = """
                    SELECT * FROM laptop WHERE modelNumber = '{}';
                """.format(modelNumber)

            try:
                cursor.execute(query)

                result = cursor.fetchone()
                return result
            except Exception as error:
                print(error)
                return None

    @staticmethod
    def insert(laptop):

        with Database() as cursor:
            query = """
                INSERT INTO laptop (modelNumber, quantity, name, weight, weightFormat, price, priceFormat, brandName,
                                    type, ramSize, ramFormat, processorType, numCores, hardDriveSize, hardDriveFormat,
                                    os, batteryInfo, dx, dy, dz, dimensionFormat, cameraInfo, size, sizeFormat)
                VALUES ('{modelNumber}', {quantity}, '{name}', {weight}, '{weightFormat}', {price}, '{priceFormat}',
                                    '{brandName}', 'laptop', {ramSize}, '{ramFormat}', '{processorType}', {numCores},
                                    {hardDriveSize}, '{hardDriveFormat}', '{os}', '{batteryInfo}', {dx}, {dy}, {dz},
                                    '{dimensionFormat}', '{cameraInfo}', {size}, '{sizeFormat}');
            """.format(**laptop)

            try:
                cursor.execute(query)
            except Exception as error:
                print(error)

    @staticmethod
    def update(laptop):

        with Database() as cursor:
            query = """
                UPDATE laptop SET
                quantity = {quantity},
                    name = '{name}',
                    weight = {weight},
                    weightFormat = '{weightFormat}',
                    price = {price},
                    priceFormat = '{priceFormat}',
                    brandName = '{brandName}',
                    type = 'laptop',
                    ramSize = '{ramSize}',
                    ramFormat = {ramFormat},
                    processorType = '{processorType}',
                    numCores = '{numCores}',
                    hardDriveSize = '{hardDriveSize}',
                    hardDriveFormat = '{hardDriveFormat}',
                    os ='{os}',
                    batteryInfo ='{batteryInfo}',
                    dx = '{dx}',
                    dy = '{dy}',
                    dz = '{dz}',
                    dimensionFormat = '{dimensionFormat}',
                    cameraInfo = '{cameraInfo}',
                    size = {size},
                    sizeFormat = '{sizeFormat}'
                    WHERE modelNumber = '{modelNumber}';
            """.format(**(laptop.__dict__))

            try:
                cursor.execute(query)

            except Exception as error:
                print(error)

    @staticmethod
    def delete(laptop):

        with Database() as cursor:
            query = """
                INSERT INTO deleteFlag (modelNumber, type)
                VALUES ('{modelNumber}', 'laptop');
            """

            try:
                cursor.execute(query)
            except Exception as error:
                print(error)

    @staticmethod
    def lock(uow):
        if LaptopTDG.owner is None:
            owner = uow
            return True
        else:
            return False

    @staticmethod
    def unlock(uow):
        if LaptopTDG.owner is uow:
            owner = None
            return True
        else:
            return False


from functools import reduce

print('###------ Homework 3 ------###')
print('Student: Tony Jubran 319115127')

# Question A.1
print('@----- 1.1')
def display_camel_temp(camel):
    """
     # this function will print the camel’s catalog
     name the camel's temperature in Celsius
    """
    print("Catalog name:",camel[0])
    print("Temperature:",camel[1],"C")
    return

# Question A.2
print('@----- 1.2')
def get_camel_temp_fahr(camel):
    """
    # this function will calculate temprefure of
     camel in Fahrenheit out of temprefure in celsius
    """
    fehr_tempre = camel[1] * (9 / 5) + 32
    cml_num = camel[0]
    number_of_clm = cml_num[4:]
    print("Camel number" , number_of_clm , "-" , camel[1] , "Celsius," , fehr_tempre , "Fahrenheit")
    return fehr_tempre

# Question A.3
print('@----- 1.3')
def camels_temp_fahr(camel_list):
    """
    :param camel_list:
    :return:
    """
    fehr_tempreture_list= list(map(get_camel_temp_fahr,camel_list))
    return fehr_tempreture_list

new_temps = camels_temp_fahr([['cml_1', 38.5], ['cml_2', 36.9], ['cml_3', 39.3], ['cml_4', 35.8]])

def add(a,b):
    return a + b

fehr_tempreture_sum = reduce(add ,new_temps)
print("Temperatures in Fahrenheit summed:" , fehr_tempreture_sum)

# Question B.1
print('@----- 2.1')

inserts = ["GGCTATATAGCGCGATGCTGATCGCGCGCGATGCTAGCTGCTCCGCGCGCGAAT"
    ,"TGAATAGAATTATATAGAATGACGCGCGATGAATCCGCTACGCGATAAGTCCGTAA"
    ,"ACCGCGCTATATAGCGTAAGCTGAATCGCCGCGCGTAAGCTGAATCGCTAGGGGCCGCC"
    ,"TGGTATATACGCGCGCGCCCGCGAATGCTGATCGCCTCGCGCGTAAGATGC"
    ,"CCGTGAATGCCTCGTATATACGCGCTGAATGCCTGCCGCGCGCGCGCGCGCG"]

# Question B.2
print('@----- 2.2')
def lets_find_G(str):
    return str.index("G")
G_indexes = list(map(lets_find_G,inserts))

# Question B.3
print('@----- 2.3')
def TATATA_remover(str):
    return str[str.index("TATATA")+len("TATATA"):]

trimmed_inserts = list(map(TATATA_remover,inserts))

# Question B.4
print('@----- 2.4')
def insert_to_vector(vector, insert):
    first_part = vector[:10]
    last_part = vector[10:]
    sequence = first_part.lower() + insert + last_part.lower()
    seq_len = len(sequence)
    return [sequence, seq_len]

def insert_to_vector_hellper(insert):
    return insert_to_vector(vector, insert)

# Question B.5
print('@----- 2.4')

vector = "CGTACAGCGATCGTACATGCGATCCACTCGGCTATCG"
full_vectors = list(map(insert_to_vector_hellper, inserts))

# Question C.1
print('@----- 3.1')
def seq_Tm(seq):

    A_count = seq.count("A")
    T_count = seq.count("T")
    C_count = seq.count("C")
    G_count = seq.count("G")

    if len(seq)<=13:
        return 2 * (A_count + T_count) + 4 * (C_count + G_count)
    else:
        return (64.9 + ((41 * (G_count + C_count -16.4))/(A_count +T_count +G_count + C_count )))

# Question C.2
print('@----- 3.2')
def  add_with_TACTAC(first, second):

    return first + "TACTAC" + second

def concat_strings_w_TACTAC(seq_list):

    conncted_seq = reduce(add_with_TACTAC,seq_list)

    print(conncted_seq)
    return conncted_seq

# Question C.3
print('@----- 3.3')

part_C3_sequence = [['TTTTTCCCC', 'AAAAA'],
['ATCGGG', 'GACGATCGC', 'CGATCGTGTA', 'CACGTC'],
['CATACCGTCT', 'CGTCTCTAC', 'AACCGCAT'],
['GCATCGATCG', 'AGCTC', 'CCGCTAA', 'GAGC', 'GTAGGAG']]

dna_special_list = list(map(concat_strings_w_TACTAC, part_C3_sequence))
print(dna_special_list)

"""
 i wrote the print with another line just to be sure i have the variable  that
 iclude the special list, but i can write it all with one line too ( including the print )
print( list(map(concat_strings_w_TACTAC, part_C3_sequence)) )
 but i wont have the special list variable
 """

# Question C.4
print('@----- 3.4')
def add(a,b):
    """ return sum of a and b"""
    return a+b

def melt_temp_for_list(dna_list, sum_or_mean):
    Tm_sum = reduce(add, list(map( seq_Tm , dna_list )))
    """ first i want to calculate the sum of all Tm tempretures, so i map seq_Tm fun on all dna list
    and then add them all using add function and reduce"""
    if sum_or_mean == "sum": # if sum_or_mean equal to "sum" return the sum of the tempretures
        return Tm_sum
    return Tm_sum/len(dna_list) # if sum_or_mean is not equal to "sum" then return mean tempreture

# Question C.5
print('@----- 3.5')

dna_special_Tm_sum = melt_temp_for_list(dna_special_list, "sum")
dna_special_Tm_mean = melt_temp_for_list(dna_special_list, "mean")

# Question *Bonus

print('@----- *Bonus')

def lets_multiply(number, n, multiplication):
    if n==1:
        return multiplication * number
    return lets_multiply(int(number / 10) , n-1 , multiplication * ( number % 10 ))

def lets_add(number, n, sum):
    if n==1:
        return sum + number
    return lets_add(int(number / 10) , n-1 , sum + ( number % 10 ))

def calc_digits(number, n, operation):
    if operation == "add":
        return lets_multiply(number, n , 1)

    elif operation == "multiply":
        return lets_add(number, n, 0)

    else:
        print("calc_digits got an unknown operation")
        return


import os, sys, random
import torch
import cv2
import numpy as np
import argparse
from torch._C import device

from torchvision.transforms.transforms import Resize
from dcgan import *
import torch
import torch.optim as optim
import torch.utils.data
import torchvision
import torchvision.datasets as dset
import torchvision.transforms as transforms
import torchvision.utils as vutils
from tqdm import tqdm

REPEAT = 0
REPEAT_D = 3

device_ = torch.device('cuda:0')
def train():
    modelG = Generator()
    modelD = Discriminator()
    modelG = modelG.to(device_)
    modelG.apply(weights_init)
    modelD = modelD.to(device_)
    modelD.apply(weights_init)
    criterion = nn.BCELoss()
    fixed_noise = torch.randn(64, NZ, 1, 1, device=device_)
    optG = optim.Adam(modelG.parameters(), lr=1e-4)
    optD = optim.Adam(modelD.parameters(), lr=1e-4)

    dataset = dset.ImageFolder(
        root='./minidata',
        transform=transforms.Compose([
            transforms.CenterCrop(178),
            transforms.Resize(64),
            transforms.ToTensor(),
            transforms.Normalize((0.5, 0.5, 0.5), (0.5, 0.5, 0.5))
        ])
    )

    dataloader = torch.utils.data.DataLoader(dataset, batch_size=64, shuffle=True)
    f = open('records_4v1.txt', 'a', encoding='utf8')
    f.write('-------------------------\n')
    noise_norm = 0.0
    def make_noise(batch, norm):
        noise = torch.randn(batch, 3, 64, 64).cuda()
        noise.requires_grad = False
        return noise * norm

    assert(REPEAT == 0 or REPEAT_D == 0)
    for epoch in tqdm(range(100)):
        modelD.train()
        modelG.train()
        Dloss = 0.0
        Gloss = 0.0
        for i, data in tqdm(enumerate(dataloader)):
            data = data[0].to(device_)
            modelD.zero_grad()
            logits = modelD(data + make_noise(data.shape[0], noise_norm)).view(-1)
            labels = torch.ones_like(logits)
            loss = criterion(logits, labels)
            loss.backward()
            Dloss += loss.mean().item()

            Z = torch.randn(data.shape[0], NZ, 1, 1).to(device_)
            GZ = modelG(Z)
            logits = modelD(GZ.detach() + make_noise(data.shape[0], noise_norm)).view(-1)
            labels = torch.zeros_like(logits)
            loss = criterion(logits, labels)
            loss.backward()
            Dloss += loss.mean().item()
            optD.step()

            if REPEAT > 0:
                for repeat in range(REPEAT):
                    Z = torch.randn(data.shape[0], NZ, 1, 1).to(device_)
                    Z.requires_grad = False
                    GZ = modelG(Z)
                    modelG.zero_grad()
                    logits = modelD(GZ + make_noise(data.shape[0], noise_norm)).view(-1)
                    labels = torch.ones_like(logits)
                    loss = criterion(logits, labels)
                    loss.backward()
                    Gloss += loss.mean().item()
                    optG.step()

            else:
                if (REPEAT_D == 0) or ((i + 1) % REPEAT_D == 0):
                    modelG.zero_grad()
                    logits = modelD(GZ + make_noise(data.shape[0], noise_norm)).view(-1)
                    labels = torch.ones_like(logits)
                    loss = criterion(logits, labels)
                    loss.backward()
                    Gloss += loss.mean().item()
                    optG.step()

            if (i + 1) % 100 == 0:
                # print(Dloss / (i + 1), Gloss / (i + 1))
                print(Dloss / 100, Gloss / (100 * (1 + REPEAT)))
                f.write('{} {}\n'.format(Dloss / 100, Gloss / (100 * (1 + REPEAT))))
                Dloss = 0.0
                Gloss = 0.0
        noise_norm = noise_norm * 0.8
        modelG.eval()
        with torch.no_grad():
            Gfixed = modelG(fixed_noise)
            vutils.save_image(Gfixed / 2.0 + 0.5, './generated2/generated_4v1_{}.jpg'.format(epoch), nrow=8, normalize=True)

        if (epoch + 1) % 10 == 0:
            to_save = {'D': modelD.state_dict(), 'G': modelG.state_dict()}
            torch.save(to_save, './model/4v1_model_saved_epoch{}.pth'.format(epoch + 1))

    f.close()
def main():
    manual_seed = 777
    random.seed(manual_seed)
    train()

if __name__ == '__main__':
    main()


"""
This application runs in the console.
The result of its operation is information whether the user has drawn winning numbers in LOTTO.
"""

import random

rnd = sorted(random.sample(range(1, 50), 6))
entered_numbers = []
i = 1

while i < 7:

    try:
        your_number = int(input(f"Enter your {i} number:"))
        print(your_number)
    except ValueError:
        print("It's not a number!")
        continue

    if 1 <= your_number <= 49:
        if your_number in entered_numbers:
            print("You've already given this number. Name another one.")
            continue
        else:
            entered_numbers.append(your_number)
            i += 1
    else:
        print("Number outside the range 1 to 49. Enter another number.")
        continue

print(f"Your drawn numbers: {sorted(entered_numbers)}")
print(f"Lotto numbers: {rnd}")
matched_numbers = [number for number in entered_numbers if number in rnd]

if len(matched_numbers) >= 3:
    print(f"Congratulations! You matched {len(matched_numbers)} numbers")
else:
    print(f"Bardzo się starałeś lecz z gry wyleciałeś :(. Unfortunately, no win. You only matched {len(matched_numbers)} numbers.")


def move(cups):
    """Given cups (current first), make one move. Return the new cup order."""
    destination = cups[0] - 1 if cups[0] > 1 else 9
    while destination in cups[1:4]:
        destination -= 1 if destination > 1 else -8
    i = cups.index(destination)
    return cups[4:i] + [cups[i]] + cups[1:4] + cups[i+1:] + [cups[0]]

def play(cups, moves=100):
    """Play one game. Return the labels on the cups after cup 1."""
    cups = [int(c) for c in cups]
    for _ in range(moves):
        cups = move(cups)
    i = cups.index(1)
    return ''.join(str(n) for n in cups[i+1:] + cups[:i])

if __name__ == '__main__':
    print(play('792845136'))


import ctypes
from MLP_cuda import MLP, shuffle_and_split_data, forward_layer, sigmoid

import sklearn.datasets
import numpy as np

# INIT data
np.random.seed(1)
X, y = sklearn.datasets.make_moons(n_samples=300, noise=0.20)  # We create a dataset with 300 elements

X_train, y_train, X_test, y_test = shuffle_and_split_data(X, y, 0.8)

# Load the shared library
mylibrary = ctypes.CDLL('./library.so')

# Define the function signature
mylibrary.sigmoid_of_matrix.argtypes = [ctypes.POINTER(ctypes.c_float), ctypes.c_int, ctypes.c_int]
mylibrary.sigmoid_of_matrix.restype = ctypes.POINTER(ctypes.c_float)  # The function doesn't return anything directly

def cuda_sigmoid(matrix):
    # Flatten the matrix to a 1D array
    flattened_matrix = matrix.flatten().astype(np.float32)

    # Get a pointer to the flattened data
    matrix_ptr = flattened_matrix.ctypes.data_as(ctypes.POINTER(ctypes.c_float))

    # Call the CUDA function
    result_matrix_ptr = mylibrary.sigmoid_of_matrix(matrix_ptr, len(matrix), len(matrix[0]))

    # Convert the result pointer to a NumPy array
    result_matrix = np.fromiter(result_matrix_ptr, dtype=np.float32, count=len(matrix) * len(matrix[0]))

    # Reshape the flattened result back to a matrix
    result_matrix = np.reshape(result_matrix, matrix.shape)

    return result_matrix

d_input=2
d_hidden=3
d_output=2

np.random.seed(0)

W1 = np.random.rand(d_input, d_hidden).astype(np.float32)-0.5
b1 = np.random.rand(d_hidden).astype(np.float32)-0.5

#z1 = forward_layer(X_train, W1, b1) # Output of the first layer

a1 = sigmoid(W1) # Sigmoid activation of the first layer
a1_cuda = cuda_sigmoid(W1) # Sigmoid activation of the first layer

print("equal ? \n", a1==a1_cuda)
print("sum equal ? \n", np.sum(a1), " =?", np.sum(a1_cuda))

print("W1 :\n", W1)

print("\na1 :\n", a1)
print("\n a1_cuda :\n", a1_cuda)


import time
import numpy as np
import matplotlib.pyplot as plt
from riglib.experiment import traits
import scipy.io as sio

#remember to change "plexnet_softserver_oldfiles" back to "plexnet" in LFP.__init__
channels = [1, 2, 5, 9, 10, 33, 191, 192, 250, 256]
chan_offset = 512

# # remember to change "plexnet" to "plexnet_softserver_oldfiles" in LFP.__init__
# channels = [66, 67, 68, 91, 151, 191, 192]
# chan_offset = 0

class PlexonLFPData(traits.HasTraits):
    '''Stream neural LFP data from the Plexon system'''

    def init(self):
        from riglib import plexon, source
        print(channels)
        self.neurondata = source.MultiChanDataSource(plexon.LFP, channels=channels, chan_offset=chan_offset)
        try:
            super(PlexonLFPData, self).init()
        except:
            print("PlexonLFPData: running without a task")

    def run(self):
        self.neurondata.start()

if __name__ == '__main__':

    self = PlexonLFPData()
    self.init()
    self.run()

    n_secs = 15
    update_rate = 1./60
    N = int(n_secs / update_rate)

    samp_freq = 1000
    n_samp = N * update_rate * samp_freq  # approx number of samples we'll collect per channel

    n_chan = len(channels)
    data = np.zeros((n_chan, 2*n_samp))
    idxs = np.zeros(n_chan)

    print('discarding initial data...', end=' ')
    t_start = time.time()
    while time.time() - t_start < 5:
        # get new_data but don't do anything with it
        new_data = self.neurondata.get_new(channels=channels)
        time.sleep(0.005)
    print('done.')

    for k in range(N):
        t_start = time.time()

        new_data = self.neurondata.get_new(channels=channels)
        print(new_data[0].shape)

        for row in range(n_chan):
            d = new_data[row]
            idx = idxs[row]
            data[row, idx:idx+len(d)] = d
            idxs[row] += len(d)

        t_elapsed = time.time() - t_start
        # print t_elapsed
        time.sleep(update_rate - t_elapsed)

    self.neurondata.stop()

    save_dict = dict()
    save_dict['data'] = data
    save_dict['channels'] = channels
    # save_dict['n_garbage'] = n_garbage

    print('saving data...', end=' ')
    sio.matlab.savemat('lfp_data_0222_8pm_1.mat', save_dict)
    print('done.')

    print(data)
    print(idxs)