hexsha stringlengths 40 40 | size int64 7 1.04M | ext stringclasses 10 values | lang stringclasses 1 value | max_stars_repo_path stringlengths 4 247 | max_stars_repo_name stringlengths 4 125 | max_stars_repo_head_hexsha stringlengths 40 78 | max_stars_repo_licenses listlengths 1 10 | max_stars_count int64 1 368k ⌀ | max_stars_repo_stars_event_min_datetime stringlengths 24 24 ⌀ | max_stars_repo_stars_event_max_datetime stringlengths 24 24 ⌀ | max_issues_repo_path stringlengths 4 247 | max_issues_repo_name stringlengths 4 125 | max_issues_repo_head_hexsha stringlengths 40 78 | max_issues_repo_licenses listlengths 1 10 | max_issues_count int64 1 116k ⌀ | max_issues_repo_issues_event_min_datetime stringlengths 24 24 ⌀ | max_issues_repo_issues_event_max_datetime stringlengths 24 24 ⌀ | max_forks_repo_path stringlengths 4 247 | max_forks_repo_name stringlengths 4 125 | max_forks_repo_head_hexsha stringlengths 40 78 | max_forks_repo_licenses listlengths 1 10 | max_forks_count int64 1 105k ⌀ | max_forks_repo_forks_event_min_datetime stringlengths 24 24 ⌀ | max_forks_repo_forks_event_max_datetime stringlengths 24 24 ⌀ | content stringlengths 1 1.04M | avg_line_length float64 1.77 618k | max_line_length int64 1 1.02M | alphanum_fraction float64 0 1 | original_content stringlengths 7 1.04M | filtered:remove_function_no_docstring int64 -102 942k | filtered:remove_class_no_docstring int64 -354 977k | filtered:remove_delete_markers int64 0 60.1k |
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
50130c0336ac4ecad32bf1cfe47a0d7871688d46 | 28,590 | py | Python | sequential_tracing/source/source/library_tools/LibraryTools.py | ZhuangLab/Chromatin_Analysis_2020_cell | ecc0d3e92e8b9cb0dcf970c29440f91404055da6 | [
"MIT"
] | 19 | 2020-08-20T15:05:10.000Z | 2021-08-17T19:31:07.000Z | sequential_tracing/source/source/library_tools/LibraryTools.py | zhengpuas47/Chromatin_Tracing_Analysis | 850f6e068798408662aa40d20719e038a20176be | [
"MIT"
] | 1 | 2020-12-07T12:48:49.000Z | 2020-12-17T06:45:57.000Z | sequential_tracing/source/library_tools/LibraryTools.py | ZhuangLab/Chromatin_Analysis_2020_cell | ecc0d3e92e8b9cb0dcf970c29440f91404055da6 | [
"MIT"
] | 4 | 2020-08-21T07:39:25.000Z | 2021-03-10T08:10:43.000Z | import numpy as np
import os
import pickle
def seqrc(string):
"returns the reverse complement of a sequence"
dic_rc = constant_key_dict({'a':'t','c':'g','g':'c','t':'a','A':'T','C':'G','G':'C','T':'A'})
string_rc = "".join([dic_rc[c] for c in string][::-1])
return string_rc
def getFastaWeb(chrom,pos1,pos2):
"For mouse genome this impots from the infojax website the chr:pos1:pos2 genomic sequence"
import urllib.request, urllib.error, urllib.parse
site_name = "http://www.informatics.jax.org/seqfetch/tofasta.cgi?seq1=mousegenome%21%21"+str(chrom)+"%21"+str(pos1)+"%21"+str(pos2)+"%21%21&flank1=0"
html = str(urllib.request.urlopen(site_name).read())
sequence = "".join(html.split("\n")[1:-1])
return sequence
def getGeneWeb(gene_id):
"For mouse genome this impots from the infojax website a given gene its genomic sequence"
import urllib.request, urllib.error, urllib.parse
site_name = "http://useast.ensembl.org/Mus_musculus/Export/Output/Gene?db=core;flank3_display=0;flank5_display=0;g="+gene_id+";output=fasta;strand=feature;genomic=unmasked;_format=Text"
html = str(urllib.request.urlopen(site_name).read())
sequence = "".join(html.split("\r\n")[2:-1])
return sequence
class OTTable (dict):
""" run this as:
specTable = OTTable()
specTableMAP = specTable.computeOTTable(gen_seq,block)
specTable.Save(filename)
OR:
specTable = OTTable()
specTable.Load(filename)
specTableMAP = specTable.Map()
"""
def compute_pair_probes(gene_names,gene_seqs,folder_save="",blk=17,pb_len=30,map_rep=None,map_noGenes=None,maps_Genes=None,FPKM_cuttoff1=2,FPKM_cuttoff2=10,min_gc=0.30,max_gc=0.70,gene_cutoff1=3,gene_cutoff2=5):
"""This is intended to return to you pairs of probes for bTree
Require paramaters:
@gene_names : a list of names for the genes you require probes.
@gene_seqs : a list of sequences (A,C,G,T,N) for the genes you require probes. For exon junctions or masking use N.
@blk : word size of the maps
@pb_len : desired probe length
@map_noGenes : if dictionary: the OT map of FPKM excluding the genes interested in.
It is not necessary to exclude the genes or to use FPKM vs just sequences, but then use the cutoffs appropriately.
if None: ignore this test
if string: the path of a fasta file and compute the map on the spot using blk word size
@maps_Genes : if dictionary: the Index map for the gese interested in.
if None: ignore this test
if string: the path of a fasta file and compute the map on the spot using blk word size
@map_rep : if dictionary: the OT maps of higly abundant genes. No crosstalk with these genes will be accepted
if None: ignore this test
if string: the path of a fasta file and compute the map on the spot using blk word size
@FPKM_cuttoff1/FPKM_cuttoff2 : min/max cut for the map_noGenes
@gene_cutoff1/gene_cutoff2 : min/max cut for the maps_Genes
@pb_len : probe length
@min_gc/max_gc
Returns:
@pb_names_f : names of the probe in the form "<gene name>_pb:<location>_pb-pair:[<pair index>, <index in pair>]"
@pb_seqs_f : sequences of the probes
"""
### Check for variable pop:
if type(map_noGenes)==str:
print("Computing the map for transcriptome! Please wait!")
names_,seqs_ = fastaread(map_noGenes)
#construct specificity table (dictionary) for all the sequences of the transcripts in MOE.
specTable = OTTable()
print("Warning: FPKM might not be computed correctly!")
FPKM_ = [float(nm.split('_')[-3]) for nm in names_] #change this for generic FPKM
map_noGenes = specTable.computeOTTable(seqs_,blk,FPKM=FPKM_)
if type(maps_Genes)==str:
print("Computing the maps for genes!")
names_,seqs_ = fastaread(maps_Genes)
maps_Genes = computeIndexTable(seqs_,blk)
if type(map_rep)==str:
print("Computing the map for repetitive RNA!")
names_,seqs_ = fastaread(map_rep)
specTable = OTTable()
map_rep = specTable.computeOTTable(seqs_,blk)
###Construct the probe scoring function
pb_names_f,pb_seqs_f=[],[]
num_pairs_f = []
###Iterate through genes:
for current_gene in range(len(gene_seqs)):
gene_seq = gene_seqs[current_gene]
gene_name = gene_names[current_gene]
locations_recorded = []
location,pair_ind,pb_pair_ind=0,0,0
pb_names,pb_seqs=[],[]
num_pairs = 0
while True:
pb1,pb2 = gene_seq[location:location+pb_len],gene_seq[location+pb_len:location+2*pb_len]
#check where this probe is already in the set
pb1_verified = False
if locations_recorded.count(location): pb1_verified = True
noNs = pb1.count('N') + pb2.count('N') == 0
if noNs:
seq_cut = gc(pb1)>=min_gc and gc(pb2)>=min_gc and gc(pb1)<=max_gc and gc(pb2)<=max_gc
if seq_cut:
if map_rep is not None:
#Deal with cross-reactivity
#--To very abundant mRNA
score_rep1 = map_seq(pb1,map_rep,blk)
score_rep2 = map_seq(pb2,map_rep,blk)
rep_cut = score_rep1==0 and score_rep2==0
else:
rep_cut=True
if rep_cut:
if map_noGenes is not None:
#--To all RNA's except the olfrs (using FPKMcuttoff)
score_RNA1 = map_seq(pb1,map_noGenes,blk)
score_RNA2 = map_seq(pb2,map_noGenes,blk)
RNA_cut = min(score_RNA1,score_RNA2)<min(FPKM_cuttoff1,FPKM_cuttoff2) and max(score_RNA1,score_RNA2)<max(FPKM_cuttoff1,FPKM_cuttoff2)
else:
RNA_cut=True
if RNA_cut:
if maps_Genes is not None:
#--To all olfrs
#--To all olfrs
scores_Gene1 = map_seq(pb1,maps_Genes,blk)
scores_Gene1.pop(np.argmax([sc[1] for sc in scores_Gene1])) # pop the maximum
scores_Gene2 = map_seq(pb2,maps_Genes,blk)
scores_Gene2.pop(np.argmax([sc[1] for sc in scores_Gene2])) # pop the maximum
geneIdx_offGene1 = [score[0] for score in scores_Gene1 if score[1]>gene_cutoff1]
geneIdx_offGene2 = [score[0] for score in scores_Gene2 if score[1]>gene_cutoff2]
geneIdx_offGene1_ = [score[0] for score in scores_Gene2 if score[1]>gene_cutoff1]
geneIdx_offGene2_ = [score[0] for score in scores_Gene1 if score[1]>gene_cutoff2]
gene_int = min(len(np.intersect1d(geneIdx_offGene1,geneIdx_offGene2)),len(np.intersect1d(geneIdx_offGene1_,geneIdx_offGene2_)))
else:
gene_int=0
if gene_int==0:
# record poisitions:
## create name:
if pb1_verified:
pb_pair_ind+=1
pb_name = gene_name+"_pb:"+str(location+pb_len)+'_pb-pair:'+str([pair_ind,pb_pair_ind])
pb_names.append(pb_name)
pb_seqs.append(pb2)
locations_recorded.append(location+pb_len)
num_pairs+=1
else:
pair_ind+=1
pb_pair_ind=1
pb_name = gene_name+"_pb:"+str(location)+'_pb-pair:'+str([pair_ind,pb_pair_ind])
pb_names.append(pb_name)
pb_seqs.append(pb1)
locations_recorded.append(location)
pb_pair_ind+=1
pb_name = gene_name+"_pb:"+str(location+pb_len)+'_pb-pair:'+str([pair_ind,pb_pair_ind])
pb_names.append(pb_name)
pb_seqs.append(pb2)
locations_recorded.append(location+pb_len)
num_pairs+=1
gene_seq = gene_seq[:location]+"".join(['N' for k in range(pb_len)])+gene_seq[location+pb_len:]
location+=1
if location+2*pb_len>len(gene_seq):
break
print(gene_name+" (pairs: "+str(num_pairs)+") done!")
fastawrite(folder_save+os.sep+gene_name+'_probes.fasta',pb_names,pb_seqs)
pb_names_f.append(pb_names)
pb_seqs_f.append(pb_seqs)
num_pairs_f+=[num_pairs]
return pb_names_f,pb_seqs_f,num_pairs_f
def file_to_mat(file_,sep_str=',',d_type=None,skip_first=False):
"""
Converts .csv files to a list of its entries
Inputs:
file_ - the location of a .csv file
sep_str - the separator between data points
d_type - the datatype in the file
skip_first - an option to skip the first component (e.g. if there's a menu)
Returns:
lines - a list of the lines in the file, each of which itself a list of all entries in the line
"""
lines = [ln for ln in open(file_,'r')]
start_=(1 if skip_first==True else 0) #skip first line if option selected
lines = [refine_line(ln,d_type,skip_first) for ln in lines[start_:]]
return lines
def map_gene(pairs_nms_,pairs_sqs_,code,tails,pair_limit_per_bit=10):
""" Use as:
map_gene([['name_pb-pair:[1,1]','name_pb-pair:[1,2]','name_pb-pair:[1,3]'],['name_pb-pair:[2,1]','name_pb-pair:[2,2]']],
[['sq1','sq2','sq3'],['sq4','sq5']],[0,1,2],
['0000','1111','2222','3333','4444','5555'],pair_limit_per_bit=10)
"""
nms_gene,sqs_gene = [],[]
cts_icode = [0 for i in range(len(code))]
cts_vcode = [0 for i in range(len(code))]
for nms_,sqs_ in zip(pairs_nms_,pairs_sqs_):
nms_new,sqs_new = map_pair(nms_,sqs_,code,cts_icode,cts_vcode,tails,pair_limit_per_bit)
nms_gene.extend(nms_new)
sqs_gene.extend(sqs_new)
if min(cts_vcode)>=pair_limit_per_bit: break
return nms_gene,sqs_gene
| 43.782542 | 216 | 0.591815 | import numpy as np
import os
import pickle
class constant_key_dict (dict):
def __missing__ (self, key):
return key
def seqrc(string):
"returns the reverse complement of a sequence"
dic_rc = constant_key_dict({'a':'t','c':'g','g':'c','t':'a','A':'T','C':'G','G':'C','T':'A'})
string_rc = "".join([dic_rc[c] for c in string][::-1])
return string_rc
def getFastaWeb(chrom,pos1,pos2):
"For mouse genome this impots from the infojax website the chr:pos1:pos2 genomic sequence"
import urllib.request, urllib.error, urllib.parse
site_name = "http://www.informatics.jax.org/seqfetch/tofasta.cgi?seq1=mousegenome%21%21"+str(chrom)+"%21"+str(pos1)+"%21"+str(pos2)+"%21%21&flank1=0"
html = str(urllib.request.urlopen(site_name).read())
sequence = "".join(html.split("\n")[1:-1])
return sequence
def getGeneWeb(gene_id):
"For mouse genome this impots from the infojax website a given gene its genomic sequence"
import urllib.request, urllib.error, urllib.parse
site_name = "http://useast.ensembl.org/Mus_musculus/Export/Output/Gene?db=core;flank3_display=0;flank5_display=0;g="+gene_id+";output=fasta;strand=feature;genomic=unmasked;_format=Text"
html = str(urllib.request.urlopen(site_name).read())
sequence = "".join(html.split("\r\n")[2:-1])
return sequence
def split_pieces(save_fl,coords,gen_seq,name_seq,piece_length=int(10E3)):
num_pieces = round(len(gen_seq)/piece_length)
gen_seqs = []
names_seqs = []
for i in range(int(num_pieces)):
start = i*piece_length
end = min((i+1)*piece_length,len(gen_seq))
gen_seqs.append(gen_seq[start:end])
names_seqs.append("chr"+str(coords[0])+":"+str(int(coords[1])+start)+"-"+str(int(coords[1])+end)+" region="+name_seq+"_pt_"+str(i))
fastawrite(save_fl,names_seqs,gen_seqs)
return names_seqs,gen_seqs
def fastawrite(file_name,names,seqs,append=False):
if append:
print("do something")
f=open(file_name,'w')
for i in range(len(names)):
name = names[i]
seq = seqs[i]
f.write('>'+name+'\n'+seq+'\n')
f.close()
def deal_with_masks0(seq_test,masks = ["GGGGGG","CCCC","TTTTTT","AAAA"],dicRepMask = {"G":"C","C":"G","A":"T","T":"A","g":"c","c":"g","a":"t","t":"a"}):
dicMask = {mask[0]:len(mask) for mask in masks}
seq_t=seq_test.upper()
contigs=[]
prev_let="N"
count=1
for i_let in range(len(seq_t)):
let = seq_t[i_let]
if prev_let==let:
count+=1
else:
contigs.append([prev_let,i_let,count])
prev_let=let
count=1
contigs.append([prev_let,i_let,count])
contigs = contigs[1:]
contig_danger = [contig for contig in contigs if dicMask[contig[0]]<=contig[-1]]
replace_indx = [0]
replace_indx.extend([item for sublist in [list(range(contig[1]-contig[2],contig[1]))[dicMask[contig[0]]/2::dicMask[contig[0]]] for contig in contig_danger] for item in sublist])
replace_indx.append(len(seq_t))
seqs_split = [dicRepMask[seq_test[replace_indx[i]]]+seq_test[replace_indx[i]+1:replace_indx[i+1]] for i in range(len(replace_indx)-1)]
seq_final = seq_test[0]+"".join(seqs_split)[1:]
return seq_final,len(replace_indx)-2
def deal_with_masks(seq_test,masks = ["GGGGGG","CCCC","TTTTTT","AAAA"],dicRepMask = {"G":"C","C":"G","A":"T","T":"A","g":"c","c":"g","a":"t","t":"a"}):
lenrep_t=0
seq_final_,lenrep = deal_with_masks0(seq_test,masks=masks,dicRepMask=dicRepMask)
lenrep_t+=lenrep
while(sum([seq_final_.upper().count(mask) for mask in masks])>0):
seq_final_,lenrep = deal_with_masks0(seq_final_,masks=masks,dicRepMask=dicRepMask)
lenrep_t+=lenrep
return seq_final_,lenrep_t
def up_down_split(seq):
splits = ['']
c0 = seq[0]
for c in seq:
if c.islower()==c0.islower():
splits[-1]+=c
else:
c0 = c
splits.append(c)
return splits
def up_down(seqs):
count=0
seqs_ = []
for seq in seqs:
count+=1
if np.mod(count,2):
seqs_.append(seq.upper())
else:
seqs_.append(seq.lower())
return "".join(seqs_)
def fastaread(fl,force_upper=False):
fid = open(fl,'r')
names = []
seqs = []
lines = []
while True:
line = fid.readline()
if not line:
seq = "".join(lines)
if force_upper:
seq=seq.upper()
seqs.append(seq)
break
if line[0]=='>':
name = line[1:-1]
names.append(name)
seq = "".join(lines)
if force_upper:
seq=seq.upper()
seqs.append(seq)
lines = []
else:
lines.append(line[:-1])
fid.close()
return [names,seqs[1:]]
def nt2intblock(gen_seq):
int_gen_seq = nt2int(gen_seq)
block = len(gen_seq)
base = 5**np.arange(block,dtype="int64")
hit = np.dot(base,int_gen_seq)
return hit
def nt2intblock_rc(gen_seq):
int_gen_seq = nt2int(gen_seq)
int_gen_seq = 4-int_gen_seq[::-1]
block = len(gen_seq)
base = 5**np.arange(block,dtype="int64")
hit = np.dot(base,int_gen_seq)
return hit
def nt2int(gen_seq):
nt2int_dic=constant_minus_one_dict({'a':0,'c':1,'g':2,'t':3,'A':0,'C':1,'G':2,'T':3})
int_gen_seq = [nt2int_dic[ch] for ch in gen_seq]
int_gen_seq = np.array(int_gen_seq)+1
return int_gen_seq
def single_report(pb_t,maps,block):
pb_t_counts = np.zeros(len(maps))
for j in range(len(pb_t)-block+1):
blk_t = pb_t[j:j+block]
##Deal with maps:
blk_t_counts = np.array([OTTableMap[blk_t] for OTTableMap in maps])
pb_t_counts+=blk_t_counts
return pb_t_counts
def fastacombine(files_,new_file = None):
#This combines multiple fasta files and returns names,seqs
names_f,seqs_f = [],[]
for file_ in files_:
names_,seqs_ = fastaread(file_)
names_f.extend(names_)
seqs_f.extend(seqs_)
if new_file!=None:
fastawrite(new_file,names_f,seqs_f)
return names_f,seqs_f
def pad_seqs(seqs_,max_len=None,pad=None):
#The pad comes from the last 10 orthogonal primers in my old list
if pad is None:
pad = 'CACGGGCCGGATTGGTTGAGATGGCGACGGGTCACTTGCCCGATGAAGCGCCTGTTTGCGTACGGGTCATCGCCCTTGGCTTCGTGCCTCTTGGGTTGGGTGCCCGTTCCCGATCTTGTCATCGGGTCGCCGCGATTTAGTATGCATTGGCCGCGTTTCCTTCGGAGGCGTCACGTTTCGTGACACGCGACCGACTTTGG'
#pad="".join(primers_all[-((max_len-min_len)/20+1):])
if max_len is None:
max_len = max(list(map(len,seqs_)))
seqs_pad = []
for seq in seqs_:
padlen = max_len-len(seq)
pad_left = min(5,padlen)
pad_right = padlen-pad_left
if seq[0].islower():
padL = pad[:pad_left].upper()
else:
padL = pad[:pad_left].lower()
if seq[-1].islower():
padR = pad[-pad_right:].upper()
else:
padR = pad[-pad_right:].lower()
if pad_right==0:
padR=""
seqs_pad.append(padL+seq+padR)
return seqs_pad
def combine_lib(files_,deal_mask=False,masks = ["GGGGGG","CCCC","TTTTTT","AAAA"]):
print("Combining library")
names_,seqs_=[],[]
for file_ in files_:
names_t,seqs_t = fastaread(file_)
names_.extend(names_t)
seqs_.extend(seqs_t)
primersA = [seq[:20] for seq in seqs_]
primersB = [seq[-20:] for seq in seqs_]
max_len = max([len(seq) for seq in seqs_])
min_len = min([len(seq) for seq in seqs_])
seqs_pad = pad_seqs(seqs_,max_len)
if deal_mask:
print("Dealing with masks")
seqs_mask=[deal_with_masks(seq,masks=masks) for seq in seqs_pad]
seqs_f = [seq[0] for seq in seqs_mask]
changes = [seq[1] for seq in seqs_mask]
print("Changes:"+str(np.unique(changes,return_counts=True)))
#Rough test mispriming
print("Performing rough test for mispriming")
maps_seqs_12 = [computeOTTable(seq,12) for seq in seqs_f]
maps_seqs_19 = [computeOTTable(seq,19) for seq in seqs_f]
primersAB = ["".join(zipAB) for zipAB in zip(primersA,primersB)]
primersAB_unq,primersA_inv = np.unique(primersAB,return_inverse=True)
primersA_unq = np.array([prm[:20] for prm in primersAB_unq])
primersB_unq = np.array([prm[-20:] for prm in primersAB_unq])
mis_primed,mis_useA,mis_useB = [],[],[]
for index_prm in range(len(primersA_unq)):
primer_tA = primersA_unq[index_prm]
primer_tB = primersB_unq[index_prm]
vals0=np.zeros(len(seqs_f))
vals0[primersA_inv==index_prm]=len(primer_tA)-12
mis_primed.append(np.sum(((single_report(primer_tA,maps_seqs_12,12)-vals0)>0)&((single_report(primer_tB,maps_seqs_12,12)-vals0)>0)))
vals0=np.zeros(len(seqs_f))
vals0[primersA_inv==index_prm]=len(primer_tA)-19
mis_useA.append(np.sum((single_report(primer_tA,maps_seqs_19,19)-vals0)>0))
mis_useB.append(np.sum((single_report(primer_tB,maps_seqs_19,19)-vals0)>0))
print("[Mis-primed(12bp both fwd and rev),Mis-used_A,Mis-used_B]:"+str([sum(mis_primed),sum(mis_useA),sum(mis_useB)]))
return names_,seqs_f
def computeOTTable(gen_seq_,block,FPKM = None,verbose = False,progress_report=False):
#This takes a sequence <gen_seq_> (or a list of sequences) and computes the specificity table as a modified dictionary with values spanning up to 5^block
OTTableDic = constant_zero_dict()
count_gen = 0
recount_gen = 0
if type(gen_seq_)==list:
gen_seqs_ = gen_seq_
else:
gen_seqs_ = [gen_seq_]
for gen_seq in gen_seqs_:
if len(gen_seq)>block:
arr = [gen_seq[i:i+block] for i in range(len(gen_seq)-block+1)]
arr = np.array(arr)
if verbose: print("Computing dictionary")
if FPKM is None:
for key in arr:
OTTableDic[key]+=1
else:
FPKM_ = FPKM[count_gen]
for key in arr:
OTTableDic[key]+=FPKM_
count_gen += 1
recount_gen += 1
if progress_report:
if recount_gen>len(gen_seq_)/100:
recount_gen = 0
print(str(count_gen*100/len(gen_seq_))+"% complete")
return OTTableDic
def computeIndexTable(gen_seq_,block,verbose = False,progress_report=False):
#This takes a sequence <gen_seq_> (or a list of sequences) and computes the specificity table as a modified dictionary with values spanning up to 5^block
IndexTableDic = constant_list_dict()
count_gen = 0
recount_gen = 0
if type(gen_seq_)==list:
gen_seqs_ = gen_seq_
else:
gen_seqs_ = [gen_seq_]
for gen_seq in gen_seqs_:
if len(gen_seq)>block:
if verbose: print("Computing conversion nt2int excluding bad symbols")
nt2int=constant_minus_one_dict({'a':0,'c':1,'g':2,'t':3,'A':0,'C':1,'G':2,'T':3})
int_gen_seq =[nt2int[ch] for ch in gen_seq]
int_gen_seq = np.array(int_gen_seq)+1
#int_gen_seq = int_gen_seq[int_gen_seq>=0]
if verbose: print("Computing block matrix version of nt2int ")
len_int_gen_seq = len(int_gen_seq)
arr = [int_gen_seq[i:len_int_gen_seq+i-block+1] for i in range(block)]
arr = np.array(arr)
if verbose: print("Computing hits")
base = 5**np.arange(block,dtype="int64")
hits = np.dot(base,arr)
if verbose: print("Computing dictionary")
for key in hits:
IndexTableDic[key]+=[count_gen]
count_gen += 1
recount_gen += 1
if progress_report:
if recount_gen>len(gen_seq_)/100:
recount_gen = 0
print(str(count_gen*100/len(gen_seq_))+"% complete")
return IndexTableDic
class OTTable (dict):
""" run this as:
specTable = OTTable()
specTableMAP = specTable.computeOTTable(gen_seq,block)
specTable.Save(filename)
OR:
specTable = OTTable()
specTable.Load(filename)
specTableMAP = specTable.Map()
"""
def Load(self,filename):
import pickle as pickle
dic = pickle.load(open(filename, 'rb'))
self.keys,self.values,self.block,self.filename = dic["keys"],dic["values"],dic["block"],dic["filename"]
def Save(self,filename):
import pickle as pickle
self.filename = filename
print("Saving keys/values")
dic = {"keys":self.keys,"values":self.values,"block":self.block,"filename":self.filename}
pickle.dump(dic,open(filename, 'wb'),protocol=pickle.HIGHEST_PROTOCOL)
def Map(self):
# This computes the map of hash table
keys,values = self.keys,self.values
self.OTTableDic = constant_zero_dict()
print("Computing dictionary")
for i in range(len(keys)):
self.OTTableDic[keys[i]]=values[i]
return self.OTTableDic
def computeOTTable(self,gen_seq_,block,FPKM = None,verbose = False,progress_report=False):
#This takes a sequence <gen_seq_> (or a list of sequences) and computes the specificity table as a modified dictionary with values spanning up to 5^block
OTTableDic = constant_zero_dict()
count_gen = 0
recount_gen = 0
if type(gen_seq_)==list:
gen_seqs_ = gen_seq_
else:
gen_seqs_ = [gen_seq_]
for gen_seq in gen_seqs_:
if len(gen_seq)>block:
arr = [gen_seq[i:i+block] for i in range(len(gen_seq)-block+1)]
arr = np.array(arr)
if verbose: print("Computing dictionary")
if FPKM is None:
for key in arr:
OTTableDic[key]+=1
else:
FPKM_ = FPKM[count_gen]
for key in arr:
OTTableDic[key]+=FPKM_
count_gen += 1
recount_gen += 1
if progress_report:
if recount_gen>len(gen_seq_)/100:
recount_gen = 0
print(str(count_gen*100/len(gen_seq_))+"% complete")
self.OTTableDic = OTTableDic
return self.OTTableDic
def tm(string):
from Bio.SeqUtils import MeltingTemp as mt
return mt.Tm_NN(string, nn_table=mt.DNA_NN4)
def gc(string):
return float(string.count('g')+string.count('G')+string.count('c')+string.count('C'))/len(string)
def find_value_dic(dic,key):
try:
return dic[key]
except:
return 0
def specificity_report(probes,names,maps,block=17):
pb_report = []
for i in range(len(probes)):
pb_t,name_curr = probes[i],names[i]
pb_t_counts = np.zeros(len(maps),dtype=int)
#Iterate through block regions:
for j in range(len(pb_t)-block):
blk_t = pb_t[j:j+block]
blk_t_rc = seqrc(blk_t)
##Deal with maps:
blk_t_counts = np.array([find_value_dic(OTTableMap,blk_t)+find_value_dic(OTTableMap,blk_t_rc) for OTTableMap in maps])
pb_t_counts+=blk_t_counts
ls0 = [pb_t,i,name_curr,tm(pb_t),gc(pb_t)]
ls0.extend(pb_t_counts)
pb_report.append(ls0)
return pb_report
def compute_pair_probes(gene_names,gene_seqs,folder_save="",blk=17,pb_len=30,map_rep=None,map_noGenes=None,maps_Genes=None,FPKM_cuttoff1=2,FPKM_cuttoff2=10,min_gc=0.30,max_gc=0.70,gene_cutoff1=3,gene_cutoff2=5):
"""This is intended to return to you pairs of probes for bTree
Require paramaters:
@gene_names : a list of names for the genes you require probes.
@gene_seqs : a list of sequences (A,C,G,T,N) for the genes you require probes. For exon junctions or masking use N.
@blk : word size of the maps
@pb_len : desired probe length
@map_noGenes : if dictionary: the OT map of FPKM excluding the genes interested in.
It is not necessary to exclude the genes or to use FPKM vs just sequences, but then use the cutoffs appropriately.
if None: ignore this test
if string: the path of a fasta file and compute the map on the spot using blk word size
@maps_Genes : if dictionary: the Index map for the gese interested in.
if None: ignore this test
if string: the path of a fasta file and compute the map on the spot using blk word size
@map_rep : if dictionary: the OT maps of higly abundant genes. No crosstalk with these genes will be accepted
if None: ignore this test
if string: the path of a fasta file and compute the map on the spot using blk word size
@FPKM_cuttoff1/FPKM_cuttoff2 : min/max cut for the map_noGenes
@gene_cutoff1/gene_cutoff2 : min/max cut for the maps_Genes
@pb_len : probe length
@min_gc/max_gc
Returns:
@pb_names_f : names of the probe in the form "<gene name>_pb:<location>_pb-pair:[<pair index>, <index in pair>]"
@pb_seqs_f : sequences of the probes
"""
### Check for variable pop:
if type(map_noGenes)==str:
print("Computing the map for transcriptome! Please wait!")
names_,seqs_ = fastaread(map_noGenes)
#construct specificity table (dictionary) for all the sequences of the transcripts in MOE.
specTable = OTTable()
print("Warning: FPKM might not be computed correctly!")
FPKM_ = [float(nm.split('_')[-3]) for nm in names_] #change this for generic FPKM
map_noGenes = specTable.computeOTTable(seqs_,blk,FPKM=FPKM_)
if type(maps_Genes)==str:
print("Computing the maps for genes!")
names_,seqs_ = fastaread(maps_Genes)
maps_Genes = computeIndexTable(seqs_,blk)
if type(map_rep)==str:
print("Computing the map for repetitive RNA!")
names_,seqs_ = fastaread(map_rep)
specTable = OTTable()
map_rep = specTable.computeOTTable(seqs_,blk)
###Construct the probe scoring function
def map_seq(seq,map_OT,blk):
if type(map_OT[0])==list:
return_val = []
for i in range(len(seq)-blk+1):
return_val += map_OT[seq[i:i+blk]]
gns,cts = np.unique(return_val,return_counts=True)
return list(zip(gns,cts))
else:
return sum([map_OT[seq[i:i+blk]] for i in range(len(seq)-blk+1)])
pb_names_f,pb_seqs_f=[],[]
num_pairs_f = []
###Iterate through genes:
for current_gene in range(len(gene_seqs)):
gene_seq = gene_seqs[current_gene]
gene_name = gene_names[current_gene]
locations_recorded = []
location,pair_ind,pb_pair_ind=0,0,0
pb_names,pb_seqs=[],[]
num_pairs = 0
while True:
pb1,pb2 = gene_seq[location:location+pb_len],gene_seq[location+pb_len:location+2*pb_len]
#check where this probe is already in the set
pb1_verified = False
if locations_recorded.count(location): pb1_verified = True
noNs = pb1.count('N') + pb2.count('N') == 0
if noNs:
seq_cut = gc(pb1)>=min_gc and gc(pb2)>=min_gc and gc(pb1)<=max_gc and gc(pb2)<=max_gc
if seq_cut:
if map_rep is not None:
#Deal with cross-reactivity
#--To very abundant mRNA
score_rep1 = map_seq(pb1,map_rep,blk)
score_rep2 = map_seq(pb2,map_rep,blk)
rep_cut = score_rep1==0 and score_rep2==0
else:
rep_cut=True
if rep_cut:
if map_noGenes is not None:
#--To all RNA's except the olfrs (using FPKMcuttoff)
score_RNA1 = map_seq(pb1,map_noGenes,blk)
score_RNA2 = map_seq(pb2,map_noGenes,blk)
RNA_cut = min(score_RNA1,score_RNA2)<min(FPKM_cuttoff1,FPKM_cuttoff2) and max(score_RNA1,score_RNA2)<max(FPKM_cuttoff1,FPKM_cuttoff2)
else:
RNA_cut=True
if RNA_cut:
if maps_Genes is not None:
#--To all olfrs
#--To all olfrs
scores_Gene1 = map_seq(pb1,maps_Genes,blk)
scores_Gene1.pop(np.argmax([sc[1] for sc in scores_Gene1])) # pop the maximum
scores_Gene2 = map_seq(pb2,maps_Genes,blk)
scores_Gene2.pop(np.argmax([sc[1] for sc in scores_Gene2])) # pop the maximum
geneIdx_offGene1 = [score[0] for score in scores_Gene1 if score[1]>gene_cutoff1]
geneIdx_offGene2 = [score[0] for score in scores_Gene2 if score[1]>gene_cutoff2]
geneIdx_offGene1_ = [score[0] for score in scores_Gene2 if score[1]>gene_cutoff1]
geneIdx_offGene2_ = [score[0] for score in scores_Gene1 if score[1]>gene_cutoff2]
gene_int = min(len(np.intersect1d(geneIdx_offGene1,geneIdx_offGene2)),len(np.intersect1d(geneIdx_offGene1_,geneIdx_offGene2_)))
else:
gene_int=0
if gene_int==0:
# record poisitions:
## create name:
if pb1_verified:
pb_pair_ind+=1
pb_name = gene_name+"_pb:"+str(location+pb_len)+'_pb-pair:'+str([pair_ind,pb_pair_ind])
pb_names.append(pb_name)
pb_seqs.append(pb2)
locations_recorded.append(location+pb_len)
num_pairs+=1
else:
pair_ind+=1
pb_pair_ind=1
pb_name = gene_name+"_pb:"+str(location)+'_pb-pair:'+str([pair_ind,pb_pair_ind])
pb_names.append(pb_name)
pb_seqs.append(pb1)
locations_recorded.append(location)
pb_pair_ind+=1
pb_name = gene_name+"_pb:"+str(location+pb_len)+'_pb-pair:'+str([pair_ind,pb_pair_ind])
pb_names.append(pb_name)
pb_seqs.append(pb2)
locations_recorded.append(location+pb_len)
num_pairs+=1
gene_seq = gene_seq[:location]+"".join(['N' for k in range(pb_len)])+gene_seq[location+pb_len:]
location+=1
if location+2*pb_len>len(gene_seq):
break
print(gene_name+" (pairs: "+str(num_pairs)+") done!")
fastawrite(folder_save+os.sep+gene_name+'_probes.fasta',pb_names,pb_seqs)
pb_names_f.append(pb_names)
pb_seqs_f.append(pb_seqs)
num_pairs_f+=[num_pairs]
return pb_names_f,pb_seqs_f,num_pairs_f
def index_no_overlap(starts,ends):
# This returns the index of probes ensuring that they do not overlap
starts_i = np.argsort(starts)
#starts_inv = np.argsort(starts_i)
starts_ = np.array(starts)[starts_i]
ends_ = np.array(ends)[starts_i]
starts_t = list(starts_)
ends_t = list(ends_)
danger_tag = True
while danger_tag:
danger_tag = False
for i in range(len(starts_t)-1):
if starts_t[i+1]<ends_t[i]:
danger_tag = True
danger = i
del starts_t[i]
del ends_t[i]
break
starts_ = list(starts)
index_keep = [starts_.index(st) for st in starts_t]
return index_keep
def map_pair(nms_,sqs_,code,cts_icode,cts_vcode,tails,pair_limit_per_bit):
nms_new,sqs_new=[],[]
for nm,sq in zip(nms_,sqs_):
if nm is nms_[0]:
str_l = 'i_'
str_r = 'v_'
l = code[np.argmin(cts_icode)]
cts_icode[code.index(l)]+=1
r = code[np.argmin(cts_vcode)]
elif nm is nms_[-1]:
str_l = 'v_'
str_r = 'i_'
l = r
cts_vcode[code.index(l)]+=1
r = code[np.argmin(cts_icode)]
cts_icode[code.index(r)]+=1
else:
str_l = 'v_'
str_r = 'v_'
l = r
cts_vcode[code.index(l)]+=1
r = code[np.argmin(cts_vcode)]
#name modif
nm_lr=str([str_l+str(l),str_r+str(r)])
nm+='_code:'+str(code)+'_left-right-new:'+nm_lr
nms_new.append(nm)
#seq modif
l_seq=seqrc(tails[l][15:])
r_seq=seqrc(tails[r][:15])
sqs_new.append(up_down([l_seq,seqrc(sq),r_seq]))
if min(cts_vcode)>=pair_limit_per_bit: break
return nms_new,sqs_new
def file_to_mat(file_,sep_str=',',d_type=None,skip_first=False):
"""
Converts .csv files to a list of its entries
Inputs:
file_ - the location of a .csv file
sep_str - the separator between data points
d_type - the datatype in the file
skip_first - an option to skip the first component (e.g. if there's a menu)
Returns:
lines - a list of the lines in the file, each of which itself a list of all entries in the line
"""
lines = [ln for ln in open(file_,'r')]
start_=(1 if skip_first==True else 0) #skip first line if option selected
def refine_line(ln,d_type=None,skip_first=False): #separates the data into its constituents
splits = ln[:-1].split(sep_str)
if d_type is None:
return [ln_ for ln_ in splits[start_:]]
if d_type=='int':
return [np.nan if ln_=='' else int(ln_) for ln_ in splits[start_:]]
if d_type=='float':
return [np.nan if ln_=='' else float(ln_) for ln_ in splits[start_:]]
lines = [refine_line(ln,d_type,skip_first) for ln in lines[start_:]]
return lines
def map_gene(pairs_nms_,pairs_sqs_,code,tails,pair_limit_per_bit=10):
""" Use as:
map_gene([['name_pb-pair:[1,1]','name_pb-pair:[1,2]','name_pb-pair:[1,3]'],['name_pb-pair:[2,1]','name_pb-pair:[2,2]']],
[['sq1','sq2','sq3'],['sq4','sq5']],[0,1,2],
['0000','1111','2222','3333','4444','5555'],pair_limit_per_bit=10)
"""
nms_gene,sqs_gene = [],[]
cts_icode = [0 for i in range(len(code))]
cts_vcode = [0 for i in range(len(code))]
for nms_,sqs_ in zip(pairs_nms_,pairs_sqs_):
nms_new,sqs_new = map_pair(nms_,sqs_,code,cts_icode,cts_vcode,tails,pair_limit_per_bit)
nms_gene.extend(nms_new)
sqs_gene.extend(sqs_new)
if min(cts_vcode)>=pair_limit_per_bit: break
return nms_gene,sqs_gene
def simmilar(str1,str2,val=10):
str1_=str1.lower();
str2_=str2.lower();
str2_rc=seqrc(str2_);
sim=sum([str2_.count(str1_[i:i+val]) for i in range(len(str1_)-val+1)])
sim_rc=sum([str2_rc.count(str1_[i:i+val]) for i in range(len(str1_)-val+1)])
return sim+sim_rc
def simmilar_list(lst,names=None,seq_len=12):
problems=[]
for i in range(len(lst)):
for j in range(len(lst)):
if i>j:
sim=simmilar(lst[i],lst[j],val=seq_len)
if sim:
if names is not None:
problems.append([names[i],names[j],sim])
else:
problems.append([i,j,sim])
return problems
class constant_zero_dict (dict):
def __missing__ (self, key):
return 0
def get(self,k,d=0):
return dict.get(self,k,d)
class constant_minus_one_dict (dict):
def __missing__ (self, key):
return -1
class constant_nan_dict (dict):
def __missing__ (self, key):
return np.nan
class constant_list_dict (dict):
def __missing__ (self, key):
return []
def valid_sequence(pb_seq):
pb_valid = sum([pb_seq.count(let) for let in 'aAtTgGcC'])==len(pb_seq)
return pb_valid
def tail_to_lr(seq):
n_=len(seq)
return list(map(seqrc,[seq[n_/2:],seq[:n_/2]]))
def lr_to_tail(seqs):
l,r=seqs
return seqrc(r)+seqrc(l)
| 16,707 | 58 | 1,026 |
9c74bc304474a90f922e3ba5e1d7784293623014 | 9,738 | py | Python | plaso/storage/sqlite/merge_reader.py | infosecjosh/plaso | 7b5fc33591c60e89afc231a451449d40e02d8985 | [
"Apache-2.0"
] | null | null | null | plaso/storage/sqlite/merge_reader.py | infosecjosh/plaso | 7b5fc33591c60e89afc231a451449d40e02d8985 | [
"Apache-2.0"
] | null | null | null | plaso/storage/sqlite/merge_reader.py | infosecjosh/plaso | 7b5fc33591c60e89afc231a451449d40e02d8985 | [
"Apache-2.0"
] | null | null | null | # -*- coding: utf-8 -*-
"""Merge reader for SQLite storage files."""
from __future__ import unicode_literals
import os
import sqlite3
import zlib
from plaso.containers import errors
from plaso.containers import event_sources
from plaso.containers import events
from plaso.containers import reports
from plaso.containers import tasks
from plaso.lib import definitions
from plaso.storage import identifiers
from plaso.storage import interface
class SQLiteStorageMergeReader(interface.StorageFileMergeReader):
"""SQLite-based storage file reader for merging."""
_CONTAINER_TYPE_ANALYSIS_REPORT = reports.AnalysisReport.CONTAINER_TYPE
_CONTAINER_TYPE_EVENT = events.EventObject.CONTAINER_TYPE
_CONTAINER_TYPE_EVENT_DATA = events.EventData.CONTAINER_TYPE
_CONTAINER_TYPE_EVENT_SOURCE = event_sources.EventSource.CONTAINER_TYPE
_CONTAINER_TYPE_EVENT_TAG = events.EventTag.CONTAINER_TYPE
_CONTAINER_TYPE_EXTRACTION_ERROR = errors.ExtractionError.CONTAINER_TYPE
_CONTAINER_TYPE_TASK_COMPLETION = tasks.TaskCompletion.CONTAINER_TYPE
_CONTAINER_TYPE_TASK_START = tasks.TaskStart.CONTAINER_TYPE
# Some container types reference other container types, such as event
# referencing event_data. Container types in this tuple must be ordered after
# all the container types they reference.
_CONTAINER_TYPES = (
_CONTAINER_TYPE_EVENT_SOURCE,
_CONTAINER_TYPE_EVENT_DATA,
_CONTAINER_TYPE_EVENT,
_CONTAINER_TYPE_EVENT_TAG,
_CONTAINER_TYPE_EXTRACTION_ERROR,
_CONTAINER_TYPE_ANALYSIS_REPORT)
_ADD_CONTAINER_TYPE_METHODS = {
_CONTAINER_TYPE_ANALYSIS_REPORT: '_AddAnalysisReport',
_CONTAINER_TYPE_EVENT: '_AddEvent',
_CONTAINER_TYPE_EVENT_DATA: '_AddEventData',
_CONTAINER_TYPE_EVENT_SOURCE: '_AddEventSource',
_CONTAINER_TYPE_EVENT_TAG: '_AddEventTag',
_CONTAINER_TYPE_EXTRACTION_ERROR: '_AddError',
}
_TABLE_NAMES_QUERY = (
'SELECT name FROM sqlite_master WHERE type = "table"')
def __init__(self, storage_writer, path):
"""Initializes a storage merge reader.
Args:
storage_writer (StorageWriter): storage writer.
path (str): path to the input file.
Raises:
IOError: if the input file cannot be opened.
RuntimeError: if an add container method is missing.
"""
super(SQLiteStorageMergeReader, self).__init__(storage_writer)
self._active_container_type = None
self._active_cursor = None
self._add_active_container_method = None
self._add_container_type_methods = {}
self._compression_format = definitions.COMPRESSION_FORMAT_NONE
self._connection = None
self._container_types = None
self._cursor = None
self._event_data_identifier_mappings = {}
self._path = path
# Create a runtime lookup table for the add container type method. This
# prevents having to create a series of if-else checks for container types.
# The table is generated at runtime as there are no forward function
# declarations in Python.
for container_type, method_name in self._ADD_CONTAINER_TYPE_METHODS.items():
method = getattr(self, method_name, None)
if not method:
raise RuntimeError(
'Add method missing for container type: {0:s}'.format(
container_type))
self._add_container_type_methods[container_type] = method
def _AddAnalysisReport(self, analysis_report):
"""Adds an analysis report.
Args:
analysis_report (AnalysisReport): analysis report.
"""
self._storage_writer.AddAnalysisReport(analysis_report)
def _AddError(self, error):
"""Adds an error.
Args:
error (ExtractionError): error.
"""
self._storage_writer.AddError(error)
def _AddEvent(self, event):
"""Adds an event.
Args:
event (EventObject): event.
"""
if hasattr(event, 'event_data_row_identifier'):
event_data_identifier = identifiers.SQLTableIdentifier(
self._CONTAINER_TYPE_EVENT_DATA,
event.event_data_row_identifier)
lookup_key = event_data_identifier.CopyToString()
event_data_identifier = self._event_data_identifier_mappings[lookup_key]
event.SetEventDataIdentifier(event_data_identifier)
# TODO: add event identifier mappings for event tags.
self._storage_writer.AddEvent(event)
def _AddEventData(self, event_data):
"""Adds event data.
Args:
event_data (EventData): event data.
"""
identifier = event_data.GetIdentifier()
lookup_key = identifier.CopyToString()
self._storage_writer.AddEventData(event_data)
identifier = event_data.GetIdentifier()
self._event_data_identifier_mappings[lookup_key] = identifier
def _AddEventSource(self, event_source):
"""Adds an event source.
Args:
event_source (EventSource): event source.
"""
self._storage_writer.AddEventSource(event_source)
def _AddEventTag(self, event_tag):
"""Adds an event tag.
Args:
event_tag (EventTag): event tag.
"""
self._storage_writer.AddEventTag(event_tag)
def _Close(self):
"""Closes the task storage after reading."""
self._connection.close()
self._connection = None
self._cursor = None
def _GetContainerTypes(self):
"""Retrieves the container types to merge.
Container types not defined in _CONTAINER_TYPES are ignored and not merged.
Specific container types reference other container types, such
as event referencing event data. The names are ordered to ensure the
attribute containers are merged in the correct order.
Returns:
list[str]: names of the container types to merge.
"""
self._cursor.execute(self._TABLE_NAMES_QUERY)
table_names = [row[0] for row in self._cursor.fetchall()]
return [
table_name for table_name in self._CONTAINER_TYPES
if table_name in table_names]
def _Open(self):
"""Opens the task storage for reading."""
self._connection = sqlite3.connect(
self._path, detect_types=sqlite3.PARSE_DECLTYPES|sqlite3.PARSE_COLNAMES)
self._cursor = self._connection.cursor()
def _ReadStorageMetadata(self):
"""Reads the task storage metadata."""
query = 'SELECT key, value FROM metadata'
self._cursor.execute(query)
metadata_values = {row[0]: row[1] for row in self._cursor.fetchall()}
self._compression_format = metadata_values['compression_format']
def _PrepareForNextContainerType(self):
"""Prepares for the next container type.
This method prepares the task storage for merging the next container type.
It set the active container type, its add method and active cursor
accordingly.
"""
self._active_container_type = self._container_types.pop(0)
self._add_active_container_method = self._add_container_type_methods.get(
self._active_container_type)
query = 'SELECT _identifier, _data FROM {0:s}'.format(
self._active_container_type)
self._cursor.execute(query)
self._active_cursor = self._cursor
def MergeAttributeContainers(
self, callback=None, maximum_number_of_containers=0):
"""Reads attribute containers from a task storage file into the writer.
Args:
callback (function[StorageWriter, AttributeContainer]): function to call
after each attribute container is deserialized.
maximum_number_of_containers (Optional[int]): maximum number of
containers to merge, where 0 represent no limit.
Returns:
bool: True if the entire task storage file has been merged.
Raises:
RuntimeError: if the add method for the active attribute container
type is missing.
OSError: if the task storage file cannot be deleted.
ValueError: if the maximum number of containers is a negative value.
"""
if maximum_number_of_containers < 0:
raise ValueError('Invalid maximum number of containers')
if not self._cursor:
self._Open()
self._ReadStorageMetadata()
self._container_types = self._GetContainerTypes()
number_of_containers = 0
while self._active_cursor or self._container_types:
if not self._active_cursor:
self._PrepareForNextContainerType()
if maximum_number_of_containers == 0:
rows = self._active_cursor.fetchall()
else:
number_of_rows = maximum_number_of_containers - number_of_containers
rows = self._active_cursor.fetchmany(size=number_of_rows)
if not rows:
self._active_cursor = None
continue
for row in rows:
identifier = identifiers.SQLTableIdentifier(
self._active_container_type, row[0])
if self._compression_format == definitions.COMPRESSION_FORMAT_ZLIB:
serialized_data = zlib.decompress(row[1])
else:
serialized_data = row[1]
attribute_container = self._DeserializeAttributeContainer(
self._active_container_type, serialized_data)
attribute_container.SetIdentifier(identifier)
if self._active_container_type == self._CONTAINER_TYPE_EVENT_TAG:
event_identifier = identifiers.SQLTableIdentifier(
self._CONTAINER_TYPE_EVENT,
attribute_container.event_row_identifier)
attribute_container.SetEventIdentifier(event_identifier)
del attribute_container.event_row_identifier
if callback:
callback(self._storage_writer, attribute_container)
self._add_active_container_method(attribute_container)
number_of_containers += 1
if (maximum_number_of_containers != 0 and
number_of_containers >= maximum_number_of_containers):
return False
self._Close()
os.remove(self._path)
return True
| 33.235495 | 80 | 0.728692 | # -*- coding: utf-8 -*-
"""Merge reader for SQLite storage files."""
from __future__ import unicode_literals
import os
import sqlite3
import zlib
from plaso.containers import errors
from plaso.containers import event_sources
from plaso.containers import events
from plaso.containers import reports
from plaso.containers import tasks
from plaso.lib import definitions
from plaso.storage import identifiers
from plaso.storage import interface
class SQLiteStorageMergeReader(interface.StorageFileMergeReader):
"""SQLite-based storage file reader for merging."""
_CONTAINER_TYPE_ANALYSIS_REPORT = reports.AnalysisReport.CONTAINER_TYPE
_CONTAINER_TYPE_EVENT = events.EventObject.CONTAINER_TYPE
_CONTAINER_TYPE_EVENT_DATA = events.EventData.CONTAINER_TYPE
_CONTAINER_TYPE_EVENT_SOURCE = event_sources.EventSource.CONTAINER_TYPE
_CONTAINER_TYPE_EVENT_TAG = events.EventTag.CONTAINER_TYPE
_CONTAINER_TYPE_EXTRACTION_ERROR = errors.ExtractionError.CONTAINER_TYPE
_CONTAINER_TYPE_TASK_COMPLETION = tasks.TaskCompletion.CONTAINER_TYPE
_CONTAINER_TYPE_TASK_START = tasks.TaskStart.CONTAINER_TYPE
# Some container types reference other container types, such as event
# referencing event_data. Container types in this tuple must be ordered after
# all the container types they reference.
_CONTAINER_TYPES = (
_CONTAINER_TYPE_EVENT_SOURCE,
_CONTAINER_TYPE_EVENT_DATA,
_CONTAINER_TYPE_EVENT,
_CONTAINER_TYPE_EVENT_TAG,
_CONTAINER_TYPE_EXTRACTION_ERROR,
_CONTAINER_TYPE_ANALYSIS_REPORT)
_ADD_CONTAINER_TYPE_METHODS = {
_CONTAINER_TYPE_ANALYSIS_REPORT: '_AddAnalysisReport',
_CONTAINER_TYPE_EVENT: '_AddEvent',
_CONTAINER_TYPE_EVENT_DATA: '_AddEventData',
_CONTAINER_TYPE_EVENT_SOURCE: '_AddEventSource',
_CONTAINER_TYPE_EVENT_TAG: '_AddEventTag',
_CONTAINER_TYPE_EXTRACTION_ERROR: '_AddError',
}
_TABLE_NAMES_QUERY = (
'SELECT name FROM sqlite_master WHERE type = "table"')
def __init__(self, storage_writer, path):
"""Initializes a storage merge reader.
Args:
storage_writer (StorageWriter): storage writer.
path (str): path to the input file.
Raises:
IOError: if the input file cannot be opened.
RuntimeError: if an add container method is missing.
"""
super(SQLiteStorageMergeReader, self).__init__(storage_writer)
self._active_container_type = None
self._active_cursor = None
self._add_active_container_method = None
self._add_container_type_methods = {}
self._compression_format = definitions.COMPRESSION_FORMAT_NONE
self._connection = None
self._container_types = None
self._cursor = None
self._event_data_identifier_mappings = {}
self._path = path
# Create a runtime lookup table for the add container type method. This
# prevents having to create a series of if-else checks for container types.
# The table is generated at runtime as there are no forward function
# declarations in Python.
for container_type, method_name in self._ADD_CONTAINER_TYPE_METHODS.items():
method = getattr(self, method_name, None)
if not method:
raise RuntimeError(
'Add method missing for container type: {0:s}'.format(
container_type))
self._add_container_type_methods[container_type] = method
def _AddAnalysisReport(self, analysis_report):
"""Adds an analysis report.
Args:
analysis_report (AnalysisReport): analysis report.
"""
self._storage_writer.AddAnalysisReport(analysis_report)
def _AddError(self, error):
"""Adds an error.
Args:
error (ExtractionError): error.
"""
self._storage_writer.AddError(error)
def _AddEvent(self, event):
"""Adds an event.
Args:
event (EventObject): event.
"""
if hasattr(event, 'event_data_row_identifier'):
event_data_identifier = identifiers.SQLTableIdentifier(
self._CONTAINER_TYPE_EVENT_DATA,
event.event_data_row_identifier)
lookup_key = event_data_identifier.CopyToString()
event_data_identifier = self._event_data_identifier_mappings[lookup_key]
event.SetEventDataIdentifier(event_data_identifier)
# TODO: add event identifier mappings for event tags.
self._storage_writer.AddEvent(event)
def _AddEventData(self, event_data):
"""Adds event data.
Args:
event_data (EventData): event data.
"""
identifier = event_data.GetIdentifier()
lookup_key = identifier.CopyToString()
self._storage_writer.AddEventData(event_data)
identifier = event_data.GetIdentifier()
self._event_data_identifier_mappings[lookup_key] = identifier
def _AddEventSource(self, event_source):
"""Adds an event source.
Args:
event_source (EventSource): event source.
"""
self._storage_writer.AddEventSource(event_source)
def _AddEventTag(self, event_tag):
"""Adds an event tag.
Args:
event_tag (EventTag): event tag.
"""
self._storage_writer.AddEventTag(event_tag)
def _Close(self):
"""Closes the task storage after reading."""
self._connection.close()
self._connection = None
self._cursor = None
def _GetContainerTypes(self):
"""Retrieves the container types to merge.
Container types not defined in _CONTAINER_TYPES are ignored and not merged.
Specific container types reference other container types, such
as event referencing event data. The names are ordered to ensure the
attribute containers are merged in the correct order.
Returns:
list[str]: names of the container types to merge.
"""
self._cursor.execute(self._TABLE_NAMES_QUERY)
table_names = [row[0] for row in self._cursor.fetchall()]
return [
table_name for table_name in self._CONTAINER_TYPES
if table_name in table_names]
def _Open(self):
"""Opens the task storage for reading."""
self._connection = sqlite3.connect(
self._path, detect_types=sqlite3.PARSE_DECLTYPES|sqlite3.PARSE_COLNAMES)
self._cursor = self._connection.cursor()
def _ReadStorageMetadata(self):
"""Reads the task storage metadata."""
query = 'SELECT key, value FROM metadata'
self._cursor.execute(query)
metadata_values = {row[0]: row[1] for row in self._cursor.fetchall()}
self._compression_format = metadata_values['compression_format']
def _PrepareForNextContainerType(self):
"""Prepares for the next container type.
This method prepares the task storage for merging the next container type.
It set the active container type, its add method and active cursor
accordingly.
"""
self._active_container_type = self._container_types.pop(0)
self._add_active_container_method = self._add_container_type_methods.get(
self._active_container_type)
query = 'SELECT _identifier, _data FROM {0:s}'.format(
self._active_container_type)
self._cursor.execute(query)
self._active_cursor = self._cursor
def MergeAttributeContainers(
self, callback=None, maximum_number_of_containers=0):
"""Reads attribute containers from a task storage file into the writer.
Args:
callback (function[StorageWriter, AttributeContainer]): function to call
after each attribute container is deserialized.
maximum_number_of_containers (Optional[int]): maximum number of
containers to merge, where 0 represent no limit.
Returns:
bool: True if the entire task storage file has been merged.
Raises:
RuntimeError: if the add method for the active attribute container
type is missing.
OSError: if the task storage file cannot be deleted.
ValueError: if the maximum number of containers is a negative value.
"""
if maximum_number_of_containers < 0:
raise ValueError('Invalid maximum number of containers')
if not self._cursor:
self._Open()
self._ReadStorageMetadata()
self._container_types = self._GetContainerTypes()
number_of_containers = 0
while self._active_cursor or self._container_types:
if not self._active_cursor:
self._PrepareForNextContainerType()
if maximum_number_of_containers == 0:
rows = self._active_cursor.fetchall()
else:
number_of_rows = maximum_number_of_containers - number_of_containers
rows = self._active_cursor.fetchmany(size=number_of_rows)
if not rows:
self._active_cursor = None
continue
for row in rows:
identifier = identifiers.SQLTableIdentifier(
self._active_container_type, row[0])
if self._compression_format == definitions.COMPRESSION_FORMAT_ZLIB:
serialized_data = zlib.decompress(row[1])
else:
serialized_data = row[1]
attribute_container = self._DeserializeAttributeContainer(
self._active_container_type, serialized_data)
attribute_container.SetIdentifier(identifier)
if self._active_container_type == self._CONTAINER_TYPE_EVENT_TAG:
event_identifier = identifiers.SQLTableIdentifier(
self._CONTAINER_TYPE_EVENT,
attribute_container.event_row_identifier)
attribute_container.SetEventIdentifier(event_identifier)
del attribute_container.event_row_identifier
if callback:
callback(self._storage_writer, attribute_container)
self._add_active_container_method(attribute_container)
number_of_containers += 1
if (maximum_number_of_containers != 0 and
number_of_containers >= maximum_number_of_containers):
return False
self._Close()
os.remove(self._path)
return True
| 0 | 0 | 0 |
b85bd517170fb2c46c50b357f62819dc54489c92 | 3,744 | py | Python | tests/utest/test_utils.py | josflorap/robotframework-tidy | 9d4e1ccc6a50c415187468305235830f80f3373b | [
"Apache-2.0"
] | null | null | null | tests/utest/test_utils.py | josflorap/robotframework-tidy | 9d4e1ccc6a50c415187468305235830f80f3373b | [
"Apache-2.0"
] | null | null | null | tests/utest/test_utils.py | josflorap/robotframework-tidy | 9d4e1ccc6a50c415187468305235830f80f3373b | [
"Apache-2.0"
] | null | null | null | import os
from pathlib import Path
import pytest
from robotidy.app import Robotidy
from robotidy.utils import decorate_diff_with_color, split_args_from_name_or_path, GlobalFormattingConfig
@pytest.fixture
| 34.348624 | 116 | 0.560096 | import os
from pathlib import Path
import pytest
from robotidy.app import Robotidy
from robotidy.utils import decorate_diff_with_color, split_args_from_name_or_path, GlobalFormattingConfig
@pytest.fixture
def app():
formatting_config = GlobalFormattingConfig(
space_count=4,
line_sep="auto",
start_line=None,
separator="space",
end_line=None,
)
return Robotidy(
transformers=[],
transformers_config=[],
src=(".",),
exclude=None,
extend_exclude=None,
overwrite=False,
show_diff=False,
formatting_config=formatting_config,
verbose=False,
check=False,
output=None,
force_order=False,
)
class TestUtils:
def test_not_changed_lines_not_colorized(self):
lines = ["this is one line\n", "and another\n"]
output = decorate_diff_with_color(lines)
assert output == "".join(lines)
def test_diff_lines_colorized(self):
lines = [
"+++ color category\n",
"--- color category\n",
"+ new line\n",
"- removed line\n",
"@@ line numbers\n",
"no diff line\n",
"signs + in the - middle @@ +++ ---\n",
]
expected_lines = [
"\033[1m+++ color category\n\033[0m",
"\033[1m--- color category\n\033[0m",
"\033[32m+ new line\n\033[0m",
"\033[31m- removed line\n\033[0m",
"\033[36m@@ line numbers\n\033[0m",
"no diff line\n",
"signs + in the - middle @@ +++ ---\n",
]
output = decorate_diff_with_color(lines)
assert output == "".join(expected_lines)
@pytest.mark.parametrize(
"name_or_path, expected_name, expected_args",
[
("DiscardEmptySections", "DiscardEmptySections", []),
("DiscardEmptySections:allow_only_comments=True", "DiscardEmptySections", ["allow_only_comments=True"]),
("DiscardEmptySections;allow_only_comments=True", "DiscardEmptySections", ["allow_only_comments=True"]),
(
"DiscardEmptySections;allow_only_comments=True:my_var=1",
"DiscardEmptySections",
["allow_only_comments=True:my_var=1"],
),
(r"C:\path\to\module\transformer:my_variable=1", r"C:\path\to\module\transformer", ["my_variable=1"]),
(__file__, __file__, []),
],
)
def test_split_args_from_name_or_path(self, name_or_path, expected_name, expected_args):
name, args = split_args_from_name_or_path(name_or_path)
assert name == expected_name
assert args == expected_args
@pytest.mark.parametrize(
"line_sep, source_file, expected",
[
("auto", "lf.robot", "\n"),
("auto", "crlf.robot", "\r\n"),
("auto", "cr.robot", "\r"),
("auto", "crlf_mixed.robot", "\n"),
("auto", "empty.robot", os.linesep),
("native", "lf.robot", os.linesep),
("native", "crlf.robot", os.linesep),
("windows", "lf.robot", "\r\n"),
("windows", "crlf.robot", "\r\n"),
("unix", "lf.robot", "\n"),
("unix", "crlf.robot", "\n"),
],
)
def test_get_line_ending(self, line_sep, source_file, expected, app):
source = str(Path(__file__).parent / "testdata" / "auto_line_sep" / source_file)
app.formatting_config = GlobalFormattingConfig(
space_count=4,
line_sep=line_sep,
start_line=None,
separator="space",
end_line=None,
)
assert app.get_line_ending(source) == expected
| 2,032 | 1,457 | 45 |
eb2a1467c4234db8a4875a5a94aa28520f59d682 | 1,113 | py | Python | Cinema/migrations/0011_auto_20210614_1505.py | jmv21/oficial_project | 1098dde46a80cff312a25f30ed0e560ce2c21e2b | [
"MIT"
] | null | null | null | Cinema/migrations/0011_auto_20210614_1505.py | jmv21/oficial_project | 1098dde46a80cff312a25f30ed0e560ce2c21e2b | [
"MIT"
] | null | null | null | Cinema/migrations/0011_auto_20210614_1505.py | jmv21/oficial_project | 1098dde46a80cff312a25f30ed0e560ce2c21e2b | [
"MIT"
] | null | null | null | # Generated by Django 3.2 on 2021-06-14 21:05
from django.db import migrations, models
| 29.289474 | 121 | 0.583109 | # Generated by Django 3.2 on 2021-06-14 21:05
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('Cinema', '0010_merge_0009_auto_20210611_1256_0009_auto_20210611_1549'),
]
operations = [
migrations.RemoveField(
model_name='purchase',
name='discounts',
),
migrations.AddField(
model_name='entry',
name='discounts',
field=models.ManyToManyField(db_index=True, to='Cinema.Discount'),
),
migrations.AddField(
model_name='entry',
name='reserved',
field=models.BooleanField(default=False),
),
migrations.AlterField(
model_name='movie',
name='poster',
field=models.ImageField(blank=True, default='/movie_pics/default.jpg', null=True, upload_to='profile_pics/'),
),
migrations.AlterField(
model_name='purchase',
name='entries',
field=models.ManyToManyField(db_index=True, to='Cinema.Entry'),
),
]
| 0 | 1,001 | 23 |
0adf3b85c88c62deb19c2d6d5e8cf6f50a3e171b | 435 | py | Python | tests/basics/comprehension1.py | geowor01/micropython | 7fb13eeef4a85f21cae36f1d502bcc53880e1815 | [
"MIT"
] | 7 | 2019-10-18T13:41:39.000Z | 2022-03-15T17:27:57.000Z | tests/basics/comprehension1.py | geowor01/micropython | 7fb13eeef4a85f21cae36f1d502bcc53880e1815 | [
"MIT"
] | null | null | null | tests/basics/comprehension1.py | geowor01/micropython | 7fb13eeef4a85f21cae36f1d502bcc53880e1815 | [
"MIT"
] | 2 | 2020-06-23T09:10:15.000Z | 2020-12-22T06:42:14.000Z |
f()
print("PASS") | 20.714286 | 55 | 0.528736 | def f():
# list comprehension
print([a + 1 for a in range(5)])
print([(a, b) for a in range(3) for b in range(2)])
print([a * 2 for a in range(7) if a > 3])
print([a for a in [1, 3, 5]])
print([a for a in [a for a in range(4)]])
# dict comprehension
d = {a : 2 * a for a in range(5)}
print(d[0], d[1], d[2], d[3], d[4])
# set comprehension
# see set_comprehension.py
f()
print("PASS") | 394 | 0 | 22 |
c7ea3b6ca37492c99d8961d4b45945fe7a2bbafc | 8,679 | py | Python | tensorflow_compression/python/distributions/round_adapters.py | SamuelMarks/compression | e5c0dcf2d4846a030abc5f91f75863b204357c35 | [
"Apache-2.0"
] | 1 | 2020-12-30T04:33:36.000Z | 2020-12-30T04:33:36.000Z | tensorflow_compression/python/distributions/round_adapters.py | wwxn/compression | 734ff910119bd24bbfdb08b6f6da906c789a57a1 | [
"Apache-2.0"
] | null | null | null | tensorflow_compression/python/distributions/round_adapters.py | wwxn/compression | 734ff910119bd24bbfdb08b6f6da906c789a57a1 | [
"Apache-2.0"
] | null | null | null | # Copyright 2020 Google LLC. 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.
# ==============================================================================
"""Distribution adapters for (soft) round functions."""
import tensorflow as tf
import tensorflow_probability as tfp
from tensorflow_compression.python.distributions import deep_factorized
from tensorflow_compression.python.distributions import helpers
from tensorflow_compression.python.distributions import uniform_noise
from tensorflow_compression.python.ops import soft_round_ops
__all__ = [
"MonotonicAdapter", "RoundAdapter", "NoisyRoundedNormal",
"NoisyRoundedDeepFactorized", "SoftRoundAdapter", "NoisySoftRoundedNormal",
"NoisySoftRoundedDeepFactorized"
]
class MonotonicAdapter(tfp.distributions.Distribution):
"""Adapt a continuous distribution via an ascending monotonic function.
This is described in Appendix E. in the paper
> "Universally Quantized Neural Compression"<br />
> Eirikur Agustsson & Lucas Theis<br />
> https://arxiv.org/abs/2006.09952
"""
invertible = True # Set to false if the transform is not invertible.
def __init__(self, base, name="MonotonicAdapter"):
"""Initializer.
Arguments:
base: A `tfp.distributions.Distribution` object representing a
continuous-valued random variable.
name: String. A name for this distribution.
"""
parameters = dict(locals())
self._base = base
super().__init__(
dtype=base.dtype,
reparameterization_type=base.reparameterization_type,
validate_args=base.validate_args,
allow_nan_stats=base.allow_nan_stats,
parameters=parameters,
name=name,
)
@property
def base(self):
"""The base distribution."""
return self._base
def transform(self, x):
"""The forward transform."""
raise NotImplementedError()
def inverse_transform(self, y):
"""The backward transform."""
# Let f(x) = self.transform(x)
# Then g(y) = self.inverse_transform(y) is defined as
# g(y) := inf_x { x : f(x) >= y }
# which is just the inverse of `f` if it is invertible.
raise NotImplementedError()
# pylint: disable=protected-access
# pylint: enable=protected-access
class RoundAdapter(MonotonicAdapter):
"""Continuous density function + round."""
invertible = False
class NoisyRoundAdapter(uniform_noise.UniformNoiseAdapter):
"""Uniform noise + round."""
def __init__(self, base, name="NoisyRoundAdapter"):
"""Initializer.
Arguments:
base: A `tfp.distributions.Distribution` object representing a
continuous-valued random variable.
name: String. A name for this distribution.
"""
super().__init__(RoundAdapter(base), name=name)
class NoisyRoundedDeepFactorized(NoisyRoundAdapter):
"""Rounded DeepFactorized + uniform noise."""
class NoisyRoundedNormal(NoisyRoundAdapter):
"""Rounded normal distribution + uniform noise."""
class SoftRoundAdapter(MonotonicAdapter):
"""Differentiable approximation to round."""
def __init__(self, base, alpha, name="SoftRoundAdapter"):
"""Initializer.
Arguments:
base: A `tfp.distributions.Distribution` object representing a
continuous-valued random variable.
alpha: Float or tf.Tensor. Controls smoothness of the approximation.
name: String. A name for this distribution.
"""
super().__init__(base=base, name=name)
self._alpha = alpha
class NoisySoftRoundAdapter(uniform_noise.UniformNoiseAdapter):
"""Uniform noise + differentiable approximation to round."""
def __init__(self, base, alpha, name="NoisySoftRoundAdapter"):
"""Initializer.
Arguments:
base: A `tfp.distributions.Distribution` object representing a
continuous-valued random variable.
alpha: Float or tf.Tensor. Controls smoothness of soft round.
name: String. A name for this distribution.
"""
super().__init__(SoftRoundAdapter(base, alpha), name=name)
class NoisySoftRoundedNormal(NoisySoftRoundAdapter):
"""Soft rounded normal distribution + uniform noise."""
class NoisySoftRoundedDeepFactorized(NoisySoftRoundAdapter):
"""Soft rounded deep factorized distribution + uniform noise."""
| 30.996429 | 80 | 0.686024 | # Copyright 2020 Google LLC. 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.
# ==============================================================================
"""Distribution adapters for (soft) round functions."""
import tensorflow as tf
import tensorflow_probability as tfp
from tensorflow_compression.python.distributions import deep_factorized
from tensorflow_compression.python.distributions import helpers
from tensorflow_compression.python.distributions import uniform_noise
from tensorflow_compression.python.ops import soft_round_ops
__all__ = [
"MonotonicAdapter", "RoundAdapter", "NoisyRoundedNormal",
"NoisyRoundedDeepFactorized", "SoftRoundAdapter", "NoisySoftRoundedNormal",
"NoisySoftRoundedDeepFactorized"
]
class MonotonicAdapter(tfp.distributions.Distribution):
"""Adapt a continuous distribution via an ascending monotonic function.
This is described in Appendix E. in the paper
> "Universally Quantized Neural Compression"<br />
> Eirikur Agustsson & Lucas Theis<br />
> https://arxiv.org/abs/2006.09952
"""
invertible = True # Set to false if the transform is not invertible.
def __init__(self, base, name="MonotonicAdapter"):
"""Initializer.
Arguments:
base: A `tfp.distributions.Distribution` object representing a
continuous-valued random variable.
name: String. A name for this distribution.
"""
parameters = dict(locals())
self._base = base
super().__init__(
dtype=base.dtype,
reparameterization_type=base.reparameterization_type,
validate_args=base.validate_args,
allow_nan_stats=base.allow_nan_stats,
parameters=parameters,
name=name,
)
@property
def base(self):
"""The base distribution."""
return self._base
def transform(self, x):
"""The forward transform."""
raise NotImplementedError()
def inverse_transform(self, y):
"""The backward transform."""
# Let f(x) = self.transform(x)
# Then g(y) = self.inverse_transform(y) is defined as
# g(y) := inf_x { x : f(x) >= y }
# which is just the inverse of `f` if it is invertible.
raise NotImplementedError()
def _batch_shape_tensor(self):
return self.base.batch_shape_tensor()
def _batch_shape(self):
return self.base.batch_shape
def _event_shape_tensor(self):
return self.base.event_shape_tensor()
def _event_shape(self):
return self.base.event_shape
def _sample_n(self, n, seed=None):
with tf.name_scope("round"):
n = tf.convert_to_tensor(n, name="n")
samples = self.base.sample(n, seed=seed)
return self.transform(samples)
def _prob(self, *args, **kwargs):
raise NotImplementedError
def _log_prob(self, *args, **kwargs):
raise NotImplementedError
# pylint: disable=protected-access
def _cdf(self, y):
# Let f be the forward transform and g the inverse.
# Then we have:
# P( f(x) <= y )
# P( g(f(x)) <= g(y) )
# = P( x <= g(y) )
return self.base._cdf(self.inverse_transform(y))
def _log_cdf(self, y):
return self.base._log_cdf(self.inverse_transform(y))
def _survival_function(self, y):
return self.base._survival_function(self.inverse_transform(y))
def _log_survival_function(self, y):
return self.base._log_survival_function(self.inverse_transform(y))
def _quantile(self, value):
if not self.invertible:
raise NotImplementedError()
# We have:
# P( x <= z ) = value
# if and only if
# P( f(x) <= f(z) ) = value
return self.transform(self.base._quantile(value))
def _mode(self):
# Same logic as for _quantile.
if not self.invertible:
raise NotImplementedError()
return self.transform(self.base._mode())
def _quantization_offset(self):
# Same logic as for _quantile.
if not self.invertible:
raise NotImplementedError()
return self.transform(helpers.quantization_offset(self.base))
def _lower_tail(self, tail_mass):
# Same logic as for _quantile.
if not self.invertible:
raise NotImplementedError()
return self.transform(helpers.lower_tail(self.base, tail_mass))
def _upper_tail(self, tail_mass):
# Same logic as for _quantile.
if not self.invertible:
raise NotImplementedError()
return self.transform(helpers.upper_tail(self.base, tail_mass))
# pylint: enable=protected-access
class RoundAdapter(MonotonicAdapter):
"""Continuous density function + round."""
invertible = False
def transform(self, x):
return tf.round(x)
def inverse_transform(self, y):
# Let f(x) = round(x)
# Then g(y) = inverse_transform(y) is defined as
# g(y) := inf_x { x : f(x) >= y }
# For f = round, we have
# round(x) >= y
# <=> round(x) >= ceil(y)
# so g(y) = inf_x { x: round(x) >= ceil(y) }
# = ceil(y)-0.5
# Alternative derivation:
# P( round(x) <= y )
# = P( round(x) <= floor(y) )
# = P( x <= floor(y)+0.5 )
# = P( x <= ceil(y)-0.5 )
# = P( x <= inverse_transform(y) )
return tf.math.ceil(y) - 0.5
def _quantization_offset(self):
return tf.convert_to_tensor(0.0, dtype=self.dtype)
def _lower_tail(self, tail_mass):
return tf.math.floor(helpers.lower_tail(self.base, tail_mass))
def _upper_tail(self, tail_mass):
return tf.math.ceil(helpers.upper_tail(self.base, tail_mass))
class NoisyRoundAdapter(uniform_noise.UniformNoiseAdapter):
"""Uniform noise + round."""
def __init__(self, base, name="NoisyRoundAdapter"):
"""Initializer.
Arguments:
base: A `tfp.distributions.Distribution` object representing a
continuous-valued random variable.
name: String. A name for this distribution.
"""
super().__init__(RoundAdapter(base), name=name)
class NoisyRoundedDeepFactorized(NoisyRoundAdapter):
"""Rounded DeepFactorized + uniform noise."""
def __init__(self, name="NoisyRoundedDeepFactorized", **kwargs):
prior = deep_factorized.DeepFactorized(**kwargs)
super().__init__(base=prior, name=name)
class NoisyRoundedNormal(NoisyRoundAdapter):
"""Rounded normal distribution + uniform noise."""
def __init__(self, name="NoisyRoundedNormal", **kwargs):
super().__init__(base=tfp.distributions.Normal(**kwargs), name=name)
class SoftRoundAdapter(MonotonicAdapter):
"""Differentiable approximation to round."""
def __init__(self, base, alpha, name="SoftRoundAdapter"):
"""Initializer.
Arguments:
base: A `tfp.distributions.Distribution` object representing a
continuous-valued random variable.
alpha: Float or tf.Tensor. Controls smoothness of the approximation.
name: String. A name for this distribution.
"""
super().__init__(base=base, name=name)
self._alpha = alpha
def transform(self, x):
return soft_round_ops.soft_round(x, self._alpha)
def inverse_transform(self, y):
return soft_round_ops.soft_round_inverse(y, self._alpha)
class NoisySoftRoundAdapter(uniform_noise.UniformNoiseAdapter):
"""Uniform noise + differentiable approximation to round."""
def __init__(self, base, alpha, name="NoisySoftRoundAdapter"):
"""Initializer.
Arguments:
base: A `tfp.distributions.Distribution` object representing a
continuous-valued random variable.
alpha: Float or tf.Tensor. Controls smoothness of soft round.
name: String. A name for this distribution.
"""
super().__init__(SoftRoundAdapter(base, alpha), name=name)
class NoisySoftRoundedNormal(NoisySoftRoundAdapter):
"""Soft rounded normal distribution + uniform noise."""
def __init__(self, alpha=5.0, name="NoisySoftRoundedNormal", **kwargs):
super().__init__(
base=tfp.distributions.Normal(**kwargs),
alpha=alpha,
name=name)
class NoisySoftRoundedDeepFactorized(NoisySoftRoundAdapter):
"""Soft rounded deep factorized distribution + uniform noise."""
def __init__(self,
alpha=5.0,
name="NoisySoftRoundedDeepFactorized",
**kwargs):
super().__init__(
base=deep_factorized.DeepFactorized(**kwargs),
alpha=alpha,
name=name)
| 3,252 | 0 | 674 |
f3002145209ee8b737ec2f4d286e4a38f0f7d345 | 262 | py | Python | src/dal_jal/views.py | pandabuilder/django-autocomplete-light | 41f699aadaa6214acd5d947b717394b1237a7223 | [
"MIT"
] | null | null | null | src/dal_jal/views.py | pandabuilder/django-autocomplete-light | 41f699aadaa6214acd5d947b717394b1237a7223 | [
"MIT"
] | null | null | null | src/dal_jal/views.py | pandabuilder/django-autocomplete-light | 41f699aadaa6214acd5d947b717394b1237a7223 | [
"MIT"
] | null | null | null |
from django.views import generic
class JalQuerySetView(generic.ListView):
"""View mixin to render a JSON response for Select2."""
def render_to_response(self, context):
"""Return a JSON response in Select2 format."""
return 'hello !'
| 23.818182 | 59 | 0.687023 |
from django.views import generic
class JalQuerySetView(generic.ListView):
"""View mixin to render a JSON response for Select2."""
def render_to_response(self, context):
"""Return a JSON response in Select2 format."""
return 'hello !'
| 0 | 0 | 0 |
620fcc7b4276e841a11ec20ede451a0949a8feb1 | 714 | py | Python | problems/A/TelephoneNumber.py | deveshbajpai19/CodeForces | 707b374f03012ec68054841f791d48b33ae4ef1b | [
"MIT"
] | 55 | 2016-06-19T05:45:15.000Z | 2022-03-31T15:18:53.000Z | problems/A/TelephoneNumber.py | farhadcu/CodeForces-2 | 707b374f03012ec68054841f791d48b33ae4ef1b | [
"MIT"
] | null | null | null | problems/A/TelephoneNumber.py | farhadcu/CodeForces-2 | 707b374f03012ec68054841f791d48b33ae4ef1b | [
"MIT"
] | 25 | 2016-07-29T13:03:15.000Z | 2021-09-17T01:45:45.000Z | __author__ = 'Devesh Bajpai'
'''
https://codeforces.com/problemset/problem/1167/A
Solution: From the first occurrence of 8 in the given string s, we should have at least 10 characters. Say that 8 exists
on ith index. Then n - 1 - i + 1 = n - i would give the length of the longest string starting with 8. That should be
at least 11 characters. The extra ones (>11) can be deleted by the operations.
'''
if __name__ == "__main__":
t = int(raw_input())
for _ in xrange(0, t):
n = int(raw_input())
s = raw_input()
print solve(n, s)
| 23.032258 | 120 | 0.602241 | __author__ = 'Devesh Bajpai'
'''
https://codeforces.com/problemset/problem/1167/A
Solution: From the first occurrence of 8 in the given string s, we should have at least 10 characters. Say that 8 exists
on ith index. Then n - 1 - i + 1 = n - i would give the length of the longest string starting with 8. That should be
at least 11 characters. The extra ones (>11) can be deleted by the operations.
'''
def solve(n, s):
i = 0
while i < n:
if s[i] == '8':
break
i += 1
return "YES" if n - i >= 11 else "NO"
if __name__ == "__main__":
t = int(raw_input())
for _ in xrange(0, t):
n = int(raw_input())
s = raw_input()
print solve(n, s)
| 123 | 0 | 23 |
5de25e56d03ec7529b49111e303f4cbcadddf004 | 1,952 | py | Python | designate-8.0.0/designate/backend/impl_powerdns/migrate_repo/versions/009_cascade_domain_deletes.py | scottwedge/OpenStack-Stein | 7077d1f602031dace92916f14e36b124f474de15 | [
"Apache-2.0"
] | null | null | null | designate-8.0.0/designate/backend/impl_powerdns/migrate_repo/versions/009_cascade_domain_deletes.py | scottwedge/OpenStack-Stein | 7077d1f602031dace92916f14e36b124f474de15 | [
"Apache-2.0"
] | 5 | 2019-08-14T06:46:03.000Z | 2021-12-13T20:01:25.000Z | designate-8.0.0/designate/backend/impl_powerdns/migrate_repo/versions/009_cascade_domain_deletes.py | scottwedge/OpenStack-Stein | 7077d1f602031dace92916f14e36b124f474de15 | [
"Apache-2.0"
] | 2 | 2020-03-15T01:24:15.000Z | 2020-07-22T20:34:26.000Z | # Copyright 2014 Hewlett-Packard Development Company, L.P.
#
# Author: Kiall Mac Innes <kiall@hpe.com>
#
# 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.
from sqlalchemy import MetaData, Table
from migrate.changeset.constraint import ForeignKeyConstraint
meta = MetaData()
| 30.5 | 75 | 0.717213 | # Copyright 2014 Hewlett-Packard Development Company, L.P.
#
# Author: Kiall Mac Innes <kiall@hpe.com>
#
# 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.
from sqlalchemy import MetaData, Table
from migrate.changeset.constraint import ForeignKeyConstraint
meta = MetaData()
def upgrade(migrate_engine):
meta.bind = migrate_engine
domains_table = Table('domains', meta, autoload=True)
domainmetadata_table = Table('domainmetadata', meta, autoload=True)
records_table = Table('records', meta, autoload=True)
records_fk = ForeignKeyConstraint(
[records_table.c.domain_id],
[domains_table.c.id],
ondelete="CASCADE")
records_fk.create()
domainmetadata_fk = ForeignKeyConstraint(
[domainmetadata_table.c.domain_id],
[domains_table.c.id],
ondelete="CASCADE")
domainmetadata_fk.create()
def downgrade(migrate_engine):
meta.bind = migrate_engine
domains_table = Table('domains', meta, autoload=True)
domainmetadata_table = Table('domainmetadata', meta, autoload=True)
records_table = Table('records', meta, autoload=True)
records_fk = ForeignKeyConstraint(
[records_table.c.domain_id],
[domains_table.c.id],
ondelete="CASCADE")
records_fk.drop()
domainmetadata_fk = ForeignKeyConstraint(
[domainmetadata_table.c.domain_id],
[domains_table.c.id],
ondelete="CASCADE")
domainmetadata_fk.drop()
| 1,134 | 0 | 46 |
eb12d1bb6f9cb70a43876fd387a56d535b88ed8e | 463 | py | Python | paginas/migrations/0004_publicacao_upload.py | DSheridanmt/Safety-Life | 522578858f8e063e14d0274de008c345ef2c0a75 | [
"MIT"
] | null | null | null | paginas/migrations/0004_publicacao_upload.py | DSheridanmt/Safety-Life | 522578858f8e063e14d0274de008c345ef2c0a75 | [
"MIT"
] | null | null | null | paginas/migrations/0004_publicacao_upload.py | DSheridanmt/Safety-Life | 522578858f8e063e14d0274de008c345ef2c0a75 | [
"MIT"
] | null | null | null | # Generated by Django 4.0 on 2022-03-08 23:22
from django.db import migrations, models
| 23.15 | 72 | 0.62203 | # Generated by Django 4.0 on 2022-03-08 23:22
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('paginas', '0003_remove_publicacao_data_atualizacao_and_more'),
]
operations = [
migrations.AddField(
model_name='publicacao',
name='upload',
field=models.FileField(default=1, upload_to='midia/'),
preserve_default=False,
),
]
| 0 | 351 | 23 |
9f8596434453fada0ce44edab6fb4e92888b37c4 | 1,198 | py | Python | .github/workflows/patch-asyncio.py | jwj019/SimpleITK-Notebooks | ade3741c3fa807a35b239f68b83f39c5f67e099f | [
"Apache-2.0"
] | 657 | 2015-02-20T13:50:28.000Z | 2022-03-31T11:42:22.000Z | .github/workflows/patch-asyncio.py | jwj019/SimpleITK-Notebooks | ade3741c3fa807a35b239f68b83f39c5f67e099f | [
"Apache-2.0"
] | 100 | 2015-02-19T18:53:06.000Z | 2022-03-29T15:20:39.000Z | .github/workflows/patch-asyncio.py | jwj019/SimpleITK-Notebooks | ade3741c3fa807a35b239f68b83f39c5f67e099f | [
"Apache-2.0"
] | 313 | 2015-01-29T20:23:36.000Z | 2022-03-23T06:34:21.000Z | from __future__ import print_function
import fileinput
import asyncio
asyncLib = asyncio.__file__
lineNum = 0
# This script is used to address an issue on Windows with asyncio in the Tornado web server.
# See links below for more information
# https://github.com/tornadoweb/tornado/issues/2608
# https://www.tornadoweb.org/en/stable/releases/v6.0.4.html#general-changes
# https://bugs.python.org/issue37373
with open(asyncLib, 'r+') as origLib:
lines = origLib.readlines()
for line in lines:
lineNum += 1
if line.startswith('import sys'):
print('Found 1.')
print(line, end='')
importLine = lineNum
elif line.startswith(' from .windows_events import'):
print('Found 2.')
print(line, end='')
asyncLine = lineNum
if importLine is not None and asyncLine is not None:
origLib = fileinput.input(asyncLib, inplace = True)
for n, line in enumerate(origLib, start=1):
if n == importLine:
print('import asyncio')
if n == asyncLine + 1:
print(' asyncio.set_event_loop_policy(asyncio.WindowsSelectorEventLoopPolicy())')
print(line, end='') | 35.235294 | 96 | 0.651085 | from __future__ import print_function
import fileinput
import asyncio
asyncLib = asyncio.__file__
lineNum = 0
# This script is used to address an issue on Windows with asyncio in the Tornado web server.
# See links below for more information
# https://github.com/tornadoweb/tornado/issues/2608
# https://www.tornadoweb.org/en/stable/releases/v6.0.4.html#general-changes
# https://bugs.python.org/issue37373
with open(asyncLib, 'r+') as origLib:
lines = origLib.readlines()
for line in lines:
lineNum += 1
if line.startswith('import sys'):
print('Found 1.')
print(line, end='')
importLine = lineNum
elif line.startswith(' from .windows_events import'):
print('Found 2.')
print(line, end='')
asyncLine = lineNum
if importLine is not None and asyncLine is not None:
origLib = fileinput.input(asyncLib, inplace = True)
for n, line in enumerate(origLib, start=1):
if n == importLine:
print('import asyncio')
if n == asyncLine + 1:
print(' asyncio.set_event_loop_policy(asyncio.WindowsSelectorEventLoopPolicy())')
print(line, end='') | 0 | 0 | 0 |
599ae95603603736cbe31f2844356305a075fb9d | 629 | py | Python | wordhell/Part_1/wordhell.py | gcp825/code_challenges | 97de884260f23f1e69d4867d52507a1be01e8824 | [
"MIT"
] | null | null | null | wordhell/Part_1/wordhell.py | gcp825/code_challenges | 97de884260f23f1e69d4867d52507a1be01e8824 | [
"MIT"
] | null | null | null | wordhell/Part_1/wordhell.py | gcp825/code_challenges | 97de884260f23f1e69d4867d52507a1be01e8824 | [
"MIT"
] | null | null | null | from collections import Counter
| 34.944444 | 126 | 0.586645 | from collections import Counter
def get_result(guess,answer):
guess, answer, colours = (guess.upper(), answer.upper(), [])
letters = list(zip(guess[:len(answer)],answer))[::-1]
greyout = [g for g,x in Counter(guess).items() for a,y in Counter(answer).items() for z in range(x-y) if g == a and x > y]
for guessed, actual in letters:
if guessed == actual: colours += ['GREEN']
elif guessed in greyout: colours += ['GREY']; greyout.remove(guessed)
elif guessed in answer: colours += ['YELLOW']
else: colours += ['GREY']
return colours[::-1]
| 570 | 0 | 23 |
74ce5869c1273641db819c7df939bc619b77d924 | 1,130 | py | Python | pancan_fusion/fusion_outliers/abundance_calculations.py | ding-lab/griffin-fusion | cb2970f448dd3f50c678fcb755daa8f0b5a005a2 | [
"MIT"
] | 4 | 2019-09-02T15:03:22.000Z | 2021-12-03T19:28:50.000Z | pancan_fusion/fusion_outliers/abundance_calculations.py | ding-lab/griffin-fusion | cb2970f448dd3f50c678fcb755daa8f0b5a005a2 | [
"MIT"
] | null | null | null | pancan_fusion/fusion_outliers/abundance_calculations.py | ding-lab/griffin-fusion | cb2970f448dd3f50c678fcb755daa8f0b5a005a2 | [
"MIT"
] | 2 | 2020-09-15T02:37:22.000Z | 2020-09-29T09:24:27.000Z | import sys
import numpy
ensg_gene = open(sys.argv[1], 'r')
abun_file = open(sys.argv[2], 'r')
output_file = open(sys.argv[3],'w')
#set up ensg dict
ensg_dict = {}
gene_dict = {}
gene_list = []
for line in ensg_gene:
ensg, gene = line.strip().split()
ensg_dict[ ensg ] = gene
if gene not in gene_dict:
gene_dict[gene] = [ ensg, 0 ]
else:
gene_dict[gene][0] += ','+ensg
if gene not in gene_list:
gene_list.append(gene)
ensg_gene.close()
#add abundances to ensg_dict
abun_file.readline() #skip first line
for line in abun_file:
ensg = line.strip().split()[0].split('_')[0]
tpm = float(line.strip().split()[4])
if ensg in ensg_dict:
gene = ensg_dict[ ensg ]
gene_dict[gene][1] += tpm
abun_file.close()
#convert gene level tpm to log10(tpm+1)
for gene in gene_dict.keys():
gene_dict[gene].append( numpy.log10(gene_dict[gene][1] + 1) )
#print output file
output_file.write( '\t'.join( ['ensg', 'gene', 'tpm','log10tpm'] ) + '\n')
for gene in gene_list:
output_file.write( '\t'.join( [ gene_dict[gene][0], gene, str(gene_dict[gene][1]), str(gene_dict[gene][2]) ] )+ '\n')
output_file.close()
| 26.904762 | 119 | 0.658407 | import sys
import numpy
ensg_gene = open(sys.argv[1], 'r')
abun_file = open(sys.argv[2], 'r')
output_file = open(sys.argv[3],'w')
#set up ensg dict
ensg_dict = {}
gene_dict = {}
gene_list = []
for line in ensg_gene:
ensg, gene = line.strip().split()
ensg_dict[ ensg ] = gene
if gene not in gene_dict:
gene_dict[gene] = [ ensg, 0 ]
else:
gene_dict[gene][0] += ','+ensg
if gene not in gene_list:
gene_list.append(gene)
ensg_gene.close()
#add abundances to ensg_dict
abun_file.readline() #skip first line
for line in abun_file:
ensg = line.strip().split()[0].split('_')[0]
tpm = float(line.strip().split()[4])
if ensg in ensg_dict:
gene = ensg_dict[ ensg ]
gene_dict[gene][1] += tpm
abun_file.close()
#convert gene level tpm to log10(tpm+1)
for gene in gene_dict.keys():
gene_dict[gene].append( numpy.log10(gene_dict[gene][1] + 1) )
#print output file
output_file.write( '\t'.join( ['ensg', 'gene', 'tpm','log10tpm'] ) + '\n')
for gene in gene_list:
output_file.write( '\t'.join( [ gene_dict[gene][0], gene, str(gene_dict[gene][1]), str(gene_dict[gene][2]) ] )+ '\n')
output_file.close()
| 0 | 0 | 0 |
06149c92025f132045f0478d86818f166b5de67f | 4,250 | py | Python | src/silx/io/test/test_write_to_h5.py | tifuchs/silx | 4b8b9e58ecd6fd4ca0ae80f2e74b956b26bcc3f7 | [
"CC0-1.0",
"MIT"
] | 94 | 2016-03-04T17:25:53.000Z | 2022-03-18T18:05:23.000Z | src/silx/io/test/test_write_to_h5.py | tifuchs/silx | 4b8b9e58ecd6fd4ca0ae80f2e74b956b26bcc3f7 | [
"CC0-1.0",
"MIT"
] | 2,841 | 2016-01-21T09:06:49.000Z | 2022-03-18T14:53:56.000Z | src/silx/io/test/test_write_to_h5.py | t20100/silx | 035cb286dd46f3f0cb3f819a3cfb6ce253c9933b | [
"CC0-1.0",
"MIT"
] | 71 | 2015-09-30T08:35:35.000Z | 2022-03-16T07:16:28.000Z | # coding: utf-8
# /*##########################################################################
# Copyright (C) 2021 European Synchrotron Radiation Facility
#
# Permission is hereby granted, free of charge, to any person obtaining a copy
# of this software and associated documentation files (the "Software"), to deal
# in the Software without restriction, including without limitation the rights
# to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
# copies of the Software, and to permit persons to whom the Software is
# furnished to do so, subject to the following conditions:
#
# The above copyright notice and this permission notice shall be included in
# all copies or substantial portions of the Software.
#
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
# THE SOFTWARE.
#
# ############################################################################*/
"""Test silx.io.convert.write_to_h5"""
import h5py
import numpy
from silx.io import spech5
from silx.io.convert import write_to_h5
from silx.io.dictdump import h5todict
from silx.io import commonh5
from silx.io.spech5 import SpecH5
def test_with_commonh5(tmp_path):
"""Test write_to_h5 with commonh5 input"""
fobj = commonh5.File("filename.txt", mode="w")
group = fobj.create_group("group")
dataset = group.create_dataset("dataset", data=numpy.array(50))
group["soft_link"] = dataset # Create softlink
output_filepath = tmp_path / "output.h5"
write_to_h5(fobj, str(output_filepath))
assert h5todict(str(output_filepath)) == {
'group': {'dataset': numpy.array(50), 'soft_link': numpy.array(50)},
}
with h5py.File(output_filepath, mode="r") as h5file:
soft_link = h5file.get("/group/soft_link", getlink=True)
assert isinstance(soft_link, h5py.SoftLink)
assert soft_link.path == "/group/dataset"
def test_with_hdf5(tmp_path):
"""Test write_to_h5 with HDF5 file input"""
filepath = tmp_path / "base.h5"
with h5py.File(filepath, mode="w") as h5file:
h5file["group/dataset"] = 50
h5file["group/soft_link"] = h5py.SoftLink("/group/dataset")
h5file["group/external_link"] = h5py.ExternalLink("base.h5", "/group/dataset")
output_filepath = tmp_path / "output.h5"
write_to_h5(str(filepath), str(output_filepath))
assert h5todict(str(output_filepath)) == {
'group': {'dataset': 50, 'soft_link': 50},
}
with h5py.File(output_filepath, mode="r") as h5file:
soft_link = h5file.get("group/soft_link", getlink=True)
assert isinstance(soft_link, h5py.SoftLink)
assert soft_link.path == "/group/dataset"
def test_with_spech5(tmp_path):
"""Test write_to_h5 with SpecH5 input"""
filepath = tmp_path / "file.spec"
filepath.write_bytes(
bytes(
"""#F /tmp/sf.dat
#S 1 cmd
#L a b
1 2
""",
encoding='ascii')
)
output_filepath = tmp_path / "output.h5"
with spech5.SpecH5(str(filepath)) as spech5file:
write_to_h5(spech5file, str(output_filepath))
print(h5todict(str(output_filepath)))
assert_equal(h5todict(str(output_filepath)), {
'1.1': {
'instrument': {
'positioners': {},
'specfile': {
'file_header': ['#F /tmp/sf.dat'],
'scan_header': ['#S 1 cmd', '#L a b'],
},
},
'measurement': {
'a': [1.],
'b': [2.],
},
'start_time': '',
'title': 'cmd',
},
})
| 35.714286 | 86 | 0.624941 | # coding: utf-8
# /*##########################################################################
# Copyright (C) 2021 European Synchrotron Radiation Facility
#
# Permission is hereby granted, free of charge, to any person obtaining a copy
# of this software and associated documentation files (the "Software"), to deal
# in the Software without restriction, including without limitation the rights
# to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
# copies of the Software, and to permit persons to whom the Software is
# furnished to do so, subject to the following conditions:
#
# The above copyright notice and this permission notice shall be included in
# all copies or substantial portions of the Software.
#
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
# THE SOFTWARE.
#
# ############################################################################*/
"""Test silx.io.convert.write_to_h5"""
import h5py
import numpy
from silx.io import spech5
from silx.io.convert import write_to_h5
from silx.io.dictdump import h5todict
from silx.io import commonh5
from silx.io.spech5 import SpecH5
def test_with_commonh5(tmp_path):
"""Test write_to_h5 with commonh5 input"""
fobj = commonh5.File("filename.txt", mode="w")
group = fobj.create_group("group")
dataset = group.create_dataset("dataset", data=numpy.array(50))
group["soft_link"] = dataset # Create softlink
output_filepath = tmp_path / "output.h5"
write_to_h5(fobj, str(output_filepath))
assert h5todict(str(output_filepath)) == {
'group': {'dataset': numpy.array(50), 'soft_link': numpy.array(50)},
}
with h5py.File(output_filepath, mode="r") as h5file:
soft_link = h5file.get("/group/soft_link", getlink=True)
assert isinstance(soft_link, h5py.SoftLink)
assert soft_link.path == "/group/dataset"
def test_with_hdf5(tmp_path):
"""Test write_to_h5 with HDF5 file input"""
filepath = tmp_path / "base.h5"
with h5py.File(filepath, mode="w") as h5file:
h5file["group/dataset"] = 50
h5file["group/soft_link"] = h5py.SoftLink("/group/dataset")
h5file["group/external_link"] = h5py.ExternalLink("base.h5", "/group/dataset")
output_filepath = tmp_path / "output.h5"
write_to_h5(str(filepath), str(output_filepath))
assert h5todict(str(output_filepath)) == {
'group': {'dataset': 50, 'soft_link': 50},
}
with h5py.File(output_filepath, mode="r") as h5file:
soft_link = h5file.get("group/soft_link", getlink=True)
assert isinstance(soft_link, h5py.SoftLink)
assert soft_link.path == "/group/dataset"
def test_with_spech5(tmp_path):
"""Test write_to_h5 with SpecH5 input"""
filepath = tmp_path / "file.spec"
filepath.write_bytes(
bytes(
"""#F /tmp/sf.dat
#S 1 cmd
#L a b
1 2
""",
encoding='ascii')
)
output_filepath = tmp_path / "output.h5"
with spech5.SpecH5(str(filepath)) as spech5file:
write_to_h5(spech5file, str(output_filepath))
print(h5todict(str(output_filepath)))
def assert_equal(item1, item2):
if isinstance(item1, dict):
assert tuple(item1.keys()) == tuple(item2.keys())
for key in item1.keys():
assert_equal(item1[key], item2[key])
else:
numpy.array_equal(item1, item2)
assert_equal(h5todict(str(output_filepath)), {
'1.1': {
'instrument': {
'positioners': {},
'specfile': {
'file_header': ['#F /tmp/sf.dat'],
'scan_header': ['#S 1 cmd', '#L a b'],
},
},
'measurement': {
'a': [1.],
'b': [2.],
},
'start_time': '',
'title': 'cmd',
},
})
| 256 | 0 | 27 |
3dd8ff67b12a905723423a8663578b8f649a0421 | 2,044 | py | Python | robot/waffles_display.py | rsthomp/wafflesazoo | 57a2542b6bd61036efa3fff8839909f774e1dd67 | [
"MIT"
] | null | null | null | robot/waffles_display.py | rsthomp/wafflesazoo | 57a2542b6bd61036efa3fff8839909f774e1dd67 | [
"MIT"
] | null | null | null | robot/waffles_display.py | rsthomp/wafflesazoo | 57a2542b6bd61036efa3fff8839909f774e1dd67 | [
"MIT"
] | null | null | null | import pygame
import os
import time
import random
import requests
from rx import Observable, Observer
from rx.concurrency import ThreadPoolScheduler
from waffles_feels import waffles_feels
from waffles_commands import WafflesCMD
from waffles_pos import five_second_timer
print('0')
#Updates the actual displayed image based on waffle's reported emotional state.
#Helper method for retrieving images
_image_library = {}
#starting the display
print('0')
pygame.init()
screen = pygame.display.set_mode((400, 300))
done = False
clock = pygame.time.Clock()
CMD = WafflesCMD()
print('1')
#Creates an observable that publishes the same stream to multiple observers
emote_gen = Observable.create(waffles_feels).publish()
print('2')
#The display subscriber
disp = emote_gen.subscribe(UpdateDisplay)
print('3')
#The serial communication subscriber
pool_sch = ThreadPoolScheduler()
pos_gen = Observable.create(five_second_timer).subscribe_on(pool_sch)
emote_and_turn = Observable.merge(emote_gen, pos_gen)
print('q')
cmd = emote_and_turn.subscribe(CMD)
print('4')
emote_gen.connect()
emote_and_turn.connect()
print('5')
| 24.926829 | 102 | 0.728474 | import pygame
import os
import time
import random
import requests
from rx import Observable, Observer
from rx.concurrency import ThreadPoolScheduler
from waffles_feels import waffles_feels
from waffles_commands import WafflesCMD
from waffles_pos import five_second_timer
print('0')
#Updates the actual displayed image based on waffle's reported emotional state.
class UpdateDisplay(Observer):
def on_next(x):
screen.fill((255, 255, 255))
#Quits when the screen is closed
for event in pygame.event.get():
if event.type == pygame.QUIT:
exit(0)
#Loads the appropriate image for the emotion
screen.blit(pygame.transform.scale(get_image('../faces/waffles_' + x + '.png'), (400, 300)), (0, 0))
#Updates the website with the new image
requests.post("http://wafflesazoo.mit.edu/set_mood", json=x)
pygame.display.flip()
def on_error(error):
print("Got error: %s" % error)
def on_completed(self):
print("Sequence completed")
#Helper method for retrieving images
_image_library = {}
def get_image(path):
global _image_library
image = _image_library.get(path)
if image == None:
canonicalized_path = path.replace('/', os.sep).replace('\\', os.sep)
image = pygame.image.load(canonicalized_path)
_image_library[path] = image
return image
#starting the display
print('0')
pygame.init()
screen = pygame.display.set_mode((400, 300))
done = False
clock = pygame.time.Clock()
CMD = WafflesCMD()
print('1')
#Creates an observable that publishes the same stream to multiple observers
emote_gen = Observable.create(waffles_feels).publish()
print('2')
#The display subscriber
disp = emote_gen.subscribe(UpdateDisplay)
print('3')
#The serial communication subscriber
pool_sch = ThreadPoolScheduler()
pos_gen = Observable.create(five_second_timer).subscribe_on(pool_sch)
emote_and_turn = Observable.merge(emote_gen, pos_gen)
print('q')
cmd = emote_and_turn.subscribe(CMD)
print('4')
emote_gen.connect()
emote_and_turn.connect()
print('5')
| 795 | 9 | 115 |
fd0600b8353e414fc31968043f51d0d27fbf8f12 | 22,203 | py | Python | pm/models/situ_social_activity_family.py | aosojnik/pipeline-manager-features-models | e5232f1c1b2073253a1c505dc9fff0d3d839dd6c | [
"MIT"
] | null | null | null | pm/models/situ_social_activity_family.py | aosojnik/pipeline-manager-features-models | e5232f1c1b2073253a1c505dc9fff0d3d839dd6c | [
"MIT"
] | null | null | null | pm/models/situ_social_activity_family.py | aosojnik/pipeline-manager-features-models | e5232f1c1b2073253a1c505dc9fff0d3d839dd6c | [
"MIT"
] | null | null | null | ##################################################################################
##########--this is an autogenerated python model definition for proDEX--#########
##--original file: Family_Assessment_v05_forprodex.dxi --##
##################################################################################
from .lib.proDEX import *
situ_social_activity_family = Node()
Relative_activity_Family = Node()
calls_last_7_days = Node()
visits_last_7_days = Node()
together_outside_last_7_days = Node()
Absolute_daily_activity_Family = Node()
feat_calls_count_family_relative = Atrib()
feat_calls_duration_family_relative = Atrib()
feat_visits_family_relative_past_week = Atrib()
feat_visits_family_relative = Atrib()
feat_outside_family_relative_past_week = Atrib()
feat_outside_family_relative = Atrib()
feat_calls_count_family_weekly_vs_goal = Atrib()
feat_visits_count_family_weekly_vs_goal = Atrib()
feat_outside_count_family_weekly_vs_goal = Atrib()
situ_social_activity_family.setName('situ_social_activity_family')
Relative_activity_Family.setName('Relative_activity_Family')
calls_last_7_days.setName('calls_last_7_days')
visits_last_7_days.setName('visits_last_7_days')
together_outside_last_7_days.setName('together_outside_last_7_days')
Absolute_daily_activity_Family.setName('Absolute_daily_activity_Family')
feat_calls_count_family_relative.setName('feat_calls_count_family_relative')
feat_calls_duration_family_relative.setName('feat_calls_duration_family_relative')
feat_visits_family_relative_past_week.setName('feat_visits_family_relative_past_week')
feat_visits_family_relative.setName('feat_visits_family_relative')
feat_outside_family_relative_past_week.setName('feat_outside_family_relative_past_week')
feat_outside_family_relative.setName('feat_outside_family_relative')
feat_calls_count_family_weekly_vs_goal.setName('feat_calls_count_family_weekly_vs_goal')
feat_visits_count_family_weekly_vs_goal.setName('feat_visits_count_family_weekly_vs_goal')
feat_outside_count_family_weekly_vs_goal.setName('feat_outside_count_family_weekly_vs_goal')
situ_social_activity_family.setValues(['very_low', 'low', 'medium', 'high', 'very_high'])
Relative_activity_Family.setValues(['high decrease', 'decrease', 'stable', 'increase', 'high increase'])
calls_last_7_days.setValues(['decrease', 'stable', 'increase'])
visits_last_7_days.setValues(['decrease', 'stable', 'increase'])
together_outside_last_7_days.setValues(['decrease', 'stable', 'increase'])
Absolute_daily_activity_Family.setValues(['very low', 'low', 'medium', 'high', 'very high'])
feat_calls_count_family_relative.setValues(['decrease', 'stable', 'increase'])
feat_calls_duration_family_relative.setValues(['decrease', 'stable', 'increase'])
feat_visits_family_relative_past_week.setValues(['decrease', 'stable', 'increase'])
feat_visits_family_relative.setValues(['decrease', 'stable', 'increase'])
feat_outside_family_relative_past_week.setValues(['decrease', 'stable', 'increase'])
feat_outside_family_relative.setValues(['decrease', 'stable', 'increase'])
feat_calls_count_family_weekly_vs_goal.setValues(['low', 'medium', 'high'])
feat_visits_count_family_weekly_vs_goal.setValues(['low', 'medium', 'high'])
feat_outside_count_family_weekly_vs_goal.setValues(['low', 'medium', 'high'])
situ_social_activity_family.addChild(Relative_activity_Family)
Relative_activity_Family.setParent(situ_social_activity_family)
situ_social_activity_family.addChild(Absolute_daily_activity_Family)
Absolute_daily_activity_Family.setParent(situ_social_activity_family)
Relative_activity_Family.addChild(calls_last_7_days)
calls_last_7_days.setParent(Relative_activity_Family)
Relative_activity_Family.addChild(visits_last_7_days)
visits_last_7_days.setParent(Relative_activity_Family)
Relative_activity_Family.addChild(together_outside_last_7_days)
together_outside_last_7_days.setParent(Relative_activity_Family)
calls_last_7_days.addChild(feat_calls_count_family_relative)
feat_calls_count_family_relative.setParent(calls_last_7_days)
calls_last_7_days.addChild(feat_calls_duration_family_relative)
feat_calls_duration_family_relative.setParent(calls_last_7_days)
visits_last_7_days.addChild(feat_visits_family_relative_past_week)
feat_visits_family_relative_past_week.setParent(visits_last_7_days)
visits_last_7_days.addChild(feat_visits_family_relative)
feat_visits_family_relative.setParent(visits_last_7_days)
together_outside_last_7_days.addChild(feat_outside_family_relative_past_week)
feat_outside_family_relative_past_week.setParent(together_outside_last_7_days)
together_outside_last_7_days.addChild(feat_outside_family_relative)
feat_outside_family_relative.setParent(together_outside_last_7_days)
Absolute_daily_activity_Family.addChild(feat_calls_count_family_weekly_vs_goal)
feat_calls_count_family_weekly_vs_goal.setParent(Absolute_daily_activity_Family)
Absolute_daily_activity_Family.addChild(feat_visits_count_family_weekly_vs_goal)
feat_visits_count_family_weekly_vs_goal.setParent(Absolute_daily_activity_Family)
Absolute_daily_activity_Family.addChild(feat_outside_count_family_weekly_vs_goal)
feat_outside_count_family_weekly_vs_goal.setParent(Absolute_daily_activity_Family)
situ_social_activity_family.addFunctionRow([{Relative_activity_Family:'high decrease', Absolute_daily_activity_Family:'very low'}, 'very_low'])
situ_social_activity_family.addFunctionRow([{Relative_activity_Family:'high decrease', Absolute_daily_activity_Family:'low'}, 'very_low'])
situ_social_activity_family.addFunctionRow([{Relative_activity_Family:'high decrease', Absolute_daily_activity_Family:'medium'}, 'low'])
situ_social_activity_family.addFunctionRow([{Relative_activity_Family:'high decrease', Absolute_daily_activity_Family:'high'}, 'medium'])
situ_social_activity_family.addFunctionRow([{Relative_activity_Family:'high decrease', Absolute_daily_activity_Family:'very high'}, 'high'])
situ_social_activity_family.addFunctionRow([{Relative_activity_Family:'decrease', Absolute_daily_activity_Family:'very low'}, 'very_low'])
situ_social_activity_family.addFunctionRow([{Relative_activity_Family:'decrease', Absolute_daily_activity_Family:'low'}, 'low'])
situ_social_activity_family.addFunctionRow([{Relative_activity_Family:'decrease', Absolute_daily_activity_Family:'medium'}, 'medium'])
situ_social_activity_family.addFunctionRow([{Relative_activity_Family:'decrease', Absolute_daily_activity_Family:'high'}, 'high'])
situ_social_activity_family.addFunctionRow([{Relative_activity_Family:'decrease', Absolute_daily_activity_Family:'very high'}, 'very_high'])
situ_social_activity_family.addFunctionRow([{Relative_activity_Family:'stable', Absolute_daily_activity_Family:'very low'}, 'very_low'])
situ_social_activity_family.addFunctionRow([{Relative_activity_Family:'stable', Absolute_daily_activity_Family:'low'}, 'low'])
situ_social_activity_family.addFunctionRow([{Relative_activity_Family:'stable', Absolute_daily_activity_Family:'medium'}, 'medium'])
situ_social_activity_family.addFunctionRow([{Relative_activity_Family:'stable', Absolute_daily_activity_Family:'high'}, 'high'])
situ_social_activity_family.addFunctionRow([{Relative_activity_Family:'stable', Absolute_daily_activity_Family:'very high'}, 'very_high'])
situ_social_activity_family.addFunctionRow([{Relative_activity_Family:'increase', Absolute_daily_activity_Family:'very low'}, 'very_low'])
situ_social_activity_family.addFunctionRow([{Relative_activity_Family:'increase', Absolute_daily_activity_Family:'low'}, 'low'])
situ_social_activity_family.addFunctionRow([{Relative_activity_Family:'increase', Absolute_daily_activity_Family:'medium'}, 'medium'])
situ_social_activity_family.addFunctionRow([{Relative_activity_Family:'increase', Absolute_daily_activity_Family:'high'}, 'high'])
situ_social_activity_family.addFunctionRow([{Relative_activity_Family:'increase', Absolute_daily_activity_Family:'very high'}, 'very_high'])
situ_social_activity_family.addFunctionRow([{Relative_activity_Family:'high increase', Absolute_daily_activity_Family:'very low'}, 'low'])
situ_social_activity_family.addFunctionRow([{Relative_activity_Family:'high increase', Absolute_daily_activity_Family:'low'}, 'medium'])
situ_social_activity_family.addFunctionRow([{Relative_activity_Family:'high increase', Absolute_daily_activity_Family:'medium'}, 'high'])
situ_social_activity_family.addFunctionRow([{Relative_activity_Family:'high increase', Absolute_daily_activity_Family:'high'}, 'very_high'])
situ_social_activity_family.addFunctionRow([{Relative_activity_Family:'high increase', Absolute_daily_activity_Family:'very high'}, 'very_high'])
Relative_activity_Family.addFunctionRow([{calls_last_7_days:'decrease', visits_last_7_days:'decrease', together_outside_last_7_days:'decrease'}, 'high decrease'])
Relative_activity_Family.addFunctionRow([{calls_last_7_days:'decrease', visits_last_7_days:'decrease', together_outside_last_7_days:'stable'}, 'high decrease'])
Relative_activity_Family.addFunctionRow([{calls_last_7_days:'decrease', visits_last_7_days:'decrease', together_outside_last_7_days:'increase'}, 'decrease'])
Relative_activity_Family.addFunctionRow([{calls_last_7_days:'decrease', visits_last_7_days:'stable', together_outside_last_7_days:'decrease'}, 'high decrease'])
Relative_activity_Family.addFunctionRow([{calls_last_7_days:'decrease', visits_last_7_days:'stable', together_outside_last_7_days:'stable'}, 'decrease'])
Relative_activity_Family.addFunctionRow([{calls_last_7_days:'decrease', visits_last_7_days:'stable', together_outside_last_7_days:'increase'}, 'stable'])
Relative_activity_Family.addFunctionRow([{calls_last_7_days:'decrease', visits_last_7_days:'increase', together_outside_last_7_days:'decrease'}, 'decrease'])
Relative_activity_Family.addFunctionRow([{calls_last_7_days:'decrease', visits_last_7_days:'increase', together_outside_last_7_days:'stable'}, 'stable'])
Relative_activity_Family.addFunctionRow([{calls_last_7_days:'decrease', visits_last_7_days:'increase', together_outside_last_7_days:'increase'}, 'increase'])
Relative_activity_Family.addFunctionRow([{calls_last_7_days:'stable', visits_last_7_days:'decrease', together_outside_last_7_days:'decrease'}, 'high decrease'])
Relative_activity_Family.addFunctionRow([{calls_last_7_days:'stable', visits_last_7_days:'decrease', together_outside_last_7_days:'stable'}, 'decrease'])
Relative_activity_Family.addFunctionRow([{calls_last_7_days:'stable', visits_last_7_days:'decrease', together_outside_last_7_days:'increase'}, 'stable'])
Relative_activity_Family.addFunctionRow([{calls_last_7_days:'stable', visits_last_7_days:'stable', together_outside_last_7_days:'decrease'}, 'decrease'])
Relative_activity_Family.addFunctionRow([{calls_last_7_days:'stable', visits_last_7_days:'stable', together_outside_last_7_days:'stable'}, 'stable'])
Relative_activity_Family.addFunctionRow([{calls_last_7_days:'stable', visits_last_7_days:'stable', together_outside_last_7_days:'increase'}, 'increase'])
Relative_activity_Family.addFunctionRow([{calls_last_7_days:'stable', visits_last_7_days:'increase', together_outside_last_7_days:'decrease'}, 'stable'])
Relative_activity_Family.addFunctionRow([{calls_last_7_days:'stable', visits_last_7_days:'increase', together_outside_last_7_days:'stable'}, 'increase'])
Relative_activity_Family.addFunctionRow([{calls_last_7_days:'stable', visits_last_7_days:'increase', together_outside_last_7_days:'increase'}, 'high increase'])
Relative_activity_Family.addFunctionRow([{calls_last_7_days:'increase', visits_last_7_days:'decrease', together_outside_last_7_days:'decrease'}, 'decrease'])
Relative_activity_Family.addFunctionRow([{calls_last_7_days:'increase', visits_last_7_days:'decrease', together_outside_last_7_days:'stable'}, 'stable'])
Relative_activity_Family.addFunctionRow([{calls_last_7_days:'increase', visits_last_7_days:'decrease', together_outside_last_7_days:'increase'}, 'increase'])
Relative_activity_Family.addFunctionRow([{calls_last_7_days:'increase', visits_last_7_days:'stable', together_outside_last_7_days:'decrease'}, 'stable'])
Relative_activity_Family.addFunctionRow([{calls_last_7_days:'increase', visits_last_7_days:'stable', together_outside_last_7_days:'stable'}, 'increase'])
Relative_activity_Family.addFunctionRow([{calls_last_7_days:'increase', visits_last_7_days:'stable', together_outside_last_7_days:'increase'}, 'high increase'])
Relative_activity_Family.addFunctionRow([{calls_last_7_days:'increase', visits_last_7_days:'increase', together_outside_last_7_days:'decrease'}, 'increase'])
Relative_activity_Family.addFunctionRow([{calls_last_7_days:'increase', visits_last_7_days:'increase', together_outside_last_7_days:'stable'}, 'high increase'])
Relative_activity_Family.addFunctionRow([{calls_last_7_days:'increase', visits_last_7_days:'increase', together_outside_last_7_days:'increase'}, 'high increase'])
calls_last_7_days.addFunctionRow([{feat_calls_count_family_relative:'decrease', feat_calls_duration_family_relative:'decrease'}, 'decrease'])
calls_last_7_days.addFunctionRow([{feat_calls_count_family_relative:'decrease', feat_calls_duration_family_relative:'stable'}, 'decrease'])
calls_last_7_days.addFunctionRow([{feat_calls_count_family_relative:'decrease', feat_calls_duration_family_relative:'increase'}, 'stable'])
calls_last_7_days.addFunctionRow([{feat_calls_count_family_relative:'stable', feat_calls_duration_family_relative:'decrease'}, 'decrease'])
calls_last_7_days.addFunctionRow([{feat_calls_count_family_relative:'stable', feat_calls_duration_family_relative:'stable'}, 'stable'])
calls_last_7_days.addFunctionRow([{feat_calls_count_family_relative:'stable', feat_calls_duration_family_relative:'increase'}, 'increase'])
calls_last_7_days.addFunctionRow([{feat_calls_count_family_relative:'increase', feat_calls_duration_family_relative:'decrease'}, 'stable'])
calls_last_7_days.addFunctionRow([{feat_calls_count_family_relative:'increase', feat_calls_duration_family_relative:'stable'}, 'increase'])
calls_last_7_days.addFunctionRow([{feat_calls_count_family_relative:'increase', feat_calls_duration_family_relative:'increase'}, 'increase'])
visits_last_7_days.addFunctionRow([{feat_visits_family_relative_past_week:'decrease', feat_visits_family_relative:'decrease'}, 'decrease'])
visits_last_7_days.addFunctionRow([{feat_visits_family_relative_past_week:'decrease', feat_visits_family_relative:'stable'}, 'stable'])
visits_last_7_days.addFunctionRow([{feat_visits_family_relative_past_week:'decrease', feat_visits_family_relative:'increase'}, 'increase'])
visits_last_7_days.addFunctionRow([{feat_visits_family_relative_past_week:'stable', feat_visits_family_relative:'decrease'}, 'decrease'])
visits_last_7_days.addFunctionRow([{feat_visits_family_relative_past_week:'stable', feat_visits_family_relative:'stable'}, 'stable'])
visits_last_7_days.addFunctionRow([{feat_visits_family_relative_past_week:'stable', feat_visits_family_relative:'increase'}, 'increase'])
visits_last_7_days.addFunctionRow([{feat_visits_family_relative_past_week:'increase', feat_visits_family_relative:'decrease'}, 'decrease'])
visits_last_7_days.addFunctionRow([{feat_visits_family_relative_past_week:'increase', feat_visits_family_relative:'stable'}, 'stable'])
visits_last_7_days.addFunctionRow([{feat_visits_family_relative_past_week:'increase', feat_visits_family_relative:'increase'}, 'increase'])
together_outside_last_7_days.addFunctionRow([{feat_outside_family_relative_past_week:'decrease', feat_outside_family_relative:'decrease'}, 'decrease'])
together_outside_last_7_days.addFunctionRow([{feat_outside_family_relative_past_week:'decrease', feat_outside_family_relative:'stable'}, 'decrease'])
together_outside_last_7_days.addFunctionRow([{feat_outside_family_relative_past_week:'decrease', feat_outside_family_relative:'increase'}, 'stable'])
together_outside_last_7_days.addFunctionRow([{feat_outside_family_relative_past_week:'stable', feat_outside_family_relative:'decrease'}, 'decrease'])
together_outside_last_7_days.addFunctionRow([{feat_outside_family_relative_past_week:'stable', feat_outside_family_relative:'stable'}, 'stable'])
together_outside_last_7_days.addFunctionRow([{feat_outside_family_relative_past_week:'stable', feat_outside_family_relative:'increase'}, 'increase'])
together_outside_last_7_days.addFunctionRow([{feat_outside_family_relative_past_week:'increase', feat_outside_family_relative:'decrease'}, 'decrease'])
together_outside_last_7_days.addFunctionRow([{feat_outside_family_relative_past_week:'increase', feat_outside_family_relative:'stable'}, 'stable'])
together_outside_last_7_days.addFunctionRow([{feat_outside_family_relative_past_week:'increase', feat_outside_family_relative:'increase'}, 'increase'])
Absolute_daily_activity_Family.addFunctionRow([{feat_calls_count_family_weekly_vs_goal:'low', feat_visits_count_family_weekly_vs_goal:'low', feat_outside_count_family_weekly_vs_goal:'low'}, 'very low'])
Absolute_daily_activity_Family.addFunctionRow([{feat_calls_count_family_weekly_vs_goal:'low', feat_visits_count_family_weekly_vs_goal:'low', feat_outside_count_family_weekly_vs_goal:'medium'}, 'very low'])
Absolute_daily_activity_Family.addFunctionRow([{feat_calls_count_family_weekly_vs_goal:'low', feat_visits_count_family_weekly_vs_goal:'low', feat_outside_count_family_weekly_vs_goal:'high'}, 'low'])
Absolute_daily_activity_Family.addFunctionRow([{feat_calls_count_family_weekly_vs_goal:'low', feat_visits_count_family_weekly_vs_goal:'medium', feat_outside_count_family_weekly_vs_goal:'low'}, 'very low'])
Absolute_daily_activity_Family.addFunctionRow([{feat_calls_count_family_weekly_vs_goal:'low', feat_visits_count_family_weekly_vs_goal:'medium', feat_outside_count_family_weekly_vs_goal:'medium'}, 'low'])
Absolute_daily_activity_Family.addFunctionRow([{feat_calls_count_family_weekly_vs_goal:'low', feat_visits_count_family_weekly_vs_goal:'medium', feat_outside_count_family_weekly_vs_goal:'high'}, 'medium'])
Absolute_daily_activity_Family.addFunctionRow([{feat_calls_count_family_weekly_vs_goal:'low', feat_visits_count_family_weekly_vs_goal:'high', feat_outside_count_family_weekly_vs_goal:'low'}, 'low'])
Absolute_daily_activity_Family.addFunctionRow([{feat_calls_count_family_weekly_vs_goal:'low', feat_visits_count_family_weekly_vs_goal:'high', feat_outside_count_family_weekly_vs_goal:'medium'}, 'medium'])
Absolute_daily_activity_Family.addFunctionRow([{feat_calls_count_family_weekly_vs_goal:'low', feat_visits_count_family_weekly_vs_goal:'high', feat_outside_count_family_weekly_vs_goal:'high'}, 'high'])
Absolute_daily_activity_Family.addFunctionRow([{feat_calls_count_family_weekly_vs_goal:'medium', feat_visits_count_family_weekly_vs_goal:'low', feat_outside_count_family_weekly_vs_goal:'low'}, 'very low'])
Absolute_daily_activity_Family.addFunctionRow([{feat_calls_count_family_weekly_vs_goal:'medium', feat_visits_count_family_weekly_vs_goal:'low', feat_outside_count_family_weekly_vs_goal:'medium'}, 'low'])
Absolute_daily_activity_Family.addFunctionRow([{feat_calls_count_family_weekly_vs_goal:'medium', feat_visits_count_family_weekly_vs_goal:'low', feat_outside_count_family_weekly_vs_goal:'high'}, 'medium'])
Absolute_daily_activity_Family.addFunctionRow([{feat_calls_count_family_weekly_vs_goal:'medium', feat_visits_count_family_weekly_vs_goal:'medium', feat_outside_count_family_weekly_vs_goal:'low'}, 'low'])
Absolute_daily_activity_Family.addFunctionRow([{feat_calls_count_family_weekly_vs_goal:'medium', feat_visits_count_family_weekly_vs_goal:'medium', feat_outside_count_family_weekly_vs_goal:'medium'}, 'medium'])
Absolute_daily_activity_Family.addFunctionRow([{feat_calls_count_family_weekly_vs_goal:'medium', feat_visits_count_family_weekly_vs_goal:'medium', feat_outside_count_family_weekly_vs_goal:'high'}, 'high'])
Absolute_daily_activity_Family.addFunctionRow([{feat_calls_count_family_weekly_vs_goal:'medium', feat_visits_count_family_weekly_vs_goal:'high', feat_outside_count_family_weekly_vs_goal:'low'}, 'medium'])
Absolute_daily_activity_Family.addFunctionRow([{feat_calls_count_family_weekly_vs_goal:'medium', feat_visits_count_family_weekly_vs_goal:'high', feat_outside_count_family_weekly_vs_goal:'medium'}, 'high'])
Absolute_daily_activity_Family.addFunctionRow([{feat_calls_count_family_weekly_vs_goal:'medium', feat_visits_count_family_weekly_vs_goal:'high', feat_outside_count_family_weekly_vs_goal:'high'}, 'very high'])
Absolute_daily_activity_Family.addFunctionRow([{feat_calls_count_family_weekly_vs_goal:'high', feat_visits_count_family_weekly_vs_goal:'low', feat_outside_count_family_weekly_vs_goal:'low'}, 'low'])
Absolute_daily_activity_Family.addFunctionRow([{feat_calls_count_family_weekly_vs_goal:'high', feat_visits_count_family_weekly_vs_goal:'low', feat_outside_count_family_weekly_vs_goal:'medium'}, 'medium'])
Absolute_daily_activity_Family.addFunctionRow([{feat_calls_count_family_weekly_vs_goal:'high', feat_visits_count_family_weekly_vs_goal:'low', feat_outside_count_family_weekly_vs_goal:'high'}, 'high'])
Absolute_daily_activity_Family.addFunctionRow([{feat_calls_count_family_weekly_vs_goal:'high', feat_visits_count_family_weekly_vs_goal:'medium', feat_outside_count_family_weekly_vs_goal:'low'}, 'medium'])
Absolute_daily_activity_Family.addFunctionRow([{feat_calls_count_family_weekly_vs_goal:'high', feat_visits_count_family_weekly_vs_goal:'medium', feat_outside_count_family_weekly_vs_goal:'medium'}, 'high'])
Absolute_daily_activity_Family.addFunctionRow([{feat_calls_count_family_weekly_vs_goal:'high', feat_visits_count_family_weekly_vs_goal:'medium', feat_outside_count_family_weekly_vs_goal:'high'}, 'very high'])
Absolute_daily_activity_Family.addFunctionRow([{feat_calls_count_family_weekly_vs_goal:'high', feat_visits_count_family_weekly_vs_goal:'high', feat_outside_count_family_weekly_vs_goal:'low'}, 'high'])
Absolute_daily_activity_Family.addFunctionRow([{feat_calls_count_family_weekly_vs_goal:'high', feat_visits_count_family_weekly_vs_goal:'high', feat_outside_count_family_weekly_vs_goal:'medium'}, 'very high'])
Absolute_daily_activity_Family.addFunctionRow([{feat_calls_count_family_weekly_vs_goal:'high', feat_visits_count_family_weekly_vs_goal:'high', feat_outside_count_family_weekly_vs_goal:'high'}, 'very high'])
| 112.705584 | 209 | 0.85511 | ##################################################################################
##########--this is an autogenerated python model definition for proDEX--#########
##--original file: Family_Assessment_v05_forprodex.dxi --##
##################################################################################
from .lib.proDEX import *
situ_social_activity_family = Node()
Relative_activity_Family = Node()
calls_last_7_days = Node()
visits_last_7_days = Node()
together_outside_last_7_days = Node()
Absolute_daily_activity_Family = Node()
feat_calls_count_family_relative = Atrib()
feat_calls_duration_family_relative = Atrib()
feat_visits_family_relative_past_week = Atrib()
feat_visits_family_relative = Atrib()
feat_outside_family_relative_past_week = Atrib()
feat_outside_family_relative = Atrib()
feat_calls_count_family_weekly_vs_goal = Atrib()
feat_visits_count_family_weekly_vs_goal = Atrib()
feat_outside_count_family_weekly_vs_goal = Atrib()
situ_social_activity_family.setName('situ_social_activity_family')
Relative_activity_Family.setName('Relative_activity_Family')
calls_last_7_days.setName('calls_last_7_days')
visits_last_7_days.setName('visits_last_7_days')
together_outside_last_7_days.setName('together_outside_last_7_days')
Absolute_daily_activity_Family.setName('Absolute_daily_activity_Family')
feat_calls_count_family_relative.setName('feat_calls_count_family_relative')
feat_calls_duration_family_relative.setName('feat_calls_duration_family_relative')
feat_visits_family_relative_past_week.setName('feat_visits_family_relative_past_week')
feat_visits_family_relative.setName('feat_visits_family_relative')
feat_outside_family_relative_past_week.setName('feat_outside_family_relative_past_week')
feat_outside_family_relative.setName('feat_outside_family_relative')
feat_calls_count_family_weekly_vs_goal.setName('feat_calls_count_family_weekly_vs_goal')
feat_visits_count_family_weekly_vs_goal.setName('feat_visits_count_family_weekly_vs_goal')
feat_outside_count_family_weekly_vs_goal.setName('feat_outside_count_family_weekly_vs_goal')
situ_social_activity_family.setValues(['very_low', 'low', 'medium', 'high', 'very_high'])
Relative_activity_Family.setValues(['high decrease', 'decrease', 'stable', 'increase', 'high increase'])
calls_last_7_days.setValues(['decrease', 'stable', 'increase'])
visits_last_7_days.setValues(['decrease', 'stable', 'increase'])
together_outside_last_7_days.setValues(['decrease', 'stable', 'increase'])
Absolute_daily_activity_Family.setValues(['very low', 'low', 'medium', 'high', 'very high'])
feat_calls_count_family_relative.setValues(['decrease', 'stable', 'increase'])
feat_calls_duration_family_relative.setValues(['decrease', 'stable', 'increase'])
feat_visits_family_relative_past_week.setValues(['decrease', 'stable', 'increase'])
feat_visits_family_relative.setValues(['decrease', 'stable', 'increase'])
feat_outside_family_relative_past_week.setValues(['decrease', 'stable', 'increase'])
feat_outside_family_relative.setValues(['decrease', 'stable', 'increase'])
feat_calls_count_family_weekly_vs_goal.setValues(['low', 'medium', 'high'])
feat_visits_count_family_weekly_vs_goal.setValues(['low', 'medium', 'high'])
feat_outside_count_family_weekly_vs_goal.setValues(['low', 'medium', 'high'])
situ_social_activity_family.addChild(Relative_activity_Family)
Relative_activity_Family.setParent(situ_social_activity_family)
situ_social_activity_family.addChild(Absolute_daily_activity_Family)
Absolute_daily_activity_Family.setParent(situ_social_activity_family)
Relative_activity_Family.addChild(calls_last_7_days)
calls_last_7_days.setParent(Relative_activity_Family)
Relative_activity_Family.addChild(visits_last_7_days)
visits_last_7_days.setParent(Relative_activity_Family)
Relative_activity_Family.addChild(together_outside_last_7_days)
together_outside_last_7_days.setParent(Relative_activity_Family)
calls_last_7_days.addChild(feat_calls_count_family_relative)
feat_calls_count_family_relative.setParent(calls_last_7_days)
calls_last_7_days.addChild(feat_calls_duration_family_relative)
feat_calls_duration_family_relative.setParent(calls_last_7_days)
visits_last_7_days.addChild(feat_visits_family_relative_past_week)
feat_visits_family_relative_past_week.setParent(visits_last_7_days)
visits_last_7_days.addChild(feat_visits_family_relative)
feat_visits_family_relative.setParent(visits_last_7_days)
together_outside_last_7_days.addChild(feat_outside_family_relative_past_week)
feat_outside_family_relative_past_week.setParent(together_outside_last_7_days)
together_outside_last_7_days.addChild(feat_outside_family_relative)
feat_outside_family_relative.setParent(together_outside_last_7_days)
Absolute_daily_activity_Family.addChild(feat_calls_count_family_weekly_vs_goal)
feat_calls_count_family_weekly_vs_goal.setParent(Absolute_daily_activity_Family)
Absolute_daily_activity_Family.addChild(feat_visits_count_family_weekly_vs_goal)
feat_visits_count_family_weekly_vs_goal.setParent(Absolute_daily_activity_Family)
Absolute_daily_activity_Family.addChild(feat_outside_count_family_weekly_vs_goal)
feat_outside_count_family_weekly_vs_goal.setParent(Absolute_daily_activity_Family)
situ_social_activity_family.addFunctionRow([{Relative_activity_Family:'high decrease', Absolute_daily_activity_Family:'very low'}, 'very_low'])
situ_social_activity_family.addFunctionRow([{Relative_activity_Family:'high decrease', Absolute_daily_activity_Family:'low'}, 'very_low'])
situ_social_activity_family.addFunctionRow([{Relative_activity_Family:'high decrease', Absolute_daily_activity_Family:'medium'}, 'low'])
situ_social_activity_family.addFunctionRow([{Relative_activity_Family:'high decrease', Absolute_daily_activity_Family:'high'}, 'medium'])
situ_social_activity_family.addFunctionRow([{Relative_activity_Family:'high decrease', Absolute_daily_activity_Family:'very high'}, 'high'])
situ_social_activity_family.addFunctionRow([{Relative_activity_Family:'decrease', Absolute_daily_activity_Family:'very low'}, 'very_low'])
situ_social_activity_family.addFunctionRow([{Relative_activity_Family:'decrease', Absolute_daily_activity_Family:'low'}, 'low'])
situ_social_activity_family.addFunctionRow([{Relative_activity_Family:'decrease', Absolute_daily_activity_Family:'medium'}, 'medium'])
situ_social_activity_family.addFunctionRow([{Relative_activity_Family:'decrease', Absolute_daily_activity_Family:'high'}, 'high'])
situ_social_activity_family.addFunctionRow([{Relative_activity_Family:'decrease', Absolute_daily_activity_Family:'very high'}, 'very_high'])
situ_social_activity_family.addFunctionRow([{Relative_activity_Family:'stable', Absolute_daily_activity_Family:'very low'}, 'very_low'])
situ_social_activity_family.addFunctionRow([{Relative_activity_Family:'stable', Absolute_daily_activity_Family:'low'}, 'low'])
situ_social_activity_family.addFunctionRow([{Relative_activity_Family:'stable', Absolute_daily_activity_Family:'medium'}, 'medium'])
situ_social_activity_family.addFunctionRow([{Relative_activity_Family:'stable', Absolute_daily_activity_Family:'high'}, 'high'])
situ_social_activity_family.addFunctionRow([{Relative_activity_Family:'stable', Absolute_daily_activity_Family:'very high'}, 'very_high'])
situ_social_activity_family.addFunctionRow([{Relative_activity_Family:'increase', Absolute_daily_activity_Family:'very low'}, 'very_low'])
situ_social_activity_family.addFunctionRow([{Relative_activity_Family:'increase', Absolute_daily_activity_Family:'low'}, 'low'])
situ_social_activity_family.addFunctionRow([{Relative_activity_Family:'increase', Absolute_daily_activity_Family:'medium'}, 'medium'])
situ_social_activity_family.addFunctionRow([{Relative_activity_Family:'increase', Absolute_daily_activity_Family:'high'}, 'high'])
situ_social_activity_family.addFunctionRow([{Relative_activity_Family:'increase', Absolute_daily_activity_Family:'very high'}, 'very_high'])
situ_social_activity_family.addFunctionRow([{Relative_activity_Family:'high increase', Absolute_daily_activity_Family:'very low'}, 'low'])
situ_social_activity_family.addFunctionRow([{Relative_activity_Family:'high increase', Absolute_daily_activity_Family:'low'}, 'medium'])
situ_social_activity_family.addFunctionRow([{Relative_activity_Family:'high increase', Absolute_daily_activity_Family:'medium'}, 'high'])
situ_social_activity_family.addFunctionRow([{Relative_activity_Family:'high increase', Absolute_daily_activity_Family:'high'}, 'very_high'])
situ_social_activity_family.addFunctionRow([{Relative_activity_Family:'high increase', Absolute_daily_activity_Family:'very high'}, 'very_high'])
Relative_activity_Family.addFunctionRow([{calls_last_7_days:'decrease', visits_last_7_days:'decrease', together_outside_last_7_days:'decrease'}, 'high decrease'])
Relative_activity_Family.addFunctionRow([{calls_last_7_days:'decrease', visits_last_7_days:'decrease', together_outside_last_7_days:'stable'}, 'high decrease'])
Relative_activity_Family.addFunctionRow([{calls_last_7_days:'decrease', visits_last_7_days:'decrease', together_outside_last_7_days:'increase'}, 'decrease'])
Relative_activity_Family.addFunctionRow([{calls_last_7_days:'decrease', visits_last_7_days:'stable', together_outside_last_7_days:'decrease'}, 'high decrease'])
Relative_activity_Family.addFunctionRow([{calls_last_7_days:'decrease', visits_last_7_days:'stable', together_outside_last_7_days:'stable'}, 'decrease'])
Relative_activity_Family.addFunctionRow([{calls_last_7_days:'decrease', visits_last_7_days:'stable', together_outside_last_7_days:'increase'}, 'stable'])
Relative_activity_Family.addFunctionRow([{calls_last_7_days:'decrease', visits_last_7_days:'increase', together_outside_last_7_days:'decrease'}, 'decrease'])
Relative_activity_Family.addFunctionRow([{calls_last_7_days:'decrease', visits_last_7_days:'increase', together_outside_last_7_days:'stable'}, 'stable'])
Relative_activity_Family.addFunctionRow([{calls_last_7_days:'decrease', visits_last_7_days:'increase', together_outside_last_7_days:'increase'}, 'increase'])
Relative_activity_Family.addFunctionRow([{calls_last_7_days:'stable', visits_last_7_days:'decrease', together_outside_last_7_days:'decrease'}, 'high decrease'])
Relative_activity_Family.addFunctionRow([{calls_last_7_days:'stable', visits_last_7_days:'decrease', together_outside_last_7_days:'stable'}, 'decrease'])
Relative_activity_Family.addFunctionRow([{calls_last_7_days:'stable', visits_last_7_days:'decrease', together_outside_last_7_days:'increase'}, 'stable'])
Relative_activity_Family.addFunctionRow([{calls_last_7_days:'stable', visits_last_7_days:'stable', together_outside_last_7_days:'decrease'}, 'decrease'])
Relative_activity_Family.addFunctionRow([{calls_last_7_days:'stable', visits_last_7_days:'stable', together_outside_last_7_days:'stable'}, 'stable'])
Relative_activity_Family.addFunctionRow([{calls_last_7_days:'stable', visits_last_7_days:'stable', together_outside_last_7_days:'increase'}, 'increase'])
Relative_activity_Family.addFunctionRow([{calls_last_7_days:'stable', visits_last_7_days:'increase', together_outside_last_7_days:'decrease'}, 'stable'])
Relative_activity_Family.addFunctionRow([{calls_last_7_days:'stable', visits_last_7_days:'increase', together_outside_last_7_days:'stable'}, 'increase'])
Relative_activity_Family.addFunctionRow([{calls_last_7_days:'stable', visits_last_7_days:'increase', together_outside_last_7_days:'increase'}, 'high increase'])
Relative_activity_Family.addFunctionRow([{calls_last_7_days:'increase', visits_last_7_days:'decrease', together_outside_last_7_days:'decrease'}, 'decrease'])
Relative_activity_Family.addFunctionRow([{calls_last_7_days:'increase', visits_last_7_days:'decrease', together_outside_last_7_days:'stable'}, 'stable'])
Relative_activity_Family.addFunctionRow([{calls_last_7_days:'increase', visits_last_7_days:'decrease', together_outside_last_7_days:'increase'}, 'increase'])
Relative_activity_Family.addFunctionRow([{calls_last_7_days:'increase', visits_last_7_days:'stable', together_outside_last_7_days:'decrease'}, 'stable'])
Relative_activity_Family.addFunctionRow([{calls_last_7_days:'increase', visits_last_7_days:'stable', together_outside_last_7_days:'stable'}, 'increase'])
Relative_activity_Family.addFunctionRow([{calls_last_7_days:'increase', visits_last_7_days:'stable', together_outside_last_7_days:'increase'}, 'high increase'])
Relative_activity_Family.addFunctionRow([{calls_last_7_days:'increase', visits_last_7_days:'increase', together_outside_last_7_days:'decrease'}, 'increase'])
Relative_activity_Family.addFunctionRow([{calls_last_7_days:'increase', visits_last_7_days:'increase', together_outside_last_7_days:'stable'}, 'high increase'])
Relative_activity_Family.addFunctionRow([{calls_last_7_days:'increase', visits_last_7_days:'increase', together_outside_last_7_days:'increase'}, 'high increase'])
calls_last_7_days.addFunctionRow([{feat_calls_count_family_relative:'decrease', feat_calls_duration_family_relative:'decrease'}, 'decrease'])
calls_last_7_days.addFunctionRow([{feat_calls_count_family_relative:'decrease', feat_calls_duration_family_relative:'stable'}, 'decrease'])
calls_last_7_days.addFunctionRow([{feat_calls_count_family_relative:'decrease', feat_calls_duration_family_relative:'increase'}, 'stable'])
calls_last_7_days.addFunctionRow([{feat_calls_count_family_relative:'stable', feat_calls_duration_family_relative:'decrease'}, 'decrease'])
calls_last_7_days.addFunctionRow([{feat_calls_count_family_relative:'stable', feat_calls_duration_family_relative:'stable'}, 'stable'])
calls_last_7_days.addFunctionRow([{feat_calls_count_family_relative:'stable', feat_calls_duration_family_relative:'increase'}, 'increase'])
calls_last_7_days.addFunctionRow([{feat_calls_count_family_relative:'increase', feat_calls_duration_family_relative:'decrease'}, 'stable'])
calls_last_7_days.addFunctionRow([{feat_calls_count_family_relative:'increase', feat_calls_duration_family_relative:'stable'}, 'increase'])
calls_last_7_days.addFunctionRow([{feat_calls_count_family_relative:'increase', feat_calls_duration_family_relative:'increase'}, 'increase'])
visits_last_7_days.addFunctionRow([{feat_visits_family_relative_past_week:'decrease', feat_visits_family_relative:'decrease'}, 'decrease'])
visits_last_7_days.addFunctionRow([{feat_visits_family_relative_past_week:'decrease', feat_visits_family_relative:'stable'}, 'stable'])
visits_last_7_days.addFunctionRow([{feat_visits_family_relative_past_week:'decrease', feat_visits_family_relative:'increase'}, 'increase'])
visits_last_7_days.addFunctionRow([{feat_visits_family_relative_past_week:'stable', feat_visits_family_relative:'decrease'}, 'decrease'])
visits_last_7_days.addFunctionRow([{feat_visits_family_relative_past_week:'stable', feat_visits_family_relative:'stable'}, 'stable'])
visits_last_7_days.addFunctionRow([{feat_visits_family_relative_past_week:'stable', feat_visits_family_relative:'increase'}, 'increase'])
visits_last_7_days.addFunctionRow([{feat_visits_family_relative_past_week:'increase', feat_visits_family_relative:'decrease'}, 'decrease'])
visits_last_7_days.addFunctionRow([{feat_visits_family_relative_past_week:'increase', feat_visits_family_relative:'stable'}, 'stable'])
visits_last_7_days.addFunctionRow([{feat_visits_family_relative_past_week:'increase', feat_visits_family_relative:'increase'}, 'increase'])
together_outside_last_7_days.addFunctionRow([{feat_outside_family_relative_past_week:'decrease', feat_outside_family_relative:'decrease'}, 'decrease'])
together_outside_last_7_days.addFunctionRow([{feat_outside_family_relative_past_week:'decrease', feat_outside_family_relative:'stable'}, 'decrease'])
together_outside_last_7_days.addFunctionRow([{feat_outside_family_relative_past_week:'decrease', feat_outside_family_relative:'increase'}, 'stable'])
together_outside_last_7_days.addFunctionRow([{feat_outside_family_relative_past_week:'stable', feat_outside_family_relative:'decrease'}, 'decrease'])
together_outside_last_7_days.addFunctionRow([{feat_outside_family_relative_past_week:'stable', feat_outside_family_relative:'stable'}, 'stable'])
together_outside_last_7_days.addFunctionRow([{feat_outside_family_relative_past_week:'stable', feat_outside_family_relative:'increase'}, 'increase'])
together_outside_last_7_days.addFunctionRow([{feat_outside_family_relative_past_week:'increase', feat_outside_family_relative:'decrease'}, 'decrease'])
together_outside_last_7_days.addFunctionRow([{feat_outside_family_relative_past_week:'increase', feat_outside_family_relative:'stable'}, 'stable'])
together_outside_last_7_days.addFunctionRow([{feat_outside_family_relative_past_week:'increase', feat_outside_family_relative:'increase'}, 'increase'])
Absolute_daily_activity_Family.addFunctionRow([{feat_calls_count_family_weekly_vs_goal:'low', feat_visits_count_family_weekly_vs_goal:'low', feat_outside_count_family_weekly_vs_goal:'low'}, 'very low'])
Absolute_daily_activity_Family.addFunctionRow([{feat_calls_count_family_weekly_vs_goal:'low', feat_visits_count_family_weekly_vs_goal:'low', feat_outside_count_family_weekly_vs_goal:'medium'}, 'very low'])
Absolute_daily_activity_Family.addFunctionRow([{feat_calls_count_family_weekly_vs_goal:'low', feat_visits_count_family_weekly_vs_goal:'low', feat_outside_count_family_weekly_vs_goal:'high'}, 'low'])
Absolute_daily_activity_Family.addFunctionRow([{feat_calls_count_family_weekly_vs_goal:'low', feat_visits_count_family_weekly_vs_goal:'medium', feat_outside_count_family_weekly_vs_goal:'low'}, 'very low'])
Absolute_daily_activity_Family.addFunctionRow([{feat_calls_count_family_weekly_vs_goal:'low', feat_visits_count_family_weekly_vs_goal:'medium', feat_outside_count_family_weekly_vs_goal:'medium'}, 'low'])
Absolute_daily_activity_Family.addFunctionRow([{feat_calls_count_family_weekly_vs_goal:'low', feat_visits_count_family_weekly_vs_goal:'medium', feat_outside_count_family_weekly_vs_goal:'high'}, 'medium'])
Absolute_daily_activity_Family.addFunctionRow([{feat_calls_count_family_weekly_vs_goal:'low', feat_visits_count_family_weekly_vs_goal:'high', feat_outside_count_family_weekly_vs_goal:'low'}, 'low'])
Absolute_daily_activity_Family.addFunctionRow([{feat_calls_count_family_weekly_vs_goal:'low', feat_visits_count_family_weekly_vs_goal:'high', feat_outside_count_family_weekly_vs_goal:'medium'}, 'medium'])
Absolute_daily_activity_Family.addFunctionRow([{feat_calls_count_family_weekly_vs_goal:'low', feat_visits_count_family_weekly_vs_goal:'high', feat_outside_count_family_weekly_vs_goal:'high'}, 'high'])
Absolute_daily_activity_Family.addFunctionRow([{feat_calls_count_family_weekly_vs_goal:'medium', feat_visits_count_family_weekly_vs_goal:'low', feat_outside_count_family_weekly_vs_goal:'low'}, 'very low'])
Absolute_daily_activity_Family.addFunctionRow([{feat_calls_count_family_weekly_vs_goal:'medium', feat_visits_count_family_weekly_vs_goal:'low', feat_outside_count_family_weekly_vs_goal:'medium'}, 'low'])
Absolute_daily_activity_Family.addFunctionRow([{feat_calls_count_family_weekly_vs_goal:'medium', feat_visits_count_family_weekly_vs_goal:'low', feat_outside_count_family_weekly_vs_goal:'high'}, 'medium'])
Absolute_daily_activity_Family.addFunctionRow([{feat_calls_count_family_weekly_vs_goal:'medium', feat_visits_count_family_weekly_vs_goal:'medium', feat_outside_count_family_weekly_vs_goal:'low'}, 'low'])
Absolute_daily_activity_Family.addFunctionRow([{feat_calls_count_family_weekly_vs_goal:'medium', feat_visits_count_family_weekly_vs_goal:'medium', feat_outside_count_family_weekly_vs_goal:'medium'}, 'medium'])
Absolute_daily_activity_Family.addFunctionRow([{feat_calls_count_family_weekly_vs_goal:'medium', feat_visits_count_family_weekly_vs_goal:'medium', feat_outside_count_family_weekly_vs_goal:'high'}, 'high'])
Absolute_daily_activity_Family.addFunctionRow([{feat_calls_count_family_weekly_vs_goal:'medium', feat_visits_count_family_weekly_vs_goal:'high', feat_outside_count_family_weekly_vs_goal:'low'}, 'medium'])
Absolute_daily_activity_Family.addFunctionRow([{feat_calls_count_family_weekly_vs_goal:'medium', feat_visits_count_family_weekly_vs_goal:'high', feat_outside_count_family_weekly_vs_goal:'medium'}, 'high'])
Absolute_daily_activity_Family.addFunctionRow([{feat_calls_count_family_weekly_vs_goal:'medium', feat_visits_count_family_weekly_vs_goal:'high', feat_outside_count_family_weekly_vs_goal:'high'}, 'very high'])
Absolute_daily_activity_Family.addFunctionRow([{feat_calls_count_family_weekly_vs_goal:'high', feat_visits_count_family_weekly_vs_goal:'low', feat_outside_count_family_weekly_vs_goal:'low'}, 'low'])
Absolute_daily_activity_Family.addFunctionRow([{feat_calls_count_family_weekly_vs_goal:'high', feat_visits_count_family_weekly_vs_goal:'low', feat_outside_count_family_weekly_vs_goal:'medium'}, 'medium'])
Absolute_daily_activity_Family.addFunctionRow([{feat_calls_count_family_weekly_vs_goal:'high', feat_visits_count_family_weekly_vs_goal:'low', feat_outside_count_family_weekly_vs_goal:'high'}, 'high'])
Absolute_daily_activity_Family.addFunctionRow([{feat_calls_count_family_weekly_vs_goal:'high', feat_visits_count_family_weekly_vs_goal:'medium', feat_outside_count_family_weekly_vs_goal:'low'}, 'medium'])
Absolute_daily_activity_Family.addFunctionRow([{feat_calls_count_family_weekly_vs_goal:'high', feat_visits_count_family_weekly_vs_goal:'medium', feat_outside_count_family_weekly_vs_goal:'medium'}, 'high'])
Absolute_daily_activity_Family.addFunctionRow([{feat_calls_count_family_weekly_vs_goal:'high', feat_visits_count_family_weekly_vs_goal:'medium', feat_outside_count_family_weekly_vs_goal:'high'}, 'very high'])
Absolute_daily_activity_Family.addFunctionRow([{feat_calls_count_family_weekly_vs_goal:'high', feat_visits_count_family_weekly_vs_goal:'high', feat_outside_count_family_weekly_vs_goal:'low'}, 'high'])
Absolute_daily_activity_Family.addFunctionRow([{feat_calls_count_family_weekly_vs_goal:'high', feat_visits_count_family_weekly_vs_goal:'high', feat_outside_count_family_weekly_vs_goal:'medium'}, 'very high'])
Absolute_daily_activity_Family.addFunctionRow([{feat_calls_count_family_weekly_vs_goal:'high', feat_visits_count_family_weekly_vs_goal:'high', feat_outside_count_family_weekly_vs_goal:'high'}, 'very high'])
| 0 | 0 | 0 |
73203aca3d16bb92f993919016b4a09e053e902b | 1,119 | py | Python | chapter 3 - stacks and queues/3.2.py | anuraagdjain/cracking_the_coding_interview | 09083b4c464f41d5752c7ca3d27ab7c992793619 | [
"MIT"
] | null | null | null | chapter 3 - stacks and queues/3.2.py | anuraagdjain/cracking_the_coding_interview | 09083b4c464f41d5752c7ca3d27ab7c992793619 | [
"MIT"
] | null | null | null | chapter 3 - stacks and queues/3.2.py | anuraagdjain/cracking_the_coding_interview | 09083b4c464f41d5752c7ca3d27ab7c992793619 | [
"MIT"
] | null | null | null |
if __name__ == "__main__":
s = MinStack()
s.add(5)
s.add(-3)
s.add(1)
s.add(6)
s.add(-1)
print(s.pop())
print(s.get_min())
s.add(-10)
s.pop()
| 18.966102 | 61 | 0.526363 | class Node:
def __init__(self, data):
self.data = data
self.next = None
class Stack:
def __init__(self):
self.top = None
def add(self, data):
node = Node(data)
node.next = self.top
self.top = node
def pop(self):
item = self.top.data
self.top = self.top.next
return item
def peek(self):
return self.top.data if self.top else None
def print_stack(self, stack_index):
print(self.top)
class MinStack:
def __init__(self):
self.min = Stack()
self.stack = Stack()
def add(self, data):
self.stack.add(data)
if self.min.peek() == None or data < self.min.peek():
self.min.add(data)
def pop(self):
item = self.stack.pop()
if self.min.peek() == item:
self.min.pop()
return item
def get_min(self):
return self.min.peek()
if __name__ == "__main__":
s = MinStack()
s.add(5)
s.add(-3)
s.add(1)
s.add(6)
s.add(-1)
print(s.pop())
print(s.get_min())
s.add(-10)
s.pop()
| 623 | -25 | 335 |
86eadf6b705f0089cbbe547b10a749f347fbf86f | 1,755 | py | Python | Moving-to-Melbourne---Housing-Again!/code.py | ANanade/ga-learner-dsmp-repo | ba5c06d039cfba6222998fccaca88e629c4bc3b8 | [
"MIT"
] | null | null | null | Moving-to-Melbourne---Housing-Again!/code.py | ANanade/ga-learner-dsmp-repo | ba5c06d039cfba6222998fccaca88e629c4bc3b8 | [
"MIT"
] | null | null | null | Moving-to-Melbourne---Housing-Again!/code.py | ANanade/ga-learner-dsmp-repo | ba5c06d039cfba6222998fccaca88e629c4bc3b8 | [
"MIT"
] | null | null | null | # --------------
import numpy as np
import pandas as pd
from sklearn.model_selection import train_test_split
# path- variable storing file path
df = pd.read_csv(path)
df.columns[range(5)]
X = df.drop(['Price'], axis = 1)
y= df.Price
X_train,X_test,y_train,y_test = train_test_split(X , y , test_size = 0.3, random_state = 6)
corr = X_train.corr(method = 'pearson')
print(corr)
#Code starts here
# --------------
from sklearn.linear_model import LinearRegression
from sklearn.metrics import mean_squared_error, r2_score
from math import sqrt
regressor = LinearRegression()
regressor.fit(X_train, y_train)
y_pred = regressor.predict(X_test)
mse = (mean_squared_error(y_test, y_pred))
print(mse)
r2 = r2_score (y_test, y_pred)
# Code starts here
# --------------
from sklearn.linear_model import Lasso
# Code starts here
lasso = Lasso()
lasso.fit(X_train, y_train)
lasso_pred = lasso.predict(X_test)
r2_lasso = r2_score(y_test, y_pred)
print(r2_lasso)
# --------------
from sklearn.linear_model import Ridge
# Code starts here
ridge = Ridge()
ridge.fit(X_train, y_train)
ridge_pred = ridge.predict(X_test)
r2_ridge = r2_score(y_test , y_pred)
print(r2_ridge)
# Code ends here
# --------------
from sklearn.model_selection import cross_val_score
#Code starts here
score = cross_val_score(regressor, X_train, y_train, cv= 10)
mean_score = np.mean(score)
print(mean_score)
# --------------
from sklearn.preprocessing import PolynomialFeatures
from sklearn.pipeline import make_pipeline
#Code starts here
model = make_pipeline(PolynomialFeatures(2), LinearRegression())
model.fit(X_train , y_train)
y_pred = model.predict(X_test)
r2_poly = r2_score(y_test , y_pred)
print(r2_poly)
| 21.9375 | 92 | 0.707692 | # --------------
import numpy as np
import pandas as pd
from sklearn.model_selection import train_test_split
# path- variable storing file path
df = pd.read_csv(path)
df.columns[range(5)]
X = df.drop(['Price'], axis = 1)
y= df.Price
X_train,X_test,y_train,y_test = train_test_split(X , y , test_size = 0.3, random_state = 6)
corr = X_train.corr(method = 'pearson')
print(corr)
#Code starts here
# --------------
from sklearn.linear_model import LinearRegression
from sklearn.metrics import mean_squared_error, r2_score
from math import sqrt
regressor = LinearRegression()
regressor.fit(X_train, y_train)
y_pred = regressor.predict(X_test)
mse = (mean_squared_error(y_test, y_pred))
print(mse)
r2 = r2_score (y_test, y_pred)
# Code starts here
# --------------
from sklearn.linear_model import Lasso
# Code starts here
lasso = Lasso()
lasso.fit(X_train, y_train)
lasso_pred = lasso.predict(X_test)
r2_lasso = r2_score(y_test, y_pred)
print(r2_lasso)
# --------------
from sklearn.linear_model import Ridge
# Code starts here
ridge = Ridge()
ridge.fit(X_train, y_train)
ridge_pred = ridge.predict(X_test)
r2_ridge = r2_score(y_test , y_pred)
print(r2_ridge)
# Code ends here
# --------------
from sklearn.model_selection import cross_val_score
#Code starts here
score = cross_val_score(regressor, X_train, y_train, cv= 10)
mean_score = np.mean(score)
print(mean_score)
# --------------
from sklearn.preprocessing import PolynomialFeatures
from sklearn.pipeline import make_pipeline
#Code starts here
model = make_pipeline(PolynomialFeatures(2), LinearRegression())
model.fit(X_train , y_train)
y_pred = model.predict(X_test)
r2_poly = r2_score(y_test , y_pred)
print(r2_poly)
| 0 | 0 | 0 |
0c177cb946bb0bcc84e16ee3f15e953374a97fbd | 8,918 | py | Python | Quadrotor_velocity_control.py | Ryan906k9/quadrotor_velocity_control | 7e3f28d94c931d277394a8591a5925583642586c | [
"MIT"
] | null | null | null | Quadrotor_velocity_control.py | Ryan906k9/quadrotor_velocity_control | 7e3f28d94c931d277394a8591a5925583642586c | [
"MIT"
] | null | null | null | Quadrotor_velocity_control.py | Ryan906k9/quadrotor_velocity_control | 7e3f28d94c931d277394a8591a5925583642586c | [
"MIT"
] | null | null | null | import numpy as np
import parl
from parl.utils import logger
from parl.utils import action_mapping # 将神经网络输出映射到对应的 实际动作取值范围 内
from parl.utils import ReplayMemory # 经验回放
from rlschool import make_env # 使用 RLSchool 创建飞行器环境
from parl.algorithms import DDPG
import paddle.fluid as fluid
import parl
from parl import layers
GAMMA = 0.99 # reward 的衰减因子,一般取 0.9 到 0.999 不等
TAU = 0.001 # target_model 跟 model 同步参数 的 软更新参数
ACTOR_LR = 0.0002 # Actor网络更新的 learning rate
CRITIC_LR = 0.001 # Critic网络更新的 learning rate
MEMORY_SIZE = 1e6 # replay memory的大小,越大越占用内存
MEMORY_WARMUP_SIZE = 1e4 # replay_memory 里需要预存一些经验数据,再从里面sample一个batch的经验让agent去learn
REWARD_SCALE = 0.01 # reward 的缩放因子
BATCH_SIZE = 256 # 每次给agent learn的数据数量,从replay memory随机里sample一批数据出来
TRAIN_TOTAL_STEPS = 1e6 # 总训练步数
TEST_EVERY_STEPS = 1e4 # 每个N步评估一下算法效果,每次评估5个episode求平均reward
# 评估 agent, 跑 5 个episode,总reward求平均
# 创建飞行器环境
env = make_env("Quadrotor", task="velocity_control", seed=0)
env.reset()
obs_dim = env.observation_space.shape[ 0 ]
act_dim = 5
# 使用parl框架搭建Agent:QuadrotorModel, DDPG, QuadrotorAgent三者嵌套
model = QuadrotorModel(act_dim)
algorithm = DDPG(
model, gamma=GAMMA, tau=TAU, actor_lr=ACTOR_LR, critic_lr=CRITIC_LR)
agent = QuadrotorAgent(algorithm, obs_dim, act_dim)
# 加载模型
# save_path = 'model_dir_3/steps_1000000.ckpt'
# agent.restore(save_path)
# parl库也为DDPG算法内置了ReplayMemory,可直接从 parl.utils 引入使用
rpm = ReplayMemory(int(MEMORY_SIZE), obs_dim, act_dim)
test_flag = 0
total_steps = 0
testing = 1
if (not testing):
while total_steps < TRAIN_TOTAL_STEPS:
train_reward, steps = run_episode(env, agent, rpm)
total_steps += steps
# logger.info('Steps: {} Reward: {}'.format(total_steps, train_reward))
if total_steps // TEST_EVERY_STEPS >= test_flag:
while total_steps // TEST_EVERY_STEPS >= test_flag:
test_flag += 1
evaluate_reward = evaluate(env, agent)
logger.info('Steps {}, Test reward: {}'.format(total_steps,
evaluate_reward))
# 保存模型
ckpt = 'model_dir_1/steps_{}.ckpt'.format(total_steps)
agent.save(ckpt)
else:
# 加载模型
save_path = 'steps_1000000.ckpt'
agent.restore(save_path)
evaluate_reward = evaluate(env, agent, render=True)
logger.info('Test reward: {}'.format(evaluate_reward)) | 32.429091 | 86 | 0.591837 | import numpy as np
import parl
from parl.utils import logger
from parl.utils import action_mapping # 将神经网络输出映射到对应的 实际动作取值范围 内
from parl.utils import ReplayMemory # 经验回放
from rlschool import make_env # 使用 RLSchool 创建飞行器环境
from parl.algorithms import DDPG
class QuadrotorAgent(parl.Agent):
def __init__(self, algorithm, obs_dim, act_dim=4):
assert isinstance(obs_dim, int)
assert isinstance(act_dim, int)
self.obs_dim = obs_dim
self.act_dim = act_dim
super(QuadrotorAgent, self).__init__(algorithm)
# Attention: In the beginning, sync target model totally.
self.alg.sync_target(decay=0)
def build_program(self):
self.pred_program = fluid.Program()
self.learn_program = fluid.Program()
with fluid.program_guard(self.pred_program):
obs = layers.data(
name='obs', shape=[self.obs_dim], dtype='float32')
self.pred_act = self.alg.predict(obs)
with fluid.program_guard(self.learn_program):
obs = layers.data(
name='obs', shape=[self.obs_dim], dtype='float32')
act = layers.data(
name='act', shape=[self.act_dim], dtype='float32')
reward = layers.data(name='reward', shape=[], dtype='float32')
next_obs = layers.data(
name='next_obs', shape=[self.obs_dim], dtype='float32')
terminal = layers.data(name='terminal', shape=[], dtype='bool')
_, self.critic_cost = self.alg.learn(obs, act, reward, next_obs,
terminal)
def predict(self, obs):
obs = np.expand_dims(obs, axis=0)
act = self.fluid_executor.run(
self.pred_program, feed={'obs': obs},
fetch_list=[self.pred_act])[0]
return act
def learn(self, obs, act, reward, next_obs, terminal):
feed = {
'obs': obs,
'act': act,
'reward': reward,
'next_obs': next_obs,
'terminal': terminal
}
critic_cost = self.fluid_executor.run(
self.learn_program, feed=feed, fetch_list=[self.critic_cost])[0]
self.alg.sync_target()
return critic_cost
import paddle.fluid as fluid
import parl
from parl import layers
class ActorModel(parl.Model):
def __init__(self, act_dim):
hidden_dim_1, hidden_dim_2 = 64, 64
self.fc1 = layers.fc(size=hidden_dim_1, act='tanh')
self.fc2 = layers.fc(size=hidden_dim_2, act='tanh')
self.fc3 = layers.fc(size=act_dim, act='tanh')
def policy(self, obs):
x = self.fc1(obs)
x = self.fc2(x)
return self.fc3(x)
class CriticModel(parl.Model):
def __init__(self):
hidden_dim_1, hidden_dim_2 = 64, 64
self.fc1 = layers.fc(size=hidden_dim_1, act='tanh')
self.fc2 = layers.fc(size=hidden_dim_2, act='tanh')
self.fc3 = layers.fc(size=1, act=None)
def value(self, obs, act):
x = self.fc1(obs)
concat = layers.concat([x, act], axis=1)
x = self.fc2(concat)
Q = self.fc3(x)
Q = layers.squeeze(Q, axes=[1])
return Q
class QuadrotorModel(parl.Model):
def __init__(self, act_dim):
self.actor_model = ActorModel(act_dim)
self.critic_model = CriticModel()
def policy(self, obs):
return self.actor_model.policy(obs)
def value(self, obs, act):
return self.critic_model.value(obs, act)
def get_actor_params(self):
return self.actor_model.parameters()
GAMMA = 0.99 # reward 的衰减因子,一般取 0.9 到 0.999 不等
TAU = 0.001 # target_model 跟 model 同步参数 的 软更新参数
ACTOR_LR = 0.0002 # Actor网络更新的 learning rate
CRITIC_LR = 0.001 # Critic网络更新的 learning rate
MEMORY_SIZE = 1e6 # replay memory的大小,越大越占用内存
MEMORY_WARMUP_SIZE = 1e4 # replay_memory 里需要预存一些经验数据,再从里面sample一个batch的经验让agent去learn
REWARD_SCALE = 0.01 # reward 的缩放因子
BATCH_SIZE = 256 # 每次给agent learn的数据数量,从replay memory随机里sample一批数据出来
TRAIN_TOTAL_STEPS = 1e6 # 总训练步数
TEST_EVERY_STEPS = 1e4 # 每个N步评估一下算法效果,每次评估5个episode求平均reward
def run_episode(env, agent, rpm):
obs = env.reset()
total_reward, steps = 0, 0
while True:
steps += 1
batch_obs = np.expand_dims(obs, axis=0)
action = agent.predict(batch_obs.astype('float32'))
# 给输出动作增加探索扰动
action = np.random.normal(action, 1.0)
action = np.squeeze(action)
# 动作从 5 个压缩为 4 个
temp = np.zeros((1, 4))
temp_1 = np.array([ [ 1.0, 0.0, 0.0, 0.0 ] ])
temp_2 = np.array([ [ 0.0, 1.0, 0.0, 0.0 ] ])
temp_3 = np.array([ [ 0.0, 0.0, 1.0, 0.0 ] ])
temp_4 = np.array([ [ 0.0, 0.0, 0.0, 1.0 ] ])
temp += list(action)[ 0 ]
temp_1 *= list(action)[ 1 ]
temp_2 *= list(action)[ 2 ]
temp_3 *= list(action)[ 3 ]
temp_4 *= list(action)[ 4 ]
action_4 = temp + 0.1 * (temp_1 + temp_2 + temp_3 + temp_4)
action_4 = np.squeeze(action_4)
action_4 = np.squeeze(action_4)
action_4 = np.clip(action_4, -1.0, 1.0)
# 动作映射到对应的 实际动作取值范围 内, action_mapping是从parl.utils那里import进来的函数
action_4 = action_mapping(action_4, env.action_space.low[ 0 ],
env.action_space.high[ 0 ])
next_obs, reward, done, info = env.step(action_4)
rpm.append(obs, action, REWARD_SCALE * reward, next_obs, done)
if rpm.size() > MEMORY_WARMUP_SIZE:
batch_obs, batch_action, batch_reward, batch_next_obs, \
batch_terminal = rpm.sample_batch(BATCH_SIZE)
critic_cost = agent.learn(batch_obs, batch_action, batch_reward,
batch_next_obs, batch_terminal)
obs = next_obs
total_reward += reward
if done:
break
return total_reward, steps
# 评估 agent, 跑 5 个episode,总reward求平均
def evaluate(env, agent, render=False):
eval_reward = [ ]
for i in range(5):
obs = env.reset()
total_reward, steps = 0, 0
while True:
batch_obs = np.expand_dims(obs, axis=0)
action = agent.predict(batch_obs.astype('float32'))
action = np.squeeze(action)
# 动作从 5 个压缩为 4 个
temp = np.zeros((1, 4))
temp_1 = np.array([ [ 1.0, 0.0, 0.0, 0.0 ] ])
temp_2 = np.array([ [ 0.0, 1.0, 0.0, 0.0 ] ])
temp_3 = np.array([ [ 0.0, 0.0, 1.0, 0.0 ] ])
temp_4 = np.array([ [ 0.0, 0.0, 0.0, 1.0 ] ])
temp += list(action)[ 0 ]
temp_1 *= list(action)[ 1 ]
temp_2 *= list(action)[ 2 ]
temp_3 *= list(action)[ 3 ]
temp_4 *= list(action)[ 4 ]
action_4 = temp + 0.1 * (temp_1 + temp_2 + temp_3 + temp_4)
action_4 = np.squeeze(action_4)
action_4 = np.squeeze(action_4)
action_4 = np.clip(action_4, -1.0, 1.0)
action_4 = action_mapping(action_4, env.action_space.low[ 0 ],
env.action_space.high[ 0 ])
next_obs, reward, done, info = env.step(action_4)
obs = next_obs
total_reward += reward
steps += 1
if render:
env.render()
if done:
break
eval_reward.append(total_reward)
return np.mean(eval_reward)
# 创建飞行器环境
env = make_env("Quadrotor", task="velocity_control", seed=0)
env.reset()
obs_dim = env.observation_space.shape[ 0 ]
act_dim = 5
# 使用parl框架搭建Agent:QuadrotorModel, DDPG, QuadrotorAgent三者嵌套
model = QuadrotorModel(act_dim)
algorithm = DDPG(
model, gamma=GAMMA, tau=TAU, actor_lr=ACTOR_LR, critic_lr=CRITIC_LR)
agent = QuadrotorAgent(algorithm, obs_dim, act_dim)
# 加载模型
# save_path = 'model_dir_3/steps_1000000.ckpt'
# agent.restore(save_path)
# parl库也为DDPG算法内置了ReplayMemory,可直接从 parl.utils 引入使用
rpm = ReplayMemory(int(MEMORY_SIZE), obs_dim, act_dim)
test_flag = 0
total_steps = 0
testing = 1
if (not testing):
while total_steps < TRAIN_TOTAL_STEPS:
train_reward, steps = run_episode(env, agent, rpm)
total_steps += steps
# logger.info('Steps: {} Reward: {}'.format(total_steps, train_reward))
if total_steps // TEST_EVERY_STEPS >= test_flag:
while total_steps // TEST_EVERY_STEPS >= test_flag:
test_flag += 1
evaluate_reward = evaluate(env, agent)
logger.info('Steps {}, Test reward: {}'.format(total_steps,
evaluate_reward))
# 保存模型
ckpt = 'model_dir_1/steps_{}.ckpt'.format(total_steps)
agent.save(ckpt)
else:
# 加载模型
save_path = 'steps_1000000.ckpt'
agent.restore(save_path)
evaluate_reward = evaluate(env, agent, render=True)
logger.info('Test reward: {}'.format(evaluate_reward)) | 6,123 | 41 | 457 |
eb88fdadfb290aecfda1d0c370c0cbc8e4c3bdc2 | 3,189 | py | Python | addons/rest_api/controllers/redisdb.py | Prescrypto/odooku | a6647e0e22bb5d41a2f025852df736a5c657a038 | [
"Apache-2.0"
] | null | null | null | addons/rest_api/controllers/redisdb.py | Prescrypto/odooku | a6647e0e22bb5d41a2f025852df736a5c657a038 | [
"Apache-2.0"
] | 9 | 2017-09-07T18:42:16.000Z | 2021-03-18T05:58:58.000Z | addons/rest_api/controllers/redisdb.py | Prescrypto/odooku | a6647e0e22bb5d41a2f025852df736a5c657a038 | [
"Apache-2.0"
] | 1 | 2018-10-16T20:45:10.000Z | 2018-10-16T20:45:10.000Z | # -*- coding: utf-8 -*-
import redis
import logging
try:
import simplejson as json
except ImportError:
import json
_logger = logging.getLogger(__name__)
| 34.290323 | 83 | 0.56789 | # -*- coding: utf-8 -*-
import redis
import logging
try:
import simplejson as json
except ImportError:
import json
_logger = logging.getLogger(__name__)
class RedisTokenStore(object):
def __init__(self, host='localhost', port=6379, db=0, password=None):
self.rs = redis.StrictRedis(host=host, port=port, db=db, password=password)
# Connection test
try:
res = self.rs.get('foo')
_logger.info("<REDIS> Successful connect to Redis-server.")
except:
_logger.error("<REDIS> ERROR: Failed to connect to Redis-server!")
print "<REDIS> ERROR: Failed to connect to Redis-server!"
def save_all_tokens(self, access_token, expires_in,
refresh_token, refresh_expires_in, user_id):
# access_token
self.rs.set('access_' + access_token,
json.dumps({'user_id': user_id}),
expires_in
)
# refresh_token
self.rs.set('refresh_' + refresh_token,
json.dumps({
'access_token': access_token,
'user_id': user_id
}),
refresh_expires_in
)
def fetch_by_access_token(self, access_token):
key = 'access_' + access_token
_logger.info("<REDIS> Fetch by access token.")
data = self.rs.get(key)
if data:
return json.loads(data)
else:
return None
def fetch_by_refresh_token(self, refresh_token):
key = 'refresh_' + refresh_token
_logger.info("<REDIS> Fetch by refresh token.")
data = self.rs.get(key)
if data:
return json.loads(data)
else:
return None
def delete_access_token(self, access_token):
self.rs.delete('access_' + access_token)
def delete_refresh_token(self, refresh_token):
self.rs.delete('refresh_' + refresh_token)
def update_access_token(self, old_access_token,
new_access_token, expires_in,
refresh_token, user_id):
# Delete old access token
self.delete_access_token(old_access_token)
# Write new access token
self.rs.set('access_' + new_access_token,
json.dumps({'user_id': user_id}),
expires_in
)
# Rewrite refresh token
refresh_token_key = 'refresh_' + refresh_token
current_ttl = self.rs.ttl(refresh_token_key)
self.rs.set(refresh_token_key,
json.dumps({
'access_token': new_access_token,
'user_id': user_id
}),
current_ttl
)
def delete_all_tokens_by_refresh_token(self, refresh_token):
refresh_token_data = self.fetch_by_refresh_token(refresh_token)
if refresh_token_data:
access_token = refresh_token_data['access_token']
# Delete tokens
self.delete_access_token(access_token)
self.delete_refresh_token(refresh_token)
| 2,741 | 9 | 271 |
421f011ca77258f909f26458d6c8149223833f62 | 19,490 | py | Python | model_multi_classifier.py | mbarbetti/lymphoma-classification | e1ec25302270388a4215d840b0c2925b043e1716 | [
"MIT"
] | null | null | null | model_multi_classifier.py | mbarbetti/lymphoma-classification | e1ec25302270388a4215d840b0c2925b043e1716 | [
"MIT"
] | null | null | null | model_multi_classifier.py | mbarbetti/lymphoma-classification | e1ec25302270388a4215d840b0c2925b043e1716 | [
"MIT"
] | null | null | null | import os
import pickle
import numpy as np
from tqdm import tqdm
from argparse import ArgumentParser
import optuna
optuna.logging.set_verbosity ( optuna.logging.ERROR ) # silence Optuna during trials study
import warnings
warnings.filterwarnings ( "ignore", category = RuntimeWarning )
from sklearn.model_selection import StratifiedShuffleSplit
from sklearn.preprocessing import MinMaxScaler
from imblearn.over_sampling import SMOTE
from sklearn.linear_model import LogisticRegression
from sklearn.svm import SVC
from sklearn.gaussian_process import GaussianProcessClassifier
from sklearn.ensemble import RandomForestClassifier, GradientBoostingClassifier
from sklearn.feature_selection import RFECV
from sklearn.metrics import roc_auc_score, confusion_matrix, roc_curve
from utils import custom_predictions, multiclass_predictions, plot_conf_matrices, plot_multi_prf_histos
LABELS = ["cHL", "GZL", "PMBCL"]
# +-------------------+
# | Options setup |
# +-------------------+
MODELS = [ "log-reg", "lin-svm", "gaus-proc", "rnd-frs", "grad-bdt" ]
parser = ArgumentParser ( description = "training script" )
parser . add_argument ( "-m" , "--model" , required = True , choices = MODELS )
parser . add_argument ( "-s" , "--split" , default = "50/30/20" )
parser . add_argument ( "-t" , "--threshold" , default = "rec90" )
args = parser . parse_args()
if len ( args.split.split("/") ) == 2:
test_size = 0.5 * float(args.split.split("/")[-1]) / 100
val_size = test_size
val_size /= ( 1 - test_size ) # w.r.t. new dataset size
elif len ( args.split.split("/") ) == 3:
test_size = float(args.split.split("/")[2]) / 100
val_size = float(args.split.split("/")[1]) / 100
val_size /= ( 1 - test_size ) # w.r.t. new dataset size
else:
raise ValueError (f"The splitting ratios should be passed as 'XX/YY/ZZ', where XX% is "
f"the percentage of data used for training, while YY% and ZZ% are "
f"the ones used for validation and testing respectively.")
if "rec" in args.threshold:
rec_score = float(args.threshold.split("rec")[-1]) / 100
prec_score = None
elif "prec" in args.threshold:
rec_score = None
prec_score = float(args.threshold.split("prec")[-1]) / 100
else:
raise ValueError (f"The rule for custom predictions should be passed as 'recXX' where "
f"XX% is the minimum recall score required, or as 'precYY' where YY% "
f"is the minimum precision score required.")
# +------------------+
# | Data loading |
# +------------------+
data_dir = "./data"
data_file = "db_mediastinalbulky_reduced.pkl"
file_path = os.path.join ( data_dir, data_file )
with open (file_path, "rb") as file:
data = pickle.load (file)
# +------------------------------+
# | Input/output preparation |
# +------------------------------+
cols = list ( data.columns )
X_cols = cols[2:]
y_cols = "lymphoma_type"
X = data.query("lymphoma_type != 2")[X_cols] . to_numpy()
y = data.query("lymphoma_type != 2")[y_cols] . to_numpy() . flatten()
y = ( y == 3 ) # PMBCL/cHL classification
X_gz = data.query("lymphoma_type == 2")[X_cols] . to_numpy()
y_gz = data.query("lymphoma_type == 2")[y_cols] . to_numpy() . flatten()
# +------------------------+
# | Sub-sample studies |
# +------------------------+
conf_matrices = [ list() , list() , list() ] # container for confusion matrices
recalls = [ list() , list() , list() ] # container for recalls
precisions = [ list() , list() , list() ] # container for precisions
roc_curves = [ list() , list() ] # container for ROC curve variables
## initial control values
optimized = False
append_to_roc = [ True , True ]
n_roc_points = [ -1 , -1 ]
for i in tqdm(range(250)):
# +--------------------------+
# | Train/test splitting |
# +--------------------------+
sss = StratifiedShuffleSplit ( n_splits = 1, test_size = test_size )
for idx_train, idx_test in sss . split ( X, y ):
X_train , y_train = X[idx_train] , y[idx_train]
X_test , y_test = X[idx_test] , y[idx_test]
# +------------------------+
# | Data preprocessing |
# +------------------------+
scaler_train = MinMaxScaler()
X_train = scaler_train.fit_transform (X_train)
scaler_test = MinMaxScaler()
X_test = scaler_test.fit_transform (X_test)
scaler_gz = MinMaxScaler()
X_gz = scaler_gz.fit_transform (X_gz)
# +------------------+
# | Optuna setup |
# +------------------+
# +------------------------------+
# | Hyperparams optimization |
# +------------------------------+
## LOGISTIC REGRESSION
if args.model == "log-reg":
best_model = LogisticRegression()
## LINEAR SVM
elif args.model == "lin-svm":
best_model = SVC ( kernel = "linear", probability = True )
## GAUSSIAN PROCESS
elif args.model == "gaus-proc":
best_model = GaussianProcessClassifier()
## RANDOM FOREST
elif args.model == "rnd-frs":
if not optimized:
study = optuna_study ( model_name = "rnd_forest_clf" ,
storage_dir = "./storage" ,
objective = objective ,
n_trials = 50 ,
direction = "maximize" ,
load_if_exists = False )
optimized = True
best_model = RandomForestClassifier ( n_estimators = study.best_params["n_estims"] ,
max_depth = study.best_params["max_depth"] )
## GRADIENT BDT
elif args.model == "grad-bdt":
if not optimized:
study = optuna_study ( model_name = "grad_bdt_clf" ,
storage_dir = "./storage" ,
objective = objective ,
n_trials = 50 ,
direction = "maximize" ,
load_if_exists = False )
optimized = True
best_model = GradientBoostingClassifier ( learning_rate = study.best_params["learn_rate"] ,
n_estimators = study.best_params["n_estims"] ,
max_depth = study.best_params["max_depth"] )
# +---------------------------+
# | Multiclass boundaries |
# +---------------------------+
# +-----------------------------------------+
# | Model performance on train/test set |
# +-----------------------------------------+
## train/val splitting
sss = StratifiedShuffleSplit ( n_splits = 1, test_size = val_size )
for idx_trn, idx_val in sss . split ( X_train, y_train ):
X_trn , y_trn = X_train[idx_trn] , y_train[idx_trn]
X_val , y_val = X_train[idx_val] , y_train[idx_val]
sm = SMOTE() # oversampling technique
X_trn_res, y_trn_res = sm.fit_resample ( X_trn , y_trn )
## combine the datasets
X_trn_comb = np.concatenate ( [ X_trn, X_gz ] )
y_trn_comb = np.concatenate ( [ np.where(y_trn, 3, 1), y_gz ] )
X_val_comb = np.concatenate ( [ X_val, X_gz ] )
y_val_comb = np.concatenate ( [ np.where(y_val, 3, 1), y_gz ] )
X_test_comb = np.concatenate ( [ X_test, X_gz ] )
y_test_comb = np.concatenate ( [ np.where(y_test, 3, 1), y_gz ] )
X_eval_comb = np.concatenate ( [ X_val, X_test, X_gz ] )
y_eval_comb = np.concatenate ( [ np.where(y_val, 3, 1) , np.where(y_test, 3, 1), y_gz ] )
## model training
best_model . fit (X_trn_res, y_trn_res)
## model predictions
y_scores_trn = best_model.predict_proba ( X_trn )
_, threshold = custom_predictions ( y_true = y_trn ,
y_scores = y_scores_trn ,
recall_score = rec_score ,
precision_score = prec_score )
y_scores_trn_comb = best_model.predict_proba ( X_trn_comb )
y_pred_trn = multiclass_predictions ( y_true = y_trn_comb ,
y_scores = y_scores_trn_comb ,
boundaries = get_decision_boundaries ( y_scores_trn, threshold, len(y_gz) / len(y_trn_comb) ) ) # pred for the true train-set
y_scores_val_comb = best_model.predict_proba ( X_val_comb )
y_pred_val = multiclass_predictions ( y_true = y_val_comb ,
y_scores = y_scores_val_comb ,
boundaries = get_decision_boundaries ( y_scores_trn, threshold, len(y_gz) / len(y_trn_comb) ) ) # pred for the val-set
y_scores_test_comb = best_model.predict_proba ( X_test_comb )
y_pred_test = multiclass_predictions ( y_true = y_test_comb ,
y_scores = y_scores_test_comb ,
boundaries = get_decision_boundaries ( y_scores_trn, threshold, len(y_gz) / len(y_trn_comb) ) ) # pred for the test-set
y_scores_eval_comb = best_model.predict_proba ( X_eval_comb )
y_pred_eval = multiclass_predictions ( y_true = y_eval_comb ,
y_scores = y_scores_eval_comb ,
boundaries = get_decision_boundaries ( y_scores_trn, threshold, len(y_gz) / len(y_trn_comb) ) ) # pred for the val-set + test-set
## model performances
conf_matrix_trn = confusion_matrix ( y_trn_comb, y_pred_trn )
recall_2 = conf_matrix_trn[2,2] / np.sum ( conf_matrix_trn[2,:] )
recall_1 = conf_matrix_trn[1,1] / np.sum ( conf_matrix_trn[1,:] )
precision_2 = conf_matrix_trn[2,2] / np.sum ( conf_matrix_trn[:,2] )
precision_1 = conf_matrix_trn[1,1] / np.sum ( conf_matrix_trn[:,1] )
conf_matrices[0] . append ( conf_matrix_trn ) # add to the relative container
recalls[0] . append ( [recall_2, recall_1] ) # add to the relative container
precisions[0] . append ( [precision_2, precision_1] ) # add to the relative container
conf_matrix_val = confusion_matrix ( y_val_comb, y_pred_val )
recall_2 = conf_matrix_val[2,2] / np.sum ( conf_matrix_val[2,:] )
recall_1 = conf_matrix_val[1,1] / np.sum ( conf_matrix_val[1,:] )
precision_2 = conf_matrix_val[2,2] / np.sum ( conf_matrix_val[:,2] )
precision_1 = conf_matrix_val[1,1] / np.sum ( conf_matrix_val[:,1] )
conf_matrices[1] . append ( conf_matrix_val ) # add to the relative container
recalls[1] . append ( [recall_2, recall_1] ) # add to the relative container
precisions[1] . append ( [precision_2, precision_1] ) # add to the relative container
conf_matrix_test = confusion_matrix ( y_test_comb, y_pred_test )
recall_2 = conf_matrix_test[2,2] / np.sum ( conf_matrix_test[2,:] )
recall_1 = conf_matrix_test[1,1] / np.sum ( conf_matrix_test[1,:] )
precision_2 = conf_matrix_test[2,2] / np.sum ( conf_matrix_test[:,2] )
precision_1 = conf_matrix_test[1,1] / np.sum ( conf_matrix_test[:,1] )
conf_matrices[2] . append ( conf_matrix_test ) # add to the relative container
recalls[2] . append ( [recall_2, recall_1] ) # add to the relative container
precisions[2] . append ( [precision_2, precision_1] ) # add to the relative container
auc_eval_2 = roc_auc_score ( (y_eval_comb == 3), y_scores_eval_comb[:,1] ) # one-vs-all AUC score (PMBCL class)
fpr_eval_2 , tpr_eval_2 , _ = roc_curve ( (y_eval_comb == 3), y_scores_eval_comb[:,1] ) # one-vs-all ROC curve (PMBCL class)
if (len(fpr_eval_2) == n_roc_points[0]): append_to_roc[0] = True
if append_to_roc[0]:
roc_curves[0] . append ( np.c_ [1 - fpr_eval_2, tpr_eval_2, auc_eval_2 * np.ones_like(fpr_eval_2)] ) # add to the relative container
append_to_roc[0] = False ; n_roc_points[0] = len(fpr_eval_2)
auc_eval_1 = roc_auc_score ( (y_eval_comb == 2), y_scores_eval_comb[:,1] ) # one-vs-all AUC score (GZL class)
fpr_eval_1 , tpr_eval_1 , _ = roc_curve ( (y_eval_comb == 2), y_scores_eval_comb[:,1] ) # one-vs-all ROC curve (GZL class)
if (len(fpr_eval_1) == n_roc_points[1]): append_to_roc[1] = True
if append_to_roc[1]:
roc_curves[1] . append ( np.c_ [1 - fpr_eval_1, tpr_eval_1, auc_eval_1 * np.ones_like(fpr_eval_1)] ) # add to the relative container
append_to_roc[1] = False ; n_roc_points[1] = len(fpr_eval_1)
# +----------------------+
# | Plots generation |
# +----------------------+
plot_conf_matrices ( conf_matrix = np.mean(conf_matrices[0], axis = 0) . astype(np.int32) ,
labels = LABELS ,
show_matrix = "both" ,
save_figure = True ,
fig_name = f"multi-clf/{args.model}/{args.model}_{args.threshold}_train" )
plot_conf_matrices ( conf_matrix = np.mean(conf_matrices[1], axis = 0) . astype(np.int32) ,
labels = LABELS ,
show_matrix = "both" ,
save_figure = True ,
fig_name = f"multi-clf/{args.model}/{args.model}_{args.threshold}_val" )
plot_conf_matrices ( conf_matrix = np.mean(conf_matrices[2], axis = 0) . astype(np.int32) ,
labels = LABELS ,
show_matrix = "both" ,
save_figure = True ,
fig_name = f"multi-clf/{args.model}/{args.model}_{args.threshold}_test" )
plot_multi_prf_histos ( rec_scores = ( np.array(recalls[0])[:,0] , np.array(recalls[0])[:,1] ) ,
prec_scores = ( np.array(precisions[0])[:,0] , np.array(precisions[0])[:,1] ) ,
bins = 25 ,
title = f"Performance of multi-class {model_name()} (on train-set)" ,
cls_labels = (LABELS[2], LABELS[1]) ,
save_figure = True ,
fig_name = f"multi-clf/{args.model}/{args.model}_{args.threshold}_train_prf" )
plot_multi_prf_histos ( rec_scores = ( np.array(recalls[1])[:,0] , np.array(recalls[1])[:,1] ) ,
prec_scores = ( np.array(precisions[1])[:,0] , np.array(precisions[1])[:,1] ) ,
bins = 25 ,
title = f"Performance of multi-class {model_name()} (on val-set)" ,
cls_labels = (LABELS[2], LABELS[1]) ,
save_figure = True ,
fig_name = f"multi-clf/{args.model}/{args.model}_{args.threshold}_val_prf" )
plot_multi_prf_histos ( rec_scores = ( np.array(recalls[2])[:,0] , np.array(recalls[2])[:,1] ) ,
prec_scores = ( np.array(precisions[2])[:,0] , np.array(precisions[2])[:,1] ) ,
bins = 25 ,
title = f"Performance of multi-class {model_name()} (on test-set)" ,
cls_labels = (LABELS[2], LABELS[1]) ,
save_figure = True ,
fig_name = f"multi-clf/{args.model}/{args.model}_{args.threshold}_test_prf" )
# +-------------------+
# | Scores export |
# +-------------------+
roc_vars_lbl3 = np.c_ [ np.mean(roc_curves[0], axis = 0) , np.std(roc_curves[0], axis = 0)[:,2] ]
roc_vars_lbl2 = np.c_ [ np.mean(roc_curves[1], axis = 0) , np.std(roc_curves[1], axis = 0)[:,2] ]
score_dir = "scores"
score_name = f"{args.model}_{args.threshold}"
filename = f"{score_dir}/multi-clf/{score_name}.npz"
np . savez ( filename, roc_vars_lbl3 = roc_vars_lbl3, roc_vars_lbl2 = roc_vars_lbl2 )
print (f"Scores correctly exported to {filename}")
| 45.115741 | 172 | 0.579682 | import os
import pickle
import numpy as np
from tqdm import tqdm
from argparse import ArgumentParser
import optuna
optuna.logging.set_verbosity ( optuna.logging.ERROR ) # silence Optuna during trials study
import warnings
warnings.filterwarnings ( "ignore", category = RuntimeWarning )
from sklearn.model_selection import StratifiedShuffleSplit
from sklearn.preprocessing import MinMaxScaler
from imblearn.over_sampling import SMOTE
from sklearn.linear_model import LogisticRegression
from sklearn.svm import SVC
from sklearn.gaussian_process import GaussianProcessClassifier
from sklearn.ensemble import RandomForestClassifier, GradientBoostingClassifier
from sklearn.feature_selection import RFECV
from sklearn.metrics import roc_auc_score, confusion_matrix, roc_curve
from utils import custom_predictions, multiclass_predictions, plot_conf_matrices, plot_multi_prf_histos
LABELS = ["cHL", "GZL", "PMBCL"]
# +-------------------+
# | Options setup |
# +-------------------+
MODELS = [ "log-reg", "lin-svm", "gaus-proc", "rnd-frs", "grad-bdt" ]
parser = ArgumentParser ( description = "training script" )
parser . add_argument ( "-m" , "--model" , required = True , choices = MODELS )
parser . add_argument ( "-s" , "--split" , default = "50/30/20" )
parser . add_argument ( "-t" , "--threshold" , default = "rec90" )
args = parser . parse_args()
if len ( args.split.split("/") ) == 2:
test_size = 0.5 * float(args.split.split("/")[-1]) / 100
val_size = test_size
val_size /= ( 1 - test_size ) # w.r.t. new dataset size
elif len ( args.split.split("/") ) == 3:
test_size = float(args.split.split("/")[2]) / 100
val_size = float(args.split.split("/")[1]) / 100
val_size /= ( 1 - test_size ) # w.r.t. new dataset size
else:
raise ValueError (f"The splitting ratios should be passed as 'XX/YY/ZZ', where XX% is "
f"the percentage of data used for training, while YY% and ZZ% are "
f"the ones used for validation and testing respectively.")
if "rec" in args.threshold:
rec_score = float(args.threshold.split("rec")[-1]) / 100
prec_score = None
elif "prec" in args.threshold:
rec_score = None
prec_score = float(args.threshold.split("prec")[-1]) / 100
else:
raise ValueError (f"The rule for custom predictions should be passed as 'recXX' where "
f"XX% is the minimum recall score required, or as 'precYY' where YY% "
f"is the minimum precision score required.")
# +------------------+
# | Data loading |
# +------------------+
data_dir = "./data"
data_file = "db_mediastinalbulky_reduced.pkl"
file_path = os.path.join ( data_dir, data_file )
with open (file_path, "rb") as file:
data = pickle.load (file)
# +------------------------------+
# | Input/output preparation |
# +------------------------------+
cols = list ( data.columns )
X_cols = cols[2:]
y_cols = "lymphoma_type"
X = data.query("lymphoma_type != 2")[X_cols] . to_numpy()
y = data.query("lymphoma_type != 2")[y_cols] . to_numpy() . flatten()
y = ( y == 3 ) # PMBCL/cHL classification
X_gz = data.query("lymphoma_type == 2")[X_cols] . to_numpy()
y_gz = data.query("lymphoma_type == 2")[y_cols] . to_numpy() . flatten()
# +------------------------+
# | Sub-sample studies |
# +------------------------+
conf_matrices = [ list() , list() , list() ] # container for confusion matrices
recalls = [ list() , list() , list() ] # container for recalls
precisions = [ list() , list() , list() ] # container for precisions
roc_curves = [ list() , list() ] # container for ROC curve variables
## initial control values
optimized = False
append_to_roc = [ True , True ]
n_roc_points = [ -1 , -1 ]
for i in tqdm(range(250)):
# +--------------------------+
# | Train/test splitting |
# +--------------------------+
sss = StratifiedShuffleSplit ( n_splits = 1, test_size = test_size )
for idx_train, idx_test in sss . split ( X, y ):
X_train , y_train = X[idx_train] , y[idx_train]
X_test , y_test = X[idx_test] , y[idx_test]
# +------------------------+
# | Data preprocessing |
# +------------------------+
scaler_train = MinMaxScaler()
X_train = scaler_train.fit_transform (X_train)
scaler_test = MinMaxScaler()
X_test = scaler_test.fit_transform (X_test)
scaler_gz = MinMaxScaler()
X_gz = scaler_gz.fit_transform (X_gz)
# +------------------+
# | Optuna setup |
# +------------------+
def optuna_study ( model_name : str ,
storage_dir : str ,
objective : float ,
n_trials : int = 10 ,
direction : str = "minimize" ,
load_if_exists : bool = False ) -> optuna.study.Study:
storage_path = "{}/{}.db" . format (storage_dir, model_name)
storage_name = "sqlite:///{}" . format (storage_path)
if load_if_exists:
pass
elif not ( load_if_exists ) and os.path.isfile ( storage_path ):
os.remove ( storage_path )
study = optuna.create_study ( study_name = model_name ,
storage = storage_name ,
load_if_exists = load_if_exists ,
direction = direction )
study . optimize ( objective, n_trials = n_trials )
return study
# +------------------------------+
# | Hyperparams optimization |
# +------------------------------+
## LOGISTIC REGRESSION
if args.model == "log-reg":
best_model = LogisticRegression()
## LINEAR SVM
elif args.model == "lin-svm":
best_model = SVC ( kernel = "linear", probability = True )
## GAUSSIAN PROCESS
elif args.model == "gaus-proc":
best_model = GaussianProcessClassifier()
## RANDOM FOREST
elif args.model == "rnd-frs":
def objective (trial):
## train/val splitting
sss = StratifiedShuffleSplit ( n_splits = 1, test_size = val_size )
for idx_train, idx_val in sss . split ( X_train, y_train ):
X_trn , y_trn = X_train[idx_train] , y_train[idx_train]
X_val , y_val = X_train[idx_val] , y_train[idx_val]
sm = SMOTE() # oversampling technique
X_trn_res, y_trn_res = sm.fit_resample ( X_trn , y_trn )
## hyperparams to optimize
n_estims = trial . suggest_int ( "n_estims" , 5 , 150 , log = True )
max_depth = trial . suggest_int ( "max_depth" , 1 , 10 )
## model to optimize
model = RandomForestClassifier ( n_estimators = n_estims ,
max_depth = max_depth )
model.fit (X_trn_res, y_trn_res)
y_scores = model.predict_proba (X_val)
return roc_auc_score ( y_val, y_scores[:,1] ) # score to optimize
if not optimized:
study = optuna_study ( model_name = "rnd_forest_clf" ,
storage_dir = "./storage" ,
objective = objective ,
n_trials = 50 ,
direction = "maximize" ,
load_if_exists = False )
optimized = True
best_model = RandomForestClassifier ( n_estimators = study.best_params["n_estims"] ,
max_depth = study.best_params["max_depth"] )
## GRADIENT BDT
elif args.model == "grad-bdt":
def objective (trial):
## train/val splitting
sss = StratifiedShuffleSplit ( n_splits = 1, test_size = val_size )
for idx_train, idx_val in sss . split ( X_train, y_train ):
X_trn , y_trn = X_train[idx_train] , y_train[idx_train]
X_val , y_val = X_train[idx_val] , y_train[idx_val]
sm = SMOTE() # oversampling technique
X_trn_res, y_trn_res = sm.fit_resample ( X_trn , y_trn )
## hyperparams to optimize
learn_rate = trial . suggest_float ( "learn_rate" , 5e-2 , 5e-1 , log = True )
n_estims = trial . suggest_int ( "n_estims" , 5 , 150 , log = True )
max_depth = trial . suggest_int ( "max_depth" , 1 , 10 )
## model to optimize
model = GradientBoostingClassifier ( learning_rate = learn_rate ,
n_estimators = n_estims ,
max_depth = max_depth )
model.fit (X_trn_res, y_trn_res)
y_scores = model.predict_proba (X_val)
return roc_auc_score ( y_val, y_scores[:,1] ) # score to optimize
if not optimized:
study = optuna_study ( model_name = "grad_bdt_clf" ,
storage_dir = "./storage" ,
objective = objective ,
n_trials = 50 ,
direction = "maximize" ,
load_if_exists = False )
optimized = True
best_model = GradientBoostingClassifier ( learning_rate = study.best_params["learn_rate"] ,
n_estimators = study.best_params["n_estims"] ,
max_depth = study.best_params["max_depth"] )
# +---------------------------+
# | Multiclass boundaries |
# +---------------------------+
def get_decision_boundaries ( y_scores : np.ndarray, threshold : float, width : float = 0.0 ) -> tuple:
hist, bins = np.histogram ( y_scores[:,1], bins = 20 )
cumsum = np.cumsum ( hist.astype(np.float32) )
cumsum /= cumsum[-1]
scores = ( bins[1:] + bins[:-1] ) / 2.0
th_cumsum = np.interp ( threshold, scores, cumsum ) # cumulative value of the threshold
th_cumsum_min = th_cumsum - width / 2.0
score_min = np.interp (th_cumsum_min, cumsum, scores)
th_cumsum_max = th_cumsum + width / 2.0
score_max = np.interp (th_cumsum_max, cumsum, scores)
return score_min, score_max
# +-----------------------------------------+
# | Model performance on train/test set |
# +-----------------------------------------+
## train/val splitting
sss = StratifiedShuffleSplit ( n_splits = 1, test_size = val_size )
for idx_trn, idx_val in sss . split ( X_train, y_train ):
X_trn , y_trn = X_train[idx_trn] , y_train[idx_trn]
X_val , y_val = X_train[idx_val] , y_train[idx_val]
sm = SMOTE() # oversampling technique
X_trn_res, y_trn_res = sm.fit_resample ( X_trn , y_trn )
## combine the datasets
X_trn_comb = np.concatenate ( [ X_trn, X_gz ] )
y_trn_comb = np.concatenate ( [ np.where(y_trn, 3, 1), y_gz ] )
X_val_comb = np.concatenate ( [ X_val, X_gz ] )
y_val_comb = np.concatenate ( [ np.where(y_val, 3, 1), y_gz ] )
X_test_comb = np.concatenate ( [ X_test, X_gz ] )
y_test_comb = np.concatenate ( [ np.where(y_test, 3, 1), y_gz ] )
X_eval_comb = np.concatenate ( [ X_val, X_test, X_gz ] )
y_eval_comb = np.concatenate ( [ np.where(y_val, 3, 1) , np.where(y_test, 3, 1), y_gz ] )
## model training
best_model . fit (X_trn_res, y_trn_res)
## model predictions
y_scores_trn = best_model.predict_proba ( X_trn )
_, threshold = custom_predictions ( y_true = y_trn ,
y_scores = y_scores_trn ,
recall_score = rec_score ,
precision_score = prec_score )
y_scores_trn_comb = best_model.predict_proba ( X_trn_comb )
y_pred_trn = multiclass_predictions ( y_true = y_trn_comb ,
y_scores = y_scores_trn_comb ,
boundaries = get_decision_boundaries ( y_scores_trn, threshold, len(y_gz) / len(y_trn_comb) ) ) # pred for the true train-set
y_scores_val_comb = best_model.predict_proba ( X_val_comb )
y_pred_val = multiclass_predictions ( y_true = y_val_comb ,
y_scores = y_scores_val_comb ,
boundaries = get_decision_boundaries ( y_scores_trn, threshold, len(y_gz) / len(y_trn_comb) ) ) # pred for the val-set
y_scores_test_comb = best_model.predict_proba ( X_test_comb )
y_pred_test = multiclass_predictions ( y_true = y_test_comb ,
y_scores = y_scores_test_comb ,
boundaries = get_decision_boundaries ( y_scores_trn, threshold, len(y_gz) / len(y_trn_comb) ) ) # pred for the test-set
y_scores_eval_comb = best_model.predict_proba ( X_eval_comb )
y_pred_eval = multiclass_predictions ( y_true = y_eval_comb ,
y_scores = y_scores_eval_comb ,
boundaries = get_decision_boundaries ( y_scores_trn, threshold, len(y_gz) / len(y_trn_comb) ) ) # pred for the val-set + test-set
## model performances
conf_matrix_trn = confusion_matrix ( y_trn_comb, y_pred_trn )
recall_2 = conf_matrix_trn[2,2] / np.sum ( conf_matrix_trn[2,:] )
recall_1 = conf_matrix_trn[1,1] / np.sum ( conf_matrix_trn[1,:] )
precision_2 = conf_matrix_trn[2,2] / np.sum ( conf_matrix_trn[:,2] )
precision_1 = conf_matrix_trn[1,1] / np.sum ( conf_matrix_trn[:,1] )
conf_matrices[0] . append ( conf_matrix_trn ) # add to the relative container
recalls[0] . append ( [recall_2, recall_1] ) # add to the relative container
precisions[0] . append ( [precision_2, precision_1] ) # add to the relative container
conf_matrix_val = confusion_matrix ( y_val_comb, y_pred_val )
recall_2 = conf_matrix_val[2,2] / np.sum ( conf_matrix_val[2,:] )
recall_1 = conf_matrix_val[1,1] / np.sum ( conf_matrix_val[1,:] )
precision_2 = conf_matrix_val[2,2] / np.sum ( conf_matrix_val[:,2] )
precision_1 = conf_matrix_val[1,1] / np.sum ( conf_matrix_val[:,1] )
conf_matrices[1] . append ( conf_matrix_val ) # add to the relative container
recalls[1] . append ( [recall_2, recall_1] ) # add to the relative container
precisions[1] . append ( [precision_2, precision_1] ) # add to the relative container
conf_matrix_test = confusion_matrix ( y_test_comb, y_pred_test )
recall_2 = conf_matrix_test[2,2] / np.sum ( conf_matrix_test[2,:] )
recall_1 = conf_matrix_test[1,1] / np.sum ( conf_matrix_test[1,:] )
precision_2 = conf_matrix_test[2,2] / np.sum ( conf_matrix_test[:,2] )
precision_1 = conf_matrix_test[1,1] / np.sum ( conf_matrix_test[:,1] )
conf_matrices[2] . append ( conf_matrix_test ) # add to the relative container
recalls[2] . append ( [recall_2, recall_1] ) # add to the relative container
precisions[2] . append ( [precision_2, precision_1] ) # add to the relative container
auc_eval_2 = roc_auc_score ( (y_eval_comb == 3), y_scores_eval_comb[:,1] ) # one-vs-all AUC score (PMBCL class)
fpr_eval_2 , tpr_eval_2 , _ = roc_curve ( (y_eval_comb == 3), y_scores_eval_comb[:,1] ) # one-vs-all ROC curve (PMBCL class)
if (len(fpr_eval_2) == n_roc_points[0]): append_to_roc[0] = True
if append_to_roc[0]:
roc_curves[0] . append ( np.c_ [1 - fpr_eval_2, tpr_eval_2, auc_eval_2 * np.ones_like(fpr_eval_2)] ) # add to the relative container
append_to_roc[0] = False ; n_roc_points[0] = len(fpr_eval_2)
auc_eval_1 = roc_auc_score ( (y_eval_comb == 2), y_scores_eval_comb[:,1] ) # one-vs-all AUC score (GZL class)
fpr_eval_1 , tpr_eval_1 , _ = roc_curve ( (y_eval_comb == 2), y_scores_eval_comb[:,1] ) # one-vs-all ROC curve (GZL class)
if (len(fpr_eval_1) == n_roc_points[1]): append_to_roc[1] = True
if append_to_roc[1]:
roc_curves[1] . append ( np.c_ [1 - fpr_eval_1, tpr_eval_1, auc_eval_1 * np.ones_like(fpr_eval_1)] ) # add to the relative container
append_to_roc[1] = False ; n_roc_points[1] = len(fpr_eval_1)
# +----------------------+
# | Plots generation |
# +----------------------+
def model_name() -> str:
if args.model == "log-reg" : return "Logistic Regression"
elif args.model == "lin-svm" : return "Linear SVM classifier"
elif args.model == "gaus-proc" : return "Gaussian Process classifier"
elif args.model == "rnd-frs" : return "Random Forest classifier"
elif args.model == "grad-bdt" : return "Gradient BDT classifier"
plot_conf_matrices ( conf_matrix = np.mean(conf_matrices[0], axis = 0) . astype(np.int32) ,
labels = LABELS ,
show_matrix = "both" ,
save_figure = True ,
fig_name = f"multi-clf/{args.model}/{args.model}_{args.threshold}_train" )
plot_conf_matrices ( conf_matrix = np.mean(conf_matrices[1], axis = 0) . astype(np.int32) ,
labels = LABELS ,
show_matrix = "both" ,
save_figure = True ,
fig_name = f"multi-clf/{args.model}/{args.model}_{args.threshold}_val" )
plot_conf_matrices ( conf_matrix = np.mean(conf_matrices[2], axis = 0) . astype(np.int32) ,
labels = LABELS ,
show_matrix = "both" ,
save_figure = True ,
fig_name = f"multi-clf/{args.model}/{args.model}_{args.threshold}_test" )
plot_multi_prf_histos ( rec_scores = ( np.array(recalls[0])[:,0] , np.array(recalls[0])[:,1] ) ,
prec_scores = ( np.array(precisions[0])[:,0] , np.array(precisions[0])[:,1] ) ,
bins = 25 ,
title = f"Performance of multi-class {model_name()} (on train-set)" ,
cls_labels = (LABELS[2], LABELS[1]) ,
save_figure = True ,
fig_name = f"multi-clf/{args.model}/{args.model}_{args.threshold}_train_prf" )
plot_multi_prf_histos ( rec_scores = ( np.array(recalls[1])[:,0] , np.array(recalls[1])[:,1] ) ,
prec_scores = ( np.array(precisions[1])[:,0] , np.array(precisions[1])[:,1] ) ,
bins = 25 ,
title = f"Performance of multi-class {model_name()} (on val-set)" ,
cls_labels = (LABELS[2], LABELS[1]) ,
save_figure = True ,
fig_name = f"multi-clf/{args.model}/{args.model}_{args.threshold}_val_prf" )
plot_multi_prf_histos ( rec_scores = ( np.array(recalls[2])[:,0] , np.array(recalls[2])[:,1] ) ,
prec_scores = ( np.array(precisions[2])[:,0] , np.array(precisions[2])[:,1] ) ,
bins = 25 ,
title = f"Performance of multi-class {model_name()} (on test-set)" ,
cls_labels = (LABELS[2], LABELS[1]) ,
save_figure = True ,
fig_name = f"multi-clf/{args.model}/{args.model}_{args.threshold}_test_prf" )
# +-------------------+
# | Scores export |
# +-------------------+
roc_vars_lbl3 = np.c_ [ np.mean(roc_curves[0], axis = 0) , np.std(roc_curves[0], axis = 0)[:,2] ]
roc_vars_lbl2 = np.c_ [ np.mean(roc_curves[1], axis = 0) , np.std(roc_curves[1], axis = 0)[:,2] ]
score_dir = "scores"
score_name = f"{args.model}_{args.threshold}"
filename = f"{score_dir}/multi-clf/{score_name}.npz"
np . savez ( filename, roc_vars_lbl3 = roc_vars_lbl3, roc_vars_lbl2 = roc_vars_lbl2 )
print (f"Scores correctly exported to {filename}")
| 3,795 | 0 | 125 |
bfa57a625f2be19d4a30738c7fd3f863a0804ed1 | 6,048 | py | Python | Leak #5 - Lost In Translation/windows/Resources/Ops/PyScripts/windows/eventlogs.py | bidhata/EquationGroupLeaks | 1ff4bc115cb2bd5bf2ed6bf769af44392926830c | [
"Unlicense"
] | 9 | 2019-11-22T04:58:40.000Z | 2022-02-26T16:47:28.000Z | Python.Fuzzbunch/Resources/Ops/PyScripts/windows/eventlogs.py | 010001111/Vx-Suites | 6b4b90a60512cce48aa7b87aec5e5ac1c4bb9a79 | [
"MIT"
] | null | null | null | Python.Fuzzbunch/Resources/Ops/PyScripts/windows/eventlogs.py | 010001111/Vx-Suites | 6b4b90a60512cce48aa7b87aec5e5ac1c4bb9a79 | [
"MIT"
] | 8 | 2017-09-27T10:31:18.000Z | 2022-01-08T10:30:46.000Z |
import dsz, dsz.cmd, dsz.control
import ops, ops.pprint
import ops.data
import traceback, sys
from optparse import OptionParser
if (__name__ == '__main__'):
usage = 'python windows\\eventloqs.py [Options]\n-m, --monitor \n Runs in monitor mode, defaults to false\n-i, --interval [timeinterval]\n Interval between eventlogquery commands to use when running in monitor mode\n-l, --log [logname]\n Restricts query/monitor to one log\n-c, --classic\n If present, only queries System/Security/Application logs\n-t, --target\n Remote target to query\n'
parser = OptionParser(usage=usage)
parser.add_option('-m', '--monitor', dest='monitor', action='store_true', default=False)
parser.add_option('-c', '--classic', dest='classic', action='store_true', default=False)
parser.add_option('-i', '--interval', dest='interval', type='int', action='store', default='300')
parser.add_option('-l', '--log', dest='logname', type='string', action='store', default='')
parser.add_option('-t', '--target', dest='target', type='string', action='store', default=None)
(options, args) = parser.parse_args(sys.argv)
if options.monitor:
monitorlogs(options.interval, options.classic, options.logname, options.target)
else:
logs = logquery(options.logname, options.target, options.classic)
printlogtable(logs) | 52.137931 | 408 | 0.581019 |
import dsz, dsz.cmd, dsz.control
import ops, ops.pprint
import ops.data
import traceback, sys
from optparse import OptionParser
def monitorlogs(interval=300, classic=False, logname='', target=None, filters=[]):
logquerycmd = 'eventlogquery '
if classic:
logquerycmd += ' -classic '
elif (logname != ''):
logquerycmd += (' -log %s ' % logname)
if target:
logquerycmd += (' -target %s ' % target)
z = dsz.control.Method()
dsz.control.echo.Off()
(success, cmdid) = dsz.cmd.RunEx(logquerycmd, dsz.RUN_FLAG_RECORD)
logsbase = ops.data.getDszObject(cmdid=cmdid).eventlog
try:
while True:
dsz.Sleep((interval * 1000))
(success, cmdid) = dsz.cmd.RunEx(logquerycmd, dsz.RUN_FLAG_RECORD)
stamp = dsz.Timestamp()
newlogs = ops.data.getDszObject(cmdid=cmdid).eventlog
for i in range(len(newlogs)):
(oldlog, newlog) = (logsbase[i], newlogs[i])
if (newlog.mostrecentrecordnum > oldlog.mostrecentrecordnum):
dsz.control.echo.Off()
ops.info(('New logs in %s as of %s' % (oldlog.name, stamp)))
try:
newrecs = recordquery(logname=oldlog.name, start=(oldlog.mostrecentrecordnum + 1), end=newlog.mostrecentrecordnum, target=target)
except:
ops.error(('Error getting records for log %s' % oldlog.name))
traceback.print_exc(sys.exc_info())
continue
if (not newrecs):
ops.error(('Error getting records for log %s' % oldlog.name))
continue
if (len(newrecs) > 0):
ops.info(('-----------------New logs in %s-------------------' % oldlog.name))
for newrec in newrecs:
print ('%d: %d - %s %s' % (newrec.number, newrec.id, newrec.datewritten, newrec.timewritten))
print ('User: %s --- Computer: %s' % (newrec.user, newrec.computer))
print ('Source: %s' % newrec.source)
print ('Type: %s' % newrec.eventtype)
stringslist = ''
for strval in newrec.string:
stringslist += (strval.value + ', ')
print ('Strings: %s' % stringslist)
print '---------------------------------------------------------'
logsbase = newlogs
except RuntimeError as ex:
if (ex.args[0] == 'User QUIT SCRIPT'):
ops.info('You quit monitoring')
return
except KeyboardInterrupt:
ops.info('You hit Ctrl-D, which means you want to stop monitoring logs, so I am stopping')
return
def recordquery(logname=None, start=None, end='', **params):
if (logname is None):
ops.error('You must specify a log to query records')
return None
if (start is None):
ops.error('You must specify record numbers to query records')
return None
cmd = ('eventlogquery -log "%s" -record %d %s' % (logname, start, end))
if (('target' in params) and (params['target'] is not None)):
cmd += (' -target %s' % params['target'])
x = dsz.control.Method()
dsz.control.echo.Off()
(success, cmdid) = dsz.cmd.RunEx(cmd, dsz.RUN_FLAG_RECORD)
if success:
return ops.data.getDszObject(cmdid=cmdid).record
else:
ops.error(('Your command "%s" failed to run, please see your logs for command ID %d for further details' % (cmd, cmdid)))
return None
def logquery(logname=None, target=None, classic=False, **params):
cmd = 'eventlogquery '
if classic:
cmd += ' -classic '
if (target is not None):
cmd += (' -target %s ' % target)
if (logname is not None):
cmd += (' -log "%s" ' % logname)
x = dsz.control.Method()
dsz.control.echo.Off()
(success, cmdid) = dsz.cmd.RunEx(cmd, dsz.RUN_FLAG_RECORD)
if success:
return ops.data.getDszObject(cmdid=cmdid)
else:
ops.error(('Your command "%s" failed to run, please see your logs for command ID %d for further details' % (cmd, cmdid)))
return None
def printlogtable(logs):
restable = []
for log in filter((lambda x: (x.numrecords > 0)), logs.eventlog):
restable.append({'name': log.name, 'records': log.numrecords, 'recordspan': ('%s - %s' % (log.oldestrecordnum, log.mostrecentrecordnum)), 'moddatetime': ('%s %s' % (log.lastmodifieddate, log.lastmodifiedtime))})
restable.sort(key=(lambda x: x['moddatetime']))
ops.pprint.pprint(restable, ['Log name', 'Last date', 'Range'], ['name', 'moddatetime', 'recordspan'])
if (__name__ == '__main__'):
usage = 'python windows\\eventloqs.py [Options]\n-m, --monitor \n Runs in monitor mode, defaults to false\n-i, --interval [timeinterval]\n Interval between eventlogquery commands to use when running in monitor mode\n-l, --log [logname]\n Restricts query/monitor to one log\n-c, --classic\n If present, only queries System/Security/Application logs\n-t, --target\n Remote target to query\n'
parser = OptionParser(usage=usage)
parser.add_option('-m', '--monitor', dest='monitor', action='store_true', default=False)
parser.add_option('-c', '--classic', dest='classic', action='store_true', default=False)
parser.add_option('-i', '--interval', dest='interval', type='int', action='store', default='300')
parser.add_option('-l', '--log', dest='logname', type='string', action='store', default='')
parser.add_option('-t', '--target', dest='target', type='string', action='store', default=None)
(options, args) = parser.parse_args(sys.argv)
if options.monitor:
monitorlogs(options.interval, options.classic, options.logname, options.target)
else:
logs = logquery(options.logname, options.target, options.classic)
printlogtable(logs) | 4,593 | 0 | 92 |
f01b4e41f742d0c8d1d8141475e3f06a6e34955a | 15 | py | Python | src/quiltz/testsupport/version.py | qwaneu/quiltz-testsupport | d28df8657818fae75208ed0cf50d417955e92ba4 | [
"MIT"
] | null | null | null | src/quiltz/testsupport/version.py | qwaneu/quiltz-testsupport | d28df8657818fae75208ed0cf50d417955e92ba4 | [
"MIT"
] | null | null | null | src/quiltz/testsupport/version.py | qwaneu/quiltz-testsupport | d28df8657818fae75208ed0cf50d417955e92ba4 | [
"MIT"
] | null | null | null | version="0.2.1" | 15 | 15 | 0.666667 | version="0.2.1" | 0 | 0 | 0 |
e68c325abae9f0d6f6a4ce2e2488f4c69bba4a5f | 733 | py | Python | src/oscar/management/commands/oscar_send_alerts.py | sainjusajan/django-oscar | 466e8edc807be689b0a28c9e525c8323cc48b8e1 | [
"BSD-3-Clause"
] | null | null | null | src/oscar/management/commands/oscar_send_alerts.py | sainjusajan/django-oscar | 466e8edc807be689b0a28c9e525c8323cc48b8e1 | [
"BSD-3-Clause"
] | null | null | null | src/oscar/management/commands/oscar_send_alerts.py | sainjusajan/django-oscar | 466e8edc807be689b0a28c9e525c8323cc48b8e1 | [
"BSD-3-Clause"
] | null | null | null | import logging
from django.core.management.base import BaseCommand
from django.utils.translation import ugettext_lazy as _
from oscar.apps.customer.alerts import utils
logger = logging.getLogger(__name__)
class Command(BaseCommand):
"""
Check stock records of products for availability and send out alerts
to customers that have registered for an alert.
"""
help = _("Check for products that are back in "
"stock and send out alerts")
def handle(self, **options):
"""
Check all products with active product alerts for
availability and send out email alerts when a product is
available to buy.
"""
utils.send_alerts()
| 28.192308 | 73 | 0.665757 | import logging
from django.core.management.base import BaseCommand
from django.utils.translation import ugettext_lazy as _
from oscar.apps.customer.alerts import utils
logger = logging.getLogger(__name__)
class Command(BaseCommand):
"""
Check stock records of products for availability and send out alerts
to customers that have registered for an alert.
"""
help = _("Check for products that are back in "
"stock and send out alerts")
def handle(self, **options):
"""
Check all products with active product alerts for
availability and send out email alerts when a product is
available to buy.
"""
utils.send_alerts()
| 0 | 0 | 0 |
2ee02461bd282a5d55728439acfafc1cef05a08c | 4,175 | py | Python | conda_smithy/tests/test_lint_recipe.py | janschulz/conda-smithy | 7474c0cd668c7141f7aa936cf5603dae3f76697e | [
"BSD-3-Clause"
] | null | null | null | conda_smithy/tests/test_lint_recipe.py | janschulz/conda-smithy | 7474c0cd668c7141f7aa936cf5603dae3f76697e | [
"BSD-3-Clause"
] | null | null | null | conda_smithy/tests/test_lint_recipe.py | janschulz/conda-smithy | 7474c0cd668c7141f7aa936cf5603dae3f76697e | [
"BSD-3-Clause"
] | null | null | null | from __future__ import print_function
from collections import OrderedDict
import os
import shutil
import subprocess
import tempfile
import textwrap
import unittest
import conda_smithy.lint_recipe as linter
if __name__ == '__main__':
unittest.main()
| 35.381356 | 122 | 0.582754 | from __future__ import print_function
from collections import OrderedDict
import os
import shutil
import subprocess
import tempfile
import textwrap
import unittest
import conda_smithy.lint_recipe as linter
class Test_linter(unittest.TestCase):
def test_bad_order(self):
meta = OrderedDict([['package', []],
['build', []],
['source', []]])
lints = linter.lintify(meta)
expected_message = "The top level meta keys are in an unexpected order. Expecting ['package', 'source', 'build']."
self.assertIn(expected_message, lints)
def test_missing_about_license_and_summary(self):
meta = {'about': {'home': 'a URL'}}
lints = linter.lintify(meta)
expected_message = "The license item is expected in the about section."
self.assertIn(expected_message, lints)
expected_message = "The summary item is expected in the about section."
self.assertIn(expected_message, lints)
def test_missing_about_home(self):
meta = {'about': {'license': 'BSD',
'summary': 'A test summary'}}
lints = linter.lintify(meta)
expected_message = "The home item is expected in the about section."
self.assertIn(expected_message, lints)
def test_missing_about_home_empty(self):
meta = {'about': {'home': '',
'summary': '',
'license': ''}}
lints = linter.lintify(meta)
expected_message = "The home item is expected in the about section."
self.assertIn(expected_message, lints)
expected_message = "The license item is expected in the about section."
self.assertIn(expected_message, lints)
expected_message = "The summary item is expected in the about section."
self.assertIn(expected_message, lints)
def test_maintainers_section(self):
expected_message = 'The recipe could do with some maintainers listed in the "extra/recipe-maintainers" section.'
lints = linter.lintify({'extra': {'recipe-maintainers': []}})
self.assertIn(expected_message, lints)
# No extra section at all.
lints = linter.lintify({})
self.assertIn(expected_message, lints)
lints = linter.lintify({'extra': {'recipe-maintainers': ['a']}})
self.assertNotIn(expected_message, lints)
def test_test_section(self):
expected_message = 'The recipe must have some tests.'
lints = linter.lintify({})
self.assertIn(expected_message, lints)
lints = linter.lintify({'test': {'imports': 'sys'}})
self.assertNotIn(expected_message, lints)
class TestCLI_recipe_lint(unittest.TestCase):
def setUp(self):
self.tmp_dir = tempfile.mkdtemp('recipe_')
def tearDown(self):
shutil.rmtree(self.tmp_dir)
def test_cli_fail(self):
with open(os.path.join(self.tmp_dir, 'meta.yaml'), 'w') as fh:
fh.write(textwrap.dedent("""
package:
name: 'test_package'
build: []
requirements: []
"""))
child = subprocess.Popen(['conda-smithy', 'recipe-lint', self.tmp_dir],
stdout=subprocess.PIPE)
child.communicate()
self.assertEqual(child.returncode, 1)
def test_cli_success(self):
with open(os.path.join(self.tmp_dir, 'meta.yaml'), 'w') as fh:
fh.write(textwrap.dedent("""
package:
name: 'test_package'
test: []
about:
home: something
license: something else
summary: a test recipe
extra:
recipe-maintainers:
- a
- b
"""))
child = subprocess.Popen(['conda-smithy', 'recipe-lint', self.tmp_dir],
stdout=subprocess.PIPE)
child.communicate()
self.assertEqual(child.returncode, 0)
if __name__ == '__main__':
unittest.main()
| 3,562 | 40 | 315 |
9c9ab098a56dd8c3910188c0bdf3b72a68d8d56c | 1,732 | py | Python | scripts/split_fasta.py | EnvGen/toolbox | a644560d989316fffd72c696e60c95ed713f6236 | [
"MIT"
] | 5 | 2018-07-02T06:34:09.000Z | 2021-06-09T00:32:45.000Z | scripts/split_fasta.py | EnvGen/toolbox | a644560d989316fffd72c696e60c95ed713f6236 | [
"MIT"
] | 5 | 2016-09-23T08:52:53.000Z | 2019-12-19T08:49:11.000Z | scripts/split_fasta.py | EnvGen/toolbox | a644560d989316fffd72c696e60c95ed713f6236 | [
"MIT"
] | 1 | 2020-04-28T18:45:56.000Z | 2020-04-28T18:45:56.000Z | #!/usr/bin/env python
"""A script to split a fasta file into multiple smaller files.
Output files will be <original>.xx.fasta
"""
from __future__ import print_function
import argparse
import sys
import os
import re
from os.path import join as ospj
if __name__ == "__main__":
parser = argparse.ArgumentParser(description=__doc__)
parser.add_argument('--outdir', '-o', help="output directory")
parser.add_argument('--input_fasta', help="Input read fasta 1")
parser.add_argument('--prefix', help="output prefix")
parser.add_argument('n_seqs', type=int, help="Number of sequences per file, the last file will contain slightly less")
args = parser.parse_args()
main(args)
| 27.935484 | 122 | 0.64261 | #!/usr/bin/env python
"""A script to split a fasta file into multiple smaller files.
Output files will be <original>.xx.fasta
"""
from __future__ import print_function
import argparse
import sys
import os
import re
from os.path import join as ospj
def header(row):
regex = re.compile("^>")
return regex.findall(row)
def next_output_file(input_file, prefix, outdir, i):
if input_file is not None:
prefix = ".".join(os.path.basename(input_file).split('.')[0:])
new_filename = "{0}.{1}.fasta".format(prefix, i)
print(new_filename)
if outdir is not None:
return open(ospj(outdir, new_filename), 'w')
else:
return open(new_filename, 'w')
def main(args):
if args.input_fasta is not None:
input_handle = open(args.input_fasta, 'r')
else:
input_handle = sys.stdin
n = 0
i = 0
outputfh = next_output_file(args.input_fasta, args.prefix, args.outdir, i)
for row in input_handle:
if header(row):
n+=1
if n > args.n_seqs:
i += 1
n = 1
outputfh.close()
outputfh = next_output_file(args.input_fasta, args.prefix, args.outdir, i)
outputfh.write(row)
outputfh.close()
input_handle.close()
if __name__ == "__main__":
parser = argparse.ArgumentParser(description=__doc__)
parser.add_argument('--outdir', '-o', help="output directory")
parser.add_argument('--input_fasta', help="Input read fasta 1")
parser.add_argument('--prefix', help="output prefix")
parser.add_argument('n_seqs', type=int, help="Number of sequences per file, the last file will contain slightly less")
args = parser.parse_args()
main(args)
| 965 | 0 | 69 |
6f9a31ec57f043ee015bf879c14c27a2999e8772 | 3,122 | py | Python | database.py | luontonurkka/fetcher | 439d3531b13dcf296c75c1a637dce4e7a7cf8b91 | [
"MIT"
] | null | null | null | database.py | luontonurkka/fetcher | 439d3531b13dcf296c75c1a637dce4e7a7cf8b91 | [
"MIT"
] | null | null | null | database.py | luontonurkka/fetcher | 439d3531b13dcf296c75c1a637dce4e7a7cf8b91 | [
"MIT"
] | null | null | null | # -*- coding: utf-8 -*-
import dataset,codecs, Names, sqlite3
"""
Under MIT-Licence, 2016 Perttu Rautaniemi
"""
def createtables():
"""
Opening the database and tables, create tables if they dont exist
"""
conn = sqlite3.connect('LuontonurkkaDB.db')
conn.execute('''CREATE TABLE `grid` (
`id` INTEGER NOT NULL,
`N` INTEGER NOT NULL,
`E` INTEGER NOT NULL,
`sqrname` VARCHAR,
PRIMARY KEY(id)
);''')
conn.execute('''CREATE TABLE `species` (
`id` INTEGER NOT NULL,
`namelatin` VARCHAR NOT NULL,
`namefin` VARCHAR,
`type` INTEGER NOT NULL,
`picture` VARCHAR,
`idEN` VARCHAR,
`idFI` VARCHAR,
PRIMARY KEY(id)
);''')
conn.execute('''CREATE TABLE "species_in_square" (
`id` INTEGER NOT NULL,
`sid` INTEGER NOT NULL,
`gid` INTEGER NOT NULL,
`freq` INTEGER,
PRIMARY KEY(id)
)''')
##
## Sql for indexes
##
conn.execute('''CREATE INDEX gridIndex
on grid (N, E);''')
conn.execute('''CREATE INDEX sqrID
on species_in_square (gid);''')
conn.close()
"""filling both species in square and square tables using id data from speciestable and gridcsv for"""
#createtables()
data_fillfromCSV() | 29.17757 | 118 | 0.584241 | # -*- coding: utf-8 -*-
import dataset,codecs, Names, sqlite3
"""
Under MIT-Licence, 2016 Perttu Rautaniemi
"""
def createtables():
"""
Opening the database and tables, create tables if they dont exist
"""
conn = sqlite3.connect('LuontonurkkaDB.db')
conn.execute('''CREATE TABLE `grid` (
`id` INTEGER NOT NULL,
`N` INTEGER NOT NULL,
`E` INTEGER NOT NULL,
`sqrname` VARCHAR,
PRIMARY KEY(id)
);''')
conn.execute('''CREATE TABLE `species` (
`id` INTEGER NOT NULL,
`namelatin` VARCHAR NOT NULL,
`namefin` VARCHAR,
`type` INTEGER NOT NULL,
`picture` VARCHAR,
`idEN` VARCHAR,
`idFI` VARCHAR,
PRIMARY KEY(id)
);''')
conn.execute('''CREATE TABLE "species_in_square" (
`id` INTEGER NOT NULL,
`sid` INTEGER NOT NULL,
`gid` INTEGER NOT NULL,
`freq` INTEGER,
PRIMARY KEY(id)
)''')
##
## Sql for indexes
##
conn.execute('''CREATE INDEX gridIndex
on grid (N, E);''')
conn.execute('''CREATE INDEX sqrID
on species_in_square (gid);''')
conn.close()
"""filling both species in square and square tables using id data from speciestable and gridcsv for"""
def data_fillfromCSV():
db = dataset.connect('sqlite:///LuontonurkkaDB.db')
tableSquare = db.get_table("grid")
tableSpecies = db.get_table("species")
tableSpeSqr = db.get_table("species_in_square")
csv = codecs.open("species.CSV", "r", "UTF-8")
asdi = csv.readlines()
datablob = {}
specieslist = []
counter = 1
for line in asdi:
if not line.__contains__("###ERROR###"):
specdata = line.split(',')
specdata[5] = specdata[5].strip("\n")
data = dict(id=counter, namelatin=specdata[0], namefin=specdata[1], type=specdata[2], picture=specdata[3],
idEN=specdata[4], idFI=specdata[5])
counter += 1
specieslist.append(data)
datablob[specdata[0]] = data
gridcsv = codecs.open("grid_sorted.csv", "r", "UTF-8")
gridnames = Names.getgridnames()
listItems = []
listCoords = []
stackItems = gridcsv.readlines()
for line in stackItems:
blo = []
blo = line.split(',')
bla = blo[0].split(':')
namn =""
for i, dic in enumerate(gridnames):
if dic['N'] == bla[0] and dic['E'] == bla[1]:
namn = dic['name']
acab = dict(N=bla[0], E=bla[1], sqrname=namn)
listCoords.append(acab)
del blo[0]
for item in blo:
species = item.split(':')
spec = datablob.get(species[0]) # replace the name with id from speciestable
if spec is not None:
specgrid = len(listCoords) # replace coords with ID from squaretable
info = dict(sid=spec['id'], gid=specgrid, freq=species[2].strip("\r\n"))
listItems.append(info)
#finally, the inserts
tableSpecies.insert_many(specieslist)
tableSquare.insert_many(listCoords)
tableSpeSqr.insert_many(listItems)
#createtables()
data_fillfromCSV() | 1,855 | 0 | 22 |
f3ec3f1a6c80881e00dc45f2e1504d19fe743b75 | 2,316 | py | Python | pyHMI/SimGas.py | sourceperl/pyHMI | 61f2742181372a2cff24b6dec5af920dddc210c9 | [
"MIT"
] | null | null | null | pyHMI/SimGas.py | sourceperl/pyHMI | 61f2742181372a2cff24b6dec5af920dddc210c9 | [
"MIT"
] | null | null | null | pyHMI/SimGas.py | sourceperl/pyHMI | 61f2742181372a2cff24b6dec5af920dddc210c9 | [
"MIT"
] | null | null | null | # -*- coding: utf-8 -*-
import math
import threading
import time
| 25.450549 | 96 | 0.58247 | # -*- coding: utf-8 -*-
import math
import threading
import time
class GasPipe:
def __init__(self, init_volume=50000, water_volume=10000):
# private
self._add_flow = 0
self._sub_flow = 0
self._stock_vol = init_volume
self._water_vol = water_volume
self._th_lock = threading.Lock()
# start update thread
self._th = threading.Thread(target=self._updater)
self._th.daemon = True
self._th.start()
@property
def in_flow(self):
with self._th_lock:
return self._add_flow
@in_flow.setter
def in_flow(self, value):
with self._th_lock:
self._add_flow = value
@property
def out_flow(self):
with self._th_lock:
return self._sub_flow
@out_flow.setter
def out_flow(self, value):
with self._th_lock:
self._sub_flow = value
@property
def avg_p(self):
with self._th_lock:
return self._stock_vol / self._water_vol
@property
def water_vol(self):
with self._th_lock:
return self._water_vol
@property
def current_vol(self):
with self._th_lock:
return self._stock_vol
def _updater(self):
while True:
with self._th_lock:
# add volume
self._stock_vol += self._add_flow / 3600
# sub volume
self._stock_vol -= self._sub_flow / 3600
# min val
self._stock_vol = max(0, self._stock_vol)
time.sleep(1.0)
class FlowValve:
def __init__(self, q_max, up_pres=0.0, up_flow=0.0, up_w_stock=0.0, down_pres=0.0, pos=0.0):
self.q_max = q_max
self.up_pres = up_pres
self.up_flow = up_flow
self.up_w_stock = up_w_stock
self.down_pres = down_pres
self.pos = pos
@property
def delta_p(self):
return self.up_pres - self.down_pres
def get_flow(self):
# VL max flow at current pos
max_flow = (self.pos / 100.0) * self.q_max
return min((self.up_w_stock * self.delta_p + self.up_flow) * self.pos / 100.0, max_flow)
def get_water_volume(d_mm, l_km):
d_m = d_mm / 1000.0
l_m = l_km * 1000.0
return math.pi * (d_m / 2) ** 2 * l_m
| 1,743 | 435 | 69 |
1726a03adf8587073f3c1e5389d9c4e0f67a2d4e | 309 | py | Python | pesto-cli/pesto/ws/features/converter/primitive_converter.py | CS-SI/pesto | 654a961d1064049578050d4c96e6f68f6a6dd770 | [
"Apache-2.0"
] | 25 | 2020-05-19T16:22:52.000Z | 2022-01-06T13:31:19.000Z | pesto-cli/pesto/ws/features/converter/primitive_converter.py | CS-SI/pesto | 654a961d1064049578050d4c96e6f68f6a6dd770 | [
"Apache-2.0"
] | 5 | 2020-10-12T09:30:20.000Z | 2021-12-13T12:49:06.000Z | pesto-cli/pesto/ws/features/converter/primitive_converter.py | CS-SI/pesto | 654a961d1064049578050d4c96e6f68f6a6dd770 | [
"Apache-2.0"
] | 5 | 2020-06-19T16:05:13.000Z | 2021-03-11T11:51:19.000Z | from typing import Any, Tuple
from pesto.ws.core.match_apply import MatchApply, Json
| 23.769231 | 54 | 0.68932 | from typing import Any, Tuple
from pesto.ws.core.match_apply import MatchApply, Json
class PrimitiveConverter(MatchApply):
def match(self, schema: Json):
return schema.get("type") is not None
def convert(self, data: Tuple[Any, Json]):
payload, schema = data
return payload
| 130 | 16 | 76 |
48fa43f09fe1d7615ba3f343f7811f7cce4dd04f | 826 | py | Python | jp.atcoder/abc132/abc132_d/8438043.py | kagemeka/atcoder-submissions | 91d8ad37411ea2ec582b10ba41b1e3cae01d4d6e | [
"MIT"
] | 1 | 2022-02-09T03:06:25.000Z | 2022-02-09T03:06:25.000Z | jp.atcoder/abc132/abc132_d/8438043.py | kagemeka/atcoder-submissions | 91d8ad37411ea2ec582b10ba41b1e3cae01d4d6e | [
"MIT"
] | 1 | 2022-02-05T22:53:18.000Z | 2022-02-09T01:29:30.000Z | jp.atcoder/abc132/abc132_d/8438043.py | kagemeka/atcoder-submissions | 91d8ad37411ea2ec582b10ba41b1e3cae01d4d6e | [
"MIT"
] | null | null | null | # 2019-11-15 00:35:39(JST)
import operator as op
import sys
# import collections
# import math
# from string import ascii_lowercase, ascii_uppercase, digits
# from bisect import bisect_left as bi_l, bisect_right as bi_r
# import itertools
from functools import reduce
# from scipy.misc import comb # float
# import numpy as np
mod = 10 ** 9 + 7
if __name__ == "__main__":
main()
| 24.294118 | 63 | 0.576271 | # 2019-11-15 00:35:39(JST)
import operator as op
import sys
# import collections
# import math
# from string import ascii_lowercase, ascii_uppercase, digits
# from bisect import bisect_left as bi_l, bisect_right as bi_r
# import itertools
from functools import reduce
# from scipy.misc import comb # float
# import numpy as np
def nCr(n, r):
r = min(r, n - r)
upper = reduce(op.mul, range(n, n-r, -1), 1)
lower = reduce(op.mul, range(r, 0, -1), 1)
return upper // lower
mod = 10 ** 9 + 7
def main():
n, k = [int(x) for x in sys.stdin.readline().split()]
for i in range(1, k+1):
if i <= n - k + 1:
print(nCr(n-k+1, i) * nCr(k-1, i-1) % mod)
else:
print(0) # i > n - k + 1 となる並べ方は存在しない
if __name__ == "__main__":
main()
| 396 | 0 | 49 |
104707e6e38cc8779cbfe5282a7d811bf41b5daa | 1,107 | py | Python | dstream_excel/dstream/workbook/functions.py | nickderobertis/datastream-excel-downloader-py | 3407decdf27da117758ce5ecc538d9f65c6ad5f6 | [
"MIT"
] | 1 | 2019-10-14T10:36:18.000Z | 2019-10-14T10:36:18.000Z | dstream_excel/dstream/workbook/functions.py | whoopnip/datastream-excel-downloader-py | 3407decdf27da117758ce5ecc538d9f65c6ad5f6 | [
"MIT"
] | 4 | 2020-03-24T17:45:15.000Z | 2021-06-02T00:20:24.000Z | dstream_excel/dstream/workbook/functions.py | whoopnip/datastream-excel-downloader-py | 3407decdf27da117758ce5ecc538d9f65c6ad5f6 | [
"MIT"
] | null | null | null | from typing import Sequence, Union
| 50.318182 | 111 | 0.71635 | from typing import Sequence, Union
class DatastreamExcelFunction:
def __init__(self, symbols: Union[Sequence[str], str]):
self.symbols = symbols
def time_series(self, variables: Sequence[str], begin='-2Y', end='', freq='D'):
return _datastream_excel_function(self.symbols, variables, begin=begin, end=end, freq=freq)
def static(self, variables: Sequence[str]):
return _datastream_excel_function(self.symbols, variables, begin='Latest Value', end='', freq='')
def _datastream_excel_function(symbols: Union[Sequence[str], str], variables: Sequence[str], begin, end, freq):
variables_str = ';'.join(variables)
if isinstance(symbols, (list, tuple)):
symbols = ','.join(symbols)
middle_str = '","'.join([symbols, variables_str, begin, end, freq])
custom_header_str = 'CustomHeader=true;CustHeaderDatatypes=DATATYPE'
headers_str = f'RowHeader=true;ColHeader=false'
other_str = 'DispSeriesDescription=false;YearlyTSFormat=false;QuarterlyTSFormat=false'
return f'=DSGRID("{middle_str}","{custom_header_str};{headers_str};{other_str}","")' | 937 | 9 | 126 |
d81256ff57e194d818c4e9bf8f9c6e8d5d916041 | 5,596 | py | Python | gperc/cli.py | yashbonde/general-perceivers | 3cc6d8fd7fd1da852cf8aef796c385eaa69f984f | [
"MIT"
] | 4 | 2021-11-02T08:18:06.000Z | 2021-12-25T13:45:06.000Z | gperc/cli.py | sanjibansg/general-perceivers | 9b881637e017ea1a4d7131042634c9a2fcd8211f | [
"MIT"
] | 1 | 2021-10-30T12:32:49.000Z | 2021-10-30T12:32:49.000Z | gperc/cli.py | sanjibansg/general-perceivers | 9b881637e017ea1a4d7131042634c9a2fcd8211f | [
"MIT"
] | 2 | 2021-10-18T04:25:40.000Z | 2021-11-21T11:33:38.000Z | r"""
CLI
===
**DO NOT USE (WIP)**
This module contains the command line interface for gperc. Is this really needed? I am not sure.
But having something along the lines of CLI means that running orchestration jobs would be possible.
Add code to your github actions by loading data from one place, dispatch this for training and then
testing it out all via CLI.
I am using ``python-fire`` from google for this, `link <https://github.com/google/python-fire>`_, that
can convert any arbitrary python object to a CLI. Normally I would use this with a ``main`` function,
but since there has to be configuration in the CLI, I am using a class ``Main`` (yes, I know, weird).
The default CLI has the following structure:
.. code-block::
python3 -m gperc [BEHEVIOUR] [CONFIGS] [TASKS]
BEHEVIOUR:
-h, --help: Show this modal and exit.
main: Run the main orchestration
serve (WIP): serve using YoCo
CONFIGS:
main: configurations for the main orchestration.
train: python3 -m gperc main train -h
data: python3 -m gperc main data -h
arch: python3 -m gperc main arch -h
serve (WIP): configurations for the server mode.
port: python3 -m gperc serve -h
TASKS:
Tasks are specific to behaviour and can raise errors for incorrect configs
main: tasks for the main orchestration.
profile: python3 -m gperc main [CONFIGS] profile -h
start: python3 -m gperc main [CONFIGS] start -h
deploy: deploy model on NimbleBox.ai. python3 -m gperc main [CONFIGS] deploy -h
This is how something like loading a dataset and running a model would look like:
.. code-block:: bash
python3 -m gperc main --modality "image/class" \
data --dataset_name "cifar10" \
arch --mno [1024,128,1] --ced [3,32,10] \
train --epochs 10 --batch_size 32 --lr 0.001 \
start
In the first line we have invoked the ``gperc`` module with modality (read below), in the next three
lines we have specified the data, the architecture and the training parameters. It ends with the
``start`` command, which starts the training.
"""
from typing import List
import torch
from torch.profiler import profile, record_function, ProfilerActivity
from .models import Perceiver
from .configs import PerceiverConfig
| 36.575163 | 181 | 0.649571 | r"""
CLI
===
**DO NOT USE (WIP)**
This module contains the command line interface for gperc. Is this really needed? I am not sure.
But having something along the lines of CLI means that running orchestration jobs would be possible.
Add code to your github actions by loading data from one place, dispatch this for training and then
testing it out all via CLI.
I am using ``python-fire`` from google for this, `link <https://github.com/google/python-fire>`_, that
can convert any arbitrary python object to a CLI. Normally I would use this with a ``main`` function,
but since there has to be configuration in the CLI, I am using a class ``Main`` (yes, I know, weird).
The default CLI has the following structure:
.. code-block::
python3 -m gperc [BEHEVIOUR] [CONFIGS] [TASKS]
BEHEVIOUR:
-h, --help: Show this modal and exit.
main: Run the main orchestration
serve (WIP): serve using YoCo
CONFIGS:
main: configurations for the main orchestration.
train: python3 -m gperc main train -h
data: python3 -m gperc main data -h
arch: python3 -m gperc main arch -h
serve (WIP): configurations for the server mode.
port: python3 -m gperc serve -h
TASKS:
Tasks are specific to behaviour and can raise errors for incorrect configs
main: tasks for the main orchestration.
profile: python3 -m gperc main [CONFIGS] profile -h
start: python3 -m gperc main [CONFIGS] start -h
deploy: deploy model on NimbleBox.ai. python3 -m gperc main [CONFIGS] deploy -h
This is how something like loading a dataset and running a model would look like:
.. code-block:: bash
python3 -m gperc main --modality "image/class" \
data --dataset_name "cifar10" \
arch --mno [1024,128,1] --ced [3,32,10] \
train --epochs 10 --batch_size 32 --lr 0.001 \
start
In the first line we have invoked the ``gperc`` module with modality (read below), in the next three
lines we have specified the data, the architecture and the training parameters. It ends with the
``start`` command, which starts the training.
"""
from typing import List
import torch
from torch.profiler import profile, record_function, ProfilerActivity
from .models import Perceiver
from .configs import PerceiverConfig
class Main:
def __init__(
self,
mno: List,
cde: List,
ffw_width: float = 1.0,
num_heads: int = 2,
num_layers: int = 2,
decoder_reduction: str = "mean",
decoder_residual: bool = False,
decoder_projection: bool = True,
dropout: float = 0.1,
n_classes: int = None,
output_pos_enc: bool = False,
):
r"""This is the main class for manging things from CLI. Errors are raised by the gperc.models and not here, so __setup() will
throw errors
Args:
mno (List): The first dimension of input, latent and output arrays
cde (List): The second dimension of input, latent and output arrays
ffw_width (float, optional): The width of the feed forward layer as ratio of dims
num_heads (int, optional): The number of attention heads
num_layers (int, optional): The number of (latent) layers
decoder_reduction (str, optional): After the decoder, how should the output be reduced, should be one of gperc.models.VALID_REDUCTIONS
decoder_residual (bool, optional): Whether output array performs residual connection with the latent array
decoder_projection (bool, optional): Is decoder output projected to a certain size
dropout (float, optional): The dropout rate
n_classes (int, optional): The number of classes in the output array, must be set if decoder_projection
output_pos_enc (bool, optional): Whether to use position encoding in the decoder
"""
config = PerceiverConfig(
input_len=mno[0],
input_dim=cde[0],
latent_len=mno[1],
latent_dim=cde[1],
output_len=mno[2],
output_dim=cde[2],
ffw_latent=int(mno[1] * ffw_width),
ffw_output=int(mno[2] * ffw_width),
num_heads=num_heads,
num_layers=num_layers,
decoder_reduction=decoder_reduction,
decoder_residual=decoder_residual,
decoder_projection=decoder_projection,
dropout=dropout,
n_classes=n_classes,
output_pos_enc=output_pos_enc,
pos_init_std=0.02,
)
self._model = Perceiver(config)
def profile(self, input_shape: List, sort_by: str = "cpu_time"):
r"""Profile the input based on the configurations given above.
Args:
input_shape (List): what should be the input shape of the tensor
sort_by (str): one of ``cpu_time, cuda_time, cpu_time_total, cuda_time_total, cpu_memory_usage, cuda_memory_usage, self_cpu_memory_usage, self_cuda_memory_usage, count``
"""
sample_input = torch.randn(*input_shape)
with profile(
activities=[ProfilerActivity.CPU],
record_shapes=True,
profile_memory=True,
with_stack=True,
) as prof:
with record_function("gperc_inference"):
self._model(sample_input)
print(prof.key_averages(group_by_input_shape=True).table(sort_by=sort_by))
prof.export_chrome_trace("trace.json")
class Serve:
pass
| 0 | 3,177 | 46 |
1573d07b69f4d4df39e2799dd0eac8a72e2063a9 | 7,725 | py | Python | andes_addon/minipmu.py | CURENT/andes_addon | 5b71b3558b8f147ba463a686b4ee2d1ea3ed22eb | [
"BSD-3-Clause"
] | null | null | null | andes_addon/minipmu.py | CURENT/andes_addon | 5b71b3558b8f147ba463a686b4ee2d1ea3ed22eb | [
"BSD-3-Clause"
] | null | null | null | andes_addon/minipmu.py | CURENT/andes_addon | 5b71b3558b8f147ba463a686b4ee2d1ea3ed22eb | [
"BSD-3-Clause"
] | null | null | null | """Python module to request PMU data from a running ANDES
"""
import logging
import time
from .dime import Dime
from numpy import array, ndarray, zeros
from pypmu import Pmu
from pypmu.frame import ConfigFrame2, HeaderFrame
if __name__ == "__main__":
mini = MiniPMU(
name='TestPMU',
dime_address='ipc:///tmp/dime',
pmu_idx=[1],
pmu_port=1414)
mini.run()
| 32.322176 | 85 | 0.529968 | """Python module to request PMU data from a running ANDES
"""
import logging
import time
from .dime import Dime
from numpy import array, ndarray, zeros
from pypmu import Pmu
from pypmu.frame import ConfigFrame2, HeaderFrame
def get_logger(name):
logger = logging.getLogger(name)
if not logger.handlers:
# Prevent logging from propagating to the root logger
logger.propagate = 0
console = logging.StreamHandler()
logger.addHandler(console)
formatter = logging.Formatter('%(asctime)s - %(name)s - %(log)s')
console.setFormatter(formatter)
return logger
class MiniPMU(object):
def __init__(
self,
name: str = '',
dime_address: str = 'ipc:///tmp/dime',
pmu_idx: list = list(),
max_store: int = 1000,
pmu_ip: str = '0.0.0.0',
pmu_port: int = 1410,
):
assert name, 'PMU Receiver name is empty'
assert pmu_idx, 'PMU idx is empty'
self.name = name
self.dime_address = dime_address
self.pmu_idx = pmu_idx
self.max_store = max_store
self.bus_name = []
self.var_idx = {
'am': [],
'vm': [],
'w': [],
}
self.Varheader = list()
self.Idxvgs = dict()
self.SysParam = dict()
self.Varvgs = ndarray([])
self.t = ndarray([])
self.data = ndarray([])
self.count = 0
self.dimec = Dime(self.name, self.dime_address)
self.pmu = Pmu(ip="0.0.0.0", port=pmu_port)
self.logger = get_logger(self.name)
def start_dime(self):
"""Starts the dime client stored in `self.dimec`
"""
self.logger.info('Trying to connect to dime server {}'.format(
self.dime_address))
assert self.dimec.start()
# clear data in the DiME server queue
self.dimec.exit()
assert self.dimec.start()
self.logger.info('DiME client connected')
def respond_to_sim(self):
"""Respond with data streaming configuration to the simulator"""
response = {
'vgsvaridx': self.vgsvaridx,
'limitsample': 0,
}
self.dimec.send_var('sim', self.name, response)
def get_bus_name(self):
"""
Return bus names based on ``self.pmu_idx``.
Store bus names to ``self.bus_name``
"""
# TODO: implement method to read bus names from Varheader
self.bus_name = list(self.pmu_idx)
for i in range(len(self.bus_name)):
self.bus_name[i] = 'Bus_' + str(self.bus_name[i])
return self.bus_name
def config_pmu(self):
"""Sets the ConfigFrame2 of the PMU
"""
self.cfg = ConfigFrame2(
self.pmu_idx[0], # PMU_ID
1000000, # TIME_BASE
1, # Number of PMUs included in data frame
self.bus_name[0], # Station name
self.pmu_idx[0], # Data-stream ID(s)
(True, True, True,
True), # Data format - POLAR; PH - REAL; AN - REAL; FREQ - REAL;
1, # Number of phasors
1, # Number of analog values
1, # Number of digital status words
[
"VA", "ANALOG1", "BREAKER 1 STATUS", "BREAKER 2 STATUS",
"BREAKER 3 STATUS", "BREAKER 4 STATUS", "BREAKER 5 STATUS",
"BREAKER 6 STATUS", "BREAKER 7 STATUS", "BREAKER 8 STATUS",
"BREAKER 9 STATUS", "BREAKER A STATUS", "BREAKER B STATUS",
"BREAKER C STATUS", "BREAKER D STATUS", "BREAKER E STATUS",
"BREAKER F STATUS", "BREAKER G STATUS"
], # Channel Names
[
(0, 'v')
],
# Conversion factor for phasor channels -
# (float representation, not important)
[(1, 'pow')], # Conversion factor for analog channels
[(0x0000, 0xffff)], # Mask words for digital status words
60, # Nominal frequency
1, # Configuration change count
30) # Rate of phasor data transmission)
self.hf = HeaderFrame(
self.pmu_idx[0], # PMU_ID
"Hello I'm a MiniPMU!") # Header Message
self.pmu.set_configuration(self.cfg)
self.pmu.set_header(self.hf)
self.pmu.run()
def find_var_idx(self):
"""Returns a dictionary of the indices into Varheader based on
`self.pmu_idx`. Items in `self.pmu_idx` uses 1-indexing.
For example, if `self.pmu_idx` == [1, 2], this function will return
the indices of
- Idxvgs.Pmu.vm[0] and Idxvgs.Pmu.vm[1] as vm
- Idxvgs.Pmu.am[0] and Idxvgs.Pmu.am[1] as am
- Idxvgs.Bus.w_Busfreq[0] and Idxvgs.Bus.w_Busfreq[1] as w
in the dictionary `self. var_idx` with the above fields.
"""
for item in self.pmu_idx:
self.var_idx['am'].append(self.Idxvgs['Pmu']['am'][0, item - 1])
self.var_idx['vm'].append(self.Idxvgs['Pmu']['vm'][0, item - 1])
self.var_idx['w'].append(
self.Idxvgs['Bus']['w_Busfreq'][0, item - 1])
@property
def vgsvaridx(self):
return array(self.var_idx['am'] + self.var_idx['vm'] +
self.var_idx['w'])
def init_storage(self):
"""Initialize data storage `self.t` and `self.data`
"""
if self.count % self.max_store == 0:
self.t = zeros(shape=(self.max_store, 1), dtype=float)
self.data = zeros(
shape=(self.max_store, len(self.pmu_idx * 3)), dtype=float)
self.count = 0
return True
else:
return False
def sync_measurement_data(self):
"""Store synced data into self.data and return in a tuple of (t, values)
"""
self.init_storage()
var = self.dimec.sync()
ws = self.dimec.workspace
if var == 'Varvgs':
self.data[self.count, :] = ws[var]['vars'][:]
self.t[self.count, :] = ws[var]['t']
self.count += 1
return ws[var]['t'], ws[var]['vars']
else:
return None, None
def sync_initialization(self):
"""Sync for ``SysParam``, ``Idxvgs`` and ``Varheader`` until all are received
"""
self.logger.info('Syncing for SysParam, Idxvgs and Varheader')
ret = False
count = 0
while True:
var = self.dimec.sync()
if var is False:
time.sleep(0.05)
continue
if var in ('SysParam', 'Idxvgs', 'Varheader'):
self.__dict__[var] = self.dimec.workspace[var]
count += 1
self.logger.info('{} synced.'.format(var))
if count == 3:
ret = True
break
return ret
def run(self):
"""Process control function
"""
self.start_dime()
if self.sync_initialization():
self.find_var_idx()
self.respond_to_sim()
self.get_bus_name()
self.config_pmu()
while True:
t, var = self.sync_measurement_data()
if not t:
continue
if self.pmu.clients:
self.pmu.send_data(
phasors=[(220 * int(var[0, 1]), int(var[0, 0]))],
analog=[9.99],
digital=[0x0001],
freq=60 * var[0, 2])
if __name__ == "__main__":
mini = MiniPMU(
name='TestPMU',
dime_address='ipc:///tmp/dime',
pmu_idx=[1],
pmu_port=1414)
mini.run()
| 1,423 | 5,855 | 46 |
0782dbc58a1f55d81bf13d773d0b85b00e6f8a04 | 39 | py | Python | Chapter 03/Chap03_Example3.23.py | Anancha/Programming-Techniques-using-Python | e80c329d2a27383909d358741a5cab03cb22fd8b | [
"MIT"
] | null | null | null | Chapter 03/Chap03_Example3.23.py | Anancha/Programming-Techniques-using-Python | e80c329d2a27383909d358741a5cab03cb22fd8b | [
"MIT"
] | null | null | null | Chapter 03/Chap03_Example3.23.py | Anancha/Programming-Techniques-using-Python | e80c329d2a27383909d358741a5cab03cb22fd8b | [
"MIT"
] | null | null | null | print("St-1")
print(2/0)
print("St-2")
| 9.75 | 13 | 0.589744 | print("St-1")
print(2/0)
print("St-2")
| 0 | 0 | 0 |
0d493834c464fab7f0a570e486b60c358231f079 | 2,563 | py | Python | data_loader/datasets.py | mhd53/ssd-from-torch | 1ae6eaab87afd6ef243b2fe444cbb5b15a12cfc7 | [
"MIT"
] | null | null | null | data_loader/datasets.py | mhd53/ssd-from-torch | 1ae6eaab87afd6ef243b2fe444cbb5b15a12cfc7 | [
"MIT"
] | null | null | null | data_loader/datasets.py | mhd53/ssd-from-torch | 1ae6eaab87afd6ef243b2fe444cbb5b15a12cfc7 | [
"MIT"
] | null | null | null | import torch
from torch.utils.data import Dataset
import json
import os
from PIL import Image
from utils.trms_util import transform
class PascalVOCDataset(Dataset):
"""
A Dataset class to be used in a DataLoader to create batches.
"""
def __init__(self, data_folder, split="TEST", keep_difficult=False):
"""
Args:
data_folder: folder where data files are stored.
split: split, one of 'TRAIN' or 'TEST'.
keep_difficult: keep or discard objects that are condidered difficult to detect.
"""
self.split = split.upper()
assert self.split in {"TRAIN", "TEST"}
self.data_folder = data_folder
self.keep_difficult = keep_difficult
with open(os.path.join(data_folder, self.split + "_images.json"), "r") as j:
self.images = json.load(j)
with open(os.path.join(data_folder, self.split + "_objects.json"), "r") as j:
self.objects = json.load(j)
assert len(self.images) == len(self.objects)
def collate_fn(self, batch):
"""
Describes how to combine images with different number of objects by using lists.
Since each image may have a different number of objects, we need a collate function
(to bew passed to the DataLoader).
Args:
batch: an iterable of N sets from __getitem__()
Returns:
a tensor of images, lists of varying-size tensors of bounding boxes, labels, and difficulties.
"""
images = list()
boxes = list()
labels = list()
difficulties = list()
for b in batch:
images.append(b[0])
boxes.append(b[1])
labels.append(b[2])
difficulties.append(b[3])
images = torch.stack(images, dim=0)
return images, boxes, labels, difficulties | 29.802326 | 104 | 0.610613 | import torch
from torch.utils.data import Dataset
import json
import os
from PIL import Image
from utils.trms_util import transform
class PascalVOCDataset(Dataset):
"""
A Dataset class to be used in a DataLoader to create batches.
"""
def __init__(self, data_folder, split="TEST", keep_difficult=False):
"""
Args:
data_folder: folder where data files are stored.
split: split, one of 'TRAIN' or 'TEST'.
keep_difficult: keep or discard objects that are condidered difficult to detect.
"""
self.split = split.upper()
assert self.split in {"TRAIN", "TEST"}
self.data_folder = data_folder
self.keep_difficult = keep_difficult
with open(os.path.join(data_folder, self.split + "_images.json"), "r") as j:
self.images = json.load(j)
with open(os.path.join(data_folder, self.split + "_objects.json"), "r") as j:
self.objects = json.load(j)
assert len(self.images) == len(self.objects)
def __getitem__(self, i):
image = Image.open(self.images[i], mode="r")
image = image.convert("RGB")
objects = self.objects[i]
boxes = torch.FloatTensor(objects["boxes"])
labels = torch.LongTensor(objects["labels"])
difficulties = torch.ByteTensor(objects["difficulties"])
if not self.keep_difficult:
boxes = boxes[1 - difficulties]
labels = labels[1 - difficulties]
image, boxes, labels, difficulties = transform(
image, boxes, labels, difficulties, split=self.split
)
return image, boxes, labels, difficulties
def __len__(self):
return len(self.images)
def collate_fn(self, batch):
"""
Describes how to combine images with different number of objects by using lists.
Since each image may have a different number of objects, we need a collate function
(to bew passed to the DataLoader).
Args:
batch: an iterable of N sets from __getitem__()
Returns:
a tensor of images, lists of varying-size tensors of bounding boxes, labels, and difficulties.
"""
images = list()
boxes = list()
labels = list()
difficulties = list()
for b in batch:
images.append(b[0])
boxes.append(b[1])
labels.append(b[2])
difficulties.append(b[3])
images = torch.stack(images, dim=0)
return images, boxes, labels, difficulties | 638 | 0 | 54 |
43476669c0e07b4881c73f91b2a4e194e94da549 | 921 | py | Python | setup.py | Neuroglycerin/neukrill-net-tools | 133c68403128e6fcea6d6c8c8326b45443ef7f4e | [
"MIT"
] | null | null | null | setup.py | Neuroglycerin/neukrill-net-tools | 133c68403128e6fcea6d6c8c8326b45443ef7f4e | [
"MIT"
] | null | null | null | setup.py | Neuroglycerin/neukrill-net-tools | 133c68403128e6fcea6d6c8c8326b45443ef7f4e | [
"MIT"
] | null | null | null | #!/usr/bin/env python
from distutils.core import setup
from setuptools.command.test import test as TestCommand
setup(name='neukrill-net',
version='1.0',
description='Neukrill-net NDSB tools',
author='neuroglycerin',
author_email='root@finlaymagui.re',
packages=['neukrill_net'],
tests_require=['pytest'],
install_requires=['scipy==0.14.0',
'numpy==1.9.1',
'six==1.8.0',
'pytest==2.6.4',
'Pillow==2.7.0',
'scikit-image==0.10.1',
'scikit-learn==0.15.2'],
cmdclass={'test': PyTest},
)
| 29.709677 | 55 | 0.543974 | #!/usr/bin/env python
from distutils.core import setup
from setuptools.command.test import test as TestCommand
class PyTest(TestCommand):
def finalize_options(self):
TestCommand.finalize_options(self)
self.test_args = []
self.test_suite = True
def run_tests(self):
import pytest
pytest.main(self.test_args)
setup(name='neukrill-net',
version='1.0',
description='Neukrill-net NDSB tools',
author='neuroglycerin',
author_email='root@finlaymagui.re',
packages=['neukrill_net'],
tests_require=['pytest'],
install_requires=['scipy==0.14.0',
'numpy==1.9.1',
'six==1.8.0',
'pytest==2.6.4',
'Pillow==2.7.0',
'scikit-image==0.10.1',
'scikit-learn==0.15.2'],
cmdclass={'test': PyTest},
)
| 165 | 5 | 75 |
82773881e1cd78cba0c3ed8588b4d786447d5b82 | 459 | py | Python | tensornetwork/contractors/custom_path_solvers/__init__.py | khanhgithead/TensorNetwork | e12580f1749493dbe05f474d2fecdec4eaba73c5 | [
"Apache-2.0"
] | 1,681 | 2019-04-30T21:07:24.000Z | 2022-03-31T14:51:19.000Z | tensornetwork/contractors/custom_path_solvers/__init__.py | khanhgithead/TensorNetwork | e12580f1749493dbe05f474d2fecdec4eaba73c5 | [
"Apache-2.0"
] | 671 | 2019-05-04T22:01:20.000Z | 2022-03-31T16:02:55.000Z | tensornetwork/contractors/custom_path_solvers/__init__.py | khanhgithead/TensorNetwork | e12580f1749493dbe05f474d2fecdec4eaba73c5 | [
"Apache-2.0"
] | 394 | 2019-04-29T03:24:26.000Z | 2022-03-11T14:16:21.000Z | from tensornetwork.contractors.custom_path_solvers import pathsolvers
from tensornetwork.contractors.custom_path_solvers import nconinterface
#pylint: disable=line-too-long
from tensornetwork.contractors.custom_path_solvers.pathsolvers import greedy_cost_solve, greedy_size_solve, full_solve_complete
#pylint: disable=line-too-long
from tensornetwork.contractors.custom_path_solvers.nconinterface import ncon_solver, ncon_to_adj, ord_to_ncon, ncon_cost_check
| 65.571429 | 127 | 0.891068 | from tensornetwork.contractors.custom_path_solvers import pathsolvers
from tensornetwork.contractors.custom_path_solvers import nconinterface
#pylint: disable=line-too-long
from tensornetwork.contractors.custom_path_solvers.pathsolvers import greedy_cost_solve, greedy_size_solve, full_solve_complete
#pylint: disable=line-too-long
from tensornetwork.contractors.custom_path_solvers.nconinterface import ncon_solver, ncon_to_adj, ord_to_ncon, ncon_cost_check
| 0 | 0 | 0 |
33fa392b08f1093fd3a75a7d5b57799fd25b8e44 | 412 | py | Python | filter_plugins/apiserver_proxy.py | ochinchina/KubeClus | 2a90e33cd0334c0ff3136c955ed44333ecb5cc98 | [
"MIT"
] | null | null | null | filter_plugins/apiserver_proxy.py | ochinchina/KubeClus | 2a90e33cd0334c0ff3136c955ed44333ecb5cc98 | [
"MIT"
] | null | null | null | filter_plugins/apiserver_proxy.py | ochinchina/KubeClus | 2a90e33cd0334c0ff3136c955ed44333ecb5cc98 | [
"MIT"
] | null | null | null | #!/usr/bin/python2
import os
import yaml
| 29.428571 | 84 | 0.68932 | #!/usr/bin/python2
import os
import yaml
class FilterModule:
def filters(self):
return { "change_apiserver_proxy": self.change_apiserver_proxy}
def change_apiserver_proxy( self, kubelet_conf, new_apiserver):
conf = yaml.load( kubelet_conf )
conf['clusters'][0]['cluster']['server'] = "https://%s:6443" % new_apiserver
return yaml.dump( conf, default_flow_style=False )
| 296 | -2 | 76 |
5bbaaad6e83dfa532f4a5797627fc5ede61dd075 | 40 | py | Python | core/apps/core/models/__init__.py | jlebunetel/agile | 63b6d6be55eb0ba33b6815e62478ff216576b3b7 | [
"MIT"
] | null | null | null | core/apps/core/models/__init__.py | jlebunetel/agile | 63b6d6be55eb0ba33b6815e62478ff216576b3b7 | [
"MIT"
] | 1 | 2021-05-07T16:27:07.000Z | 2021-05-07T16:27:07.000Z | core/apps/core/models/__init__.py | jlebunetel/agile | 63b6d6be55eb0ba33b6815e62478ff216576b3b7 | [
"MIT"
] | null | null | null | from .base import *
from .site import *
| 13.333333 | 19 | 0.7 | from .base import *
from .site import *
| 0 | 0 | 0 |
3dc7b4c968696b2f37879db6704389aaa60185c0 | 2,775 | py | Python | np_autoencoder.py | nirajjayantbolt/cs224u | b0321d4db5f2f6310081565d9ff74976aeb94b91 | [
"Apache-2.0"
] | 1 | 2022-02-07T21:41:10.000Z | 2022-02-07T21:41:10.000Z | np_autoencoder.py | nirajjayantbolt/cs224u | b0321d4db5f2f6310081565d9ff74976aeb94b91 | [
"Apache-2.0"
] | 1 | 2020-02-23T05:11:20.000Z | 2020-02-23T05:11:20.000Z | np_autoencoder.py | nirajjayantbolt/cs224u | b0321d4db5f2f6310081565d9ff74976aeb94b91 | [
"Apache-2.0"
] | 1 | 2020-05-04T01:50:08.000Z | 2020-05-04T01:50:08.000Z | import numpy as np
from np_model_base import NNModelBase
import pandas as pd
__author__ = "Christopher Potts"
__version__ = "CS224u, Stanford, Spring 2020"
if __name__ == '__main__':
simple_example()
| 28.030303 | 74 | 0.625946 | import numpy as np
from np_model_base import NNModelBase
import pandas as pd
__author__ = "Christopher Potts"
__version__ = "CS224u, Stanford, Spring 2020"
class Autoencoder(NNModelBase):
def __init__(self, **kwargs):
super(Autoencoder, self).__init__(**kwargs)
def prepare_output_data(self, y):
return y
def fit(self, X):
self.input_dim = X.shape[1]
self.output_dim = self.input_dim
X_array = self.convert_input_to_array(X)
super().fit(X_array, X_array)
H = self.hidden_activation(X.dot(self.W_xh))
H = self.convert_output(H, X)
return H
@staticmethod
def get_error(predictions, labels):
return (0.5 * (predictions - labels)**2).sum()
def initialize_parameters(self):
self.W_xh = self.weight_init(self.input_dim, self.hidden_dim)
self.b_xh = self.bias_init(self.hidden_dim)
self.W_hy = self.weight_init(self.hidden_dim, self.output_dim)
self.b_hy = self.bias_init(self.output_dim)
def update_parameters(self, gradients):
d_W_hy, d_b_hy, d_W_xh, d_b_xh = gradients
self.W_hy -= self.eta * d_W_hy
self.b_hy -= self.eta * d_b_hy
self.W_xh -= self.eta * d_W_xh
self.b_xh -= self.eta * d_b_xh
def forward_propagation(self, x):
h = self.hidden_activation(x.dot(self.W_xh) + self.b_xh)
y = h.dot(self.W_hy) + self.b_hy
return h, y
def backward_propagation(self, h, predictions, x, labels):
y_err = predictions - labels
d_b_hy = y_err
h_err = y_err.dot(self.W_hy.T) * self.d_hidden_activation(h)
d_W_hy = np.outer(h, y_err)
d_W_xh = np.outer(x, h_err)
d_b_xh = h_err
return d_W_hy, d_b_hy, d_W_xh, d_b_xh
def predict(self, X):
h, y = self.forward_propagation(X)
return y
@staticmethod
def convert_input_to_array(X):
if isinstance(X, pd.DataFrame):
X = X.values
return X
@staticmethod
def convert_output(X_pred, X):
if isinstance(X, pd.DataFrame):
X_pred = pd.DataFrame(X_pred, index=X.index)
return X_pred
def simple_example():
import numpy as np
np.random.seed(seed=42)
def randmatrix(m, n, sigma=0.1, mu=0):
return sigma * np.random.randn(m, n) + mu
rank = 20
nrow = 1000
ncol = 100
X = randmatrix(nrow, rank).dot(randmatrix(rank, ncol))
ae = Autoencoder(hidden_dim=rank, max_iter=200)
H = ae.fit(X)
X_pred = ae.predict(X)
mse = (0.5 * (X_pred - X)**2).mean()
print("\nMSE between actual and reconstructed: {0:0.09f}".format(mse))
print("Hidden representations")
print(H)
return mse
if __name__ == '__main__':
simple_example()
| 2,161 | 360 | 46 |
882146e24e886e028f11c2822c6ccc4856613a95 | 1,087 | py | Python | admin/migrations/0002_auto_20180227_1101.py | rodlukas/UP-admin | 08f36de0773f39c6222da82016bf1384af2cce18 | [
"MIT"
] | 4 | 2019-07-19T17:39:04.000Z | 2022-03-22T21:02:15.000Z | admin/migrations/0002_auto_20180227_1101.py | rodlukas/UP-admin | 08f36de0773f39c6222da82016bf1384af2cce18 | [
"MIT"
] | 53 | 2019-08-04T14:25:40.000Z | 2022-03-26T20:30:55.000Z | admin/migrations/0002_auto_20180227_1101.py | rodlukas/UP-admin | 08f36de0773f39c6222da82016bf1384af2cce18 | [
"MIT"
] | 3 | 2020-03-09T07:11:03.000Z | 2020-09-11T01:22:50.000Z | # Generated by Django 2.0.2 on 2018-02-27 10:01
from django.db import migrations, models
| 41.807692 | 98 | 0.680773 | # Generated by Django 2.0.2 on 2018-02-27 10:01
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [("admin", "0001_initial")]
operations = [
migrations.RenameField(
model_name="attendance", old_name="attendancestateid", new_name="attendancestate"
),
migrations.RenameField(model_name="attendance", old_name="clientid", new_name="client"),
migrations.RenameField(model_name="attendance", old_name="lectureid", new_name="lecture"),
migrations.RenameField(model_name="lecture", old_name="courseid", new_name="course"),
migrations.RenameField(model_name="lecture", old_name="groupid", new_name="group"),
migrations.RenameField(model_name="memberof", old_name="clientid", new_name="client"),
migrations.RenameField(model_name="memberof", old_name="groupid", new_name="group"),
migrations.AlterField(
model_name="lecture",
name="duration",
field=models.PositiveIntegerField(blank=True, null=True),
),
]
| 0 | 973 | 23 |
912d668287be2cf55d3d6ac5fce530b7e78ab4c0 | 9,910 | py | Python | test.py | Sanjana7395/face_segmentation | cc06c6adf639c9ce1a3c64608ff9190dbf25a5ce | [
"MIT"
] | 22 | 2020-08-23T21:27:31.000Z | 2022-03-03T09:11:34.000Z | test.py | Sanjana7395/face_segmentation | cc06c6adf639c9ce1a3c64608ff9190dbf25a5ce | [
"MIT"
] | 7 | 2020-07-17T08:35:41.000Z | 2021-09-07T11:35:23.000Z | test.py | Sanjana7395/face_segmentation | cc06c6adf639c9ce1a3c64608ff9190dbf25a5ce | [
"MIT"
] | 10 | 2020-07-17T08:56:51.000Z | 2022-03-29T08:53:48.000Z | import os
import numpy as np
import cv2
import argparse
from sklearn.metrics import confusion_matrix
import matplotlib.pyplot as plt
import seaborn as sns
from tensorflow.keras import Input
from model import u_net
from preprocessing.preprocess_utils import display
from experiments import lip_hair_color
def make_confusion_matrix(cf, categories,
group_names=None,
count=True,
percent=True,
color_bar=True,
xy_ticks=True,
xy_plot_labels=True,
sum_stats=True,
fig_size=None,
c_map='Blues',
title=None):
""" Code to generate text within each box and beautify confusion matrix.
:param cf: Confusion matrix.
:type cf: numpy array
:param categories: array of classes.
:type categories: numpy array
:param group_names: classes in the project.
:type group_names: numpy array
:param count: whether to display the count of each class.
:type count: boolean
:param percent: whether to display percentage for each class.
:type percent: boolean
:param color_bar: whether to display color bar for the heat map.
:type color_bar: boolean
:param xy_ticks: whether to display xy labels.
:type xy_ticks: boolean
:param xy_plot_labels: whether to display xy title.
:type xy_plot_labels: boolean
:param sum_stats: whether to display overall accuracy.
:type sum_stats: boolean
:param fig_size: size of the plot.
:type fig_size: tuple
:param c_map: color scheme to use.
:type c_map: str
:param title: Title of the plot.
:type title: str
"""
blanks = ['' for i in range(cf.size)]
if group_names and len(group_names) == cf.size:
group_labels = ["{}\n".format(value) for value in group_names]
else:
group_labels = blanks
if count:
group_counts = ["{0:0.0f}\n".format(value) for value in cf.flatten()]
else:
group_counts = blanks
if percent:
row_size = np.size(cf, 0)
col_size = np.size(cf, 1)
group_percentages = []
for i in range(row_size):
for j in range(col_size):
group_percentages.append(cf[i][j] / cf[i].sum())
group_percentages = ["{0:.2%}".format(value)
for value in group_percentages]
else:
group_percentages = blanks
box_labels = [f"{v1}{v2}{v3}".strip()
for v1, v2, v3 in zip(group_labels,
group_counts,
group_percentages)]
box_labels = np.asarray(box_labels).reshape(cf.shape[0], cf.shape[1])
# CODE TO GENERATE SUMMARY STATISTICS & TEXT FOR SUMMARY STATS
if sum_stats:
# Accuracy is sum of diagonal divided by total observations
accuracy = np.trace(cf) / float(np.sum(cf))
stats_text = "\n\nAccuracy={0:0.2%}".format(accuracy)
else:
stats_text = ""
# SET FIGURE PARAMETERS ACCORDING TO OTHER ARGUMENTS
if fig_size is None:
# Get default figure size if not set
fig_size = plt.rcParams.get('figure.figsize')
if not xy_ticks:
# Do not show categories if xyticks is False
categories = False
# MAKE THE HEAT MAP VISUALIZATION
plt.figure(figsize=fig_size)
sns.heatmap(cf, annot=box_labels, fmt="",
cmap=c_map, cbar=color_bar,
xticklabels=categories,
yticklabels=categories)
if xy_plot_labels:
plt.ylabel('True label')
plt.xlabel('Predicted label' + stats_text)
else:
plt.xlabel(stats_text)
if title:
plt.title(title)
def plot_confusion_matrix(predictions, masks, path):
""" Visualize confusion matrix.
:param predictions: predicted output of the model.
:type predictions: array
:param masks: true masks of the images.
:type masks: array
:param path: directory to store the output
:type path: str
"""
print('[INFO] Plotting confusion matrix...')
corr = confusion_matrix(masks.ravel(), predictions.ravel())
make_confusion_matrix(corr,
categories=['bg', 'skin', 'nose', 'eye_g', 'l_eye',
'r_eye', 'l_brow', 'r_brow', 'l_ear',
'r_ear', 'mouth', 'u_lip',
'l_lip', 'hair', 'hat', 'ear_r',
'neck_l', 'neck', 'cloth'],
count=True,
percent=False,
color_bar=False,
xy_ticks=True,
xy_plot_labels=True,
sum_stats=True,
fig_size=(20, 18),
c_map='coolwarm',
title='Confusion matrix')
# error correction - cropped heat map
b, t = plt.ylim() # discover the values for bottom and top
b += 0.5 # Add 0.5 to the bottom
t -= 0.5 # Subtract 0.5 from the top
plt.ylim(b, t) # update the ylim(bottom, top) values
plt.savefig(os.path.join(path, 'confusion_matrix.png'))
print('[ACTION] See results/visualization/confusion_matrix.png')
def plot_mask(prediction, mask, norm_image):
""" PLot segmentation mask for the given image.
:param prediction: predicted output of the model.
:type prediction: array
:param mask: true masks of the images.
:type mask: array
:param norm_image: original image.
:type norm_image: array
"""
image = (norm_image * 255.).astype(np.uint8)
im_base = np.zeros((256, 256, 3), dtype=np.uint8)
for idx, color in enumerate(color_list):
im_base[prediction == idx] = color
cv2.addWeighted(im_base, 0.8, image, 1, 0, im_base)
display([image, mask, im_base],
['Original image', 'True mask', 'Predicted mask'],
'predict')
def test(image, masks, action, color='red'):
""" Used to plot either confusion matrix or predicted mask or apply makeup.
:param image: original image.
:type image: bytearray
:param masks: true segmentation masks.
:type masks: array
:param action: user input specifying confusion matrix/mask
prediction/applying makeup.
:type action: str
:param color: if action is applying makeup, then color to apply.
Defaults to red.
:type color: str
"""
input_img = Input(shape=(256, 256, 3), name='img')
model = u_net.get_u_net(input_img, num_classes=19)
model.load_weights(os.path.join(MODEL_DIR, 'u_net.h5'))
print('[INFO] Predicting ...')
predictions = model.predict(image)
predictions = np.argmax(predictions, axis=-1)
table = {
'hair': 13,
'upper_lip': 11,
'lower_lip': 12
}
colors = {
'red': [212, 34, 34],
'purple': [128, 51, 125],
'pink': [247, 32, 125]
}
# Redirect to the function of specified action.
if action == 'confusion_matrix':
print('[INFO] Plotting confusion matrix ...')
plot_confusion_matrix(predictions, masks, VISUALIZATION_DIR)
elif action == 'mask':
print('[INFO] Plotting segmentation mask ...')
plot_mask(predictions[sample], masks[sample], image[sample])
elif action == 'hair_color':
print('[INFO] Applying hair color ...')
parts = [table['hair']]
changed = lip_hair_color.color_change(image[sample],
predictions[sample],
parts, colors[color])
display([image[sample], changed], 'hair')
elif action == "lip_color":
print('[INFO] Applying lip color ...')
parts = [table['upper_lip'], table['lower_lip']]
changed = lip_hair_color.color_change(image[sample],
predictions[sample],
parts, colors[color])
display([image[sample], changed], 'lip')
def main():
""" Define user arguments.
"""
ap = argparse.ArgumentParser()
ap.add_argument("-v", "--visualize", type=str, required=True,
choices=("confusion_matrix", "mask",
"hair_color", "lip_color"),
help="type of model")
ap.add_argument("-c", "--color", type=str,
choices=("red", "pink", "purple"),
help="color to apply")
args = vars(ap.parse_args())
# print('[INFO] Getting test data...')
# test_data = get_test()
# imgs = []
# masks = []
# for img, label in test_data:
# for i in img:
# i = np.array(i, dtype='float32')
# imgs.append(i)
# for j in label:
# j = np.array(j, dtype='float32')
# masks.append(j)
# images = np.array(imgs)
# masks = np.array(masks)
# np.save('data/test_images.npy', images)
# np.save('data/test_mask.npy', masks)
# Load test images
images = np.load('data/test_images.npy')
masks = np.load('data/test_mask.npy')
test(images, masks, args["visualize"], args["color"])
if __name__ == '__main__':
VISUALIZATION_DIR = 'results/visualization/'
MODEL_DIR = 'results/models/'
color_list = [[0, 0, 0], [204, 0, 0], [255, 140, 26],
[204, 204, 0], [51, 51, 255], [204, 0, 204],
[0, 255, 255], [255, 204, 204], [102, 51, 0],
[255, 0, 0], [102, 204, 0], [255, 255, 0],
[0, 0, 153], [0, 0, 204], [255, 51, 153],
[0, 204, 204], [0, 51, 0], [255, 153, 51],
[0, 204, 0]]
sample = 4
main()
| 34.65035 | 79 | 0.560343 | import os
import numpy as np
import cv2
import argparse
from sklearn.metrics import confusion_matrix
import matplotlib.pyplot as plt
import seaborn as sns
from tensorflow.keras import Input
from model import u_net
from preprocessing.preprocess_utils import display
from experiments import lip_hair_color
def make_confusion_matrix(cf, categories,
group_names=None,
count=True,
percent=True,
color_bar=True,
xy_ticks=True,
xy_plot_labels=True,
sum_stats=True,
fig_size=None,
c_map='Blues',
title=None):
""" Code to generate text within each box and beautify confusion matrix.
:param cf: Confusion matrix.
:type cf: numpy array
:param categories: array of classes.
:type categories: numpy array
:param group_names: classes in the project.
:type group_names: numpy array
:param count: whether to display the count of each class.
:type count: boolean
:param percent: whether to display percentage for each class.
:type percent: boolean
:param color_bar: whether to display color bar for the heat map.
:type color_bar: boolean
:param xy_ticks: whether to display xy labels.
:type xy_ticks: boolean
:param xy_plot_labels: whether to display xy title.
:type xy_plot_labels: boolean
:param sum_stats: whether to display overall accuracy.
:type sum_stats: boolean
:param fig_size: size of the plot.
:type fig_size: tuple
:param c_map: color scheme to use.
:type c_map: str
:param title: Title of the plot.
:type title: str
"""
blanks = ['' for i in range(cf.size)]
if group_names and len(group_names) == cf.size:
group_labels = ["{}\n".format(value) for value in group_names]
else:
group_labels = blanks
if count:
group_counts = ["{0:0.0f}\n".format(value) for value in cf.flatten()]
else:
group_counts = blanks
if percent:
row_size = np.size(cf, 0)
col_size = np.size(cf, 1)
group_percentages = []
for i in range(row_size):
for j in range(col_size):
group_percentages.append(cf[i][j] / cf[i].sum())
group_percentages = ["{0:.2%}".format(value)
for value in group_percentages]
else:
group_percentages = blanks
box_labels = [f"{v1}{v2}{v3}".strip()
for v1, v2, v3 in zip(group_labels,
group_counts,
group_percentages)]
box_labels = np.asarray(box_labels).reshape(cf.shape[0], cf.shape[1])
# CODE TO GENERATE SUMMARY STATISTICS & TEXT FOR SUMMARY STATS
if sum_stats:
# Accuracy is sum of diagonal divided by total observations
accuracy = np.trace(cf) / float(np.sum(cf))
stats_text = "\n\nAccuracy={0:0.2%}".format(accuracy)
else:
stats_text = ""
# SET FIGURE PARAMETERS ACCORDING TO OTHER ARGUMENTS
if fig_size is None:
# Get default figure size if not set
fig_size = plt.rcParams.get('figure.figsize')
if not xy_ticks:
# Do not show categories if xyticks is False
categories = False
# MAKE THE HEAT MAP VISUALIZATION
plt.figure(figsize=fig_size)
sns.heatmap(cf, annot=box_labels, fmt="",
cmap=c_map, cbar=color_bar,
xticklabels=categories,
yticklabels=categories)
if xy_plot_labels:
plt.ylabel('True label')
plt.xlabel('Predicted label' + stats_text)
else:
plt.xlabel(stats_text)
if title:
plt.title(title)
def plot_confusion_matrix(predictions, masks, path):
""" Visualize confusion matrix.
:param predictions: predicted output of the model.
:type predictions: array
:param masks: true masks of the images.
:type masks: array
:param path: directory to store the output
:type path: str
"""
print('[INFO] Plotting confusion matrix...')
corr = confusion_matrix(masks.ravel(), predictions.ravel())
make_confusion_matrix(corr,
categories=['bg', 'skin', 'nose', 'eye_g', 'l_eye',
'r_eye', 'l_brow', 'r_brow', 'l_ear',
'r_ear', 'mouth', 'u_lip',
'l_lip', 'hair', 'hat', 'ear_r',
'neck_l', 'neck', 'cloth'],
count=True,
percent=False,
color_bar=False,
xy_ticks=True,
xy_plot_labels=True,
sum_stats=True,
fig_size=(20, 18),
c_map='coolwarm',
title='Confusion matrix')
# error correction - cropped heat map
b, t = plt.ylim() # discover the values for bottom and top
b += 0.5 # Add 0.5 to the bottom
t -= 0.5 # Subtract 0.5 from the top
plt.ylim(b, t) # update the ylim(bottom, top) values
plt.savefig(os.path.join(path, 'confusion_matrix.png'))
print('[ACTION] See results/visualization/confusion_matrix.png')
def plot_mask(prediction, mask, norm_image):
""" PLot segmentation mask for the given image.
:param prediction: predicted output of the model.
:type prediction: array
:param mask: true masks of the images.
:type mask: array
:param norm_image: original image.
:type norm_image: array
"""
image = (norm_image * 255.).astype(np.uint8)
im_base = np.zeros((256, 256, 3), dtype=np.uint8)
for idx, color in enumerate(color_list):
im_base[prediction == idx] = color
cv2.addWeighted(im_base, 0.8, image, 1, 0, im_base)
display([image, mask, im_base],
['Original image', 'True mask', 'Predicted mask'],
'predict')
def test(image, masks, action, color='red'):
""" Used to plot either confusion matrix or predicted mask or apply makeup.
:param image: original image.
:type image: bytearray
:param masks: true segmentation masks.
:type masks: array
:param action: user input specifying confusion matrix/mask
prediction/applying makeup.
:type action: str
:param color: if action is applying makeup, then color to apply.
Defaults to red.
:type color: str
"""
input_img = Input(shape=(256, 256, 3), name='img')
model = u_net.get_u_net(input_img, num_classes=19)
model.load_weights(os.path.join(MODEL_DIR, 'u_net.h5'))
print('[INFO] Predicting ...')
predictions = model.predict(image)
predictions = np.argmax(predictions, axis=-1)
table = {
'hair': 13,
'upper_lip': 11,
'lower_lip': 12
}
colors = {
'red': [212, 34, 34],
'purple': [128, 51, 125],
'pink': [247, 32, 125]
}
# Redirect to the function of specified action.
if action == 'confusion_matrix':
print('[INFO] Plotting confusion matrix ...')
plot_confusion_matrix(predictions, masks, VISUALIZATION_DIR)
elif action == 'mask':
print('[INFO] Plotting segmentation mask ...')
plot_mask(predictions[sample], masks[sample], image[sample])
elif action == 'hair_color':
print('[INFO] Applying hair color ...')
parts = [table['hair']]
changed = lip_hair_color.color_change(image[sample],
predictions[sample],
parts, colors[color])
display([image[sample], changed], 'hair')
elif action == "lip_color":
print('[INFO] Applying lip color ...')
parts = [table['upper_lip'], table['lower_lip']]
changed = lip_hair_color.color_change(image[sample],
predictions[sample],
parts, colors[color])
display([image[sample], changed], 'lip')
def main():
""" Define user arguments.
"""
ap = argparse.ArgumentParser()
ap.add_argument("-v", "--visualize", type=str, required=True,
choices=("confusion_matrix", "mask",
"hair_color", "lip_color"),
help="type of model")
ap.add_argument("-c", "--color", type=str,
choices=("red", "pink", "purple"),
help="color to apply")
args = vars(ap.parse_args())
# print('[INFO] Getting test data...')
# test_data = get_test()
# imgs = []
# masks = []
# for img, label in test_data:
# for i in img:
# i = np.array(i, dtype='float32')
# imgs.append(i)
# for j in label:
# j = np.array(j, dtype='float32')
# masks.append(j)
# images = np.array(imgs)
# masks = np.array(masks)
# np.save('data/test_images.npy', images)
# np.save('data/test_mask.npy', masks)
# Load test images
images = np.load('data/test_images.npy')
masks = np.load('data/test_mask.npy')
test(images, masks, args["visualize"], args["color"])
if __name__ == '__main__':
VISUALIZATION_DIR = 'results/visualization/'
MODEL_DIR = 'results/models/'
color_list = [[0, 0, 0], [204, 0, 0], [255, 140, 26],
[204, 204, 0], [51, 51, 255], [204, 0, 204],
[0, 255, 255], [255, 204, 204], [102, 51, 0],
[255, 0, 0], [102, 204, 0], [255, 255, 0],
[0, 0, 153], [0, 0, 204], [255, 51, 153],
[0, 204, 204], [0, 51, 0], [255, 153, 51],
[0, 204, 0]]
sample = 4
main()
| 0 | 0 | 0 |
45c7e65d5a58484022e55ea62f4b70c3fa489a01 | 475 | py | Python | girder_rnascope/tilesource/tiff.py | abcsFrederick/RNAScope | 9cb049f9c64f52e49afddfb32a286c90223bad78 | [
"Apache-2.0"
] | null | null | null | girder_rnascope/tilesource/tiff.py | abcsFrederick/RNAScope | 9cb049f9c64f52e49afddfb32a286c90223bad78 | [
"Apache-2.0"
] | 8 | 2019-09-25T14:07:14.000Z | 2019-10-01T16:45:08.000Z | girder_rnascope/tilesource/tiff.py | cj-abcs/RNAScope | 9cb049f9c64f52e49afddfb32a286c90223bad78 | [
"Apache-2.0"
] | null | null | null | import large_image_source_tiff as tiff
# from large_image.tilesource.base import GirderTileSource
from large_image_source_tiff import girder_source
from .tiff_reader import TiledTiffDirectory
tiff.TiledTiffDirectory = TiledTiffDirectory
| 27.941176 | 83 | 0.821053 | import large_image_source_tiff as tiff
# from large_image.tilesource.base import GirderTileSource
from large_image_source_tiff import girder_source
from .tiff_reader import TiledTiffDirectory
tiff.TiledTiffDirectory = TiledTiffDirectory
class TiffFileTileSource(tiff.TiffFileTileSource):
cacheName = 'tilesource'
name = 'tifffile'
class TiffGirderTileSource(TiffFileTileSource, girder_source.TiffGirderTileSource):
cacheName = 'tilesource'
name = 'tiff'
| 0 | 189 | 46 |
a324ee7a3459d4ec211befb07ccbe404786243a9 | 907 | py | Python | scraper/storage_spiders/songvunet.py | chongiadung/choinho | d2a216fe7a5064d73cdee3e928a7beef7f511fd1 | [
"MIT"
] | null | null | null | scraper/storage_spiders/songvunet.py | chongiadung/choinho | d2a216fe7a5064d73cdee3e928a7beef7f511fd1 | [
"MIT"
] | 10 | 2020-02-11T23:34:28.000Z | 2022-03-11T23:16:12.000Z | scraper/storage_spiders/songvunet.py | chongiadung/choinho | d2a216fe7a5064d73cdee3e928a7beef7f511fd1 | [
"MIT"
] | 3 | 2018-08-05T14:54:25.000Z | 2021-06-07T01:49:59.000Z | # Auto generated by generator.py. Delete this line if you make modification.
from scrapy.spiders import Rule
from scrapy.linkextractors import LinkExtractor
XPATH = {
'name' : "//div[@class='header_layer_2']/h1",
'price' : "//input[@name='price']/@value",
'category' : "//div[@class='thanh_dinh_huong']/a",
'description' : "",
'images' : "//img[@id='anh_chitiet_sanpham']/@src",
'canonical' : "",
'base_url' : "//base/@href",
'brand' : ""
}
name = 'songvu.net'
allowed_domains = ['songvu.net']
start_urls = ['http://songvu.net/ao-so-mi-nam-d37v3.html']
tracking_url = ''
sitemap_urls = ['']
sitemap_rules = [('', 'parse_item')]
sitemap_follow = []
rules = [
Rule(LinkExtractor(allow=['/[a-zA-Z0-9-]+-id\d+\.html$']), 'parse_item'),
Rule(LinkExtractor(allow=['/[a-zA-Z0-9-]+-d\d+(v3)?(p\d+)?\.html$']), 'parse'),
#Rule(LinkExtractor(), 'parse_item_and_links'),
]
| 33.592593 | 83 | 0.62183 | # Auto generated by generator.py. Delete this line if you make modification.
from scrapy.spiders import Rule
from scrapy.linkextractors import LinkExtractor
XPATH = {
'name' : "//div[@class='header_layer_2']/h1",
'price' : "//input[@name='price']/@value",
'category' : "//div[@class='thanh_dinh_huong']/a",
'description' : "",
'images' : "//img[@id='anh_chitiet_sanpham']/@src",
'canonical' : "",
'base_url' : "//base/@href",
'brand' : ""
}
name = 'songvu.net'
allowed_domains = ['songvu.net']
start_urls = ['http://songvu.net/ao-so-mi-nam-d37v3.html']
tracking_url = ''
sitemap_urls = ['']
sitemap_rules = [('', 'parse_item')]
sitemap_follow = []
rules = [
Rule(LinkExtractor(allow=['/[a-zA-Z0-9-]+-id\d+\.html$']), 'parse_item'),
Rule(LinkExtractor(allow=['/[a-zA-Z0-9-]+-d\d+(v3)?(p\d+)?\.html$']), 'parse'),
#Rule(LinkExtractor(), 'parse_item_and_links'),
]
| 0 | 0 | 0 |
ac9be7a8b5a5c2a234164185c4e23dd581187a69 | 447 | py | Python | cpdb/data/migrations/0107_remove_area_line_area_from_allegation.py | invinst/CPDBv2_backend | b4e96d620ff7a437500f525f7e911651e4a18ef9 | [
"Apache-2.0"
] | 25 | 2018-07-20T22:31:40.000Z | 2021-07-15T16:58:41.000Z | cpdb/data/migrations/0107_remove_area_line_area_from_allegation.py | invinst/CPDBv2_backend | b4e96d620ff7a437500f525f7e911651e4a18ef9 | [
"Apache-2.0"
] | 13 | 2018-06-18T23:08:47.000Z | 2022-02-10T07:38:25.000Z | cpdb/data/migrations/0107_remove_area_line_area_from_allegation.py | invinst/CPDBv2_backend | b4e96d620ff7a437500f525f7e911651e4a18ef9 | [
"Apache-2.0"
] | 6 | 2018-05-17T21:59:43.000Z | 2020-11-17T00:30:26.000Z | # Generated by Django 2.1.3 on 2019-01-08 04:17
from django.db import migrations
| 20.318182 | 52 | 0.574944 | # Generated by Django 2.1.3 on 2019-01-08 04:17
from django.db import migrations
class Migration(migrations.Migration):
dependencies = [
('data', '0106_add_field_police_witnesses'),
]
operations = [
migrations.RemoveField(
model_name='allegation',
name='areas',
),
migrations.RemoveField(
model_name='allegation',
name='line_areas',
),
]
| 0 | 341 | 23 |
69cc2165b44440845ddc93cd30a1945f73e4c1f1 | 2,262 | py | Python | regularization/train_xgb.py | Fenkail/Deep_learning_basics | a395b5a78e9a742b7fbcf0bf9fe8a0f7022499a5 | [
"Apache-2.0"
] | null | null | null | regularization/train_xgb.py | Fenkail/Deep_learning_basics | a395b5a78e9a742b7fbcf0bf9fe8a0f7022499a5 | [
"Apache-2.0"
] | null | null | null | regularization/train_xgb.py | Fenkail/Deep_learning_basics | a395b5a78e9a742b7fbcf0bf9fe8a0f7022499a5 | [
"Apache-2.0"
] | null | null | null | import numpy as np
import time
import xgboost as xgb
from sklearn.model_selection import KFold
from regularization.score import myFeval
from sklearn.metrics import mean_squared_error
from regularization.data_process import data_process
s = time.time()
X_train, y_train, X_test, train_len, test_len = data_process()
print('加载数据及预处理消耗时间:', time.time()-s)
xgb_params = {"booster": 'gbtree',
'eta': 0.005,
'max_depth': 5,
'subsample': 0.7, # 随机采样训练样本
'colsample_bytree': 0.8,
'objective': 'reg:linear',
'eval_metric': 'rmse',
'silent': True,
'lambda': 1
}
folds = KFold(n_splits=5, shuffle=True, random_state=2018)
oof_xgb = np.zeros(train_len)
predictions_xgb = np.zeros(test_len)
for fold_, (trn_idx, val_idx) in enumerate(folds.split(X_train, y_train)):
print("fold n°{}".format(fold_ + 1))
trn_data = xgb.DMatrix(X_train[trn_idx], y_train[trn_idx])
val_data = xgb.DMatrix(X_train[val_idx], y_train[val_idx])
watchlist = [(trn_data, 'train'), (val_data, 'valid_data')]
clf = xgb.train(dtrain=trn_data, num_boost_round=20000, evals=watchlist, early_stopping_rounds=200,
verbose_eval=100, params=xgb_params, feval=myFeval)
oof_xgb[val_idx] = clf.predict(xgb.DMatrix(X_train[val_idx]), ntree_limit=clf.best_ntree_limit)
predictions_xgb += clf.predict(xgb.DMatrix(X_test), ntree_limit=clf.best_ntree_limit) / folds.n_splits
print("CV score: {:<8.8f}".format(mean_squared_error(oof_xgb, y_train.tolist())))
'''
--------------------------------------------
1. 初始参数 reg:linear 0.45434592
2. 增加L2正则 'lambda':2 0.45488106
3. 2+增加L1正则 'alpha': 1 0.45456481
4. 增加L1正则 'alpha': 1 0.45460193
5. 3+subsample改为0.6 0.45449627
6. 只改subsample 0.6 0.45448684
7. 只改subsample 0.8 0.45625735
8. 1+增加L1正则0.5 0.45431723
9. 1+增加L1正则0.3 0.45450940
10.1+增加L1正则0.7 0.45447847
11.1+增加L1正则0.6 0.45467713
12.1+增加L1正则0.55 0.45430484 ○
13.12+L2正则0.5 0.45467713
14.12+L2正则3 0.45431729
15.1+增加L2正则3 0.45484879
16.1+增加L2正则1 0.45434592
17.1+增加L2正则0.5 0.45469010
''' | 34.8 | 106 | 0.631742 | import numpy as np
import time
import xgboost as xgb
from sklearn.model_selection import KFold
from regularization.score import myFeval
from sklearn.metrics import mean_squared_error
from regularization.data_process import data_process
s = time.time()
X_train, y_train, X_test, train_len, test_len = data_process()
print('加载数据及预处理消耗时间:', time.time()-s)
xgb_params = {"booster": 'gbtree',
'eta': 0.005,
'max_depth': 5,
'subsample': 0.7, # 随机采样训练样本
'colsample_bytree': 0.8,
'objective': 'reg:linear',
'eval_metric': 'rmse',
'silent': True,
'lambda': 1
}
folds = KFold(n_splits=5, shuffle=True, random_state=2018)
oof_xgb = np.zeros(train_len)
predictions_xgb = np.zeros(test_len)
for fold_, (trn_idx, val_idx) in enumerate(folds.split(X_train, y_train)):
print("fold n°{}".format(fold_ + 1))
trn_data = xgb.DMatrix(X_train[trn_idx], y_train[trn_idx])
val_data = xgb.DMatrix(X_train[val_idx], y_train[val_idx])
watchlist = [(trn_data, 'train'), (val_data, 'valid_data')]
clf = xgb.train(dtrain=trn_data, num_boost_round=20000, evals=watchlist, early_stopping_rounds=200,
verbose_eval=100, params=xgb_params, feval=myFeval)
oof_xgb[val_idx] = clf.predict(xgb.DMatrix(X_train[val_idx]), ntree_limit=clf.best_ntree_limit)
predictions_xgb += clf.predict(xgb.DMatrix(X_test), ntree_limit=clf.best_ntree_limit) / folds.n_splits
print("CV score: {:<8.8f}".format(mean_squared_error(oof_xgb, y_train.tolist())))
'''
--------------------------------------------
1. 初始参数 reg:linear 0.45434592
2. 增加L2正则 'lambda':2 0.45488106
3. 2+增加L1正则 'alpha': 1 0.45456481
4. 增加L1正则 'alpha': 1 0.45460193
5. 3+subsample改为0.6 0.45449627
6. 只改subsample 0.6 0.45448684
7. 只改subsample 0.8 0.45625735
8. 1+增加L1正则0.5 0.45431723
9. 1+增加L1正则0.3 0.45450940
10.1+增加L1正则0.7 0.45447847
11.1+增加L1正则0.6 0.45467713
12.1+增加L1正则0.55 0.45430484 ○
13.12+L2正则0.5 0.45467713
14.12+L2正则3 0.45431729
15.1+增加L2正则3 0.45484879
16.1+增加L2正则1 0.45434592
17.1+增加L2正则0.5 0.45469010
''' | 0 | 0 | 0 |
d16be71e287d71b716337ff7bcc9cf3256561c20 | 5,259 | py | Python | server/apps/utils/objects/tests.py | iotile/iotile_cloud | 9dc65ac86d3a730bba42108ed7d9bbb963d22ba6 | [
"MIT"
] | null | null | null | server/apps/utils/objects/tests.py | iotile/iotile_cloud | 9dc65ac86d3a730bba42108ed7d9bbb963d22ba6 | [
"MIT"
] | null | null | null | server/apps/utils/objects/tests.py | iotile/iotile_cloud | 9dc65ac86d3a730bba42108ed7d9bbb963d22ba6 | [
"MIT"
] | null | null | null | from django.test import TestCase
from apps.datablock.models import DataBlock
from apps.fleet.models import Fleet
from apps.physicaldevice.models import Device
from apps.stream.models import StreamId, StreamVariable
from ..test_util import TestMixin
from .utils import *
from .utils import _get_real_slug
| 37.564286 | 115 | 0.659631 | from django.test import TestCase
from apps.datablock.models import DataBlock
from apps.fleet.models import Fleet
from apps.physicaldevice.models import Device
from apps.stream.models import StreamId, StreamVariable
from ..test_util import TestMixin
from .utils import *
from .utils import _get_real_slug
class ObjectBySlugTests(TestMixin, TestCase):
def setUp(self):
self.usersTestSetup()
self.orgTestSetup()
self.deviceTemplateTestSetup()
self.v1 = StreamVariable.objects.create_variable(
name='Var A', project=self.p1, created_by=self.u2, lid=1,
)
self.v2 = StreamVariable.objects.create_variable(
name='Var B', project=self.p2, created_by=self.u3, lid=2,
)
self.pd1 = Device.objects.create_device(project=self.p1, label='d1', template=self.dt1, created_by=self.u2)
self.pd2 = Device.objects.create_device(project=self.p2, label='d2', template=self.dt1, created_by=self.u3)
def tearDown(self):
StreamId.objects.all().delete()
StreamVariable.objects.all().delete()
Device.objects.all().delete()
DataBlock.objects.all().delete()
self.deviceTemplateTestTearDown()
self.orgTestTearDown()
self.userTestTearDown()
def testRealSlug(self):
real = _get_real_slug('@foo')
self.assertEqual(real, 'foo')
real = _get_real_slug('^bar')
self.assertEqual(real, 'bar')
real = _get_real_slug('d--0001')
self.assertEqual(real, 'd--0001')
def testProject(self):
n, o = get_object_by_slug(self.p1.obj_target_slug)
self.assertEqual(n, 'project')
self.assertIsNotNone(o)
self.assertEqual(o.id, self.p1.id)
def testDevice(self):
n, o = get_object_by_slug(self.pd1.obj_target_slug)
self.assertEqual(n, 'device')
self.assertIsNotNone(o)
self.assertEqual(o.id, self.pd1.id)
def testVariable(self):
n, o = get_object_by_slug(self.v1.obj_target_slug)
self.assertEqual(n, 'variable')
self.assertIsNotNone(o)
self.assertEqual(o.id, self.v1.id)
def testStream(self):
StreamId.objects.create_after_new_device(self.pd1)
StreamId.objects.create_after_new_device(self.pd2)
s1 = StreamId.objects.filter(variable=self.v1).first()
n, o = get_object_by_slug(s1.obj_target_slug)
self.assertEqual(n, 'stream')
self.assertIsNotNone(o)
self.assertEqual(o.id, s1.id)
def testStreamWithoutStreamId(self):
sys_stream = '--'.join(['s', self.pd2.project.formatted_gid, self.pd2.formatted_gid, '5800'])
n, o = get_object_by_slug(sys_stream)
self.assertEqual(n, 'stream')
self.assertIsNone(o)
def testDataBlock(self):
db1 = DataBlock.objects.create(org=self.o1, title='test1', device=self.pd1, block=1, created_by=self.u1)
DataBlock.objects.create(org=self.o1, title='test2', device=self.pd1, block=2, created_by=self.u1)
n, o = get_object_by_slug(db1.obj_target_slug)
self.assertEqual(n, 'datablock')
self.assertIsNotNone(o)
self.assertEqual(o.id, db1.id)
def testDeviceOrDataBlock(self):
db1 = DataBlock.objects.create(org=self.o1, title='test1', device=self.pd1, block=1, created_by=self.u1)
DataBlock.objects.create(org=self.o1, title='test2', device=self.pd1, block=2, created_by=self.u1)
b = get_device_or_block('b--0001-123-0000-0001')
self.assertIsNone(b)
b = get_device_or_block(db1.obj_target_slug)
self.assertIsNotNone(b)
self.assertEqual(b.title, db1.title)
d = get_device_or_block('d--0000-123-0000-0001')
self.assertIsNone(d)
d = get_device_or_block(self.pd1.obj_target_slug)
self.assertIsNotNone(d)
self.assertEqual(d.id, self.pd1.id)
def testFleet(self):
fleet1 = Fleet.objects.create(name='F1', org=self.o2, created_by=self.u2)
n, o = get_object_by_slug(fleet1.obj_target_slug)
self.assertEqual(n, 'fleet')
self.assertIsNotNone(o)
self.assertEqual(o.id, fleet1.id)
def testUser(self):
n, o = get_object_by_slug(self.u2.obj_target_slug)
self.assertEqual(n, 'user')
self.assertIsNotNone(o)
self.assertEqual(o.id, self.u2.id)
def testOrg(self):
n, o = get_object_by_slug(self.o2.obj_target_slug)
self.assertEqual(n, 'org')
self.assertIsNotNone(o)
self.assertEqual(o.id, self.o2.id)
def testErorrHandleGetObjectWithDuplicate(self):
# While there should not be duplicated slugs
# test that if they exist, they don't crash the get_object_by_slug function
s1 = StreamId.objects.create_stream(
project=self.pd1.project, variable=self.v1, device=self.pd1, created_by=self.u2
)
s2 = StreamId.objects.create_stream(
project=self.pd1.project, variable=self.v1, device=self.pd1, created_by=self.u2
)
self.assertEqual(s1.slug, s2.slug)
n, o = get_object_by_slug(s2.slug)
self.assertEqual(n, 'stream')
self.assertIsNotNone(o)
self.assertTrue(str(o.id) in [str(s1.id), str(s2.id)])
| 4,527 | 24 | 401 |
834f9c87021cb2bb5137640f7ebb950dc0ac0eee | 798 | py | Python | system_tests/test_app_engine.py | yhuang/google-auth-library-python | ccf2e502e0b15633956c007fae92e2404a6418ad | [
"Apache-2.0"
] | 1 | 2020-05-27T15:48:51.000Z | 2020-05-27T15:48:51.000Z | system_tests/test_app_engine.py | yhuang/google-auth-library-python | ccf2e502e0b15633956c007fae92e2404a6418ad | [
"Apache-2.0"
] | null | null | null | system_tests/test_app_engine.py | yhuang/google-auth-library-python | ccf2e502e0b15633956c007fae92e2404a6418ad | [
"Apache-2.0"
] | 1 | 2019-11-11T18:39:46.000Z | 2019-11-11T18:39:46.000Z | # Copyright 2016 Google Inc.
#
# 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.
import os
TEST_APP_URL = os.environ['TEST_APP_URL']
| 34.695652 | 74 | 0.756892 | # Copyright 2016 Google Inc.
#
# 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.
import os
TEST_APP_URL = os.environ['TEST_APP_URL']
def test_live_application(http_request):
response = http_request(method='GET', url=TEST_APP_URL)
assert response.status == 200, response.data.decode('utf-8')
| 144 | 0 | 23 |
c600576e5860966b3254155c8bab3c8a148fd251 | 180 | py | Python | 2d.py | tcstewar/ik2017 | 582156a9e3f888f2d1a5e27024e08ef97652e57c | [
"MIT"
] | 5 | 2017-03-13T15:29:18.000Z | 2017-03-14T14:54:54.000Z | comm.py | tcstewar/ik2017 | 582156a9e3f888f2d1a5e27024e08ef97652e57c | [
"MIT"
] | null | null | null | comm.py | tcstewar/ik2017 | 582156a9e3f888f2d1a5e27024e08ef97652e57c | [
"MIT"
] | null | null | null | import nengo
model = nengo.Network()
with model:
a = nengo.Ensemble(n_neurons=100, dimensions=2, radius=1)
stim = nengo.Node([0,0])
nengo.Connection(stim, a) | 20 | 61 | 0.644444 | import nengo
model = nengo.Network()
with model:
a = nengo.Ensemble(n_neurons=100, dimensions=2, radius=1)
stim = nengo.Node([0,0])
nengo.Connection(stim, a) | 0 | 0 | 0 |
766d111951c2d783a6fb6d8bc5c9611421ae0867 | 1,428 | py | Python | exec/12-2.py | MasazI/python-r-stan-bayesian-model-2 | 288876b31b6c3d74d523babc475d4794cd29680a | [
"MIT"
] | 25 | 2020-07-11T11:07:28.000Z | 2022-03-06T01:12:45.000Z | exec/12-2.py | MasazI/python-r-stan-bayesian-model-2 | 288876b31b6c3d74d523babc475d4794cd29680a | [
"MIT"
] | null | null | null | exec/12-2.py | MasazI/python-r-stan-bayesian-model-2 | 288876b31b6c3d74d523babc475d4794cd29680a | [
"MIT"
] | 1 | 2021-05-06T08:48:55.000Z | 2021-05-06T08:48:55.000Z | # 時系列予測の問題に季節項を導入する
# 時系列データは、目的変数を観測値の要素の和に分解するのが定石
# Own Library
import mcmc_tools
import analysis_data as ad
import seaborn as sns
import matplotlib.pyplot as plt
if __name__ == '__main__':
spm = SPM('data-ss2.txt', '../model/model12-2')
spm.describe()
spm.observe_ts()
stan_data = spm.create_data()
mcmc_sample = spm.fit(stan_data)
# 全体の観測および予測分布
spm.create_figure(mcmc_sample, 'y_mean_pred')
# 要素ごとに分けて観測および予測分布
spm.create_figure(mcmc_sample, 'mu_pred')
spm.create_figure(mcmc_sample, 'season_pred')
| 24.62069 | 89 | 0.587535 | # 時系列予測の問題に季節項を導入する
# 時系列データは、目的変数を観測値の要素の和に分解するのが定石
# Own Library
import mcmc_tools
import analysis_data as ad
import seaborn as sns
import matplotlib.pyplot as plt
class SPM(ad.AnalysisData):
def observe_ts(self):
sns.lineplot(x=self.data['X'], y=self.data['Y'])
plt.show()
plt.close()
def create_data(self):
Y = self.data['Y']
N = len(Y)
N_pred = 4
L = 4
return {
'Y': Y,
'N': N,
'L': L,
'N_pred': N_pred
}
def fit(self, stan_data):
mcmc_result = mcmc_tools.sampling(self.model_file, stan_data, n_jobs=4, seed=123)
return mcmc_result.extract()
def create_figure(self, mcmc_sample, state: str):
pred_dates = [i for i in range(len(self.data['Y']) + 4)]
# pred_dates = np.linspace(0, len(self.data['Y']) + 3, 100)
mcmc_tools.plot_ssm(mcmc_sample, pred_dates, 'season and trend model'
'model', 'Y', state)
if __name__ == '__main__':
spm = SPM('data-ss2.txt', '../model/model12-2')
spm.describe()
spm.observe_ts()
stan_data = spm.create_data()
mcmc_sample = spm.fit(stan_data)
# 全体の観測および予測分布
spm.create_figure(mcmc_sample, 'y_mean_pred')
# 要素ごとに分けて観測および予測分布
spm.create_figure(mcmc_sample, 'mu_pred')
spm.create_figure(mcmc_sample, 'season_pred')
| 737 | 6 | 130 |
27588fd5f14b8212df3a99af54f72d43a28cfd8f | 16,055 | py | Python | legacy/ScopTester.py | 861934367/cgat | 77fdc2f819320110ed56b5b61968468f73dfc5cb | [
"BSD-2-Clause",
"BSD-3-Clause"
] | 87 | 2015-01-01T03:48:19.000Z | 2021-11-23T16:23:24.000Z | legacy/ScopTester.py | 861934367/cgat | 77fdc2f819320110ed56b5b61968468f73dfc5cb | [
"BSD-2-Clause",
"BSD-3-Clause"
] | 189 | 2015-01-06T15:53:11.000Z | 2019-05-31T13:19:45.000Z | legacy/ScopTester.py | CGATOxford/cgat | 326aad4694bdfae8ddc194171bb5d73911243947 | [
"BSD-2-Clause",
"BSD-3-Clause"
] | 56 | 2015-01-13T02:18:50.000Z | 2022-01-05T10:00:59.000Z | ################################################################################
#
# MRC FGU Computational Genomics Group
#
# $Id$
#
# Copyright (C) 2009 Andreas Heger
#
# This program is free software; you can redistribute it and/or
# modify it under the terms of the GNU General Public License
# as published by the Free Software Foundation; either version 2
# of the License, or (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program; if not, write to the Free Software
# Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
#################################################################################
'''
ScopTester.py -
======================================================
:Author: Andreas Heger
:Release: $Id$
:Date: |today|
:Tags: Python
Code
----
'''
import sys
import re
import string
import os
import time
from Pairsdb import *
import alignlib
import pairsdblib
from MessagePairsdb import MessagePairsdb
from TableDomainsScopTest import TableDomainsScopTest
from TablePairsdbNeighbours import TablePairsdbNeighbours
from Pairsdb import *
import Tools
#-------------------------------------------
# Class: ScopTest
# Superclasses: Message
# Subclasses:
# Function: update ScopTest-database
#
# Author: Andreas Heger
#-------------------------------------------
##--------------------------------------------------------------------------------------
##--------------------------------------------------------------------------------------
##--------------------------------------------------------------------------------------
class ScopTesterFullProfiles( ScopTesterProfiles ):
"""use full length profiles.
beware of multidomain-proteins, use iterative multiple alignment
method.
"""
##--------------------------------------------------------------------------------------
class Alignator:
"""
aligns two sequences and returns result.
"""
##--------------------------------------------------------------------------------------
##--------------------------------------------------------------------------------------
def CheckResult( self,
result,
info1 = None,
info2 = None):
"""check if result is ok. The function below returns everything.
return tuple of strings as result.
"""
if (result.getLength() > 0):
row_ali, col_ali = alignlib.writeAlignataCompressed( result )
return map(str, (result.getScore(),
result.getLength(),
result.getNumGaps(),
alignlib.calculatePercentSimilarity( result ),
result.getRowFrom(), result.getRowTo(), row_ali,
result.getColFrom(), result.getColTo(), col_ali ) )
else:
return ("0",) * 12
##--------------------------------------------------------------------------------------
class AlignatorIterative(Alignator):
"""
aligns two sequences iteratively, checks if alignment regions are overlapping with
domain regions and returns result only for those overlapping. This is useful if you have
several domains in a sequence, but you need only compare to one.
"""
##--------------------------------------------------------------------------------------
def Align( self, a1, a2, result ):
"""align repetetively. Take highest scoring alignment, that overlaps with domains
and put it in result. Note: performIterativeAlignment does not work, as it is linear.
It requires domains to be in the same order.
Result is empty, fragments are saved in object.
"""
fragmentor = alignlib.makeFragmentorRepetitive( self.mAlignator, self.mMinScore )
## align iteratively and convert fragments to Alignata-objects
val = fragmentor.Fragment( a1, a2, result)
self.mFragments = map( lambda x: alignlib.AlignataPtr(x), val)
for fragment in self.mFragments:
fragment.thisown = 1
## alignlib.performIterativeAlignmentNonConst( result,
## a1, a2,
## self.mAlignator,
## self.mMinScore )
##--------------------------------------------------------------------------------------
def CheckResult( self,
result,
info1, info2):
"""check if result is ok. Check for each fragment, if it overlaps
with the domains to be tested and dump if ok. This simulates
psiblast.
"""
row_from, row_to = map(string.atoi, info1[1:3])
col_from, col_to = map(string.atoi, info2[1:3])
## check for overlap
for fragment in self.mFragments:
# print alignlib.writeAlignataTable( fragment, 8, 1)
xcol_from = Tools.MapRight(fragment, row_from )
xcol_to = Tools.MapLeft(fragment, row_to )
overlap = min(col_to, xcol_to) - max(col_from, xcol_from)
# print self.mMinOverlap, overlap, xcol_from, xcol_to, col_from, col_to
if overlap > self.mMinOverlap:
return map(str, (fragment.getScore(),
fragment.getLength(),
fragment.getNumGaps(),
alignlib.calculatePercentSimilarity( fragment ),
fragment.getRowFrom(), fragment.getRowTo(),
fragment.getColFrom(), fragment.getColTo(),
overlap, xcol_from, xcol_to,
(xcol_to - xcol_from) - (col_to - col_from)) )
return ("0",) * 12
##--------------------------------------------------------------------------------------
if __name__ == '__main__':
dbhandle = Pairsdb()
if not dbhandle.Connect():
print "Connection failed"
sys.exit(1)
a = alignlib.makeFullDP( -10.0, -2.0 )
alignator = Alignator( a )
x = ScopTesterSequences( dbhandle, alignator )
x.Process()
if param_alignator == 0:
a = alignlib.makeFullDP( param_gop, param_gep)
alignator = Alignator( a )
if param_entities == 0:
tester = ScopTesterSequences( dbhandle, alignator )
tester.mLogLevel = param_loglevel
matches = a.CalculateMatches()
| 36.823394 | 120 | 0.482903 | ################################################################################
#
# MRC FGU Computational Genomics Group
#
# $Id$
#
# Copyright (C) 2009 Andreas Heger
#
# This program is free software; you can redistribute it and/or
# modify it under the terms of the GNU General Public License
# as published by the Free Software Foundation; either version 2
# of the License, or (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program; if not, write to the Free Software
# Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
#################################################################################
'''
ScopTester.py -
======================================================
:Author: Andreas Heger
:Release: $Id$
:Date: |today|
:Tags: Python
Code
----
'''
import sys
import re
import string
import os
import time
from Pairsdb import *
import alignlib
import pairsdblib
from MessagePairsdb import MessagePairsdb
from TableDomainsScopTest import TableDomainsScopTest
from TablePairsdbNeighbours import TablePairsdbNeighbours
from Pairsdb import *
import Tools
#-------------------------------------------
# Class: ScopTest
# Superclasses: Message
# Subclasses:
# Function: update ScopTest-database
#
# Author: Andreas Heger
#-------------------------------------------
class ScopTester:
def __init__ (self, dbhandle, alignator, table_scop_test ):
self.mLogLevel = 1
self.dbhandle = dbhandle
# C++ connection to pairsdb
self.mDatabaseNamePairsdb = dbhandle.GetDatabase()
self.mConnectionPairsdb = pairsdblib.Connection( dbhandle.GetHost(),
dbhandle.GetUser(),
dbhandle.GetPassword(),
dbhandle.GetPort())
self.mConnectionPairsdb.Connect( self.mDatabaseNamePairsdb )
self.mTableScopTest = table_scop_test
self.mAlignanda = []
self.mInformation = []
self.mAlignator = alignator
self.startAt = 0
##--------------------------------------------------------------------------------------
def CalculateMatches( self ):
"""calculate all-vs-all alignments.
"""
if not self.mAlignanda:
self.GetAlignanda()
if self.mLogLevel >= 1:
print "# --> calculating alignments for %i entries" % len(self.mAlignanda)
print "# --> starting at:", Tools.GetTimeStamp()
nalignanda = len(self.mAlignanda)
for a1 in range(self.startAt, nalignanda-1):
if self.mLogLevel >= 1:
print "# %5i/%5i at %s" % (a1, nalignanda, Tools.GetTimeStamp())
sys.stdout.flush()
for a2 in range(a1+1,nalignanda):
if self.mLogLevel >= 3:
print "# aligning to %i" % (a2), self.mInformation[a2]
sys.stdout.flush()
result = alignlib.makeAlignataVector()
self.mAlignator.Align( self.mAlignanda[a1], self.mAlignanda[a2], result )
info = self.mAlignator.CheckResult( result, self.mInformation[a1], self.mInformation[a2] )
if info:
r = tuple(self.mInformation[a1]) + tuple(self.mInformation[a2]) + tuple(info)
print string.join(r, "\t" )
sys.stdout.flush()
self.mAlignanda[a1].Release()
self.mAlignanda[a1] = None
if self.mLogLevel >= 1:
print "# --> finished at:", Tools.GetTimeStamp()
##--------------------------------------------------------------------------------------
def SetAlignator( self, alignator ):
self.mAlignator = alignator
##--------------------------------------------------------------------------------------
def GetAlignanda( self ):
"""retrieve alignandum-objects.
"""
## do not get additional info so that non-redundant table can be used.
domains = self.mTableScopTest.GetAllDomains( all = 0 )
if self.mLogLevel >= 1:
print "# --> retrieving %i entries at %s" % (len(domains), Tools.GetTimeStamp())
sys.stdout.flush()
for domain in domains:
if self.mLogLevel >= 2:
print "# retrieving", domain
sys.stdout.flush()
(nid, nrdb_from, nrdb_to, scop_class) = domain
## dummy values
pdb_id = "test"
region_nr = 0
if scop_class[0:3] not in ("00a", "00b", "00c", "00d"):
if self.mLogLevel >= 2:
print "# skipped because not in first four classes"
sys.stdout.flush()
continue
# if nid not in (47268, 74355): continue
# if nid not in (36388, 148361): continue
# if nid not in (3503, 115681): continue
# if nid not in (17, 1011060): continue
alignandum, info = self.GetAlignandum( nid, nrdb_from, nrdb_to )
if alignandum:
if info:
self.mInformation.append( ( "%i_%i_%i" % (nid, nrdb_from, nrdb_to),
scop_class, pdb_id, str(region_nr)) + tuple(info) )
else:
self.mInformation.append( ( "%i_%i_%i" % (nid, nrdb_from, nrdb_to),
scop_class, pdb_id, str(region_nr)) )
self.mAlignanda.append(alignandum)
else:
if self.mLogLevel >= 2:
print "# skipped because no alignandum found"
sys.stdout.flush()
if self.mLogLevel >= 1:
print "# --> retrieved %i entries at %s" % (len(self.mAlignanda), Tools.GetTimeStamp())
sys.stdout.flush()
##--------------------------------------------------------------------------------------
class ScopTesterSequences( ScopTester ):
def GetAlignandum( self, nid, nrdb_from, nrdb_to ):
alignandum = pairsdblib.makeSequenceFromPairsdb( self.mConnectionPairsdb, nid )
alignandum.useSegment( nrdb_from, nrdb_to )
return alignandum, None
##--------------------------------------------------------------------------------------
class ScopTesterProfiles( ScopTester ):
def __init__(self,
dbhandle,
alignator,
table_scop_test,
min_profile_size = 20,
min_level = 30,
max_level = 90,
neighbours = "pairsdb_90x90"):
self.mMinProfileSize = min_profile_size
self.mMinLevel = min_level
self.mMaxLevel = max_level
self.mTableNameNeighbours = neighbours
ScopTester.__init__( self, dbhandle, alignator, table_scop_test )
self.mTableNeighbours = TablePairsdbNeighbours( self.dbhandle )
self.mTableNeighbours.SetName( self.mTableNameNeighbours)
self.mBlastL = 0.3 # lambda
self.mLogOddorScaleFactor = self.mBlastL
self.mLogOddor = alignlib.makeLogOddorDirichlet( self.mLogOddorScaleFactor )
self.mMaxLinesMali = 1000
self.mRegularizor = alignlib.makeRegularizorDirichletPrecomputed()
def GetAlignandum( self, nid, nrdb_from, nrdb_to ):
n = self.mTableNeighbours.GetNumNeighbours( nid )
if n >= self.mMinProfileSize:
profile = alignlib.makeEmptyProfile( self.mRegularizor, self.mLogOddor )
pairsdblib.fillProfileNeighbours( profile,
self.mConnectionPairsdb,
nid,
self.mTableNameNeighbours,
self.mMaxLinesMali,
0,
self.mMaxLevel,
self.mMinLevel )
if self.mLogLevel >= 3:
print "# ------> using profile for rep %i" % nid
else:
profile = pairsdblib.makeSequenceFromPicasso( self.mConnectionPairsdb, nid )
if self.mLogLevel >= 3:
print "# ------> using sequence for rep %i" % nid
profile.useSegment( nrdb_from, nrdb_to )
return profile, (str(n),)
##--------------------------------------------------------------------------------------
class ScopTesterFullProfiles( ScopTesterProfiles ):
"""use full length profiles.
beware of multidomain-proteins, use iterative multiple alignment
method.
"""
def __init__(self,
dbhandle,
alignator,
table_scop_test,
min_profile_size = 20,
min_level = 30,
max_level = 90,
neighbours = "pairsdb_90x90"):
ScopTesterProfiles.__init__( self,dbhandle, alignator, table_scop_test,
min_profile_size, min_level, max_level, neighbours)
self.mAddLength = 500
self.mMaxLength = 2000
def GetAlignandum( self, nid, nrdb_from, nrdb_to ):
profile, x = ScopTesterProfiles.GetAlignandum( self, nid, nrdb_from, nrdb_to)
profile.useFullLength()
# add some context around
xfrom = max( 1, nrdb_from - self.mAddLength)
xto = min( profile.getLength(), nrdb_to + self.mAddLength)
if self.mLogLevel >= 3:
print "using segment %i-%i" % (xfrom, xto)
sys.stdout.flush()
profile.useSegment( xfrom, xto)
return profile, x
##--------------------------------------------------------------------------------------
class Alignator:
"""
aligns two sequences and returns result.
"""
def __init__( self, alignator ):
self.mAlignator = alignator
##--------------------------------------------------------------------------------------
def Align( self, a1, a2, result ):
self.mAlignator.Align( a1, a2, result )
##--------------------------------------------------------------------------------------
def CheckResult( self,
result,
info1 = None,
info2 = None):
"""check if result is ok. The function below returns everything.
return tuple of strings as result.
"""
if (result.getLength() > 0):
row_ali, col_ali = alignlib.writeAlignataCompressed( result )
return map(str, (result.getScore(),
result.getLength(),
result.getNumGaps(),
alignlib.calculatePercentSimilarity( result ),
result.getRowFrom(), result.getRowTo(), row_ali,
result.getColFrom(), result.getColTo(), col_ali ) )
else:
return ("0",) * 12
##--------------------------------------------------------------------------------------
class AlignatorIterative(Alignator):
"""
aligns two sequences iteratively, checks if alignment regions are overlapping with
domain regions and returns result only for those overlapping. This is useful if you have
several domains in a sequence, but you need only compare to one.
"""
def __init__( self, alignator, min_score, min_overlap, gop, gep ):
self.mAlignator = alignator
self.mMinScore = float(min_score)
self.mMinOverlap = min_overlap
self.mGop = gop
self.mGep = gep
##--------------------------------------------------------------------------------------
def Align( self, a1, a2, result ):
"""align repetetively. Take highest scoring alignment, that overlaps with domains
and put it in result. Note: performIterativeAlignment does not work, as it is linear.
It requires domains to be in the same order.
Result is empty, fragments are saved in object.
"""
fragmentor = alignlib.makeFragmentorRepetitive( self.mAlignator, self.mMinScore )
## align iteratively and convert fragments to Alignata-objects
val = fragmentor.Fragment( a1, a2, result)
self.mFragments = map( lambda x: alignlib.AlignataPtr(x), val)
for fragment in self.mFragments:
fragment.thisown = 1
## alignlib.performIterativeAlignmentNonConst( result,
## a1, a2,
## self.mAlignator,
## self.mMinScore )
##--------------------------------------------------------------------------------------
def CheckResult( self,
result,
info1, info2):
"""check if result is ok. Check for each fragment, if it overlaps
with the domains to be tested and dump if ok. This simulates
psiblast.
"""
row_from, row_to = map(string.atoi, info1[1:3])
col_from, col_to = map(string.atoi, info2[1:3])
## check for overlap
for fragment in self.mFragments:
# print alignlib.writeAlignataTable( fragment, 8, 1)
xcol_from = Tools.MapRight(fragment, row_from )
xcol_to = Tools.MapLeft(fragment, row_to )
overlap = min(col_to, xcol_to) - max(col_from, xcol_from)
# print self.mMinOverlap, overlap, xcol_from, xcol_to, col_from, col_to
if overlap > self.mMinOverlap:
return map(str, (fragment.getScore(),
fragment.getLength(),
fragment.getNumGaps(),
alignlib.calculatePercentSimilarity( fragment ),
fragment.getRowFrom(), fragment.getRowTo(),
fragment.getColFrom(), fragment.getColTo(),
overlap, xcol_from, xcol_to,
(xcol_to - xcol_from) - (col_to - col_from)) )
return ("0",) * 12
##--------------------------------------------------------------------------------------
if __name__ == '__main__':
dbhandle = Pairsdb()
if not dbhandle.Connect():
print "Connection failed"
sys.exit(1)
a = alignlib.makeFullDP( -10.0, -2.0 )
alignator = Alignator( a )
x = ScopTesterSequences( dbhandle, alignator )
x.Process()
if param_alignator == 0:
a = alignlib.makeFullDP( param_gop, param_gep)
alignator = Alignator( a )
if param_entities == 0:
tester = ScopTesterSequences( dbhandle, alignator )
tester.mLogLevel = param_loglevel
matches = a.CalculateMatches()
| 4,470 | 4,071 | 299 |
9d68468167a5ad6a7cbcf83c2e4439a5b61db798 | 3,045 | py | Python | tests/cookie_jar_test.py | p/webracer | 3eb40b520bbf884c4458482fc3a05a9a9632d026 | [
"BSD-2-Clause"
] | null | null | null | tests/cookie_jar_test.py | p/webracer | 3eb40b520bbf884c4458482fc3a05a9a9632d026 | [
"BSD-2-Clause"
] | null | null | null | tests/cookie_jar_test.py | p/webracer | 3eb40b520bbf884c4458482fc3a05a9a9632d026 | [
"BSD-2-Clause"
] | 1 | 2019-04-13T07:43:28.000Z | 2019-04-13T07:43:28.000Z | import webracer
import nose.plugins.attrib
from . import utils
from .apps import kitchen_sink_app
utils.app_runner_setup(__name__, kitchen_sink_app.app, 8056)
base_config = dict(host='localhost', port=8056)
@nose.plugins.attrib.attr('client')
| 34.213483 | 68 | 0.639409 | import webracer
import nose.plugins.attrib
from . import utils
from .apps import kitchen_sink_app
utils.app_runner_setup(__name__, kitchen_sink_app.app, 8056)
base_config = dict(host='localhost', port=8056)
@nose.plugins.attrib.attr('client')
class AgentWithoutCookieJarTest(webracer.WebTestCase):
def test_request(self):
'''Tests that the client works when use_cookie_jar is False.
'''
config = utils.add_dicts(base_config, dict(
use_cookie_jar=False))
s = webracer.Agent(**config)
s.get('/ok')
self.assertEqual(200, s.response.code)
self.assertEqual('ok', s.response.body)
# response cookie access
self.assertEqual([], utils.listit(s.response.raw_cookies))
self.assertEqual({}, s.response.cookies)
# response assertions
s.assert_not_response_cookie('visited')
s.assert_not_cookie_jar_cookie('visited')
def test_no_cookie_jar(self):
'''Tests that the client works when use_cookie_jar is True,
when cookies are set in response.
'''
config = utils.add_dicts(base_config, dict(
use_cookie_jar=False))
s = webracer.Agent(**config)
s.get('/set_cookie')
self.assertEqual(200, s.response.code)
self.assertEqual('ok', s.response.body)
# response cookie access
self.assertEqual(1, len(s.response.raw_cookies))
self.assertEqual(1, len(s.response.cookies))
assert 'visited' in s.response.cookies
cookie = s.response.cookies['visited']
self.assertEqual('yes', cookie.value)
# response assertions
s.assert_response_cookie('visited')
s.assert_not_cookie_jar_cookie('visited')
def test_with_cookie_jar(self):
s = webracer.agent.Agent(**base_config)
s.get('/set_cookie')
self.assertEqual(200, s.response.code)
self.assertEqual('ok', s.response.body)
# response cookie access
self.assertEqual(1, len(s.response.raw_cookies))
self.assertEqual(1, len(s.response.cookies))
assert 'visited' in s.response.cookies
cookie = s.response.cookies['visited']
self.assertEqual('yes', cookie.value)
# response assertions
s.assert_response_cookie('visited')
s.assert_cookie_jar_cookie('visited')
@webracer.config(**base_config)
def test_cookies_on_test_case_with_cookie_jar(self):
self.get('/set_cookie')
self.assert_status(200)
self.assertEqual('ok', self.response.body)
assert self.cookies is self.response.cookies
@webracer.config(use_cookie_jar=False)
@webracer.config(**base_config)
def test_cookies_on_test_case_without_cookie_jar(self):
self.get('/set_cookie')
self.assert_status(200)
self.assertEqual('ok', self.response.body)
assert self.cookies is self.response.cookies
| 1,031 | 1,746 | 22 |
485e7adc798133d68d09418c1fa6da75a642fe2f | 1,221 | py | Python | examinations/models.py | CASDON-MYSTERY/studentapp | 0fd942e963a10a02a6c9f358dd362cfd646eecc3 | [
"MIT"
] | null | null | null | examinations/models.py | CASDON-MYSTERY/studentapp | 0fd942e963a10a02a6c9f358dd362cfd646eecc3 | [
"MIT"
] | null | null | null | examinations/models.py | CASDON-MYSTERY/studentapp | 0fd942e963a10a02a6c9f358dd362cfd646eecc3 | [
"MIT"
] | null | null | null | from django.db import models
from lectures.models import Day
# Create your models here.
| 33 | 98 | 0.701065 | from django.db import models
from lectures.models import Day
# Create your models here.
class Exam_day_and_venue(models.Model):
day = models.ForeignKey(Day, on_delete=models.CASCADE,related_name="examination_day")
starting_time = models.TimeField("startin_time", auto_now=False, auto_now_add=False)
closing_time = models.TimeField("closing_time", auto_now=False, auto_now_add=False)
venue = models.CharField(max_length = 150)
def __str__(self):
return str(self.day)
class Meta:
db_table = ''
managed = True
verbose_name = 'Exam_day_and_venue'
verbose_name_plural = 'Exam_days_and_venues'
class Examination(models.Model):
course_code = models.IntegerField()
course_title = models.CharField("course_title", max_length = 150)
days_and_venues = models.ManyToManyField(Exam_day_and_venue,related_name="exam_day_and_venue")
invigilators = models.CharField("invigilators", max_length = 250, blank=True, null=True)
def __str__(self):
return f"{self.code} : {self.title}"
class Meta:
db_table = ''
managed = True
verbose_name = 'Examination'
verbose_name_plural = 'Examinations'
| 68 | 1,017 | 46 |
3d05df3acb44863b17295456c5d0343654bc478b | 17,059 | py | Python | tests/unit/test_webhooks.py | sharma7n/braintree_python | 34c36bddca7aa55512ee5129175eedcfc6d1fb30 | [
"MIT"
] | null | null | null | tests/unit/test_webhooks.py | sharma7n/braintree_python | 34c36bddca7aa55512ee5129175eedcfc6d1fb30 | [
"MIT"
] | null | null | null | tests/unit/test_webhooks.py | sharma7n/braintree_python | 34c36bddca7aa55512ee5129175eedcfc6d1fb30 | [
"MIT"
] | null | null | null | from tests.test_helper import *
from datetime import date
from braintree.dispute import Dispute
| 50.620178 | 145 | 0.743479 | from tests.test_helper import *
from datetime import date
from braintree.dispute import Dispute
class TestWebhooks(unittest.TestCase):
def test_sample_notification_builds_a_parsable_notification(self):
sample_notification = WebhookTesting.sample_notification(
WebhookNotification.Kind.SubscriptionWentPastDue,
"my_id"
)
notification = WebhookNotification.parse(sample_notification['bt_signature'], sample_notification['bt_payload'])
self.assertEqual(WebhookNotification.Kind.SubscriptionWentPastDue, notification.kind)
self.assertEqual("my_id", notification.subscription.id)
self.assertTrue((datetime.utcnow() - notification.timestamp).seconds < 10)
@raises(InvalidSignatureError)
def test_completely_invalid_signature(self):
sample_notification = WebhookTesting.sample_notification(
WebhookNotification.Kind.SubscriptionWentPastDue,
"my_id"
)
WebhookNotification.parse("bad_stuff", sample_notification['bt_payload'])
def test_parse_raises_when_public_key_is_wrong(self):
sample_notification = WebhookTesting.sample_notification(
WebhookNotification.Kind.SubscriptionWentPastDue,
"my_id"
)
config = Configuration(
environment=Environment.Development,
merchant_id="integration_merchant_id",
public_key="wrong_public_key",
private_key="wrong_private_key"
)
gateway = BraintreeGateway(config)
try:
gateway.webhook_notification.parse(sample_notification['bt_signature'], sample_notification['bt_payload'])
except InvalidSignatureError as e:
self.assertEqual("no matching public key", str(e))
else:
self.assertFalse("raises exception")
def test_invalid_signature_when_payload_modified(self):
sample_notification = WebhookTesting.sample_notification(
WebhookNotification.Kind.SubscriptionWentPastDue,
"my_id"
)
try:
WebhookNotification.parse(sample_notification['bt_signature'], b"badstuff" + sample_notification['bt_payload'])
except InvalidSignatureError as e:
self.assertEqual("signature does not match payload - one has been modified", str(e))
else:
self.assertFalse("raises exception")
def test_invalid_signature_when_contains_invalid_characters(self):
sample_notification = WebhookTesting.sample_notification(
WebhookNotification.Kind.SubscriptionWentPastDue,
"my_id"
)
try:
WebhookNotification.parse(sample_notification['bt_signature'], "~* invalid! *~")
except InvalidSignatureError as e:
self.assertEqual("payload contains illegal characters", str(e))
else:
self.assertFalse("raises exception")
def test_parse_allows_all_valid_characters(self):
sample_notification = WebhookTesting.sample_notification(
WebhookNotification.Kind.SubscriptionWentPastDue,
"my_id"
)
try:
WebhookNotification.parse(sample_notification['bt_signature'], "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789+=/\n")
except InvalidSignatureError as e:
self.assertNotEqual("payload contains illegal characters", str(e))
def test_parse_retries_payload_with_a_newline(self):
sample_notification = WebhookTesting.sample_notification(
WebhookNotification.Kind.SubscriptionWentPastDue,
"my_id"
)
notification = WebhookNotification.parse(sample_notification['bt_signature'], sample_notification['bt_payload'].rstrip())
self.assertEqual(WebhookNotification.Kind.SubscriptionWentPastDue, notification.kind)
self.assertEqual("my_id", notification.subscription.id)
self.assertTrue((datetime.utcnow() - notification.timestamp).seconds < 10)
def test_verify_returns_a_correct_challenge_response(self):
response = WebhookNotification.verify("20f9f8ed05f77439fe955c977e4c8a53")
self.assertEqual("integration_public_key|d9b899556c966b3f06945ec21311865d35df3ce4", response)
def test_verify_raises_when_challenge_is_invalid(self):
try:
WebhookNotification.verify("bad challenge")
except InvalidChallengeError as e:
self.assertEqual("challenge contains non-hex characters", str(e))
else:
self.assertFalse("raises exception")
def test_builds_notification_for_approved_sub_merchant_account(self):
sample_notification = WebhookTesting.sample_notification(
WebhookNotification.Kind.SubMerchantAccountApproved,
"my_id"
)
notification = WebhookNotification.parse(sample_notification['bt_signature'], sample_notification['bt_payload'])
self.assertEqual(WebhookNotification.Kind.SubMerchantAccountApproved, notification.kind)
self.assertEqual("my_id", notification.merchant_account.id)
self.assertEqual(MerchantAccount.Status.Active, notification.merchant_account.status)
self.assertEqual("master_ma_for_my_id", notification.merchant_account.master_merchant_account.id)
self.assertEqual(MerchantAccount.Status.Active, notification.merchant_account.master_merchant_account.status)
def test_builds_notification_for_declined_sub_merchant_account(self):
sample_notification = WebhookTesting.sample_notification(
WebhookNotification.Kind.SubMerchantAccountDeclined,
"my_id"
)
notification = WebhookNotification.parse(sample_notification['bt_signature'], sample_notification['bt_payload'])
self.assertEqual(WebhookNotification.Kind.SubMerchantAccountDeclined, notification.kind)
self.assertEqual("my_id", notification.merchant_account.id)
self.assertEqual(MerchantAccount.Status.Suspended, notification.merchant_account.status)
self.assertEqual("master_ma_for_my_id", notification.merchant_account.master_merchant_account.id)
self.assertEqual(MerchantAccount.Status.Suspended, notification.merchant_account.master_merchant_account.status)
self.assertEqual("Credit score is too low", notification.message)
self.assertEqual(ErrorCodes.MerchantAccount.DeclinedOFAC, notification.errors.for_object("merchant_account").on("base")[0].code)
def test_builds_notification_for_disbursed_transactions(self):
sample_notification = WebhookTesting.sample_notification(
WebhookNotification.Kind.TransactionDisbursed,
"my_id"
)
notification = WebhookNotification.parse(sample_notification['bt_signature'], sample_notification['bt_payload'])
self.assertEqual(WebhookNotification.Kind.TransactionDisbursed, notification.kind)
self.assertEqual("my_id", notification.transaction.id)
self.assertEqual(100, notification.transaction.amount)
self.assertEqual(datetime(2013, 7, 9, 18, 23, 29), notification.transaction.disbursement_details.disbursement_date)
def test_builds_notification_for_settled_transactions(self):
sample_notification = WebhookTesting.sample_notification(
WebhookNotification.Kind.TransactionSettled,
"my_id"
)
notification = WebhookNotification.parse(sample_notification['bt_signature'], sample_notification['bt_payload'])
self.assertEqual(WebhookNotification.Kind.TransactionSettled, notification.kind)
self.assertEqual("my_id", notification.transaction.id)
self.assertEqual("settled", notification.transaction.status)
self.assertEqual(100, notification.transaction.amount)
self.assertEqual(notification.transaction.us_bank_account.routing_number, "123456789")
self.assertEqual(notification.transaction.us_bank_account.last_4, "1234")
self.assertEqual(notification.transaction.us_bank_account.account_type, "checking")
self.assertEqual(notification.transaction.us_bank_account.account_holder_name, "Dan Schulman")
def test_builds_notification_for_settlement_declined_transactions(self):
sample_notification = WebhookTesting.sample_notification(
WebhookNotification.Kind.TransactionSettlementDeclined,
"my_id"
)
notification = WebhookNotification.parse(sample_notification['bt_signature'], sample_notification['bt_payload'])
self.assertEqual(WebhookNotification.Kind.TransactionSettlementDeclined, notification.kind)
self.assertEqual("my_id", notification.transaction.id)
self.assertEqual("settlement_declined", notification.transaction.status)
self.assertEqual(100, notification.transaction.amount)
self.assertEqual(notification.transaction.us_bank_account.routing_number, "123456789")
self.assertEqual(notification.transaction.us_bank_account.last_4, "1234")
self.assertEqual(notification.transaction.us_bank_account.account_type, "checking")
self.assertEqual(notification.transaction.us_bank_account.account_holder_name, "Dan Schulman")
def test_builds_notification_for_disbursements(self):
sample_notification = WebhookTesting.sample_notification(
WebhookNotification.Kind.Disbursement,
"my_id"
)
notification = WebhookNotification.parse(sample_notification['bt_signature'], sample_notification['bt_payload'])
self.assertEqual(WebhookNotification.Kind.Disbursement, notification.kind)
self.assertEqual("my_id", notification.disbursement.id)
self.assertEqual(100, notification.disbursement.amount)
self.assertEqual(None, notification.disbursement.exception_message)
self.assertEqual(None, notification.disbursement.follow_up_action)
self.assertEqual(date(2014, 2, 9), notification.disbursement.disbursement_date)
def test_builds_notification_for_disbursement_exceptions(self):
sample_notification = WebhookTesting.sample_notification(
WebhookNotification.Kind.DisbursementException,
"my_id"
)
notification = WebhookNotification.parse(sample_notification['bt_signature'], sample_notification['bt_payload'])
self.assertEqual(WebhookNotification.Kind.DisbursementException, notification.kind)
self.assertEqual("my_id", notification.disbursement.id)
self.assertEqual(100, notification.disbursement.amount)
self.assertEqual("bank_rejected", notification.disbursement.exception_message)
self.assertEqual("update_funding_information", notification.disbursement.follow_up_action)
self.assertEqual(date(2014, 2, 9), notification.disbursement.disbursement_date)
def test_builds_notification_for_dispute_opened(self):
sample_notification = WebhookTesting.sample_notification(
WebhookNotification.Kind.DisputeOpened,
"my_id"
)
notification = WebhookNotification.parse(sample_notification['bt_signature'], sample_notification['bt_payload'])
self.assertEqual(WebhookNotification.Kind.DisputeOpened, notification.kind)
self.assertEqual("my_id", notification.dispute.id)
self.assertEqual(Dispute.Status.Open, notification.dispute.status)
self.assertEqual(Dispute.Kind.Chargeback, notification.dispute.kind)
self.assertEqual(notification.dispute.date_opened, date(2014, 3, 28))
def test_builds_notification_for_dispute_lost(self):
sample_notification = WebhookTesting.sample_notification(
WebhookNotification.Kind.DisputeLost,
"my_id"
)
notification = WebhookNotification.parse(sample_notification['bt_signature'], sample_notification['bt_payload'])
self.assertEqual(WebhookNotification.Kind.DisputeLost, notification.kind)
self.assertEqual("my_id", notification.dispute.id)
self.assertEqual(Dispute.Status.Lost, notification.dispute.status)
self.assertEqual(Dispute.Kind.Chargeback, notification.dispute.kind)
self.assertEqual(notification.dispute.date_opened, date(2014, 3, 28))
def test_builds_notification_for_dispute_won(self):
sample_notification = WebhookTesting.sample_notification(
WebhookNotification.Kind.DisputeWon,
"my_id"
)
notification = WebhookNotification.parse(sample_notification['bt_signature'], sample_notification['bt_payload'])
self.assertEqual(WebhookNotification.Kind.DisputeWon, notification.kind)
self.assertEqual("my_id", notification.dispute.id)
self.assertEqual(Dispute.Status.Won, notification.dispute.status)
self.assertEqual(Dispute.Kind.Chargeback, notification.dispute.kind)
self.assertEqual(notification.dispute.date_opened, date(2014, 3, 28))
self.assertEqual(notification.dispute.date_won, date(2014, 9, 1))
def test_builds_notification_for_partner_merchant_connected(self):
sample_notification = WebhookTesting.sample_notification(
WebhookNotification.Kind.PartnerMerchantConnected,
"my_id"
)
notification = WebhookNotification.parse(sample_notification['bt_signature'], sample_notification['bt_payload'])
self.assertEqual(WebhookNotification.Kind.PartnerMerchantConnected, notification.kind)
self.assertEqual("abc123", notification.partner_merchant.partner_merchant_id)
self.assertEqual("public_key", notification.partner_merchant.public_key)
self.assertEqual("private_key", notification.partner_merchant.private_key)
self.assertEqual("public_id", notification.partner_merchant.merchant_public_id)
self.assertEqual("cse_key", notification.partner_merchant.client_side_encryption_key)
self.assertTrue((datetime.utcnow() - notification.timestamp).seconds < 10)
def test_builds_notification_for_partner_merchant_disconnected(self):
sample_notification = WebhookTesting.sample_notification(
WebhookNotification.Kind.PartnerMerchantDisconnected,
"my_id"
)
notification = WebhookNotification.parse(sample_notification['bt_signature'], sample_notification['bt_payload'])
self.assertEqual(WebhookNotification.Kind.PartnerMerchantDisconnected, notification.kind)
self.assertEqual("abc123", notification.partner_merchant.partner_merchant_id)
self.assertTrue((datetime.utcnow() - notification.timestamp).seconds < 10)
def test_builds_notification_for_partner_merchant_declined(self):
sample_notification = WebhookTesting.sample_notification(
WebhookNotification.Kind.PartnerMerchantDeclined,
"my_id"
)
notification = WebhookNotification.parse(sample_notification['bt_signature'], sample_notification['bt_payload'])
self.assertEqual(WebhookNotification.Kind.PartnerMerchantDeclined, notification.kind)
self.assertEqual("abc123", notification.partner_merchant.partner_merchant_id)
self.assertTrue((datetime.utcnow() - notification.timestamp).seconds < 10)
def test_builds_notification_for_subscription_charged_successfully(self):
sample_notification = WebhookTesting.sample_notification(
WebhookNotification.Kind.SubscriptionChargedSuccessfully,
"my_id"
)
notification = WebhookNotification.parse(sample_notification['bt_signature'], sample_notification['bt_payload'])
self.assertEqual(WebhookNotification.Kind.SubscriptionChargedSuccessfully, notification.kind)
self.assertEqual("my_id", notification.subscription.id)
self.assertTrue(len(notification.subscription.transactions) == 1)
transaction = notification.subscription.transactions.pop()
self.assertEqual("submitted_for_settlement", transaction.status)
self.assertEqual(Decimal("49.99"), transaction.amount)
def test_builds_notification_for_check(self):
sample_notification = WebhookTesting.sample_notification(
WebhookNotification.Kind.Check,
""
)
notification = WebhookNotification.parse(sample_notification['bt_signature'], sample_notification['bt_payload'])
self.assertEqual(WebhookNotification.Kind.Check, notification.kind)
def test_builds_notification_for_account_updater_daily_report_webhook(self):
sample_notification = WebhookTesting.sample_notification(
WebhookNotification.Kind.AccountUpdaterDailyReport,
"my_id"
)
notification = WebhookNotification.parse(sample_notification['bt_signature'], sample_notification['bt_payload'])
self.assertEqual(WebhookNotification.Kind.AccountUpdaterDailyReport, notification.kind)
self.assertEqual("link-to-csv-report", notification.account_updater_daily_report.report_url)
self.assertEqual(date(2016, 1, 14), notification.account_updater_daily_report.report_date)
| 16,214 | 726 | 23 |
cbb70d43a8d3ff65154e3094134aa202598e0698 | 520 | py | Python | chapter_1/update_db_classes.py | bimri/programming_python | ba52ccd18b9b4e6c5387bf4032f381ae816b5e77 | [
"MIT"
] | null | null | null | chapter_1/update_db_classes.py | bimri/programming_python | ba52ccd18b9b4e6c5387bf4032f381ae816b5e77 | [
"MIT"
] | null | null | null | chapter_1/update_db_classes.py | bimri/programming_python | ba52ccd18b9b4e6c5387bf4032f381ae816b5e77 | [
"MIT"
] | null | null | null | "Step 3: Stepping Up to OOP"
'Adding Persistence'
# Notice how we still fetch, update, and
# reassign to keys to update the shelve.
import shelve
db = shelve.open('class-shelve')
sue = db['sue']
sue.giveRaise(.25)
db['sue'] = sue
tom = db['tom']
tom.giveRaise(.20)
db['tom'] = tom
db.close()
'''
class instances allow us to combine both data and behavior for our
stored items. In a sense, instance attributes and class methods take the place of records
and processing programs in more traditional schemes.
'''
| 20 | 89 | 0.717308 | "Step 3: Stepping Up to OOP"
'Adding Persistence'
# Notice how we still fetch, update, and
# reassign to keys to update the shelve.
import shelve
db = shelve.open('class-shelve')
sue = db['sue']
sue.giveRaise(.25)
db['sue'] = sue
tom = db['tom']
tom.giveRaise(.20)
db['tom'] = tom
db.close()
'''
class instances allow us to combine both data and behavior for our
stored items. In a sense, instance attributes and class methods take the place of records
and processing programs in more traditional schemes.
'''
| 0 | 0 | 0 |
0a881db586e6a52a9d7f7a3a1b1799f27a90fb26 | 2,315 | py | Python | src/wat/read_annotations.py | luiscarlosgph/keypoint-annotation-tool | 390a328b5d0d02587a1d12784b7ef70363966036 | [
"MIT"
] | 6 | 2021-01-29T18:17:37.000Z | 2022-03-08T22:17:26.000Z | src/wat/read_annotations.py | luiscarlosgph/keypoint-annotation-tool | 390a328b5d0d02587a1d12784b7ef70363966036 | [
"MIT"
] | null | null | null | src/wat/read_annotations.py | luiscarlosgph/keypoint-annotation-tool | 390a328b5d0d02587a1d12784b7ef70363966036 | [
"MIT"
] | null | null | null | #!/usr/bin/python
#
# Exemplary script to read the annotations generated by the web application
# in this repo.
#
# @author: Luis Carlos Garcia-Peraza Herrera (luiscarlos.gph@gmail.com).
# @date : 20 Jan 2021.
import argparse
import json
import cv2
import numpy as np
import os
# My imports
import wat.common
def parse_cmdline_params():
"""
@brief Parse command line parameters to get input and output file names.
@param[in] argv Array of command line arguments.
@return input and output file names if they were specified.
"""
parser = argparse.ArgumentParser()
parser.add_argument('--dir', required=True, help='Path to the output directory.')
parser.add_argument('--gt-suffix', default='_seg', required=False,
help='Suffix of the segmentation-like annotations.')
args = parser.parse_args()
return args
if __name__ == "__main__":
main()
| 30.866667 | 85 | 0.67689 | #!/usr/bin/python
#
# Exemplary script to read the annotations generated by the web application
# in this repo.
#
# @author: Luis Carlos Garcia-Peraza Herrera (luiscarlos.gph@gmail.com).
# @date : 20 Jan 2021.
import argparse
import json
import cv2
import numpy as np
import os
# My imports
import wat.common
def parse_cmdline_params():
"""
@brief Parse command line parameters to get input and output file names.
@param[in] argv Array of command line arguments.
@return input and output file names if they were specified.
"""
parser = argparse.ArgumentParser()
parser.add_argument('--dir', required=True, help='Path to the output directory.')
parser.add_argument('--gt-suffix', default='_seg', required=False,
help='Suffix of the segmentation-like annotations.')
args = parser.parse_args()
return args
def valid_cmdline_params(args):
if not os.path.isdir(args.dir):
raise ValueError('[ERROR] The provided directory does not exist.')
def isimage(f):
return True if '.png' in f or '.jpg' in f else False
def main():
# Reading command line parameters
args = parse_cmdline_params()
valid_cmdline_params(args)
# List the annotated data
files = wat.common.listdir(args.dir, onlyfiles=True)
segmentations = [f for f in files if args.gt_suffix in f]
jsons = [f for f in files if '.json' in f]
images = [f for f in files if isimage(f) and f not in segmentations]
# Loop over the annotated images
print('Listing of the data found in the provided directory:')
for im_fname, json_fname, seg_fname in zip(images, jsons, segmentations):
print('Reading annotations for image:', im_fname)
# Read image
im_path = os.path.join(args.dir, im_fname)
im = cv2.imread(im_path, cv2.IMREAD_UNCHANGED)
# Read segmentation-like single-channel annotation
seg_path = os.path.join(args.dir, seg_fname)
seg = cv2.imread(seg_fname, cv2.IMREAD_UNCHANGED)
# Read JSON annotation
json_path = os.path.join(args.dir, json_fname)
with open(json_path) as json_file:
json_data = json.load(json_file)
# Do something with the annotation here!
print(json_data)
if __name__ == "__main__":
main()
| 1,341 | 0 | 69 |
85dc97c10a3b03dac2ae07effad2e7b455ad2038 | 2,802 | py | Python | loaner/web_app/backend/api/loaner_endpoints.py | McDiesel/loaner | dcf5fa640ee9059a814650fa4432fa1116df78e9 | [
"Apache-2.0"
] | null | null | null | loaner/web_app/backend/api/loaner_endpoints.py | McDiesel/loaner | dcf5fa640ee9059a814650fa4432fa1116df78e9 | [
"Apache-2.0"
] | null | null | null | loaner/web_app/backend/api/loaner_endpoints.py | McDiesel/loaner | dcf5fa640ee9059a814650fa4432fa1116df78e9 | [
"Apache-2.0"
] | null | null | null | # Copyright 2018 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.
"""Module to enforce authentication on endpoints.method.
Usage:
-----
# configuration of an endpoints method with enforced user auth check only.
@loaner_endpoints.authed_method(
chrome_message.ChromeRequest,
chrome_message.ChromeResponse,
name='heartbeat',
path='heartbeat',
http_method='GET',
user_auth_only=True)
def do_something(self, request):
...
The above method will execute if the current user is authenticated properly.
# configuration of an endpoints method with enforced permission.
@loaner_endpoints.authed_method(
chrome_message.ChromeRequest,
chrome_message.ChromeResponse,
name='heartbeat',
path='heartbeat',
http_method='GET',
permission='view')
def do_something(self, request):
...
The above method will only execute if the current user's role has the permission
"view".
Note:
-----
Please see permission module for more information on how the check_auth()
decorator works.
"""
import endpoints
from loaner.web_app.backend.auth import permissions
class Error(Exception):
"""Default error class for this module."""
class AuthCheckNotPresent(Error):
"""Raised when auth_method was called without auth check."""
def authed_method(*args, **kwargs):
"""Configures an endpoint method and enforces permissions."""
def auth_method_decorator(auth_function):
"""Decorator for auth_method."""
kwarg_auth = None
kwarg_permission = None
for key in kwargs:
if key is 'permission':
kwarg_permission = kwargs.pop('permission')
auth_function = permissions.check_auth(
permission=kwarg_permission)(auth_function)
break
elif key is 'user_auth_only':
kwarg_auth = kwargs.pop('user_auth_only')
auth_function = permissions.check_auth(
user_auth_only=kwarg_auth)(auth_function)
break
if not kwarg_auth and not kwarg_permission:
raise AuthCheckNotPresent(
'No permission or user_auth_only was passed. Authentication on this '
'method cannot run.')
# Always apply the standard `endpoints.method` decorator.
return endpoints.method(*args, **kwargs)(auth_function)
return auth_method_decorator
| 30.791209 | 80 | 0.729479 | # Copyright 2018 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.
"""Module to enforce authentication on endpoints.method.
Usage:
-----
# configuration of an endpoints method with enforced user auth check only.
@loaner_endpoints.authed_method(
chrome_message.ChromeRequest,
chrome_message.ChromeResponse,
name='heartbeat',
path='heartbeat',
http_method='GET',
user_auth_only=True)
def do_something(self, request):
...
The above method will execute if the current user is authenticated properly.
# configuration of an endpoints method with enforced permission.
@loaner_endpoints.authed_method(
chrome_message.ChromeRequest,
chrome_message.ChromeResponse,
name='heartbeat',
path='heartbeat',
http_method='GET',
permission='view')
def do_something(self, request):
...
The above method will only execute if the current user's role has the permission
"view".
Note:
-----
Please see permission module for more information on how the check_auth()
decorator works.
"""
import endpoints
from loaner.web_app.backend.auth import permissions
class Error(Exception):
"""Default error class for this module."""
class AuthCheckNotPresent(Error):
"""Raised when auth_method was called without auth check."""
def authed_method(*args, **kwargs):
"""Configures an endpoint method and enforces permissions."""
def auth_method_decorator(auth_function):
"""Decorator for auth_method."""
kwarg_auth = None
kwarg_permission = None
for key in kwargs:
if key is 'permission':
kwarg_permission = kwargs.pop('permission')
auth_function = permissions.check_auth(
permission=kwarg_permission)(auth_function)
break
elif key is 'user_auth_only':
kwarg_auth = kwargs.pop('user_auth_only')
auth_function = permissions.check_auth(
user_auth_only=kwarg_auth)(auth_function)
break
if not kwarg_auth and not kwarg_permission:
raise AuthCheckNotPresent(
'No permission or user_auth_only was passed. Authentication on this '
'method cannot run.')
# Always apply the standard `endpoints.method` decorator.
return endpoints.method(*args, **kwargs)(auth_function)
return auth_method_decorator
| 0 | 0 | 0 |
f7f108f68a198ca04eb13f738f69699895622019 | 4,088 | py | Python | DQM/SiPixelPhase1Track/python/SiPixelPhase1RecHits_cfi.py | nistefan/cmssw | ea13af97f7f2117a4f590a5e654e06ecd9825a5b | [
"Apache-2.0"
] | 1 | 2019-03-09T19:47:49.000Z | 2019-03-09T19:47:49.000Z | DQM/SiPixelPhase1Track/python/SiPixelPhase1RecHits_cfi.py | nistefan/cmssw | ea13af97f7f2117a4f590a5e654e06ecd9825a5b | [
"Apache-2.0"
] | null | null | null | DQM/SiPixelPhase1Track/python/SiPixelPhase1RecHits_cfi.py | nistefan/cmssw | ea13af97f7f2117a4f590a5e654e06ecd9825a5b | [
"Apache-2.0"
] | 1 | 2019-03-19T13:44:54.000Z | 2019-03-19T13:44:54.000Z | import FWCore.ParameterSet.Config as cms
from DQMServices.Core.DQMEDHarvester import DQMEDHarvester
from DQM.SiPixelPhase1Common.HistogramManager_cfi import *
import DQM.SiPixelPhase1Common.TriggerEventFlag_cfi as trigger
SiPixelPhase1RecHitsNRecHits = DefaultHistoTrack.clone(
name = "rechits",
title = "RecHits",
range_min = 0, range_max = 30, range_nbins = 30,
xlabel = "rechits",
dimensions = 0,
specs = VPSet(
StandardSpecificationTrend_Num,
Specification().groupBy("PXBarrel/Event")
.reduce("COUNT")
.groupBy("PXBarrel")
.save(nbins=100, xmin=0, xmax=5000),
Specification().groupBy("PXForward/Event")
.reduce("COUNT")
.groupBy("PXForward")
.save(nbins=100, xmin=0, xmax=5000),
Specification().groupBy("PXAll/Event")
.reduce("COUNT")
.groupBy("PXAll")
.save(nbins=100, xmin=0, xmax=5000)
)
)
SiPixelPhase1RecHitsClustX = DefaultHistoTrack.clone(
name = "clustersize_x",
title = "Cluster Size X (OnTrack)",
range_min = 0, range_max = 50, range_nbins = 50,
xlabel = "size[pixels]",
dimensions = 1,
specs = VPSet(
StandardSpecification2DProfile
)
)
SiPixelPhase1RecHitsClustY = SiPixelPhase1RecHitsClustX.clone(
name = "clustersize_y",
title = "Cluster Size Y (OnTrack)",
xlabel = "size[pixels]"
)
SiPixelPhase1RecHitsErrorX = DefaultHistoTrack.clone(
enabled=False,
name = "rechiterror_x",
title = "RecHit Error in X-direction",
range_min = 0, range_max = 0.02, range_nbins = 100,
xlabel = "X error",
dimensions = 1,
specs = VPSet(
StandardSpecification2DProfile
)
)
SiPixelPhase1RecHitsErrorY = SiPixelPhase1RecHitsErrorX.clone(
enabled=False,
name = "rechiterror_y",
title = "RecHit Error in Y-direction",
xlabel = "Y error"
)
SiPixelPhase1RecHitsPosition = DefaultHistoTrack.clone(
enabled = False,
name = "rechit_pos",
title = "Position of RecHits on Module",
range_min = -1, range_max = 1, range_nbins = 100,
range_y_min = -4, range_y_max = 4, range_y_nbins = 100,
xlabel = "x offset",
ylabel = "y offset",
dimensions = 2,
specs = VPSet(
Specification(PerModule).groupBy("PXBarrel/PXLayer/DetId").save(),
Specification(PerModule).groupBy("PXForward/PXDisk/DetId").save(),
)
)
SiPixelPhase1RecHitsProb = DefaultHistoTrack.clone(
name = "clusterprob",
title = "Cluster Probability",
xlabel = "log_10(Pr)",
range_min = -10, range_max = 1, range_nbins = 50,
dimensions = 1,
specs = VPSet(
Specification().groupBy("PXBarrel/PXLayer").saveAll(),
Specification().groupBy("PXForward/PXDisk").saveAll(),
StandardSpecification2DProfile,
Specification().groupBy("PXBarrel/LumiBlock")
.reduce("MEAN")
.groupBy("PXBarrel", "EXTEND_X")
.save(),
Specification().groupBy("PXForward/LumiBlock")
.reduce("MEAN")
.groupBy("PXForward", "EXTEND_X")
.save(),
Specification(PerLayer1D).groupBy("PXBarrel/Shell/PXLayer").save(),
Specification(PerLayer1D).groupBy("PXForward/HalfCylinder/PXRing/PXDisk").save()
)
)
SiPixelPhase1RecHitsConf = cms.VPSet(
SiPixelPhase1RecHitsNRecHits,
SiPixelPhase1RecHitsClustX,
SiPixelPhase1RecHitsClustY,
SiPixelPhase1RecHitsErrorX,
SiPixelPhase1RecHitsErrorY,
SiPixelPhase1RecHitsPosition,
SiPixelPhase1RecHitsProb,
)
from DQMServices.Core.DQMEDAnalyzer import DQMEDAnalyzer
SiPixelPhase1RecHitsAnalyzer = DQMEDAnalyzer('SiPixelPhase1RecHits',
src = cms.InputTag("generalTracks"),
histograms = SiPixelPhase1RecHitsConf,
geometry = SiPixelPhase1Geometry,
onlyValidHits = cms.bool(False),
triggerflags = trigger.SiPixelPhase1Triggers
)
SiPixelPhase1RecHitsHarvester = DQMEDHarvester("SiPixelPhase1Harvester",
histograms = SiPixelPhase1RecHitsConf,
geometry = SiPixelPhase1Geometry
)
| 30.281481 | 88 | 0.668297 | import FWCore.ParameterSet.Config as cms
from DQMServices.Core.DQMEDHarvester import DQMEDHarvester
from DQM.SiPixelPhase1Common.HistogramManager_cfi import *
import DQM.SiPixelPhase1Common.TriggerEventFlag_cfi as trigger
SiPixelPhase1RecHitsNRecHits = DefaultHistoTrack.clone(
name = "rechits",
title = "RecHits",
range_min = 0, range_max = 30, range_nbins = 30,
xlabel = "rechits",
dimensions = 0,
specs = VPSet(
StandardSpecificationTrend_Num,
Specification().groupBy("PXBarrel/Event")
.reduce("COUNT")
.groupBy("PXBarrel")
.save(nbins=100, xmin=0, xmax=5000),
Specification().groupBy("PXForward/Event")
.reduce("COUNT")
.groupBy("PXForward")
.save(nbins=100, xmin=0, xmax=5000),
Specification().groupBy("PXAll/Event")
.reduce("COUNT")
.groupBy("PXAll")
.save(nbins=100, xmin=0, xmax=5000)
)
)
SiPixelPhase1RecHitsClustX = DefaultHistoTrack.clone(
name = "clustersize_x",
title = "Cluster Size X (OnTrack)",
range_min = 0, range_max = 50, range_nbins = 50,
xlabel = "size[pixels]",
dimensions = 1,
specs = VPSet(
StandardSpecification2DProfile
)
)
SiPixelPhase1RecHitsClustY = SiPixelPhase1RecHitsClustX.clone(
name = "clustersize_y",
title = "Cluster Size Y (OnTrack)",
xlabel = "size[pixels]"
)
SiPixelPhase1RecHitsErrorX = DefaultHistoTrack.clone(
enabled=False,
name = "rechiterror_x",
title = "RecHit Error in X-direction",
range_min = 0, range_max = 0.02, range_nbins = 100,
xlabel = "X error",
dimensions = 1,
specs = VPSet(
StandardSpecification2DProfile
)
)
SiPixelPhase1RecHitsErrorY = SiPixelPhase1RecHitsErrorX.clone(
enabled=False,
name = "rechiterror_y",
title = "RecHit Error in Y-direction",
xlabel = "Y error"
)
SiPixelPhase1RecHitsPosition = DefaultHistoTrack.clone(
enabled = False,
name = "rechit_pos",
title = "Position of RecHits on Module",
range_min = -1, range_max = 1, range_nbins = 100,
range_y_min = -4, range_y_max = 4, range_y_nbins = 100,
xlabel = "x offset",
ylabel = "y offset",
dimensions = 2,
specs = VPSet(
Specification(PerModule).groupBy("PXBarrel/PXLayer/DetId").save(),
Specification(PerModule).groupBy("PXForward/PXDisk/DetId").save(),
)
)
SiPixelPhase1RecHitsProb = DefaultHistoTrack.clone(
name = "clusterprob",
title = "Cluster Probability",
xlabel = "log_10(Pr)",
range_min = -10, range_max = 1, range_nbins = 50,
dimensions = 1,
specs = VPSet(
Specification().groupBy("PXBarrel/PXLayer").saveAll(),
Specification().groupBy("PXForward/PXDisk").saveAll(),
StandardSpecification2DProfile,
Specification().groupBy("PXBarrel/LumiBlock")
.reduce("MEAN")
.groupBy("PXBarrel", "EXTEND_X")
.save(),
Specification().groupBy("PXForward/LumiBlock")
.reduce("MEAN")
.groupBy("PXForward", "EXTEND_X")
.save(),
Specification(PerLayer1D).groupBy("PXBarrel/Shell/PXLayer").save(),
Specification(PerLayer1D).groupBy("PXForward/HalfCylinder/PXRing/PXDisk").save()
)
)
SiPixelPhase1RecHitsConf = cms.VPSet(
SiPixelPhase1RecHitsNRecHits,
SiPixelPhase1RecHitsClustX,
SiPixelPhase1RecHitsClustY,
SiPixelPhase1RecHitsErrorX,
SiPixelPhase1RecHitsErrorY,
SiPixelPhase1RecHitsPosition,
SiPixelPhase1RecHitsProb,
)
from DQMServices.Core.DQMEDAnalyzer import DQMEDAnalyzer
SiPixelPhase1RecHitsAnalyzer = DQMEDAnalyzer('SiPixelPhase1RecHits',
src = cms.InputTag("generalTracks"),
histograms = SiPixelPhase1RecHitsConf,
geometry = SiPixelPhase1Geometry,
onlyValidHits = cms.bool(False),
triggerflags = trigger.SiPixelPhase1Triggers
)
SiPixelPhase1RecHitsHarvester = DQMEDHarvester("SiPixelPhase1Harvester",
histograms = SiPixelPhase1RecHitsConf,
geometry = SiPixelPhase1Geometry
)
| 0 | 0 | 0 |
632451821cd68317df541d0fbb2c8499a34ac64b | 1,624 | py | Python | add_doi_minting_date.py | caltechlibrary/caltechdata_api | 69a986642942379a12fac64cbba4c08c4ae29cc3 | [
"BSD-3-Clause"
] | 7 | 2018-03-07T17:24:22.000Z | 2022-02-01T20:01:30.000Z | add_doi_minting_date.py | caltechlibrary/caltechdata_api | 69a986642942379a12fac64cbba4c08c4ae29cc3 | [
"BSD-3-Clause"
] | 7 | 2018-05-18T23:49:17.000Z | 2021-07-22T23:40:26.000Z | add_doi_minting_date.py | caltechlibrary/caltechdata_api | 69a986642942379a12fac64cbba4c08c4ae29cc3 | [
"BSD-3-Clause"
] | null | null | null | import os, requests
from progressbar import progressbar
from caltechdata_api import get_metadata, caltechdata_edit
def get_datacite_dates(prefix):
"""Get sumbitted date for DataCite DOIs with specific prefix"""
doi_dates = {}
doi_urls = {}
url = (
"https://api.datacite.org/dois?query=prefix:"
+ prefix
+ "&page[cursor]=1&page[size]=500"
)
next_link = url
meta = requests.get(next_link).json()["meta"]
for j in progressbar(range(meta["totalPages"])):
r = requests.get(next_link)
data = r.json()
for doi in data["data"]:
date = doi["attributes"]["registered"].split("T")[0]
doi_dates[doi["id"]] = date
doi_urls[doi["id"]] = doi["attributes"]["url"]
if "next" in data["links"]:
next_link = data["links"]["next"]
else:
next_link = None
return doi_dates, doi_urls
token = os.environ["TINDTOK"]
doi_dates, doi_urls = get_datacite_dates("10.14291")
for doi in doi_urls:
if "data.caltech.edu" in doi_urls[doi]:
caltech_id = doi_urls[doi].split("/")[-1]
if caltech_id not in ["252", "253", "254", "255"]:
metadata = get_metadata(caltech_id, emails=True)
print(caltech_id)
# print(metadata['dates'])
for date in metadata["dates"]:
if date["dateType"] == "Issued":
print(date["date"], doi_dates[doi])
date["date"] = doi_dates[doi]
response = caltechdata_edit(token, caltech_id, metadata, production=True)
print(response)
| 34.553191 | 85 | 0.580665 | import os, requests
from progressbar import progressbar
from caltechdata_api import get_metadata, caltechdata_edit
def get_datacite_dates(prefix):
"""Get sumbitted date for DataCite DOIs with specific prefix"""
doi_dates = {}
doi_urls = {}
url = (
"https://api.datacite.org/dois?query=prefix:"
+ prefix
+ "&page[cursor]=1&page[size]=500"
)
next_link = url
meta = requests.get(next_link).json()["meta"]
for j in progressbar(range(meta["totalPages"])):
r = requests.get(next_link)
data = r.json()
for doi in data["data"]:
date = doi["attributes"]["registered"].split("T")[0]
doi_dates[doi["id"]] = date
doi_urls[doi["id"]] = doi["attributes"]["url"]
if "next" in data["links"]:
next_link = data["links"]["next"]
else:
next_link = None
return doi_dates, doi_urls
token = os.environ["TINDTOK"]
doi_dates, doi_urls = get_datacite_dates("10.14291")
for doi in doi_urls:
if "data.caltech.edu" in doi_urls[doi]:
caltech_id = doi_urls[doi].split("/")[-1]
if caltech_id not in ["252", "253", "254", "255"]:
metadata = get_metadata(caltech_id, emails=True)
print(caltech_id)
# print(metadata['dates'])
for date in metadata["dates"]:
if date["dateType"] == "Issued":
print(date["date"], doi_dates[doi])
date["date"] = doi_dates[doi]
response = caltechdata_edit(token, caltech_id, metadata, production=True)
print(response)
| 0 | 0 | 0 |
66f88e14c1a7455191b654ac531447a4e5aaf53c | 2,217 | py | Python | tests/behave/test_positive.py | valentinDruzhinin/CategoryMappingApp | 8d9bd64d0284c0024a851592e9e9d2bc06606557 | [
"MIT"
] | null | null | null | tests/behave/test_positive.py | valentinDruzhinin/CategoryMappingApp | 8d9bd64d0284c0024a851592e9e9d2bc06606557 | [
"MIT"
] | null | null | null | tests/behave/test_positive.py | valentinDruzhinin/CategoryMappingApp | 8d9bd64d0284c0024a851592e9e9d2bc06606557 | [
"MIT"
] | null | null | null | import json
from app import Category
| 27.37037 | 70 | 0.583672 | import json
from app import Category
def test_user_behaviour(client):
mock_category = Category(name='Men', mapping='Men clothes')
# categories endpoint
categories_url = '/categories'
response = client.get(categories_url)
assert '200 OK' == response.status
assert [] == response.json
response = client.post(
categories_url,
data=json.dumps({
'name': mock_category.name,
'mapping': mock_category.mapping
}),
content_type='application/json'
)
assert '200 OK' == response.status
assert 'id' in response.json
# category endpoint
category_url = f'{categories_url}/{response.json["id"]}'
response = client.get(category_url)
assert '200 OK' == response.status
assert mock_category.name == response.json['name']
assert mock_category.mapping == response.json['mapping']
response = client.put(
category_url,
data=json.dumps({
'name': 'test_name',
'mapping': 'test_mapping'
}),
content_type='application/json'
)
assert '204 NO CONTENT' == response.status
response = client.get(category_url)
assert '200 OK' == response.status
assert 'test_name' == response.json['name']
assert 'test_mapping' == response.json['mapping']
response = client.delete(category_url)
assert '204 NO CONTENT' == response.status
response = client.get(categories_url)
assert '200 OK' == response.status
assert [] == response.json
# batch processing
response = client.post(
categories_url,
data=json.dumps([
{
'name': 'Name1',
'mapping': 'Mapping1'
},
{
'name': 'Name2',
'mapping': 'Mapping2'
},
{
'name': 'Name3',
'mapping': 'Mapping3'
}
]),
content_type='application/json'
)
assert '202 ACCEPTED' == response.status
assert 'process_id' in response.json
response = client.get(f'/processes/{response.json["process_id"]}')
assert '200 OK' == response.status
assert 'state' in response.json
| 2,156 | 0 | 23 |
80440041b109c31bfaff3f15a0eeac9320c0e9ea | 457 | py | Python | lecture_02/114_transformation_between_frames.py | farzanehesk/COMPAS-II-FS2022 | 857eb40000f0532d0c04689331eadefd38dce6b7 | [
"MIT"
] | 11 | 2022-01-24T15:07:15.000Z | 2022-03-29T12:58:05.000Z | lecture_02/114_transformation_between_frames.py | farzanehesk/COMPAS-II-FS2022 | 857eb40000f0532d0c04689331eadefd38dce6b7 | [
"MIT"
] | 4 | 2022-03-16T06:06:45.000Z | 2022-03-29T22:59:11.000Z | lecture_02/114_transformation_between_frames.py | farzanehesk/COMPAS-II-FS2022 | 857eb40000f0532d0c04689331eadefd38dce6b7 | [
"MIT"
] | 20 | 2022-03-02T10:36:41.000Z | 2022-03-09T00:12:33.000Z | """Transformation between two frames.
"""
from compas.geometry import Frame
from compas.geometry import Point
from compas.geometry import Transformation
F1 = Frame.worldXY()
F2 = Frame([1.5, 1, 0], [0.68, 0.68, 0.27], [-0.67, 0.73, -0.15])
P = Point(2, 2, 2) # local point in F1
# transformation between 2 frames F1, F2
T = Transformation.from_frame_to_frame(F1, F2)
# Transform geometry (=point P) into another coordinate frame
print(P.transformed(T))
| 28.5625 | 65 | 0.719912 | """Transformation between two frames.
"""
from compas.geometry import Frame
from compas.geometry import Point
from compas.geometry import Transformation
F1 = Frame.worldXY()
F2 = Frame([1.5, 1, 0], [0.68, 0.68, 0.27], [-0.67, 0.73, -0.15])
P = Point(2, 2, 2) # local point in F1
# transformation between 2 frames F1, F2
T = Transformation.from_frame_to_frame(F1, F2)
# Transform geometry (=point P) into another coordinate frame
print(P.transformed(T))
| 0 | 0 | 0 |
d741996533bed2e2caf9549d319c0dd2a1c3bfb2 | 1,201 | py | Python | Firewall/sttsotpt.py | d4rkl0rd3r3b05/Firewall | 1721d19846e4dbb98f5ac38ff3722b6f6fd17afc | [
"MIT"
] | 2 | 2015-05-12T22:11:19.000Z | 2019-04-02T01:36:03.000Z | Firewall/sttsotpt.py | d4rkl0rd3r3b05/Firewall | 1721d19846e4dbb98f5ac38ff3722b6f6fd17afc | [
"MIT"
] | 1 | 2021-08-10T06:59:53.000Z | 2021-08-10T06:59:53.000Z | Firewall/sttsotpt.py | d4rkl0rd3r3b05/Firewall | 1721d19846e4dbb98f5ac38ff3722b6f6fd17afc | [
"MIT"
] | 3 | 2015-08-18T08:45:02.000Z | 2021-08-10T07:00:18.000Z | import os
| 27.930233 | 100 | 0.586178 | import os
def prtcl():
result=os.popen('netstat -anut |grep -iv "active" |grep -iv "proto"|awk \'{print $1}\'',"r").read()
return result
def src():
result=os.popen(' netstat -anut |grep -iv "active" |grep -iv "proto"\
| awk \'{print $4}\' | cut -d: -f1 | sed -e \'/^$/d\'',"r").read()
return result
def srcpt():
result=os.popen('netstat -anut |grep -iv "active" |grep -iv "proto"|awk \'{print $4}\'\
|awk \'BEGIN {FS=":"};{print $NF}\'',"r").read()
return result
def des():
result=os.popen(' netstat -anut |grep -iv "active" |grep -iv "proto"\
| awk \'{print $5}\' | cut -d: -f1 | sed -e \'/^$/d\'',"r").read()
return result
def despt():
result=os.popen('netstat -anut |grep -iv "active" |grep -iv "proto"|awk \'{print $5}\'\
|awk \'BEGIN {FS=":"};{print $NF}\'',"r").read()
return result
def recv():
result=os.popen('netstat -anut |grep -iv "active" |grep -iv "proto"|awk \'{print $2}\'',"r").read()
return result
def send():
result=os.popen('netstat -anut |grep -iv "active" |grep -iv "proto"|awk \'{print $3}\'',"r").read()
return result
def stt():
result=os.popen('netstat -anut |grep -iv "active" |grep -iv "proto"|awk \'{print $6}\'',"r").read()
return result
| 1,000 | 0 | 186 |
f37916b8764d66a84758a1a7bc5c2d1b6e728743 | 6,168 | py | Python | mmdet/models/detectors/siamese_rpn_v2.py | ArthurWish/mmdetection | bd4c5b04e9d880f7a38131f17d3b43e4a3630c4f | [
"Apache-2.0"
] | null | null | null | mmdet/models/detectors/siamese_rpn_v2.py | ArthurWish/mmdetection | bd4c5b04e9d880f7a38131f17d3b43e4a3630c4f | [
"Apache-2.0"
] | null | null | null | mmdet/models/detectors/siamese_rpn_v2.py | ArthurWish/mmdetection | bd4c5b04e9d880f7a38131f17d3b43e4a3630c4f | [
"Apache-2.0"
] | null | null | null | import torch
from torch import nn
from torchvision import transforms
from .faster_rcnn import FasterRCNN
from ..builder import DETECTORS
from PIL import Image
import numpy as np
@DETECTORS.register_module()
| 39.037975 | 148 | 0.530318 | import torch
from torch import nn
from torchvision import transforms
from .faster_rcnn import FasterRCNN
from ..builder import DETECTORS
from PIL import Image
import numpy as np
@DETECTORS.register_module()
class SiameseRPNV2(FasterRCNN):
def __init__(self,
backbone,
rpn_head,
roi_head,
train_cfg,
test_cfg,
neck=None,
pretrained=None,
init_cfg=None,
sub_images=()):
super(SiameseRPNV2, self).__init__(
backbone=backbone,
neck=neck,
rpn_head=rpn_head,
roi_head=roi_head,
train_cfg=train_cfg,
test_cfg=test_cfg,
pretrained=pretrained,
init_cfg=init_cfg)
self.sub_images = sub_images
def extract_feat(self, imgs):
assert len(imgs) == len(self.sub_images)
# feature_list = []
# img = torch.cat([img[0], img[1]], dim=1)
# img = imgs[0].detach().cpu().numpy()
# im = np.squeeze(img, axis=0).transpose(1,2,0)
# im = Image.fromarray(im, 'RGB')
# im.save("xxresult.png")
out = self.backbone(imgs)
# for input_img in img:
# feature = self.backbone(input_img)
# # List[list[tensor,tensor,tensor,tensor], list[tensor,tensor,tensor,tensor]]
# feature_list.append(feature)
# feature_concat = tuple(torch.cat(x, dim=1) for x in zip(*feature_list))
# # print(len(img))
# out = [
# nn.Sequential(
# nn.Conv2d(feature_concat_channel.size(1), int(
# feature_concat_channel.size(1) / len(img)), kernel_size=1),
# nn.BatchNorm2d(int(feature_concat_channel.size(1) / len(img))),
# nn.ReLU()
# ).cuda()(feature_concat_channel)
# for feature_concat_channel in feature_concat
# ] if len(img) > 1 else feature_concat
if self.with_neck:
out = self.neck(out)
return out
def forward_dummy(self, imgs):
outs = ()
# backbone
x = self.extract_feat(imgs)
# rpn
if self.with_rpn:
rpn_outs = self.rpn_head(x)
outs = outs + (rpn_outs, )
proposals = torch.randn(1000, 4).to(imgs[0].device)
# roi_head
roi_outs = self.roi_head.forward_dummy(x, proposals)
outs = outs + (roi_outs, )
return outs
def forward_train(self,
imgs,
img_metas,
gt_bboxes,
gt_labels,
gt_bboxes_ignore=None,
gt_masks=None,
proposals=None,
**kwargs):
x = self.extract_feat(imgs)
losses = dict()
# RPN forward and loss
if self.with_rpn:
proposal_cfg = self.train_cfg.get('rpn_proposal',
self.test_cfg.rpn)
rpn_losses, proposal_list = self.rpn_head.forward_train(
x,
img_metas,
gt_bboxes,
gt_labels=None,
gt_bboxes_ignore=gt_bboxes_ignore,
proposal_cfg=proposal_cfg)
losses.update(rpn_losses)
else:
proposal_list = proposals
roi_losses = self.roi_head.forward_train(x, img_metas, proposal_list,
gt_bboxes, gt_labels,
gt_bboxes_ignore, gt_masks,
**kwargs)
losses.update(roi_losses)
return losses
def forward_test(self, imgs_list, img_metas, **kwargs):
for var, name in [(imgs_list, 'imgs_list'), (img_metas, 'img_metas')]:
if not isinstance(var, list):
raise TypeError(f'{name} must be a list, but got {type(var)}')
num_augs = len(imgs_list)
if num_augs != len(img_metas):
raise ValueError(f'num of augmentations ({len(imgs_list)}) '
f'!= num of image meta ({len(img_metas)})')
for imgs, img_meta in zip(imgs_list, img_metas):
batch_size = len(img_meta)
for img_id in range(batch_size):
img_meta[img_id]['batch_input_shape'] = tuple(
imgs[0].size()[-2:])
if num_augs == 1:
# proposals (List[List[Tensor]]): the outer list indicates
# test-time augs (multiscale, flip, etc.) and the inner list
# indicates images in a batch.
# The Tensor should have a shape Px4, where P is the number of
# proposals.
if 'proposals' in kwargs:
kwargs['proposals'] = kwargs['proposals'][0]
return self.simple_test(imgs_list[0], img_metas[0], **kwargs)
else:
assert imgs_list[0][0].size(0) == 1, 'aug test does not support ' \
'inference with batch size ' \
f'{imgs_list[0][0].size(0)}'
# TODO: support test augmentation for predefined proposals
assert 'proposals' not in kwargs
return self.aug_test(imgs_list, img_metas, **kwargs)
def onnx_export(self, imgs, img_metas):
img_shape = torch._shape_as_tensor(imgs[0])[2:]
img_metas[0]['img_shape_for_onnx'] = img_shape
x = self.extract_feat(imgs)
proposals = self.rpn_head.onnx_export(x, img_metas)
if hasattr(self.roi_head, 'onnx_export'):
return self.roi_head.onnx_export(x, proposals, img_metas)
else:
raise NotImplementedError(
f'{self.__class__.__name__} can not '
f'be exported to ONNX. Please refer to the '
f'list of supported models,'
f'https://mmdetection.readthedocs.io/en/latest/tutorials/pytorch2onnx.html#list-of-supported-models-exportable-to-onnx' # noqa E501
)
| 5,763 | 10 | 187 |
6885620e6742d218394dec3d59818cd86ca65791 | 641 | py | Python | instaapp/urls.py | Michellemukami/insta-clone | 423aa3d2aacac82372a611f8f51ba487889a2f9d | [
"MIT"
] | null | null | null | instaapp/urls.py | Michellemukami/insta-clone | 423aa3d2aacac82372a611f8f51ba487889a2f9d | [
"MIT"
] | 4 | 2020-06-05T22:37:15.000Z | 2021-09-08T01:15:10.000Z | instaapp/urls.py | Michellemukami/insta-clone | 423aa3d2aacac82372a611f8f51ba487889a2f9d | [
"MIT"
] | null | null | null | from django.conf.urls import url
from . import views
from django.conf import settings
from django.conf.urls.static import static
urlpatterns=[
url('^$',views.login_page,name = 'come'),
url(r'^new/profile$', views.profile, name='profile'),
url(r'^user/', views.user, name='user'),
url(r'^search/', views.search_results, name='search_results'),
url(r'^new/article$', views.new_article, name='new-article'),
url(r'^home/', views.home, name='home'),
url(r'^comment/', views.comment, name='comment'),
]
if settings.DEBUG:
urlpatterns+= static(settings.MEDIA_URL, document_root = settings.MEDIA_ROOT)
| 30.52381 | 81 | 0.678627 | from django.conf.urls import url
from . import views
from django.conf import settings
from django.conf.urls.static import static
urlpatterns=[
url('^$',views.login_page,name = 'come'),
url(r'^new/profile$', views.profile, name='profile'),
url(r'^user/', views.user, name='user'),
url(r'^search/', views.search_results, name='search_results'),
url(r'^new/article$', views.new_article, name='new-article'),
url(r'^home/', views.home, name='home'),
url(r'^comment/', views.comment, name='comment'),
]
if settings.DEBUG:
urlpatterns+= static(settings.MEDIA_URL, document_root = settings.MEDIA_ROOT)
| 0 | 0 | 0 |
5c78fbb9c800452caf6342bc4bd90b168a90e6ef | 19,090 | py | Python | autonomous_exploration/autonomous_exploration/autonomousExploration.py | antonikaras/thesis_ros2 | 36673cd8a4161b1cf4045e8bdda36275a2a337ce | [
"BSD-2-Clause"
] | 1 | 2021-06-27T02:01:22.000Z | 2021-06-27T02:01:22.000Z | autonomous_exploration/autonomous_exploration/autonomousExploration.py | antonikaras/thesis_ros2 | 36673cd8a4161b1cf4045e8bdda36275a2a337ce | [
"BSD-2-Clause"
] | 1 | 2021-09-30T01:56:04.000Z | 2021-09-30T10:26:13.000Z | autonomous_exploration/autonomous_exploration/autonomousExploration.py | antonikaras/thesis_ros2 | 36673cd8a4161b1cf4045e8bdda36275a2a337ce | [
"BSD-2-Clause"
] | 1 | 2021-09-30T01:52:28.000Z | 2021-09-30T01:52:28.000Z | # Import ROS2 libraries
import rclpy
from rclpy.node import Node
from rclpy.action import ActionClient, ActionServer, GoalResponse, CancelResponse
from rclpy.qos import QoSProfile
from rclpy.callback_groups import ReentrantCallbackGroup
from rclpy.executors import MultiThreadedExecutor
# Import message files
from geometry_msgs.msg import PoseStamped
from nav_msgs.msg import OccupancyGrid as OccG
from nav_msgs.msg import Odometry
from nav2_msgs.action import NavigateToPose
from tf2_msgs.msg import TFMessage
from autonomous_exploration_msgs.msg import ExplorationTargets, ExplorationTarget, PosData
from autonomous_exploration_msgs.action import AutonomousExplorationAction
# Import other libraries
import numpy as np
import time
###################################################################################################
if __name__ == '__main__':
main() | 40.274262 | 195 | 0.582556 | # Import ROS2 libraries
import rclpy
from rclpy.node import Node
from rclpy.action import ActionClient, ActionServer, GoalResponse, CancelResponse
from rclpy.qos import QoSProfile
from rclpy.callback_groups import ReentrantCallbackGroup
from rclpy.executors import MultiThreadedExecutor
# Import message files
from geometry_msgs.msg import PoseStamped
from nav_msgs.msg import OccupancyGrid as OccG
from nav_msgs.msg import Odometry
from nav2_msgs.action import NavigateToPose
from tf2_msgs.msg import TFMessage
from autonomous_exploration_msgs.msg import ExplorationTargets, ExplorationTarget, PosData
from autonomous_exploration_msgs.action import AutonomousExplorationAction
# Import other libraries
import numpy as np
import time
class AutonomousExploration(Node):
def __init__(self):
super().__init__('autonomous_exploration')
# Range of the lidar
self.LidarRange = 3.5
# Create callback group
## Topic callback group
self.top_callback_group = ReentrantCallbackGroup()
## Action callback group
self.act_callback_group = ReentrantCallbackGroup()
## Timer callback group
self.timer_callback_group = ReentrantCallbackGroup()
## Publisher callback group
self.pub_callback_group = ReentrantCallbackGroup()
# Initialize the variables
self.VFCandidates_near = []
self.VFCandidates_center = []
self.VFCandidates_far = []
self.exploredTargets = []
self.mapOdomOffset = []
self.pos = np.array([0.0, 0.0])
self.curTar = []
self.curTarScore = 0.0
self.newTarScore = 0.0
self.newTar = []
self.goal_sent = 0
self.remaining_distance = 0.0
self.recovery_attempts = 0
self.stopThread = False
self.mapUpdated = False
qos = QoSProfile(depth=10)
# Setup rate
self.rate = self.create_rate(2)
# Create the navigation2 action client
self.nav2_action_Client = ActionClient(self, NavigateToPose, 'navigate_to_pose')
self.nav2_action_Client.wait_for_server()
# Setup subscribers
## /vision_based_frontier_detection/exploration_candidates
self.create_subscription(ExplorationTargets, '/vision_based_frontier_detection/exploration_candidates', self._explorationCandidatesVFCallback, qos, callback_group=self.top_callback_group)
## /odom
self.create_subscription(Odometry, 'odom', self._odomCallback, qos, callback_group=self.top_callback_group)
## /tf
self.create_subscription(TFMessage, 'tf', self._tfCallback, qos, callback_group=self.top_callback_group)
## /map
self.create_subscription(OccG, 'map', self._mapCallback, qos)
# Setup publishers
## /rosbridge_msgs_publisher/current_target
self.curTar_pub = self.create_publisher(PosData, '/rosbridge_msgs_publisher/current_target', qos, callback_group=self.pub_callback_group)
# Create the action server
self.auto_explore_action_server = ActionServer(self, AutonomousExplorationAction, 'autonomous_exploration',
execute_callback = self._aeActionCallback,
callback_group=self.act_callback_group,
cancel_callback = self._aeCancelCallback)
# goal_callback = self._aeGoalCallback,
# Publish the exploration target
self.create_timer(1.0, self.pubExplorationTarget, callback_group=self.timer_callback_group) # unit: s
self.get_logger().info('Autonomous explorer was initiated successfully')
def pubExplorationTarget(self) -> None:
curTar = PosData()
if len(self.curTar) > 0:
curTar.x = float(self.curTar[0])
curTar.y = float(self.curTar[1])
curTar.yaw = float(1)
else:
curTar.yaw = float(-1)
self.curTar_pub.publish(curTar)
def _mapCallback(self, data:OccG):
if len(self.curTar) == 0:
return
# Convert the current target to map coordinates
x = int((self.curTar[1] - data.info.origin.position.x) / data.info.resolution)
y = int((self.curTar[0] - data.info.origin.position.y) / data.info.resolution)
# Convert the map from 1D to 2D
map = np.array(data.data).reshape((data.info.height, data.info.width)).T
# Compute the undiscovered area surrounding the target
step = int(self.LidarRange / data.info.resolution)
areaOfInterest = map[x - step: x + step, y - step: y + step].copy()
area = float(np.count_nonzero((areaOfInterest == -1)))
w, h = areaOfInterest.shape
areaNormalized = area / float(w * h + 0.0001)
dist = np.linalg.norm(self.curTar - self.pos)
self.curTarScore = self.EvaluatePoint([dist, areaNormalized])
self.mapUpdated = True
def _tfCallback(self, data:TFMessage):
''' Read the tf data and find the transformation between odom and map '''
for tr in data.transforms:
if tr.header.frame_id == 'map' and tr.child_frame_id == 'odom':
if (len(self.mapOdomOffset) == 0):
self.mapOdomOffset = [0.0] * 2
self.mapOdomOffset[0] = tr.transform.translation.x
self.mapOdomOffset[1] = tr.transform.translation.y
def _odomCallback(self, msg:Odometry):
# Don't publish the map in case the initial pose is not published
if (len(self.mapOdomOffset) == 0):
return
pos = msg.pose.pose.position
self.pos[0:2] = [pos.x + self.mapOdomOffset[0], pos.y + self.mapOdomOffset[1]]
def _explorationCandidatesVFCallback(self, data:ExplorationTargets):
''' Read the exploration candidates detected using computer vision '''
self.VFCandidates_near[:] = []
self.VFCandidates_center[:] = []
self.VFCandidates_far[:] = []
for dt in data.targets:
self.VFCandidates_near.append(dt.cluster_point_near)
self.VFCandidates_center.append(dt.cluster_point_center)
self.VFCandidates_far.append(dt.cluster_point_far)
# Find the best new target
self.newTar, self.newTarScore = self.PickTargetMaxExpEntr()
def _navGoalResponseCallback(self, future:rclpy.Future):
'''
Callback to process the request send to the navigtion2 action server
goal_sent -> -1 goal wasn't accepted
-> 0 goal is being processed
-> 1 goal was accepted
'''
goal_handle = future.result()
# Goal wasn't accepted
if not goal_handle.accepted:
self.get_logger().info('Goal rejected :(')
self.goal_sent = -1
return
self.nav_goal_handle = goal_handle
# Goal was accepted
self.goal_sent = 1
#self.get_logger().info('Goal accepted :)')
self._get_result_future = goal_handle.get_result_async()
self._get_result_future.add_done_callback(self._navGoalResultCallback)
def _navGoalResultCallback(self, future:rclpy.Future):
result = future.result().result
def _navGoalFeedbackCallback(self, data):
self.remaining_distance = data.feedback.distance_remaining
self.recovery_attempts = data.feedback.number_of_recoveries
def _sendNavGoal(self, goal_pos:float):
'''
Send target position to the navigation2 controller
'''
# Check if the goal pos has been previously explored
xs = float("{:.3f}".format(goal_pos[0]))
ys = float("{:.3f}".format(goal_pos[1]))
goal_msg = NavigateToPose.Goal()
# Generate the target goal
goal = PoseStamped()
goal.header.frame_id = 'map'
goal.header.stamp = self.get_clock().now().to_msg()
# Position part
goal.pose.position.x = float(goal_pos[0])
goal.pose.position.y = float(goal_pos[1])
goal_msg.pose = goal
#self.nav2_action_Client.send_goal(goal_msg)
future = self.nav2_action_Client.send_goal_async(goal_msg)
future.add_done_callback(self._navGoalResponseCallback)
def _aeGoalCallback(self, req):
pass
def _aeCancelCallback(self, req):
self.get_logger().info('Autonomous exploration received cancel request')
self.nav_goal_handle.cancel_goal_async()
return CancelResponse.ACCEPT
async def _aeActionCallback(self, goal):
self.get_logger().info('Autonomous explorer was called')
# Proccess the goal inputs
maxSteps = goal.request.max_steps
timeOut = goal.request.time_out
method = goal.request.method
self.get_logger().info("max_steps = {}, timeOut = {}, method = ".format(maxSteps, timeOut) + method)
# Call the explore function
succeeded = self.Explore(timeOut, maxSteps, method, goal)
# Update the status of goal
if succeeded:
self.get_logger().info("Autonomous exploration succeeded")
goal.succeed()
else:
self.get_logger().warn("Autonomous exploration failed")
goal.abort()
result = AutonomousExplorationAction.Result()
result.succeeded = succeeded
return result
def IsExplored(self, tar:np.array) -> bool:
''' Check if the target is already explored'''
#self.get_logger().info("Target IsExplored--> {}".format(tar))
already_explored = False
for el in self.exploredTargets:
#self.get_logger().info("--------------> IsExplored Dist{}".format(np.linalg.norm(el - tar)))
#self.get_logger().info("TmpTar {}, cur Tar {}".format(el, tar))
if np.linalg.norm(el - tar) < 0.1:
already_explored = True
break
return already_explored
def PickTargetNear(self) -> float:
''' Pick the closest exploration target '''
# TODO add attempts if the exploration target is not found
# Sort the targets in increasing order
dists = [dt[2] for dt in self.VFCandidates_near]
indexes = [*range(len(dists))]
sorted_indexes = [x for _,x in sorted(zip(dists, indexes))]
# Check if the current target has already been explored
tar = []
for index in sorted_indexes:
tmp_tar = np.array([self.VFCandidates_near[index][0], self.VFCandidates_near[index][1]])
if not self.IsExplored(tmp_tar):
tar = np.array(tmp_tar)
break
self.get_logger().info("Closest target selected {}".format(tar))
return tar
def PickTargetFar(self) -> float:
''' Pick the furthest exploration target '''
# TODO add attempts if the exploration target is not found
# Sort the targets in increasing order
dists = [dt[2] for dt in self.VFCandidates_far]
indexes = [*range(len(dists))]
sorted_indexes = [x for _,x in sorted(zip(dists, indexes), reverse=True)]
# Check if the current target has already been explored
tar = []
for index in sorted_indexes:
tmp_tar = np.array([self.VFCandidates_far[index][0], self.VFCandidates_far[index][1]])
if not self.IsExplored(tmp_tar):
tar = np.array(tmp_tar)
break
self.get_logger().info("Furthest target selected {}".format(tar))
return tar
def EvaluatePoint(self, pt:float) -> float:
'''Compute the entropy in the given point'''
# Get the distance from the robot to the target
dist = pt[0]
area = pt[1]
# Compute the undiscovered area surrounding the target
if dist > 1:
return area ** np.log(dist + 0.0001)
else:
return -area ** np.log(dist + 0.0001)
def PickTargetMaxExpEntr(self):
''' Use a cost function to estimate the best goal '''
if len(self.VFCandidates_center) == 0:
return [], 0
if len(self.VFCandidates_center) != len(self.VFCandidates_far):
self.get_logger().warn("Center {}, far {}".format(len(self.VFCandidates_center), len(self.VFCandidates_far)))
# Create a copy of the targets
targetCriteria = np.array(self.VFCandidates_center).copy()
targets = np.array(self.VFCandidates_far).copy()
scores = []
poss = []
# Compute the score for each of the frontier goals
for cnt in range(len(targets)):
#self.get_logger().info("center {}, far {}".format(targetCriteria.shape, targets.shape))
dist = targetCriteria[cnt][2]
area = targetCriteria[cnt][3]
tar = np.array([targets[cnt][0], targets[cnt][1]])
#self.get_logger().info("Target --> {}".format(tar))
if not self.IsExplored(tar):
scores.append(self.EvaluatePoint([dist, area]))
poss.append(np.array([tar[0], tar[1]]))
# Return the most promissing candidate
if len(scores) == 0:
return [], 0
return poss[np.argmax(scores)], max(scores)
def Explore(self, timeOut : float, maxSteps : int, method : str, goal) -> bool:
'''
Perform autonomous exploration and travel to the nearest frontier point
@timeout : Used to avoid the recovery mode of the robot when stuck in a position
@maxSteps : Maximum number of goals to explore
@method : Exploration target selection method-> near, far
@status : Return value, False -> robot stuck, True -> maxSteps reached
'''
# Initialize loop variables
cnt = 0
finishedExploration = False
feedback_msg = AutonomousExplorationAction.Feedback()
stuck_cnt = 0
while cnt < maxSteps:
# Check if there aren't more exploration targets
if len(self.VFCandidates_center) == 0:
self.get_logger().info('No more exploration candidates found')
finishedExploration = True
break
# Get the exploration target
tar = []
if method == "near":
tar = self.PickTargetNear()
elif method == "far":
tar = self.PickTargetFar()
else:
tar, self.curTarScore = self.PickTargetMaxExpEntr()
#self.get_logger().info("{}, {}".format(tar, score))
# if there is a target sent it to the navigation controller
if len(tar) > 0:
self.get_logger().info("Navigating to {}".format(tar))
self.mapUpdated = False
self.curTar = np.array(tar)
self.exploredTargets.append(np.array(tar))
self._sendNavGoal(tar)
ts = time.time()
ts2 = time.time()
pos_bef = np.array([self.pos[0], self.pos[1]])
# -1:Cancel navigation, 0:continue, 1:navigation succedded 2:found better goal
navigation_status = 0
# Wait until timeout or goal reached and publish feedback
while (rclpy.ok()) and (navigation_status == 0):
# Create the action feedback
feedback_msg.goal = [float(tar[0]), float(tar[1]), 0.0]
feedback_msg.pos = [float(self.pos[0]), float(self.pos[1])]
feedback_msg.goal_id = cnt
feedback_msg.remaining_distance = self.remaining_distance
goal.publish_feedback(feedback_msg)
if np.linalg.norm(self.pos - self.curTar) < 0.4:
self.get_logger().info("Reached goal, pos {}".format(self.pos))
navigation_status = 1
break
# Check if the robot stuck in the same position for too long
pos_now = np.array([self.pos[0], self.pos[1]])
if time.time() - ts > timeOut:
ts = time.time()
if np.linalg.norm(pos_bef - pos_now) < 0.1:
self.get_logger().warn("Robot didn't move while navigating to the next waypoint")
navigation_status = -1
break
pos_bef = pos_now.copy()
# Check if it took too long to go to the goal
if (time.time() - ts2 > 60.0):
self.get_logger().warn("Timeout reached, too much time spent travelling to goal")
navigation_status = -1
break
# Check if a better goal exist, only for the Entopy method
if method != 'near' and method != 'far':
if self.curTarScore > 0.01:
if self.newTarScore / self.curTarScore > 2.5:
self.get_logger().info("Found better navigation target {}".format(self.newTar))
navigation_status = 2
self.curTar = []
break
cnt += 1
else:
self.get_logger().warn("No more " + method + " targets, exploration stopping")
finishedExploration = False
self.curTar = []
break
# Check if the robot reached the goal
if navigation_status > 0:
stuck_cnt = 0
self.curTar = []
else:
stuck_cnt += 1
if stuck_cnt == 4:
self.get_logger().error("Robot stuck too many times, manual control needed")
self.curTar = []
break
# Return status
status = finishedExploration
if cnt == maxSteps:
status = True
return status
###################################################################################################
def main(args=None):
rclpy.init(args=args)
AE = AutonomousExploration()
executor = MultiThreadedExecutor()
try:
rclpy.spin(AE, executor)
except KeyboardInterrupt:
pass #rclpy.spin_until_future_complete(SR, )
# Destroy the node explicitly
# (optional - otherwise it will be done automatically
# when the garbage collector destroys the node object)
AE.destroy_node()
rclpy.shutdown()
if __name__ == '__main__':
main() | 6,291 | 11,879 | 45 |
36812059fa58166e6ee951d9dfb976bcdcdb394d | 2,773 | py | Python | loggers/progress_interface.py | kefir/snakee | a17734d4b2d7dfd3e6c7b195baa128fbc84d197b | [
"MIT"
] | null | null | null | loggers/progress_interface.py | kefir/snakee | a17734d4b2d7dfd3e6c7b195baa128fbc84d197b | [
"MIT"
] | null | null | null | loggers/progress_interface.py | kefir/snakee | a17734d4b2d7dfd3e6c7b195baa128fbc84d197b | [
"MIT"
] | 2 | 2021-04-10T19:22:15.000Z | 2022-03-08T19:37:56.000Z | from abc import ABC, abstractmethod
from enum import Enum
from typing import Optional, Union, Iterable, NoReturn
try: # Assume we're a sub-module in a package.
from utils import arguments as arg
from base.abstract.tree_item import TreeInterface
from loggers.extended_logger_interface import ExtendedLoggerInterface
except ImportError: # Apparently no higher-level package has been imported, fall back to a local import.
from ..utils import arguments as arg
from ..base.abstract.tree_item import TreeInterface
from .extended_logger_interface import ExtendedLoggerInterface
Logger = Union[ExtendedLoggerInterface, arg.DefaultArgument]
| 27.186275 | 107 | 0.653083 | from abc import ABC, abstractmethod
from enum import Enum
from typing import Optional, Union, Iterable, NoReturn
try: # Assume we're a sub-module in a package.
from utils import arguments as arg
from base.abstract.tree_item import TreeInterface
from loggers.extended_logger_interface import ExtendedLoggerInterface
except ImportError: # Apparently no higher-level package has been imported, fall back to a local import.
from ..utils import arguments as arg
from ..base.abstract.tree_item import TreeInterface
from .extended_logger_interface import ExtendedLoggerInterface
Logger = Union[ExtendedLoggerInterface, arg.DefaultArgument]
class OperationStatus(Enum):
New = 'new'
InProgress = 'in_progress'
Done = 'done'
def get_name(self):
return self.value
class ProgressInterface(TreeInterface, ABC):
@abstractmethod
def get_logger(self) -> Logger:
pass
@abstractmethod
def get_position(self) -> int:
pass
@abstractmethod
def set_position(self, position: int, inplace: bool) -> Optional[TreeInterface]:
pass
@abstractmethod
def get_selection_logger(self, name=arg.DEFAULT) -> Logger:
pass
@abstractmethod
def log(
self, msg: str,
level: Union[int, arg.DefaultArgument] = arg.DEFAULT,
end: Union[str, arg.DefaultArgument] = arg.DEFAULT,
verbose: Union[bool, arg.DefaultArgument] = arg.DEFAULT,
) -> NoReturn:
pass
@abstractmethod
def log_selection_batch(self, level=arg.DEFAULT, reset_after: bool = True) -> NoReturn:
pass
@abstractmethod
def is_started(self) -> bool:
pass
@abstractmethod
def is_finished(self) -> bool:
pass
@abstractmethod
def get_percent(self, round_digits: int = 1, default_value: str = 'UNK') -> str:
pass
@abstractmethod
def evaluate_share(self) -> float:
pass
@abstractmethod
def evaluate_speed(self) -> int:
pass
@abstractmethod
def update_now(self, cur):
pass
@abstractmethod
def update(self, position: int, step: Optional[int] = None, message: Optional[str] = None) -> NoReturn:
pass
@abstractmethod
def start(self, position: int = 0) -> NoReturn:
pass
@abstractmethod
def finish(self, position: Optional[int] = None, log_selection_batch: bool = True) -> NoReturn:
pass
@abstractmethod
def iterate(
self,
items: Iterable,
name: Optional[str] = None,
expected_count: Optional[int] = None,
step: Union[int, arg.DefaultArgument] = arg.DEFAULT,
log_selection_batch: bool = True
) -> Iterable:
pass
| 1,191 | 873 | 46 |
06147a362cae90b4d400fabd85cb0b31d1338c1b | 1,240 | py | Python | CLASSIC PUZZLE - MEDIUM/mayan-calculation.py | martincourtois/CodinGame | 4df9c8af5cb9c513880dd086da9bf3f201bd56ed | [
"Unlicense"
] | null | null | null | CLASSIC PUZZLE - MEDIUM/mayan-calculation.py | martincourtois/CodinGame | 4df9c8af5cb9c513880dd086da9bf3f201bd56ed | [
"Unlicense"
] | null | null | null | CLASSIC PUZZLE - MEDIUM/mayan-calculation.py | martincourtois/CodinGame | 4df9c8af5cb9c513880dd086da9bf3f201bd56ed | [
"Unlicense"
] | null | null | null | import sys
import math
BASE=20
Sym2Base={}
Base2Sym={}
l, h = [int(i) for i in input().split()]
for i in range(h):
numeral=input()
for j in range(BASE):
idx=l*j
STR=numeral[idx:idx+l]
if j in Base2Sym:
Base2Sym[j]+=[STR]
else:
Base2Sym[j]=[STR]
for key,value in Base2Sym.items():
Sym2Base[''.join(value)]=key
########################################
N1_sym=[]
N2_sym=[]
s1 = int(int(input())/h)
for i in range(s1):
N1_sym.append(''.join([input() for i in range(h)]))
s2 = int(int(input())/h)
for i in range(s2):
N2_sym.append(''.join([input() for i in range(h)]))
#########################################
N1=0
N2=0
for i in N1_sym:
N1=N1*20+Sym2Base[i]
for i in N2_sym:
N2=N2*20+Sym2Base[i]
#########################################
operation = input()
if operation=='+':
result=N1+N2
elif operation=='*':
result=N1*N2
elif operation=='-':
result=N1-N2
elif operation=='/':
result=N1/N2
result_Base=[]
if result==0:
result_Base.append(0)
while not(result/BASE==0):
result_Base.append(result % BASE)
result=int(result/BASE)
result_Base.reverse()
for i in result_Base:
for j in Base2Sym[i]:
print(j)
| 18.507463 | 55 | 0.537097 | import sys
import math
BASE=20
Sym2Base={}
Base2Sym={}
l, h = [int(i) for i in input().split()]
for i in range(h):
numeral=input()
for j in range(BASE):
idx=l*j
STR=numeral[idx:idx+l]
if j in Base2Sym:
Base2Sym[j]+=[STR]
else:
Base2Sym[j]=[STR]
for key,value in Base2Sym.items():
Sym2Base[''.join(value)]=key
########################################
N1_sym=[]
N2_sym=[]
s1 = int(int(input())/h)
for i in range(s1):
N1_sym.append(''.join([input() for i in range(h)]))
s2 = int(int(input())/h)
for i in range(s2):
N2_sym.append(''.join([input() for i in range(h)]))
#########################################
N1=0
N2=0
for i in N1_sym:
N1=N1*20+Sym2Base[i]
for i in N2_sym:
N2=N2*20+Sym2Base[i]
#########################################
operation = input()
if operation=='+':
result=N1+N2
elif operation=='*':
result=N1*N2
elif operation=='-':
result=N1-N2
elif operation=='/':
result=N1/N2
result_Base=[]
if result==0:
result_Base.append(0)
while not(result/BASE==0):
result_Base.append(result % BASE)
result=int(result/BASE)
result_Base.reverse()
for i in result_Base:
for j in Base2Sym[i]:
print(j)
| 0 | 0 | 0 |
a197e2de1fc9100ea53ed671c6bed2bbd3b2ff67 | 5,551 | py | Python | main.py | vutienhung260798/keras-retinanet | 73e167cf0bd76563f1171699697343cf9945f53b | [
"Apache-2.0"
] | null | null | null | main.py | vutienhung260798/keras-retinanet | 73e167cf0bd76563f1171699697343cf9945f53b | [
"Apache-2.0"
] | 4 | 2020-01-28T22:22:00.000Z | 2022-02-09T23:36:54.000Z | main.py | vutienhung260798/keras-retinanet | 73e167cf0bd76563f1171699697343cf9945f53b | [
"Apache-2.0"
] | null | null | null | import os
import shutil
import zipfile
import urllib
import xml.etree.ElementTree as ET
import numpy as np
import csv
import pandas
# from google.colab import drive
# from google.colab import files
# %matplotlib inline
# # automatically reload modules when they have changed
# %reload_ext autoreload
# %autoreload 2
# # import keras
import keras
# import keras_retinanet
from keras_retinanet import models
from keras_retinanet.utils.image import read_image_bgr, preprocess_image, resize_image
from keras_retinanet.utils.visualization import draw_box, draw_caption
from keras_retinanet.utils.colors import label_color
# import miscellaneous modules
import matplotlib.pyplot as plt
import cv2
import os
import numpy as np
import time
# set tf backend to allow memory to grow, instead of claiming everything
import tensorflow as tf
import json
import os
import pickle as pkl
import Save_solar
import shutil
solar_detection(images_path = './keras-retinanet/7fc8992d8a_012288112DOPENPIPELINE_Orthomosaic_export_FriNov22014645.383588.jpg')
Save_solar.save_json('./list_bb.json')
| 33.239521 | 194 | 0.652495 | import os
import shutil
import zipfile
import urllib
import xml.etree.ElementTree as ET
import numpy as np
import csv
import pandas
# from google.colab import drive
# from google.colab import files
# %matplotlib inline
# # automatically reload modules when they have changed
# %reload_ext autoreload
# %autoreload 2
# # import keras
import keras
# import keras_retinanet
from keras_retinanet import models
from keras_retinanet.utils.image import read_image_bgr, preprocess_image, resize_image
from keras_retinanet.utils.visualization import draw_box, draw_caption
from keras_retinanet.utils.colors import label_color
# import miscellaneous modules
import matplotlib.pyplot as plt
import cv2
import os
import numpy as np
import time
# set tf backend to allow memory to grow, instead of claiming everything
import tensorflow as tf
import json
import os
import pickle as pkl
import Save_solar
import shutil
def sliding_window(path_img):
over_lap_x = 100
over_lap_y = 80
list_img = []
list_solar = []
window_size = (240, 250)
img = cv2.imread(path_img)
# print(np.shape(img))
x, y,_ = np.shape(img)
# print(x, y)
x = x//(window_size[0] - over_lap_x)
y = y//(window_size[1] - over_lap_y)
print(x, y)
image_size_x = (window_size[0] - over_lap_x) * x + over_lap_x
image_size_y = (window_size[1] - over_lap_y) * y + over_lap_y
print(image_size_x, image_size_y)
image_size = (image_size_y, image_size_x)
image = cv2.resize(img, (image_size))
# print(np.shape(image))
for i in range(x):
for j in range(y):
if(i != 0 and j != 0):
split_image = image[(window_size[0]-over_lap_x)*i :(window_size[0]-over_lap_x)*i + window_size[0], (window_size[1]-over_lap_y)*j : (window_size[1]-over_lap_y)*j + window_size[1]]
if(i == 0 and j != 0):
split_image = image[0 : window_size[0], (window_size[1]-over_lap_y)*j : (window_size[1]-over_lap_y)*j + window_size[1]]
if(j == 0 and i != 0):
split_image = image[(window_size[0]-over_lap_x)*i :(window_size[0]-over_lap_x)*i + window_size[0], 0 : window_size[1]]
if(i == 0 and j == 0):
split_image = image[0: window_size[0], 0 : window_size[1]]
# list_img.append(split_image)
cv2.imwrite('./anh/' + str(i)+'.'+str(j) + '.jpg', split_image)
cv2.imwrite('./a.jpg', image)
def img_inference(img_path, pos_window, model, labels_to_names):
window_size = (240, 250)
over_lap_x = 100
over_lap_y = 80
list_bb = []
image = read_image_bgr(img_path)
# copy to draw on
draw = image.copy()
draw = cv2.cvtColor(draw, cv2.COLOR_BGR2RGB)
# preprocess image for network
image = preprocess_image(image)
image, scale = resize_image(image)
# print(scale)
# process image
start = time.time()
boxes, scores, labels = model.predict_on_batch(np.expand_dims(image, axis=0))
print("processing time: ", time.time() - start)
boxes /= scale
for box, score, label in zip(boxes[0], scores[0], labels[0]):
box_restore = []
# scores are sorted so we can break
if score < 0.8 or labels_to_names[label] != "solar":
break
box_restore.append(box[0] + pos_window[1] * (window_size[1]- over_lap_y))
box_restore.append(box[1] + pos_window[0] * (window_size[0]- over_lap_x))
box_restore.append(box[2] + pos_window[1] * (window_size[1]- over_lap_y))
box_restore.append(box[3] + pos_window[0] * (window_size[0]- over_lap_x))
# print(box)
# print(score)
# print(labels_to_names[label])
list_bb.append(box_restore)
color = label_color(label)
b = box.astype(int)
draw_box(draw, b, color=color)
caption = "{} {:.3f}".format(labels_to_names[label], score)
draw_caption(draw, b, caption)
plt.figure(figsize=(10, 10))
plt.axis('off')
plt.imshow(draw)
plt.show()
# for box in list_bb:
# print(box)
# print(list_bb[0])
return list_bb
def get_session():
config = tf.ConfigProto()
config.gpu_options.allow_growth = True
return tf.Session(config=config)
def solar_detection(images_path = ''):
DATASET_DIR = 'dataset'
ANNOTATIONS_FILE = 'annotations.csv'
CLASSES_FILE = 'classes.csv'
keras.backend.tensorflow_backend.set_session(get_session())
#load model
model_path = './resnet50_csv_10.h5'
print(model_path)
# load retinanet model
model = models.load_model(model_path, backbone_name='resnet50')
model = models.convert_model(model)
# load label to names mapping for visualization purposes
labels_to_names = pandas.read_csv(CLASSES_FILE,header=None).T.loc[0].to_dict()
list_dir = os.listdir('./')
if 'anh' in list_dir:
shutil.rmtree('anh')
sliding_window(images_path)
os.mkdir('anh')
path_file = './anh/'
list_bb = {}
for img in os.listdir(path_file):
A = img.split('.')
pos_window = (int(A[0]), int(A[1]))
path_img = os.path.join(path_file, img)
id = A[0] + '.' + A[1]
print(id)
bb = img_inference(path_img, pos_window, model, labels_to_names)
# print(bb)
list_bb[id] = bb
with open('./list_bb.json', 'w') as f_w:
json.dump(list_bb, f_w)
solar_detection(images_path = './keras-retinanet/7fc8992d8a_012288112DOPENPIPELINE_Orthomosaic_export_FriNov22014645.383588.jpg')
Save_solar.save_json('./list_bb.json')
| 4,378 | 0 | 92 |
43ee1d4b0f5fd09b8583052db30dee40c388a21c | 2,489 | py | Python | Chapter06/descriptors_pythonic_2.py | TranQuangDuc/Clean-Code-in-Python | 3c4b4a2fde2ccf28d2e0ec5002b2e1921704164e | [
"MIT"
] | 402 | 2018-08-19T03:09:40.000Z | 2022-03-30T08:10:26.000Z | Chapter06/descriptors_pythonic_2.py | TranQuangDuc/Clean-Code-in-Python | 3c4b4a2fde2ccf28d2e0ec5002b2e1921704164e | [
"MIT"
] | 3 | 2019-01-29T20:36:28.000Z | 2022-03-02T02:16:23.000Z | Chapter06/descriptors_pythonic_2.py | TranQuangDuc/Clean-Code-in-Python | 3c4b4a2fde2ccf28d2e0ec5002b2e1921704164e | [
"MIT"
] | 140 | 2018-09-16T05:47:46.000Z | 2022-03-31T03:20:30.000Z | """Clean Code in Python - Chapter 6: Descriptors
> A Pythonic Implementation
"""
class HistoryTracedAttribute:
"""Trace the values of this attribute into another one given by the name at
``trace_attribute_name``.
"""
def _needs_to_track_change(self, instance, value) -> bool:
"""Determine if the value change needs to be traced or not.
Rules for adding a value to the trace:
* If the value is not previously set (it's the first one).
* If the new value is != than the current one.
"""
try:
current_value = instance.__dict__[self._name]
except KeyError:
return True
return value != current_value
class Traveller:
"""A person visiting several cities.
We wish to track the path of the traveller, as he or she is visiting each
new city.
>>> alice = Traveller("Alice", "Barcelona")
>>> alice.current_city = "Paris"
>>> alice.current_city = "Brussels"
>>> alice.current_city = "Amsterdam"
>>> alice.cities_visited
['Barcelona', 'Paris', 'Brussels', 'Amsterdam']
>>> alice.current_city
'Amsterdam'
>>> alice.current_city = "Amsterdam"
>>> alice.cities_visited
['Barcelona', 'Paris', 'Brussels', 'Amsterdam']
>>> bob = Traveller("Bob", "Rotterdam")
>>> bob.current_city = "Amsterdam"
>>> bob.current_city
'Amsterdam'
>>> bob.cities_visited
['Rotterdam', 'Amsterdam']
"""
current_city = HistoryTracedAttribute("cities_visited")
| 28.94186 | 79 | 0.648855 | """Clean Code in Python - Chapter 6: Descriptors
> A Pythonic Implementation
"""
class HistoryTracedAttribute:
"""Trace the values of this attribute into another one given by the name at
``trace_attribute_name``.
"""
def __init__(self, trace_attribute_name: str) -> None:
self.trace_attribute_name = trace_attribute_name
self._name = None
def __set_name__(self, owner, name):
self._name = name
def __get__(self, instance, owner):
if instance is None:
return self
return instance.__dict__[self._name]
def __set__(self, instance, value):
self._track_change_in_value_for_instance(instance, value)
instance.__dict__[self._name] = value
def _track_change_in_value_for_instance(self, instance, value):
self._set_default(instance)
if self._needs_to_track_change(instance, value):
instance.__dict__[self.trace_attribute_name].append(value)
def _needs_to_track_change(self, instance, value) -> bool:
"""Determine if the value change needs to be traced or not.
Rules for adding a value to the trace:
* If the value is not previously set (it's the first one).
* If the new value is != than the current one.
"""
try:
current_value = instance.__dict__[self._name]
except KeyError:
return True
return value != current_value
def _set_default(self, instance):
instance.__dict__.setdefault(self.trace_attribute_name, [])
class Traveller:
"""A person visiting several cities.
We wish to track the path of the traveller, as he or she is visiting each
new city.
>>> alice = Traveller("Alice", "Barcelona")
>>> alice.current_city = "Paris"
>>> alice.current_city = "Brussels"
>>> alice.current_city = "Amsterdam"
>>> alice.cities_visited
['Barcelona', 'Paris', 'Brussels', 'Amsterdam']
>>> alice.current_city
'Amsterdam'
>>> alice.current_city = "Amsterdam"
>>> alice.cities_visited
['Barcelona', 'Paris', 'Brussels', 'Amsterdam']
>>> bob = Traveller("Bob", "Rotterdam")
>>> bob.current_city = "Amsterdam"
>>> bob.current_city
'Amsterdam'
>>> bob.cities_visited
['Rotterdam', 'Amsterdam']
"""
current_city = HistoryTracedAttribute("cities_visited")
def __init__(self, name, current_city):
self.name = name
self.current_city = current_city
| 765 | 0 | 189 |
71250c279386af28fe56d8a22bdf0dd78d63e5ee | 2,621 | py | Python | pypi_portal/tasks/pypi.py | SiddharthSudhakar/Flask-prod-app-structure | 4213201ab007ec7b10bdb44c4c8acc6dd3dc59ca | [
"MIT"
] | 565 | 2015-01-08T15:04:14.000Z | 2022-03-20T16:43:28.000Z | pypi_portal/tasks/pypi.py | rams502/Flask-Large-Application-Example | f536c3dee4050634cf4dfe77a6bb116040e6cf14 | [
"MIT"
] | 4 | 2015-11-30T08:28:08.000Z | 2016-12-09T08:54:26.000Z | pypi_portal/tasks/pypi.py | rams502/Flask-Large-Application-Example | f536c3dee4050634cf4dfe77a6bb116040e6cf14 | [
"MIT"
] | 138 | 2015-02-16T23:03:18.000Z | 2021-11-04T01:17:40.000Z | """Retrieve data from PyPI."""
from distutils.version import LooseVersion
from logging import getLogger
import xmlrpclib
from flask.ext.celery import single_instance
from pypi_portal.extensions import celery, db, redis
from pypi_portal.models.pypi import Package
from pypi_portal.models.redis import POLL_SIMPLE_THROTTLE
LOG = getLogger(__name__)
THROTTLE = 1 * 60 * 60
@celery.task(bind=True, soft_time_limit=120)
@single_instance
def update_package_list():
"""Get a list of all packages from PyPI through their XMLRPC API.
This task returns something in case the user schedules it from a view. The view can wait up to a certain amount of
time for this task to finish, and if nothing times out, it can tell the user if it found any new packages.
Since views can schedule this task, we don't want some rude person hammering PyPI or our application with repeated
requests. This task is limited to one run per 1 hour at most.
Returns:
List of new packages found. Returns None if task is rate-limited.
"""
# Rate limit.
lock = redis.lock(POLL_SIMPLE_THROTTLE, timeout=int(THROTTLE))
have_lock = lock.acquire(blocking=False)
if not have_lock:
LOG.warning('poll_simple() task has already executed in the past 4 hours. Rate limiting.')
return None
# Query API.
client = xmlrpclib.ServerProxy('https://pypi.python.org/pypi')
results = client.search(dict(summary=''))
if not results:
LOG.error('Reply from API had no results.')
return list()
LOG.debug('Sorting results.')
results.sort(key=lambda x: (x['name'], LooseVersion(x['version'])))
filtered = (r for r in results if r['version'][0].isdigit())
packages = {r['name']: dict(summary=r['summary'], version=r['version'], id=0) for r in filtered}
LOG.debug('Pruning unchanged packages.')
for row in db.session.query(Package.id, Package.name, Package.summary, Package.latest_version):
if packages.get(row[1]) == dict(summary=row[2], version=row[3], id=0):
packages.pop(row[1])
elif row[1] in packages:
packages[row[1]]['id'] = row[0]
new_package_names = {n for n, d in packages.items() if not d['id']}
# Merge into database.
LOG.debug('Found {} new packages in PyPI, updating {} total.'.format(len(new_package_names), len(packages)))
with db.session.begin_nested():
for name, data in packages.items():
db.session.merge(Package(id=data['id'], name=name, summary=data['summary'], latest_version=data['version']))
db.session.commit()
return list(new_package_names)
| 40.323077 | 120 | 0.695155 | """Retrieve data from PyPI."""
from distutils.version import LooseVersion
from logging import getLogger
import xmlrpclib
from flask.ext.celery import single_instance
from pypi_portal.extensions import celery, db, redis
from pypi_portal.models.pypi import Package
from pypi_portal.models.redis import POLL_SIMPLE_THROTTLE
LOG = getLogger(__name__)
THROTTLE = 1 * 60 * 60
@celery.task(bind=True, soft_time_limit=120)
@single_instance
def update_package_list():
"""Get a list of all packages from PyPI through their XMLRPC API.
This task returns something in case the user schedules it from a view. The view can wait up to a certain amount of
time for this task to finish, and if nothing times out, it can tell the user if it found any new packages.
Since views can schedule this task, we don't want some rude person hammering PyPI or our application with repeated
requests. This task is limited to one run per 1 hour at most.
Returns:
List of new packages found. Returns None if task is rate-limited.
"""
# Rate limit.
lock = redis.lock(POLL_SIMPLE_THROTTLE, timeout=int(THROTTLE))
have_lock = lock.acquire(blocking=False)
if not have_lock:
LOG.warning('poll_simple() task has already executed in the past 4 hours. Rate limiting.')
return None
# Query API.
client = xmlrpclib.ServerProxy('https://pypi.python.org/pypi')
results = client.search(dict(summary=''))
if not results:
LOG.error('Reply from API had no results.')
return list()
LOG.debug('Sorting results.')
results.sort(key=lambda x: (x['name'], LooseVersion(x['version'])))
filtered = (r for r in results if r['version'][0].isdigit())
packages = {r['name']: dict(summary=r['summary'], version=r['version'], id=0) for r in filtered}
LOG.debug('Pruning unchanged packages.')
for row in db.session.query(Package.id, Package.name, Package.summary, Package.latest_version):
if packages.get(row[1]) == dict(summary=row[2], version=row[3], id=0):
packages.pop(row[1])
elif row[1] in packages:
packages[row[1]]['id'] = row[0]
new_package_names = {n for n, d in packages.items() if not d['id']}
# Merge into database.
LOG.debug('Found {} new packages in PyPI, updating {} total.'.format(len(new_package_names), len(packages)))
with db.session.begin_nested():
for name, data in packages.items():
db.session.merge(Package(id=data['id'], name=name, summary=data['summary'], latest_version=data['version']))
db.session.commit()
return list(new_package_names)
| 0 | 0 | 0 |
4cce00aa5de582f5670857de07c52a8bef04a856 | 2,546 | py | Python | quex/output/core/state_machine_coder.py | Liby99/quex | 45f3d21d5df3307376e175cca2d8473e26cb5622 | [
"MIT"
] | null | null | null | quex/output/core/state_machine_coder.py | Liby99/quex | 45f3d21d5df3307376e175cca2d8473e26cb5622 | [
"MIT"
] | 1 | 2022-01-31T18:08:44.000Z | 2022-01-31T18:08:44.000Z | quex/output/core/state_machine_coder.py | raccoonmonk/quex | 20ffe451df9fd49bdc216ce45b8263fa228670e5 | [
"MIT"
] | null | null | null | # Project Quex (http://quex.sourceforge.net); License: MIT;
# (C) 2005-2020 Frank-Rene Schaefer;
#_______________________________________________________________________________
import quex.output.core.state.core as state_coder
import quex.output.core.state.entry as entry
import quex.output.core.mega_state.core as mega_state_coder
from quex.blackboard import Lng
from collections import defaultdict
from copy import copy
def do(TheAnalyzer):
"""Generate source code for a given state machine 'SM'.
"""
Lng.register_analyzer(TheAnalyzer)
assert id(Lng.analyzer) == id(TheAnalyzer)
# (*) Init State must be first!
txt = []
state_coder.do(txt, TheAnalyzer.state_db[TheAnalyzer.init_state_index], TheAnalyzer)
# (*) Second: The drop-out catcher, since it is referenced the most.
# (Is implemented entirely by 'entry')
code_drop_out_catcher(txt, TheAnalyzer)
# (*) Code the Mega States (implementing multiple states in one)
for state in TheAnalyzer.mega_state_list:
mega_state_coder.do(txt, state, TheAnalyzer)
# (*) All other (normal) states (sorted by their frequency of appearance)
for state in remaining_non_mega_state_iterable(TheAnalyzer):
state_coder.do(txt, state, TheAnalyzer)
Lng.unregister_analyzer()
return txt
def get_frequency_db(StateDB, RemainderStateIndexList):
"""Sort the list in a away, so that states that are used more
often appear earlier. This happens in the hope of more
cache locality.
"""
# Count number of transitions to a state: frequency_db
frequency_db = defaultdict(int)
for state in (StateDB[i] for i in RemainderStateIndexList):
assert state.transition_map is not None
for interval, target_index in state.transition_map:
frequency_db[target_index] += 1
return frequency_db
| 38 | 88 | 0.706991 | # Project Quex (http://quex.sourceforge.net); License: MIT;
# (C) 2005-2020 Frank-Rene Schaefer;
#_______________________________________________________________________________
import quex.output.core.state.core as state_coder
import quex.output.core.state.entry as entry
import quex.output.core.mega_state.core as mega_state_coder
from quex.blackboard import Lng
from collections import defaultdict
from copy import copy
def do(TheAnalyzer):
"""Generate source code for a given state machine 'SM'.
"""
Lng.register_analyzer(TheAnalyzer)
assert id(Lng.analyzer) == id(TheAnalyzer)
# (*) Init State must be first!
txt = []
state_coder.do(txt, TheAnalyzer.state_db[TheAnalyzer.init_state_index], TheAnalyzer)
# (*) Second: The drop-out catcher, since it is referenced the most.
# (Is implemented entirely by 'entry')
code_drop_out_catcher(txt, TheAnalyzer)
# (*) Code the Mega States (implementing multiple states in one)
for state in TheAnalyzer.mega_state_list:
mega_state_coder.do(txt, state, TheAnalyzer)
# (*) All other (normal) states (sorted by their frequency of appearance)
for state in remaining_non_mega_state_iterable(TheAnalyzer):
state_coder.do(txt, state, TheAnalyzer)
Lng.unregister_analyzer()
return txt
def code_drop_out_catcher(txt, TheAnalyzer):
pre_txt, post_txt = entry.do(TheAnalyzer.drop_out)
txt.extend(pre_txt)
txt.extend(post_txt)
def remaining_non_mega_state_iterable(TheAnalyzer):
frequency_db = get_frequency_db(TheAnalyzer.state_db,
TheAnalyzer.non_mega_state_index_set)
remainder = copy(TheAnalyzer.non_mega_state_index_set)
remainder.remove(TheAnalyzer.init_state_index)
for state in sorted(map(lambda i: TheAnalyzer.state_db[i], remainder),
key=lambda s: frequency_db[s.index], reverse=True):
yield state
def get_frequency_db(StateDB, RemainderStateIndexList):
"""Sort the list in a away, so that states that are used more
often appear earlier. This happens in the hope of more
cache locality.
"""
# Count number of transitions to a state: frequency_db
frequency_db = defaultdict(int)
for state in (StateDB[i] for i in RemainderStateIndexList):
assert state.transition_map is not None
for interval, target_index in state.transition_map:
frequency_db[target_index] += 1
return frequency_db
| 575 | 0 | 46 |
0ca4b19554d9dc9108e289b3ba59d1f5db6441a4 | 21,179 | py | Python | script/BuildConsolidatedFeaturesFile.py | smenon8/AnimalPhotoBias | 0b97a8a6d51ad749b4338febdee9d67b80dc3853 | [
"BSD-3-Clause"
] | 2 | 2017-02-12T02:33:12.000Z | 2021-06-21T09:03:34.000Z | script/BuildConsolidatedFeaturesFile.py | smenon8/AnimalWildlifeEstimator | 0b97a8a6d51ad749b4338febdee9d67b80dc3853 | [
"BSD-3-Clause"
] | 14 | 2016-08-31T03:05:44.000Z | 2017-06-02T17:37:29.000Z | script/BuildConsolidatedFeaturesFile.py | smenon8/AnimalPhotoBias | 0b97a8a6d51ad749b4338febdee9d67b80dc3853 | [
"BSD-3-Clause"
] | 1 | 2016-04-29T20:33:45.000Z | 2016-04-29T20:33:45.000Z | # python-3
# coding: utf-8
'''
Script Name: BuildConsolidatedFeaturesFile.py
Created date : Sunday, 27th March
Author : Sreejith Menon
Description :
buildFeatureFl(input file,output file)
Reads from a csv file (taken as a parameter) containing a list of image GIDs.
Extracts the below features from the IBEIS dataset:
1. nid
2. names
3. species_texts
4. sex_texts
5. age_months_est
6. exemplar_flags
7. quality_texts
Outputs 3 files in the same directory as the outFL directory
File 1 : Map of all images and their annotation IDs (csv)
File 2 : Annotation ID's and their features (csv)
File 3 : Image GID, annotation ID's and their features (csv)
File 4 : Image GID, annotation ID's and their features (json)
'''
from __future__ import print_function
import GetPropertiesAPI as GP
import importlib, json, re, sys, csv, time, math
# importlib.reload(GP) # un-comment if there are any changes made to API
import pandas as pd
# import DataStructsHelperAPI as DS
from math import floor
# importlib.reload(GP)
from multiprocessing import Process
import DataStructsHelperAPI as DS
# Original Microsoft Tagging API output is a R list,
# This method parses the data into python readable form and dumps the output into a JSON.
'''
Logic for reading data from the consolidatedHITResults file - changed
The input for the below method will be a csv file/list with all the image GID's for which the features have to be extracted.
'''
# these APIs require encoded annot_uuid_list
ggr_eco_ftr_api_map = {'age': "/api/annot/age/months/json",
'sex': "/api/annot/sex/text/json",
'bbox': "/api/annot/bbox/json",
'nid': "/api/annot/name/rowid/json",
'exemplar': "/api/annot/exemplar/json",
'species': "/api/annot/species/json",
'quality': "/api/annot/quality/text/json",
'view_point': "/api/annot/yaw/text/json"
}
# these APIs takes in an encoded gid list
ggr_otr_ftr_api_map = {'contributor': "/api/image/note",
'lat': "/api/image/lat",
'long': "/api/image/lon",
'datetime': "/api/image/unixtime",
'width': "/api/image/width",
'height': "/api/image/height",
'orientation': "/api/image/orientation"
}
if __name__ == "__main__":
gids = list(map(str, list(range(1, 1862))))
buildFeatureFl(gids, "../data/Flickr_IBEIS_Giraffe_Ftrs.csv", False)
# __main__()
# gidAidMapFl = "../data/full_gid_aid_map.json"
# getAdditionalAnnotFeatures(gidAidMapFl,'bbox',"../data/gid_bbox.json")
# buildBeautyFtrFl("../data/beautyFeatures_GZC_R.csv",['GID','pleasure','arousal','dominance','y'],"../data/beautyFeatures_GZC")
# DS.combineJson("../data/beautyFeatures_GZC.json","../data/imgs_exif_data_full.json","../data/GZC_exifs_beauty_full.json")
# p1 = Process(target=build_exif_ftrs_fl_ggr, args=("uuid_gid_map.json", "ggr_uuid_list.dat", "ggr_exif_extract_1.json",1,5000))
# p2 = Process(target=build_exif_ftrs_fl_ggr, args=("uuid_gid_map.json", "ggr_uuid_list.dat", "ggr_exif_extract_2.json",5001,10000))
# p3 = Process(target=build_exif_ftrs_fl_ggr, args=("uuid_gid_map.json", "ggr_uuid_list.dat", "ggr_exif_extract_3.json",10001,15000))
# p4 = Process(target=build_exif_ftrs_fl_ggr, args=("uuid_gid_map.json", "ggr_uuid_list.dat", "ggr_exif_extract_4.json",15001,20000))
# p5 = Process(target=build_exif_ftrs_fl_ggr, args=("uuid_gid_map.json", "ggr_uuid_list.dat", "ggr_exif_extract_5.json",20001,25000))
# p6 = Process(target=build_exif_ftrs_fl_ggr, args=("uuid_gid_map.json", "ggr_uuid_list.dat", "ggr_exif_extract_6.json",25001,30000))
# p7 = Process(target=build_exif_ftrs_fl_ggr, args=("uuid_gid_map.json", "ggr_uuid_list.dat", "ggr_exif_extract_7.json",30001,35000))
# p8 = Process(target=build_exif_ftrs_fl_ggr, args=("uuid_gid_map.json", "ggr_uuid_list.dat", "ggr_exif_extract_8.json",35001,37433))
# p9 = Process(target=build_feature_file_ggr, args=("uuid_gid_map.json", "ggr_ftr_extract_1",1,5000))
# p10 = Process(target=build_feature_file_ggr, args=("uuid_gid_map.json", "ggr_ftr_extract_2",5001,10000))
# p11 = Process(target=build_feature_file_ggr, args=("uuid_gid_map.json", "ggr_ftr_extract_3",10001,15000))
# p12 = Process(target=build_feature_file_ggr, args=("uuid_gid_map.json", "ggr_ftr_extract_4",15001,20000))
# p13 = Process(target=build_feature_file_ggr, args=("uuid_gid_map.json", "ggr_ftr_extract_5",20001,25000))
# p14 = Process(target=build_feature_file_ggr, args=("uuid_gid_map.json", "ggr_ftr_extract_6",25001,30000))
# p15 = Process(target=build_feature_file_ggr, args=("uuid_gid_map.json", "ggr_ftr_extract_7",30001,35000))
# p16 = Process(target=build_feature_file_ggr, args=("uuid_gid_map.json", "ggr_ftr_extract_8",35001,37433))
# p1 = Process(target=test, args=(0, 400, "/tmp/test1.json"))
# p2 = Process(target=test, args=(400, 800, "/tmp/test2.json"))
# p3 = Process(target=test, args=(800, 1200, "/tmp/test3.json"))
# p4 = Process(target=test, args=(1200, 1600, "/tmp/test4.json"))
# p5 = Process(target=test, args=(1600, 2000, "/tmp/test5.json"))
# p6 = Process(target=test, args=(2000, 2400, "/tmp/test6.json"))
# p7 = Process(target=test, args=(2400, 2800, "/tmp/test7.json"))
# p8 = Process(target=test, args=(2800, 3200, "/tmp/test8.json"))
# p9 = Process(target=test, args=(3200, 3600, "/tmp/test9.json"))
# p10 = Process(target=test, args=(3600, 4033, "/tmp/test10.json"))
# p1.start()
# p2.start()
# p3.start()
# p4.start()
# p5.start()
# p6.start()
# p7.start()
# p8.start()
# p9.start()
# p10.start()
# # p11.start()
# # p12.start()
# # p13.start()
# # p14.start()
# # p15.start()
# # p16.start()
| 41.855731 | 161 | 0.656074 | # python-3
# coding: utf-8
'''
Script Name: BuildConsolidatedFeaturesFile.py
Created date : Sunday, 27th March
Author : Sreejith Menon
Description :
buildFeatureFl(input file,output file)
Reads from a csv file (taken as a parameter) containing a list of image GIDs.
Extracts the below features from the IBEIS dataset:
1. nid
2. names
3. species_texts
4. sex_texts
5. age_months_est
6. exemplar_flags
7. quality_texts
Outputs 3 files in the same directory as the outFL directory
File 1 : Map of all images and their annotation IDs (csv)
File 2 : Annotation ID's and their features (csv)
File 3 : Image GID, annotation ID's and their features (csv)
File 4 : Image GID, annotation ID's and their features (json)
'''
from __future__ import print_function
import GetPropertiesAPI as GP
import importlib, json, re, sys, csv, time, math
# importlib.reload(GP) # un-comment if there are any changes made to API
import pandas as pd
# import DataStructsHelperAPI as DS
from math import floor
# importlib.reload(GP)
from multiprocessing import Process
import DataStructsHelperAPI as DS
def printCompltnPercent(percentComplete):
i = int(percentComplete)
sys.stdout.write('\r')
# the exact output you're looking for:
sys.stdout.write("[%-100s] %d%%" % ('=' * i, i))
sys.stdout.flush()
def writeCsvFromDict(header, inDict, outFL):
writeFL = open(outFL, 'w')
writer = csv.writer(writeFL)
writer.writerow(header)
for key in inDict.keys():
if inDict[key] == None:
value = ["NONE"]
else:
value = inDict[key]
writer.writerow([key] + value)
writeFL.close()
def buildExifFeatureFl(inp, outFL, isInpFl=True):
if isInpFl:
with open(inp, "r") as inpFL:
gids = [row[0] for row in csv.reader(inpFL)]
else: # input is provided as a list
gids = inp
gids = list(map(lambda x: int(x), gids))
datetimes = GP.getExifData(gids, 'unixtime')
lats = GP.getExifData(gids, 'lat')
longs = GP.getExifData(gids, 'lon')
width = GP.getExifData(gids, 'width')
height = GP.getExifData(gids, 'height')
orientation = GP.getExifData(gids, 'orientation')
size = GP.getExifData(gids, 'size')
imgProps = {gids[i]: {'datetime': GP.getUnixTimeReadableFmt(datetimes[i]),
'lat': lats[i],
'long': longs[i],
'width': width[i],
'height': height[i],
'orientation': orientation[i],
'size': size[i]
}
for i in range(0, len(gids))}
with open(outFL, "w") as outFl:
json.dump(imgProps, outFl, indent=4)
return None
def buildBeautyFtrFl(inpFl, ftrs, outFlPrefix):
df = pd.DataFrame.from_csv(inpFl).transpose().reset_index()
df['index'] = df['index'].apply(lambda x: floor(float(x)))
df.columns = ftrs
df['GID'] = df['GID'].apply(lambda x: str(int(x)))
df.to_csv(str(outFlPrefix + ".csv"), index=False)
df.index = df['GID']
df.drop(['GID'], 1, inplace=True)
dctObj = df.to_dict(orient='index')
with open(str(outFlPrefix + ".json"), "w") as jsonObj:
json.dump(dctObj, jsonObj, indent=4)
return None
# Original Microsoft Tagging API output is a R list,
# This method parses the data into python readable form and dumps the output into a JSON.
def genJsonFromMSAIData(flName, outFlNm):
data = []
with open(flName) as openFl:
for row in openFl:
data.append(row)
cleanData = []
for row in data:
cleanData.append(row.replace("\\", "").replace('"\n', ""))
apiResultsDict = {}
for i in range(1, len(cleanData)):
key, value = cleanData[i].split("\t")
value = value.replace('"{"tags"', '{"tags"')
key = key.replace('"', '')
apiResultsDict[key] = json.loads(value)
json.dump(apiResultsDict, open(outFlNm, "w"), indent=4)
return None
def getAdditionalAnnotFeatures(gidAidMap, ftrName, outFlNm='/tmp/getAdditionalAnnotFeatures.dump.json'):
with open(gidAidMap, "r") as gidAidMapFl:
gidAidJson = json.load(gidAidMapFl)
additionalFtrDct = {}
gidInd = 0
n = len(gidAidJson.keys())
for gid in gidAidJson.keys():
additionalFtrDct[gid] = additionalFtrDct.get(gid, []) + [GP.getImageFeature(gidAidJson[gid][0], ftrName)][0]
gidInd += 1
percentComplete = gidInd * 100 / n
if math.floor(percentComplete) % 5 == 0:
printCompltnPercent(percentComplete)
with open(outFlNm, "w") as outFlObj:
json.dump(additionalFtrDct, outFlObj, indent=4)
return None
'''
Logic for reading data from the consolidatedHITResults file - changed
The input for the below method will be a csv file/list with all the image GID's for which the features have to be extracted.
'''
def buildFeatureFl(inp, outFL, isInpFl=True):
allGID = []
if isInpFl:
reader = csv.reader(open(inp, "r"))
for row in reader:
allGID.append(row)
else: # input is provided as a list
allGID = inp
# aids = GP.getAnnotID(allGID)
# Extracts all the annotation ID's from IBEIS
# GidAidMap = {allGID[i] : aids[i] for i in range(0,len(allGID))}
gidInd = 0
GidAidMap = {}
for gid in allGID:
aid = GP.getAnnotID(int(gid))
GidAidMap[gid] = [aid]
gidInd += 1
percentComplete = gidInd * 100 / len(allGID)
if math.floor(percentComplete) % 5 == 0:
printCompltnPercent(percentComplete)
print()
print("Extracted all annotation ID's for selected images.")
# filter out all the non-NONE annotation ids
aidList = []
for gid in GidAidMap.keys():
for aid in filter(lambda x: x != None, GidAidMap[gid]):
aidList = aidList + aid
# Extracts all feature info based on annotation ID's from IBEIS
features = {}
print("Features to be extracted for %d annotation IDs" % len(aidList))
nids = GP.getImageFeature(aidList, "name/rowid")
names = GP.getImageFeature(aidList, "name/text")
species_texts = GP.getImageFeature(aidList, "species/text")
sex_texts = GP.getImageFeature(aidList, "sex/text")
age_months = GP.getImageFeature(aidList, "age/months")
exemplar_flags = GP.getImageFeature(aidList, "exemplar")
quality_texts = GP.getImageFeature(aidList, "quality/text")
yaw_texts = GP.getImageFeature(aidList, "yaw/text")
image_contrib_tags = GP.getImageFeature(aidList, "image/contributor/tag")
features = {aidList[i]: {'nid': nids[i], "name": names[i], "species": species_texts[i], "sex": sex_texts[i],
'age': GP.getAgeFeatureReadableFmt(age_months[i]), 'exemplar': str(exemplar_flags[i]),
'quality': quality_texts[i], 'yaw': yaw_texts[i], 'contributor': image_contrib_tags[i]}
for i in range(0, len(aidList))}
print()
print("All features extracted.")
# Build the all combined file
GidAidFeatures = {}
for gid in GidAidMap.keys():
if GidAidMap[gid][0] == None:
GidAidFeatures[gid] = None
else:
GidAidFeatures[gid] = []
for aid in GidAidMap.get(gid)[0]:
newAidFeatures = {}
newAidFeatures[aid] = features[aid]
GidAidFeatures[gid].append(newAidFeatures)
writeFLTitle, writeFLExt = outFL.split('.csv')
writeFLExt = 'csv'
writeFLGidAidFl = writeFLTitle + "_gid_aid_map." + writeFLExt
writeFLAidFeatureFl = writeFLTitle + "_aid_features." + writeFLExt
writeFLGidAidFeatureFl = writeFLTitle + "_gid_aid_features." + writeFLExt
# Snippet for writing image GID - annotation ID map to a csv file
# head = ['GID','ANNOTATION_ID']
# writeCsvFromDict(head,GidAidMap,writeFLGidAidFl)
# head = ['ANNOTATION_ID','NID','NAME','SPECIES','SEX','AGE_MONTHS','EXEMPLAR_FLAG','IMAGE_QUALITY','IMAGE_YAW']
# writeCsvFromDict(head,features,writeFLAidFeatureFl)
# head = ['GID','ANNOTATION_ID','FEATURES']
# writeCsvFromDict(head,GidAidFeatures,writeFLGidAidFeatureFl)
outFL = open((writeFLTitle + "_gid_aid_map.json"), "w")
json.dump(GidAidMap, outFL, indent=4)
outFL.close()
outFL = open((writeFLTitle + "_aid_features.json"), "w")
json.dump(features, outFL, indent=4)
outFL.close()
outFL = open((writeFLTitle + "_gid_aid_features.json"), "w")
json.dump(GidAidFeatures, outFL, indent=4)
outFL.close()
print("Script completed.")
# these APIs require encoded annot_uuid_list
ggr_eco_ftr_api_map = {'age': "/api/annot/age/months/json",
'sex': "/api/annot/sex/text/json",
'bbox': "/api/annot/bbox/json",
'nid': "/api/annot/name/rowid/json",
'exemplar': "/api/annot/exemplar/json",
'species': "/api/annot/species/json",
'quality': "/api/annot/quality/text/json",
'view_point': "/api/annot/yaw/text/json"
}
# these APIs takes in an encoded gid list
ggr_otr_ftr_api_map = {'contributor': "/api/image/note",
'lat': "/api/image/lat",
'long': "/api/image/lon",
'datetime': "/api/image/unixtime",
'width': "/api/image/width",
'height': "/api/image/height",
'orientation': "/api/image/orientation"
}
def check_time_elapsed(start_time):
if time.time() - start_time >= 1.0:
return True
else:
return False
def build_feature_file_ggr(in_file, out_fl_head, start_count, end_count):
with open(in_file, "r") as in_fl:
img_uuids = list(json.load(in_fl).keys())
# img_uuids = [re.findall(r'(.*).jpg', uuid)[0] for uuid in img_uuids][start_count:end_count+1] # extract the filename without the extension
img_uuids = [uuid for uuid in img_uuids][start_count:end_count + 1]
print("Starting extract: %i to %i" % (start_count, end_count))
start_time = time.time()
uuid_annot_uuid_map = {}
for img_uuid in img_uuids:
uuid_dict = GP.ggr_get("/api/image/annot/uuid/json", GP.ggr_image_form_arg(img_uuid))
if len(uuid_dict['results'][0]) == 0: # case 1: has no annotation
uuid_annot_uuid_map[img_uuid] = [None]
else: # case 2, has 1 or more annot
for annot_dict in uuid_dict['results'][0]:
uuid_annot_uuid_map[img_uuid] = uuid_annot_uuid_map.get(img_uuid, []) + [annot_dict["__UUID__"]]
# elapsed time check
if check_time_elapsed(start_time):
start_time = time.time()
print("100 seconds elapsed..!")
print("Annotation UUIDs extracted")
# logic to flatten out the list of lists
aid_uuid_list = [item for sublist in list(uuid_annot_uuid_map.values()) for item in sublist if item]
start_time = time.time()
aid_uuid_feature_map = {}
for aid in aid_uuid_list:
species = GP.ggr_get(ggr_eco_ftr_api_map['species'], GP.ggr_annot_form_arg(aid))['results'][0]
sex = GP.ggr_get(ggr_eco_ftr_api_map['sex'], GP.ggr_annot_form_arg(aid))['results'][0]
age = GP.getAgeFeatureReadableFmt(
GP.ggr_get(ggr_eco_ftr_api_map['age'], GP.ggr_annot_form_arg(aid))['results'][0])
bbox = GP.ggr_get(ggr_eco_ftr_api_map['bbox'], GP.ggr_annot_form_arg(aid))['results'][0]
exemplar = GP.ggr_get(ggr_eco_ftr_api_map['exemplar'], GP.ggr_annot_form_arg(aid))['results'][0]
nid = GP.ggr_get(ggr_eco_ftr_api_map['nid'], GP.ggr_annot_form_arg(aid))['results'][0]
quality = GP.ggr_get(ggr_eco_ftr_api_map['quality'], GP.ggr_annot_form_arg(aid))['results'][0]
view_point = GP.ggr_get(ggr_eco_ftr_api_map['view_point'], GP.ggr_annot_form_arg(aid))['results'][0]
aid_uuid_feature_map[aid] = dict(sex=sex, age=age, bbox=bbox, exemplar=exemplar, nid=nid, species=species,
view_point=view_point, quality=quality)
if check_time_elapsed(start_time):
start_time = time.time()
print("100 seconds elapsed..!")
print("Feature extraction completed..!")
uuid_annot_uuid_map_fl_nm = out_fl_head + "_uuid_annot_uuid_map.json"
with open(uuid_annot_uuid_map_fl_nm, "w") as uuid_annot_uuid_map_fl:
json.dump(uuid_annot_uuid_map, uuid_annot_uuid_map_fl, indent=4)
annot_uuid_ftr_map_fl_nm = out_fl_head + "_annot_uuid_ftr_map.json"
with open(annot_uuid_ftr_map_fl_nm, "w") as annot_uuid_ftr_map_fl:
json.dump(aid_uuid_feature_map, annot_uuid_ftr_map_fl, indent=4)
return 0
def build_exif_ftrs_fl_ggr(in_file_uuid_gid_map, in_file_uuid_list, out_fl, start, end):
with open(in_file_uuid_gid_map, "r") as in_map_fl:
uuid_gid_map = json.load(in_map_fl)
with open(in_file_uuid_list, "r") as in_list_fl:
uuid_list = in_list_fl.read().split("\n")[start:end + 1]
start_time = time.time()
gid_uuid_exif_ftr_map = {}
for uuid in uuid_list:
gid = uuid_gid_map[uuid]
lat = GP.ggr_get(ggr_otr_ftr_api_map['lat'], GP.ggr_gid_form_arg(gid))['results'][0]
long = GP.ggr_get(ggr_otr_ftr_api_map['long'], GP.ggr_gid_form_arg(gid))['results'][0]
datetime = GP.getUnixTimeReadableFmt(
GP.ggr_get(ggr_otr_ftr_api_map['datetime'], GP.ggr_gid_form_arg(gid))['results'][0])
contributor = GP.ggr_get(ggr_otr_ftr_api_map['contributor'], GP.ggr_gid_form_arg(gid))['results'][0]
height = GP.ggr_get(ggr_otr_ftr_api_map['height'], GP.ggr_gid_form_arg(gid))['results'][0]
width = GP.ggr_get(ggr_otr_ftr_api_map['width'], GP.ggr_gid_form_arg(gid))['results'][0]
orientation = GP.ggr_get(ggr_otr_ftr_api_map['orientation'], GP.ggr_gid_form_arg(gid))['results'][0]
gid_uuid_exif_ftr_map[uuid] = dict(lat=lat, long=long, datetime=datetime, contributor=contributor,
height=height, width=width, orientation=orientation)
if check_time_elapsed(start_time):
start_time = time.time()
print("100 seconds elapsed..!")
with open(out_fl, "w") as uuid_exif_ftr_fl:
json.dump(gid_uuid_exif_ftr_map, uuid_exif_ftr_fl, indent=4)
return 0
def build_reqd_ftrs():
return 0
def __main__():
allGidPart1 = list(map(str, list(range(1, 5000))))
print("Starting feature extraction for GIDs . . .Part1")
buildFeatureFl(allGidPart1, "../data/full1.csv", False)
print("Completed feature extraction . . .Part1")
print("Starting EXIF feature extraction for GIDs . . .Part1")
buildExifFeatureFl(allGidPart1, "../data/imgs_exif_data_full1.json", False)
print("Completed EXIF feature extraction . . .Part1")
allGidPart2 = list(map(str, list(range(5000, 9407))))
print("Starting feature extraction for GIDs . . .Part2")
buildFeatureFl(allGidPart2, "../data/full2.csv", False)
print("Completed feature extraction . . .Part2")
print("Starting EXIF feature extraction for GIDs . . .Part2")
buildExifFeatureFl(allGidPart2, "../data/imgs_exif_data_full2.json", False)
print("Completed EXIF feature extraction . . .Part2")
print("Combining part files to full files")
DS.combineJson("../data/full1_gid_aid_map.json", "../data/full2_gid_aid_map.json", "../data/full_gid_aid_map.json")
DS.combineJson("../data/full1_gid_aid_features.json", "../data/full2_gid_aid_features.json",
"../data/full_gid_aid_features.json")
DS.combineJson("../data/full1_aid_features.json", "../data/full2_aid_features.json",
"../data/full_aid_features.json")
DS.combineJson("../data/imgs_exif_data_full1.json", "../data/imgs_exif_data_full2.json",
"../data/imgs_exif_data_full.json")
def test(start, end, out):
inExifFl, inGidAidMapFl, inAidFtrFl = "../data/ggr_gid_uuid_exif_ftr_map.json", "../data/ggr_uuid_annot_uuid_map.json", "../data/ggr_annot_uuid_ftr_map.json"
with open(inGidAidMapFl, "r") as fl:
obj = json.load(fl)
with open(inAidFtrFl, "r") as fl:
obj2 = json.load(fl)
no_ftr_annots = []
for uuid in obj:
if obj[uuid][0] != None: # there is atleast one aid
for annot_id in obj[uuid]:
# check if annot_id in ftr file
if annot_id not in obj2.keys():
no_ftr_annots.append(annot_id)
print(len(no_ftr_annots))
aid_uuid_feature_map = {}
for aid in no_ftr_annots[start:end]:
species = GP.ggr_get(ggr_eco_ftr_api_map['species'], GP.ggr_annot_form_arg(aid))['results'][0]
sex = GP.ggr_get(ggr_eco_ftr_api_map['sex'], GP.ggr_annot_form_arg(aid))['results'][0]
age = GP.getAgeFeatureReadableFmt(
GP.ggr_get(ggr_eco_ftr_api_map['age'], GP.ggr_annot_form_arg(aid))['results'][0])
bbox = GP.ggr_get(ggr_eco_ftr_api_map['bbox'], GP.ggr_annot_form_arg(aid))['results'][0]
exemplar = GP.ggr_get(ggr_eco_ftr_api_map['exemplar'], GP.ggr_annot_form_arg(aid))['results'][0]
nid = GP.ggr_get(ggr_eco_ftr_api_map['nid'], GP.ggr_annot_form_arg(aid))['results'][0]
quality = GP.ggr_get(ggr_eco_ftr_api_map['quality'], GP.ggr_annot_form_arg(aid))['results'][0]
view_point = GP.ggr_get(ggr_eco_ftr_api_map['view_point'], GP.ggr_annot_form_arg(aid))['results'][0]
aid_uuid_feature_map[aid] = dict(sex=sex, age=age, bbox=bbox, exemplar=exemplar, nid=nid, species=species,
view_point=view_point, quality=quality)
with open(out, "w") as fl:
json.dump(aid_uuid_feature_map, fl, indent=4)
if __name__ == "__main__":
gids = list(map(str, list(range(1, 1862))))
buildFeatureFl(gids, "../data/Flickr_IBEIS_Giraffe_Ftrs.csv", False)
# __main__()
# gidAidMapFl = "../data/full_gid_aid_map.json"
# getAdditionalAnnotFeatures(gidAidMapFl,'bbox',"../data/gid_bbox.json")
# buildBeautyFtrFl("../data/beautyFeatures_GZC_R.csv",['GID','pleasure','arousal','dominance','y'],"../data/beautyFeatures_GZC")
# DS.combineJson("../data/beautyFeatures_GZC.json","../data/imgs_exif_data_full.json","../data/GZC_exifs_beauty_full.json")
# p1 = Process(target=build_exif_ftrs_fl_ggr, args=("uuid_gid_map.json", "ggr_uuid_list.dat", "ggr_exif_extract_1.json",1,5000))
# p2 = Process(target=build_exif_ftrs_fl_ggr, args=("uuid_gid_map.json", "ggr_uuid_list.dat", "ggr_exif_extract_2.json",5001,10000))
# p3 = Process(target=build_exif_ftrs_fl_ggr, args=("uuid_gid_map.json", "ggr_uuid_list.dat", "ggr_exif_extract_3.json",10001,15000))
# p4 = Process(target=build_exif_ftrs_fl_ggr, args=("uuid_gid_map.json", "ggr_uuid_list.dat", "ggr_exif_extract_4.json",15001,20000))
# p5 = Process(target=build_exif_ftrs_fl_ggr, args=("uuid_gid_map.json", "ggr_uuid_list.dat", "ggr_exif_extract_5.json",20001,25000))
# p6 = Process(target=build_exif_ftrs_fl_ggr, args=("uuid_gid_map.json", "ggr_uuid_list.dat", "ggr_exif_extract_6.json",25001,30000))
# p7 = Process(target=build_exif_ftrs_fl_ggr, args=("uuid_gid_map.json", "ggr_uuid_list.dat", "ggr_exif_extract_7.json",30001,35000))
# p8 = Process(target=build_exif_ftrs_fl_ggr, args=("uuid_gid_map.json", "ggr_uuid_list.dat", "ggr_exif_extract_8.json",35001,37433))
# p9 = Process(target=build_feature_file_ggr, args=("uuid_gid_map.json", "ggr_ftr_extract_1",1,5000))
# p10 = Process(target=build_feature_file_ggr, args=("uuid_gid_map.json", "ggr_ftr_extract_2",5001,10000))
# p11 = Process(target=build_feature_file_ggr, args=("uuid_gid_map.json", "ggr_ftr_extract_3",10001,15000))
# p12 = Process(target=build_feature_file_ggr, args=("uuid_gid_map.json", "ggr_ftr_extract_4",15001,20000))
# p13 = Process(target=build_feature_file_ggr, args=("uuid_gid_map.json", "ggr_ftr_extract_5",20001,25000))
# p14 = Process(target=build_feature_file_ggr, args=("uuid_gid_map.json", "ggr_ftr_extract_6",25001,30000))
# p15 = Process(target=build_feature_file_ggr, args=("uuid_gid_map.json", "ggr_ftr_extract_7",30001,35000))
# p16 = Process(target=build_feature_file_ggr, args=("uuid_gid_map.json", "ggr_ftr_extract_8",35001,37433))
# p1 = Process(target=test, args=(0, 400, "/tmp/test1.json"))
# p2 = Process(target=test, args=(400, 800, "/tmp/test2.json"))
# p3 = Process(target=test, args=(800, 1200, "/tmp/test3.json"))
# p4 = Process(target=test, args=(1200, 1600, "/tmp/test4.json"))
# p5 = Process(target=test, args=(1600, 2000, "/tmp/test5.json"))
# p6 = Process(target=test, args=(2000, 2400, "/tmp/test6.json"))
# p7 = Process(target=test, args=(2400, 2800, "/tmp/test7.json"))
# p8 = Process(target=test, args=(2800, 3200, "/tmp/test8.json"))
# p9 = Process(target=test, args=(3200, 3600, "/tmp/test9.json"))
# p10 = Process(target=test, args=(3600, 4033, "/tmp/test10.json"))
# p1.start()
# p2.start()
# p3.start()
# p4.start()
# p5.start()
# p6.start()
# p7.start()
# p8.start()
# p9.start()
# p10.start()
# # p11.start()
# # p12.start()
# # p13.start()
# # p14.start()
# # p15.start()
# # p16.start()
| 15,081 | 0 | 298 |
8e03e376e99bc71cbaabe97c09cb6c6de66197ff | 18,642 | py | Python | component/FileBrowser.py | timothyhalim/nuke-welcome-screen | 563c91c535d8914892fa7c1f8bf29851b8397eb3 | [
"Unlicense"
] | 3 | 2021-04-12T19:17:19.000Z | 2022-03-03T18:23:45.000Z | component/FileBrowser.py | timothyhalim/welcome-screen | 563c91c535d8914892fa7c1f8bf29851b8397eb3 | [
"Unlicense"
] | null | null | null | component/FileBrowser.py | timothyhalim/welcome-screen | 563c91c535d8914892fa7c1f8bf29851b8397eb3 | [
"Unlicense"
] | null | null | null | # TODO
import subprocess
import sys
import os
import re
from glob import glob
try:
from PySide2.QtWidgets import *
from PySide2.QtGui import *
from PySide2.QtCore import *
except:
from PySide.QtGui import *
from PySide.QtCore import * | 35.508571 | 118 | 0.564639 | # TODO
import subprocess
import sys
import os
import re
from glob import glob
try:
from PySide2.QtWidgets import *
from PySide2.QtGui import *
from PySide2.QtCore import *
except:
from PySide.QtGui import *
from PySide.QtCore import *
def getDrives():
platform = sys.platform
if platform.startswith("win"):
drives = []
keys = None
driveTypes = [
"Unknown",
"No Root Directory",
"Removable Disk",
"Local Disk",
"Network Drive",
"Compact Disc",
"RAM Disk"
]
startupinfo = subprocess.STARTUPINFO()
startupinfo.dwFlags |= subprocess.STARTF_USESHOWWINDOW
argument = " ".join(["wmic", "logicaldisk", "get", "/format:csv"])
result = subprocess.Popen(
argument,
stdout=subprocess.PIPE,
stdin=subprocess.PIPE,
stderr=subprocess.PIPE,
startupinfo=startupinfo,
universal_newlines=True
)
for line in result.stdout.readlines():
if line in ["", "\n"]: continue
splits = line.split(",")
if keys is None:
keys = splits
if splits != keys:
letter = splits[keys.index("Caption")]
driveType = splits[keys.index("DriveType")]
drivePath = splits[keys.index("ProviderName")]
driveName = splits[keys.index("VolumeName")]
drive = QFileInfo(letter+"/")
drive.driveType = driveTypes[int(driveType)]
drive.driveName = drivePath if drivePath else driveName if driveName else driveTypes[int(driveType)]
drives.append(drive)
elif platform.startswith("linux"):
drives = QDir.drives()
elif platform == "darwin":
drives = QDir.drives()
return drives
def reconnect(signal, newhandler=None, oldhandler=None):
try:
if oldhandler is not None:
while True:
signal.disconnect(oldhandler)
else:
signal.disconnect()
except:
pass
if newhandler is not None:
signal.connect(newhandler)
class PathBar(QLineEdit):
upPressed = Signal()
downPressed = Signal()
def __init__(self, parent=None):
super(PathBar, self).__init__(parent)
def keyPressEvent(self, event):
if event.key() == Qt.Key_Up:
self.upPressed.emit()
elif event.key() == Qt.Key_Down:
self.downPressed.emit()
else:
super(PathBar, self).keyPressEvent(event)
class FileModel(QAbstractTableModel):
rootPathChanged = Signal(str, str)
def __init__(self, root=""):
super(FileModel, self).__init__()
self._qdir = QDir()
self._qdir.setFilter(QDir.NoDot | QDir.Files | QDir.AllDirs)
self._headers = ("Filename", "Size", "Type", "Modified")
self._icons = QFileIconProvider()
self._qdir.setPath(root)
self.refresh()
self.rootPathChanged.emit(root, "")
def rowFromFilePath(self, path):
path = path + "/" if path.endswith(":") else path
path = os.path.abspath(path).replace("\\", "/")
# Search for case sensitive first
for row in range(self.rowCount()):
if self._data[row].absoluteFilePath() == path:
return row
# Search for case insensitive
for row in range(self.rowCount()):
if self._data[row].absoluteFilePath().lower() == path.lower():
return row
return 0
def filePathFromIndex(self, index):
row = index.row()
return self._data[row].filePath()
def rootPath(self):
return self._qdir.path()
def fixCase(self, path):
unc, p = os.path.splitdrive(path)
unc = unc.upper() if ":" in unc else unc
r = glob(unc + re.sub(r'([^:/\\])(?=[/\\]|$)', r'[\1]', p))
return r and r[0] or path
def setRootPath(self, path):
if os.path.isfile(path):
path = os.path.dirname(path)
if path == "" or os.path.isdir(path):
prevRoot = self.rootPath()
if path:
if re.search("[a-zA-Z]:/\.\.$", path):
path = ""
else:
if path.endswith(":"):
path += "/"
path = os.path.abspath(path).replace("\\", "/")
path = self.fixCase(path)
if path != self.rootPath():
self._data = []
self.beginResetModel()
self._qdir.setPath(path)
self._data = self._qdir.entryInfoList() if path else self._drives
backPath = os.path.join(self.rootPath(), "..").replace("\\", "/")
if not backPath in [d.filePath() for d in self._data] and self.rootPath() != "":
self._data.insert(0, QFileInfo(backPath))
self.endResetModel()
self.rootPathChanged.emit(self.rootPath(), prevRoot)
def refresh(self):
self._drives = getDrives()
self._qdir.refresh()
self.beginResetModel()
self.endResetModel()
self._data = self._qdir.entryInfoList() if self.rootPath() else self._drives
def setFilter(self, filter):
self._qdir.setFilter(filter)
def setNameFilters(self, filter):
self._qdir.setNameFilters(filter)
def headerData(self, section, orientation, role):
if (orientation == Qt.Horizontal):
if role == Qt.TextAlignmentRole:
if section >= 1:
return int(Qt.AlignRight | Qt.AlignVCenter)
else:
return int(Qt.AlignLeft | Qt.AlignVCenter)
elif role == Qt.DisplayRole:
return self._headers[section]
return super(FileModel, self).headerData(section, orientation, role=role)
def data(self, index, role):
row = index.row()
column = index.column()
data = self._data[row]
if role == Qt.DisplayRole:
if column == 0:
if data.isRoot():
try:
return "{0} ({1})".format(data.driveName, data.absolutePath())
except:
return data.absolutePath()
if data.fileName():
return data.fileName()
else:
return data.absolutePath()
elif column == 1:
if data.isFile():
factor = 1024
size = data.size()
for unit in ["", "K", "M", "G", "T", "P"]:
if size < factor:
return "{0:.2f} {1}B".format(size, unit)
size /= factor
elif column == 2:
if data.isRoot():
try:
return data.driveType
except:
pass
return self._icons.type(data)
elif column == 3:
return data.lastModified()
elif role == Qt.DecorationRole:
if column == 0:
if data.filePath().endswith("/..") and data.isDir():
return QIcon(QApplication.style().standardIcon(QStyle.SP_FileDialogBack))
return self._icons.icon(data)
elif role == Qt.TextAlignmentRole:
if column >= 1:
return int(Qt.AlignRight | Qt.AlignVCenter)
else:
return int(Qt.AlignLeft | Qt.AlignVCenter)
def sort(self, col, order):
self.emit(SIGNAL("layoutAboutToBeChanged()"))
if col == 0:
if self.rootPath():
self._data = sorted(self._data, key=lambda x : x.fileName())
else:
self._data = sorted(self._data, key=lambda x : x.absolutePath())
elif col == 1:
self._data = sorted(self._data, key=lambda x : x.size())
elif col == 2:
if self.rootPath():
self._data = sorted(self._data, key=lambda x : self._icons.type(x))
else:
self._data = sorted(self._data, key=lambda x : x.driveType)
elif col == 3:
self._data = sorted(self._data, key=lambda x : x.lastModified())
if order == Qt.DescendingOrder:
self._data.reverse()
self.emit(SIGNAL("layoutChanged()"))
def rowCount(self, index=None):
return len(self._data)
def columnCount(self, index=None):
return len(self._headers)
def getFiles(self):
return [d.absoluteFilePath() for d in self._data]
class FileList(QTableView):
pathSelected = Signal(str)
rootChanged = Signal(str)
executed = Signal(str)
def __init__(self, parent=None, filterExtension=[]):
super(FileList, self).__init__(parent)
self.setAttribute(Qt.WA_DeleteOnClose)
self.path = ""
self.prev = ""
self.target = ""
self.filterExtension = filterExtension
# Model
self.fileModel = FileModel()
self.fileModel.setFilter(QDir.NoDot | QDir.Files | QDir.AllDirs)
if self.filterExtension:
self.fileModel.setNameFilters(self.filterExtension)
self.setModel(self.fileModel)
self.tableSelectionModel = self.selectionModel()
# Gui
self.verticalHeader().setVisible(False)
self.verticalHeader().setDefaultSectionSize(24)
self.setSelectionBehavior(QAbstractItemView.SelectRows)
self.setSelectionMode(QAbstractItemView.SingleSelection)
self.setShowGrid(False)
self.setSortingEnabled(True)
self.sortByColumn(0, Qt.AscendingOrder)
header = self.horizontalHeader()
try:
header.setSectionResizeMode(0, QHeaderView.Stretch)
except:
header.setResizeMode(0, QHeaderView.Stretch)
self.setColumnWidth(1,80)
self.setColumnWidth(2,80)
self.setColumnWidth(3,150)
# Signal
self.fileModel.rootPathChanged.connect(self.onRootChanged)
self.tableSelectionModel.currentChanged.connect(self.onSelectionChanged)
self.doubleClicked.connect(self.onDoubleClick)
self.setRoot("")
self.fileModel.rootPathChanged.emit("", "")
def isdrive(self, path):
path = path.replace("\\", "/")
drives = [d.filePath().lower() for d in QDir.drives()]
return path.lower() in drives
def root(self):
return self.fileModel.rootPath()
def setRoot(self, path):
self.fileModel.setRootPath(path)
def onRootChanged(self, newPath, oldPath):
index = self.fileModel.index(0, 0)
filepath = self.fileModel.filePathFromIndex(index)
if newPath != oldPath:
if newPath in oldPath or newPath == "":
prevselection = [f for f in oldPath.replace(newPath, "").split("/") if f]
if prevselection:
filepath = os.path.join(newPath, prevselection[0])
self.selectPath(filepath)
self.rootChanged.emit(newPath)
def onSelectionChanged(self, current, prev):
self.path = self.fileModel.filePathFromIndex(current)
self.pathSelected.emit(self.path)
def onDoubleClick(self, index=None):
self.execute()
def execute(self):
if self.path.endswith("..") and self.isdrive(self.path.replace("..", "")):
self.setRoot("")
elif os.path.isdir(self.path) or self.isdrive(self.path):
self.setRoot(self.path)
elif os.path.isfile(self.path):
self.executed.emit(self.path)
def selectPath(self, path):
self.selectRow(self.fileModel.rowFromFilePath(path))
def selectIndex(self, index):
self.tableSelectionModel.setCurrentIndex(index, QItemSelectionModel.Rows | QItemSelectionModel.ClearAndSelect)
self.tableSelectionModel.select(index, QItemSelectionModel.Rows | QItemSelectionModel.ClearAndSelect)
self.scrollTo(index)
def selectRow(self, row):
row = max(row, 0)
row = min(row, self.fileModel.rowCount()-1)
index = self.fileModel.index(row, 0)
self.selectIndex(index)
def selectPrev(self):
currentRow = self.currentIndex().row()
self.selectRow(currentRow-1)
def selectNext(self):
currentRow = self.currentIndex().row()
self.selectRow(currentRow+1)
def getFiles(self):
return self.fileModel.getFiles()
def keyPressEvent(self, event):
if event.key() == Qt.Key_Return:
self.execute()
elif event.key() == Qt.Key_Backspace:
if self.fileModel.rootPath():
root = os.path.abspath(self.fileModel.rootPath())
paths = [d for d in root.split("\\") if d]
if len(paths) > 1:
parentdir = "/".join(paths+[".."])
else:
parentdir = ""
self.setRoot(parentdir)
elif event.key() == Qt.Key_F5:
index = self.currentIndex()
self.fileModel.refresh()
self.selectIndex(index)
elif event.key() == Qt.Key_Tab:
if self.parent():
siblings = [w for w in self.parent().findChildren(QWidget) if w.parent() == self.parent()]
currentIndex = -1
for i, sibling in enumerate(siblings):
if sibling == self:
currentIndex = i
siblings.pop(i)
break
siblings[currentIndex].setFocus()
else:
super(FileList, self).keyPressEvent(event)
class FileBrowser(QWidget):
executed = Signal(str)
def __init__(self, parent=None, filterExtension=[], exeLabel="Open", title="Open File"):
QWidget.__init__(self, parent=None)
self.setAttribute(Qt.WA_DeleteOnClose)
self.fileList = FileList(filterExtension=filterExtension)
self.fileLayout = QHBoxLayout()
self.currentPath = PathBar()
self.currentPath.setPlaceholderText("File Path")
self.exeButton = QPushButton(exeLabel)
self.fileLayout.addWidget(self.currentPath)
self.fileLayout.addWidget(self.exeButton)
self.mainLayout = QVBoxLayout(self)
self.mainLayout.setContentsMargins(0,0,0,0)
self.mainLayout.addWidget(self.fileList)
self.mainLayout.addLayout(self.fileLayout)
for l in [self.currentPath]:
l.setFixedHeight(26)
self.currentPath.textChanged.connect(self.onTextChanged)
self.currentPath.returnPressed.connect(self.execute)
self.currentPath.upPressed.connect(self.selectPrev)
self.currentPath.downPressed.connect(self.selectNext)
self.fileList.rootChanged.connect(self.onRootChanged)
self.fileList.pathSelected.connect(self.onPathChanged)
self.fileList.executed.connect(self.execute)
self.exeButton.clicked.connect(self.execute)
self.exeButton.setMinimumWidth(70)
self.onPathChanged(self.fileList.path)
self.currentPath.installEventFilter(self)
self.fileList.installEventFilter(self)
self.exeButton.installEventFilter(self)
self.lastFocus = None
def eventFilter(self, source, event):
if event.type() == QEvent.FocusOut:
if source != self.lastFocus :
self.lastFocus = source
if source is self.currentPath:
if (event.type() == QEvent.FocusOut):
reconnect(self.fileList.pathSelected, self.onPathChanged)
self.validatePath()
elif (event.type() == QEvent.FocusIn):
reconnect(self.fileList.pathSelected)
elif source is self.fileList:
if (event.type() == QEvent.FocusOut):
reconnect(self.currentPath.textChanged, self.onTextChanged)
elif (event.type() == QEvent.FocusIn):
reconnect(self.currentPath.textChanged)
return super(FileBrowser, self).eventFilter(source, event)
def validatePath(self):
self.changeCurrentPath(self.fileList.path)
def onRootChanged(self):
root = self.fileList.root()
currentText = self.currentPath.text()
self.changeCurrentPath(root+currentText[len(root):])
def cleanupPath(self, path):
search = re.search("^\"(.*?)\"$", path)
if search:
path = search.group(1)
search = re.search("(.*?)\.\.$", path)
if search:
path = search.group(1)
path = path.replace("\\", "/")
return path
def changeCurrentPath(self, path):
reconnect(self.currentPath.textChanged)
path = self.cleanupPath(path)
self.currentPath.setText(path)
reconnect(self.currentPath.textChanged, self.onTextChanged)
def onPathChanged(self, path):
path = self.cleanupPath(path)
self.changeCurrentPath(path)
def onTextChanged(self):
if self.currentPath.text():
cp = self.currentPath.text()
if re.search("^\"(.*?)\"$", cp) or re.search("(.*?)\.\.$", cp):
self.currentPath.setText(self.cleanupPath(cp))
splits = cp.split("/")
path = "/".join(splits[:-1]) if len(splits) > 1 else cp + "/"
self.setRoot(path)
files = [f.lower() for f in self.files]
for file in files:
if cp.lower() in file:
self.selectPath(file)
break
else:
self.setRoot("")
def selectPrev(self):
self.fileList.selectPrev()
self.changeCurrentPath(self.fileList.path)
def selectNext(self):
self.fileList.selectNext()
self.changeCurrentPath(self.fileList.path)
def selectPath(self, path):
self.fileList.selectPath(path)
def setRoot(self, path):
if path != self.fileList.root():
self.fileList.setRoot(path)
self.files = self.fileList.getFiles()
def execute(self):
if os.path.isfile(self.fileList.path):
self.executed.emit(self.fileList.path)
else:
self.setRoot(self.fileList.path)
self.changeCurrentPath(self.fileList.path) | 16,763 | 1,468 | 146 |
f3167a11f305bd52e84dacb04f8a81a811d44393 | 8,784 | py | Python | NightlyTests/tensorflow/test_adaround.py | aaronkjones/aimet | 08feb34573281f87c53301935652a02f8d573858 | [
"BSD-3-Clause"
] | null | null | null | NightlyTests/tensorflow/test_adaround.py | aaronkjones/aimet | 08feb34573281f87c53301935652a02f8d573858 | [
"BSD-3-Clause"
] | null | null | null | NightlyTests/tensorflow/test_adaround.py | aaronkjones/aimet | 08feb34573281f87c53301935652a02f8d573858 | [
"BSD-3-Clause"
] | null | null | null | # /usr/bin/env python3.6
# -*- mode: python -*-
# =============================================================================
# @@-COPYRIGHT-START-@@
#
# Copyright (c) 2021, Qualcomm Innovation Center, Inc. All rights reserved.
#
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions are met:
#
# 1. Redistributions of source code must retain the above copyright notice,
# this list of conditions and the following disclaimer.
#
# 2. Redistributions in binary form must reproduce the above copyright notice,
# this list of conditions and the following disclaimer in the documentation
# and/or other materials provided with the distribution.
#
# 3. Neither the name of the copyright holder nor the names of its contributors
# may be used to endorse or promote products derived from this software
# without specific prior written permission.
#
# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
# AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
# IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
# ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE
# LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
# CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
# SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
# INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
# CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
# ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
# POSSIBILITY OF SUCH DAMAGE.
#
# SPDX-License-Identifier: BSD-3-Clause
#
# @@-COPYRIGHT-END-@@
# =============================================================================
""" AdaRound Nightly Tests """
import pytest
import json
import unittest
import logging
import os
os.environ['TF_CPP_MIN_LOG_LEVEL'] = '2'
import numpy as np
import tensorflow as tf
from tensorflow.keras.applications.mobilenet import MobileNet
from packaging import version
from aimet_common.utils import AimetLogger
from aimet_common.defs import QuantScheme
from aimet_tensorflow.examples.test_models import keras_model
from aimet_tensorflow.quantsim import QuantizationSimModel
from aimet_tensorflow.adaround.adaround_weight import Adaround, AdaroundParameters
tf.compat.v1.disable_eager_execution()
class AdaroundAcceptanceTests(unittest.TestCase):
"""
AdaRound test cases
"""
@pytest.mark.cuda
def test_adaround_mobilenet_only_weights(self):
""" test end to end adaround with only weight quantized """
def dummy_forward_pass(session: tf.compat.v1.Session):
""" Dummy forward pass """
input_data = np.random.rand(1, 224, 224, 3)
input_tensor = session.graph.get_tensor_by_name('input_1:0')
output_tensor = session.graph.get_tensor_by_name('conv_preds/BiasAdd:0')
output = session.run(output_tensor, feed_dict={input_tensor: input_data})
return output
AimetLogger.set_level_for_all_areas(logging.DEBUG)
tf.compat.v1.reset_default_graph()
_ = MobileNet(weights=None, input_shape=(224, 224, 3))
init = tf.compat.v1.global_variables_initializer()
dataset_size = 128
batch_size = 64
possible_batches = dataset_size // batch_size
input_data = np.random.rand(dataset_size, 224, 224, 3)
dataset = tf.data.Dataset.from_tensor_slices(input_data)
dataset = dataset.batch(batch_size=batch_size)
session = tf.compat.v1.Session(graph=tf.compat.v1.get_default_graph())
session.run(init)
params = AdaroundParameters(data_set=dataset, num_batches=possible_batches, default_num_iterations=1,
default_reg_param=0.01, default_beta_range=(20, 2), default_warm_start=0.2)
starting_op_names = ['input_1']
if version.parse(tf.version.VERSION) >= version.parse("2.00"):
output_op_names = ['predictions/Softmax']
else:
output_op_names = ['act_softmax/Softmax']
adarounded_session = Adaround.apply_adaround(session, starting_op_names, output_op_names, params, path='./',
filename_prefix='mobilenet', default_param_bw=4,
default_quant_scheme=QuantScheme.post_training_tf_enhanced)
orig_output = dummy_forward_pass(session)
adarounded_output = dummy_forward_pass(adarounded_session)
self.assertEqual(orig_output.shape, adarounded_output.shape)
# Test exported encodings JSON file
with open('./mobilenet.encodings') as json_file:
encoding_data = json.load(json_file)
print(encoding_data)
self.assertTrue(isinstance(encoding_data["conv1/Conv2D/ReadVariableOp:0"], list))
session.close()
adarounded_session.close()
# Delete encodings JSON file
if os.path.exists("./mobilenet.encodings"):
os.remove("./mobilenet.encodings")
def test_adaround_resnet18_followed_by_quantsim(self):
""" test end to end adaround with weight 4 bits and output activations 8 bits quantized """
def dummy_forward_pass(session: tf.compat.v1.Session, _):
""" Dummy forward pass """
input_data = np.random.rand(32, 16, 16, 3)
input_tensor = session.graph.get_tensor_by_name('conv2d_input:0')
output_tensor = session.graph.get_tensor_by_name('keras_model/Softmax:0')
output = session.run(output_tensor, feed_dict={input_tensor: input_data})
return output
np.random.seed(1)
AimetLogger.set_level_for_all_areas(logging.DEBUG)
tf.compat.v1.reset_default_graph()
_ = keras_model()
init = tf.compat.v1.global_variables_initializer()
dataset_size = 32
batch_size = 16
possible_batches = dataset_size // batch_size
input_data = np.random.rand(dataset_size, 16, 16, 3)
dataset = tf.data.Dataset.from_tensor_slices(input_data)
dataset = dataset.batch(batch_size=batch_size)
session = tf.compat.v1.Session(graph=tf.compat.v1.get_default_graph())
session.run(init)
params = AdaroundParameters(data_set=dataset, num_batches=possible_batches, default_num_iterations=10)
starting_op_names = ['conv2d_input']
output_op_names = ['keras_model/Softmax']
# W4A8
param_bw = 4
output_bw = 8
quant_scheme = QuantScheme.post_training_tf_enhanced
adarounded_session = Adaround.apply_adaround(session, starting_op_names, output_op_names, params, path='./',
filename_prefix='dummy', default_param_bw=param_bw,
default_quant_scheme=quant_scheme, default_config_file=None)
# Read exported param encodings JSON file
with open('./dummy.encodings') as json_file:
encoding_data = json.load(json_file)
encoding = encoding_data["conv2d/Conv2D/ReadVariableOp:0"][0]
before_min, before_max, before_delta, before_offset = encoding.get('min'), encoding.get('max'), \
encoding.get('scale'), encoding.get('offset')
print(before_min, before_max, before_delta, before_offset)
# Create QuantSim using adarounded_model, set and freeze parameter encodings and then invoke compute_encodings
sim = QuantizationSimModel(adarounded_session, starting_op_names, output_op_names, quant_scheme,
default_output_bw=output_bw, default_param_bw=param_bw, use_cuda=False)
sim.set_and_freeze_param_encodings(encoding_path='./dummy.encodings')
sim.compute_encodings(dummy_forward_pass, None)
quantizer = sim.quantizer_config('conv2d/Conv2D/ReadVariableOp_quantized')
encoding = quantizer.get_encoding()
after_min, after_max, after_delta, after_offset = encoding.min, encoding.max, encoding.delta, encoding.offset
print(after_min, after_max, after_delta, after_offset)
self.assertEqual(before_min, after_min)
self.assertEqual(before_max, after_max)
self.assertAlmostEqual(before_delta, after_delta, places=4)
self.assertEqual(before_offset, after_offset)
session.close()
adarounded_session.close()
# Delete encodings file
if os.path.exists("./dummy.encodings"):
os.remove("./dummy.encodings")
| 44.588832 | 118 | 0.677026 | # /usr/bin/env python3.6
# -*- mode: python -*-
# =============================================================================
# @@-COPYRIGHT-START-@@
#
# Copyright (c) 2021, Qualcomm Innovation Center, Inc. All rights reserved.
#
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions are met:
#
# 1. Redistributions of source code must retain the above copyright notice,
# this list of conditions and the following disclaimer.
#
# 2. Redistributions in binary form must reproduce the above copyright notice,
# this list of conditions and the following disclaimer in the documentation
# and/or other materials provided with the distribution.
#
# 3. Neither the name of the copyright holder nor the names of its contributors
# may be used to endorse or promote products derived from this software
# without specific prior written permission.
#
# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
# AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
# IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
# ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE
# LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
# CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
# SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
# INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
# CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
# ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
# POSSIBILITY OF SUCH DAMAGE.
#
# SPDX-License-Identifier: BSD-3-Clause
#
# @@-COPYRIGHT-END-@@
# =============================================================================
""" AdaRound Nightly Tests """
import pytest
import json
import unittest
import logging
import os
os.environ['TF_CPP_MIN_LOG_LEVEL'] = '2'
import numpy as np
import tensorflow as tf
from tensorflow.keras.applications.mobilenet import MobileNet
from packaging import version
from aimet_common.utils import AimetLogger
from aimet_common.defs import QuantScheme
from aimet_tensorflow.examples.test_models import keras_model
from aimet_tensorflow.quantsim import QuantizationSimModel
from aimet_tensorflow.adaround.adaround_weight import Adaround, AdaroundParameters
tf.compat.v1.disable_eager_execution()
class AdaroundAcceptanceTests(unittest.TestCase):
"""
AdaRound test cases
"""
@pytest.mark.cuda
def test_adaround_mobilenet_only_weights(self):
""" test end to end adaround with only weight quantized """
def dummy_forward_pass(session: tf.compat.v1.Session):
""" Dummy forward pass """
input_data = np.random.rand(1, 224, 224, 3)
input_tensor = session.graph.get_tensor_by_name('input_1:0')
output_tensor = session.graph.get_tensor_by_name('conv_preds/BiasAdd:0')
output = session.run(output_tensor, feed_dict={input_tensor: input_data})
return output
AimetLogger.set_level_for_all_areas(logging.DEBUG)
tf.compat.v1.reset_default_graph()
_ = MobileNet(weights=None, input_shape=(224, 224, 3))
init = tf.compat.v1.global_variables_initializer()
dataset_size = 128
batch_size = 64
possible_batches = dataset_size // batch_size
input_data = np.random.rand(dataset_size, 224, 224, 3)
dataset = tf.data.Dataset.from_tensor_slices(input_data)
dataset = dataset.batch(batch_size=batch_size)
session = tf.compat.v1.Session(graph=tf.compat.v1.get_default_graph())
session.run(init)
params = AdaroundParameters(data_set=dataset, num_batches=possible_batches, default_num_iterations=1,
default_reg_param=0.01, default_beta_range=(20, 2), default_warm_start=0.2)
starting_op_names = ['input_1']
if version.parse(tf.version.VERSION) >= version.parse("2.00"):
output_op_names = ['predictions/Softmax']
else:
output_op_names = ['act_softmax/Softmax']
adarounded_session = Adaround.apply_adaround(session, starting_op_names, output_op_names, params, path='./',
filename_prefix='mobilenet', default_param_bw=4,
default_quant_scheme=QuantScheme.post_training_tf_enhanced)
orig_output = dummy_forward_pass(session)
adarounded_output = dummy_forward_pass(adarounded_session)
self.assertEqual(orig_output.shape, adarounded_output.shape)
# Test exported encodings JSON file
with open('./mobilenet.encodings') as json_file:
encoding_data = json.load(json_file)
print(encoding_data)
self.assertTrue(isinstance(encoding_data["conv1/Conv2D/ReadVariableOp:0"], list))
session.close()
adarounded_session.close()
# Delete encodings JSON file
if os.path.exists("./mobilenet.encodings"):
os.remove("./mobilenet.encodings")
def test_adaround_resnet18_followed_by_quantsim(self):
""" test end to end adaround with weight 4 bits and output activations 8 bits quantized """
def dummy_forward_pass(session: tf.compat.v1.Session, _):
""" Dummy forward pass """
input_data = np.random.rand(32, 16, 16, 3)
input_tensor = session.graph.get_tensor_by_name('conv2d_input:0')
output_tensor = session.graph.get_tensor_by_name('keras_model/Softmax:0')
output = session.run(output_tensor, feed_dict={input_tensor: input_data})
return output
np.random.seed(1)
AimetLogger.set_level_for_all_areas(logging.DEBUG)
tf.compat.v1.reset_default_graph()
_ = keras_model()
init = tf.compat.v1.global_variables_initializer()
dataset_size = 32
batch_size = 16
possible_batches = dataset_size // batch_size
input_data = np.random.rand(dataset_size, 16, 16, 3)
dataset = tf.data.Dataset.from_tensor_slices(input_data)
dataset = dataset.batch(batch_size=batch_size)
session = tf.compat.v1.Session(graph=tf.compat.v1.get_default_graph())
session.run(init)
params = AdaroundParameters(data_set=dataset, num_batches=possible_batches, default_num_iterations=10)
starting_op_names = ['conv2d_input']
output_op_names = ['keras_model/Softmax']
# W4A8
param_bw = 4
output_bw = 8
quant_scheme = QuantScheme.post_training_tf_enhanced
adarounded_session = Adaround.apply_adaround(session, starting_op_names, output_op_names, params, path='./',
filename_prefix='dummy', default_param_bw=param_bw,
default_quant_scheme=quant_scheme, default_config_file=None)
# Read exported param encodings JSON file
with open('./dummy.encodings') as json_file:
encoding_data = json.load(json_file)
encoding = encoding_data["conv2d/Conv2D/ReadVariableOp:0"][0]
before_min, before_max, before_delta, before_offset = encoding.get('min'), encoding.get('max'), \
encoding.get('scale'), encoding.get('offset')
print(before_min, before_max, before_delta, before_offset)
# Create QuantSim using adarounded_model, set and freeze parameter encodings and then invoke compute_encodings
sim = QuantizationSimModel(adarounded_session, starting_op_names, output_op_names, quant_scheme,
default_output_bw=output_bw, default_param_bw=param_bw, use_cuda=False)
sim.set_and_freeze_param_encodings(encoding_path='./dummy.encodings')
sim.compute_encodings(dummy_forward_pass, None)
quantizer = sim.quantizer_config('conv2d/Conv2D/ReadVariableOp_quantized')
encoding = quantizer.get_encoding()
after_min, after_max, after_delta, after_offset = encoding.min, encoding.max, encoding.delta, encoding.offset
print(after_min, after_max, after_delta, after_offset)
self.assertEqual(before_min, after_min)
self.assertEqual(before_max, after_max)
self.assertAlmostEqual(before_delta, after_delta, places=4)
self.assertEqual(before_offset, after_offset)
session.close()
adarounded_session.close()
# Delete encodings file
if os.path.exists("./dummy.encodings"):
os.remove("./dummy.encodings")
| 0 | 0 | 0 |
61205a6832b5abb6004146fd516d3addbef0ffaf | 1,888 | py | Python | test/test_7.py | rgooler/AOC2019 | f761881240a5fe8711f730887f0f5033ea287e3d | [
"Apache-2.0"
] | null | null | null | test/test_7.py | rgooler/AOC2019 | f761881240a5fe8711f730887f0f5033ea287e3d | [
"Apache-2.0"
] | null | null | null | test/test_7.py | rgooler/AOC2019 | f761881240a5fe8711f730887f0f5033ea287e3d | [
"Apache-2.0"
] | null | null | null | import unittest
import logging
logging.basicConfig(level=logging.CRITICAL)
from aoc2019 import Amplifier
| 40.170213 | 191 | 0.603284 | import unittest
import logging
logging.basicConfig(level=logging.CRITICAL)
from aoc2019 import Amplifier
class Day7(unittest.TestCase):
def test_part1_a(self):
phase_sequence = [4,3,2,1,0]
code = [3,15,3,16,1002,16,10,16,1,16,15,15,4,15,99,0,0]
chall = Amplifier(code=code, enable_logs=False)
r = chall.run(phase_sequence)
self.assertEqual(r, 43210)
del chall
def test_part1_b(self):
phase_sequence = [0,1,2,3,4]
code = [3,23,3,24,1002,24,10,24,1002,23,-1,23,101,5,23,23,1,24,23,23,4,23,99,0,0]
chall = Amplifier(code=code, enable_logs=False)
r = chall.run(phase_sequence)
self.assertEqual(r, 54321)
del chall
def test_part1_c(self):
phase_sequence = [1,0,4,3,2]
code = [3,31,3,32,1002,32,10,32,1001,31,-2,31,1007,31,0,33,1002,33,7,33,1,33,31,31,1,32,31,31,4,31,99,0,0,0]
chall = Amplifier(code=code, enable_logs=False)
r = chall.run(phase_sequence)
self.assertEqual(r, 65210)
del chall
def test_part2_a(self):
# Skip this test for being slow
return
phase_sequence = [9,8,7,6,5]
code = [3,26,1001,26,-4,26,3,27,1002,27,2,27,1,27,26,27,4,27,1001,28,-1,28,1005,28,6,99,0,0,5]
chall = Amplifier(code=code, enable_logs=False)
r = chall.run_feedback(phase_sequence)
self.assertEqual(r, 139629729)
del chall
def test_part2_b(self):
phase_sequence = [9,7,8,5,6]
code = [3,52,1001,52,-5,52,3,53,1,52,56,54,1007,54,5,55,1005,55,26,1001,54,-5,54,1105,1,12,1,53,54,53,1008,54,0,55,1001,55,1,55,2,53,55,53,4,53,1001,56,-1,56,1005,56,6,99,0,0,0,0,10]
chall = Amplifier(code=code, enable_logs=False)
r = chall.run_feedback(phase_sequence)
self.assertEqual(r, 18216)
del chall | 1,604 | 9 | 167 |
7012f9d95fc65ac47f73e994b77273ec96e31638 | 2,015 | py | Python | crawling scripts/uber_eats.py | kulten/Restaurant-search-engine | ba9d90c5f97f3360757aa7e60d4e9a349943dab9 | [
"MIT"
] | null | null | null | crawling scripts/uber_eats.py | kulten/Restaurant-search-engine | ba9d90c5f97f3360757aa7e60d4e9a349943dab9 | [
"MIT"
] | null | null | null | crawling scripts/uber_eats.py | kulten/Restaurant-search-engine | ba9d90c5f97f3360757aa7e60d4e9a349943dab9 | [
"MIT"
] | null | null | null | import time
from selenium import webdriver
import json
from crawlpack.helpers import id_gen, connect
chrome_options = webdriver.ChromeOptions()
chrome_options.add_experimental_option( "prefs",{'profile.managed_default_content_settings.javascript': 2})
driver = webdriver.Chrome(chrome_options=chrome_options)
conn, cur = connect()
for count in range(1,89):
try:
url = "file:///home/Desktop/crawler%20scripts/scripts/uber_eats/page_source"+str(count)+".html"
driver.get(url)
raw_title = driver.find_element_by_xpath('//*[@id="app-content"]/div/div/div[1]/div/div[1]/div[2]/div/div[2]/div/div/h1').text
try:
split_title = raw_title.split('-')
rest_name = split_title[0].strip()
location = split_title[1].strip()
except:
rest_name = raw_title
location = "Bangalore"
dedupe_id = id_gen(rest_name,location)
items = driver.find_elements_by_css_selector('#app-content>div>div>div:nth-child(1)>div>div:nth-child(1)>div:nth-child(2)>div>div:nth-child(3)>div:nth-child(2)>div:nth-child(1)>div>div:nth-child(2)>div>div>div>div:nth-child(1)>div:nth-child(1)')
prices = driver.find_elements_by_css_selector('#app-content>div>div>div:nth-child(1)>div>div:nth-child(1)>div:nth-child(2)>div>div:nth-child(3)>div:nth-child(2)>div:nth-child(1)>div>div:nth-child(2)>div>div>div>div:nth-child(1)>div:nth-child(3)>span:nth-child(1)')
items_final = {}
num_items = len(items)
for i in range(0,num_items):
item_price = prices[i].text.replace("INR","")
item_name = items[i].text
items_final[item_name] = item_price
items_json = json.dumps(items_final)
cur.execute("""INSERT INTO uber_eats2 (name,location,items) VALUES (%s,%s,%s)""",(rest_name,location,items_json))
conn.commit()
print("Crawled {0}/88 Restaurant: {1} Items: {2}".format(count,rest_name,str(len(items_final))))
except:
print("error ",url)
| 51.666667 | 272 | 0.665509 | import time
from selenium import webdriver
import json
from crawlpack.helpers import id_gen, connect
chrome_options = webdriver.ChromeOptions()
chrome_options.add_experimental_option( "prefs",{'profile.managed_default_content_settings.javascript': 2})
driver = webdriver.Chrome(chrome_options=chrome_options)
conn, cur = connect()
for count in range(1,89):
try:
url = "file:///home/Desktop/crawler%20scripts/scripts/uber_eats/page_source"+str(count)+".html"
driver.get(url)
raw_title = driver.find_element_by_xpath('//*[@id="app-content"]/div/div/div[1]/div/div[1]/div[2]/div/div[2]/div/div/h1').text
try:
split_title = raw_title.split('-')
rest_name = split_title[0].strip()
location = split_title[1].strip()
except:
rest_name = raw_title
location = "Bangalore"
dedupe_id = id_gen(rest_name,location)
items = driver.find_elements_by_css_selector('#app-content>div>div>div:nth-child(1)>div>div:nth-child(1)>div:nth-child(2)>div>div:nth-child(3)>div:nth-child(2)>div:nth-child(1)>div>div:nth-child(2)>div>div>div>div:nth-child(1)>div:nth-child(1)')
prices = driver.find_elements_by_css_selector('#app-content>div>div>div:nth-child(1)>div>div:nth-child(1)>div:nth-child(2)>div>div:nth-child(3)>div:nth-child(2)>div:nth-child(1)>div>div:nth-child(2)>div>div>div>div:nth-child(1)>div:nth-child(3)>span:nth-child(1)')
items_final = {}
num_items = len(items)
for i in range(0,num_items):
item_price = prices[i].text.replace("INR","")
item_name = items[i].text
items_final[item_name] = item_price
items_json = json.dumps(items_final)
cur.execute("""INSERT INTO uber_eats2 (name,location,items) VALUES (%s,%s,%s)""",(rest_name,location,items_json))
conn.commit()
print("Crawled {0}/88 Restaurant: {1} Items: {2}".format(count,rest_name,str(len(items_final))))
except:
print("error ",url)
| 0 | 0 | 0 |
081ece9169ae9f097b481614b641bcbc937f7ad6 | 64 | py | Python | evision_model/models/__init__.py | jiafeng5513/BinocularNet | c26262cef69f99f9db832ec5610cc03bf50aed88 | [
"MIT"
] | 21 | 2019-07-23T06:42:08.000Z | 2021-09-26T12:14:13.000Z | evision_model/models/__init__.py | jiafeng5513/BinocularNet | c26262cef69f99f9db832ec5610cc03bf50aed88 | [
"MIT"
] | 1 | 2021-09-26T13:33:40.000Z | 2021-09-26T13:33:40.000Z | evision_model/models/__init__.py | jiafeng5513/BinocularNet | c26262cef69f99f9db832ec5610cc03bf50aed88 | [
"MIT"
] | 6 | 2019-10-04T02:55:55.000Z | 2022-02-12T03:36:44.000Z | from .DepthNet import DepthNet
from .MotionNet import MotionNet
| 21.333333 | 32 | 0.84375 | from .DepthNet import DepthNet
from .MotionNet import MotionNet
| 0 | 0 | 0 |
1404028406d10381b34041ce381700c4c5e64506 | 990 | py | Python | phiimages/tests.py | denn-is-njeruh/Instaclone | a2f3c36822c419bfeadc56adccce00ce77e1d16e | [
"MIT"
] | null | null | null | phiimages/tests.py | denn-is-njeruh/Instaclone | a2f3c36822c419bfeadc56adccce00ce77e1d16e | [
"MIT"
] | null | null | null | phiimages/tests.py | denn-is-njeruh/Instaclone | a2f3c36822c419bfeadc56adccce00ce77e1d16e | [
"MIT"
] | null | null | null | from django.test import TestCase
from .models import Image, Profile
# Create your tests here.
| 35.357143 | 192 | 0.713131 | from django.test import TestCase
from .models import Image, Profile
# Create your tests here.
class TestProfileClass(TestCase):
def setUp(self):
self.new_profile = Profile(name = 'the_phi', profile_photo = 'image.jpg', bio = 'Dedicated coder')
def test_instance(self):
self.assertTrue(isinstance(self.new_profile,Profile))
def test_save_method(self):
self.new_profile.save_profile()
profiles = Profile.objects.all()
self.assertTrue(len(profiles) > 0)
class TestImageClass(TestCase):
def setUp(self):
self.new_profile = Profile(name = 'the_phi', profile_photo = 'image.jpg', bio = 'Dedicated coder')
self.new_profile.save_profile()
self.new_image = Image(name = 'Coding Time', captions ='Coding is therapeutic', comments = 'What a cool image and message', photo = 'image.jpeg', likes = '2', profile = 'self.new_profile')
self.new_image.save_image()
def tearDown(self):
Profile.objects.all().delete()
Image.objects.all().delete() | 705 | 22 | 168 |
a8224b54c25f0f4161bab881ff1dc019d12d9b80 | 9,052 | py | Python | pysnmp/NBS-SIGLANE-MIB.py | agustinhenze/mibs.snmplabs.com | 1fc5c07860542b89212f4c8ab807057d9a9206c7 | [
"Apache-2.0"
] | 11 | 2021-02-02T16:27:16.000Z | 2021-08-31T06:22:49.000Z | pysnmp/NBS-SIGLANE-MIB.py | agustinhenze/mibs.snmplabs.com | 1fc5c07860542b89212f4c8ab807057d9a9206c7 | [
"Apache-2.0"
] | 75 | 2021-02-24T17:30:31.000Z | 2021-12-08T00:01:18.000Z | pysnmp/NBS-SIGLANE-MIB.py | agustinhenze/mibs.snmplabs.com | 1fc5c07860542b89212f4c8ab807057d9a9206c7 | [
"Apache-2.0"
] | 10 | 2019-04-30T05:51:36.000Z | 2022-02-16T03:33:41.000Z | #
# PySNMP MIB module NBS-SIGLANE-MIB (http://snmplabs.com/pysmi)
# ASN.1 source file:///Users/davwang4/Dev/mibs.snmplabs.com/asn1/NBS-SIGLANE-MIB
# Produced by pysmi-0.3.4 at Mon Apr 29 20:07:45 2019
# On host DAVWANG4-M-1475 platform Darwin version 18.5.0 by user davwang4
# Using Python version 3.7.3 (default, Mar 27 2019, 09:23:15)
#
Integer, ObjectIdentifier, OctetString = mibBuilder.importSymbols("ASN1", "Integer", "ObjectIdentifier", "OctetString")
NamedValues, = mibBuilder.importSymbols("ASN1-ENUMERATION", "NamedValues")
ValueRangeConstraint, ConstraintsIntersection, ConstraintsUnion, ValueSizeConstraint, SingleValueConstraint = mibBuilder.importSymbols("ASN1-REFINEMENT", "ValueRangeConstraint", "ConstraintsIntersection", "ConstraintsUnion", "ValueSizeConstraint", "SingleValueConstraint")
InterfaceIndex, = mibBuilder.importSymbols("IF-MIB", "InterfaceIndex")
NbsCmmcChannelBand, = mibBuilder.importSymbols("NBS-CMMCENUM-MIB", "NbsCmmcChannelBand")
NbsTcMicroAmp, NbsTcMHz, NbsTcTemperature, NbsTcMilliDb, nbs = mibBuilder.importSymbols("NBS-MIB", "NbsTcMicroAmp", "NbsTcMHz", "NbsTcTemperature", "NbsTcMilliDb", "nbs")
NotificationGroup, ModuleCompliance = mibBuilder.importSymbols("SNMPv2-CONF", "NotificationGroup", "ModuleCompliance")
MibScalar, MibTable, MibTableRow, MibTableColumn, Counter64, Unsigned32, ModuleIdentity, ObjectIdentity, Bits, Gauge32, iso, TimeTicks, IpAddress, Integer32, MibIdentifier, NotificationType, Counter32 = mibBuilder.importSymbols("SNMPv2-SMI", "MibScalar", "MibTable", "MibTableRow", "MibTableColumn", "Counter64", "Unsigned32", "ModuleIdentity", "ObjectIdentity", "Bits", "Gauge32", "iso", "TimeTicks", "IpAddress", "Integer32", "MibIdentifier", "NotificationType", "Counter32")
DisplayString, TextualConvention = mibBuilder.importSymbols("SNMPv2-TC", "DisplayString", "TextualConvention")
nbsSigLaneMib = ModuleIdentity((1, 3, 6, 1, 4, 1, 629, 236))
if mibBuilder.loadTexts: nbsSigLaneMib.setLastUpdated('201503120000Z')
if mibBuilder.loadTexts: nbsSigLaneMib.setOrganization('NBS')
nbsSigLanePortGrp = ObjectIdentity((1, 3, 6, 1, 4, 1, 629, 236, 10))
if mibBuilder.loadTexts: nbsSigLanePortGrp.setStatus('current')
nbsSigLaneLaneGrp = ObjectIdentity((1, 3, 6, 1, 4, 1, 629, 236, 20))
if mibBuilder.loadTexts: nbsSigLaneLaneGrp.setStatus('current')
nbsSigLaneTraps = ObjectIdentity((1, 3, 6, 1, 4, 1, 629, 236, 100))
if mibBuilder.loadTexts: nbsSigLaneTraps.setStatus('current')
nbsSigLaneTraps0 = ObjectIdentity((1, 3, 6, 1, 4, 1, 629, 236, 100, 0))
if mibBuilder.loadTexts: nbsSigLaneTraps0.setStatus('current')
nbsSigLanePortTable = MibTable((1, 3, 6, 1, 4, 1, 629, 236, 10, 1), )
if mibBuilder.loadTexts: nbsSigLanePortTable.setStatus('current')
nbsSigLanePortEntry = MibTableRow((1, 3, 6, 1, 4, 1, 629, 236, 10, 1, 1), ).setIndexNames((0, "NBS-SIGLANE-MIB", "nbsSigLanePortIfIndex"))
if mibBuilder.loadTexts: nbsSigLanePortEntry.setStatus('current')
nbsSigLanePortIfIndex = MibTableColumn((1, 3, 6, 1, 4, 1, 629, 236, 10, 1, 1, 1), InterfaceIndex()).setMaxAccess("readonly")
if mibBuilder.loadTexts: nbsSigLanePortIfIndex.setStatus('current')
nbsSigLanePortFacility = MibTableColumn((1, 3, 6, 1, 4, 1, 629, 236, 10, 1, 1, 10), Integer32().subtype(subtypeSpec=ConstraintsUnion(SingleValueConstraint(1, 2, 3))).clone(namedValues=NamedValues(("other", 1), ("fiber", 2), ("lambda", 3)))).setMaxAccess("readonly")
if mibBuilder.loadTexts: nbsSigLanePortFacility.setStatus('current')
nbsSigLanePortLanes = MibTableColumn((1, 3, 6, 1, 4, 1, 629, 236, 10, 1, 1, 20), Integer32()).setMaxAccess("readonly")
if mibBuilder.loadTexts: nbsSigLanePortLanes.setStatus('current')
nbsSigLaneLaneTable = MibTable((1, 3, 6, 1, 4, 1, 629, 236, 20, 1), )
if mibBuilder.loadTexts: nbsSigLaneLaneTable.setStatus('current')
nbsSigLaneLaneEntry = MibTableRow((1, 3, 6, 1, 4, 1, 629, 236, 20, 1, 1), ).setIndexNames((0, "NBS-SIGLANE-MIB", "nbsSigLaneLaneIfIndex"), (0, "NBS-SIGLANE-MIB", "nbsSigLaneLaneIndex"))
if mibBuilder.loadTexts: nbsSigLaneLaneEntry.setStatus('current')
nbsSigLaneLaneIfIndex = MibTableColumn((1, 3, 6, 1, 4, 1, 629, 236, 20, 1, 1, 1), InterfaceIndex()).setMaxAccess("readonly")
if mibBuilder.loadTexts: nbsSigLaneLaneIfIndex.setStatus('current')
nbsSigLaneLaneIndex = MibTableColumn((1, 3, 6, 1, 4, 1, 629, 236, 20, 1, 1, 2), Integer32()).setMaxAccess("readonly")
if mibBuilder.loadTexts: nbsSigLaneLaneIndex.setStatus('current')
nbsSigLaneLaneFrequency = MibTableColumn((1, 3, 6, 1, 4, 1, 629, 236, 20, 1, 1, 10), NbsTcMHz()).setMaxAccess("readonly")
if mibBuilder.loadTexts: nbsSigLaneLaneFrequency.setStatus('current')
nbsSigLaneLaneWavelengthX = MibTableColumn((1, 3, 6, 1, 4, 1, 629, 236, 20, 1, 1, 11), DisplayString().subtype(subtypeSpec=ValueSizeConstraint(4, 8))).setMaxAccess("readonly")
if mibBuilder.loadTexts: nbsSigLaneLaneWavelengthX.setStatus('current')
nbsSigLaneLaneChannelBand = MibTableColumn((1, 3, 6, 1, 4, 1, 629, 236, 20, 1, 1, 12), NbsCmmcChannelBand()).setMaxAccess("readonly")
if mibBuilder.loadTexts: nbsSigLaneLaneChannelBand.setStatus('current')
nbsSigLaneLaneChannelNumber = MibTableColumn((1, 3, 6, 1, 4, 1, 629, 236, 20, 1, 1, 13), Integer32()).setMaxAccess("readonly")
if mibBuilder.loadTexts: nbsSigLaneLaneChannelNumber.setStatus('current')
nbsSigLaneLaneTxPowerLevel = MibTableColumn((1, 3, 6, 1, 4, 1, 629, 236, 20, 1, 1, 20), Integer32().subtype(subtypeSpec=ConstraintsUnion(SingleValueConstraint(1, 2, 3, 4, 5, 6))).clone(namedValues=NamedValues(("notSupported", 1), ("lowAlarm", 2), ("lowWarning", 3), ("ok", 4), ("highWarning", 5), ("highAlarm", 6))).clone('ok')).setMaxAccess("readonly")
if mibBuilder.loadTexts: nbsSigLaneLaneTxPowerLevel.setStatus('current')
nbsSigLaneLaneTxPower = MibTableColumn((1, 3, 6, 1, 4, 1, 629, 236, 20, 1, 1, 21), NbsTcMilliDb().clone(-2147483648)).setMaxAccess("readonly")
if mibBuilder.loadTexts: nbsSigLaneLaneTxPower.setStatus('current')
nbsSigLaneLaneRxPowerLevel = MibTableColumn((1, 3, 6, 1, 4, 1, 629, 236, 20, 1, 1, 30), Integer32().subtype(subtypeSpec=ConstraintsUnion(SingleValueConstraint(1, 2, 3, 4, 5, 6))).clone(namedValues=NamedValues(("notSupported", 1), ("lowAlarm", 2), ("lowWarning", 3), ("ok", 4), ("highWarning", 5), ("highAlarm", 6))).clone('ok')).setMaxAccess("readonly")
if mibBuilder.loadTexts: nbsSigLaneLaneRxPowerLevel.setStatus('current')
nbsSigLaneLaneRxPower = MibTableColumn((1, 3, 6, 1, 4, 1, 629, 236, 20, 1, 1, 31), NbsTcMilliDb().clone(-2147483648)).setMaxAccess("readonly")
if mibBuilder.loadTexts: nbsSigLaneLaneRxPower.setStatus('current')
nbsSigLaneLaneBiasAmpsLevel = MibTableColumn((1, 3, 6, 1, 4, 1, 629, 236, 20, 1, 1, 40), Integer32().subtype(subtypeSpec=ConstraintsUnion(SingleValueConstraint(1, 2, 3, 4, 5, 6))).clone(namedValues=NamedValues(("notSupported", 1), ("lowAlarm", 2), ("lowWarning", 3), ("ok", 4), ("highWarning", 5), ("highAlarm", 6))).clone('ok')).setMaxAccess("readonly")
if mibBuilder.loadTexts: nbsSigLaneLaneBiasAmpsLevel.setStatus('current')
nbsSigLaneLaneBiasAmps = MibTableColumn((1, 3, 6, 1, 4, 1, 629, 236, 20, 1, 1, 41), NbsTcMicroAmp().clone(-1)).setMaxAccess("readonly")
if mibBuilder.loadTexts: nbsSigLaneLaneBiasAmps.setStatus('current')
nbsSigLaneLaneLaserTempLevel = MibTableColumn((1, 3, 6, 1, 4, 1, 629, 236, 20, 1, 1, 50), Integer32().subtype(subtypeSpec=ConstraintsUnion(SingleValueConstraint(1, 2, 3, 4, 5, 6))).clone(namedValues=NamedValues(("notSupported", 1), ("lowAlarm", 2), ("lowWarning", 3), ("ok", 4), ("highWarning", 5), ("highAlarm", 6))).clone('ok')).setMaxAccess("readonly")
if mibBuilder.loadTexts: nbsSigLaneLaneLaserTempLevel.setStatus('current')
nbsSigLaneLaneLaserTemp = MibTableColumn((1, 3, 6, 1, 4, 1, 629, 236, 20, 1, 1, 51), NbsTcTemperature().clone(-2147483648)).setMaxAccess("readonly")
if mibBuilder.loadTexts: nbsSigLaneLaneLaserTemp.setStatus('current')
mibBuilder.exportSymbols("NBS-SIGLANE-MIB", nbsSigLanePortEntry=nbsSigLanePortEntry, nbsSigLaneLaneLaserTempLevel=nbsSigLaneLaneLaserTempLevel, nbsSigLanePortTable=nbsSigLanePortTable, nbsSigLaneLaneEntry=nbsSigLaneLaneEntry, nbsSigLaneTraps0=nbsSigLaneTraps0, nbsSigLaneMib=nbsSigLaneMib, PYSNMP_MODULE_ID=nbsSigLaneMib, nbsSigLaneLaneIfIndex=nbsSigLaneLaneIfIndex, nbsSigLaneLaneTable=nbsSigLaneLaneTable, nbsSigLaneLaneLaserTemp=nbsSigLaneLaneLaserTemp, nbsSigLaneLaneIndex=nbsSigLaneLaneIndex, nbsSigLaneLaneBiasAmps=nbsSigLaneLaneBiasAmps, nbsSigLanePortFacility=nbsSigLanePortFacility, nbsSigLaneLaneChannelBand=nbsSigLaneLaneChannelBand, nbsSigLaneLaneTxPowerLevel=nbsSigLaneLaneTxPowerLevel, nbsSigLanePortGrp=nbsSigLanePortGrp, nbsSigLaneLaneTxPower=nbsSigLaneLaneTxPower, nbsSigLanePortLanes=nbsSigLanePortLanes, nbsSigLaneLaneWavelengthX=nbsSigLaneLaneWavelengthX, nbsSigLaneLaneBiasAmpsLevel=nbsSigLaneLaneBiasAmpsLevel, nbsSigLanePortIfIndex=nbsSigLanePortIfIndex, nbsSigLaneLaneGrp=nbsSigLaneLaneGrp, nbsSigLaneLaneRxPowerLevel=nbsSigLaneLaneRxPowerLevel, nbsSigLaneTraps=nbsSigLaneTraps, nbsSigLaneLaneRxPower=nbsSigLaneLaneRxPower, nbsSigLaneLaneFrequency=nbsSigLaneLaneFrequency, nbsSigLaneLaneChannelNumber=nbsSigLaneLaneChannelNumber)
| 127.492958 | 1,253 | 0.773089 | #
# PySNMP MIB module NBS-SIGLANE-MIB (http://snmplabs.com/pysmi)
# ASN.1 source file:///Users/davwang4/Dev/mibs.snmplabs.com/asn1/NBS-SIGLANE-MIB
# Produced by pysmi-0.3.4 at Mon Apr 29 20:07:45 2019
# On host DAVWANG4-M-1475 platform Darwin version 18.5.0 by user davwang4
# Using Python version 3.7.3 (default, Mar 27 2019, 09:23:15)
#
Integer, ObjectIdentifier, OctetString = mibBuilder.importSymbols("ASN1", "Integer", "ObjectIdentifier", "OctetString")
NamedValues, = mibBuilder.importSymbols("ASN1-ENUMERATION", "NamedValues")
ValueRangeConstraint, ConstraintsIntersection, ConstraintsUnion, ValueSizeConstraint, SingleValueConstraint = mibBuilder.importSymbols("ASN1-REFINEMENT", "ValueRangeConstraint", "ConstraintsIntersection", "ConstraintsUnion", "ValueSizeConstraint", "SingleValueConstraint")
InterfaceIndex, = mibBuilder.importSymbols("IF-MIB", "InterfaceIndex")
NbsCmmcChannelBand, = mibBuilder.importSymbols("NBS-CMMCENUM-MIB", "NbsCmmcChannelBand")
NbsTcMicroAmp, NbsTcMHz, NbsTcTemperature, NbsTcMilliDb, nbs = mibBuilder.importSymbols("NBS-MIB", "NbsTcMicroAmp", "NbsTcMHz", "NbsTcTemperature", "NbsTcMilliDb", "nbs")
NotificationGroup, ModuleCompliance = mibBuilder.importSymbols("SNMPv2-CONF", "NotificationGroup", "ModuleCompliance")
MibScalar, MibTable, MibTableRow, MibTableColumn, Counter64, Unsigned32, ModuleIdentity, ObjectIdentity, Bits, Gauge32, iso, TimeTicks, IpAddress, Integer32, MibIdentifier, NotificationType, Counter32 = mibBuilder.importSymbols("SNMPv2-SMI", "MibScalar", "MibTable", "MibTableRow", "MibTableColumn", "Counter64", "Unsigned32", "ModuleIdentity", "ObjectIdentity", "Bits", "Gauge32", "iso", "TimeTicks", "IpAddress", "Integer32", "MibIdentifier", "NotificationType", "Counter32")
DisplayString, TextualConvention = mibBuilder.importSymbols("SNMPv2-TC", "DisplayString", "TextualConvention")
nbsSigLaneMib = ModuleIdentity((1, 3, 6, 1, 4, 1, 629, 236))
if mibBuilder.loadTexts: nbsSigLaneMib.setLastUpdated('201503120000Z')
if mibBuilder.loadTexts: nbsSigLaneMib.setOrganization('NBS')
nbsSigLanePortGrp = ObjectIdentity((1, 3, 6, 1, 4, 1, 629, 236, 10))
if mibBuilder.loadTexts: nbsSigLanePortGrp.setStatus('current')
nbsSigLaneLaneGrp = ObjectIdentity((1, 3, 6, 1, 4, 1, 629, 236, 20))
if mibBuilder.loadTexts: nbsSigLaneLaneGrp.setStatus('current')
nbsSigLaneTraps = ObjectIdentity((1, 3, 6, 1, 4, 1, 629, 236, 100))
if mibBuilder.loadTexts: nbsSigLaneTraps.setStatus('current')
nbsSigLaneTraps0 = ObjectIdentity((1, 3, 6, 1, 4, 1, 629, 236, 100, 0))
if mibBuilder.loadTexts: nbsSigLaneTraps0.setStatus('current')
nbsSigLanePortTable = MibTable((1, 3, 6, 1, 4, 1, 629, 236, 10, 1), )
if mibBuilder.loadTexts: nbsSigLanePortTable.setStatus('current')
nbsSigLanePortEntry = MibTableRow((1, 3, 6, 1, 4, 1, 629, 236, 10, 1, 1), ).setIndexNames((0, "NBS-SIGLANE-MIB", "nbsSigLanePortIfIndex"))
if mibBuilder.loadTexts: nbsSigLanePortEntry.setStatus('current')
nbsSigLanePortIfIndex = MibTableColumn((1, 3, 6, 1, 4, 1, 629, 236, 10, 1, 1, 1), InterfaceIndex()).setMaxAccess("readonly")
if mibBuilder.loadTexts: nbsSigLanePortIfIndex.setStatus('current')
nbsSigLanePortFacility = MibTableColumn((1, 3, 6, 1, 4, 1, 629, 236, 10, 1, 1, 10), Integer32().subtype(subtypeSpec=ConstraintsUnion(SingleValueConstraint(1, 2, 3))).clone(namedValues=NamedValues(("other", 1), ("fiber", 2), ("lambda", 3)))).setMaxAccess("readonly")
if mibBuilder.loadTexts: nbsSigLanePortFacility.setStatus('current')
nbsSigLanePortLanes = MibTableColumn((1, 3, 6, 1, 4, 1, 629, 236, 10, 1, 1, 20), Integer32()).setMaxAccess("readonly")
if mibBuilder.loadTexts: nbsSigLanePortLanes.setStatus('current')
nbsSigLaneLaneTable = MibTable((1, 3, 6, 1, 4, 1, 629, 236, 20, 1), )
if mibBuilder.loadTexts: nbsSigLaneLaneTable.setStatus('current')
nbsSigLaneLaneEntry = MibTableRow((1, 3, 6, 1, 4, 1, 629, 236, 20, 1, 1), ).setIndexNames((0, "NBS-SIGLANE-MIB", "nbsSigLaneLaneIfIndex"), (0, "NBS-SIGLANE-MIB", "nbsSigLaneLaneIndex"))
if mibBuilder.loadTexts: nbsSigLaneLaneEntry.setStatus('current')
nbsSigLaneLaneIfIndex = MibTableColumn((1, 3, 6, 1, 4, 1, 629, 236, 20, 1, 1, 1), InterfaceIndex()).setMaxAccess("readonly")
if mibBuilder.loadTexts: nbsSigLaneLaneIfIndex.setStatus('current')
nbsSigLaneLaneIndex = MibTableColumn((1, 3, 6, 1, 4, 1, 629, 236, 20, 1, 1, 2), Integer32()).setMaxAccess("readonly")
if mibBuilder.loadTexts: nbsSigLaneLaneIndex.setStatus('current')
nbsSigLaneLaneFrequency = MibTableColumn((1, 3, 6, 1, 4, 1, 629, 236, 20, 1, 1, 10), NbsTcMHz()).setMaxAccess("readonly")
if mibBuilder.loadTexts: nbsSigLaneLaneFrequency.setStatus('current')
nbsSigLaneLaneWavelengthX = MibTableColumn((1, 3, 6, 1, 4, 1, 629, 236, 20, 1, 1, 11), DisplayString().subtype(subtypeSpec=ValueSizeConstraint(4, 8))).setMaxAccess("readonly")
if mibBuilder.loadTexts: nbsSigLaneLaneWavelengthX.setStatus('current')
nbsSigLaneLaneChannelBand = MibTableColumn((1, 3, 6, 1, 4, 1, 629, 236, 20, 1, 1, 12), NbsCmmcChannelBand()).setMaxAccess("readonly")
if mibBuilder.loadTexts: nbsSigLaneLaneChannelBand.setStatus('current')
nbsSigLaneLaneChannelNumber = MibTableColumn((1, 3, 6, 1, 4, 1, 629, 236, 20, 1, 1, 13), Integer32()).setMaxAccess("readonly")
if mibBuilder.loadTexts: nbsSigLaneLaneChannelNumber.setStatus('current')
nbsSigLaneLaneTxPowerLevel = MibTableColumn((1, 3, 6, 1, 4, 1, 629, 236, 20, 1, 1, 20), Integer32().subtype(subtypeSpec=ConstraintsUnion(SingleValueConstraint(1, 2, 3, 4, 5, 6))).clone(namedValues=NamedValues(("notSupported", 1), ("lowAlarm", 2), ("lowWarning", 3), ("ok", 4), ("highWarning", 5), ("highAlarm", 6))).clone('ok')).setMaxAccess("readonly")
if mibBuilder.loadTexts: nbsSigLaneLaneTxPowerLevel.setStatus('current')
nbsSigLaneLaneTxPower = MibTableColumn((1, 3, 6, 1, 4, 1, 629, 236, 20, 1, 1, 21), NbsTcMilliDb().clone(-2147483648)).setMaxAccess("readonly")
if mibBuilder.loadTexts: nbsSigLaneLaneTxPower.setStatus('current')
nbsSigLaneLaneRxPowerLevel = MibTableColumn((1, 3, 6, 1, 4, 1, 629, 236, 20, 1, 1, 30), Integer32().subtype(subtypeSpec=ConstraintsUnion(SingleValueConstraint(1, 2, 3, 4, 5, 6))).clone(namedValues=NamedValues(("notSupported", 1), ("lowAlarm", 2), ("lowWarning", 3), ("ok", 4), ("highWarning", 5), ("highAlarm", 6))).clone('ok')).setMaxAccess("readonly")
if mibBuilder.loadTexts: nbsSigLaneLaneRxPowerLevel.setStatus('current')
nbsSigLaneLaneRxPower = MibTableColumn((1, 3, 6, 1, 4, 1, 629, 236, 20, 1, 1, 31), NbsTcMilliDb().clone(-2147483648)).setMaxAccess("readonly")
if mibBuilder.loadTexts: nbsSigLaneLaneRxPower.setStatus('current')
nbsSigLaneLaneBiasAmpsLevel = MibTableColumn((1, 3, 6, 1, 4, 1, 629, 236, 20, 1, 1, 40), Integer32().subtype(subtypeSpec=ConstraintsUnion(SingleValueConstraint(1, 2, 3, 4, 5, 6))).clone(namedValues=NamedValues(("notSupported", 1), ("lowAlarm", 2), ("lowWarning", 3), ("ok", 4), ("highWarning", 5), ("highAlarm", 6))).clone('ok')).setMaxAccess("readonly")
if mibBuilder.loadTexts: nbsSigLaneLaneBiasAmpsLevel.setStatus('current')
nbsSigLaneLaneBiasAmps = MibTableColumn((1, 3, 6, 1, 4, 1, 629, 236, 20, 1, 1, 41), NbsTcMicroAmp().clone(-1)).setMaxAccess("readonly")
if mibBuilder.loadTexts: nbsSigLaneLaneBiasAmps.setStatus('current')
nbsSigLaneLaneLaserTempLevel = MibTableColumn((1, 3, 6, 1, 4, 1, 629, 236, 20, 1, 1, 50), Integer32().subtype(subtypeSpec=ConstraintsUnion(SingleValueConstraint(1, 2, 3, 4, 5, 6))).clone(namedValues=NamedValues(("notSupported", 1), ("lowAlarm", 2), ("lowWarning", 3), ("ok", 4), ("highWarning", 5), ("highAlarm", 6))).clone('ok')).setMaxAccess("readonly")
if mibBuilder.loadTexts: nbsSigLaneLaneLaserTempLevel.setStatus('current')
nbsSigLaneLaneLaserTemp = MibTableColumn((1, 3, 6, 1, 4, 1, 629, 236, 20, 1, 1, 51), NbsTcTemperature().clone(-2147483648)).setMaxAccess("readonly")
if mibBuilder.loadTexts: nbsSigLaneLaneLaserTemp.setStatus('current')
mibBuilder.exportSymbols("NBS-SIGLANE-MIB", nbsSigLanePortEntry=nbsSigLanePortEntry, nbsSigLaneLaneLaserTempLevel=nbsSigLaneLaneLaserTempLevel, nbsSigLanePortTable=nbsSigLanePortTable, nbsSigLaneLaneEntry=nbsSigLaneLaneEntry, nbsSigLaneTraps0=nbsSigLaneTraps0, nbsSigLaneMib=nbsSigLaneMib, PYSNMP_MODULE_ID=nbsSigLaneMib, nbsSigLaneLaneIfIndex=nbsSigLaneLaneIfIndex, nbsSigLaneLaneTable=nbsSigLaneLaneTable, nbsSigLaneLaneLaserTemp=nbsSigLaneLaneLaserTemp, nbsSigLaneLaneIndex=nbsSigLaneLaneIndex, nbsSigLaneLaneBiasAmps=nbsSigLaneLaneBiasAmps, nbsSigLanePortFacility=nbsSigLanePortFacility, nbsSigLaneLaneChannelBand=nbsSigLaneLaneChannelBand, nbsSigLaneLaneTxPowerLevel=nbsSigLaneLaneTxPowerLevel, nbsSigLanePortGrp=nbsSigLanePortGrp, nbsSigLaneLaneTxPower=nbsSigLaneLaneTxPower, nbsSigLanePortLanes=nbsSigLanePortLanes, nbsSigLaneLaneWavelengthX=nbsSigLaneLaneWavelengthX, nbsSigLaneLaneBiasAmpsLevel=nbsSigLaneLaneBiasAmpsLevel, nbsSigLanePortIfIndex=nbsSigLanePortIfIndex, nbsSigLaneLaneGrp=nbsSigLaneLaneGrp, nbsSigLaneLaneRxPowerLevel=nbsSigLaneLaneRxPowerLevel, nbsSigLaneTraps=nbsSigLaneTraps, nbsSigLaneLaneRxPower=nbsSigLaneLaneRxPower, nbsSigLaneLaneFrequency=nbsSigLaneLaneFrequency, nbsSigLaneLaneChannelNumber=nbsSigLaneLaneChannelNumber)
| 0 | 0 | 0 |
a36bc46d294cc96d17322dd9c9fdb9fa7f5bb8a7 | 685 | py | Python | server/djangoapp/admin.py | AbdKenn/agfzb-CloudAppDevelopment_Capstone | 78512461254dc398a1f55fa198b68de5a6731b2b | [
"Apache-2.0"
] | null | null | null | server/djangoapp/admin.py | AbdKenn/agfzb-CloudAppDevelopment_Capstone | 78512461254dc398a1f55fa198b68de5a6731b2b | [
"Apache-2.0"
] | null | null | null | server/djangoapp/admin.py | AbdKenn/agfzb-CloudAppDevelopment_Capstone | 78512461254dc398a1f55fa198b68de5a6731b2b | [
"Apache-2.0"
] | null | null | null | from django.contrib import admin
from .models import CarMake, CarModel
# Register your models here.
#admin.site.register(CarMake)
#admin.site.register(CarModel)
# CarModelInline class
# CarModelAdmin class
# CarMakeAdmin class with CarModelInline
# Register models here
admin.site.register(CarModel)
admin.site.register(CarMake, CarMakeAdmin)
| 25.37037 | 49 | 0.738686 | from django.contrib import admin
from .models import CarMake, CarModel
# Register your models here.
#admin.site.register(CarMake)
#admin.site.register(CarModel)
# CarModelInline class
class CarModelInline(admin.StackedInline):
model = CarModel
#extra = 5
# CarModelAdmin class
class CarModelAdmin(admin.ModelAdmin):
#fields = ['pub_date', 'name', 'description']
#inlines = [CarModelInline]
pass
# CarMakeAdmin class with CarModelInline
class CarMakeAdmin(admin.ModelAdmin):
#fields = ['pub_date', 'name', 'description']
inlines = [CarModelInline]
# Register models here
admin.site.register(CarModel)
admin.site.register(CarMake, CarMakeAdmin)
| 0 | 268 | 66 |
355d02ea714772075a1790c26bb4c418bc4e9aad | 1,402 | py | Python | semantic_segmentation/configs/_base_/models/upernet_convnext.py | ParikhKadam/ConvNeXt | d1fa8f6fef0a165b27399986cc2bdacc92777e40 | [
"MIT"
] | 3,453 | 2022-01-11T01:49:27.000Z | 2022-03-31T12:35:56.000Z | semantic_segmentation/configs/_base_/models/upernet_convnext.py | ParikhKadam/ConvNeXt | d1fa8f6fef0a165b27399986cc2bdacc92777e40 | [
"MIT"
] | 80 | 2022-01-11T10:03:13.000Z | 2022-03-31T05:22:48.000Z | semantic_segmentation/configs/_base_/models/upernet_convnext.py | ParikhKadam/ConvNeXt | d1fa8f6fef0a165b27399986cc2bdacc92777e40 | [
"MIT"
] | 398 | 2022-01-11T02:42:28.000Z | 2022-03-31T06:30:47.000Z | # Copyright (c) Meta Platforms, Inc. and affiliates.
# All rights reserved.
# This source code is licensed under the license found in the
# LICENSE file in the root directory of this source tree.
norm_cfg = dict(type='SyncBN', requires_grad=True)
model = dict(
type='EncoderDecoder',
pretrained=None,
backbone=dict(
type='ConvNeXt',
in_chans=3,
depths=[3, 3, 9, 3],
dims=[96, 192, 384, 768],
drop_path_rate=0.2,
layer_scale_init_value=1.0,
out_indices=[0, 1, 2, 3],
),
decode_head=dict(
type='UPerHead',
in_channels=[128, 256, 512, 1024],
in_index=[0, 1, 2, 3],
pool_scales=(1, 2, 3, 6),
channels=512,
dropout_ratio=0.1,
num_classes=19,
norm_cfg=norm_cfg,
align_corners=False,
loss_decode=dict(
type='CrossEntropyLoss', use_sigmoid=False, loss_weight=1.0)),
auxiliary_head=dict(
type='FCNHead',
in_channels=384,
in_index=2,
channels=256,
num_convs=1,
concat_input=False,
dropout_ratio=0.1,
num_classes=19,
norm_cfg=norm_cfg,
align_corners=False,
loss_decode=dict(
type='CrossEntropyLoss', use_sigmoid=False, loss_weight=0.4)),
# model training and testing settings
train_cfg=dict(),
test_cfg=dict(mode='whole'))
| 28.04 | 74 | 0.598431 | # Copyright (c) Meta Platforms, Inc. and affiliates.
# All rights reserved.
# This source code is licensed under the license found in the
# LICENSE file in the root directory of this source tree.
norm_cfg = dict(type='SyncBN', requires_grad=True)
model = dict(
type='EncoderDecoder',
pretrained=None,
backbone=dict(
type='ConvNeXt',
in_chans=3,
depths=[3, 3, 9, 3],
dims=[96, 192, 384, 768],
drop_path_rate=0.2,
layer_scale_init_value=1.0,
out_indices=[0, 1, 2, 3],
),
decode_head=dict(
type='UPerHead',
in_channels=[128, 256, 512, 1024],
in_index=[0, 1, 2, 3],
pool_scales=(1, 2, 3, 6),
channels=512,
dropout_ratio=0.1,
num_classes=19,
norm_cfg=norm_cfg,
align_corners=False,
loss_decode=dict(
type='CrossEntropyLoss', use_sigmoid=False, loss_weight=1.0)),
auxiliary_head=dict(
type='FCNHead',
in_channels=384,
in_index=2,
channels=256,
num_convs=1,
concat_input=False,
dropout_ratio=0.1,
num_classes=19,
norm_cfg=norm_cfg,
align_corners=False,
loss_decode=dict(
type='CrossEntropyLoss', use_sigmoid=False, loss_weight=0.4)),
# model training and testing settings
train_cfg=dict(),
test_cfg=dict(mode='whole'))
| 0 | 0 | 0 |
e6cdd09d28b8d706c93874dff659d7ce8d79506b | 1,695 | py | Python | tests/python/twitter/common/quantity/test_parsing.py | zhouyijiaren/commons | 10df6fb63547baa9047782aa7ad4edf354914b10 | [
"Apache-2.0"
] | 1,143 | 2015-01-05T04:19:24.000Z | 2019-12-11T12:02:23.000Z | tests/python/twitter/common/quantity/test_parsing.py | zhouyijiaren/commons | 10df6fb63547baa9047782aa7ad4edf354914b10 | [
"Apache-2.0"
] | 144 | 2015-01-06T05:05:07.000Z | 2019-12-12T18:02:37.000Z | tests/python/twitter/common/quantity/test_parsing.py | zhouyijiaren/commons | 10df6fb63547baa9047782aa7ad4edf354914b10 | [
"Apache-2.0"
] | 426 | 2015-01-08T08:33:41.000Z | 2019-12-09T13:15:40.000Z | # ==================================================================================================
# Copyright 2011 Twitter, Inc.
# --------------------------------------------------------------------------------------------------
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this work except in compliance with the License.
# You may obtain a copy of the License in the LICENSE file, or 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.
# ==================================================================================================
import pytest
from twitter.common.quantity import Time, Amount
from twitter.common.quantity.parse_simple import parse_time, InvalidTime
| 43.461538 | 100 | 0.60118 | # ==================================================================================================
# Copyright 2011 Twitter, Inc.
# --------------------------------------------------------------------------------------------------
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this work except in compliance with the License.
# You may obtain a copy of the License in the LICENSE file, or 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.
# ==================================================================================================
import pytest
from twitter.common.quantity import Time, Amount
from twitter.common.quantity.parse_simple import parse_time, InvalidTime
def test_basic():
assert parse_time('') == Amount(0, Time.SECONDS)
assert parse_time('1s') == Amount(1, Time.SECONDS)
assert parse_time('2m60s') == Amount(3, Time.MINUTES)
assert parse_time('1d') == Amount(1, Time.DAYS)
assert parse_time('1d1H3600s') == Amount(26, Time.HOURS)
assert parse_time('1d-1s') == Amount(86399, Time.SECONDS)
def test_bad():
bad_strings = ['foo', 'dhms', '1s30d', 'a b c d', ' ', '1s2s3s']
for bad_string in bad_strings:
with pytest.raises(InvalidTime):
parse_time(bad_string)
bad_strings = [123, type]
for bad_string in bad_strings:
with pytest.raises(TypeError):
parse_time(bad_string)
| 612 | 0 | 46 |
f394b02017f0e1636d2d430576fb8fa5688a4a89 | 79 | py | Python | src/__init__.py | Tauseef-Hilal/iCODE-BOT | dd4efa9084c35d238f1170ff3af69eeeb055abec | [
"MIT"
] | 1 | 2022-03-31T15:31:10.000Z | 2022-03-31T15:31:10.000Z | src/__init__.py | Tauseef-Hilal/iCODE-BOT | dd4efa9084c35d238f1170ff3af69eeeb055abec | [
"MIT"
] | null | null | null | src/__init__.py | Tauseef-Hilal/iCODE-BOT | dd4efa9084c35d238f1170ff3af69eeeb055abec | [
"MIT"
] | null | null | null | __author__ = "Tauseef Hilal Tantary"
__title__ = "iCODE-BOT"
__version__ = 1.0
| 19.75 | 36 | 0.746835 | __author__ = "Tauseef Hilal Tantary"
__title__ = "iCODE-BOT"
__version__ = 1.0
| 0 | 0 | 0 |
230d2beb84eb1c772ee30285ed46a43c88b22a1f | 2,656 | py | Python | sdk/python/pulumi_gcp/sql/database_instance.py | vrutkovs/pulumi-gcp | ced632feea265d95a38c7ae02826deaae77fb358 | [
"ECL-2.0",
"Apache-2.0"
] | null | null | null | sdk/python/pulumi_gcp/sql/database_instance.py | vrutkovs/pulumi-gcp | ced632feea265d95a38c7ae02826deaae77fb358 | [
"ECL-2.0",
"Apache-2.0"
] | null | null | null | sdk/python/pulumi_gcp/sql/database_instance.py | vrutkovs/pulumi-gcp | ced632feea265d95a38c7ae02826deaae77fb358 | [
"ECL-2.0",
"Apache-2.0"
] | null | null | null | # coding=utf-8
# *** WARNING: this file was generated by the Pulumi Terraform Bridge (tfgen) Tool. ***
# *** Do not edit by hand unless you're certain you know what you are doing! ***
import pulumi
import pulumi.runtime
from .. import utilities, tables
class DatabaseInstance(pulumi.CustomResource):
"""
Creates a new Google SQL Database Instance. For more information, see the [official documentation](https://cloud.google.com/sql/),
or the [JSON API](https://cloud.google.com/sql/docs/admin-api/v1beta4/instances).
~> **NOTE on `google_sql_database_instance`:** - Second-generation instances include a
default 'root'@'%' user with no password. This user will be deleted by Terraform on
instance creation. You should use `google_sql_user` to define a custom user with
a restricted host and strong password.
"""
def __init__(__self__, __name__, __opts__=None, database_version=None, master_instance_name=None, name=None, project=None, region=None, replica_configuration=None, settings=None):
"""Create a DatabaseInstance resource with the given unique name, props, and options."""
if not __name__:
raise TypeError('Missing resource name argument (for URN creation)')
if not isinstance(__name__, str):
raise TypeError('Expected resource name to be a string')
if __opts__ and not isinstance(__opts__, pulumi.ResourceOptions):
raise TypeError('Expected resource options to be a ResourceOptions instance')
__props__ = dict()
__props__['database_version'] = database_version
__props__['master_instance_name'] = master_instance_name
__props__['name'] = name
__props__['project'] = project
__props__['region'] = region
__props__['replica_configuration'] = replica_configuration
if not settings:
raise TypeError('Missing required property settings')
__props__['settings'] = settings
__props__['connection_name'] = None
__props__['first_ip_address'] = None
__props__['ip_addresses'] = None
__props__['self_link'] = None
__props__['server_ca_cert'] = None
__props__['service_account_email_address'] = None
super(DatabaseInstance, __self__).__init__(
'gcp:sql/databaseInstance:DatabaseInstance',
__name__,
__props__,
__opts__)
| 40.242424 | 183 | 0.691642 | # coding=utf-8
# *** WARNING: this file was generated by the Pulumi Terraform Bridge (tfgen) Tool. ***
# *** Do not edit by hand unless you're certain you know what you are doing! ***
import pulumi
import pulumi.runtime
from .. import utilities, tables
class DatabaseInstance(pulumi.CustomResource):
"""
Creates a new Google SQL Database Instance. For more information, see the [official documentation](https://cloud.google.com/sql/),
or the [JSON API](https://cloud.google.com/sql/docs/admin-api/v1beta4/instances).
~> **NOTE on `google_sql_database_instance`:** - Second-generation instances include a
default 'root'@'%' user with no password. This user will be deleted by Terraform on
instance creation. You should use `google_sql_user` to define a custom user with
a restricted host and strong password.
"""
def __init__(__self__, __name__, __opts__=None, database_version=None, master_instance_name=None, name=None, project=None, region=None, replica_configuration=None, settings=None):
"""Create a DatabaseInstance resource with the given unique name, props, and options."""
if not __name__:
raise TypeError('Missing resource name argument (for URN creation)')
if not isinstance(__name__, str):
raise TypeError('Expected resource name to be a string')
if __opts__ and not isinstance(__opts__, pulumi.ResourceOptions):
raise TypeError('Expected resource options to be a ResourceOptions instance')
__props__ = dict()
__props__['database_version'] = database_version
__props__['master_instance_name'] = master_instance_name
__props__['name'] = name
__props__['project'] = project
__props__['region'] = region
__props__['replica_configuration'] = replica_configuration
if not settings:
raise TypeError('Missing required property settings')
__props__['settings'] = settings
__props__['connection_name'] = None
__props__['first_ip_address'] = None
__props__['ip_addresses'] = None
__props__['self_link'] = None
__props__['server_ca_cert'] = None
__props__['service_account_email_address'] = None
super(DatabaseInstance, __self__).__init__(
'gcp:sql/databaseInstance:DatabaseInstance',
__name__,
__props__,
__opts__)
def translate_output_property(self, prop):
return tables._CAMEL_TO_SNAKE_CASE_TABLE.get(prop) or prop
def translate_input_property(self, prop):
return tables._SNAKE_TO_CAMEL_CASE_TABLE.get(prop) or prop
| 175 | 0 | 54 |
3948742f2a5abc4ef05a2d984c85454b2d48e44f | 4,121 | py | Python | backend/apps/account/models.py | codelieche/erp | 96861ff63a63a93918fbd5181ffb2646446d0eec | [
"MIT"
] | null | null | null | backend/apps/account/models.py | codelieche/erp | 96861ff63a63a93918fbd5181ffb2646446d0eec | [
"MIT"
] | 29 | 2020-06-05T19:57:11.000Z | 2022-02-26T13:42:36.000Z | backend/apps/account/models.py | codelieche/erp | 96861ff63a63a93918fbd5181ffb2646446d0eec | [
"MIT"
] | null | null | null | from django.db import models
from django.contrib.auth.models import AbstractUser
from django.contrib.auth import get_user_model
# Create your models here.
class UserProfile(AbstractUser):
"""
自定义的用户Model
拓展字段gender, nick_name, mobile, qq
"""
GENDER_CHOICES = (
('male', "男"),
('female', "女"),
('secret', "保密")
)
nick_name = models.CharField(max_length=40, blank=True, verbose_name="昵称")
# 头像url
avatar = models.CharField(verbose_name="头像", blank=True, null=True, max_length=256)
gender = models.CharField(max_length=6, choices=GENDER_CHOICES, default="secret",
verbose_name="性别")
# email可以随便填,但是手机号需要唯一: 后续可加入校验验证码
mobile = models.CharField(max_length=11, verbose_name="手机号", unique=True)
qq = models.CharField(max_length=12, verbose_name="QQ号", blank=True, null=True)
# 公司有时候会用到钉钉/微信发送消息,需要记录用户相关ID
dingding = models.CharField(max_length=40, verbose_name="钉钉ID", blank=True, null=True)
wechat = models.CharField(max_length=40, verbose_name="微信ID", blank=True, null=True)
# 能否访问本系统,默认是不可以访问本系统
# 注意第一个管理员用户,可以去数据库调整can_view的值为1
can_view = models.BooleanField(verbose_name="能访问", default=False, blank=True)
is_deleted = models.BooleanField(verbose_name="删除", default=False, blank=True)
# 注意:get_user_model()方法可以获取到本系统使用的是哪个用户Model
# 默认的用户Model是:django.contrib.auth.models.User
# 在settings.py中配置:AUTH_USER_MODEL可以修改成指定的用户Model
# AUTH_USER_MODEL = "account.UserProfile"
User = get_user_model()
# 注意这句是要放在class UserProfile后面的
class MessageScope(models.Model):
"""
消息范围
"""
scope = models.SlugField(verbose_name="范围", max_length=10)
name = models.CharField(verbose_name="范围名称", max_length=10, blank=True)
class Message(models.Model):
"""
用户消息Model
"""
user = models.ForeignKey(to=User, verbose_name='用户', on_delete=models.CASCADE)
sender = models.CharField(max_length=15, verbose_name="发送者", default='system', blank=True)
# 消息类型,想用type,但是还是用scope,type和types是mysql的预保留字
scope = models.ForeignKey(to=MessageScope, verbose_name="消息范围", blank=True,
on_delete=models.CASCADE)
title = models.CharField(max_length=100, verbose_name="消息标题")
content = models.CharField(max_length=512, verbose_name="消息内容", blank=True)
link = models.CharField(max_length=128, verbose_name="链接", blank=True, null=True)
unread = models.BooleanField(verbose_name="未读", blank=True, default=True)
time_added = models.DateTimeField(auto_now_add=True, verbose_name="添加时间")
is_deleted = models.BooleanField(verbose_name="删除", default=False, blank=True)
| 35.834783 | 94 | 0.677263 | from django.db import models
from django.contrib.auth.models import AbstractUser
from django.contrib.auth import get_user_model
# Create your models here.
class UserProfile(AbstractUser):
"""
自定义的用户Model
拓展字段gender, nick_name, mobile, qq
"""
GENDER_CHOICES = (
('male', "男"),
('female', "女"),
('secret', "保密")
)
nick_name = models.CharField(max_length=40, blank=True, verbose_name="昵称")
# 头像url
avatar = models.CharField(verbose_name="头像", blank=True, null=True, max_length=256)
gender = models.CharField(max_length=6, choices=GENDER_CHOICES, default="secret",
verbose_name="性别")
# email可以随便填,但是手机号需要唯一: 后续可加入校验验证码
mobile = models.CharField(max_length=11, verbose_name="手机号", unique=True)
qq = models.CharField(max_length=12, verbose_name="QQ号", blank=True, null=True)
# 公司有时候会用到钉钉/微信发送消息,需要记录用户相关ID
dingding = models.CharField(max_length=40, verbose_name="钉钉ID", blank=True, null=True)
wechat = models.CharField(max_length=40, verbose_name="微信ID", blank=True, null=True)
# 能否访问本系统,默认是不可以访问本系统
# 注意第一个管理员用户,可以去数据库调整can_view的值为1
can_view = models.BooleanField(verbose_name="能访问", default=False, blank=True)
is_deleted = models.BooleanField(verbose_name="删除", default=False, blank=True)
def __repr__(self):
return "UserProfile:{}".format(self.username)
def __str__(self):
return self.username
class Meta:
verbose_name = "用户信息"
verbose_name_plural = verbose_name
# 注意:get_user_model()方法可以获取到本系统使用的是哪个用户Model
# 默认的用户Model是:django.contrib.auth.models.User
# 在settings.py中配置:AUTH_USER_MODEL可以修改成指定的用户Model
# AUTH_USER_MODEL = "account.UserProfile"
User = get_user_model()
# 注意这句是要放在class UserProfile后面的
class MessageScope(models.Model):
"""
消息范围
"""
scope = models.SlugField(verbose_name="范围", max_length=10)
name = models.CharField(verbose_name="范围名称", max_length=10, blank=True)
def save(self, force_insert=False, force_update=False, using=None,
update_fields=None):
if not self.name:
self.name = self.scope
super().save(force_insert=force_insert, force_update=force_update,
using=using, update_fields=update_fields)
def __str__(self):
return "Message:{}".format(self.scope)
class Meta:
verbose_name = "消息范围"
verbose_name_plural = verbose_name
class Message(models.Model):
"""
用户消息Model
"""
user = models.ForeignKey(to=User, verbose_name='用户', on_delete=models.CASCADE)
sender = models.CharField(max_length=15, verbose_name="发送者", default='system', blank=True)
# 消息类型,想用type,但是还是用scope,type和types是mysql的预保留字
scope = models.ForeignKey(to=MessageScope, verbose_name="消息范围", blank=True,
on_delete=models.CASCADE)
title = models.CharField(max_length=100, verbose_name="消息标题")
content = models.CharField(max_length=512, verbose_name="消息内容", blank=True)
link = models.CharField(max_length=128, verbose_name="链接", blank=True, null=True)
unread = models.BooleanField(verbose_name="未读", blank=True, default=True)
time_added = models.DateTimeField(auto_now_add=True, verbose_name="添加时间")
is_deleted = models.BooleanField(verbose_name="删除", default=False, blank=True)
def save(self, force_insert=False, force_update=False, using=None,
update_fields=None):
# 当content为空的时候,让其等于title
if not self.content:
self.content = self.title
# 设置scope
if not self.scope:
scope, created = MessageScope.objects.get_or_create(scope="default")
self.scope = scope
return super().save(force_insert=force_insert, force_update=force_update,
using=using, update_fields=update_fields)
def __repr__(self):
return 'Message({})'.format(self.pk)
def __str__(self):
return "用户消息:{}-{}".format(self.user.username, self.pk)
class Meta:
verbose_name = "用户消息"
verbose_name_plural = verbose_name
| 1,036 | 213 | 270 |
e885c149f86640e0c03b693520964b9ee91d4c2c | 929 | py | Python | record/list/migrations/0008_userorder.py | Brayton-Han/Brayton-s-Record | 67cb6f7b17d8cb2c5f428079afb091f12b015f5c | [
"MIT"
] | null | null | null | record/list/migrations/0008_userorder.py | Brayton-Han/Brayton-s-Record | 67cb6f7b17d8cb2c5f428079afb091f12b015f5c | [
"MIT"
] | null | null | null | record/list/migrations/0008_userorder.py | Brayton-Han/Brayton-s-Record | 67cb6f7b17d8cb2c5f428079afb091f12b015f5c | [
"MIT"
] | null | null | null | # Generated by Django 3.2.3 on 2021-06-09 13:27
from django.db import migrations, models
| 29.967742 | 77 | 0.482239 | # Generated by Django 3.2.3 on 2021-06-09 13:27
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('list', '0007_delete_userorder'),
]
operations = [
migrations.CreateModel(
name='userorder',
fields=[
('id', models.AutoField(primary_key=True, serialize=False)),
('time', models.DateTimeField(auto_now_add=True)),
('cd', models.BooleanField()),
('amount', models.IntegerField()),
('cost', models.FloatField()),
('total', models.FloatField()),
('tar', models.IntegerField()),
('username', models.CharField(max_length=128)),
],
options={
'verbose_name': '订单',
'ordering': ['time'],
},
),
]
| 0 | 813 | 25 |
da8f7395117236400bc244fab6d42b66306497f6 | 1,857 | py | Python | NN_PyTorch/12_RNN_regression.py | zhengxuanyu/NNByPytorch | f90b807a44234a48f914e03e45c9691f17eb3189 | [
"MIT"
] | 4 | 2019-03-17T07:51:20.000Z | 2020-02-18T20:39:16.000Z | NN_PyTorch/12_RNN_regression.py | zhengxuanyu/NNByPytorch | f90b807a44234a48f914e03e45c9691f17eb3189 | [
"MIT"
] | null | null | null | NN_PyTorch/12_RNN_regression.py | zhengxuanyu/NNByPytorch | f90b807a44234a48f914e03e45c9691f17eb3189 | [
"MIT"
] | null | null | null | import torch
from torch import nn
import numpy as np
import matplotlib.pyplot as plt
# hyper parameters
TIME_STEP = 10
INPUT_SIZE = 1
LR = 0.02
steps = np.linspace(0, np.pi * 2, 100, dtype=np.float32)
x_np = np.sin(steps)
y_np = np.cos(steps)
plt.plot(steps, y_np, 'r-', label='target (cos)')
plt.plot(steps, x_np, 'b-', label='input (sin)')
plt.legend(loc='best')
plt.show()
rnn = RNN()
print(rnn)
optimizer = torch.optim.Adam(rnn.parameters(), lr=LR)
loss_func = nn.MSELoss()
h_state = None
plt.figure(1, figsize=(12, 5))
plt.ion()
for step in range(100):
start, end = step * np.pi, (step + 1) * np.pi
# use sin predicts cos
steps = np.linspace(start, end, TIME_STEP, dtype=np.float32,
endpoint=False)
x_np = np.sin(steps)
y_np = np.cos(steps)
x = torch.from_numpy(x_np[np.newaxis, :, np.newaxis])
y = torch.from_numpy(y_np[np.newaxis, :, np.newaxis])
prediction, h_state = rnn(x, h_state)
h_state = h_state.data
loss = loss_func(prediction, y)
optimizer.zero_grad()
loss.backward()
optimizer.step()
plt.plot(steps, y_np.flatten(), 'r-')
plt.plot(steps, prediction.data.numpy().flatten(), 'b-')
plt.draw();
plt.pause(0.05)
plt.ioff()
plt.show() | 24.434211 | 65 | 0.584276 | import torch
from torch import nn
import numpy as np
import matplotlib.pyplot as plt
# hyper parameters
TIME_STEP = 10
INPUT_SIZE = 1
LR = 0.02
steps = np.linspace(0, np.pi * 2, 100, dtype=np.float32)
x_np = np.sin(steps)
y_np = np.cos(steps)
plt.plot(steps, y_np, 'r-', label='target (cos)')
plt.plot(steps, x_np, 'b-', label='input (sin)')
plt.legend(loc='best')
plt.show()
class RNN(nn.Module):
def __init__(self):
super(RNN, self).__init__()
self.rnn = nn.RNN(
input_size=INPUT_SIZE,
hidden_size=32,
num_layers=1,
batch_first=True,
)
self.out = nn.Linear(32, 1)
def forward(self, x, h_state):
r_out, h_state = self.rnn(x, h_state)
outs = []
for time_step in range(r_out.size(1)):
outs.append(self.out(r_out[:, time_step, :]))
return torch.stack(outs, dim=1), h_state
rnn = RNN()
print(rnn)
optimizer = torch.optim.Adam(rnn.parameters(), lr=LR)
loss_func = nn.MSELoss()
h_state = None
plt.figure(1, figsize=(12, 5))
plt.ion()
for step in range(100):
start, end = step * np.pi, (step + 1) * np.pi
# use sin predicts cos
steps = np.linspace(start, end, TIME_STEP, dtype=np.float32,
endpoint=False)
x_np = np.sin(steps)
y_np = np.cos(steps)
x = torch.from_numpy(x_np[np.newaxis, :, np.newaxis])
y = torch.from_numpy(y_np[np.newaxis, :, np.newaxis])
prediction, h_state = rnn(x, h_state)
h_state = h_state.data
loss = loss_func(prediction, y)
optimizer.zero_grad()
loss.backward()
optimizer.step()
plt.plot(steps, y_np.flatten(), 'r-')
plt.plot(steps, prediction.data.numpy().flatten(), 'b-')
plt.draw();
plt.pause(0.05)
plt.ioff()
plt.show() | 468 | 0 | 81 |
93243cb4b1ceea3e29fdf0c8924e9e481b0b1ddc | 1,478 | py | Python | deploy/create_dummy_notes.py | nonlinearfunction/gatsby-garden | ef8e60cf47300bcf709f20fb06ca4aa6f64c8a1c | [
"MIT"
] | null | null | null | deploy/create_dummy_notes.py | nonlinearfunction/gatsby-garden | ef8e60cf47300bcf709f20fb06ca4aa6f64c8a1c | [
"MIT"
] | null | null | null | deploy/create_dummy_notes.py | nonlinearfunction/gatsby-garden | ef8e60cf47300bcf709f20fb06ca4aa6f64c8a1c | [
"MIT"
] | 3 | 2022-02-22T22:38:47.000Z | 2022-02-25T15:17:49.000Z | import os
import re
import collections
NOTES_DIR = '/home/dave/nonlinearfunction/gatsby-garden/_notes'
md_files = [fname for fname in os.listdir(NOTES_DIR) if fname.endswith('.md')]
existing_notes = [fname[:-3] for fname in md_files]
refs = collections.defaultdict(int)
linked_notes = set()
for filename in md_files:
with open(os.path.join(NOTES_DIR, filename), 'r') as f:
md_str = f.read()
wikilinks = re.findall(r'\[\[([^\]]+)\]\]', md_str)
wikilinks = set([s.split('|')[0] for s in wikilinks])
for s in wikilinks:
refs[s] += 1
# print(f"File: {filename} wikilinks: {wikilinks}")
linked_notes = linked_notes.union(wikilinks)
new_notes = linked_notes - set(existing_notes)
trivial_notes = set()
for s in new_notes:
if refs[s] > 1:
print(f'creating {s} with {refs[s]} refs')
with open(os.path.join(NOTES_DIR, s + '.md'), 'w') as f:
f.write('')
else:
trivial_notes.add(s)
for filename in md_files:
with open(os.path.join(NOTES_DIR, filename), 'r') as f:
md_str = f.read()
for s in trivial_notes:
new_md_str = re.sub(r'\[\[' + s + r'(\|([^\]]+))?\]\]',
lambda m: m.group(2) if m.group(2) else s,
md_str)
if new_md_str != md_str:
print(f"{filename}: removed trivial link '{s}'")
md_str = new_md_str
with open(os.path.join(NOTES_DIR, filename), 'w') as f:
f.write(md_str)
| 32.844444 | 78 | 0.592693 | import os
import re
import collections
NOTES_DIR = '/home/dave/nonlinearfunction/gatsby-garden/_notes'
md_files = [fname for fname in os.listdir(NOTES_DIR) if fname.endswith('.md')]
existing_notes = [fname[:-3] for fname in md_files]
refs = collections.defaultdict(int)
linked_notes = set()
for filename in md_files:
with open(os.path.join(NOTES_DIR, filename), 'r') as f:
md_str = f.read()
wikilinks = re.findall(r'\[\[([^\]]+)\]\]', md_str)
wikilinks = set([s.split('|')[0] for s in wikilinks])
for s in wikilinks:
refs[s] += 1
# print(f"File: {filename} wikilinks: {wikilinks}")
linked_notes = linked_notes.union(wikilinks)
new_notes = linked_notes - set(existing_notes)
trivial_notes = set()
for s in new_notes:
if refs[s] > 1:
print(f'creating {s} with {refs[s]} refs')
with open(os.path.join(NOTES_DIR, s + '.md'), 'w') as f:
f.write('')
else:
trivial_notes.add(s)
for filename in md_files:
with open(os.path.join(NOTES_DIR, filename), 'r') as f:
md_str = f.read()
for s in trivial_notes:
new_md_str = re.sub(r'\[\[' + s + r'(\|([^\]]+))?\]\]',
lambda m: m.group(2) if m.group(2) else s,
md_str)
if new_md_str != md_str:
print(f"{filename}: removed trivial link '{s}'")
md_str = new_md_str
with open(os.path.join(NOTES_DIR, filename), 'w') as f:
f.write(md_str)
| 0 | 0 | 0 |
4ce6830e171dd240815c8a7847226c9f8a729bc9 | 1,517 | py | Python | web_app/end2end/pyteserract_engine.py | ikhovryak/PyTorchHackathon | 7a75edeccaee15ff142f9561c1c98fe49ca81e8c | [
"MIT"
] | 1 | 2020-07-28T15:41:36.000Z | 2020-07-28T15:41:36.000Z | web_app/end2end/pyteserract_engine.py | ikhovryak/PyTorchHackathon | 7a75edeccaee15ff142f9561c1c98fe49ca81e8c | [
"MIT"
] | null | null | null | web_app/end2end/pyteserract_engine.py | ikhovryak/PyTorchHackathon | 7a75edeccaee15ff142f9561c1c98fe49ca81e8c | [
"MIT"
] | 1 | 2020-08-25T04:03:48.000Z | 2020-08-25T04:03:48.000Z | import pytesseract
import numpy as np
import cv2
| 26.614035 | 109 | 0.55768 | import pytesseract
import numpy as np
import cv2
def recognize(img, bboxes):
(origH, origW) = img.shape[:2]
results = []
pytesseract.pytesseract.tesseract_cmd = 'C://Users//Samuel//AppData//Local//Tesseract-OCR//tesseract.exe'
for idx, ([l, t], [r, t], [r, b], [l, b]) in enumerate(bboxes):
poly = np.array(bboxes[idx]).astype(np.int32).reshape((-1))
poly = poly.reshape(-1, 2)
pts = poly.reshape((-1, 1, 2))
## (1) Crop the bounding rect
rect = cv2.boundingRect(pts)
x,y,w,h = rect
roi = img[y:y+h, x:x+w].copy()
## (2) make mask
pts = pts - pts.min(axis=0)
mask = np.zeros(roi.shape[:2], np.uint8)
cv2.drawContours(mask, [pts], -1, (255, 255, 255), -1, cv2.LINE_AA)
## (3) do bit-op
dst = cv2.bitwise_and(roi, roi, mask=mask)
## (4) add the white background
bg = np.ones_like(roi, np.uint8)*255
cv2.bitwise_not(bg,bg, mask=mask)
dst2 = bg+ dst
# channel_count = roi.shape[2] # i.e. 3 or 4 depending on your image
# ignore_mask_color = (255,) * channel_count
# cv2.fillPoly(mask, [poly.reshape((-1, 1, 2))], ignore_mask_color)
# masked_image = cv2.bitwise_or(roi, mask)
config = ("-l eng --oem 1 --psm 7")
text = pytesseract.image_to_string(dst2, config=config)
results.append((text, (l, r, t, b)))
# cv2.imshow(text, dst2)
# cv2.waitKey(0)
return results
| 1,438 | 0 | 23 |
8b4cc94a2766ab4f206771288749309a5b6b6ba4 | 769 | py | Python | miepy/vsh/__init__.py | johnaparker/MiePy | 5c5bb5a07c8ab79e9e2a9fc79fb9779e690147be | [
"MIT"
] | 3 | 2016-05-30T06:45:29.000Z | 2017-08-30T19:58:56.000Z | miepy/vsh/__init__.py | johnaparker/MiePy | 5c5bb5a07c8ab79e9e2a9fc79fb9779e690147be | [
"MIT"
] | null | null | null | miepy/vsh/__init__.py | johnaparker/MiePy | 5c5bb5a07c8ab79e9e2a9fc79fb9779e690147be | [
"MIT"
] | 5 | 2016-12-13T02:05:31.000Z | 2018-03-23T07:11:30.000Z | from . import special
from . import old_special
from .mode_indices import rmax_to_lmax, lmax_to_rmax, mode_indices
from .vsh_functions import (Emn, vsh_mode, get_zn, VSH, vsh_normalization_values,
get_zn_far, VSH_far, vsh_normalization_values_far)
from .vsh_translation import vsh_translation
from .vsh_rotation import vsh_rotation_matrix, rotate_expansion_coefficients
from .expansion import expand_E, expand_E_far, expand_H, expand_H_far
from .decomposition import (near_field_point_matching, far_field_point_matching,
integral_project_fields_onto, integral_project_fields,
integral_project_source, integral_project_source)
from .cluster_coefficients import cluster_coefficients
| 54.928571 | 82 | 0.775033 | from . import special
from . import old_special
from .mode_indices import rmax_to_lmax, lmax_to_rmax, mode_indices
from .vsh_functions import (Emn, vsh_mode, get_zn, VSH, vsh_normalization_values,
get_zn_far, VSH_far, vsh_normalization_values_far)
from .vsh_translation import vsh_translation
from .vsh_rotation import vsh_rotation_matrix, rotate_expansion_coefficients
from .expansion import expand_E, expand_E_far, expand_H, expand_H_far
from .decomposition import (near_field_point_matching, far_field_point_matching,
integral_project_fields_onto, integral_project_fields,
integral_project_source, integral_project_source)
from .cluster_coefficients import cluster_coefficients
| 0 | 0 | 0 |
0d16a7557165a155627b2b9afddb27bfca31e839 | 7,136 | py | Python | configs/functions.py | jordimas/spacy | 744783b56513f6d51baa40f3a4ccdac4a7b7533e | [
"MIT"
] | 13 | 2021-05-20T18:51:48.000Z | 2021-11-07T08:17:59.000Z | configs/functions.py | projecte-aina/spacy | 9996d385a036551c7ba0b20d1f0be976bf9c9c02 | [
"MIT"
] | 3 | 2021-05-20T17:52:01.000Z | 2021-06-22T20:10:24.000Z | configs/functions.py | projecte-aina/spacy | 9996d385a036551c7ba0b20d1f0be976bf9c9c02 | [
"MIT"
] | 2 | 2021-06-19T16:37:12.000Z | 2021-07-28T15:41:22.000Z | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Wed Apr 14 10:10:32 2021
@author: carlos.rodriguez1@bsc.es asier.gutierrez@bsc.es carme.armentano@bsc.es
"""
import spacy
import os
import json
from typing import List, Tuple, Optional
from thinc.api import Model
from spacy.pipeline import Lemmatizer
from spacy.tokens import Token
from spacy.language import Language
from spacy.lang.ca import Catalan
@spacy.registry.callbacks("before_callback")
@spacy.registry.misc("ca_lookups_loader")
@Catalan.factory(
"lemmatizer",
assigns=["token.lemma"],
default_config={"model": None, "mode": "rule", "overwrite": False},
default_score_weights={"lemma_acc": 1.0},
)
class CatalanLemmatizer(Lemmatizer):
"""
Copied from French Lemmatizer
Catalan language lemmatizer applies the default rule based lemmatization
procedure with some modifications for better Catalan language support.
The parts of speech 'ADV', 'PRON', 'DET', 'ADP' and 'AUX' are added to use
the rule-based lemmatization. As a last resort, the lemmatizer checks in
the lookup table.
"""
@classmethod
| 39.208791 | 134 | 0.565022 | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Wed Apr 14 10:10:32 2021
@author: carlos.rodriguez1@bsc.es asier.gutierrez@bsc.es carme.armentano@bsc.es
"""
import spacy
import os
import json
from typing import List, Tuple, Optional
from thinc.api import Model
from spacy.pipeline import Lemmatizer
from spacy.tokens import Token
from spacy.language import Language
from spacy.lang.ca import Catalan
@spacy.registry.callbacks("before_callback")
def create_callback():
from typing import Union, Iterator
from spacy.symbols import NOUN, PROPN, PRON
from spacy.errors import Errors
from spacy.tokens import Doc, Span
import re
def before_callback(nlp):
def _noun_chunks(doclike):
"""Detect base noun phrases from a dependency parse. Works on Doc and Span."""
# fmt: off
labels = ["nsubj", "nsubj:pass", "obj", "obl", "iobj", "ROOT", "appos", "nmod", "nmod:poss"]
# fmt: on
doc = doclike.doc # Ensure works on both Doc and Span.
if not doc.has_annotation("DEP"):
raise ValueError(Errors.E029)
np_deps = [doc.vocab.strings[label] for label in labels]
conj = doc.vocab.strings.add("conj")
np_label = doc.vocab.strings.add("NP")
prev_end = -1
for i, word in enumerate(doclike):
if word.pos not in (NOUN, PROPN):
continue
# Prevent nested chunks from being produced
if word.left_edge.i <= prev_end:
continue
if word.dep in np_deps:
left = word.left_edge.i
right = word.right_edge.i + 1
# leave prepositions and punctuation out of the left side of the chunk
if word.left_edge.pos_ == "ADP" or word.left_edge.pos_ == "PUNCT":
left = word.left_edge.i + 1
prev_end = word.right_edge.i
# leave subordinated clauses and appositions out of the chunk
a = word.i + 1
while a < word.right_edge.i:
paraula = doc[a]
if paraula.pos_ == "VERB":
right = paraula.left_edge.i
prev_end = paraula.left_edge.i -1
elif paraula.dep_ == "appos":
right = paraula.left_edge.i + 1
prev_end = paraula.left_edge.i -1
a += 1
# leave punctuation out of the right side of the chunk
if word.right_edge.pos_ == "PUNCT":
right = right - 1
yield left, right, np_label
nlp.Defaults.syntax_iterators = {"noun_chunks": _noun_chunks}
nlp.Defaults.infixes.insert(3, "('ls|'ns|'t|'m|'n|-les|-la|-lo|-los|-me|-nos|-te|-vos|-se|-hi|-ne|-ho)(?![A-Za-z])|(-l'|-n')")
nlp.Defaults.prefixes.insert(0, "-")
nlp.Defaults.suffixes.insert(0, "-")
return nlp
return before_callback
@spacy.registry.misc("ca_lookups_loader")
def load_lookups(data_path):
from spacy.lookups import Lookups
lookups = Lookups()
# "lemma_lookup", "lemma_rules", "lemma_exc", "lemma_index"
with open(os.path.join(data_path, 'ca_lemma_lookup.json'), 'r') as lemma_lookup, \
open(os.path.join(data_path, 'ca_lemma_rules.json'), 'r') as lemma_rules, \
open(os.path.join(data_path, 'ca_lemma_exc.json'), 'r') as lemma_exc, \
open(os.path.join(data_path, 'ca_lemma_index.json'), 'r') as lemma_index:
lookups.add_table('lemma_lookup', json.load(lemma_lookup))
lookups.add_table('lemma_rules', json.load(lemma_rules))
lookups.add_table('lemma_exc', json.load(lemma_exc))
lookups.add_table('lemma_index', json.load(lemma_index))
return lookups
@Catalan.factory(
"lemmatizer",
assigns=["token.lemma"],
default_config={"model": None, "mode": "rule", "overwrite": False},
default_score_weights={"lemma_acc": 1.0},
)
def make_lemmatizer(
nlp: Language, model: Optional[Model], name: str, mode: str, overwrite: bool = False
):
return CatalanLemmatizer(nlp.vocab, model, name, mode=mode, overwrite=overwrite)
class CatalanLemmatizer(Lemmatizer):
"""
Copied from French Lemmatizer
Catalan language lemmatizer applies the default rule based lemmatization
procedure with some modifications for better Catalan language support.
The parts of speech 'ADV', 'PRON', 'DET', 'ADP' and 'AUX' are added to use
the rule-based lemmatization. As a last resort, the lemmatizer checks in
the lookup table.
"""
@classmethod
def get_lookups_config(cls, mode: str) -> Tuple[List[str], List[str]]:
if mode == "rule":
required = ["lemma_lookup", "lemma_rules", "lemma_exc", "lemma_index"]
return (required, [])
else:
return super().get_lookups_config(mode)
def rule_lemmatize(self, token: Token) -> List[str]:
cache_key = (token.orth, token.pos)
if cache_key in self.cache:
return self.cache[cache_key]
string = token.text
univ_pos = token.pos_.lower()
if univ_pos in ("", "eol", "space"):
return [string.lower()]
elif "lemma_rules" not in self.lookups or univ_pos not in (
"noun",
"verb",
"adj",
"adp",
"adv",
"aux",
"cconj",
"det",
"pron",
"punct",
"sconj",
):
return self.lookup_lemmatize(token)
index_table = self.lookups.get_table("lemma_index", {})
exc_table = self.lookups.get_table("lemma_exc", {})
rules_table = self.lookups.get_table("lemma_rules", {})
lookup_table = self.lookups.get_table("lemma_lookup", {})
index = index_table.get(univ_pos, {})
exceptions = exc_table.get(univ_pos, {})
rules = rules_table.get(univ_pos, [])
string = string.lower()
forms = []
if string in index:
forms.append(string)
self.cache[cache_key] = forms
return forms
forms.extend(exceptions.get(string, []))
oov_forms = []
if not forms:
for old, new in rules:
if string.endswith(old):
form = string[: len(string) - len(old)] + new
if not form:
pass
elif form in index or not form.isalpha():
forms.append(form)
else:
oov_forms.append(form)
if not forms:
forms.extend(oov_forms)
if not forms and string in lookup_table.keys():
forms.append(self.lookup_lemmatize(token)[0])
if not forms:
forms.append(string)
forms = list(set(forms))
self.cache[cache_key] = forms
return forms
| 5,884 | 0 | 119 |
112fa1db8bb60617eed4f20b4464c5f9ef683ed2 | 389 | py | Python | algovenv/lib/python3.8/site-packages/algosdk/abi/reference.py | jakobrichert/RichDAO | fa4934fb4fb9673aa529c4c1ec072b39a6974030 | [
"MIT"
] | null | null | null | algovenv/lib/python3.8/site-packages/algosdk/abi/reference.py | jakobrichert/RichDAO | fa4934fb4fb9673aa529c4c1ec072b39a6974030 | [
"MIT"
] | null | null | null | algovenv/lib/python3.8/site-packages/algosdk/abi/reference.py | jakobrichert/RichDAO | fa4934fb4fb9673aa529c4c1ec072b39a6974030 | [
"MIT"
] | 2 | 2022-03-21T13:13:50.000Z | 2022-03-24T15:09:59.000Z | from typing import Any
| 18.52381 | 42 | 0.66838 | from typing import Any
class ABIReferenceType:
# Account reference type
ACCOUNT = "account"
# Application reference type
APPLICATION = "application"
# Asset reference type
ASSET = "asset"
def is_abi_reference_type(t: Any) -> bool:
return t in (
ABIReferenceType.ACCOUNT,
ABIReferenceType.APPLICATION,
ABIReferenceType.ASSET,
)
| 149 | 169 | 46 |
02f3a1ffa6d264785465aa55ffbca59961bdd325 | 5,918 | py | Python | BLU.py | AdroitAdorKhan/EnergizedBlu | 6c48bf9f1a91b37ff07086692a8afc92818d60fe | [
"MIT"
] | null | null | null | BLU.py | AdroitAdorKhan/EnergizedBlu | 6c48bf9f1a91b37ff07086692a8afc92818d60fe | [
"MIT"
] | null | null | null | BLU.py | AdroitAdorKhan/EnergizedBlu | 6c48bf9f1a91b37ff07086692a8afc92818d60fe | [
"MIT"
] | null | null | null | #!/usr/bin/python3
# -*- coding: utf-8 -*-
# Energized Blu
import urllib.request
import datetime
import os
import time
File = 'energized/blu'
List = []
# Thanks to all maintainers of hosts lists.
Sources = [
'https://raw.githubusercontent.com/AdroitAdorKhan/Energized/master/EnergizedHosts/EnergizedHosts',
'https://raw.githubusercontent.com/StevenBlack/hosts/master/alternates/fakenews-gambling/hosts',
'http://someonewhocares.org/hosts/zero/',
'https://hblock.molinero.xyz/hosts',
'https://raw.githubusercontent.com/EnergizedProtection/EnergizedTools/master/Mirror/MoaAB/MoaAB.active.txt',
'https://raw.githubusercontent.com/hoshsadiq/adblock-nocoin-list/master/hosts.txt',
'https://raw.githubusercontent.com/Yhonay/antipopads/master/hosts',
'https://raw.githubusercontent.com/notracking/hosts-blocklists/master/hostnames.txt',
'https://raw.githubusercontent.com/FadeMind/hosts.extras/master/add.2o7Net/hosts',
'https://raw.githubusercontent.com/FadeMind/hosts.extras/master/add.Dead/hosts',
'https://raw.githubusercontent.com/FadeMind/hosts.extras/master/add.Risk/hosts',
'https://raw.githubusercontent.com/FadeMind/hosts.extras/master/add.Spam/hosts',
'https://raw.githubusercontent.com/EnergizedProtection/EnergizedTools/master/Converter/Hosts/ZeusTracker.txt',
'https://raw.githubusercontent.com/StevenBlack/hosts/master/data/StevenBlack/hosts',
'https://zerodot1.gitlab.io/CoinBlockerLists/hosts_browser',
'https://zerodot1.gitlab.io/CoinBlockerLists/hosts',
'https://raw.githubusercontent.com/EnergizedProtection/EnergizedTools/master/Converter/Hosts/Spam404.txt',
'https://raw.githubusercontent.com/CHEF-KOCH/NSABlocklist/master/HOSTS',
'https://raw.githubusercontent.com/azet12/KADhosts/master/KADhosts.txt',
'https://raw.githubusercontent.com/EnergizedProtection/EnergizedTools/master/Converter/Hosts/AdguardMobileSpyware.txt',
'https://raw.githubusercontent.com/EnergizedProtection/EnergizedTools/master/Converter/Hosts/AdguardTracking.txt',
'https://raw.githubusercontent.com/EnergizedProtection/EnergizedTools/master/Converter/Hosts/EasylistAdserver.txt',
'https://raw.githubusercontent.com/EnergizedProtection/EnergizedTools/master/Converter/Hosts/EasyPrivacySpecific.txt',
'https://raw.githubusercontent.com/EnergizedProtection/EnergizedTools/master/Converter/Hosts/EasyPrivacyTracking.txt',
'https://raw.githubusercontent.com/EnergizedProtection/EnergizedTools/master/Converter/Hosts/DisconnectMEAds.txt',
'https://raw.githubusercontent.com/EnergizedProtection/EnergizedTools/master/Converter/Hosts/DisconnectMEMalvertising.txt',
'https://raw.githubusercontent.com/EnergizedProtection/EnergizedTools/master/Converter/Hosts/DisconnectMEMalware.txt',
'https://raw.githubusercontent.com/EnergizedProtection/EnergizedTools/master/Converter/Hosts/Wally3K_Blacklist.txt'
]
for Link in Sources:
try:
print('[+] Retrieving list from: {}'.format(Link))
r = urllib.request.urlopen(Link)
Host = r.readlines()
Host = [x.decode('UTF-8') for x in Host]
Host = [x.strip() for x in Host]
Host = [z for z in Host if z != '' and z[0] != '#']
Host = [h.split()[1] for h in Host if h.split()[0] in ['0.0.0.0', '127.0.0.1']]
Host = [x for x in Host if x not in ['localhost', 'localhost.localdomain', 'locals']]
print('[+] Found {} domains to block.'.format(str(len(Host))))
r.close()
List += Host
except:
print('[-] ERROR: I can\'t retrieve the list from: {}'.format(Link))
print('[+] Removing duplicates and sorting...')
List = sorted(list(set(List)))
print('[+] Applying whitelist...')
r = urllib.request.urlopen('https://raw.githubusercontent.com/AdroitAdorKhan/Energized/master/EnergizedHosts/EnergizedWhites')
Whitelist = r.readlines()
Whitelist = [x.decode('utf-8') for x in Whitelist]
Whitelist = [x.strip() for x in Whitelist]
Whitelist = [z for z in Whitelist if z != '' and z[0] != '#']
r.close()
for i in range(0, len(Whitelist)):
try:
List.remove(Whitelist[i])
except:
pass
print('[+] Total domains count {}.'.format(str(len(List))))
if not os.path.exists(os.path.dirname(File)):
os.makedirs(os.path.dirname(File))
with open(File, 'w') as f:
print('[+] Writing to file...')
f.write('''# Energized - ad.porn.malware blocking.\n# A merged collection of hosts from reputable sources.\n# https://ador.chorompotro.com\n\n# Energized Blu - Lightweight Energized Protection.\n# Version: ''' + time.strftime("%y.%m.%j", time.gmtime()) + '''\n# Project Git: https://github.com/EnergizedProtection/EnergizedBlu\n# RAW Source: https://raw.githubusercontent.com/EnergizedProtection/EnergizedBlu/master/energized/blu\n# Last updated: {}'''.format(datetime.datetime.now().strftime('%a, %d %b %y %X')))
f.write('''\n# Total Domains: {}\n\n'''.format(str(len(List))))
f.write('''\n# -================-Maintainer-================-\n# Nayem Ador - https://adroitadorkhan.github.io\n# -============================================-\n\n''')
f.write('''\n127.0.0.1 localhost\n127.0.0.1 localhost.localdomain\n127.0.0.1 local\n255.255.255.255 broadcasthost\n::1 localhost\n::1 ip6-localhost\n::1 ip6-loopback\nfe80::1%lo0 localhost\nff00::0 ip6-localnet\nff00::0 ip6-mcastprefix\nff02::1 ip6-allnodes\nff02::2 ip6-allrouters\nff02::3 ip6-allhosts\n0.0.0.0 0.0.0.0\n\n\n# -====================-Features-====================-\n# # Lightweight Energized Protection Ever! #\n#\n# - Based on Hosts file, all the bad stuff blocked with 0.0.0.0 \n# - Compatible with all devices, regardless of OS. \n# - Strictly blocks all advertisements, malwares, spams, statistics, trackers on both web browsing and applications. \n# - YouTube, Spotify, UC and Shareit Ads Blocking. \n# - Reduces page loading time. \n# - Reduces data consumptions. Saves data expenses. \n# - Increases privacy. \n# - No extra abracadabra!\n#\n# -==================================================-\n\n\n''')
f.write('\n'.join('0.0.0.0 ' + url for url in List))
print('[+] Done!')
| 65.755556 | 932 | 0.723893 | #!/usr/bin/python3
# -*- coding: utf-8 -*-
# Energized Blu
import urllib.request
import datetime
import os
import time
File = 'energized/blu'
List = []
# Thanks to all maintainers of hosts lists.
Sources = [
'https://raw.githubusercontent.com/AdroitAdorKhan/Energized/master/EnergizedHosts/EnergizedHosts',
'https://raw.githubusercontent.com/StevenBlack/hosts/master/alternates/fakenews-gambling/hosts',
'http://someonewhocares.org/hosts/zero/',
'https://hblock.molinero.xyz/hosts',
'https://raw.githubusercontent.com/EnergizedProtection/EnergizedTools/master/Mirror/MoaAB/MoaAB.active.txt',
'https://raw.githubusercontent.com/hoshsadiq/adblock-nocoin-list/master/hosts.txt',
'https://raw.githubusercontent.com/Yhonay/antipopads/master/hosts',
'https://raw.githubusercontent.com/notracking/hosts-blocklists/master/hostnames.txt',
'https://raw.githubusercontent.com/FadeMind/hosts.extras/master/add.2o7Net/hosts',
'https://raw.githubusercontent.com/FadeMind/hosts.extras/master/add.Dead/hosts',
'https://raw.githubusercontent.com/FadeMind/hosts.extras/master/add.Risk/hosts',
'https://raw.githubusercontent.com/FadeMind/hosts.extras/master/add.Spam/hosts',
'https://raw.githubusercontent.com/EnergizedProtection/EnergizedTools/master/Converter/Hosts/ZeusTracker.txt',
'https://raw.githubusercontent.com/StevenBlack/hosts/master/data/StevenBlack/hosts',
'https://zerodot1.gitlab.io/CoinBlockerLists/hosts_browser',
'https://zerodot1.gitlab.io/CoinBlockerLists/hosts',
'https://raw.githubusercontent.com/EnergizedProtection/EnergizedTools/master/Converter/Hosts/Spam404.txt',
'https://raw.githubusercontent.com/CHEF-KOCH/NSABlocklist/master/HOSTS',
'https://raw.githubusercontent.com/azet12/KADhosts/master/KADhosts.txt',
'https://raw.githubusercontent.com/EnergizedProtection/EnergizedTools/master/Converter/Hosts/AdguardMobileSpyware.txt',
'https://raw.githubusercontent.com/EnergizedProtection/EnergizedTools/master/Converter/Hosts/AdguardTracking.txt',
'https://raw.githubusercontent.com/EnergizedProtection/EnergizedTools/master/Converter/Hosts/EasylistAdserver.txt',
'https://raw.githubusercontent.com/EnergizedProtection/EnergizedTools/master/Converter/Hosts/EasyPrivacySpecific.txt',
'https://raw.githubusercontent.com/EnergizedProtection/EnergizedTools/master/Converter/Hosts/EasyPrivacyTracking.txt',
'https://raw.githubusercontent.com/EnergizedProtection/EnergizedTools/master/Converter/Hosts/DisconnectMEAds.txt',
'https://raw.githubusercontent.com/EnergizedProtection/EnergizedTools/master/Converter/Hosts/DisconnectMEMalvertising.txt',
'https://raw.githubusercontent.com/EnergizedProtection/EnergizedTools/master/Converter/Hosts/DisconnectMEMalware.txt',
'https://raw.githubusercontent.com/EnergizedProtection/EnergizedTools/master/Converter/Hosts/Wally3K_Blacklist.txt'
]
for Link in Sources:
try:
print('[+] Retrieving list from: {}'.format(Link))
r = urllib.request.urlopen(Link)
Host = r.readlines()
Host = [x.decode('UTF-8') for x in Host]
Host = [x.strip() for x in Host]
Host = [z for z in Host if z != '' and z[0] != '#']
Host = [h.split()[1] for h in Host if h.split()[0] in ['0.0.0.0', '127.0.0.1']]
Host = [x for x in Host if x not in ['localhost', 'localhost.localdomain', 'locals']]
print('[+] Found {} domains to block.'.format(str(len(Host))))
r.close()
List += Host
except:
print('[-] ERROR: I can\'t retrieve the list from: {}'.format(Link))
print('[+] Removing duplicates and sorting...')
List = sorted(list(set(List)))
print('[+] Applying whitelist...')
r = urllib.request.urlopen('https://raw.githubusercontent.com/AdroitAdorKhan/Energized/master/EnergizedHosts/EnergizedWhites')
Whitelist = r.readlines()
Whitelist = [x.decode('utf-8') for x in Whitelist]
Whitelist = [x.strip() for x in Whitelist]
Whitelist = [z for z in Whitelist if z != '' and z[0] != '#']
r.close()
for i in range(0, len(Whitelist)):
try:
List.remove(Whitelist[i])
except:
pass
print('[+] Total domains count {}.'.format(str(len(List))))
if not os.path.exists(os.path.dirname(File)):
os.makedirs(os.path.dirname(File))
with open(File, 'w') as f:
print('[+] Writing to file...')
f.write('''# Energized - ad.porn.malware blocking.\n# A merged collection of hosts from reputable sources.\n# https://ador.chorompotro.com\n\n# Energized Blu - Lightweight Energized Protection.\n# Version: ''' + time.strftime("%y.%m.%j", time.gmtime()) + '''\n# Project Git: https://github.com/EnergizedProtection/EnergizedBlu\n# RAW Source: https://raw.githubusercontent.com/EnergizedProtection/EnergizedBlu/master/energized/blu\n# Last updated: {}'''.format(datetime.datetime.now().strftime('%a, %d %b %y %X')))
f.write('''\n# Total Domains: {}\n\n'''.format(str(len(List))))
f.write('''\n# -================-Maintainer-================-\n# Nayem Ador - https://adroitadorkhan.github.io\n# -============================================-\n\n''')
f.write('''\n127.0.0.1 localhost\n127.0.0.1 localhost.localdomain\n127.0.0.1 local\n255.255.255.255 broadcasthost\n::1 localhost\n::1 ip6-localhost\n::1 ip6-loopback\nfe80::1%lo0 localhost\nff00::0 ip6-localnet\nff00::0 ip6-mcastprefix\nff02::1 ip6-allnodes\nff02::2 ip6-allrouters\nff02::3 ip6-allhosts\n0.0.0.0 0.0.0.0\n\n\n# -====================-Features-====================-\n# # Lightweight Energized Protection Ever! #\n#\n# - Based on Hosts file, all the bad stuff blocked with 0.0.0.0 \n# - Compatible with all devices, regardless of OS. \n# - Strictly blocks all advertisements, malwares, spams, statistics, trackers on both web browsing and applications. \n# - YouTube, Spotify, UC and Shareit Ads Blocking. \n# - Reduces page loading time. \n# - Reduces data consumptions. Saves data expenses. \n# - Increases privacy. \n# - No extra abracadabra!\n#\n# -==================================================-\n\n\n''')
f.write('\n'.join('0.0.0.0 ' + url for url in List))
print('[+] Done!')
| 0 | 0 | 0 |
76b4ca5d35739f772e19658316215cfc154e9849 | 1,804 | py | Python | rain_notice.py | NekoSarada1101/secretary-slack-bot | fba66ad8227ce71af32c756971bf10e2517267ea | [
"MIT"
] | null | null | null | rain_notice.py | NekoSarada1101/secretary-slack-bot | fba66ad8227ce71af32c756971bf10e2517267ea | [
"MIT"
] | 12 | 2021-02-13T10:28:51.000Z | 2021-02-28T03:24:14.000Z | rain_notice.py | NekoSarada1101/secretary-slack-bot | fba66ad8227ce71af32c756971bf10e2517267ea | [
"MIT"
] | null | null | null | import json
import requests
from settings import *
if __name__ == "__main__":
post_rain_notice()
| 33.407407 | 96 | 0.675721 | import json
import requests
from settings import *
def post_rain_notice():
weather_data = fetch_hourly_weather_data() # type: dict
payload = create_rain_notice_payload(weather_data) # type: json
if payload is not None:
response = requests.post(SLACK_WEBHOOK_URL, payload)
print(response)
def fetch_hourly_weather_data() -> dict:
url = ("https://api.openweathermap.org/data/2.5/onecall?lat={}&lon={}&appid={}&"
"exclude=current,daily,minutely,alerts&units=metric&lang=ja"
.format(LAT_LNG[0], LAT_LNG[1], OPEN_WEATHER_API_KEY)) # type: str
response = requests.get(url)
print(response)
weather_data = json.loads(response.text) # type: dict
return weather_data
def create_rain_notice_payload(weather_data: dict) -> json:
try:
precipitation = weather_data["hourly"][0]["rain"]["1h"]
except KeyError:
print("No rain.")
return
precipitation_level = [10, 20, 30, 50, 80]
if precipitation < precipitation_level[0]:
message = "弱い雨が降りそうです。\n傘があると良いかもしれません。\n"
elif precipitation < precipitation_level[1]:
message = "やや強い雨が降りそうです。\n傘があると良いかもしれません。\n"
elif precipitation < precipitation_level[2]:
message = "強い雨が降りそうです。\n傘があると良いかもしれません。\n"
elif precipitation < precipitation_level[3]:
message = "激しい雨が降りそうです。\n外出は控えたほうが良いかもしれません。\n"
elif precipitation < precipitation_level[4]:
message = "非常に激しい雨が降りそうです。\n危険ですので外出はやめましょう。\n"
else:
message = "猛烈な雨が降りそうです。\n危険ですので外出はやめましょう。\n"
data = {"text": "<@{}>{}【1時間以内の予想降水量:{}mm/h】".format(SLACK_USER_ID, message, precipitation)}
print(data)
json_data = json.dumps(data).encode("utf-8") # type: json
return json_data
if __name__ == "__main__":
post_rain_notice()
| 1,995 | 0 | 69 |
283b6cc570cf7a896902cda895d5564271cab7a7 | 8,526 | py | Python | src/redrawing/components/pipeline.py | ReDrawing/redrawing | 20743f0c8d64d9d2e15cefa840423c9698c74653 | [
"MIT"
] | 1 | 2021-04-20T00:00:15.000Z | 2021-04-20T00:00:15.000Z | src/redrawing/components/pipeline.py | ReDrawing/redrawing | 20743f0c8d64d9d2e15cefa840423c9698c74653 | [
"MIT"
] | null | null | null | src/redrawing/components/pipeline.py | ReDrawing/redrawing | 20743f0c8d64d9d2e15cefa840423c9698c74653 | [
"MIT"
] | 1 | 2021-07-18T03:57:01.000Z | 2021-07-18T03:57:01.000Z | from collections import deque
from abc import ABC, abstractmethod
from multiprocessing import Queue as MQueue
from multiprocessing import Process
from redrawing.components.stage import Stage
class Queue(ABC):
'''!
Generic queue for communication between stages.
'''
@abstractmethod
def get(self):
'''!
Returns the first element of the queue.
Returns:
@returns the first element of the queue
'''
...
@abstractmethod
def insert(self, value):
'''!
Insert a value in the end of the queue.
Parameters:
@param value - the value
'''
...
@abstractmethod
def empty(self):
'''!
See if the queue is empty.
Returns:
@returns True if empty
'''
...
@abstractmethod
def full(self):
'''!
See if the queue if full
Returns:
@returns True if full
'''
...
class SimpleQueue(Queue):
'''!
A simple queue. Must not be used for multiprocessing
Uses collections.deque for implement the queue
'''
def get(self):
'''!
Returns the first element of the queue.
Returns:
@returns the first element of the queue
'''
return self.queue.popleft()
def insert(self, value):
'''!
Insert a value in the end of the queue.
Parameters:
@param value - the value
'''
self.queue.append(value)
def empty(self):
'''!
See if the queue is empty.
Returns:
@returns True if empty
'''
if len(self.queue) > 0:
return False
return True
def full(self):
'''!
See if the queue if full
Returns:
@returns True if full
'''
if len(self.queue) >= self.max_size:
return True
return False
class ProcessQueue(Queue):
'''!
Queue for using in multiprocessing.
For single process pipeline, SimpleQueue is better
Uses multiprocessing.queue for implement the queue
'''
def get(self):
'''!
Returns the first element of the queue.
Returns:
@returns the first element of the queue
'''
return self.queue.get()
def insert(self, value):
'''!
Insert a value in the end of the queue.
Parameters:
@param value - the value
'''
self.queue.put(value)
def empty(self):
'''!
See if the queue is empty.
Returns:
@returns True if empty
'''
return self.queue.empty()
def full(self):
'''!
See if the queue if full
Returns:
@returns True if full
'''
return self.queue.full()
class Pipeline(ABC):
'''!
Generic pipeline of stages
'''
def insert_stage(self, stage):
'''!
Inserts a new stage to the pipeline
Parameters:
@param state - the stage
@todo Alterar para o tipo correto de exceção
'''
if not isinstance(stage, Stage):
raise Exception("Stages must be of Stage class")
if stage in self.substages:
return
self.stages.append(stage)
self.substages_configs[stage] = []
@abstractmethod
def create_connection(self, stage_out, id_out, stage_in, id_in, max_size):
'''!
Create a connection between stages
Parameters:
@param stage_out - Stage where the data will come from
@param id_out - ID of the output communication channel
@param stage_in - Stage from where the data will go
@param id_in - ID of the input communication channel
@param max_size - Maximum channel queue size
'''
queue = None
if stage_in.has_input_queue(id_in):
queue = stage_in.input_queue[id_in]
else:
queue = self.create_queue(max_size)
stage_in._setInputQueue(queue, id_in)
stage_out._setOutputQueue(queue, id_out)
@abstractmethod
def run(self):
'''!
Runs the pipeline until error/exception
'''
...
class SingleProcess_Pipeline(Pipeline):
'''!
Pipeline of stages to be runned on a single process
'''
def start(self):
'''!
Starts the stages
Is automatically called by the run and runOnce method
'''
for stage in self.stages:
for substage in self.substages_configs[stage]:
substage["substage"].setup()
stage.setup()
self.started = True
def run(self):
'''!
Runs the pipeline until error/exception
'''
if not self.started:
self.start()
while True:
self.runOnce()
def runOnce(self):
'''!
Runs all the stages once
'''
if not self.started:
self.start()
for stage in self.stages:
for substage in self.substages_configs[stage]:
if substage["run_before"] == True:
substage["substage"].run(stage._context)
stage.run()
for substage in self.substages_configs[stage]:
if substage["run_before"] == False:
substage["substage"].run(stage._context)
class MultiProcess_Pipeline(Pipeline):
'''!
Pipeline of stages runned parallely on multiple process
'''
def _run_stage(self, stage):
'''!
Starts and runs a stage
Parameters:
@param stage - stage to be runned
'''
for substage in self.substages_configs[stage]:
substage["substage"].setup()
stage.setup()
while True:
for substage in self.substages_configs[stage]:
if substage["run_before"] == True:
substage["substage"].run(stage._context)
stage.run()
for substage in self.substages_configs[stage]:
if substage["run_before"] == False:
substage["substage"].run(stage._context)
def run(self):
'''!
Run the stages on multiple process.
Locks the code until the stages end
'''
process = []
for stage in self.stages:
p = Process(target=self._run_stage, args=(stage,))
p.start()
process.append(p)
while 1:
try:
pass
except KeyboardInterrupt:
break
print("TERMINANDO")
for p in process:
p.terminate()
p.join(1)
p.close()
| 23.105691 | 98 | 0.521229 | from collections import deque
from abc import ABC, abstractmethod
from multiprocessing import Queue as MQueue
from multiprocessing import Process
from redrawing.components.stage import Stage
class Queue(ABC):
'''!
Generic queue for communication between stages.
'''
def __init__(self, max_size):
self.max_size = max_size
@abstractmethod
def get(self):
'''!
Returns the first element of the queue.
Returns:
@returns the first element of the queue
'''
...
@abstractmethod
def insert(self, value):
'''!
Insert a value in the end of the queue.
Parameters:
@param value - the value
'''
...
@abstractmethod
def empty(self):
'''!
See if the queue is empty.
Returns:
@returns True if empty
'''
...
@abstractmethod
def full(self):
'''!
See if the queue if full
Returns:
@returns True if full
'''
...
class SimpleQueue(Queue):
'''!
A simple queue. Must not be used for multiprocessing
Uses collections.deque for implement the queue
'''
def __init__(self, max_size):
super().__init__(max_size)
self.queue = deque(maxlen=max_size)
def get(self):
'''!
Returns the first element of the queue.
Returns:
@returns the first element of the queue
'''
return self.queue.popleft()
def insert(self, value):
'''!
Insert a value in the end of the queue.
Parameters:
@param value - the value
'''
self.queue.append(value)
def empty(self):
'''!
See if the queue is empty.
Returns:
@returns True if empty
'''
if len(self.queue) > 0:
return False
return True
def full(self):
'''!
See if the queue if full
Returns:
@returns True if full
'''
if len(self.queue) >= self.max_size:
return True
return False
class ProcessQueue(Queue):
'''!
Queue for using in multiprocessing.
For single process pipeline, SimpleQueue is better
Uses multiprocessing.queue for implement the queue
'''
def __init__(self, max_size):
super().__init__(max_size)
self.queue = MQueue(maxsize=max_size)
def get(self):
'''!
Returns the first element of the queue.
Returns:
@returns the first element of the queue
'''
return self.queue.get()
def insert(self, value):
'''!
Insert a value in the end of the queue.
Parameters:
@param value - the value
'''
self.queue.put(value)
def empty(self):
'''!
See if the queue is empty.
Returns:
@returns True if empty
'''
return self.queue.empty()
def full(self):
'''!
See if the queue if full
Returns:
@returns True if full
'''
return self.queue.full()
class Pipeline(ABC):
'''!
Generic pipeline of stages
'''
def __init__(self):
self.stages = []
self.substages = []
self.substages_configs = {}
def insert_stage(self, stage):
'''!
Inserts a new stage to the pipeline
Parameters:
@param state - the stage
@todo Alterar para o tipo correto de exceção
'''
if not isinstance(stage, Stage):
raise Exception("Stages must be of Stage class")
if stage in self.substages:
return
self.stages.append(stage)
self.substages_configs[stage] = []
@abstractmethod
def create_queue(self, max_size):
...
def create_connection(self, stage_out, id_out, stage_in, id_in, max_size):
'''!
Create a connection between stages
Parameters:
@param stage_out - Stage where the data will come from
@param id_out - ID of the output communication channel
@param stage_in - Stage from where the data will go
@param id_in - ID of the input communication channel
@param max_size - Maximum channel queue size
'''
queue = None
if stage_in.has_input_queue(id_in):
queue = stage_in.input_queue[id_in]
else:
queue = self.create_queue(max_size)
stage_in._setInputQueue(queue, id_in)
stage_out._setOutputQueue(queue, id_out)
def set_substage(self, superstage, substage, run_before=False):
if substage not in self.substages:
self.substages.append(substage)
if substage in self.stages:
self.stages.remove(substage)
if not superstage in self.substages_configs:
self.substages_configs[superstage] = []
self.substages_configs[superstage].append({"substage":substage, "run_before": run_before})
superstage.substages.append(substage)
@abstractmethod
def run(self):
'''!
Runs the pipeline until error/exception
'''
...
class SingleProcess_Pipeline(Pipeline):
'''!
Pipeline of stages to be runned on a single process
'''
def __init__(self):
super().__init__()
self.started = False
pass
def start(self):
'''!
Starts the stages
Is automatically called by the run and runOnce method
'''
for stage in self.stages:
for substage in self.substages_configs[stage]:
substage["substage"].setup()
stage.setup()
self.started = True
def run(self):
'''!
Runs the pipeline until error/exception
'''
if not self.started:
self.start()
while True:
self.runOnce()
def runOnce(self):
'''!
Runs all the stages once
'''
if not self.started:
self.start()
for stage in self.stages:
for substage in self.substages_configs[stage]:
if substage["run_before"] == True:
substage["substage"].run(stage._context)
stage.run()
for substage in self.substages_configs[stage]:
if substage["run_before"] == False:
substage["substage"].run(stage._context)
def create_queue(self, max_size):
return SimpleQueue(max_size)
class MultiProcess_Pipeline(Pipeline):
'''!
Pipeline of stages runned parallely on multiple process
'''
def __init__(self):
super().__init__()
def create_queue(self, max_size):
return ProcessQueue(max_size)
def _run_stage(self, stage):
'''!
Starts and runs a stage
Parameters:
@param stage - stage to be runned
'''
for substage in self.substages_configs[stage]:
substage["substage"].setup()
stage.setup()
while True:
for substage in self.substages_configs[stage]:
if substage["run_before"] == True:
substage["substage"].run(stage._context)
stage.run()
for substage in self.substages_configs[stage]:
if substage["run_before"] == False:
substage["substage"].run(stage._context)
def run(self):
'''!
Run the stages on multiple process.
Locks the code until the stages end
'''
process = []
for stage in self.stages:
p = Process(target=self._run_stage, args=(stage,))
p.start()
process.append(p)
while 1:
try:
pass
except KeyboardInterrupt:
break
print("TERMINANDO")
for p in process:
p.terminate()
p.join(1)
p.close()
| 997 | 0 | 269 |
4a3c1abfc423f8d49d93f8f5e11b9a9e20bf58b5 | 15,365 | py | Python | contrib/script/py/pybase/pyopmo.py | michaelweiss092/LillyMol | a2b7d1d8a07ef338c754a0a2e3b2624aac694cc9 | [
"Apache-2.0"
] | 53 | 2018-06-01T13:16:15.000Z | 2022-02-23T21:04:28.000Z | contrib/script/py/pybase/pyopmo.py | michaelweiss092/LillyMol | a2b7d1d8a07ef338c754a0a2e3b2624aac694cc9 | [
"Apache-2.0"
] | 19 | 2018-08-14T13:43:18.000Z | 2021-09-24T12:53:11.000Z | contrib/script/py/pybase/pyopmo.py | michaelweiss092/LillyMol | a2b7d1d8a07ef338c754a0a2e3b2624aac694cc9 | [
"Apache-2.0"
] | 19 | 2018-10-23T19:41:01.000Z | 2022-02-17T08:14:00.000Z | """
Contains Python "bindings" to molecule object and Python functions
utilizing molecule object key functionalities
The intent is to provide a Pythonic interface to mo utilities and, thus,
enable easy/consistent use of mo from within python programs.
Testing:
$ python <path-to-location>/pymo.py
"""
import os
import subprocess as sp
import shlex
import shutil
import sys
import argparse
import logging
import unittest
from tempfile import NamedTemporaryFile, mkdtemp
log = logging.getLogger('lilly.' + __name__)
log.addHandler(logging.NullHandler())
build_dir = 'Linux'
try:
build_dir = os.environ['BUILD_DIR']
except EnvironmentError:
pass
home_dir = os.environ['LILLYMOL_HOME']
root_dir = home_dir + '/bin/' + build_dir
# dictionary of commands that will be turned into functions
# function_name: [script_name, debug_message, default_params_dict]
mo_tool_map = {
'dicer': [root_dir + '/dicer',
'Recursively cuts molecules based on queries',
{}],
'fileconv': [root_dir + '/fileconv',
'file/molecule conversion utilities',
{}],
'iwdescr': [root_dir + '/iwdescr',
'compute physicochemical descriptors using iwdescr',
{'-l': ''}],
'make_these_molecules': [root_dir + '/make_these_molecules',
'Makes molecules from isotopically labelled '
'reagents according to make file, not '
'combinatorial join',
{}],
'preferred_smiles': [root_dir + '/preferred_smiles',
'',
{}],
'alogp': [root_dir + '/abraham',
'',
{'-l': '',
'-F': home_dir + '/contrib/data/queries/abraham/Abraham',
'-P': home_dir + '/contrib/data/queries/abraham/Alpha2H',
'-g': 'all' }]
}
def __function_generator(fct_name,
script_name,
debug_msg,
default_params_dict,
expect_zero=True):
"""
A generator for functions which runs one of LillyMol scripts with a
predefined set of parameters.
:param str fct_name: the function name of the newly generated function
:param script_name: your LillyMol script path (from mo_tool above)
:param debug_msg: quick message about what the script does (from mo_tool above)
:param default_params_dict: default parameters
:param expect_zero: whether to expect zero as a return value from the script
:return: a function which you can call to run the script
:rtype: callable
"""
funct.__name__ = fct_name
funct.__doc__ = debug_msg
return funct
for name, params in list(mo_tool_map.items()):
nparams = len(params)
if not (3 <= nparams <= 5):
raise IndexError('mo_tool_map: "{}" has {:d} parameter(s) but should '
'have 3-5'.format(name, nparams))
locals()[name] = __function_generator(name, *params)
def make_these_molecules(rgnt_list, make_these_file, reaction_file_list, outfile=None, params_dict={}, debug=True,
loggero=None):
"""
Alternative to trxn, used in MMP code for generating new mols from MMP's, trxn version would be alternative:
For connecting one bond (two components, single cut fragments):
trxn.sh -S - -r oneConnection.rxn partOne.smi partTwo.smi
For connecting two bonds (three component, two cut fragments):
trxn.sh -S -rxn -S - -r twoConnection.rxn partThree.smi partOne.smi partTwo.smi
BUT, if we have a long list of different contexts (partOne) and don't want exhaustive enumeration, specify rxn's:
make_these_molecules.sh -R oneConnection.rxn -M m2Make.txt -S - partOne.smi partTwo.smi
In this case, you can put all context fragments SMILES (context1a, context 1b, ...) in one reagent file, and
all fragments SMILES (frag1, frag2, ...) in the second reagent file. If you have something like (context1a frag1\n
context1a frag2\ncontext1b frag3\n...) in your m2Make.txt file, you will create the molecules you wanted
"""
log.debug("Generating virtual compounds using rxn and reagents supplied plus specified combinations file")
# prep reagents file string
rgnt_string = " ".join(rgnt_list)
log.debug("These are the reagent files...." + str(rgnt_string))
# prep params string
params_string = " "
for k, v in list(params_dict.items()):
params_string += k + " " + v + " "
params_string = params_string[:-1]
# set outfile
# improved a bit to handle files with '.' in main name, other than in the extension
if outfile:
if outfile[-4:] == ".smi" or outfile[-4:] == ".txt":
params_string += " -S " + os.path.splitext(outfile)[0]
else:
params_string += " -S " + outfile
reaction_file = ""
for rxn_file in reaction_file_list: # todo: if single string, this is split in characters
reaction_file += ' -R ' + rxn_file
cmd_line = (mo_tool_map['make_these_molecules'][0] + reaction_file +
' -M ' + make_these_file + " " + params_string + " " +
rgnt_string)
log.debug("Executing: %s" % cmd_line)
#if debug:
#print(cmd_line)
my_proc = sp.Popen(shlex.split(cmd_line), stdout=None, stderr=sp.PIPE,
shell=False)
for line in my_proc.stderr.readlines():
log.debug(line.rstrip())
exit_status = my_proc.wait()
log.debug("Done generating compounds")
return exit_status
#####################################################
class _TestPymo(unittest.TestCase):
"""Test class for pymo module
Example usage:
python pymo.py (to execute all tests)
python pymo.py -c (for verbose console logging)
python pymo.py -f mylog.log (for logging to file mylog.log)
python pymo.py -c -f mylog.log (for both)
python pymo.py _Test_pymo.test_fetch_smiles # (to execute only the specified test)
coverage run pymo.py (to run test code coverage analysis)
coverage report pymo.py (to view the result of the test code coverage analysis)
"""
def setUp(self):
"""setup test data location, unittest config and logger"""
# location of test data
self.test_data_location = root_dir + '/contrib/script/py/mmp/testdata/'
# temp output file and dir
self.temp_inp_file = NamedTemporaryFile(encoding='utf-8', mode='wt', suffix='.smi', delete=False)
self.temp_out_file = NamedTemporaryFile(encoding='utf-8', mode='wt', delete=False)
self.temp_out_dir = mkdtemp()
test_smiles = {
# basic test set - all the below id's and structures are CHEMBL
'3105327': 'Cc1ccc2c(ccn2c3nc(cs3)c4cc(ccc4F)C(F)(F)F)c1',
'1526778': 'CC(=O)c1c(C)n(c(C)c1C(=O)C)c2nc(c(C)s2)c3ccc(C)c(C)c3',
'1494678': 'CC(=O)c1c(C)n(c(C)c1C(=O)C)c2nc(c(C)s2)c3ccccc3',
'472166': 'OC(CCn1ccnc1)(c2ccccc2)c3ccccc3',
'69798': 'Cc1nccn1CCC(O)(c2ccccc2)c3ccccc3',
'367346': 'Cc1sc(N)nc1c2cccc(Cl)c2',
'366881': 'Cc1sc(N)nc1c2ccc(Cl)c(Cl)c2',
'1477460': 'COc1ccc(cc1)c2nc(sc2C)n3c(C)c(C(=O)C)c(C(=O)C)c3C',
'1441050': 'COc1ccc(cc1OC)c2nc(sc2C)n3c(C)c(C(=O)C)c(C(=O)C)c3C'
}
# write test data to temp file 01
for smi_id, smi in test_smiles.items():
string = smi+' '+smi_id+'\n'
self.temp_inp_file.write(string)
self.temp_inp_file.close()
def tearDown(self):
"""cleanup test data and settings"""
# Clean up the directory
# os.removedirs(self.temp_out_dir)
shutil.rmtree(self.temp_out_dir)
if __name__ == "__main__":
# optional command line flags
parser = argparse.ArgumentParser()
parser.add_argument('-l', '--log_file',
help='Name of file to place debug log info in')
parser.add_argument('-c', '--console',
help='Switch on console logging',
default=False,
action='store_true')
args = parser.parse_args()
#print(args)
logger_file = args.log_file
console_on = args.console
pymotest_logger = logging.getLogger("pymo.testlogger")
pymotest_logger.setLevel(logging.DEBUG)
log_formatter = logging.Formatter("%(asctime)s [%(funcName)-12.12s] "
"[%(levelname)-5.5s] %(message)s",
datefmt="%Y-%m-%d %H:%M:%S")
if console_on:
print("Switched on console")
h1 = logging.StreamHandler(stream=sys.stdout)
h1.setLevel(logging.DEBUG)
h1.setFormatter(log_formatter)
pymotest_logger.addHandler(h1)
else:
print("console off")
if logger_file is not None:
print(("Switched on logging to file: {}".format(logger_file)))
fileHandler = logging.FileHandler(filename=logger_file)
fileHandler.setFormatter(log_formatter)
fileHandler.setLevel(logging.DEBUG)
pymotest_logger.addHandler(fileHandler)
else:
print("file logging off")
if console_on is False and logger_file is None:
pymotest_logger.setLevel(logging.CRITICAL)
unittest.main()
| 37.844828 | 177 | 0.589391 | """
Contains Python "bindings" to molecule object and Python functions
utilizing molecule object key functionalities
The intent is to provide a Pythonic interface to mo utilities and, thus,
enable easy/consistent use of mo from within python programs.
Testing:
$ python <path-to-location>/pymo.py
"""
import os
import subprocess as sp
import shlex
import shutil
import sys
import argparse
import logging
import unittest
from tempfile import NamedTemporaryFile, mkdtemp
log = logging.getLogger('lilly.' + __name__)
log.addHandler(logging.NullHandler())
build_dir = 'Linux'
try:
build_dir = os.environ['BUILD_DIR']
except EnvironmentError:
pass
home_dir = os.environ['LILLYMOL_HOME']
root_dir = home_dir + '/bin/' + build_dir
# dictionary of commands that will be turned into functions
# function_name: [script_name, debug_message, default_params_dict]
mo_tool_map = {
'dicer': [root_dir + '/dicer',
'Recursively cuts molecules based on queries',
{}],
'fileconv': [root_dir + '/fileconv',
'file/molecule conversion utilities',
{}],
'iwdescr': [root_dir + '/iwdescr',
'compute physicochemical descriptors using iwdescr',
{'-l': ''}],
'make_these_molecules': [root_dir + '/make_these_molecules',
'Makes molecules from isotopically labelled '
'reagents according to make file, not '
'combinatorial join',
{}],
'preferred_smiles': [root_dir + '/preferred_smiles',
'',
{}],
'alogp': [root_dir + '/abraham',
'',
{'-l': '',
'-F': home_dir + '/contrib/data/queries/abraham/Abraham',
'-P': home_dir + '/contrib/data/queries/abraham/Alpha2H',
'-g': 'all' }]
}
def __function_generator(fct_name,
script_name,
debug_msg,
default_params_dict,
expect_zero=True):
"""
A generator for functions which runs one of LillyMol scripts with a
predefined set of parameters.
:param str fct_name: the function name of the newly generated function
:param script_name: your LillyMol script path (from mo_tool above)
:param debug_msg: quick message about what the script does (from mo_tool above)
:param default_params_dict: default parameters
:param expect_zero: whether to expect zero as a return value from the script
:return: a function which you can call to run the script
:rtype: callable
"""
def funct(infile, outfile=None, params_dict=default_params_dict,
params_input_string=None, loggero=None, pretend=False,
altret=False, inpipe=False):
# Use param_input_string when a dictionary can not be used
# e.g. tsubstructure.sh -A M -A D
log.debug('funct = %s: ' % script_name + debug_msg)
params_string = ' '
if params_input_string:
params_string += params_input_string + ' '
for k, v in list(params_dict.items()):
if type(v) is list:
for vv in v:
params_string += k + ' ' + vv + ' '
else:
params_string += k + ' ' + str(v) + ' '
params_string = params_string[:-1]
if type(infile) is list:
infile_s = ' '.join(infile)
elif infile is None:
infile_s = ''
else:
infile_s = infile
cmd_2_execute = script_name + params_string + ' '
if not inpipe:
cmd_2_execute += infile_s
out_fh = None
if altret:
out_fh = sp.PIPE
elif outfile:
out_fh = open(outfile, 'w')
if pretend:
log.warning('Just pretending')
exit_status = 0
else:
cmd = shlex.split(cmd_2_execute)
log.info('Executing: {}'.format(cmd_2_execute))
#print('Executing: {}'.format(cmd_2_execute))
# FIXME: this gets really ugly now...
if inpipe:
my_proc = sp.Popen(cmd, stdin=sp.PIPE, stdout=out_fh,
stderr=sp.PIPE, shell=False)
# FIXME: Python2
out, err = my_proc.communicate(infile_s.encode('utf-8'))
else:
my_proc = sp.Popen(cmd, stdout=out_fh, stderr=sp.PIPE,
shell=False)
out, err = my_proc.communicate()
exit_status = my_proc.returncode
# NOTE: Python2 returns strings so need to check
# FIXME: this needs to be simplified as soon as everything is
# Python3
if type(err) == bytes:
err = err.decode('utf-8')
if type(out) == bytes:
out = out.decode('utf-8')
if outfile:
out_fh.close()
if exit_status and expect_zero:
log.error("%s failed:\n%s" % (script_name, cmd_2_execute))
if err:
log.error(err)
else:
log.debug("Done: " + debug_msg)
# very ugly workaround for this mis-designed function
if not altret:
return exit_status
else:
return exit_status, out, err
funct.__name__ = fct_name
funct.__doc__ = debug_msg
return funct
for name, params in list(mo_tool_map.items()):
nparams = len(params)
if not (3 <= nparams <= 5):
raise IndexError('mo_tool_map: "{}" has {:d} parameter(s) but should '
'have 3-5'.format(name, nparams))
locals()[name] = __function_generator(name, *params)
def make_these_molecules(rgnt_list, make_these_file, reaction_file_list, outfile=None, params_dict={}, debug=True,
loggero=None):
"""
Alternative to trxn, used in MMP code for generating new mols from MMP's, trxn version would be alternative:
For connecting one bond (two components, single cut fragments):
trxn.sh -S - -r oneConnection.rxn partOne.smi partTwo.smi
For connecting two bonds (three component, two cut fragments):
trxn.sh -S -rxn -S - -r twoConnection.rxn partThree.smi partOne.smi partTwo.smi
BUT, if we have a long list of different contexts (partOne) and don't want exhaustive enumeration, specify rxn's:
make_these_molecules.sh -R oneConnection.rxn -M m2Make.txt -S - partOne.smi partTwo.smi
In this case, you can put all context fragments SMILES (context1a, context 1b, ...) in one reagent file, and
all fragments SMILES (frag1, frag2, ...) in the second reagent file. If you have something like (context1a frag1\n
context1a frag2\ncontext1b frag3\n...) in your m2Make.txt file, you will create the molecules you wanted
"""
log.debug("Generating virtual compounds using rxn and reagents supplied plus specified combinations file")
# prep reagents file string
rgnt_string = " ".join(rgnt_list)
log.debug("These are the reagent files...." + str(rgnt_string))
# prep params string
params_string = " "
for k, v in list(params_dict.items()):
params_string += k + " " + v + " "
params_string = params_string[:-1]
# set outfile
# improved a bit to handle files with '.' in main name, other than in the extension
if outfile:
if outfile[-4:] == ".smi" or outfile[-4:] == ".txt":
params_string += " -S " + os.path.splitext(outfile)[0]
else:
params_string += " -S " + outfile
reaction_file = ""
for rxn_file in reaction_file_list: # todo: if single string, this is split in characters
reaction_file += ' -R ' + rxn_file
cmd_line = (mo_tool_map['make_these_molecules'][0] + reaction_file +
' -M ' + make_these_file + " " + params_string + " " +
rgnt_string)
log.debug("Executing: %s" % cmd_line)
#if debug:
#print(cmd_line)
my_proc = sp.Popen(shlex.split(cmd_line), stdout=None, stderr=sp.PIPE,
shell=False)
for line in my_proc.stderr.readlines():
log.debug(line.rstrip())
exit_status = my_proc.wait()
log.debug("Done generating compounds")
return exit_status
#####################################################
class _TestPymo(unittest.TestCase):
"""Test class for pymo module
Example usage:
python pymo.py (to execute all tests)
python pymo.py -c (for verbose console logging)
python pymo.py -f mylog.log (for logging to file mylog.log)
python pymo.py -c -f mylog.log (for both)
python pymo.py _Test_pymo.test_fetch_smiles # (to execute only the specified test)
coverage run pymo.py (to run test code coverage analysis)
coverage report pymo.py (to view the result of the test code coverage analysis)
"""
def setUp(self):
"""setup test data location, unittest config and logger"""
# location of test data
self.test_data_location = root_dir + '/contrib/script/py/mmp/testdata/'
# temp output file and dir
self.temp_inp_file = NamedTemporaryFile(encoding='utf-8', mode='wt', suffix='.smi', delete=False)
self.temp_out_file = NamedTemporaryFile(encoding='utf-8', mode='wt', delete=False)
self.temp_out_dir = mkdtemp()
test_smiles = {
# basic test set - all the below id's and structures are CHEMBL
'3105327': 'Cc1ccc2c(ccn2c3nc(cs3)c4cc(ccc4F)C(F)(F)F)c1',
'1526778': 'CC(=O)c1c(C)n(c(C)c1C(=O)C)c2nc(c(C)s2)c3ccc(C)c(C)c3',
'1494678': 'CC(=O)c1c(C)n(c(C)c1C(=O)C)c2nc(c(C)s2)c3ccccc3',
'472166': 'OC(CCn1ccnc1)(c2ccccc2)c3ccccc3',
'69798': 'Cc1nccn1CCC(O)(c2ccccc2)c3ccccc3',
'367346': 'Cc1sc(N)nc1c2cccc(Cl)c2',
'366881': 'Cc1sc(N)nc1c2ccc(Cl)c(Cl)c2',
'1477460': 'COc1ccc(cc1)c2nc(sc2C)n3c(C)c(C(=O)C)c(C(=O)C)c3C',
'1441050': 'COc1ccc(cc1OC)c2nc(sc2C)n3c(C)c(C(=O)C)c(C(=O)C)c3C'
}
# write test data to temp file 01
for smi_id, smi in test_smiles.items():
string = smi+' '+smi_id+'\n'
self.temp_inp_file.write(string)
self.temp_inp_file.close()
def tearDown(self):
"""cleanup test data and settings"""
# Clean up the directory
# os.removedirs(self.temp_out_dir)
shutil.rmtree(self.temp_out_dir)
def test_fileconv(self):
log.debug("Testing fileconv")
exit_status = fileconv(os.path.join(self.test_data_location, self.temp_inp_file.name),
params_dict={'-v': '',
'-c': '10',
'-C': '20',
'-S': os.path.join(self.temp_out_dir, 'atomcountfilter'),
'-o': 'smi'}
)
log.debug("fileconv return code was: %s" % exit_status)
self.assertEqual(exit_status, 0)
def test_make_these_molecules(self):
log.debug("Testing _make_these_molecules")
# test data from mmp_enum_mols_from_pairs.py
context = NamedTemporaryFile(encoding='utf-8', mode='wt', suffix='.smi', delete=False)
examp_context = "[1CH3]CCCCCC partOne_1\n[1CH3]CCCCCCC partOne_2\n[1CH3]CCCCCCCC partOne_3\n[1CH3]CCCCCCCCC partOne_4\n[1CH3]CCCCCCCCCC partOne_5"
context.write(examp_context)
context.close()
frags = NamedTemporaryFile(encoding='utf-8', mode='wt', suffix='.smi', delete=False)
examp_frags = "[1OH]CCCCCC partTwo_1\n[1OH]CCCCCCC partTwo_2\n[1OH]CCCCCCCC partTwo_3\n[1OH]CCCCCCCCC partTwo_4\n[1OH]CCCCCCCCCC partTwo_5\n[1OH]CCCCCCCCCCC partTwo_6\n"
frags.write(examp_frags)
frags.close()
make_instr = NamedTemporaryFile(encoding='utf-8', mode='wt', delete=False)
examp_make_instr = "partOne_2 partTwo_3\npartOne_4 partTwo_5\n"
make_instr.write(examp_make_instr)
make_instr.close()
rxn = NamedTemporaryFile(encoding='utf-8', mode='wt', suffix='.rxn', delete=False)
# this is the reaction specification that trxn needs to combine isotopically labelled mmp fragmentation points
single_rxn = "(0 Reaction\n (0 Scaffold\n (A C smarts \"[!0*]\")\n (A I isotope (0 0))\n )\n"
single_rxn += " (1 Sidechain\n (A C smarts \"[!0*]\")\n (A I isotope (0 0))\n (A I join (0 0))\n )\n)"
rxn.write(single_rxn)
rxn.close()
exit_status = make_these_molecules([context.name, frags.name],
make_instr.name,
[rxn.name])
log.debug("make_these_molecules return code was: %s" % exit_status)
self.assertEqual(exit_status, 0)
def test_dicer(self):
log.debug("Testing dicer")
log.debug("Testing %s" % dicer.__name__)
exit_status = dicer(os.path.join(self.test_data_location, self.temp_inp_file.name),
os.path.join(self.temp_out_dir, 'dicer.out'),
params_dict={}, )
log.debug("dicer return code was: %s" % exit_status)
self.assertEqual(exit_status, 0)
def test_alogp(self):
log.debug("Testing CMI")
exit_status = alogp(os.path.join(self.test_data_location, self.temp_inp_file.name),
os.path.join(self.temp_out_dir, 'alogp.out')
)
log.debug("CMI return code was: %s" % exit_status)
self.assertEqual(exit_status, 0)
if __name__ == "__main__":
# optional command line flags
parser = argparse.ArgumentParser()
parser.add_argument('-l', '--log_file',
help='Name of file to place debug log info in')
parser.add_argument('-c', '--console',
help='Switch on console logging',
default=False,
action='store_true')
args = parser.parse_args()
#print(args)
logger_file = args.log_file
console_on = args.console
pymotest_logger = logging.getLogger("pymo.testlogger")
pymotest_logger.setLevel(logging.DEBUG)
log_formatter = logging.Formatter("%(asctime)s [%(funcName)-12.12s] "
"[%(levelname)-5.5s] %(message)s",
datefmt="%Y-%m-%d %H:%M:%S")
if console_on:
print("Switched on console")
h1 = logging.StreamHandler(stream=sys.stdout)
h1.setLevel(logging.DEBUG)
h1.setFormatter(log_formatter)
pymotest_logger.addHandler(h1)
else:
print("console off")
if logger_file is not None:
print(("Switched on logging to file: {}".format(logger_file)))
fileHandler = logging.FileHandler(filename=logger_file)
fileHandler.setFormatter(log_formatter)
fileHandler.setLevel(logging.DEBUG)
pymotest_logger.addHandler(fileHandler)
else:
print("file logging off")
if console_on is False and logger_file is None:
pymotest_logger.setLevel(logging.CRITICAL)
unittest.main()
| 5,828 | 0 | 135 |
0154cd266d10abdb84725065fd8a7273dbc5e6fd | 5,068 | py | Python | tests/component/records/pandas/test_prep_for_csv.py | ellyteitsworth/records-mover | 21cd56efc2d23cfff04ec1fdf582e5229546c418 | [
"Apache-2.0"
] | null | null | null | tests/component/records/pandas/test_prep_for_csv.py | ellyteitsworth/records-mover | 21cd56efc2d23cfff04ec1fdf582e5229546c418 | [
"Apache-2.0"
] | null | null | null | tests/component/records/pandas/test_prep_for_csv.py | ellyteitsworth/records-mover | 21cd56efc2d23cfff04ec1fdf582e5229546c418 | [
"Apache-2.0"
] | null | null | null | import pandas as pd
# import pytz
import unittest
from records_mover.records.pandas import prep_df_for_csv_output
from records_mover.records.schema import RecordsSchema
from records_mover.records import DelimitedRecordsFormat, ProcessingInstructions
| 41.203252 | 88 | 0.474743 | import pandas as pd
# import pytz
import unittest
from records_mover.records.pandas import prep_df_for_csv_output
from records_mover.records.schema import RecordsSchema
from records_mover.records import DelimitedRecordsFormat, ProcessingInstructions
class TestPrepForCsv(unittest.TestCase):
def test_prep_df_for_csv_output_no_include_index(self):
schema_data = {
'schema': "bltypes/v1",
'fields': {
"date": {
"type": "date",
"index": 1,
},
"time": {
"type": "time",
"index": 2,
},
"timetz": {
"type": "timetz",
"index": 3,
},
}
}
records_format = DelimitedRecordsFormat(variant='bluelabs')
records_schema = RecordsSchema.from_data(schema_data)
processing_instructions = ProcessingInstructions()
# us_eastern = pytz.timezone('US/Eastern')
data = {
'date': [pd.Timestamp(year=1970, month=1, day=1)],
'time': [
pd.Timestamp(year=1970, month=1, day=1,
hour=12, minute=33, second=53, microsecond=1234)
],
# timetz is not well supported in records mover yet. For
# instance, specifying how it's turned into a CSV is not
# currently part of the records spec:
#
# https://github.com/bluelabsio/records-mover/issues/76
#
# In addition, Vertica suffers from a driver limitation:
#
# https://github.com/bluelabsio/records-mover/issues/77
#
# 'timetz': [
# us_eastern.localize(pd.Timestamp(year=1970, month=1, day=1,
# hour=12, minute=33, second=53,
# microsecond=1234)),
# ],
}
df = pd.DataFrame(data,
columns=['date', 'time', 'timetz'])
new_df = prep_df_for_csv_output(df=df,
include_index=False,
records_schema=records_schema,
records_format=records_format,
processing_instructions=processing_instructions)
self.assertEqual(new_df['date'][0], '1970-01-01')
self.assertEqual(new_df['time'][0], '12:33:53')
# self.assertEqual(new_df['timetz'][0], '12:33:53-05')
self.assertIsNotNone(new_df)
def test_prep_df_for_csv_output_include_index(self):
schema_data = {
'schema': "bltypes/v1",
'fields': {
"date": {
"type": "date",
"index": 1,
},
"time": {
"type": "time",
"index": 2,
},
"timetz": {
"type": "timetz",
"index": 3,
},
}
}
records_format = DelimitedRecordsFormat(variant='bluelabs')
records_schema = RecordsSchema.from_data(schema_data)
processing_instructions = ProcessingInstructions()
# us_eastern = pytz.timezone('US/Eastern')
data = {
'time': [
pd.Timestamp(year=1970, month=1, day=1,
hour=12, minute=33, second=53, microsecond=1234)
],
# timetz is not well supported in records mover yet. For
# instance, specifying how it's turned into a CSV is not
# currently part of the records spec:
#
# https://github.com/bluelabsio/records-mover/issues/76
#
# In addition, Vertica suffers from a driver limitation:
#
# https://github.com/bluelabsio/records-mover/issues/77
#
# 'timetz': [
# us_eastern.localize(pd.Timestamp(year=1970, month=1, day=1,
# hour=12, minute=33, second=53,
# microsecond=1234)),
# ],
}
df = pd.DataFrame(data,
index=[pd.Timestamp(year=1970, month=1, day=1)],
columns=['time', 'timetz'])
new_df = prep_df_for_csv_output(df=df,
include_index=True,
records_schema=records_schema,
records_format=records_format,
processing_instructions=processing_instructions)
self.assertEqual(new_df.index[0], '1970-01-01')
self.assertEqual(new_df['time'][0], '12:33:53')
# self.assertEqual(new_df['timetz'][0], '12:33:53-05')
self.assertIsNotNone(new_df)
| 4,722 | 19 | 76 |
c9ccdca949047698e5e603d5b345ed50a3281268 | 7,103 | py | Python | pytorch/New_Tuts/sequential_tasks.py | DanielMabadeje/Artificial-Intelligence-Deep-Learning-Machine-Learning-Tutorials | 7adab3877fc1d3f1d5f57e6c1743dae8f76f72c5 | [
"Apache-2.0"
] | 3,266 | 2017-08-06T16:51:46.000Z | 2022-03-30T07:34:24.000Z | pytorch/New_Tuts/sequential_tasks.py | hashDanChibueze/Artificial-Intelligence-Deep-Learning-Machine-Learning-Tutorials | bef2c415d154a052c00e99a05f0870af7a5819ac | [
"Apache-2.0"
] | 150 | 2017-08-28T14:59:36.000Z | 2022-03-11T23:21:35.000Z | pytorch/New_Tuts/sequential_tasks.py | hashDanChibueze/Artificial-Intelligence-Deep-Learning-Machine-Learning-Tutorials | bef2c415d154a052c00e99a05f0870af7a5819ac | [
"Apache-2.0"
] | 1,449 | 2017-08-06T17:40:59.000Z | 2022-03-31T12:03:24.000Z | import numpy as np
from tensorflow.python.keras.utils import Sequence, to_categorical
from tensorflow.python.keras.preprocessing.sequence import pad_sequences
class TemporalOrderExp6aSequence(Sequence):
"""
From Hochreiter&Schmidhuber(1997):
The goal is to classify sequences. Elements and targets are represented locally
(input vectors with only one non-zero bit). The sequence starts with an E, ends
with a B (the "trigger symbol") and otherwise consists of randomly chosen symbols
from the set {a, b, c, d} except for two elements at positions t1 and t2 that are
either X or Y . The sequence length is randomly chosen between 100 and 110, t1 is
randomly chosen between 10 and 20, and t2 is randomly chosen between 50 and 60.
There are 4 sequence classes Q, R, S, U which depend on the temporal order of X and Y.
The rules are:
X, X -> Q,
X, Y -> R,
Y , X -> S,
Y , Y -> U.
"""
# encoding/decoding single instance version
# encoding/decoding batch versions
def __len__(self):
""" Let's assume 1000 sequences as the size of data. """
return int(1000. / self.batch_size)
class DifficultyLevel:
""" On HARD, settings are identical to the original settings from the '97 paper."""
EASY, NORMAL, MODERATE, HARD, NIGHTMARE = range(5)
@staticmethod
| 36.055838 | 94 | 0.602562 | import numpy as np
from tensorflow.python.keras.utils import Sequence, to_categorical
from tensorflow.python.keras.preprocessing.sequence import pad_sequences
class EchoData(Sequence):
def __init__(self, series_length=40000, batch_size=32,
echo_step=3, truncated_length=10, seed=None):
self.series_length = series_length
self.truncated_length = truncated_length
self.n_batches = series_length//truncated_length
self.echo_step = echo_step
self.batch_size = batch_size
if seed is not None:
np.random.seed(seed)
self.raw_x = None
self.raw_y = None
self.x_batches = []
self.y_batches = []
self.generate_new_series()
self.prepare_batches()
def __getitem__(self, index):
if index == 0:
self.generate_new_series()
self.prepare_batches()
return self.x_batches[index], self.y_batches[index]
def __len__(self):
return self.n_batches
def generate_new_series(self):
x = np.random.choice(
2,
size=(self.batch_size, self.series_length),
p=[0.5, 0.5])
y = np.roll(x, self.echo_step, axis=1)
y[:, 0:self.echo_step] = 0
self.raw_x = x
self.raw_y = y
def prepare_batches(self):
x = np.expand_dims(self.raw_x, axis=-1)
y = np.expand_dims(self.raw_y, axis=-1)
self.x_batches = np.split(x, self.n_batches, axis=1)
self.y_batches = np.split(y, self.n_batches, axis=1)
class TemporalOrderExp6aSequence(Sequence):
"""
From Hochreiter&Schmidhuber(1997):
The goal is to classify sequences. Elements and targets are represented locally
(input vectors with only one non-zero bit). The sequence starts with an E, ends
with a B (the "trigger symbol") and otherwise consists of randomly chosen symbols
from the set {a, b, c, d} except for two elements at positions t1 and t2 that are
either X or Y . The sequence length is randomly chosen between 100 and 110, t1 is
randomly chosen between 10 and 20, and t2 is randomly chosen between 50 and 60.
There are 4 sequence classes Q, R, S, U which depend on the temporal order of X and Y.
The rules are:
X, X -> Q,
X, Y -> R,
Y , X -> S,
Y , Y -> U.
"""
def __init__(self, length_range=(100, 111), t1_range=(10, 21), t2_range=(50, 61),
batch_size=32, seed=None):
self.classes = ['Q', 'R', 'S', 'U']
self.n_classes = len(self.classes)
self.relevant_symbols = ['X', 'Y']
self.distraction_symbols = ['a', 'b', 'c', 'd']
self.start_symbol = 'B'
self.end_symbol = 'E'
self.length_range = length_range
self.t1_range = t1_range
self.t2_range = t2_range
self.batch_size = batch_size
if seed is not None:
np.random.seed(seed)
all_symbols = self.relevant_symbols + self.distraction_symbols + \
[self.start_symbol] + [self.end_symbol]
self.n_symbols = len(all_symbols)
self.s_to_idx = {s: n for n, s in enumerate(all_symbols)}
self.idx_to_s = {n: s for n, s in enumerate(all_symbols)}
self.c_to_idx = {c: n for n, c in enumerate(self.classes)}
self.idx_to_c = {n: c for n, c in enumerate(self.classes)}
def generate_pair(self):
length = np.random.randint(self.length_range[0], self.length_range[1])
t1 = np.random.randint(self.t1_range[0], self.t1_range[1])
t2 = np.random.randint(self.t2_range[0], self.t2_range[1])
x = np.random.choice(self.distraction_symbols, length)
x[0] = self.start_symbol
x[-1] = self.end_symbol
y = np.random.choice(self.classes)
if y == 'Q':
x[t1], x[t2] = self.relevant_symbols[0], self.relevant_symbols[0]
elif y == 'R':
x[t1], x[t2] = self.relevant_symbols[0], self.relevant_symbols[1]
elif y == 'S':
x[t1], x[t2] = self.relevant_symbols[1], self.relevant_symbols[0]
else:
x[t1], x[t2] = self.relevant_symbols[1], self.relevant_symbols[1]
return ''.join(x), y
# encoding/decoding single instance version
def encode_x(self, x):
idx_x = [self.s_to_idx[s] for s in x]
return to_categorical(idx_x, num_classes=self.n_symbols)
def encode_y(self, y):
idx_y = self.c_to_idx[y]
return to_categorical(idx_y, num_classes=self.n_classes)
def decode_x(self, x):
x = x[np.sum(x, axis=1) > 0] # remove padding
return ''.join([self.idx_to_s[pos] for pos in np.argmax(x, axis=1)])
def decode_y(self, y):
return self.idx_to_c[np.argmax(y)]
# encoding/decoding batch versions
def encode_x_batch(self, x_batch):
return pad_sequences([self.encode_x(x) for x in x_batch],
maxlen=self.length_range[1])
def encode_y_batch(self, y_batch):
return np.array([self.encode_y(y) for y in y_batch])
def decode_x_batch(self, x_batch):
return [self.decode_x(x) for x in x_batch]
def decode_y_batch(self, y_batch):
return [self.idx_to_c[pos] for pos in np.argmax(y_batch, axis=1)]
def __len__(self):
""" Let's assume 1000 sequences as the size of data. """
return int(1000. / self.batch_size)
def __getitem__(self, index):
batch_x, batch_y = [], []
for _ in range(self.batch_size):
x, y = self.generate_pair()
batch_x.append(x)
batch_y.append(y)
return self.encode_x_batch(batch_x), self.encode_y_batch(batch_y)
class DifficultyLevel:
""" On HARD, settings are identical to the original settings from the '97 paper."""
EASY, NORMAL, MODERATE, HARD, NIGHTMARE = range(5)
@staticmethod
def get_predefined_generator(difficulty_level, batch_size=32, seed=8382):
EASY = TemporalOrderExp6aSequence.DifficultyLevel.EASY
NORMAL = TemporalOrderExp6aSequence.DifficultyLevel.NORMAL
MODERATE = TemporalOrderExp6aSequence.DifficultyLevel.MODERATE
HARD = TemporalOrderExp6aSequence.DifficultyLevel.HARD
if difficulty_level == EASY:
length_range = (7, 9)
t1_range = (1, 3)
t2_range = (4, 6)
elif difficulty_level == NORMAL:
length_range = (30, 41)
t1_range = (2, 6)
t2_range = (20, 28)
elif difficulty_level == MODERATE:
length_range = (60, 81)
t1_range = (10, 21)
t2_range = (45, 55)
elif difficulty_level == HARD:
length_range = (100, 111)
t1_range = (10, 21)
t2_range = (50, 61)
else:
length_range = (300, 501)
t1_range = (10, 81)
t2_range = (250, 291)
return TemporalOrderExp6aSequence(length_range, t1_range, t2_range,
batch_size, seed)
| 5,189 | 4 | 481 |
22da4ef049b9e8ecbc5351dab4a7e240d8f2b253 | 7,087 | py | Python | pilanimate/__init__.py | jetstream0/PilAnimate | 077eaec0bfc5119c64f08d7ad21e3451b1c39d29 | [
"MIT"
] | null | null | null | pilanimate/__init__.py | jetstream0/PilAnimate | 077eaec0bfc5119c64f08d7ad21e3451b1c39d29 | [
"MIT"
] | null | null | null | pilanimate/__init__.py | jetstream0/PilAnimate | 077eaec0bfc5119c64f08d7ad21e3451b1c39d29 | [
"MIT"
] | null | null | null | #pilaniamte version 0.4.1
from PIL import Image, ImageDraw, ImageOps, ImageFilter, ImageEnhance, ImageColor, ImageFont, ImageSequence
import cv2
import numpy
from time import sleep
import os, math
#functions that draw stuff on
#translation functions
#transparency functions
#UNTESTED
#transform
#color change functions
#image filter functions
#blend
#clear image functions
#save frame image
#turn frame into png
#shortcut save functions (ie a function that translates every frame and also saves frame) | 40.039548 | 248 | 0.686609 | #pilaniamte version 0.4.1
from PIL import Image, ImageDraw, ImageOps, ImageFilter, ImageEnhance, ImageColor, ImageFont, ImageSequence
import cv2
import numpy
from time import sleep
import os, math
class Animation:
def __init__(self, layer_num, size=(1600,900), fps=25, mode="RGBA", color=0):
self.layers = []
self.fps = fps
self.mode = mode
self.size = size
for i in range(layer_num):
self.layers.append(Layer(size, fps, mode=mode, color=color))
def export(self, filename="hey"):
video = cv2.VideoWriter(filename+".avi", cv2.VideoWriter_fourcc(*'XVID'), 30, self.size)
for frame_num in range(len(self.layers[0].frames)):
frame = Image.new(self.mode, self.size)
for i in range(len(self.layers)):
frame.paste(self.layers[i].frames[frame_num], mask=self.layers[i].frames[frame_num])
video.write(cv2.cvtColor(numpy.array(frame), cv2.COLOR_RGB2BGR))
video.release()
class Layer:
def __init__(self, size, fps, mode="RGBA", color=0):
self.size = size
self.img = Image.new(mode, size, color=0)
self.layer = ImageDraw.Draw(self.img)
self.fps = fps
self.frames = []
self.mode = mode
#functions that draw stuff on
def createPoint(self, coords, fill=None):
self.layer.point(coords, fill=fill)
def createLine(self, coords, fill=None, width=0, joint=None):
self.layer.line(coords, fill=fill, width=width, joint=joint)
def createArc(self, boundingBox, startAngle, endAngle, fill=None, width=0):
self.layer.arc(boundingBox, startAngle, endAngle, fill=fill, width=width)
def createEllipse(self, boundingBox, fill=None, outline=None, width=0):
self.layer.ellipse(boundingBox, fill=fill, outline=outline, width=width)
def createPolygon(self, coords, fill=None, outline=None):
self.layer.polygon(coords, fill=fill, outline=outline)
def createRectangle(self, boundingBox, fill=None, outline=None, width=1):
self.layer.rectangle(boundingBox, fill=fill, outline=outline, width=width)
def createRoundedRectangle(self, boundingBox, radius=0, fill=None, outline=None, width=0):
self.layer.rounded_rectangle(boundingBox, radius=radius, fill=fill, outline=outline, width=width)
def fillAll(self, fill=None, outline=None, width=0):
self.layer.rectangle(((0,0),self.size), fill=fill, outline=outline, width=width)
def createText(self, anchorCoords, text, fill=None, font=None, anchor=None, spacing=4, align='left', direction=None, features=None, language=None, stroke_width=0, stroke_fill=None, embedded_color=False):
self.layer.text(anchorCoords, text, fill=fill, font=font, anchor=anchor, spacing=spacing, align=align, direction=direction, features=features, language=language, stroke_width=stroke_width, stroke_fill=stroke_fill, embedded_color=embedded_color)
def addImage(self, imageToAdd, coords=None):
self.img.paste(imageToAdd,box=coords)
def addGif(self, gif_location, times_to_repeat, coords=None):
for i in range(times_to_repeat):
gif = Image.open(gif_location)
for frame in ImageSequence.Iterator(gif):
self.img.paste(frame, box=coords)
self.frames.append(self.img.copy())
#translation functions
def rotate(self, angle, center=None, outsideFillColor=None, copy=None):
if copy:
self.img = copy.rotate(angle, resample=0, center=center, fillcolor=outsideFillColor)
self.layer = ImageDraw.Draw(self.img)
else:
self.img = self.img.rotate(angle, resample=0, center=center, fillcolor=outsideFillColor)
self.layer = ImageDraw.Draw(self.img)
def translate(self, x, y, img):
newimg = Image.new(self.mode, self.size, color=0)
newimg.paste(img, (round(0+x),round(0+y)), img)
self.img = newimg
self.layer = ImageDraw.Draw(self.img)
#transparency functions
def changeOpacity(self, value):
pixels = self.img.load()
for x in range(0,self.size[0]):
for y in range(0,self.size[1]):
if pixels[x,y] != (0,0,0,0):
pixels[x,y] = (pixels[x,y][0], pixels[x,y][1], pixels[x,y][2], value)
def changeEntireOpacity(self, value):
self.img.putalpha(value)
#UNTESTED
def fadeIn(self, frames):
original = self.img.copy()
current = 0
for i in range(frames-1):
self.img = original
self.changeOpacity(current+math.floor(100/frames))
current = current+math.floor(100/frames)
self.saveFrame()
self.changeOpacity(100)
self.saveFrame()
def fadeOut(self, frames):
original = self.img.copy()
current = 100
for i in range(frames-1):
self.img = original
self.changeOpacity(current-math.floor(100/frames))
current = current-math.floor(100/frames)
self.saveFrame()
self.changeOpacity(0)
self.saveFrame()
#transform
def transform(self, size, method, data=None, resample=0, fill=1, fillcolor=None):
self.img = self.img.transform(size, method, data=data, resample=resample, fill=fill, fillcolor=fillcolor)
self.layer = ImageDraw.Draw(self.img)
#color change functions
#image filter functions
def blur(self):
self.img = self.img.filter(ImageFilter.BLUR)
self.layer = ImageDraw.Draw(self.img)
#blend
#clear image functions
def clear(self, coords):
self.img.paste(0, coords)
def clearAll(self):
self.img.paste(Image.new(self.mode, self.size, color=0))
#save frame image
def saveFrame(self):
self.frames.append(self.img.copy())
def doNothing(self, frames):
self.frames = self.frames+[self.img.copy()]*frames
#for i in range(frames): self.saveFrame()
#turn frame into png
def save(self, filename):
self.img.save(filename+".png")
#shortcut save functions (ie a function that translates every frame and also saves frame)
def rise(self, frames, total_rise_amount):
copy = self.img.copy()
for i in range(frames):
self.clearAll()
#if last frame
if i == frames-1:
newimg = Image.new(self.mode, self.size, color=0)
newimg.paste(copy, (0,total_rise_amount), copy)
self.img = newimg
self.translate(0,total_rise_amount/frames*(i+1),copy)
self.saveFrame()
def descend(self, frames, total_descend_amount):
copy = self.img.copy()
for i in range(frames):
self.clearAll()
#if last frame
if i == frames-1:
newimg = Image.new(self.mode, self.size, color=0)
newimg.paste(copy, (0,total_descend_amount), copy)
self.img = newimg
self.translate(0,total_descend_amount/frames*(i+1),copy)
self.saveFrame()
def slide(self, frames, total_slide_amount):
copy = self.img.copy()
for i in range(frames):
self.clearAll()
#if last frame
if i == frames-1:
newimg = Image.new(self.mode, self.size, color=0)
newimg.paste(copy, (total_slide_amount,0), copy)
self.img = newimg
self.translate(total_slide_amount/frames*(i+1), 0, copy)
self.saveFrame()
def spin(self, frames, degrees, center):
copy = self.img.copy()
for i in range(frames):
self.rotate(degrees/frames*(i+1), center=center, copy=copy)
self.saveFrame() | 5,772 | -14 | 790 |
830c2187d7207e6add4a2133b9f662799d8fb3a2 | 5,938 | py | Python | examples/alternatives_comparision.py | fossabot/IneqPy | f9329d465a922fcacdefd14858350ee40bc5b803 | [
"MIT"
] | 21 | 2018-06-22T07:56:40.000Z | 2022-03-13T12:28:10.000Z | examples/alternatives_comparision.py | fossabot/IneqPy | f9329d465a922fcacdefd14858350ee40bc5b803 | [
"MIT"
] | 29 | 2017-08-11T20:07:42.000Z | 2022-02-21T18:43:28.000Z | examples/alternatives_comparision.py | fossabot/IneqPy | f9329d465a922fcacdefd14858350ee40bc5b803 | [
"MIT"
] | 12 | 2017-05-21T15:30:48.000Z | 2022-03-02T14:40:24.000Z | import numpy as np
from pygsl import statistics as gsl_stat
from scipy import stats as sp_stat
import ineqpy as ineq
from ineqpy import _statistics as ineq_stat
# Generate random data
x, w = ineq.utils.generate_data_to_test((60,90))
# Replicating weights
x_rep, w_rep = ineq.utils.repeat_data_from_weighted(x, w)
svy = ineq.api.Survey
print(
"""
==========
Quickstart
==========
We generate random weighted data to show how ineqpy works. The variables
simulate being:
x : Income
w : Weights
```python
>>> x, w = ineq.utils.generate_data_to_test((60,90))
```
To test with classical statistics we generate:
x_rep : Income values replicated w times each one.
w_rep : Ones column.
```python
>>> x_rep, w_rep = ineq.utils.repeat_data_from_weighted(x, w)
```
Additional information:
np : numpy package
sp : scipy package
pd : pandas package
gsl_stat : GNU Scientific Library written in C.
ineq : IneqPy
"""
)
print(
"""
Examples and comparision with other packages
============================================
STATISTICS
==========
MEAN
----
"""
)
print('```python')
print('>>> np.mean(x_rep)'.ljust(24), '=', np.mean(x_rep))
print('>>> ineq.mean(x, w)'.ljust(24), '=', ineq.mean(x, w))
print('>>> gsl_stat.wmean(w, x)'.ljust(24), '=', gsl_stat.wmean(w, x))
print('```')
# %timeit ineq.mean(None, x, w)
# %timeit gsl_stat.wmean(w, x)
# %timeit ineq_stat.mean(x, w)
print(
"""
VARIANCE
--------
"""
)
np_var = np.var(x_rep)
inq_var = ineq.var(x, w)
wvar_1 = ineq_stat.wvar(x, w, 1) # population variance
wvar_2 = ineq_stat.wvar(x, w, 2) # sample frequency variance
gsl_wvar = gsl_stat.wvariance(w, x)
wvar_3 = ineq_stat.wvar(x, w, 3) # sample reliability variance
print('```python')
print('>>> np.var(x_rep)'.ljust(32), '=', np_var)
print('>>> ineq.var(x, w)'.ljust(32), '=', inq_var)
print('>>> ineq_stat.wvar(x, w, kind=1)'.ljust(32), '=', wvar_1)
print('>>> ineq_stat.wvar(x, w, kind=2)'.ljust(32), '=', wvar_2)
print('>>> gsl_stat.wvariance(w, x)'.ljust(32), '=', gsl_wvar)
print('>>> ineq_stat.wvar(x, w, kind=3)'.ljust(32), '=', wvar_3)
print('```')
print(
"""
COVARIANCE
----------
"""
)
np_cov = np.cov(x_rep, x_rep)
ineq_wcov1 = ineq_stat.wcov(x, x, w, 1)
ineq_wcov2 = ineq_stat.wcov(x, x, w, 2)
ineq_wcov3 = ineq_stat.wcov(x, x, w, 3)
print('```python')
print('>>> np.cov(x_rep, x_rep)'.ljust(35), '= ', np_cov)
print('>>> ineq_stat.wcov(x, x, w, kind=1)'.ljust(35), '= ', ineq_wcov1)
print('>>> ineq_stat.wcov(x, x, w, kind=2)'.ljust(35), '= ', ineq_wcov2)
print('>>> ineq_stat.wcov(x, x, w, kind=3)'.ljust(35), '= ', ineq_wcov3)
print('```')
print(
"""
SKEWNESS
--------
"""
)
gsl_wskew = gsl_stat.wskew(w, x)
sp_skew = sp_stat.skew(x_rep)
ineq_skew = ineq.skew(x, w)
print('```python')
print('>>> gsl_stat.wskew(w, x)'.ljust(24), '= ', gsl_wskew)
print('>>> sp_stat.skew(x_rep)'.ljust(24), '= ', sp_skew)
print('>>> ineq.skew(x, w)'.ljust(24), '= ', ineq_skew)
print('```')
# %timeit gsl_stat.wskew(w, x)
# %timeit sp_stat.skew(x_rep)
# %timeit ineq.skew(None, x, w)
print(
"""
KURTOSIS
--------
"""
)
sp_kurt = sp_stat.kurtosis(x_rep)
gsl_wkurt = gsl_stat.wkurtosis(w, x)
ineq_kurt = ineq.kurt(x, w) - 3
print('```python')
print('>>> sp_stat.kurtosis(x_rep)'.ljust(28), '= ', sp_kurt)
print('>>> gsl_stat.wkurtosis(w, x)'.ljust(28), '= ', gsl_wkurt)
print('>>> ineq.kurt(x, w) - 3'.ljust(28), '= ', ineq_kurt)
print('```')
# %timeit sp_stat.kurtosis(x_rep)
# %timeit gsl_stat.wkurtosis(w, x)
# %timeit ineq.kurt(None, x, w) - 3
print(
"""
PERCENTILES
-----------
"""
)
q = 50
ineq_perc_50 = ineq_stat.percentile(x, w, q)
np_perc_50 = np.percentile(x_rep, q)
print('```python')
print('>>> ineq_stat.percentile(x, w, %s)'.ljust(34) % q, '= ', ineq_perc_50)
print('>>> np.percentile(x_rep, %s)'.ljust(34) % q, '= ', np_perc_50)
q = 25
ineq_perc_25 = ineq_stat.percentile(x, w, q)
np_perc_25 = np.percentile(x_rep, q)
print('>>> ineq_stat.percentile(x, w, %s)'.ljust(34) % q, '= ', ineq_perc_25)
print('>>> np.percentile(x_rep, %s)'.ljust(34) % q, '= ', np_perc_25)
q = 75
ineq_perc_75 = ineq_stat.percentile(x, w, q)
np_perc_75 = np.percentile(x_rep, q)
print('>>> ineq_stat.percentile(x, w, %s)'.ljust(34) % q, '= ', ineq_perc_75)
print('>>> np.percentile(x_rep, %s)'.ljust(34) % q, '= ', np_perc_75)
q = 10
ineq_perc_10 = ineq_stat.percentile(x, w, q)
np_perc_10 = np.percentile(x_rep, q)
print('>>> ineq_stat.percentile(x, w, %s)'.ljust(34) % q, '= ', ineq_perc_10)
print('>>> np.percentile(x_rep, %s)'.ljust(34) % q, '= ', np_perc_10)
q = 90
ineq_perc_90 = ineq_stat.percentile(x, w, q)
np_perc_90 = np.percentile(x_rep, q)
print('>>> ineq_stat.percentile(x, w, %s)'.ljust(34) % q, '= ', ineq_perc_90)
print('>>> np.percentile(x_rep, %s)'.ljust(34) % q, '= ', np_perc_90)
print('```')
print(
"""
Another way to use this is through the API module as shown below:
API MODULE
==========
"""
)
data = np.c_[x, w]
columns = list('xw')
df = svy(data=data, columns=columns, weights='w')
print('```python')
print(">>> data = svy(data=data, columns=columns, weights='w')")
print(">>> data.head()")
print(df.head())
print('')
print('>>> data.weights =', df.weights)
print('```')
print('')
main_var = 'x'
# df.mean(main_var)
# df.var(main_var)
# df.skew(main_var)
# df.kurt(main_var)
# df.gini(main_var)
# df.atkinson(main_var)
# df.theil(main_var)
# df.percentile(main_var)
print('```python')
print('>>> df.mean(main_var)'.ljust(27), '=', df.mean(main_var))
print('>>> df.percentile(main_var)'.ljust(27), '=', df.percentile(main_var))
print('>>> df.var(main_var)'.ljust(27), '=', df.var(main_var))
print('>>> df.skew(main_var)'.ljust(27), '=', df.skew(main_var))
print('>>> df.kurt(main_var)'.ljust(27), '=', df.kurt(main_var))
print('>>> df.gini(main_var)'.ljust(27), '=', df.gini(main_var))
print('>>> df.atkinson(main_var)'.ljust(27), '=', df.atkinson(main_var))
print('>>> df.theil(main_var)'.ljust(27), '=', df.theil(main_var))
print('```') | 24.436214 | 77 | 0.625126 | import numpy as np
from pygsl import statistics as gsl_stat
from scipy import stats as sp_stat
import ineqpy as ineq
from ineqpy import _statistics as ineq_stat
# Generate random data
x, w = ineq.utils.generate_data_to_test((60,90))
# Replicating weights
x_rep, w_rep = ineq.utils.repeat_data_from_weighted(x, w)
svy = ineq.api.Survey
print(
"""
==========
Quickstart
==========
We generate random weighted data to show how ineqpy works. The variables
simulate being:
x : Income
w : Weights
```python
>>> x, w = ineq.utils.generate_data_to_test((60,90))
```
To test with classical statistics we generate:
x_rep : Income values replicated w times each one.
w_rep : Ones column.
```python
>>> x_rep, w_rep = ineq.utils.repeat_data_from_weighted(x, w)
```
Additional information:
np : numpy package
sp : scipy package
pd : pandas package
gsl_stat : GNU Scientific Library written in C.
ineq : IneqPy
"""
)
print(
"""
Examples and comparision with other packages
============================================
STATISTICS
==========
MEAN
----
"""
)
print('```python')
print('>>> np.mean(x_rep)'.ljust(24), '=', np.mean(x_rep))
print('>>> ineq.mean(x, w)'.ljust(24), '=', ineq.mean(x, w))
print('>>> gsl_stat.wmean(w, x)'.ljust(24), '=', gsl_stat.wmean(w, x))
print('```')
# %timeit ineq.mean(None, x, w)
# %timeit gsl_stat.wmean(w, x)
# %timeit ineq_stat.mean(x, w)
print(
"""
VARIANCE
--------
"""
)
np_var = np.var(x_rep)
inq_var = ineq.var(x, w)
wvar_1 = ineq_stat.wvar(x, w, 1) # population variance
wvar_2 = ineq_stat.wvar(x, w, 2) # sample frequency variance
gsl_wvar = gsl_stat.wvariance(w, x)
wvar_3 = ineq_stat.wvar(x, w, 3) # sample reliability variance
print('```python')
print('>>> np.var(x_rep)'.ljust(32), '=', np_var)
print('>>> ineq.var(x, w)'.ljust(32), '=', inq_var)
print('>>> ineq_stat.wvar(x, w, kind=1)'.ljust(32), '=', wvar_1)
print('>>> ineq_stat.wvar(x, w, kind=2)'.ljust(32), '=', wvar_2)
print('>>> gsl_stat.wvariance(w, x)'.ljust(32), '=', gsl_wvar)
print('>>> ineq_stat.wvar(x, w, kind=3)'.ljust(32), '=', wvar_3)
print('```')
print(
"""
COVARIANCE
----------
"""
)
np_cov = np.cov(x_rep, x_rep)
ineq_wcov1 = ineq_stat.wcov(x, x, w, 1)
ineq_wcov2 = ineq_stat.wcov(x, x, w, 2)
ineq_wcov3 = ineq_stat.wcov(x, x, w, 3)
print('```python')
print('>>> np.cov(x_rep, x_rep)'.ljust(35), '= ', np_cov)
print('>>> ineq_stat.wcov(x, x, w, kind=1)'.ljust(35), '= ', ineq_wcov1)
print('>>> ineq_stat.wcov(x, x, w, kind=2)'.ljust(35), '= ', ineq_wcov2)
print('>>> ineq_stat.wcov(x, x, w, kind=3)'.ljust(35), '= ', ineq_wcov3)
print('```')
print(
"""
SKEWNESS
--------
"""
)
gsl_wskew = gsl_stat.wskew(w, x)
sp_skew = sp_stat.skew(x_rep)
ineq_skew = ineq.skew(x, w)
print('```python')
print('>>> gsl_stat.wskew(w, x)'.ljust(24), '= ', gsl_wskew)
print('>>> sp_stat.skew(x_rep)'.ljust(24), '= ', sp_skew)
print('>>> ineq.skew(x, w)'.ljust(24), '= ', ineq_skew)
print('```')
# %timeit gsl_stat.wskew(w, x)
# %timeit sp_stat.skew(x_rep)
# %timeit ineq.skew(None, x, w)
print(
"""
KURTOSIS
--------
"""
)
sp_kurt = sp_stat.kurtosis(x_rep)
gsl_wkurt = gsl_stat.wkurtosis(w, x)
ineq_kurt = ineq.kurt(x, w) - 3
print('```python')
print('>>> sp_stat.kurtosis(x_rep)'.ljust(28), '= ', sp_kurt)
print('>>> gsl_stat.wkurtosis(w, x)'.ljust(28), '= ', gsl_wkurt)
print('>>> ineq.kurt(x, w) - 3'.ljust(28), '= ', ineq_kurt)
print('```')
# %timeit sp_stat.kurtosis(x_rep)
# %timeit gsl_stat.wkurtosis(w, x)
# %timeit ineq.kurt(None, x, w) - 3
print(
"""
PERCENTILES
-----------
"""
)
q = 50
ineq_perc_50 = ineq_stat.percentile(x, w, q)
np_perc_50 = np.percentile(x_rep, q)
print('```python')
print('>>> ineq_stat.percentile(x, w, %s)'.ljust(34) % q, '= ', ineq_perc_50)
print('>>> np.percentile(x_rep, %s)'.ljust(34) % q, '= ', np_perc_50)
q = 25
ineq_perc_25 = ineq_stat.percentile(x, w, q)
np_perc_25 = np.percentile(x_rep, q)
print('>>> ineq_stat.percentile(x, w, %s)'.ljust(34) % q, '= ', ineq_perc_25)
print('>>> np.percentile(x_rep, %s)'.ljust(34) % q, '= ', np_perc_25)
q = 75
ineq_perc_75 = ineq_stat.percentile(x, w, q)
np_perc_75 = np.percentile(x_rep, q)
print('>>> ineq_stat.percentile(x, w, %s)'.ljust(34) % q, '= ', ineq_perc_75)
print('>>> np.percentile(x_rep, %s)'.ljust(34) % q, '= ', np_perc_75)
q = 10
ineq_perc_10 = ineq_stat.percentile(x, w, q)
np_perc_10 = np.percentile(x_rep, q)
print('>>> ineq_stat.percentile(x, w, %s)'.ljust(34) % q, '= ', ineq_perc_10)
print('>>> np.percentile(x_rep, %s)'.ljust(34) % q, '= ', np_perc_10)
q = 90
ineq_perc_90 = ineq_stat.percentile(x, w, q)
np_perc_90 = np.percentile(x_rep, q)
print('>>> ineq_stat.percentile(x, w, %s)'.ljust(34) % q, '= ', ineq_perc_90)
print('>>> np.percentile(x_rep, %s)'.ljust(34) % q, '= ', np_perc_90)
print('```')
print(
"""
Another way to use this is through the API module as shown below:
API MODULE
==========
"""
)
data = np.c_[x, w]
columns = list('xw')
df = svy(data=data, columns=columns, weights='w')
print('```python')
print(">>> data = svy(data=data, columns=columns, weights='w')")
print(">>> data.head()")
print(df.head())
print('')
print('>>> data.weights =', df.weights)
print('```')
print('')
main_var = 'x'
# df.mean(main_var)
# df.var(main_var)
# df.skew(main_var)
# df.kurt(main_var)
# df.gini(main_var)
# df.atkinson(main_var)
# df.theil(main_var)
# df.percentile(main_var)
print('```python')
print('>>> df.mean(main_var)'.ljust(27), '=', df.mean(main_var))
print('>>> df.percentile(main_var)'.ljust(27), '=', df.percentile(main_var))
print('>>> df.var(main_var)'.ljust(27), '=', df.var(main_var))
print('>>> df.skew(main_var)'.ljust(27), '=', df.skew(main_var))
print('>>> df.kurt(main_var)'.ljust(27), '=', df.kurt(main_var))
print('>>> df.gini(main_var)'.ljust(27), '=', df.gini(main_var))
print('>>> df.atkinson(main_var)'.ljust(27), '=', df.atkinson(main_var))
print('>>> df.theil(main_var)'.ljust(27), '=', df.theil(main_var))
print('```') | 0 | 0 | 0 |