hexsha
stringlengths
40
40
size
int64
2
1.02M
ext
stringclasses
10 values
lang
stringclasses
1 value
max_stars_repo_path
stringlengths
4
245
max_stars_repo_name
stringlengths
6
130
max_stars_repo_head_hexsha
stringlengths
40
40
max_stars_repo_licenses
listlengths
1
10
max_stars_count
int64
1
191k
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
245
max_issues_repo_name
stringlengths
6
130
max_issues_repo_head_hexsha
stringlengths
40
40
max_issues_repo_licenses
listlengths
1
10
max_issues_count
int64
1
67k
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
245
max_forks_repo_name
stringlengths
6
130
max_forks_repo_head_hexsha
stringlengths
40
40
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
2
1.02M
avg_line_length
float64
1
417k
max_line_length
int64
1
987k
alphanum_fraction
float64
0
1
content_no_comment
stringlengths
0
1.01M
is_comment_constant_removed
bool
1 class
is_sharp_comment_removed
bool
1 class
1c33e3bca8133ca52ee4a9c179c8779b0c8dd328
2,087
py
Python
examples/ExGroup.py
janjusti/dcma
4403b176f33967d446275ee35422ec31236ce7a6
[ "MIT" ]
null
null
null
examples/ExGroup.py
janjusti/dcma
4403b176f33967d446275ee35422ec31236ce7a6
[ "MIT" ]
null
null
null
examples/ExGroup.py
janjusti/dcma
4403b176f33967d446275ee35422ec31236ce7a6
[ "MIT" ]
null
null
null
from Bio import Entrez, AlignIO, SeqIO from Bio.Align import AlignInfo from Bio.SeqRecord import SeqRecord from Bio.Align.Applications import MuscleCommandline import dcma.core as solver import time def generate_fasta_from_ids(id_list, fasta_output): Entrez.email = 'example@example.com' f = open(fasta_output, 'w+') for curr_id in id_list: curr_req = Entrez.efetch(db='nucleotide', id=curr_id, rettype='fasta') curr_seq = curr_req.read() f.write(curr_seq) print(curr_id, 'successfully fetched.') time.sleep(1) f.close() print(fasta_output, 'sucessfully created.') def align_via_muscle(input_file, output_file): comm_muscle = MuscleCommandline( input=input_file, out=output_file ) comm_muscle() print('Alignment', input_file, '>', output_file, 'done.') def get_consensus_seq(fasta_file, q_id): align = AlignIO.read(fasta_file, 'fasta') seq = SeqRecord( AlignInfo.SummaryInfo(align).gap_consensus(), id=q_id, description='' ) print("'" + q_id + "' consensus sequence generated (original: " + fasta_file + ')') return seq def write_fasta(fasta_file, seq_list): with open(fasta_file, 'w') as handle: SeqIO.write(seq_list, handle, 'fasta') print(fasta_file, 'successfully written.') def main_group(): groupA_ids = ['KC662553.1', 'KC662552.1'] groupB_ids = ['KM058604.1', 'KM058603.1'] generate_fasta_from_ids(groupA_ids, 'groupA-unaligned.fasta') generate_fasta_from_ids(groupB_ids, 'groupB-unaligned.fasta') align_via_muscle('groupA-unaligned.fasta', 'groupA.fasta') align_via_muscle('groupB-unaligned.fasta', 'groupB.fasta') seqA = get_consensus_seq('groupA.fasta', 'groupA_any_sentence') seqB = get_consensus_seq('groupB.fasta', 'groupB_any_sentence') write_fasta('groupAB-cons.fasta', [seqA, seqB]) align_via_muscle('groupAB-cons.fasta', 'groups-target.fasta') results = solver.run('groups-target.fasta', searchable_keyphrase='any sentence') solver.export(results, 'csv', 'groups')
35.982759
87
0.698131
from Bio import Entrez, AlignIO, SeqIO from Bio.Align import AlignInfo from Bio.SeqRecord import SeqRecord from Bio.Align.Applications import MuscleCommandline import dcma.core as solver import time def generate_fasta_from_ids(id_list, fasta_output): Entrez.email = 'example@example.com' f = open(fasta_output, 'w+') for curr_id in id_list: curr_req = Entrez.efetch(db='nucleotide', id=curr_id, rettype='fasta') curr_seq = curr_req.read() f.write(curr_seq) print(curr_id, 'successfully fetched.') time.sleep(1) f.close() print(fasta_output, 'sucessfully created.') def align_via_muscle(input_file, output_file): comm_muscle = MuscleCommandline( input=input_file, out=output_file ) comm_muscle() print('Alignment', input_file, '>', output_file, 'done.') def get_consensus_seq(fasta_file, q_id): align = AlignIO.read(fasta_file, 'fasta') seq = SeqRecord( AlignInfo.SummaryInfo(align).gap_consensus(), id=q_id, description='' ) print("'" + q_id + "' consensus sequence generated (original: " + fasta_file + ')') return seq def write_fasta(fasta_file, seq_list): with open(fasta_file, 'w') as handle: SeqIO.write(seq_list, handle, 'fasta') print(fasta_file, 'successfully written.') def main_group(): groupA_ids = ['KC662553.1', 'KC662552.1'] groupB_ids = ['KM058604.1', 'KM058603.1'] generate_fasta_from_ids(groupA_ids, 'groupA-unaligned.fasta') generate_fasta_from_ids(groupB_ids, 'groupB-unaligned.fasta') align_via_muscle('groupA-unaligned.fasta', 'groupA.fasta') align_via_muscle('groupB-unaligned.fasta', 'groupB.fasta') seqA = get_consensus_seq('groupA.fasta', 'groupA_any_sentence') seqB = get_consensus_seq('groupB.fasta', 'groupB_any_sentence') write_fasta('groupAB-cons.fasta', [seqA, seqB]) align_via_muscle('groupAB-cons.fasta', 'groups-target.fasta') results = solver.run('groups-target.fasta', searchable_keyphrase='any sentence') solver.export(results, 'csv', 'groups')
true
true
1c33e502e953fb501cea4f12595b4840aca73557
1,156
py
Python
.modules/.recon-ng/modules/recon/hosts-domains/migrate_hosts.py
termux-one/EasY_HaCk
0a8d09ca4b126b027b6842e02fa0c29d8250e090
[ "Apache-2.0" ]
1,103
2018-04-20T14:08:11.000Z
2022-03-29T06:22:43.000Z
.modules/.recon-ng/modules/recon/hosts-domains/migrate_hosts.py
sshourya948/EasY_HaCk
0a8d09ca4b126b027b6842e02fa0c29d8250e090
[ "Apache-2.0" ]
29
2019-04-03T14:52:38.000Z
2022-03-24T12:33:05.000Z
.modules/.recon-ng/modules/recon/hosts-domains/migrate_hosts.py
sshourya948/EasY_HaCk
0a8d09ca4b126b027b6842e02fa0c29d8250e090
[ "Apache-2.0" ]
161
2018-04-20T15:57:12.000Z
2022-03-15T19:16:16.000Z
from recon.core.module import BaseModule import os import re class Module(BaseModule): meta = { 'name': 'Hosts to Domains Data Migrator', 'author': 'Tim Tomes (@LaNMaSteR53)', 'description': 'Adds a new domain for all the hostnames stored in the \'hosts\' table.', 'comments': ( 'This modules considers that everything after the first element could contain other hosts besides the current. Therefore, hosts > 2 domains deep will create domains > 2 elements in length.', ), 'query': 'SELECT DISTINCT host FROM hosts WHERE host IS NOT NULL', } def module_run(self, hosts): # ip address regex regex = '[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}' # only migrate hosts that aren't ip addresses hosts = [x for x in hosts if not re.match(regex, x[0])] with open(os.path.join(self.data_path, 'suffixes.txt')) as f: suffixes = [line.strip().lower() for line in f if len(line)>0 and line[0] is not '#'] domains = self.hosts_to_domains(hosts, suffixes) for domain in domains: self.add_domains(domain=domain)
42.814815
202
0.622837
from recon.core.module import BaseModule import os import re class Module(BaseModule): meta = { 'name': 'Hosts to Domains Data Migrator', 'author': 'Tim Tomes (@LaNMaSteR53)', 'description': 'Adds a new domain for all the hostnames stored in the \'hosts\' table.', 'comments': ( 'This modules considers that everything after the first element could contain other hosts besides the current. Therefore, hosts > 2 domains deep will create domains > 2 elements in length.', ), 'query': 'SELECT DISTINCT host FROM hosts WHERE host IS NOT NULL', } def module_run(self, hosts): regex = '[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}' hosts = [x for x in hosts if not re.match(regex, x[0])] with open(os.path.join(self.data_path, 'suffixes.txt')) as f: suffixes = [line.strip().lower() for line in f if len(line)>0 and line[0] is not ' domains = self.hosts_to_domains(hosts, suffixes) for domain in domains: self.add_domains(domain=domain)
true
true
1c33e56e472ec7115c80b8127bbef8760db518c3
5,466
py
Python
codes/singintex.py
Hadrien-Montanelli/singintpy
1706afe42d0cc6e0f3c53759d489f7209e50ef29
[ "MIT" ]
null
null
null
codes/singintex.py
Hadrien-Montanelli/singintpy
1706afe42d0cc6e0f3c53759d489f7209e50ef29
[ "MIT" ]
null
null
null
codes/singintex.py
Hadrien-Montanelli/singintpy
1706afe42d0cc6e0f3c53759d489f7209e50ef29
[ "MIT" ]
null
null
null
#!/usr/bin/env python3 # -*- coding: utf-8 -*- """ Created on Mon Jun 28 19:24:38 2021 Copyright 2021 by Hadrien Montanelli. """ def singintex(u0, v0, dz0): """ # Outputs the exact value (computed in Mathematica) of the singular and # near-singular integrals used in the numerical experiments of [1, Sec. 4]. # These values are computed in the singintex.nb file. # Inputs # ------ # u0, v0, dz0 : float # Position of the singularity is x0 = F(u0, v0) + dz0*z. # Output # ------ # Iex : float # The exact value of the integral. # References # ---------- # [1] H. Montanelli, M. Aussal and H. Haddar, Computing weakly singular and # near-singular integrals in high-order boundary elements, submitted. # """ # Point near the center: if (u0 == .2) and (v0 == .4) and (dz0 == 0): # singularity Iex = 3.240017458404107 if (u0 == .2) and (v0 == .4) and (dz0 == 1e-4): # near-singularity Iex = 3.239493851850319 if (u0 == .2) and (v0 == .4) and (dz0 == 1e-3): # near-singularity Iex = 3.234785969247374 if (u0 == .2) and (v0 == .4) and (dz0 == 1e-2): # near-singularity Iex = 3.188154928666069 # Point near the a1-a2 vertex: if (u0 == .5) and (v0 == 1e-1) and (dz0 == 0): # singularity Iex = 3.018547440468339 if (u0 == .5) and (v0 == 1e-1) and (dz0 == 1e-4): # near-singularity Iex = 3.018116377195088 if (u0 == .5) and (v0 == 1e-1) and (dz0 == 1e-3): # near-singularity Iex = 3.014240460722516 if (u0 == .5) and (v0 == 1e-2) and (dz0 == 0): # singularity Iex = 2.44181568875291 if (u0 == .5) and (v0 == 1e-2) and (dz0 == 1e-4): # near-singularity Iex = 2.441683569912414 if (u0 == .5) and (v0 == 1e-3) and (dz0 == 0): # singularity Iex = 2.310786384193376 if (u0 == .5) and (v0 == 1e-3) and (dz0 == 1e-4): # near-singularity Iex = 2.310927133672147 if (u0 == .5) and (v0 == 1e-4) and (dz0 == 0): # singularity Iex = 2.290532510026764 if (u0 == .5) and (v0 == 1e-4) and (dz0 == 1e-4): # near-singularity Iex = 2.290950009889399 if (u0 == .5) and (v0 == 1e-4) and (dz0 == 1e-3): # near-singularity Iex = 2.294299358958351 if (u0 == .5) and (v0 == 1e-4) and (dz0 == 1e-2): # near-singularity Iex = 2.309420005131348 if (u0 == .5) and (v0 == 1e-4) and (dz0 == 1e0): # near-singularity Iex = 0.9161025842305255 if (u0 == .5) and (v0 == 1e-5) and (dz0 == 0): # singularity Iex = 2.287793848213499 if (u0 == .5) and (v0 == 1e-5) and (dz0 == 1e-4): # near-singularity Iex = 2.288438219470312 if (u0 == .5) and (v0 == 1e-6) and (dz0 == 0): # singularity Iex = 2.287448672711318 if (u0 == .5) and (v0 == 1e-6) and (dz0 == 1e-4): # near-singularity Iex = 2.288172343092934 if (u0 == .5) and (v0 == 1e-7) and (dz0 == 0): # singularity Iex = 2.287407024410108 if (u0 == .5) and (v0 == 1e-7) and (dz0 == 1e-4): # near-singularity Iex = 2.288145597976325 if (u0 == .5) and (v0 == 1e-10) and (dz0 == 0): # singularity Iex = 2.287401524368497 if (u0 == .5) and (v0 == 1e-10) and (dz0 == 1e-4): # near-singularity Iex = 2.288142627543715 if (u0 == .5) and (v0 == 0) and (dz0 == 0): # singularity Iex = 2.287401516483698 if (u0 == .5) and (v0 == 0) and (dz0 == 1e-4): # near-singularity Iex = 2.288142624570126 # Point near the a2-a3 vertex: if (u0 == .5) and (v0 == 0.5-1e-1) and (dz0 == 0): # singularity Iex = 2.910980479568196 if (u0 == .5) and (v0 == 0.5-1e-2) and (dz0 == 0): # singularity Iex = 2.328357836622938 if (u0 == .5) and (v0 == 0.5-1e-3) and (dz0 == 0): # singularity Iex = 2.207283607389093 if (u0 == .5) and (v0 == 0.5-1e-4) and (dz0 == 0): # singularity Iex = 2.18893530823417 if (u0 == .5) and (v0 == 0.5-1e-5) and (dz0 == 0): # singularity Iex = 2.186474998717380 if (u0 == .5) and (v0 == 0.5-1e-6) and (dz0 == 0): # singularity Iex = 2.186166390068990 if (u0 == .5) and (v0 == 0.5-1e-7) and (dz0 == 0): # singularity Iex = 2.186129270984043 if (u0 == .5) and (v0 == 0.5-1e-10) and (dz0 == 0): # singularity Iex = 2.186124380996982 if (u0 == .5) and (v0 == 0.5) and (dz0 == 0): # singularity Iex = 2.186124374013931 # Point near the a3-a1 vertex: if (u0 == 1e-1) and (v0 == 0.5) and (dz0 == 0): # singularity Iex = 3.001704553910470 if (u0 == 1e-2) and (v0 == 0.5) and (dz0 == 0): # singularity Iex = 2.455261667489161 if (u0 == 1e-3) and (v0 == 0.5) and (dz0 == 0): # singularity Iex = 2.333635120399480 if (u0 == 1e-4) and (v0 == 0.5) and (dz0 == 0): # singularity Iex = 2.314977231319161 if (u0 == 1e-5) and (v0 == 0.5) and (dz0 == 0): # singularity Iex = 2.312463818083347 if (u0 == 1e-6) and (v0 == 0.5) and (dz0 == 0): # singularity Iex = 2.312147733122362 if (u0 == 1e-7) and (v0 == 0.5) and (dz0 == 0): # singularity Iex = 2.31210965045024 if (u0 == 1e-10) and (v0 == 0.5) and (dz0 == 0): # singularity Iex = 2.312104626952236 if (u0 == 0) and (v0 == 0.5) and (dz0 == 0): # singularity Iex = 2.312104619763527 return Iex
43.728
80
0.526528
def singintex(u0, v0, dz0): if (u0 == .2) and (v0 == .4) and (dz0 == 0): Iex = 3.240017458404107 if (u0 == .2) and (v0 == .4) and (dz0 == 1e-4): Iex = 3.239493851850319 if (u0 == .2) and (v0 == .4) and (dz0 == 1e-3): Iex = 3.234785969247374 if (u0 == .2) and (v0 == .4) and (dz0 == 1e-2): Iex = 3.188154928666069 if (u0 == .5) and (v0 == 1e-1) and (dz0 == 0): Iex = 3.018547440468339 if (u0 == .5) and (v0 == 1e-1) and (dz0 == 1e-4): Iex = 3.018116377195088 if (u0 == .5) and (v0 == 1e-1) and (dz0 == 1e-3): Iex = 3.014240460722516 if (u0 == .5) and (v0 == 1e-2) and (dz0 == 0): Iex = 2.44181568875291 if (u0 == .5) and (v0 == 1e-2) and (dz0 == 1e-4): Iex = 2.441683569912414 if (u0 == .5) and (v0 == 1e-3) and (dz0 == 0): Iex = 2.310786384193376 if (u0 == .5) and (v0 == 1e-3) and (dz0 == 1e-4): Iex = 2.310927133672147 if (u0 == .5) and (v0 == 1e-4) and (dz0 == 0): Iex = 2.290532510026764 if (u0 == .5) and (v0 == 1e-4) and (dz0 == 1e-4): Iex = 2.290950009889399 if (u0 == .5) and (v0 == 1e-4) and (dz0 == 1e-3): Iex = 2.294299358958351 if (u0 == .5) and (v0 == 1e-4) and (dz0 == 1e-2): Iex = 2.309420005131348 if (u0 == .5) and (v0 == 1e-4) and (dz0 == 1e0): Iex = 0.9161025842305255 if (u0 == .5) and (v0 == 1e-5) and (dz0 == 0): Iex = 2.287793848213499 if (u0 == .5) and (v0 == 1e-5) and (dz0 == 1e-4): Iex = 2.288438219470312 if (u0 == .5) and (v0 == 1e-6) and (dz0 == 0): Iex = 2.287448672711318 if (u0 == .5) and (v0 == 1e-6) and (dz0 == 1e-4): Iex = 2.288172343092934 if (u0 == .5) and (v0 == 1e-7) and (dz0 == 0): Iex = 2.287407024410108 if (u0 == .5) and (v0 == 1e-7) and (dz0 == 1e-4): Iex = 2.288145597976325 if (u0 == .5) and (v0 == 1e-10) and (dz0 == 0): Iex = 2.287401524368497 if (u0 == .5) and (v0 == 1e-10) and (dz0 == 1e-4): Iex = 2.288142627543715 if (u0 == .5) and (v0 == 0) and (dz0 == 0): Iex = 2.287401516483698 if (u0 == .5) and (v0 == 0) and (dz0 == 1e-4): Iex = 2.288142624570126 if (u0 == .5) and (v0 == 0.5-1e-1) and (dz0 == 0): Iex = 2.910980479568196 if (u0 == .5) and (v0 == 0.5-1e-2) and (dz0 == 0): Iex = 2.328357836622938 if (u0 == .5) and (v0 == 0.5-1e-3) and (dz0 == 0): Iex = 2.207283607389093 if (u0 == .5) and (v0 == 0.5-1e-4) and (dz0 == 0): Iex = 2.18893530823417 if (u0 == .5) and (v0 == 0.5-1e-5) and (dz0 == 0): Iex = 2.186474998717380 if (u0 == .5) and (v0 == 0.5-1e-6) and (dz0 == 0): Iex = 2.186166390068990 if (u0 == .5) and (v0 == 0.5-1e-7) and (dz0 == 0): Iex = 2.186129270984043 if (u0 == .5) and (v0 == 0.5-1e-10) and (dz0 == 0): Iex = 2.186124380996982 if (u0 == .5) and (v0 == 0.5) and (dz0 == 0): Iex = 2.186124374013931 if (u0 == 1e-1) and (v0 == 0.5) and (dz0 == 0): Iex = 3.001704553910470 if (u0 == 1e-2) and (v0 == 0.5) and (dz0 == 0): Iex = 2.455261667489161 if (u0 == 1e-3) and (v0 == 0.5) and (dz0 == 0): Iex = 2.333635120399480 if (u0 == 1e-4) and (v0 == 0.5) and (dz0 == 0): Iex = 2.314977231319161 if (u0 == 1e-5) and (v0 == 0.5) and (dz0 == 0): Iex = 2.312463818083347 if (u0 == 1e-6) and (v0 == 0.5) and (dz0 == 0): Iex = 2.312147733122362 if (u0 == 1e-7) and (v0 == 0.5) and (dz0 == 0): Iex = 2.31210965045024 if (u0 == 1e-10) and (v0 == 0.5) and (dz0 == 0): Iex = 2.312104626952236 if (u0 == 0) and (v0 == 0.5) and (dz0 == 0): Iex = 2.312104619763527 return Iex
true
true
1c33e63b7914a838eed8ad9be6312285010e66b4
3,013
py
Python
src/dsgrn_net_gen/makejobs.py
breecummins/dsgrn_net_gen
bcd77b71ad3e311d2906f0af986559d2c54ffe6d
[ "MIT" ]
1
2020-03-31T18:44:06.000Z
2020-03-31T18:44:06.000Z
src/dsgrn_net_gen/makejobs.py
breecummins/dsgrn_net_gen
bcd77b71ad3e311d2906f0af986559d2c54ffe6d
[ "MIT" ]
null
null
null
src/dsgrn_net_gen/makejobs.py
breecummins/dsgrn_net_gen
bcd77b71ad3e311d2906f0af986559d2c54ffe6d
[ "MIT" ]
null
null
null
import dsgrn_net_gen.networksearch as networksearch import dsgrn_net_gen.fileparsers as fileparsers import subprocess, os, json, shutil, ast, sys, time class Job(): def __init__(self,paramfile): self.paramfile = paramfile self.params = json.load(open(paramfile)) # use datetime as unique identifier to avoid overwriting if "datetime" not in self.params: datetime = subprocess.check_output(['date +%Y_%m_%d_%H_%M_%S'],shell=True).decode(sys.stdout.encoding).strip() self.params["datetime"] = datetime else: datetime = self.params["datetime"] self.params["random_seed"] = time.time() if "random_seed" not in self.params else self.params["random_seed"] resultsdir = "" if "resultsdir" not in self.params else self.params["resultsdir"] resultsdir =os.path.join(os.path.expanduser(resultsdir), "dsgrn_net_gen_results"+datetime) self.perturbationsdir = os.path.join(resultsdir,"networks"+datetime) os.makedirs(self.perturbationsdir) self.inputfilesdir = os.path.join(resultsdir,"inputs"+datetime) os.makedirs(self.inputfilesdir) # save parameter file to computations folder newpfile = os.path.basename(paramfile).split(".")[0]+"_copy.json" json.dump(self.params,open(newpfile,"w")) shutil.move(newpfile,self.inputfilesdir) shutil.copy(self.params["networkfile"], self.inputfilesdir) #TODO: Record versions/git number of DSGRN and dsgrn_net_gen def _parsefile(self,eorn,parsefunc): f = eorn+"file" l = eorn+"list" if f in self.params and self.params[f].strip(): try: self.params[l] = parsefunc(self.params[f]) shutil.copy(self.params[f], self.inputfilesdir) except: raise ValueError("Invalid " + eorn + " file.") else: self.params[l] = None def run(self): # read network file networks = open(self.params["networkfile"]).read() try: if networks[0] == "[": networks = ast.literal_eval(networks) if not networks: networks = [""] else: while networks[-1] == '\n': networks = networks[:-1] networks = [networks] except IndexError: networks = [""] sys.stdout.flush() self._parsefile('edge',fileparsers.parseEdgeFile) self._parsefile('node',fileparsers.parseNodeFile) print("\nNetwork search beginning.\n") perturbed_networks = [] for network_spec in networks: perturbed_networks.extend(networksearch.perturbNetwork(self.params,network_spec)) networks=list(set(perturbed_networks)) with open(os.path.join(self.perturbationsdir,"networks.txt"),"w") as f: f.write(str(networks)) print("\nNetwork search complete.\n") sys.stdout.flush()
41.847222
122
0.615002
import dsgrn_net_gen.networksearch as networksearch import dsgrn_net_gen.fileparsers as fileparsers import subprocess, os, json, shutil, ast, sys, time class Job(): def __init__(self,paramfile): self.paramfile = paramfile self.params = json.load(open(paramfile)) if "datetime" not in self.params: datetime = subprocess.check_output(['date +%Y_%m_%d_%H_%M_%S'],shell=True).decode(sys.stdout.encoding).strip() self.params["datetime"] = datetime else: datetime = self.params["datetime"] self.params["random_seed"] = time.time() if "random_seed" not in self.params else self.params["random_seed"] resultsdir = "" if "resultsdir" not in self.params else self.params["resultsdir"] resultsdir =os.path.join(os.path.expanduser(resultsdir), "dsgrn_net_gen_results"+datetime) self.perturbationsdir = os.path.join(resultsdir,"networks"+datetime) os.makedirs(self.perturbationsdir) self.inputfilesdir = os.path.join(resultsdir,"inputs"+datetime) os.makedirs(self.inputfilesdir) newpfile = os.path.basename(paramfile).split(".")[0]+"_copy.json" json.dump(self.params,open(newpfile,"w")) shutil.move(newpfile,self.inputfilesdir) shutil.copy(self.params["networkfile"], self.inputfilesdir) def _parsefile(self,eorn,parsefunc): f = eorn+"file" l = eorn+"list" if f in self.params and self.params[f].strip(): try: self.params[l] = parsefunc(self.params[f]) shutil.copy(self.params[f], self.inputfilesdir) except: raise ValueError("Invalid " + eorn + " file.") else: self.params[l] = None def run(self): networks = open(self.params["networkfile"]).read() try: if networks[0] == "[": networks = ast.literal_eval(networks) if not networks: networks = [""] else: while networks[-1] == '\n': networks = networks[:-1] networks = [networks] except IndexError: networks = [""] sys.stdout.flush() self._parsefile('edge',fileparsers.parseEdgeFile) self._parsefile('node',fileparsers.parseNodeFile) print("\nNetwork search beginning.\n") perturbed_networks = [] for network_spec in networks: perturbed_networks.extend(networksearch.perturbNetwork(self.params,network_spec)) networks=list(set(perturbed_networks)) with open(os.path.join(self.perturbationsdir,"networks.txt"),"w") as f: f.write(str(networks)) print("\nNetwork search complete.\n") sys.stdout.flush()
true
true
1c33e67d7a8d75efca51a7f3cd2d594c96a6efdf
1,279
py
Python
quad_garl/garl.py
kanishkaganguly/QuadGARL
2e995861cab98d9623dd36155cb472dcb4e21cd0
[ "MIT" ]
1
2019-02-08T06:17:34.000Z
2019-02-08T06:17:34.000Z
quad_garl/garl.py
kanishkaganguly/QuadGARL
2e995861cab98d9623dd36155cb472dcb4e21cd0
[ "MIT" ]
null
null
null
quad_garl/garl.py
kanishkaganguly/QuadGARL
2e995861cab98d9623dd36155cb472dcb4e21cd0
[ "MIT" ]
null
null
null
from typing import List from quad_garl import quad_utils from quad_garl.garl_utils import GARLUtils from quad_garl.genetic_algorithm import GeneticAlgorithm from quad_garl.quad_simulator import Quadcopter from quad_garl.reinforcement_learning import ReinforcementLearning def main(): # Variables chromosome_size = 10 # type:int generations = 10 # type:int population_size = 20 # type:int selection_percent = 0.3 # type:float target_pose = [2, 2, 2, 0, 0, 3.14] # type: List # x,y,z,r,p,y # Logging log = quad_utils.quad_logger # Set up RL, GA, Quad framework log(log_data="Initialize RL and GA frameworks") quad_sim = Quadcopter(log, target_pose) ga = GeneticAlgorithm(log, chromosome_size, generations, population_size, selection_percent) rl = ReinforcementLearning(log) utils = GARLUtils(genetic_algorithm=ga, reinforcement_learning=rl) log(None) i = 0 while i < 10: log("Iteration {}".format(i)) # Create population ga.initialize_population() # Evaluate current population pop = ga.population for each_population in pop: print(each_population) pass i += 1 log(None) if __name__ == '__main__': main()
26.645833
96
0.677873
from typing import List from quad_garl import quad_utils from quad_garl.garl_utils import GARLUtils from quad_garl.genetic_algorithm import GeneticAlgorithm from quad_garl.quad_simulator import Quadcopter from quad_garl.reinforcement_learning import ReinforcementLearning def main(): chromosome_size = 10 generations = 10 population_size = 20 selection_percent = 0.3 target_pose = [2, 2, 2, 0, 0, 3.14] g = quad_utils.quad_logger log(log_data="Initialize RL and GA frameworks") quad_sim = Quadcopter(log, target_pose) ga = GeneticAlgorithm(log, chromosome_size, generations, population_size, selection_percent) rl = ReinforcementLearning(log) utils = GARLUtils(genetic_algorithm=ga, reinforcement_learning=rl) log(None) i = 0 while i < 10: log("Iteration {}".format(i)) ga.initialize_population() pop = ga.population for each_population in pop: print(each_population) pass i += 1 log(None) if __name__ == '__main__': main()
true
true
1c33e6e12dcd7bb838f2c7f2077f8cc747f84551
13,234
py
Python
tests/plugins/db2_test.py
flyingbarron/detect-secrets
5f9887179794ce037d97c1b343623eb5937ce800
[ "Apache-2.0" ]
null
null
null
tests/plugins/db2_test.py
flyingbarron/detect-secrets
5f9887179794ce037d97c1b343623eb5937ce800
[ "Apache-2.0" ]
null
null
null
tests/plugins/db2_test.py
flyingbarron/detect-secrets
5f9887179794ce037d97c1b343623eb5937ce800
[ "Apache-2.0" ]
null
null
null
from __future__ import absolute_import import textwrap import pytest from mock import MagicMock from mock import patch from detect_secrets.core.constants import VerifiedResult from detect_secrets.core.potential_secret import PotentialSecret from detect_secrets.plugins.db2 import Db2Detector from detect_secrets.plugins.db2 import find_other_factor from detect_secrets.plugins.db2 import get_hostname_port_database_from_url DB2_USER = 'fake_user' DB2_PASSWORD = 'fake_password' DB2_PORT = '1234' DB2_HOSTNAME = 'fake.host.name' DB2_DATABASE = 'fake_database' DB2_CONN_STRING = 'database={DB2_DATABASE};hostname={DB2_HOSTNAME};port={DB2_PORT};' + \ 'protocol=tcpip;uid={DB2_USER};pwd={DB2_PASSWORD};ConnectTimeout=5' DB2_CONN_STRING = DB2_CONN_STRING.format( DB2_DATABASE=DB2_DATABASE, DB2_HOSTNAME=DB2_HOSTNAME, DB2_PORT=DB2_PORT, DB2_USER=DB2_USER, DB2_PASSWORD=DB2_PASSWORD, ) class TestGheDetector(object): @pytest.mark.parametrize( 'token, payload, should_flag', [ ( 'secret', 'database=test;hostname=host.test.com;' 'port=1;protocol=tcpip;uid=testid;pwd=secret', True, ), ( 'secret', 'database=test;hostname=host.test.com;' 'port=1;protocol=tcpip;uid=testid;pwd=secret;', True, ), ( 'secret', 'database=test;hostname=host.test.com;' 'port=1;protocol=tcpip;pwd=secret;uid=testid;', True, ), ( 'secret', 'database=test,hostname=host.test.com,' 'port=1,protocol=tcpip,pwd=secret,uid=testid', True, ), ( 'secret', 'database=test,hostname=host.test.com,' 'port=1,protocol=tcpip,uid=testid,pwd=secret', True, ), ( 'secret', 'user=testid,\npassword=secret,\ndatabase=test,\n' 'hostname=host.test.com,\nport=1', True, ), ( 'secret', 'user=testid\npassword=secret\ndatabase=test\n' 'hostname=host.test.com\nport=1', True, ), ( 'secret', 'jdbc:db2://hostname.test.com:1/test:user=testid;password=secret;', True, ), ( 'secret', 'jdbc:db2://hostname.test.com:1/test user=testid password=secret', True, ), ('$omespeci@!ch@r$', 'dbpwd=$omespeci@!ch@r$', True), ('astring', 'db2_password = "astring"', True), ('Iusedb2!', '"password": "Iusedb2!"', True), ('ilikespaces', 'password = "ilikespaces"', True), (':anothersyntax!', 'pwd::anothersyntax!', True), ('@#!%#', 'DB2_PASSWORD = "@#!%#"', True), ('pass', 'dashdb-password = "pass"', True), ('pass', 'dashdb-password = pass\r', True), ('', 'dashdb_host = notapassword', False), ('', 'someotherpassword = "doesnt start right"', False), ], ) def test_analyze_line(self, token, payload, should_flag): logic = Db2Detector() output = logic.analyze_line(payload, 1, 'mock_filename') assert len(output) == int(should_flag) if len(output) > 0: assert list(output.keys())[0].secret == token @patch('detect_secrets.plugins.db2.ibm_db.connect') def test_verify_invalid_connect_returns_none(self, mock_db2_connect): mock_db2_connect.return_value = None potential_secret = PotentialSecret('test db2', 'test filename', DB2_PASSWORD) assert Db2Detector().verify( DB2_PASSWORD, '''user={}, password={}, database={}, host={}, port={}'''.format(DB2_USER, DB2_PASSWORD, DB2_DATABASE, DB2_HOSTNAME, DB2_PORT), potential_secret, ) == VerifiedResult.VERIFIED_FALSE mock_db2_connect.assert_called_with(DB2_CONN_STRING, '', '') @patch('detect_secrets.plugins.db2.ibm_db.connect') def test_verify_invalid_connect_throws_exception(self, mock_db2_connect): mock_db2_connect.side_effect = Exception('oops') potential_secret = PotentialSecret('test db2', 'test filename', DB2_PASSWORD) assert Db2Detector().verify( DB2_PASSWORD, '''user={}, password={}, database={}, host={}, port={}'''.format(DB2_USER, DB2_PASSWORD, DB2_DATABASE, DB2_HOSTNAME, DB2_PORT), potential_secret, ) == VerifiedResult.UNVERIFIED mock_db2_connect.assert_called_with(DB2_CONN_STRING, '', '') @patch('detect_secrets.plugins.db2.ibm_db.connect') def test_verify_valid_secret(self, mock_db2_connect): mock_db2_connect.return_value = MagicMock() potential_secret = PotentialSecret('test db2', 'test filename', DB2_PASSWORD) assert Db2Detector().verify( DB2_PASSWORD, '''user={}, password={}, database={}, host={}, port={}'''.format(DB2_USER, DB2_PASSWORD, DB2_DATABASE, DB2_HOSTNAME, DB2_PORT), potential_secret, ) == VerifiedResult.VERIFIED_TRUE mock_db2_connect.assert_called_with(DB2_CONN_STRING, '', '') assert potential_secret.other_factors['database'] == DB2_DATABASE assert potential_secret.other_factors['hostname'] == DB2_HOSTNAME assert potential_secret.other_factors['port'] == DB2_PORT assert potential_secret.other_factors['username'] == DB2_USER @patch('detect_secrets.plugins.db2.ibm_db.connect') def test_verify_valid_secret_in_single_quotes(self, mock_db2_connect): mock_db2_connect.return_value = MagicMock() potential_secret = PotentialSecret('test db2', 'test filename', DB2_PASSWORD) assert Db2Detector().verify( DB2_PASSWORD, '''user='{}', password='{}', database='{}', host='{}', port='{}' '''.format(DB2_USER, DB2_PASSWORD, DB2_DATABASE, DB2_HOSTNAME, DB2_PORT), potential_secret, ) == VerifiedResult.VERIFIED_TRUE mock_db2_connect.assert_called_with(DB2_CONN_STRING, '', '') assert potential_secret.other_factors['database'] == DB2_DATABASE assert potential_secret.other_factors['hostname'] == DB2_HOSTNAME assert potential_secret.other_factors['port'] == DB2_PORT assert potential_secret.other_factors['username'] == DB2_USER @patch('detect_secrets.plugins.db2.ibm_db.connect') def test_verify_valid_secret_in_double_quotes(self, mock_db2_connect): mock_db2_connect.return_value = MagicMock() potential_secret = PotentialSecret('test db2', 'test filename', DB2_PASSWORD) assert Db2Detector().verify( DB2_PASSWORD, '''user="{}", password="{}", database="{}", host="{}", port="{}" '''.format(DB2_USER, DB2_PASSWORD, DB2_DATABASE, DB2_HOSTNAME, DB2_PORT), potential_secret, ) == VerifiedResult.VERIFIED_TRUE mock_db2_connect.assert_called_with(DB2_CONN_STRING, '', '') assert potential_secret.other_factors['database'] == DB2_DATABASE assert potential_secret.other_factors['hostname'] == DB2_HOSTNAME assert potential_secret.other_factors['port'] == DB2_PORT assert potential_secret.other_factors['username'] == DB2_USER @patch('detect_secrets.plugins.db2.ibm_db.connect') def test_verify_from_url(self, mock_db2_connect): mock_db2_connect.return_value = MagicMock() potential_secret = PotentialSecret('test db2', 'test filename', DB2_PASSWORD) assert Db2Detector().verify( DB2_PASSWORD, '''user={}, password={}, url=jdbc:db2://{}:{}/{}, '''.format(DB2_USER, DB2_PASSWORD, DB2_HOSTNAME, DB2_PORT, DB2_DATABASE), potential_secret, ) == VerifiedResult.VERIFIED_TRUE mock_db2_connect.assert_called_with(DB2_CONN_STRING, '', '') assert potential_secret.other_factors['database'] == DB2_DATABASE assert potential_secret.other_factors['hostname'] == DB2_HOSTNAME assert potential_secret.other_factors['port'] == DB2_PORT assert potential_secret.other_factors['username'] == DB2_USER @patch('detect_secrets.plugins.db2.ibm_db.connect') def test_verify_db2_url_key(self, mock_db2_connect): mock_db2_connect.return_value = MagicMock() potential_secret = PotentialSecret('test db2', 'test filename', DB2_PASSWORD) assert Db2Detector().verify( DB2_PASSWORD, '''jdbc:db2://{}:{}/{}:user={};password={}; '''.format(DB2_HOSTNAME, DB2_PORT, DB2_DATABASE, DB2_USER, DB2_PASSWORD), potential_secret, ) == VerifiedResult.VERIFIED_TRUE mock_db2_connect.assert_called_with(DB2_CONN_STRING, '', '') assert potential_secret.other_factors['database'] == DB2_DATABASE assert potential_secret.other_factors['hostname'] == DB2_HOSTNAME assert potential_secret.other_factors['port'] == DB2_PORT assert potential_secret.other_factors['username'] == DB2_USER @patch('detect_secrets.plugins.db2.ibm_db.connect') def test_verify_times_out(self, mock_db2_connect): mock_db2_connect.side_effect = Exception('Timeout') potential_secret = PotentialSecret('test db2', 'test filename', DB2_PASSWORD) assert Db2Detector().verify( DB2_PASSWORD, '''user={}, password={}, database={}, host={}, port={}'''.format(DB2_USER, DB2_PASSWORD, DB2_DATABASE, DB2_HOSTNAME, DB2_PORT), potential_secret, ) == VerifiedResult.UNVERIFIED mock_db2_connect.assert_called_with(DB2_CONN_STRING, '', '') def test_verify_no_other_factors(self): potential_secret = PotentialSecret('test db2', 'test filename', DB2_PASSWORD) assert Db2Detector().verify( DB2_PASSWORD, 'password={}'.format(DB2_PASSWORD), potential_secret, ) == VerifiedResult.UNVERIFIED @pytest.mark.parametrize( 'content, factor_keyword_regex, factor_regex, expected_output', ( ( textwrap.dedent(""" user = {} """)[1:-1].format( DB2_USER, ), Db2Detector().username_keyword_regex, Db2Detector().username_regex, [DB2_USER], ), ( textwrap.dedent(""" port = {} """)[1:-1].format( DB2_PORT, ), Db2Detector().port_keyword_regex, Db2Detector().port_regex, [DB2_PORT], ), ( textwrap.dedent(""" database = {} """)[1:-1].format( DB2_DATABASE, ), Db2Detector().database_keyword_regex, Db2Detector().database_regex, [DB2_DATABASE], ), ( textwrap.dedent(""" host = {} """)[1:-1].format( DB2_HOSTNAME, ), Db2Detector().hostname_keyword_regex, Db2Detector().hostname_regex, [DB2_HOSTNAME], ), ), ) def test_find_other_factor(content, factor_keyword_regex, factor_regex, expected_output): assert find_other_factor(content, factor_keyword_regex, factor_regex) == expected_output @pytest.mark.parametrize( 'content, hostname_regex, port_regex, database_regex, expected_output', ( ( textwrap.dedent(""" jdbc:db2://{}:{}/{} """)[1:-1].format( DB2_HOSTNAME, DB2_PORT, DB2_DATABASE, ), Db2Detector().hostname_regex, Db2Detector().port_regex, Db2Detector().database_regex, [(DB2_HOSTNAME, DB2_PORT, DB2_DATABASE)], ), ( textwrap.dedent(""" jdbc:db2://{}:{}/ """)[1:-1].format( DB2_HOSTNAME, DB2_PORT, ), Db2Detector().hostname_regex, Db2Detector().port_regex, Db2Detector().database_regex, [], ), ( textwrap.dedent(""" nonsense """), Db2Detector().hostname_regex, Db2Detector().port_regex, Db2Detector().database_regex, [], ), ), ) def test_get_hostname_port_database_from_url( content, hostname_regex, port_regex, database_regex, expected_output, ): assert get_hostname_port_database_from_url( content, hostname_regex, port_regex, database_regex, ) == expected_output
37.070028
95
0.584328
from __future__ import absolute_import import textwrap import pytest from mock import MagicMock from mock import patch from detect_secrets.core.constants import VerifiedResult from detect_secrets.core.potential_secret import PotentialSecret from detect_secrets.plugins.db2 import Db2Detector from detect_secrets.plugins.db2 import find_other_factor from detect_secrets.plugins.db2 import get_hostname_port_database_from_url DB2_USER = 'fake_user' DB2_PASSWORD = 'fake_password' DB2_PORT = '1234' DB2_HOSTNAME = 'fake.host.name' DB2_DATABASE = 'fake_database' DB2_CONN_STRING = 'database={DB2_DATABASE};hostname={DB2_HOSTNAME};port={DB2_PORT};' + \ 'protocol=tcpip;uid={DB2_USER};pwd={DB2_PASSWORD};ConnectTimeout=5' DB2_CONN_STRING = DB2_CONN_STRING.format( DB2_DATABASE=DB2_DATABASE, DB2_HOSTNAME=DB2_HOSTNAME, DB2_PORT=DB2_PORT, DB2_USER=DB2_USER, DB2_PASSWORD=DB2_PASSWORD, ) class TestGheDetector(object): @pytest.mark.parametrize( 'token, payload, should_flag', [ ( 'secret', 'database=test;hostname=host.test.com;' 'port=1;protocol=tcpip;uid=testid;pwd=secret', True, ), ( 'secret', 'database=test;hostname=host.test.com;' 'port=1;protocol=tcpip;uid=testid;pwd=secret;', True, ), ( 'secret', 'database=test;hostname=host.test.com;' 'port=1;protocol=tcpip;pwd=secret;uid=testid;', True, ), ( 'secret', 'database=test,hostname=host.test.com,' 'port=1,protocol=tcpip,pwd=secret,uid=testid', True, ), ( 'secret', 'database=test,hostname=host.test.com,' 'port=1,protocol=tcpip,uid=testid,pwd=secret', True, ), ( 'secret', 'user=testid,\npassword=secret,\ndatabase=test,\n' 'hostname=host.test.com,\nport=1', True, ), ( 'secret', 'user=testid\npassword=secret\ndatabase=test\n' 'hostname=host.test.com\nport=1', True, ), ( 'secret', 'jdbc:db2://hostname.test.com:1/test:user=testid;password=secret;', True, ), ( 'secret', 'jdbc:db2://hostname.test.com:1/test user=testid password=secret', True, ), ('$omespeci@!ch@r$', 'dbpwd=$omespeci@!ch@r$', True), ('astring', 'db2_password = "astring"', True), ('Iusedb2!', '"password": "Iusedb2!"', True), ('ilikespaces', 'password = "ilikespaces"', True), (':anothersyntax!', 'pwd::anothersyntax!', True), ('@#!%#', 'DB2_PASSWORD = "@#!%#"', True), ('pass', 'dashdb-password = "pass"', True), ('pass', 'dashdb-password = pass\r', True), ('', 'dashdb_host = notapassword', False), ('', 'someotherpassword = "doesnt start right"', False), ], ) def test_analyze_line(self, token, payload, should_flag): logic = Db2Detector() output = logic.analyze_line(payload, 1, 'mock_filename') assert len(output) == int(should_flag) if len(output) > 0: assert list(output.keys())[0].secret == token @patch('detect_secrets.plugins.db2.ibm_db.connect') def test_verify_invalid_connect_returns_none(self, mock_db2_connect): mock_db2_connect.return_value = None potential_secret = PotentialSecret('test db2', 'test filename', DB2_PASSWORD) assert Db2Detector().verify( DB2_PASSWORD, '''user={}, password={}, database={}, host={}, port={}'''.format(DB2_USER, DB2_PASSWORD, DB2_DATABASE, DB2_HOSTNAME, DB2_PORT), potential_secret, ) == VerifiedResult.VERIFIED_FALSE mock_db2_connect.assert_called_with(DB2_CONN_STRING, '', '') @patch('detect_secrets.plugins.db2.ibm_db.connect') def test_verify_invalid_connect_throws_exception(self, mock_db2_connect): mock_db2_connect.side_effect = Exception('oops') potential_secret = PotentialSecret('test db2', 'test filename', DB2_PASSWORD) assert Db2Detector().verify( DB2_PASSWORD, '''user={}, password={}, database={}, host={}, port={}'''.format(DB2_USER, DB2_PASSWORD, DB2_DATABASE, DB2_HOSTNAME, DB2_PORT), potential_secret, ) == VerifiedResult.UNVERIFIED mock_db2_connect.assert_called_with(DB2_CONN_STRING, '', '') @patch('detect_secrets.plugins.db2.ibm_db.connect') def test_verify_valid_secret(self, mock_db2_connect): mock_db2_connect.return_value = MagicMock() potential_secret = PotentialSecret('test db2', 'test filename', DB2_PASSWORD) assert Db2Detector().verify( DB2_PASSWORD, '''user={}, password={}, database={}, host={}, port={}'''.format(DB2_USER, DB2_PASSWORD, DB2_DATABASE, DB2_HOSTNAME, DB2_PORT), potential_secret, ) == VerifiedResult.VERIFIED_TRUE mock_db2_connect.assert_called_with(DB2_CONN_STRING, '', '') assert potential_secret.other_factors['database'] == DB2_DATABASE assert potential_secret.other_factors['hostname'] == DB2_HOSTNAME assert potential_secret.other_factors['port'] == DB2_PORT assert potential_secret.other_factors['username'] == DB2_USER @patch('detect_secrets.plugins.db2.ibm_db.connect') def test_verify_valid_secret_in_single_quotes(self, mock_db2_connect): mock_db2_connect.return_value = MagicMock() potential_secret = PotentialSecret('test db2', 'test filename', DB2_PASSWORD) assert Db2Detector().verify( DB2_PASSWORD, '''user='{}', password='{}', database='{}', host='{}', port='{}' '''.format(DB2_USER, DB2_PASSWORD, DB2_DATABASE, DB2_HOSTNAME, DB2_PORT), potential_secret, ) == VerifiedResult.VERIFIED_TRUE mock_db2_connect.assert_called_with(DB2_CONN_STRING, '', '') assert potential_secret.other_factors['database'] == DB2_DATABASE assert potential_secret.other_factors['hostname'] == DB2_HOSTNAME assert potential_secret.other_factors['port'] == DB2_PORT assert potential_secret.other_factors['username'] == DB2_USER @patch('detect_secrets.plugins.db2.ibm_db.connect') def test_verify_valid_secret_in_double_quotes(self, mock_db2_connect): mock_db2_connect.return_value = MagicMock() potential_secret = PotentialSecret('test db2', 'test filename', DB2_PASSWORD) assert Db2Detector().verify( DB2_PASSWORD, '''user="{}", password="{}", database="{}", host="{}", port="{}" '''.format(DB2_USER, DB2_PASSWORD, DB2_DATABASE, DB2_HOSTNAME, DB2_PORT), potential_secret, ) == VerifiedResult.VERIFIED_TRUE mock_db2_connect.assert_called_with(DB2_CONN_STRING, '', '') assert potential_secret.other_factors['database'] == DB2_DATABASE assert potential_secret.other_factors['hostname'] == DB2_HOSTNAME assert potential_secret.other_factors['port'] == DB2_PORT assert potential_secret.other_factors['username'] == DB2_USER @patch('detect_secrets.plugins.db2.ibm_db.connect') def test_verify_from_url(self, mock_db2_connect): mock_db2_connect.return_value = MagicMock() potential_secret = PotentialSecret('test db2', 'test filename', DB2_PASSWORD) assert Db2Detector().verify( DB2_PASSWORD, '''user={}, password={}, url=jdbc:db2://{}:{}/{}, '''.format(DB2_USER, DB2_PASSWORD, DB2_HOSTNAME, DB2_PORT, DB2_DATABASE), potential_secret, ) == VerifiedResult.VERIFIED_TRUE mock_db2_connect.assert_called_with(DB2_CONN_STRING, '', '') assert potential_secret.other_factors['database'] == DB2_DATABASE assert potential_secret.other_factors['hostname'] == DB2_HOSTNAME assert potential_secret.other_factors['port'] == DB2_PORT assert potential_secret.other_factors['username'] == DB2_USER @patch('detect_secrets.plugins.db2.ibm_db.connect') def test_verify_db2_url_key(self, mock_db2_connect): mock_db2_connect.return_value = MagicMock() potential_secret = PotentialSecret('test db2', 'test filename', DB2_PASSWORD) assert Db2Detector().verify( DB2_PASSWORD, '''jdbc:db2://{}:{}/{}:user={};password={}; '''.format(DB2_HOSTNAME, DB2_PORT, DB2_DATABASE, DB2_USER, DB2_PASSWORD), potential_secret, ) == VerifiedResult.VERIFIED_TRUE mock_db2_connect.assert_called_with(DB2_CONN_STRING, '', '') assert potential_secret.other_factors['database'] == DB2_DATABASE assert potential_secret.other_factors['hostname'] == DB2_HOSTNAME assert potential_secret.other_factors['port'] == DB2_PORT assert potential_secret.other_factors['username'] == DB2_USER @patch('detect_secrets.plugins.db2.ibm_db.connect') def test_verify_times_out(self, mock_db2_connect): mock_db2_connect.side_effect = Exception('Timeout') potential_secret = PotentialSecret('test db2', 'test filename', DB2_PASSWORD) assert Db2Detector().verify( DB2_PASSWORD, '''user={}, password={}, database={}, host={}, port={}'''.format(DB2_USER, DB2_PASSWORD, DB2_DATABASE, DB2_HOSTNAME, DB2_PORT), potential_secret, ) == VerifiedResult.UNVERIFIED mock_db2_connect.assert_called_with(DB2_CONN_STRING, '', '') def test_verify_no_other_factors(self): potential_secret = PotentialSecret('test db2', 'test filename', DB2_PASSWORD) assert Db2Detector().verify( DB2_PASSWORD, 'password={}'.format(DB2_PASSWORD), potential_secret, ) == VerifiedResult.UNVERIFIED @pytest.mark.parametrize( 'content, factor_keyword_regex, factor_regex, expected_output', ( ( textwrap.dedent(""" user = {} """)[1:-1].format( DB2_USER, ), Db2Detector().username_keyword_regex, Db2Detector().username_regex, [DB2_USER], ), ( textwrap.dedent(""" port = {} """)[1:-1].format( DB2_PORT, ), Db2Detector().port_keyword_regex, Db2Detector().port_regex, [DB2_PORT], ), ( textwrap.dedent(""" database = {} """)[1:-1].format( DB2_DATABASE, ), Db2Detector().database_keyword_regex, Db2Detector().database_regex, [DB2_DATABASE], ), ( textwrap.dedent(""" host = {} """)[1:-1].format( DB2_HOSTNAME, ), Db2Detector().hostname_keyword_regex, Db2Detector().hostname_regex, [DB2_HOSTNAME], ), ), ) def test_find_other_factor(content, factor_keyword_regex, factor_regex, expected_output): assert find_other_factor(content, factor_keyword_regex, factor_regex) == expected_output @pytest.mark.parametrize( 'content, hostname_regex, port_regex, database_regex, expected_output', ( ( textwrap.dedent(""" jdbc:db2://{}:{}/{} """)[1:-1].format( DB2_HOSTNAME, DB2_PORT, DB2_DATABASE, ), Db2Detector().hostname_regex, Db2Detector().port_regex, Db2Detector().database_regex, [(DB2_HOSTNAME, DB2_PORT, DB2_DATABASE)], ), ( textwrap.dedent(""" jdbc:db2://{}:{}/ """)[1:-1].format( DB2_HOSTNAME, DB2_PORT, ), Db2Detector().hostname_regex, Db2Detector().port_regex, Db2Detector().database_regex, [], ), ( textwrap.dedent(""" nonsense """), Db2Detector().hostname_regex, Db2Detector().port_regex, Db2Detector().database_regex, [], ), ), ) def test_get_hostname_port_database_from_url( content, hostname_regex, port_regex, database_regex, expected_output, ): assert get_hostname_port_database_from_url( content, hostname_regex, port_regex, database_regex, ) == expected_output
true
true
1c33e6f6a138884a527d0ffde240901b01d5617b
6,981
py
Python
tests/app/api_v0/test_revisions.py
xwu64/server
d358db21db4a8faf33a3681fc499aeea07e9784b
[ "BSD-3-Clause" ]
null
null
null
tests/app/api_v0/test_revisions.py
xwu64/server
d358db21db4a8faf33a3681fc499aeea07e9784b
[ "BSD-3-Clause" ]
null
null
null
tests/app/api_v0/test_revisions.py
xwu64/server
d358db21db4a8faf33a3681fc499aeea07e9784b
[ "BSD-3-Clause" ]
null
null
null
# TODO: split E2E test to unit test import pytest from starlette.testclient import TestClient from tests.fixtures.mock_service import MockUserService __all__ = ["test_person_revisions_basic", "test_person_revisions_offset", "test_person_revisions_offset_limit", "test_character_revisions_basic", "test_character_revisions_offset", "test_character_revisions_page_limit", "test_subject_revisions_basic", "test_subject_revisions_offset", "test_subject_revisions_page_limit", "test_episode_revisions_basic", "test_episode_revisions_offset", "test_episode_revisions_page_limit"] person_revisions_api_prefix = "/v0/revisions/persons" @pytest.mark.env("e2e", "database") def test_person_revisions_basic( client: TestClient, mock_user_service: MockUserService, ): response = client.get(person_revisions_api_prefix, params={"person_id": 9}) assert response.status_code == 200 assert response.headers["content-type"] == "application/json" res = response.json() assert res["total"] assert res["data"] assert res["offset"] == 0 assert "limit" in res for item in res["data"]: assert "nickname" in item["creator"] @pytest.mark.env("e2e", "database") def test_person_revisions_offset( client: TestClient, mock_user_service: MockUserService, ): offset = 1 common_params = {"person_id": 9} response1 = client.get( person_revisions_api_prefix, params={"offset": 1, **common_params} ) assert response1.status_code == 200 assert response1.headers["content-type"] == "application/json" res = response1.json() assert ( res["data"][0]["id"] == client.get(person_revisions_api_prefix, params=common_params).json()["data"][ 1 ]["id"] ) assert res["offset"] == offset @pytest.mark.env("e2e", "database") def test_person_revisions_offset_limit( client: TestClient, mock_user_service: MockUserService, ): offset = 30000 response = client.get( person_revisions_api_prefix, params={"offset": offset, "person_id": 9} ) assert response.status_code == 422, response.text character_revisions_api_prefix = "/v0/revisions/characters" @pytest.mark.env("e2e", "database") def test_character_revisions_basic( client: TestClient, mock_user_service: MockUserService, ): response = client.get(character_revisions_api_prefix, params={"character_id": 1}) assert response.status_code == 200, response.json() assert response.headers["content-type"] == "application/json" res = response.json() assert res["total"] assert res["offset"] == 0 assert "limit" in res assert res["data"] @pytest.mark.env("e2e", "database") def test_character_revisions_offset( client: TestClient, mock_user_service: MockUserService, ): offset = 1 common_params = {"character_id": 1} response1 = client.get( character_revisions_api_prefix, params={"offset": offset, **common_params} ) assert response1.status_code == 200 assert response1.headers["content-type"] == "application/json" res = response1.json() assert ( res["data"][0]["id"] == client.get(character_revisions_api_prefix, params=common_params).json()[ "data" ][1]["id"] ) assert res["offset"] == offset @pytest.mark.env("e2e", "database") def test_character_revisions_page_limit( client: TestClient, mock_user_service: MockUserService, ): offset = 30000 response = client.get( character_revisions_api_prefix, params={"character_id": 1, "offset": offset} ) assert response.status_code == 422, response.text subject_revisions_api_prefix = "/v0/revisions/subjects" @pytest.mark.env("e2e", "database") def test_subject_revisions_basic( client: TestClient, mock_user_service: MockUserService ): response = client.get(subject_revisions_api_prefix, params={"subject_id": 26}) assert response.status_code == 200 assert response.headers["content-type"] == "application/json" res = response.json() assert "total" in res assert "limit" in res assert res["offset"] == 0 if res["total"] <= res["limit"]: assert res["total"] == len(res["data"]) else: assert res["limit"] == len(res["data"]) for item in res["data"]: if item["creator"]: assert "nickname" in item["creator"] @pytest.mark.env("e2e", "database") def test_subject_revisions_offset(client: TestClient): offset = 1 common_params = {"subject_id": 1} response1 = client.get( subject_revisions_api_prefix, params={"offset": offset, **common_params} ) assert response1.status_code == 200 assert response1.headers["content-type"] == "application/json" res = response1.json() assert ( res["data"][0]["id"] == client.get(subject_revisions_api_prefix, params=common_params).json()[ "data" ][1]["id"] ) assert res["offset"] == offset @pytest.mark.env("e2e", "database") def test_subject_revisions_page_limit( client: TestClient, ): offset = 30000 response = client.get( subject_revisions_api_prefix, params={"subject_id": 1, "offset": offset} ) assert response.status_code == 422, response.text episode_revisions_api_prefix = "/v0/revisions/episodes" @pytest.mark.env("e2e", "database") def test_episode_revisions_basic( client: TestClient, ): response = client.get(episode_revisions_api_prefix, params={"episode_id": 522}) assert response.status_code == 200 assert response.headers["content-type"] == "application/json" res = response.json() assert "total" in res assert "limit" in res assert res["offset"] == 0 if res["total"] <= res["limit"]: assert res["total"] == len(res["data"]) else: assert res["limit"] == len(res["data"]) for item in res["data"]: assert "nickname" in item["creator"] @pytest.mark.env("e2e", "database") def test_episode_revisions_offset( client: TestClient, ): offset = 1 common_params = {"episode_id": 1045} response1 = client.get( episode_revisions_api_prefix, params={"offset": offset, **common_params} ) assert response1.status_code == 200 assert response1.headers["content-type"] == "application/json" res = response1.json() assert ( res["data"][0]["id"] == client.get(episode_revisions_api_prefix, params=common_params).json()[ "data" ][1]["id"] ) assert res["offset"] == offset @pytest.mark.env("e2e", "database") def test_episode_revisions_page_limit( client: TestClient, ): offset = 30000 response = client.get( episode_revisions_api_prefix, params={"episode_id": 522, "offset": offset} ) assert response.status_code == 422, response.text
29.0875
88
0.664661
import pytest from starlette.testclient import TestClient from tests.fixtures.mock_service import MockUserService __all__ = ["test_person_revisions_basic", "test_person_revisions_offset", "test_person_revisions_offset_limit", "test_character_revisions_basic", "test_character_revisions_offset", "test_character_revisions_page_limit", "test_subject_revisions_basic", "test_subject_revisions_offset", "test_subject_revisions_page_limit", "test_episode_revisions_basic", "test_episode_revisions_offset", "test_episode_revisions_page_limit"] person_revisions_api_prefix = "/v0/revisions/persons" @pytest.mark.env("e2e", "database") def test_person_revisions_basic( client: TestClient, mock_user_service: MockUserService, ): response = client.get(person_revisions_api_prefix, params={"person_id": 9}) assert response.status_code == 200 assert response.headers["content-type"] == "application/json" res = response.json() assert res["total"] assert res["data"] assert res["offset"] == 0 assert "limit" in res for item in res["data"]: assert "nickname" in item["creator"] @pytest.mark.env("e2e", "database") def test_person_revisions_offset( client: TestClient, mock_user_service: MockUserService, ): offset = 1 common_params = {"person_id": 9} response1 = client.get( person_revisions_api_prefix, params={"offset": 1, **common_params} ) assert response1.status_code == 200 assert response1.headers["content-type"] == "application/json" res = response1.json() assert ( res["data"][0]["id"] == client.get(person_revisions_api_prefix, params=common_params).json()["data"][ 1 ]["id"] ) assert res["offset"] == offset @pytest.mark.env("e2e", "database") def test_person_revisions_offset_limit( client: TestClient, mock_user_service: MockUserService, ): offset = 30000 response = client.get( person_revisions_api_prefix, params={"offset": offset, "person_id": 9} ) assert response.status_code == 422, response.text character_revisions_api_prefix = "/v0/revisions/characters" @pytest.mark.env("e2e", "database") def test_character_revisions_basic( client: TestClient, mock_user_service: MockUserService, ): response = client.get(character_revisions_api_prefix, params={"character_id": 1}) assert response.status_code == 200, response.json() assert response.headers["content-type"] == "application/json" res = response.json() assert res["total"] assert res["offset"] == 0 assert "limit" in res assert res["data"] @pytest.mark.env("e2e", "database") def test_character_revisions_offset( client: TestClient, mock_user_service: MockUserService, ): offset = 1 common_params = {"character_id": 1} response1 = client.get( character_revisions_api_prefix, params={"offset": offset, **common_params} ) assert response1.status_code == 200 assert response1.headers["content-type"] == "application/json" res = response1.json() assert ( res["data"][0]["id"] == client.get(character_revisions_api_prefix, params=common_params).json()[ "data" ][1]["id"] ) assert res["offset"] == offset @pytest.mark.env("e2e", "database") def test_character_revisions_page_limit( client: TestClient, mock_user_service: MockUserService, ): offset = 30000 response = client.get( character_revisions_api_prefix, params={"character_id": 1, "offset": offset} ) assert response.status_code == 422, response.text subject_revisions_api_prefix = "/v0/revisions/subjects" @pytest.mark.env("e2e", "database") def test_subject_revisions_basic( client: TestClient, mock_user_service: MockUserService ): response = client.get(subject_revisions_api_prefix, params={"subject_id": 26}) assert response.status_code == 200 assert response.headers["content-type"] == "application/json" res = response.json() assert "total" in res assert "limit" in res assert res["offset"] == 0 if res["total"] <= res["limit"]: assert res["total"] == len(res["data"]) else: assert res["limit"] == len(res["data"]) for item in res["data"]: if item["creator"]: assert "nickname" in item["creator"] @pytest.mark.env("e2e", "database") def test_subject_revisions_offset(client: TestClient): offset = 1 common_params = {"subject_id": 1} response1 = client.get( subject_revisions_api_prefix, params={"offset": offset, **common_params} ) assert response1.status_code == 200 assert response1.headers["content-type"] == "application/json" res = response1.json() assert ( res["data"][0]["id"] == client.get(subject_revisions_api_prefix, params=common_params).json()[ "data" ][1]["id"] ) assert res["offset"] == offset @pytest.mark.env("e2e", "database") def test_subject_revisions_page_limit( client: TestClient, ): offset = 30000 response = client.get( subject_revisions_api_prefix, params={"subject_id": 1, "offset": offset} ) assert response.status_code == 422, response.text episode_revisions_api_prefix = "/v0/revisions/episodes" @pytest.mark.env("e2e", "database") def test_episode_revisions_basic( client: TestClient, ): response = client.get(episode_revisions_api_prefix, params={"episode_id": 522}) assert response.status_code == 200 assert response.headers["content-type"] == "application/json" res = response.json() assert "total" in res assert "limit" in res assert res["offset"] == 0 if res["total"] <= res["limit"]: assert res["total"] == len(res["data"]) else: assert res["limit"] == len(res["data"]) for item in res["data"]: assert "nickname" in item["creator"] @pytest.mark.env("e2e", "database") def test_episode_revisions_offset( client: TestClient, ): offset = 1 common_params = {"episode_id": 1045} response1 = client.get( episode_revisions_api_prefix, params={"offset": offset, **common_params} ) assert response1.status_code == 200 assert response1.headers["content-type"] == "application/json" res = response1.json() assert ( res["data"][0]["id"] == client.get(episode_revisions_api_prefix, params=common_params).json()[ "data" ][1]["id"] ) assert res["offset"] == offset @pytest.mark.env("e2e", "database") def test_episode_revisions_page_limit( client: TestClient, ): offset = 30000 response = client.get( episode_revisions_api_prefix, params={"episode_id": 522, "offset": offset} ) assert response.status_code == 422, response.text
true
true
1c33e80294a94d85a9edbb95747f6f5c2e32304a
1,387
py
Python
python/ecs/fargate-load-balanced-service/app.py
samtwil/aws-cdk-examples
a0ca373be2bd4e82f888f903fdb7c57d36d5537f
[ "Apache-2.0" ]
null
null
null
python/ecs/fargate-load-balanced-service/app.py
samtwil/aws-cdk-examples
a0ca373be2bd4e82f888f903fdb7c57d36d5537f
[ "Apache-2.0" ]
null
null
null
python/ecs/fargate-load-balanced-service/app.py
samtwil/aws-cdk-examples
a0ca373be2bd4e82f888f903fdb7c57d36d5537f
[ "Apache-2.0" ]
null
null
null
from aws_cdk import ( aws_autoscaling as autoscaling, aws_ec2 as ec2, aws_ecs as ecs, aws_ecs_patterns as ecs_patterns, App, CfnOutput, Stack ) from constructs import Construct class BonjourFargate(Stack): def __init__(self, scope: Construct, id: str, **kwargs) -> None: super().__init__(scope, id, **kwargs) # Create VPC and Fargate Cluster # NOTE: Limit AZs to avoid reaching resource quotas vpc = ec2.Vpc( self, "MyVpc", max_azs=2 ) cluster = ecs.Cluster( self, 'Ec2Cluster', vpc=vpc ) fargate_service = ecs_patterns.NetworkLoadBalancedFargateService( self, "FargateService", cluster=cluster, task_image_options=ecs_patterns.NetworkLoadBalancedTaskImageOptions( image=ecs.ContainerImage.from_registry("amazon/amazon-ecs-sample") ) ) fargate_service.service.connections.security_groups[0].add_ingress_rule( peer = ec2.Peer.ipv4(vpc.vpc_cidr_block), connection = ec2.Port.tcp(80), description="Allow http inbound from VPC" ) CfnOutput( self, "LoadBalancerDNS", value=fargate_service.load_balancer.load_balancer_dns_name ) app = App() BonjourFargate(app, "Bonjour") app.synth()
27.74
82
0.617159
from aws_cdk import ( aws_autoscaling as autoscaling, aws_ec2 as ec2, aws_ecs as ecs, aws_ecs_patterns as ecs_patterns, App, CfnOutput, Stack ) from constructs import Construct class BonjourFargate(Stack): def __init__(self, scope: Construct, id: str, **kwargs) -> None: super().__init__(scope, id, **kwargs) vpc = ec2.Vpc( self, "MyVpc", max_azs=2 ) cluster = ecs.Cluster( self, 'Ec2Cluster', vpc=vpc ) fargate_service = ecs_patterns.NetworkLoadBalancedFargateService( self, "FargateService", cluster=cluster, task_image_options=ecs_patterns.NetworkLoadBalancedTaskImageOptions( image=ecs.ContainerImage.from_registry("amazon/amazon-ecs-sample") ) ) fargate_service.service.connections.security_groups[0].add_ingress_rule( peer = ec2.Peer.ipv4(vpc.vpc_cidr_block), connection = ec2.Port.tcp(80), description="Allow http inbound from VPC" ) CfnOutput( self, "LoadBalancerDNS", value=fargate_service.load_balancer.load_balancer_dns_name ) app = App() BonjourFargate(app, "Bonjour") app.synth()
true
true
1c33eb22ed93e91c820b6bf40b6fff5c184acf47
1,225
py
Python
tests/core/extraction/test_mapping_analyzer.py
ymoch/preacher
ae68170d14c72791884e91b20054bd13a79b52d0
[ "MIT" ]
3
2019-08-01T03:14:49.000Z
2020-01-31T08:55:22.000Z
tests/core/extraction/test_mapping_analyzer.py
ymoch/preacher
ae68170d14c72791884e91b20054bd13a79b52d0
[ "MIT" ]
353
2019-04-14T14:53:28.000Z
2022-03-11T03:26:08.000Z
tests/core/extraction/test_mapping_analyzer.py
ymoch/preacher
ae68170d14c72791884e91b20054bd13a79b52d0
[ "MIT" ]
1
2020-08-01T06:23:08.000Z
2020-08-01T06:23:08.000Z
from dataclasses import dataclass from datetime import datetime, timezone from typing import Mapping from unittest.mock import sentinel from lxml.etree import _Element as Element from pytest import raises from preacher.core.extraction.analysis import MappingAnalyzer from preacher.core.extraction.error import ExtractionError @dataclass(frozen=True) class Context: value: object def test_for_text(): current = datetime(2019, 1, 2, 3, 4, 5, 678, tzinfo=timezone.utc) analyzer = MappingAnalyzer({"value": [current, 1, "A"]}) def _extract(value: str) -> object: assert value == '{"value":["2019-01-02T03:04:05.000678+00:00",1,"A"]}' return sentinel.extracted assert analyzer.for_text(_extract) is sentinel.extracted def test_for_mapping(): analyzer = MappingAnalyzer({"value": 1}) def _extract(value: Mapping) -> object: assert value == {"value": 1} return sentinel.extracted assert analyzer.for_mapping(_extract) is sentinel.extracted def test_for_etree(): analyzer = MappingAnalyzer({"value": 1}) def _extract(_: Element) -> object: return sentinel.extracted with raises(ExtractionError): analyzer.for_etree(_extract)
26.06383
78
0.713469
from dataclasses import dataclass from datetime import datetime, timezone from typing import Mapping from unittest.mock import sentinel from lxml.etree import _Element as Element from pytest import raises from preacher.core.extraction.analysis import MappingAnalyzer from preacher.core.extraction.error import ExtractionError @dataclass(frozen=True) class Context: value: object def test_for_text(): current = datetime(2019, 1, 2, 3, 4, 5, 678, tzinfo=timezone.utc) analyzer = MappingAnalyzer({"value": [current, 1, "A"]}) def _extract(value: str) -> object: assert value == '{"value":["2019-01-02T03:04:05.000678+00:00",1,"A"]}' return sentinel.extracted assert analyzer.for_text(_extract) is sentinel.extracted def test_for_mapping(): analyzer = MappingAnalyzer({"value": 1}) def _extract(value: Mapping) -> object: assert value == {"value": 1} return sentinel.extracted assert analyzer.for_mapping(_extract) is sentinel.extracted def test_for_etree(): analyzer = MappingAnalyzer({"value": 1}) def _extract(_: Element) -> object: return sentinel.extracted with raises(ExtractionError): analyzer.for_etree(_extract)
true
true
1c33ebd38ae22627863e394b94ce67736dfeaaf2
927
py
Python
users/migrations/0011_auto_20210412_1908.py
msking18/minor
17cffab95b5dc1705a131a1ef66ff7f47837de64
[ "MIT" ]
3
2021-03-22T10:39:18.000Z
2021-04-30T10:29:37.000Z
users/migrations/0011_auto_20210412_1908.py
msking18/minor
17cffab95b5dc1705a131a1ef66ff7f47837de64
[ "MIT" ]
1
2021-04-16T06:54:10.000Z
2021-04-16T06:54:10.000Z
users/migrations/0011_auto_20210412_1908.py
msking18/minor
17cffab95b5dc1705a131a1ef66ff7f47837de64
[ "MIT" ]
3
2021-03-11T10:02:37.000Z
2021-04-23T07:34:10.000Z
# Generated by Django 3.1.6 on 2021-04-12 13:38 from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('users', '0010_remove_profile_date_of_birth'), ] operations = [ migrations.AddField( model_name='profile', name='branch', field=models.CharField(default='CSE', max_length=15), ), migrations.AddField( model_name='profile', name='programme', field=models.CharField(default='B.Tech', max_length=15), ), migrations.AlterField( model_name='profile', name='city', field=models.CharField(default='Jaipur', max_length=100), ), migrations.AlterField( model_name='profile', name='state', field=models.CharField(default='Rajasthan', max_length=100), ), ]
27.264706
72
0.567422
from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('users', '0010_remove_profile_date_of_birth'), ] operations = [ migrations.AddField( model_name='profile', name='branch', field=models.CharField(default='CSE', max_length=15), ), migrations.AddField( model_name='profile', name='programme', field=models.CharField(default='B.Tech', max_length=15), ), migrations.AlterField( model_name='profile', name='city', field=models.CharField(default='Jaipur', max_length=100), ), migrations.AlterField( model_name='profile', name='state', field=models.CharField(default='Rajasthan', max_length=100), ), ]
true
true
1c33ee1592f2be0a3d6959054ddbc20841c3550a
2,584
py
Python
base.py
sosterbind/hexaRanger
a0b888061af4858c78962ed8c0154531f00e8455
[ "MIT" ]
null
null
null
base.py
sosterbind/hexaRanger
a0b888061af4858c78962ed8c0154531f00e8455
[ "MIT" ]
null
null
null
base.py
sosterbind/hexaRanger
a0b888061af4858c78962ed8c0154531f00e8455
[ "MIT" ]
null
null
null
from typing import ( Optional, List, Tuple, Dict, ) from abc import ( ABC, abstractmethod, ) class StoreClient(ABC): __slots__ = () @classmethod @abstractmethod def query_range_count( cls, start_key: Optional[str] = None, stop_key: Optional[str] = None, start_inclusive: bool = True, stop_inclusive: bool = True, ) -> int: raise NotImplementedError @classmethod @abstractmethod def query_range( cls, start_key: Optional[str] = None, stop_key: Optional[str] = None, start_inclusive: bool = True, stop_inclusive: bool = True, limit: Optional[int] = None, offset: Optional[int] = None, ) -> list: raise NotImplementedError @classmethod @abstractmethod def query_range_raw( cls, start_key: Optional[str] = None, stop_key: Optional[str] = None, start_inclusive: bool = True, stop_inclusive: bool = True, limit: Optional[int] = None, offset: Optional[int] = None, ) -> list: raise NotImplementedError @classmethod @abstractmethod def add_keys(cls, keys: List[str]): raise NotImplementedError @classmethod @abstractmethod def remove_keys(cls, keys: List[str]): raise NotImplementedError @classmethod @abstractmethod def add_and_remove_keys( cls, keys_to_add: List[str], keys_to_remove: List[str] ): raise NotImplementedError class HexaStore(ABC): @classmethod @abstractmethod def add_item(cls, *args, **kwargs): raise NotImplementedError @classmethod @abstractmethod def remove_item(cls, *args, **kwargs): raise NotImplementedError @classmethod @abstractmethod def lookup_items(cls, *args, **kwargs): raise NotImplementedError @classmethod @abstractmethod def count_items(cls, *args, **kwargs): raise NotImplementedError @classmethod @abstractmethod def update_item(cls, lookup: Dict[str, str], patch: Dict[str, str]): raise NotImplementedError @classmethod @abstractmethod def to_hexastore_key_set(cls, *args, **kwargs) -> List[str]: raise NotImplementedError @classmethod @abstractmethod def hexastore_key_to_tuple(cls, key: str) -> Tuple[str, str, str]: raise NotImplementedError @classmethod @abstractmethod def get_composite_key(cls, *args, **kwargs) -> str: raise NotImplementedError
23.279279
72
0.629257
from typing import ( Optional, List, Tuple, Dict, ) from abc import ( ABC, abstractmethod, ) class StoreClient(ABC): __slots__ = () @classmethod @abstractmethod def query_range_count( cls, start_key: Optional[str] = None, stop_key: Optional[str] = None, start_inclusive: bool = True, stop_inclusive: bool = True, ) -> int: raise NotImplementedError @classmethod @abstractmethod def query_range( cls, start_key: Optional[str] = None, stop_key: Optional[str] = None, start_inclusive: bool = True, stop_inclusive: bool = True, limit: Optional[int] = None, offset: Optional[int] = None, ) -> list: raise NotImplementedError @classmethod @abstractmethod def query_range_raw( cls, start_key: Optional[str] = None, stop_key: Optional[str] = None, start_inclusive: bool = True, stop_inclusive: bool = True, limit: Optional[int] = None, offset: Optional[int] = None, ) -> list: raise NotImplementedError @classmethod @abstractmethod def add_keys(cls, keys: List[str]): raise NotImplementedError @classmethod @abstractmethod def remove_keys(cls, keys: List[str]): raise NotImplementedError @classmethod @abstractmethod def add_and_remove_keys( cls, keys_to_add: List[str], keys_to_remove: List[str] ): raise NotImplementedError class HexaStore(ABC): @classmethod @abstractmethod def add_item(cls, *args, **kwargs): raise NotImplementedError @classmethod @abstractmethod def remove_item(cls, *args, **kwargs): raise NotImplementedError @classmethod @abstractmethod def lookup_items(cls, *args, **kwargs): raise NotImplementedError @classmethod @abstractmethod def count_items(cls, *args, **kwargs): raise NotImplementedError @classmethod @abstractmethod def update_item(cls, lookup: Dict[str, str], patch: Dict[str, str]): raise NotImplementedError @classmethod @abstractmethod def to_hexastore_key_set(cls, *args, **kwargs) -> List[str]: raise NotImplementedError @classmethod @abstractmethod def hexastore_key_to_tuple(cls, key: str) -> Tuple[str, str, str]: raise NotImplementedError @classmethod @abstractmethod def get_composite_key(cls, *args, **kwargs) -> str: raise NotImplementedError
true
true
1c33ef9ee86a9ecba33247c529a8b2b9daa28e69
532
py
Python
Mundo1/des33.py
julimoraislima/Python-CursoEmVideo
d21b0485d2f5767039d819cf743255dfd0f27b18
[ "MIT" ]
2
2021-01-05T12:31:00.000Z
2021-03-20T00:31:18.000Z
Mundo1/des33.py
julimoraislima/Python-CursoEmVideo
d21b0485d2f5767039d819cf743255dfd0f27b18
[ "MIT" ]
null
null
null
Mundo1/des33.py
julimoraislima/Python-CursoEmVideo
d21b0485d2f5767039d819cf743255dfd0f27b18
[ "MIT" ]
1
2020-12-28T22:56:10.000Z
2020-12-28T22:56:10.000Z
#desafio 33: Maior e Menor. Programa lê 3 valores, e retorna o maior e o menor valor. #1-maneira simplificada usando uma lista[]. primeiro = int(input('Digite o primeiro valor inteiro: ')) segundo = int(input('Digite o segundo valor inteiro: ')) terceiro = int(input('Digite o terceiro valor inteiro: ')) numeros = [primeiro, segundo, terceiro] print('-+-'*20) print(f'O \33[31mmaior\33[m valor digitado foi \33[31m{max(numeros)}\33[m') print(f'O \33[32mmenor\33[m valor digitado foi \33[32m{min(numeros)}\33[m') print('-+-'*20)
38
85
0.708647
primeiro = int(input('Digite o primeiro valor inteiro: ')) segundo = int(input('Digite o segundo valor inteiro: ')) terceiro = int(input('Digite o terceiro valor inteiro: ')) numeros = [primeiro, segundo, terceiro] print('-+-'*20) print(f'O \33[31mmaior\33[m valor digitado foi \33[31m{max(numeros)}\33[m') print(f'O \33[32mmenor\33[m valor digitado foi \33[32m{min(numeros)}\33[m') print('-+-'*20)
true
true
1c33f01fc1c0b21826cb0fe8d7917484a3137ed5
560
py
Python
scripts/mv_rednet.py
albert-yue/objectnav
95ce9bc2c1d953887275e8d9809a506aeb5682fb
[ "MIT", "Unlicense" ]
15
2021-04-12T04:36:14.000Z
2022-03-20T04:16:36.000Z
scripts/mv_rednet.py
albert-yue/objectnav
95ce9bc2c1d953887275e8d9809a506aeb5682fb
[ "MIT", "Unlicense" ]
4
2021-07-12T18:14:08.000Z
2021-11-11T13:44:34.000Z
scripts/mv_rednet.py
albert-yue/objectnav
95ce9bc2c1d953887275e8d9809a506aeb5682fb
[ "MIT", "Unlicense" ]
10
2021-06-23T23:14:16.000Z
2022-03-20T07:47:32.000Z
#%% # Move files around for rednet from pathlib import Path from shutil import move detailed_paths = Path('/srv/flash1/jye72/share/objectnav_detailed') eval_paths = Path('/srv/flash1/jye72/share/objectnav_eval') KEY = 'gt_False.pth' NEW_KEY = 'gt_False_21.pth' for var_path in eval_paths.glob("*"): # for var_path in detailed_paths.glob("*"): for ckpt in var_path.glob("*"): for val in ckpt.glob("*"): val = str(val) if KEY in val: new_path = val[:-len(KEY)] + NEW_KEY move(val, new_path)
28
67
0.633929
from pathlib import Path from shutil import move detailed_paths = Path('/srv/flash1/jye72/share/objectnav_detailed') eval_paths = Path('/srv/flash1/jye72/share/objectnav_eval') KEY = 'gt_False.pth' NEW_KEY = 'gt_False_21.pth' for var_path in eval_paths.glob("*"): for ckpt in var_path.glob("*"): for val in ckpt.glob("*"): val = str(val) if KEY in val: new_path = val[:-len(KEY)] + NEW_KEY move(val, new_path)
true
true
1c33f09cfd5449e71f3c16d72f5d6bf8a34449c9
3,500
py
Python
client.py
murilopereirame/ChatUDP
979a8ed5927bb0a431314cad2e36505bbbb256c2
[ "MIT" ]
null
null
null
client.py
murilopereirame/ChatUDP
979a8ed5927bb0a431314cad2e36505bbbb256c2
[ "MIT" ]
null
null
null
client.py
murilopereirame/ChatUDP
979a8ed5927bb0a431314cad2e36505bbbb256c2
[ "MIT" ]
null
null
null
import socket import threading import random import json import sys from RSA import RSA class Client: SERVER_UDP_IP_ADDRESS = "127.0.0.1" SERVER_UDP_PORT_NO = 6789 user = "" room = "geral" clientSock = None def __init__(self, ip): self.SERVER_UDP_IP_ADDRESS = ip self.room = 'lobby' def autenticate(self): usr = input('Insira seu nickname: ') if(usr == ''): usr = 'Visitante'+str(random.randint(1000, 2000)) self.user = usr print("Autenticado como " + self.user) def sendMessage(self, message): messagePackage = {'user': self.user, 'room': self.room, 'connecting': False, 'message': self.RSA.encryptString(message, self.serverPK)} self.clientSock.sendto(json.dumps(messagePackage).encode( 'utf-8'), (self.SERVER_UDP_IP_ADDRESS, self.SERVER_UDP_PORT_NO)) def changeRoom(self, room): self.room = room def connectToServer(self): self.clientSock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM) messagePackage = {'user': self.user, 'room': self.room, 'connecting': True, 'message': '', 'key': self.RSA.getPublicKey()} self.clientSock.sendto(json.dumps(messagePackage).encode( 'utf-8'), (self.SERVER_UDP_IP_ADDRESS, self.SERVER_UDP_PORT_NO)) def listenMessages(self): while True: data, addr = self.clientSock.recvfrom(1024) incoming = json.loads(data.decode('utf-8')) if('keys' in incoming): self.serverPK = incoming['keys'] continue msg = self.RSA.decryptString( incoming['message'], self.RSA.getPrivateKey()) if(incoming['user'] == self.SERVER_UDP_IP_ADDRESS+str(self.SERVER_UDP_PORT_NO)): if(msg[0:5].strip() == 'nick'): newUser = msg[5:] self.user = newUser print( '[SERVER] -> Nome de usuario em uso! Seu novo nome e ' + newUser) elif(msg[0:5].strip() == 'room'): newRoom = msg[5:] self.room = newRoom print('[SERVER] -> Sala alterada para ' + newRoom) else: sys.stdout.write('\r'+'['+incoming['user']+'] -> '+msg) sys.stdout.write('\n['+self.user+']: ') def chat(self): while True: data = input("[" + self.user + "]: ") if data == 'croom': sys.stdout.write("\033[F") newRoom = input("Digite a nova sala: ") self.room = newRoom self.sendMessage('croom ' + newRoom) continue elif data == '': continue elif data == 'disconnect': self.sendMessage(data) print('Desconectado do servidor') break sys.stdout.write("\033[F") print('['+self.user+'] -> ' + data) self.sendMessage(data) def initClient(self): self.RSA = RSA() self.autenticate() self.connectToServer() threading.Thread(target=self.listenMessages).start() threading.Thread(target=self.chat).start() if len(sys.argv) == 1: print('Para iniciar -> client.py server-ip') elif len(sys.argv) == 2: client = Client(sys.argv[1]) client.initClient()
34.653465
92
0.532286
import socket import threading import random import json import sys from RSA import RSA class Client: SERVER_UDP_IP_ADDRESS = "127.0.0.1" SERVER_UDP_PORT_NO = 6789 user = "" room = "geral" clientSock = None def __init__(self, ip): self.SERVER_UDP_IP_ADDRESS = ip self.room = 'lobby' def autenticate(self): usr = input('Insira seu nickname: ') if(usr == ''): usr = 'Visitante'+str(random.randint(1000, 2000)) self.user = usr print("Autenticado como " + self.user) def sendMessage(self, message): messagePackage = {'user': self.user, 'room': self.room, 'connecting': False, 'message': self.RSA.encryptString(message, self.serverPK)} self.clientSock.sendto(json.dumps(messagePackage).encode( 'utf-8'), (self.SERVER_UDP_IP_ADDRESS, self.SERVER_UDP_PORT_NO)) def changeRoom(self, room): self.room = room def connectToServer(self): self.clientSock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM) messagePackage = {'user': self.user, 'room': self.room, 'connecting': True, 'message': '', 'key': self.RSA.getPublicKey()} self.clientSock.sendto(json.dumps(messagePackage).encode( 'utf-8'), (self.SERVER_UDP_IP_ADDRESS, self.SERVER_UDP_PORT_NO)) def listenMessages(self): while True: data, addr = self.clientSock.recvfrom(1024) incoming = json.loads(data.decode('utf-8')) if('keys' in incoming): self.serverPK = incoming['keys'] continue msg = self.RSA.decryptString( incoming['message'], self.RSA.getPrivateKey()) if(incoming['user'] == self.SERVER_UDP_IP_ADDRESS+str(self.SERVER_UDP_PORT_NO)): if(msg[0:5].strip() == 'nick'): newUser = msg[5:] self.user = newUser print( '[SERVER] -> Nome de usuario em uso! Seu novo nome e ' + newUser) elif(msg[0:5].strip() == 'room'): newRoom = msg[5:] self.room = newRoom print('[SERVER] -> Sala alterada para ' + newRoom) else: sys.stdout.write('\r'+'['+incoming['user']+'] -> '+msg) sys.stdout.write('\n['+self.user+']: ') def chat(self): while True: data = input("[" + self.user + "]: ") if data == 'croom': sys.stdout.write("\033[F") newRoom = input("Digite a nova sala: ") self.room = newRoom self.sendMessage('croom ' + newRoom) continue elif data == '': continue elif data == 'disconnect': self.sendMessage(data) print('Desconectado do servidor') break sys.stdout.write("\033[F") print('['+self.user+'] -> ' + data) self.sendMessage(data) def initClient(self): self.RSA = RSA() self.autenticate() self.connectToServer() threading.Thread(target=self.listenMessages).start() threading.Thread(target=self.chat).start() if len(sys.argv) == 1: print('Para iniciar -> client.py server-ip') elif len(sys.argv) == 2: client = Client(sys.argv[1]) client.initClient()
true
true
1c33f0e69444ade9a5b966e522f9e8149c28c794
1,608
py
Python
fastreid/layers/rfconv/function.py
SZLSP/reid2020NAIC
d0eaee768e0be606417a27ce5ea2b3071b5a9bc2
[ "Apache-2.0" ]
2
2021-05-12T13:36:46.000Z
2021-08-15T10:35:08.000Z
fastreid/layers/rfconv/function.py
SZLSP/reid2020NAIC
d0eaee768e0be606417a27ce5ea2b3071b5a9bc2
[ "Apache-2.0" ]
1
2021-12-28T12:49:49.000Z
2021-12-28T12:49:49.000Z
fastreid/layers/rfconv/function.py
SZLSP/reid2020NAIC
d0eaee768e0be606417a27ce5ea2b3071b5a9bc2
[ "Apache-2.0" ]
null
null
null
##+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ ## Created by: Hang Zhang ## Email: zhanghang0704@gmail.com ## Copyright (c) 2020 ## ## LICENSE file in the root directory of this source tree ##+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ """Rectify function""" from torch.autograd import Function from . import lib __all__ = ['rectify'] class _rectify(Function): @staticmethod def forward(ctx, y, x, kernel_size, stride, padding, dilation, average): ctx.save_for_backward(x) # assuming kernel_size is 3 kernel_size = [k + 2 * (d - 1) for k, d in zip(kernel_size, dilation)] ctx.kernel_size = kernel_size ctx.stride = stride ctx.padding = padding ctx.dilation = dilation ctx.average = average if x.is_cuda: lib.gpu.conv_rectify(y, x, kernel_size, stride, padding, dilation, average) else: lib.cpu.conv_rectify(y, x, kernel_size, stride, padding, dilation, average) ctx.mark_dirty(y) return y @staticmethod def backward(ctx, grad_y): x, = ctx.saved_variables if x.is_cuda: lib.gpu.conv_rectify(grad_y, x, ctx.kernel_size, ctx.stride, ctx.padding, ctx.dilation, ctx.average) else: lib.cpu.conv_rectify(grad_y, x, ctx.kernel_size, ctx.stride, ctx.padding, ctx.dilation, ctx.average) ctx.mark_dirty(grad_y) return grad_y, None, None, None, None, None, None rectify = _rectify.apply
32.816327
87
0.55597
(d - 1) for k, d in zip(kernel_size, dilation)] ctx.kernel_size = kernel_size ctx.stride = stride ctx.padding = padding ctx.dilation = dilation ctx.average = average if x.is_cuda: lib.gpu.conv_rectify(y, x, kernel_size, stride, padding, dilation, average) else: lib.cpu.conv_rectify(y, x, kernel_size, stride, padding, dilation, average) ctx.mark_dirty(y) return y @staticmethod def backward(ctx, grad_y): x, = ctx.saved_variables if x.is_cuda: lib.gpu.conv_rectify(grad_y, x, ctx.kernel_size, ctx.stride, ctx.padding, ctx.dilation, ctx.average) else: lib.cpu.conv_rectify(grad_y, x, ctx.kernel_size, ctx.stride, ctx.padding, ctx.dilation, ctx.average) ctx.mark_dirty(grad_y) return grad_y, None, None, None, None, None, None rectify = _rectify.apply
true
true
1c33f10cfc5099f1a9b12d2e015bf0dafde36b97
9,559
py
Python
tensorflow/python/ops/control_flow_grad.py
KosingZhu/tensorflow
7ac2521a4e609ddef0f0ea3ffc2e76102da934d7
[ "Apache-2.0" ]
9
2021-11-06T11:09:48.000Z
2021-12-12T04:52:29.000Z
tensorflow/python/ops/control_flow_grad.py
KosingZhu/tensorflow
7ac2521a4e609ddef0f0ea3ffc2e76102da934d7
[ "Apache-2.0" ]
2
2021-10-06T23:12:04.000Z
2021-10-06T23:12:04.000Z
tensorflow/python/ops/control_flow_grad.py
KosingZhu/tensorflow
7ac2521a4e609ddef0f0ea3ffc2e76102da934d7
[ "Apache-2.0" ]
1
2021-11-11T04:43:09.000Z
2021-11-11T04:43:09.000Z
# Copyright 2015 The TensorFlow Authors. 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. # ============================================================================== """Gradients for operators defined in control_flow_ops.py.""" from six.moves import xrange # pylint: disable=redefined-builtin from tensorflow.python.framework import dtypes from tensorflow.python.framework import indexed_slices from tensorflow.python.framework import ops from tensorflow.python.framework import sparse_tensor from tensorflow.python.ops import control_flow_ops from tensorflow.python.ops import control_flow_util from tensorflow.python.ops import math_ops # go/tf-wildcard-import # pylint: disable=wildcard-import,undefined-variable,redefined-builtin from tensorflow.python.ops.control_flow_ops import * # pylint: enable=wildcard-import def _SwitchGrad(op, *grad): """Gradients for a Switch op is calculated using a Merge op. If the switch is a loop switch, it will be visited twice. We create the merge on the first visit, and update the other input of the merge on the second visit. A next_iteration is also added on second visit. """ graph = ops.get_default_graph() # pylint: disable=protected-access op_ctxt = op._get_control_flow_context() grad_ctxt = graph._get_control_flow_context() # pylint: enable=protected-access if isinstance(op_ctxt, WhileContext): merge_grad = grad_ctxt.grad_state.switch_map.get(op) if merge_grad is not None: # This is the second time this Switch is visited. It comes from # the non-exit branch of the Switch, so update the second input # to the Merge. # TODO(yuanbyu): Perform shape inference with this new input. if grad[1] is not None: # pylint: disable=protected-access control_flow_ops._AddNextAndBackEdge(merge_grad, grad[1], enforce_shape_invariant=False) # pylint: enable=protected-access return None, None elif grad[0] is not None: # This is the first time this Switch is visited. It comes from # the Exit branch, which is grad[0]. grad[1] is empty at this point. # Use grad[0] for both inputs to merge for now, but update the second # input of merge when we see this Switch the second time. merge_grad = merge([grad[0], grad[0]], name="b_switch")[0] grad_ctxt.grad_state.switch_map[op] = merge_grad return merge_grad, None else: # This is the first time this Switch is visited. It comes from the # Identity branch. Such a Switch has `None` gradient for the Exit branch, # meaning the output is not differentiable. return None, None elif isinstance(op_ctxt, CondContext): zero_grad = grad[1 - op_ctxt.branch] # At this point, we have created zero_grad guarded by the right switch. # Unfortunately, we may still get None here for not trainable data types. if zero_grad is None: # For resource variables we get None always on the other branch, so bypass # this. if op.inputs[0].dtype == dtypes.resource: return merge( [grad[op_ctxt.branch]] * 2, name="cond_resource_grad")[0], None return None, None return merge(grad, name="cond_grad")[0], None else: false_grad = switch(grad[0], op.inputs[1])[0] true_grad = switch(grad[1], op.inputs[1])[1] return merge([false_grad, true_grad])[0], None ops.RegisterGradient("Switch")(_SwitchGrad) ops.RegisterGradient("RefSwitch")(_SwitchGrad) @ops.RegisterGradient("Merge") def _MergeGrad(op, grad, _): """Gradients for a Merge op are calculated using a Switch op.""" input_op = op.inputs[0].op graph = ops.get_default_graph() # pylint: disable=protected-access op_ctxt = control_flow_util.GetOutputContext(input_op) grad_ctxt = graph._get_control_flow_context() # pylint: enable=protected-access if isinstance(op_ctxt, WhileContext): # pylint: disable=protected-access return control_flow_ops._SwitchRefOrTensor(grad, grad_ctxt.pivot) # pylint: enable=protected-access elif isinstance(op_ctxt, CondContext): pred = op_ctxt.pred if grad_ctxt and grad_ctxt.grad_state: # This Merge node is part of a cond within a loop. # The backprop needs to have the value of this predicate for every # iteration. So we must have its values accumulated in the forward, and # use the accumulated values as the predicate for this backprop switch. grad_state = grad_ctxt.grad_state real_pred = grad_state.history_map.get(pred.name) if real_pred is None: # Remember the value of pred for every iteration. grad_ctxt = grad_state.grad_context grad_ctxt.Exit() history_pred = grad_state.AddForwardAccumulator(pred) grad_ctxt.Enter() # Add the stack pop op. If pred.op is in a (outer) CondContext, # the stack pop will be guarded with a switch. real_pred = grad_state.AddBackpropAccumulatedValue(history_pred, pred) grad_state.history_map[pred.name] = real_pred pred = real_pred # pylint: disable=protected-access return control_flow_ops._SwitchRefOrTensor(grad, pred, name="cond_grad") # pylint: enable=protected-access else: num_inputs = len(op.inputs) cond = [math_ops.equal(op.outputs[1], i) for i in xrange(num_inputs)] # pylint: disable=protected-access return [control_flow_ops._SwitchRefOrTensor(grad, cond[i])[1] for i in xrange(num_inputs)] # pylint: enable=protected-access @ops.RegisterGradient("RefMerge") def _RefMergeGrad(op, grad, _): return _MergeGrad(op, grad, _) @ops.RegisterGradient("Exit") def _ExitGrad(op, grad): """Gradients for an exit op are calculated using an Enter op.""" graph = ops.get_default_graph() # pylint: disable=protected-access op_ctxt = op._get_control_flow_context() grad_ctxt = graph._get_control_flow_context() # pylint: enable=protected-access if not grad_ctxt.back_prop: # The flag `back_prop` is set by users to suppress gradient # computation for this loop. If the attribute `back_prop` is false, # no gradient computation. return None if op_ctxt.grad_state: raise TypeError("Second-order gradient for while loops not supported.") if isinstance(grad, ops.Tensor): grad_ctxt.AddName(grad.name) else: if not isinstance( grad, (indexed_slices.IndexedSlices, sparse_tensor.SparseTensor)): raise TypeError(f"Type {type(grad)} not supported, must be either" "`indexed_slices.IndexedSlices` or `SparseTensor`.") grad_ctxt.AddName(grad.values.name) grad_ctxt.AddName(grad.indices.name) dense_shape = grad.dense_shape if dense_shape is not None: grad_ctxt.AddName(dense_shape.name) grad_ctxt.Enter() # pylint: disable=protected-access result = control_flow_ops._Enter( grad, grad_ctxt.name, is_constant=False, parallel_iterations=grad_ctxt.parallel_iterations, name="b_exit") # pylint: enable=protected-access grad_ctxt.loop_enters.append(result) grad_ctxt.Exit() return result ops.RegisterGradient("RefExit")(_ExitGrad) @ops.RegisterGradient("NextIteration") def _NextIterationGrad(_, grad): """A forward next_iteration is translated into a backprop identity. Note that the backprop next_iteration is added in switch grad. """ return grad @ops.RegisterGradient("RefNextIteration") def _RefNextIterationGrad(_, grad): return _NextIterationGrad(_, grad) @ops.RegisterGradient("Enter") def _EnterGrad(op, grad): """Gradients for an Enter are calculated using an Exit op. For loop variables, grad is the gradient so just add an exit. For loop invariants, we need to add an accumulator loop. """ graph = ops.get_default_graph() # pylint: disable=protected-access grad_ctxt = graph._get_control_flow_context() # pylint: enable=protected-access if grad_ctxt is None: return grad if not grad_ctxt.back_prop: # Skip gradient computation, if the attribute `back_prop` is false. return grad if grad_ctxt.grad_state is None: # Pass the gradient through if we are not in a gradient while context. return grad if op.get_attr("is_constant"): # Add a gradient accumulator for each loop invariant. if isinstance(grad, ops.Tensor): result = grad_ctxt.AddBackpropAccumulator(op, grad) elif isinstance(grad, indexed_slices.IndexedSlices): result = grad_ctxt.AddBackpropIndexedSlicesAccumulator(op, grad) else: # TODO(yuanbyu, lukasr): Add support for SparseTensor. raise TypeError(f"Type {type(grad)} not supported," "must be Tensor or Indexed Slices") else: result = exit(grad) grad_ctxt.loop_exits.append(result) grad_ctxt.ExitResult([result]) return result @ops.RegisterGradient("RefEnter") def _RefEnterGrad(op, grad): return _EnterGrad(op, grad) @ops.RegisterGradient("LoopCond") def _LoopCondGrad(_): """Stop backprop for the predicate of a while loop.""" return None
38.857724
80
0.715661
from six.moves import xrange from tensorflow.python.framework import dtypes from tensorflow.python.framework import indexed_slices from tensorflow.python.framework import ops from tensorflow.python.framework import sparse_tensor from tensorflow.python.ops import control_flow_ops from tensorflow.python.ops import control_flow_util from tensorflow.python.ops import math_ops from tensorflow.python.ops.control_flow_ops import * def _SwitchGrad(op, *grad): graph = ops.get_default_graph() op_ctxt = op._get_control_flow_context() grad_ctxt = graph._get_control_flow_context() if isinstance(op_ctxt, WhileContext): merge_grad = grad_ctxt.grad_state.switch_map.get(op) if merge_grad is not None: if grad[1] is not None: control_flow_ops._AddNextAndBackEdge(merge_grad, grad[1], enforce_shape_invariant=False) return None, None elif grad[0] is not None: merge_grad = merge([grad[0], grad[0]], name="b_switch")[0] grad_ctxt.grad_state.switch_map[op] = merge_grad return merge_grad, None else: return None, None elif isinstance(op_ctxt, CondContext): zero_grad = grad[1 - op_ctxt.branch] if zero_grad is None: if op.inputs[0].dtype == dtypes.resource: return merge( [grad[op_ctxt.branch]] * 2, name="cond_resource_grad")[0], None return None, None return merge(grad, name="cond_grad")[0], None else: false_grad = switch(grad[0], op.inputs[1])[0] true_grad = switch(grad[1], op.inputs[1])[1] return merge([false_grad, true_grad])[0], None ops.RegisterGradient("Switch")(_SwitchGrad) ops.RegisterGradient("RefSwitch")(_SwitchGrad) @ops.RegisterGradient("Merge") def _MergeGrad(op, grad, _): input_op = op.inputs[0].op graph = ops.get_default_graph() op_ctxt = control_flow_util.GetOutputContext(input_op) grad_ctxt = graph._get_control_flow_context() if isinstance(op_ctxt, WhileContext): return control_flow_ops._SwitchRefOrTensor(grad, grad_ctxt.pivot) elif isinstance(op_ctxt, CondContext): pred = op_ctxt.pred if grad_ctxt and grad_ctxt.grad_state: grad_state = grad_ctxt.grad_state real_pred = grad_state.history_map.get(pred.name) if real_pred is None: grad_ctxt = grad_state.grad_context grad_ctxt.Exit() history_pred = grad_state.AddForwardAccumulator(pred) grad_ctxt.Enter() real_pred = grad_state.AddBackpropAccumulatedValue(history_pred, pred) grad_state.history_map[pred.name] = real_pred pred = real_pred return control_flow_ops._SwitchRefOrTensor(grad, pred, name="cond_grad") else: num_inputs = len(op.inputs) cond = [math_ops.equal(op.outputs[1], i) for i in xrange(num_inputs)] return [control_flow_ops._SwitchRefOrTensor(grad, cond[i])[1] for i in xrange(num_inputs)] @ops.RegisterGradient("RefMerge") def _RefMergeGrad(op, grad, _): return _MergeGrad(op, grad, _) @ops.RegisterGradient("Exit") def _ExitGrad(op, grad): graph = ops.get_default_graph() op_ctxt = op._get_control_flow_context() grad_ctxt = graph._get_control_flow_context() if not grad_ctxt.back_prop: return None if op_ctxt.grad_state: raise TypeError("Second-order gradient for while loops not supported.") if isinstance(grad, ops.Tensor): grad_ctxt.AddName(grad.name) else: if not isinstance( grad, (indexed_slices.IndexedSlices, sparse_tensor.SparseTensor)): raise TypeError(f"Type {type(grad)} not supported, must be either" "`indexed_slices.IndexedSlices` or `SparseTensor`.") grad_ctxt.AddName(grad.values.name) grad_ctxt.AddName(grad.indices.name) dense_shape = grad.dense_shape if dense_shape is not None: grad_ctxt.AddName(dense_shape.name) grad_ctxt.Enter() result = control_flow_ops._Enter( grad, grad_ctxt.name, is_constant=False, parallel_iterations=grad_ctxt.parallel_iterations, name="b_exit") grad_ctxt.loop_enters.append(result) grad_ctxt.Exit() return result ops.RegisterGradient("RefExit")(_ExitGrad) @ops.RegisterGradient("NextIteration") def _NextIterationGrad(_, grad): return grad @ops.RegisterGradient("RefNextIteration") def _RefNextIterationGrad(_, grad): return _NextIterationGrad(_, grad) @ops.RegisterGradient("Enter") def _EnterGrad(op, grad): graph = ops.get_default_graph() grad_ctxt = graph._get_control_flow_context() if grad_ctxt is None: return grad if not grad_ctxt.back_prop: return grad if grad_ctxt.grad_state is None: return grad if op.get_attr("is_constant"): if isinstance(grad, ops.Tensor): result = grad_ctxt.AddBackpropAccumulator(op, grad) elif isinstance(grad, indexed_slices.IndexedSlices): result = grad_ctxt.AddBackpropIndexedSlicesAccumulator(op, grad) else: raise TypeError(f"Type {type(grad)} not supported," "must be Tensor or Indexed Slices") else: result = exit(grad) grad_ctxt.loop_exits.append(result) grad_ctxt.ExitResult([result]) return result @ops.RegisterGradient("RefEnter") def _RefEnterGrad(op, grad): return _EnterGrad(op, grad) @ops.RegisterGradient("LoopCond") def _LoopCondGrad(_): return None
true
true
1c33f139de8a7e5d3fbf8f0aabab26f6e70cf9c7
65
py
Python
tests/__init__.py
cthoyt/apicuron-client
f4988dd12437042492e678ac42a4685b147548d2
[ "MIT" ]
null
null
null
tests/__init__.py
cthoyt/apicuron-client
f4988dd12437042492e678ac42a4685b147548d2
[ "MIT" ]
null
null
null
tests/__init__.py
cthoyt/apicuron-client
f4988dd12437042492e678ac42a4685b147548d2
[ "MIT" ]
null
null
null
# -*- coding: utf-8 -*- """Tests for :mod:`apicuron_client`."""
16.25
39
0.553846
true
true
1c33f25ddcc7a95fb0d01c4542249e11bbb23454
326
py
Python
Backend/Trackerapp/migrations/0012_remove_customuser_is_verified.py
OscarMugendi/Project-Tracker
f805e706332bb387d9e0f1ed537e91d1360bf2b1
[ "MIT" ]
null
null
null
Backend/Trackerapp/migrations/0012_remove_customuser_is_verified.py
OscarMugendi/Project-Tracker
f805e706332bb387d9e0f1ed537e91d1360bf2b1
[ "MIT" ]
null
null
null
Backend/Trackerapp/migrations/0012_remove_customuser_is_verified.py
OscarMugendi/Project-Tracker
f805e706332bb387d9e0f1ed537e91d1360bf2b1
[ "MIT" ]
null
null
null
from django.db import migrations class Migration(migrations.Migration): dependencies = [ ('Trackerapp', '0011_merge_0008_auto_20211017_2325_0010_auto_20211019_1133'), ] operations = [ migrations.RemoveField( model_name='customuser', name='is_verified', ), ]
20.375
85
0.634969
from django.db import migrations class Migration(migrations.Migration): dependencies = [ ('Trackerapp', '0011_merge_0008_auto_20211017_2325_0010_auto_20211019_1133'), ] operations = [ migrations.RemoveField( model_name='customuser', name='is_verified', ), ]
true
true
1c33f2c02c78023d8b92c3824c4be9f5fc7bcb0d
681
py
Python
_scripts/docker_compose_run_bash.py
gerold-penz/got-your-back
614559e411e22b25512932833d429cf831b51c4f
[ "ECL-2.0", "Apache-2.0" ]
1
2020-05-08T08:12:49.000Z
2020-05-08T08:12:49.000Z
_scripts/docker_compose_run_bash.py
gerold-penz/got-your-back
614559e411e22b25512932833d429cf831b51c4f
[ "ECL-2.0", "Apache-2.0" ]
null
null
null
_scripts/docker_compose_run_bash.py
gerold-penz/got-your-back
614559e411e22b25512932833d429cf831b51c4f
[ "ECL-2.0", "Apache-2.0" ]
null
null
null
#!/usr/bin/env python3 # coding: utf-8 import os import sys import subprocess THISDIR = os.path.dirname(os.path.realpath(__file__)) DOCKERDIR = os.path.abspath(os.path.join(THISDIR, "..", "docker")) def main(): print("Docker-Compose RUN\n") try: returncode = subprocess.call( ["docker-compose", "run", "--rm", "got-your-back", "/bin/bash"], cwd=DOCKERDIR, env=os.environ, shell=sys.platform.startswith("win") ) if returncode != 0: input("Press ENTER to continue...") except KeyboardInterrupt: pass print("Fertig!") print() if __name__ == "__main__": main()
20.636364
76
0.578561
import os import sys import subprocess THISDIR = os.path.dirname(os.path.realpath(__file__)) DOCKERDIR = os.path.abspath(os.path.join(THISDIR, "..", "docker")) def main(): print("Docker-Compose RUN\n") try: returncode = subprocess.call( ["docker-compose", "run", "--rm", "got-your-back", "/bin/bash"], cwd=DOCKERDIR, env=os.environ, shell=sys.platform.startswith("win") ) if returncode != 0: input("Press ENTER to continue...") except KeyboardInterrupt: pass print("Fertig!") print() if __name__ == "__main__": main()
true
true
1c33f38502390e02bec734428384c40a1477ab00
19,941
py
Python
source/_UIAHandler.py
asaranprasad/nvda
e9609694acbfb06398eb6552067a0dcd532d67af
[ "bzip2-1.0.6" ]
1
2018-11-16T10:15:59.000Z
2018-11-16T10:15:59.000Z
source/_UIAHandler.py
asaranprasad/nvda
e9609694acbfb06398eb6552067a0dcd532d67af
[ "bzip2-1.0.6" ]
null
null
null
source/_UIAHandler.py
asaranprasad/nvda
e9609694acbfb06398eb6552067a0dcd532d67af
[ "bzip2-1.0.6" ]
null
null
null
#_UIAHandler.py #A part of NonVisual Desktop Access (NVDA) #Copyright (C) 2011-2018 NV Access Limited, Joseph Lee, Babbage B.V. #This file is covered by the GNU General Public License. #See the file COPYING for more details. from ctypes import * from ctypes.wintypes import * import comtypes.client from comtypes.automation import VT_EMPTY from comtypes import * import weakref import threading import time import config import api import appModuleHandler import queueHandler import controlTypes import NVDAHelper import winKernel import winUser import eventHandler from logHandler import log import UIAUtils from comtypes.gen.UIAutomationClient import * #Some newer UIA constants that could be missing ItemIndex_Property_GUID=GUID("{92A053DA-2969-4021-BF27-514CFC2E4A69}") ItemCount_Property_GUID=GUID("{ABBF5C45-5CCC-47b7-BB4E-87CB87BBD162}") HorizontalTextAlignment_Left=0 HorizontalTextAlignment_Centered=1 HorizontalTextAlignment_Right=2 HorizontalTextAlignment_Justified=3 # The name of the WDAG (Windows Defender Application Guard) process WDAG_PROCESS_NAME=u'hvsirdpclient' goodUIAWindowClassNames=[ # A WDAG (Windows Defender Application Guard) Window is always native UIA, even if it doesn't report as such. 'RAIL_WINDOW', ] badUIAWindowClassNames=[ "SysTreeView32", "WuDuiListView", "ComboBox", "msctls_progress32", "Edit", "CommonPlacesWrapperWndClass", "SysMonthCal32", "SUPERGRID", #Outlook 2010 message list "RichEdit", "RichEdit20", "RICHEDIT50W", "SysListView32", "EXCEL7", "Button", # #7497: Windows 10 Fall Creators Update has an incomplete UIA implementation for console windows, therefore for now we should ignore it. # It does not implement caret/selection, and probably has no new text events. "ConsoleWindowClass", ] # #8405: used to detect UIA dialogs prior to Windows 10 RS5. UIADialogClassNames=[ "#32770", "NUIDialog", "Credential Dialog Xaml Host", # UAC dialog in Anniversary Update and later "Shell_Dialog", "Shell_Flyout", "Shell_SystemDialog", # Various dialogs in Windows 10 Settings app ] NVDAUnitsToUIAUnits={ "character":TextUnit_Character, "word":TextUnit_Word, "line":TextUnit_Line, "paragraph":TextUnit_Paragraph, "readingChunk":TextUnit_Line, } UIAControlTypesToNVDARoles={ UIA_ButtonControlTypeId:controlTypes.ROLE_BUTTON, UIA_CalendarControlTypeId:controlTypes.ROLE_CALENDAR, UIA_CheckBoxControlTypeId:controlTypes.ROLE_CHECKBOX, UIA_ComboBoxControlTypeId:controlTypes.ROLE_COMBOBOX, UIA_EditControlTypeId:controlTypes.ROLE_EDITABLETEXT, UIA_HyperlinkControlTypeId:controlTypes.ROLE_LINK, UIA_ImageControlTypeId:controlTypes.ROLE_GRAPHIC, UIA_ListItemControlTypeId:controlTypes.ROLE_LISTITEM, UIA_ListControlTypeId:controlTypes.ROLE_LIST, UIA_MenuControlTypeId:controlTypes.ROLE_POPUPMENU, UIA_MenuBarControlTypeId:controlTypes.ROLE_MENUBAR, UIA_MenuItemControlTypeId:controlTypes.ROLE_MENUITEM, UIA_ProgressBarControlTypeId:controlTypes.ROLE_PROGRESSBAR, UIA_RadioButtonControlTypeId:controlTypes.ROLE_RADIOBUTTON, UIA_ScrollBarControlTypeId:controlTypes.ROLE_SCROLLBAR, UIA_SliderControlTypeId:controlTypes.ROLE_SLIDER, UIA_SpinnerControlTypeId:controlTypes.ROLE_SPINBUTTON, UIA_StatusBarControlTypeId:controlTypes.ROLE_STATUSBAR, UIA_TabControlTypeId:controlTypes.ROLE_TABCONTROL, UIA_TabItemControlTypeId:controlTypes.ROLE_TAB, UIA_TextControlTypeId:controlTypes.ROLE_STATICTEXT, UIA_ToolBarControlTypeId:controlTypes.ROLE_TOOLBAR, UIA_ToolTipControlTypeId:controlTypes.ROLE_TOOLTIP, UIA_TreeControlTypeId:controlTypes.ROLE_TREEVIEW, UIA_TreeItemControlTypeId:controlTypes.ROLE_TREEVIEWITEM, UIA_CustomControlTypeId:controlTypes.ROLE_UNKNOWN, UIA_GroupControlTypeId:controlTypes.ROLE_GROUPING, UIA_ThumbControlTypeId:controlTypes.ROLE_THUMB, UIA_DataGridControlTypeId:controlTypes.ROLE_DATAGRID, UIA_DataItemControlTypeId:controlTypes.ROLE_DATAITEM, UIA_DocumentControlTypeId:controlTypes.ROLE_DOCUMENT, UIA_SplitButtonControlTypeId:controlTypes.ROLE_SPLITBUTTON, UIA_WindowControlTypeId:controlTypes.ROLE_WINDOW, UIA_PaneControlTypeId:controlTypes.ROLE_PANE, UIA_HeaderControlTypeId:controlTypes.ROLE_HEADER, UIA_HeaderItemControlTypeId:controlTypes.ROLE_HEADERITEM, UIA_TableControlTypeId:controlTypes.ROLE_TABLE, UIA_TitleBarControlTypeId:controlTypes.ROLE_TITLEBAR, UIA_SeparatorControlTypeId:controlTypes.ROLE_SEPARATOR, } UIAPropertyIdsToNVDAEventNames={ UIA_NamePropertyId:"nameChange", UIA_HelpTextPropertyId:"descriptionChange", UIA_ExpandCollapseExpandCollapseStatePropertyId:"stateChange", UIA_ToggleToggleStatePropertyId:"stateChange", UIA_IsEnabledPropertyId:"stateChange", UIA_ValueValuePropertyId:"valueChange", UIA_RangeValueValuePropertyId:"valueChange", UIA_ControllerForPropertyId:"UIA_controllerFor", } UIAEventIdsToNVDAEventNames={ UIA_LiveRegionChangedEventId:"liveRegionChange", #UIA_Text_TextChangedEventId:"textChanged", UIA_SelectionItem_ElementSelectedEventId:"UIA_elementSelected", UIA_MenuOpenedEventId:"gainFocus", UIA_SelectionItem_ElementAddedToSelectionEventId:"stateChange", UIA_SelectionItem_ElementRemovedFromSelectionEventId:"stateChange", #UIA_MenuModeEndEventId:"menuModeEnd", #UIA_Text_TextSelectionChangedEventId:"caret", UIA_ToolTipOpenedEventId:"UIA_toolTipOpened", #UIA_AsyncContentLoadedEventId:"documentLoadComplete", #UIA_ToolTipClosedEventId:"hide", UIA_Window_WindowOpenedEventId:"UIA_window_windowOpen", UIA_SystemAlertEventId:"UIA_systemAlert", } class UIAHandler(COMObject): _com_interfaces_=[IUIAutomationEventHandler,IUIAutomationFocusChangedEventHandler,IUIAutomationPropertyChangedEventHandler,IUIAutomationNotificationEventHandler] def __init__(self): super(UIAHandler,self).__init__() self.MTAThreadInitEvent=threading.Event() self.MTAThreadStopEvent=threading.Event() self.MTAThreadInitException=None self.MTAThread=threading.Thread(target=self.MTAThreadFunc) self.MTAThread.daemon=True self.MTAThread.start() self.MTAThreadInitEvent.wait(2) if self.MTAThreadInitException: raise self.MTAThreadInitException def terminate(self): MTAThreadHandle=HANDLE(windll.kernel32.OpenThread(winKernel.SYNCHRONIZE,False,self.MTAThread.ident)) self.MTAThreadStopEvent.set() #Wait for the MTA thread to die (while still message pumping) if windll.user32.MsgWaitForMultipleObjects(1,byref(MTAThreadHandle),False,200,0)!=0: log.debugWarning("Timeout or error while waiting for UIAHandler MTA thread") windll.kernel32.CloseHandle(MTAThreadHandle) del self.MTAThread def MTAThreadFunc(self): try: oledll.ole32.CoInitializeEx(None,comtypes.COINIT_MULTITHREADED) isUIA8=False try: self.clientObject=CoCreateInstance(CUIAutomation8._reg_clsid_,interface=IUIAutomation,clsctx=CLSCTX_INPROC_SERVER) isUIA8=True except (COMError,WindowsError,NameError): self.clientObject=CoCreateInstance(CUIAutomation._reg_clsid_,interface=IUIAutomation,clsctx=CLSCTX_INPROC_SERVER) # #7345: Instruct UIA to never map MSAA winEvents to UIA propertyChange events. # These events are not needed by NVDA, and they can cause the UI Automation client library to become unresponsive if an application firing winEvents has a slow message pump. pfm=self.clientObject.proxyFactoryMapping for index in xrange(pfm.count): e=pfm.getEntry(index) for propertyID in UIAPropertyIdsToNVDAEventNames.keys(): # Check if this proxy has mapped any winEvents to the UIA propertyChange event for this property ID try: oldWinEvents=e.getWinEventsForAutomationEvent(UIA_AutomationPropertyChangedEventId,propertyID) except IndexError: # comtypes does not seem to correctly handle a returned empty SAFEARRAY, raising IndexError oldWinEvents=None if oldWinEvents: # As winEvents were mapped, replace them with an empty list e.setWinEventsForAutomationEvent(UIA_AutomationPropertyChangedEventId,propertyID,[]) # Changes to an enty are not automatically picked up. # Therefore remove the entry and re-insert it. pfm.removeEntry(index) pfm.insertEntry(index,e) if isUIA8: # #8009: use appropriate interface based on highest supported interface. # #8338: made easier by traversing interfaces supported on Windows 8 and later in reverse. for interface in reversed(CUIAutomation8._com_interfaces_): try: self.clientObject=self.clientObject.QueryInterface(interface) break except COMError: pass # Windows 10 RS5 provides new performance features for UI Automation including event coalescing and connection recovery. # Enable all of these where available. if isinstance(self.clientObject,IUIAutomation6): self.clientObject.CoalesceEvents=CoalesceEventsOptions_Enabled self.clientObject.ConnectionRecoveryBehavior=ConnectionRecoveryBehaviorOptions_Enabled log.info("UIAutomation: %s"%self.clientObject.__class__.__mro__[1].__name__) self.windowTreeWalker=self.clientObject.createTreeWalker(self.clientObject.CreateNotCondition(self.clientObject.CreatePropertyCondition(UIA_NativeWindowHandlePropertyId,0))) self.windowCacheRequest=self.clientObject.CreateCacheRequest() self.windowCacheRequest.AddProperty(UIA_NativeWindowHandlePropertyId) self.UIAWindowHandleCache={} self.baseTreeWalker=self.clientObject.RawViewWalker self.baseCacheRequest=self.windowCacheRequest.Clone() import UIAHandler self.ItemIndex_PropertyId=NVDAHelper.localLib.registerUIAProperty(byref(ItemIndex_Property_GUID),u"ItemIndex",1) self.ItemCount_PropertyId=NVDAHelper.localLib.registerUIAProperty(byref(ItemCount_Property_GUID),u"ItemCount",1) for propertyId in (UIA_FrameworkIdPropertyId,UIA_AutomationIdPropertyId,UIA_ClassNamePropertyId,UIA_ControlTypePropertyId,UIA_ProviderDescriptionPropertyId,UIA_ProcessIdPropertyId,UIA_IsTextPatternAvailablePropertyId,UIA_IsContentElementPropertyId,UIA_IsControlElementPropertyId): self.baseCacheRequest.addProperty(propertyId) self.baseCacheRequest.addPattern(UIA_TextPatternId) self.rootElement=self.clientObject.getRootElementBuildCache(self.baseCacheRequest) self.reservedNotSupportedValue=self.clientObject.ReservedNotSupportedValue self.ReservedMixedAttributeValue=self.clientObject.ReservedMixedAttributeValue self.clientObject.AddFocusChangedEventHandler(self.baseCacheRequest,self) self.clientObject.AddPropertyChangedEventHandler(self.rootElement,TreeScope_Subtree,self.baseCacheRequest,self,UIAPropertyIdsToNVDAEventNames.keys()) for x in UIAEventIdsToNVDAEventNames.iterkeys(): self.clientObject.addAutomationEventHandler(x,self.rootElement,TreeScope_Subtree,self.baseCacheRequest,self) # #7984: add support for notification event (IUIAutomation5, part of Windows 10 build 16299 and later). if isinstance(self.clientObject, IUIAutomation5): self.clientObject.AddNotificationEventHandler(self.rootElement,TreeScope_Subtree,self.baseCacheRequest,self) except Exception as e: self.MTAThreadInitException=e finally: self.MTAThreadInitEvent.set() self.MTAThreadStopEvent.wait() self.clientObject.RemoveAllEventHandlers() def IUIAutomationEventHandler_HandleAutomationEvent(self,sender,eventID): if not self.MTAThreadInitEvent.isSet(): # UIAHandler hasn't finished initialising yet, so just ignore this event. return if eventID==UIA_MenuOpenedEventId and eventHandler.isPendingEvents("gainFocus"): # We don't need the menuOpened event if focus has been fired, # as focus should be more correct. return NVDAEventName=UIAEventIdsToNVDAEventNames.get(eventID,None) if not NVDAEventName: return if not self.isNativeUIAElement(sender): return window=self.getNearestWindowHandle(sender) if window and not eventHandler.shouldAcceptEvent(NVDAEventName,windowHandle=window): return import NVDAObjects.UIA obj=NVDAObjects.UIA.UIA(UIAElement=sender) if ( not obj or (NVDAEventName=="gainFocus" and not obj.shouldAllowUIAFocusEvent) or (NVDAEventName=="liveRegionChange" and not obj._shouldAllowUIALiveRegionChangeEvent) ): return focus=api.getFocusObject() if obj==focus: obj=focus eventHandler.queueEvent(NVDAEventName,obj) def IUIAutomationFocusChangedEventHandler_HandleFocusChangedEvent(self,sender): if not self.MTAThreadInitEvent.isSet(): # UIAHandler hasn't finished initialising yet, so just ignore this event. return if not self.isNativeUIAElement(sender): return import NVDAObjects.UIA if isinstance(eventHandler.lastQueuedFocusObject,NVDAObjects.UIA.UIA): lastFocus=eventHandler.lastQueuedFocusObject.UIAElement # Ignore duplicate focus events. # It seems that it is possible for compareElements to return True, even though the objects are different. # Therefore, don't ignore the event if the last focus object has lost its hasKeyboardFocus state. if self.clientObject.compareElements(sender,lastFocus) and lastFocus.currentHasKeyboardFocus: return window=self.getNearestWindowHandle(sender) if window and not eventHandler.shouldAcceptEvent("gainFocus",windowHandle=window): return obj=NVDAObjects.UIA.UIA(UIAElement=sender) if not obj or not obj.shouldAllowUIAFocusEvent: return eventHandler.queueEvent("gainFocus",obj) def IUIAutomationPropertyChangedEventHandler_HandlePropertyChangedEvent(self,sender,propertyId,newValue): # #3867: For now manually force this VARIANT type to empty to get around a nasty double free in comtypes/ctypes. # We also don't use the value in this callback. newValue.vt=VT_EMPTY if not self.MTAThreadInitEvent.isSet(): # UIAHandler hasn't finished initialising yet, so just ignore this event. return NVDAEventName=UIAPropertyIdsToNVDAEventNames.get(propertyId,None) if not NVDAEventName: return if not self.isNativeUIAElement(sender): return window=self.getNearestWindowHandle(sender) if window and not eventHandler.shouldAcceptEvent(NVDAEventName,windowHandle=window): return import NVDAObjects.UIA obj=NVDAObjects.UIA.UIA(UIAElement=sender) if not obj: return focus=api.getFocusObject() if obj==focus: obj=focus eventHandler.queueEvent(NVDAEventName,obj) def IUIAutomationNotificationEventHandler_HandleNotificationEvent(self,sender,NotificationKind,NotificationProcessing,displayString,activityId): if not self.MTAThreadInitEvent.isSet(): # UIAHandler hasn't finished initialising yet, so just ignore this event. return import NVDAObjects.UIA obj=NVDAObjects.UIA.UIA(UIAElement=sender) if not obj: # Sometimes notification events can be fired on a UIAElement that has no windowHandle and does not connect through parents back to the desktop. # There is nothing we can do with these. return eventHandler.queueEvent("UIA_notification",obj, notificationKind=NotificationKind, notificationProcessing=NotificationProcessing, displayString=displayString, activityId=activityId) def _isUIAWindowHelper(self,hwnd): # UIA in NVDA's process freezes in Windows 7 and below processID=winUser.getWindowThreadProcessID(hwnd)[0] if windll.kernel32.GetCurrentProcessId()==processID: return False import NVDAObjects.window windowClass=NVDAObjects.window.Window.normalizeWindowClassName(winUser.getClassName(hwnd)) # For certain window classes, we always want to use UIA. if windowClass in goodUIAWindowClassNames: return True # allow the appModule for the window to also choose if this window is good # An appModule should be able to override bad UIA class names as prescribed by core appModule=appModuleHandler.getAppModuleFromProcessID(processID) if appModule and appModule.isGoodUIAWindow(hwnd): return True # There are certain window classes that just had bad UIA implementations if windowClass in badUIAWindowClassNames: return False if windowClass=="NetUIHWND": parentHwnd=winUser.getAncestor(hwnd,winUser.GA_ROOT) # #2816: Outlook 2010 auto complete does not fire enough UIA events, IAccessible is better. # #4056: Combo boxes in Office 2010 Options dialogs don't expose a name via UIA, but do via MSAA. if winUser.getClassName(parentHwnd) in {"Net UI Tool Window","NUIDialog"}: return False # allow the appModule for the window to also choose if this window is bad if appModule and appModule.isBadUIAWindow(hwnd): return False # Ask the window if it supports UIA natively res=windll.UIAutomationCore.UiaHasServerSideProvider(hwnd) if res: # the window does support UIA natively, but # Microsoft Word should not use UIA unless we can't inject or the user explicitly chose to use UIA with Microsoft word if windowClass=="_WwG" and not (config.conf['UIA']['useInMSWordWhenAvailable'] or not appModule.helperLocalBindingHandle): return False return bool(res) def isUIAWindow(self,hwnd): now=time.time() v=self.UIAWindowHandleCache.get(hwnd,None) if not v or (now-v[1])>0.5: v=self._isUIAWindowHelper(hwnd),now self.UIAWindowHandleCache[hwnd]=v return v[0] def getNearestWindowHandle(self,UIAElement): if hasattr(UIAElement,"_nearestWindowHandle"): # Called previously. Use cached result. return UIAElement._nearestWindowHandle try: processID=UIAElement.cachedProcessID except COMError: return None appModule=appModuleHandler.getAppModuleFromProcessID(processID) # WDAG (Windows Defender application Guard) UIA elements should be treated as being from a remote machine, and therefore their window handles are completely invalid on this machine. # Therefore, jump all the way up to the root of the WDAG process and use that window handle as it is local to this machine. if appModule.appName==WDAG_PROCESS_NAME: condition=UIAUtils.createUIAMultiPropertyCondition({UIA_ClassNamePropertyId:[u'ApplicationFrameWindow',u'CabinetWClass']}) walker=self.clientObject.createTreeWalker(condition) else: # Not WDAG, just walk up to the nearest valid windowHandle walker=self.windowTreeWalker try: new=walker.NormalizeElementBuildCache(UIAElement,self.windowCacheRequest) except COMError: return None try: window=new.cachedNativeWindowHandle except COMError: window=None # Cache for future use to improve performance. UIAElement._nearestWindowHandle=window return window def isNativeUIAElement(self,UIAElement): #Due to issues dealing with UIA elements coming from the same process, we do not class these UIA elements as usable. #It seems to be safe enough to retreave the cached processID, but using tree walkers or fetching other properties causes a freeze. try: processID=UIAElement.cachedProcessId except COMError: return False if processID==windll.kernel32.GetCurrentProcessId(): return False # Whether this is a native element depends on whether its window natively supports UIA. windowHandle=self.getNearestWindowHandle(UIAElement) if windowHandle: if self.isUIAWindow(windowHandle): return True if winUser.getClassName(windowHandle)=="DirectUIHWND" and "IEFRAME.dll" in UIAElement.cachedProviderDescription and UIAElement.currentClassName in ("DownloadBox", "accessiblebutton", "DUIToolbarButton", "PushButton"): # This is the IE 9 downloads list. # #3354: UiaHasServerSideProvider returns false for the IE 9 downloads list window, # so we'd normally use MSAA for this control. # However, its MSAA implementation is broken (fires invalid events) if UIA is initialised, # whereas its UIA implementation works correctly. # Therefore, we must use UIA here. return True return False
46.159722
284
0.7967
from ctypes import * from ctypes.wintypes import * import comtypes.client from comtypes.automation import VT_EMPTY from comtypes import * import weakref import threading import time import config import api import appModuleHandler import queueHandler import controlTypes import NVDAHelper import winKernel import winUser import eventHandler from logHandler import log import UIAUtils from comtypes.gen.UIAutomationClient import * ItemIndex_Property_GUID=GUID("{92A053DA-2969-4021-BF27-514CFC2E4A69}") ItemCount_Property_GUID=GUID("{ABBF5C45-5CCC-47b7-BB4E-87CB87BBD162}") HorizontalTextAlignment_Left=0 HorizontalTextAlignment_Centered=1 HorizontalTextAlignment_Right=2 HorizontalTextAlignment_Justified=3 WDAG_PROCESS_NAME=u'hvsirdpclient' goodUIAWindowClassNames=[ 'RAIL_WINDOW', ] badUIAWindowClassNames=[ "SysTreeView32", "WuDuiListView", "ComboBox", "msctls_progress32", "Edit", "CommonPlacesWrapperWndClass", "SysMonthCal32", "SUPERGRID", #Outlook 2010 message list "RichEdit", "RichEdit20", "RICHEDIT50W", "SysListView32", "EXCEL7", "Button", # #7497: Windows 10 Fall Creators Update has an incomplete UIA implementation for console windows, therefore for now we should ignore it. # It does not implement caret/selection, and probably has no new text events. "ConsoleWindowClass", ] # #8405: used to detect UIA dialogs prior to Windows 10 RS5. UIADialogClassNames=[ "#32770", "NUIDialog", "Credential Dialog Xaml Host", # UAC dialog in Anniversary Update and later "Shell_Dialog", "Shell_Flyout", "Shell_SystemDialog", # Various dialogs in Windows 10 Settings app ] NVDAUnitsToUIAUnits={ "character":TextUnit_Character, "word":TextUnit_Word, "line":TextUnit_Line, "paragraph":TextUnit_Paragraph, "readingChunk":TextUnit_Line, } UIAControlTypesToNVDARoles={ UIA_ButtonControlTypeId:controlTypes.ROLE_BUTTON, UIA_CalendarControlTypeId:controlTypes.ROLE_CALENDAR, UIA_CheckBoxControlTypeId:controlTypes.ROLE_CHECKBOX, UIA_ComboBoxControlTypeId:controlTypes.ROLE_COMBOBOX, UIA_EditControlTypeId:controlTypes.ROLE_EDITABLETEXT, UIA_HyperlinkControlTypeId:controlTypes.ROLE_LINK, UIA_ImageControlTypeId:controlTypes.ROLE_GRAPHIC, UIA_ListItemControlTypeId:controlTypes.ROLE_LISTITEM, UIA_ListControlTypeId:controlTypes.ROLE_LIST, UIA_MenuControlTypeId:controlTypes.ROLE_POPUPMENU, UIA_MenuBarControlTypeId:controlTypes.ROLE_MENUBAR, UIA_MenuItemControlTypeId:controlTypes.ROLE_MENUITEM, UIA_ProgressBarControlTypeId:controlTypes.ROLE_PROGRESSBAR, UIA_RadioButtonControlTypeId:controlTypes.ROLE_RADIOBUTTON, UIA_ScrollBarControlTypeId:controlTypes.ROLE_SCROLLBAR, UIA_SliderControlTypeId:controlTypes.ROLE_SLIDER, UIA_SpinnerControlTypeId:controlTypes.ROLE_SPINBUTTON, UIA_StatusBarControlTypeId:controlTypes.ROLE_STATUSBAR, UIA_TabControlTypeId:controlTypes.ROLE_TABCONTROL, UIA_TabItemControlTypeId:controlTypes.ROLE_TAB, UIA_TextControlTypeId:controlTypes.ROLE_STATICTEXT, UIA_ToolBarControlTypeId:controlTypes.ROLE_TOOLBAR, UIA_ToolTipControlTypeId:controlTypes.ROLE_TOOLTIP, UIA_TreeControlTypeId:controlTypes.ROLE_TREEVIEW, UIA_TreeItemControlTypeId:controlTypes.ROLE_TREEVIEWITEM, UIA_CustomControlTypeId:controlTypes.ROLE_UNKNOWN, UIA_GroupControlTypeId:controlTypes.ROLE_GROUPING, UIA_ThumbControlTypeId:controlTypes.ROLE_THUMB, UIA_DataGridControlTypeId:controlTypes.ROLE_DATAGRID, UIA_DataItemControlTypeId:controlTypes.ROLE_DATAITEM, UIA_DocumentControlTypeId:controlTypes.ROLE_DOCUMENT, UIA_SplitButtonControlTypeId:controlTypes.ROLE_SPLITBUTTON, UIA_WindowControlTypeId:controlTypes.ROLE_WINDOW, UIA_PaneControlTypeId:controlTypes.ROLE_PANE, UIA_HeaderControlTypeId:controlTypes.ROLE_HEADER, UIA_HeaderItemControlTypeId:controlTypes.ROLE_HEADERITEM, UIA_TableControlTypeId:controlTypes.ROLE_TABLE, UIA_TitleBarControlTypeId:controlTypes.ROLE_TITLEBAR, UIA_SeparatorControlTypeId:controlTypes.ROLE_SEPARATOR, } UIAPropertyIdsToNVDAEventNames={ UIA_NamePropertyId:"nameChange", UIA_HelpTextPropertyId:"descriptionChange", UIA_ExpandCollapseExpandCollapseStatePropertyId:"stateChange", UIA_ToggleToggleStatePropertyId:"stateChange", UIA_IsEnabledPropertyId:"stateChange", UIA_ValueValuePropertyId:"valueChange", UIA_RangeValueValuePropertyId:"valueChange", UIA_ControllerForPropertyId:"UIA_controllerFor", } UIAEventIdsToNVDAEventNames={ UIA_LiveRegionChangedEventId:"liveRegionChange", #UIA_Text_TextChangedEventId:"textChanged", UIA_SelectionItem_ElementSelectedEventId:"UIA_elementSelected", UIA_MenuOpenedEventId:"gainFocus", UIA_SelectionItem_ElementAddedToSelectionEventId:"stateChange", UIA_SelectionItem_ElementRemovedFromSelectionEventId:"stateChange", #UIA_MenuModeEndEventId:"menuModeEnd", #UIA_Text_TextSelectionChangedEventId:"caret", UIA_ToolTipOpenedEventId:"UIA_toolTipOpened", #UIA_AsyncContentLoadedEventId:"documentLoadComplete", #UIA_ToolTipClosedEventId:"hide", UIA_Window_WindowOpenedEventId:"UIA_window_windowOpen", UIA_SystemAlertEventId:"UIA_systemAlert", } class UIAHandler(COMObject): _com_interfaces_=[IUIAutomationEventHandler,IUIAutomationFocusChangedEventHandler,IUIAutomationPropertyChangedEventHandler,IUIAutomationNotificationEventHandler] def __init__(self): super(UIAHandler,self).__init__() self.MTAThreadInitEvent=threading.Event() self.MTAThreadStopEvent=threading.Event() self.MTAThreadInitException=None self.MTAThread=threading.Thread(target=self.MTAThreadFunc) self.MTAThread.daemon=True self.MTAThread.start() self.MTAThreadInitEvent.wait(2) if self.MTAThreadInitException: raise self.MTAThreadInitException def terminate(self): MTAThreadHandle=HANDLE(windll.kernel32.OpenThread(winKernel.SYNCHRONIZE,False,self.MTAThread.ident)) self.MTAThreadStopEvent.set() #Wait for the MTA thread to die (while still message pumping) if windll.user32.MsgWaitForMultipleObjects(1,byref(MTAThreadHandle),False,200,0)!=0: log.debugWarning("Timeout or error while waiting for UIAHandler MTA thread") windll.kernel32.CloseHandle(MTAThreadHandle) del self.MTAThread def MTAThreadFunc(self): try: oledll.ole32.CoInitializeEx(None,comtypes.COINIT_MULTITHREADED) isUIA8=False try: self.clientObject=CoCreateInstance(CUIAutomation8._reg_clsid_,interface=IUIAutomation,clsctx=CLSCTX_INPROC_SERVER) isUIA8=True except (COMError,WindowsError,NameError): self.clientObject=CoCreateInstance(CUIAutomation._reg_clsid_,interface=IUIAutomation,clsctx=CLSCTX_INPROC_SERVER) # #7345: Instruct UIA to never map MSAA winEvents to UIA propertyChange events. # These events are not needed by NVDA, and they can cause the UI Automation client library to become unresponsive if an application firing winEvents has a slow message pump. pfm=self.clientObject.proxyFactoryMapping for index in xrange(pfm.count): e=pfm.getEntry(index) for propertyID in UIAPropertyIdsToNVDAEventNames.keys(): # Check if this proxy has mapped any winEvents to the UIA propertyChange event for this property ID try: oldWinEvents=e.getWinEventsForAutomationEvent(UIA_AutomationPropertyChangedEventId,propertyID) except IndexError: # comtypes does not seem to correctly handle a returned empty SAFEARRAY, raising IndexError oldWinEvents=None if oldWinEvents: # As winEvents were mapped, replace them with an empty list e.setWinEventsForAutomationEvent(UIA_AutomationPropertyChangedEventId,propertyID,[]) # Changes to an enty are not automatically picked up. # Therefore remove the entry and re-insert it. pfm.removeEntry(index) pfm.insertEntry(index,e) if isUIA8: # #8009: use appropriate interface based on highest supported interface. # #8338: made easier by traversing interfaces supported on Windows 8 and later in reverse. for interface in reversed(CUIAutomation8._com_interfaces_): try: self.clientObject=self.clientObject.QueryInterface(interface) break except COMError: pass # Windows 10 RS5 provides new performance features for UI Automation including event coalescing and connection recovery. # Enable all of these where available. if isinstance(self.clientObject,IUIAutomation6): self.clientObject.CoalesceEvents=CoalesceEventsOptions_Enabled self.clientObject.ConnectionRecoveryBehavior=ConnectionRecoveryBehaviorOptions_Enabled log.info("UIAutomation: %s"%self.clientObject.__class__.__mro__[1].__name__) self.windowTreeWalker=self.clientObject.createTreeWalker(self.clientObject.CreateNotCondition(self.clientObject.CreatePropertyCondition(UIA_NativeWindowHandlePropertyId,0))) self.windowCacheRequest=self.clientObject.CreateCacheRequest() self.windowCacheRequest.AddProperty(UIA_NativeWindowHandlePropertyId) self.UIAWindowHandleCache={} self.baseTreeWalker=self.clientObject.RawViewWalker self.baseCacheRequest=self.windowCacheRequest.Clone() import UIAHandler self.ItemIndex_PropertyId=NVDAHelper.localLib.registerUIAProperty(byref(ItemIndex_Property_GUID),u"ItemIndex",1) self.ItemCount_PropertyId=NVDAHelper.localLib.registerUIAProperty(byref(ItemCount_Property_GUID),u"ItemCount",1) for propertyId in (UIA_FrameworkIdPropertyId,UIA_AutomationIdPropertyId,UIA_ClassNamePropertyId,UIA_ControlTypePropertyId,UIA_ProviderDescriptionPropertyId,UIA_ProcessIdPropertyId,UIA_IsTextPatternAvailablePropertyId,UIA_IsContentElementPropertyId,UIA_IsControlElementPropertyId): self.baseCacheRequest.addProperty(propertyId) self.baseCacheRequest.addPattern(UIA_TextPatternId) self.rootElement=self.clientObject.getRootElementBuildCache(self.baseCacheRequest) self.reservedNotSupportedValue=self.clientObject.ReservedNotSupportedValue self.ReservedMixedAttributeValue=self.clientObject.ReservedMixedAttributeValue self.clientObject.AddFocusChangedEventHandler(self.baseCacheRequest,self) self.clientObject.AddPropertyChangedEventHandler(self.rootElement,TreeScope_Subtree,self.baseCacheRequest,self,UIAPropertyIdsToNVDAEventNames.keys()) for x in UIAEventIdsToNVDAEventNames.iterkeys(): self.clientObject.addAutomationEventHandler(x,self.rootElement,TreeScope_Subtree,self.baseCacheRequest,self) # #7984: add support for notification event (IUIAutomation5, part of Windows 10 build 16299 and later). if isinstance(self.clientObject, IUIAutomation5): self.clientObject.AddNotificationEventHandler(self.rootElement,TreeScope_Subtree,self.baseCacheRequest,self) except Exception as e: self.MTAThreadInitException=e finally: self.MTAThreadInitEvent.set() self.MTAThreadStopEvent.wait() self.clientObject.RemoveAllEventHandlers() def IUIAutomationEventHandler_HandleAutomationEvent(self,sender,eventID): if not self.MTAThreadInitEvent.isSet(): # UIAHandler hasn't finished initialising yet, so just ignore this event. return if eventID==UIA_MenuOpenedEventId and eventHandler.isPendingEvents("gainFocus"): # as focus should be more correct. return NVDAEventName=UIAEventIdsToNVDAEventNames.get(eventID,None) if not NVDAEventName: return if not self.isNativeUIAElement(sender): return window=self.getNearestWindowHandle(sender) if window and not eventHandler.shouldAcceptEvent(NVDAEventName,windowHandle=window): return import NVDAObjects.UIA obj=NVDAObjects.UIA.UIA(UIAElement=sender) if ( not obj or (NVDAEventName=="gainFocus" and not obj.shouldAllowUIAFocusEvent) or (NVDAEventName=="liveRegionChange" and not obj._shouldAllowUIALiveRegionChangeEvent) ): return focus=api.getFocusObject() if obj==focus: obj=focus eventHandler.queueEvent(NVDAEventName,obj) def IUIAutomationFocusChangedEventHandler_HandleFocusChangedEvent(self,sender): if not self.MTAThreadInitEvent.isSet(): # UIAHandler hasn't finished initialising yet, so just ignore this event. return if not self.isNativeUIAElement(sender): return import NVDAObjects.UIA if isinstance(eventHandler.lastQueuedFocusObject,NVDAObjects.UIA.UIA): lastFocus=eventHandler.lastQueuedFocusObject.UIAElement if self.clientObject.compareElements(sender,lastFocus) and lastFocus.currentHasKeyboardFocus: return window=self.getNearestWindowHandle(sender) if window and not eventHandler.shouldAcceptEvent("gainFocus",windowHandle=window): return obj=NVDAObjects.UIA.UIA(UIAElement=sender) if not obj or not obj.shouldAllowUIAFocusEvent: return eventHandler.queueEvent("gainFocus",obj) def IUIAutomationPropertyChangedEventHandler_HandlePropertyChangedEvent(self,sender,propertyId,newValue): # #3867: For now manually force this VARIANT type to empty to get around a nasty double free in comtypes/ctypes. # We also don't use the value in this callback. newValue.vt=VT_EMPTY if not self.MTAThreadInitEvent.isSet(): return NVDAEventName=UIAPropertyIdsToNVDAEventNames.get(propertyId,None) if not NVDAEventName: return if not self.isNativeUIAElement(sender): return window=self.getNearestWindowHandle(sender) if window and not eventHandler.shouldAcceptEvent(NVDAEventName,windowHandle=window): return import NVDAObjects.UIA obj=NVDAObjects.UIA.UIA(UIAElement=sender) if not obj: return focus=api.getFocusObject() if obj==focus: obj=focus eventHandler.queueEvent(NVDAEventName,obj) def IUIAutomationNotificationEventHandler_HandleNotificationEvent(self,sender,NotificationKind,NotificationProcessing,displayString,activityId): if not self.MTAThreadInitEvent.isSet(): # UIAHandler hasn't finished initialising yet, so just ignore this event. return import NVDAObjects.UIA obj=NVDAObjects.UIA.UIA(UIAElement=sender) if not obj: return eventHandler.queueEvent("UIA_notification",obj, notificationKind=NotificationKind, notificationProcessing=NotificationProcessing, displayString=displayString, activityId=activityId) def _isUIAWindowHelper(self,hwnd): processID=winUser.getWindowThreadProcessID(hwnd)[0] if windll.kernel32.GetCurrentProcessId()==processID: return False import NVDAObjects.window windowClass=NVDAObjects.window.Window.normalizeWindowClassName(winUser.getClassName(hwnd)) # For certain window classes, we always want to use UIA. if windowClass in goodUIAWindowClassNames: return True # allow the appModule for the window to also choose if this window is good # An appModule should be able to override bad UIA class names as prescribed by core appModule=appModuleHandler.getAppModuleFromProcessID(processID) if appModule and appModule.isGoodUIAWindow(hwnd): return True # There are certain window classes that just had bad UIA implementations if windowClass in badUIAWindowClassNames: return False if windowClass=="NetUIHWND": parentHwnd=winUser.getAncestor(hwnd,winUser.GA_ROOT) # #2816: Outlook 2010 auto complete does not fire enough UIA events, IAccessible is better. # #4056: Combo boxes in Office 2010 Options dialogs don't expose a name via UIA, but do via MSAA. if winUser.getClassName(parentHwnd) in {"Net UI Tool Window","NUIDialog"}: return False if appModule and appModule.isBadUIAWindow(hwnd): return False res=windll.UIAutomationCore.UiaHasServerSideProvider(hwnd) if res: if windowClass=="_WwG" and not (config.conf['UIA']['useInMSWordWhenAvailable'] or not appModule.helperLocalBindingHandle): return False return bool(res) def isUIAWindow(self,hwnd): now=time.time() v=self.UIAWindowHandleCache.get(hwnd,None) if not v or (now-v[1])>0.5: v=self._isUIAWindowHelper(hwnd),now self.UIAWindowHandleCache[hwnd]=v return v[0] def getNearestWindowHandle(self,UIAElement): if hasattr(UIAElement,"_nearestWindowHandle"): # Called previously. Use cached result. return UIAElement._nearestWindowHandle try: processID=UIAElement.cachedProcessID except COMError: return None appModule=appModuleHandler.getAppModuleFromProcessID(processID) # WDAG (Windows Defender application Guard) UIA elements should be treated as being from a remote machine, and therefore their window handles are completely invalid on this machine. # Therefore, jump all the way up to the root of the WDAG process and use that window handle as it is local to this machine. if appModule.appName==WDAG_PROCESS_NAME: condition=UIAUtils.createUIAMultiPropertyCondition({UIA_ClassNamePropertyId:[u'ApplicationFrameWindow',u'CabinetWClass']}) walker=self.clientObject.createTreeWalker(condition) else: # Not WDAG, just walk up to the nearest valid windowHandle walker=self.windowTreeWalker try: new=walker.NormalizeElementBuildCache(UIAElement,self.windowCacheRequest) except COMError: return None try: window=new.cachedNativeWindowHandle except COMError: window=None # Cache for future use to improve performance. UIAElement._nearestWindowHandle=window return window def isNativeUIAElement(self,UIAElement): #Due to issues dealing with UIA elements coming from the same process, we do not class these UIA elements as usable. #It seems to be safe enough to retreave the cached processID, but using tree walkers or fetching other properties causes a freeze. try: processID=UIAElement.cachedProcessId except COMError: return False if processID==windll.kernel32.GetCurrentProcessId(): return False # Whether this is a native element depends on whether its window natively supports UIA. windowHandle=self.getNearestWindowHandle(UIAElement) if windowHandle: if self.isUIAWindow(windowHandle): return True if winUser.getClassName(windowHandle)=="DirectUIHWND" and "IEFRAME.dll" in UIAElement.cachedProviderDescription and UIAElement.currentClassName in ("DownloadBox", "accessiblebutton", "DUIToolbarButton", "PushButton"): # This is the IE 9 downloads list. # #3354: UiaHasServerSideProvider returns false for the IE 9 downloads list window, # so we'd normally use MSAA for this control. return True return False
true
true
1c33f4adf603c76e12800fda43481ab5d8f5e142
26,319
py
Python
ier_model/run_et.py
diegoolano/biomedical_interpretable_entity_representations
3c35f02ee8dd7ee0f2a23b0014e4b112beab6461
[ "MIT" ]
2
2021-09-24T08:54:33.000Z
2021-11-15T05:15:52.000Z
ier_model/run_et.py
diegoolano/biomedical_interpretable_entity_representations
3c35f02ee8dd7ee0f2a23b0014e4b112beab6461
[ "MIT" ]
null
null
null
ier_model/run_et.py
diegoolano/biomedical_interpretable_entity_representations
3c35f02ee8dd7ee0f2a23b0014e4b112beab6461
[ "MIT" ]
2
2021-07-05T20:19:01.000Z
2021-08-01T01:01:41.000Z
#!/usr/bin/env python3 import argparse import gc import json import numpy as np import pickle import random import time import torch import torch.nn as nn from tqdm import tqdm from transformers import AdamW, get_linear_schedule_with_warmup import transformer_constant import transformer_data_utils from transformer_data_utils import to_torch from models import TransformerModel """ Args """ parser = argparse.ArgumentParser() parser.add_argument("-model_id", help="Identifier for model") parser.add_argument('-device', type=int, default=0, help='CUDA device') parser.add_argument("-n_gpu", help="Number of GPUs.", type=int, default=1) parser.add_argument("-mode", help="Whether to train or test", default="train", choices=["train", "val", "test"]) parser.add_argument("-local_rank", type=int, default=-1, help="For distributed training: local_rank") # Data parser.add_argument("-train_data", help="Train data", default="train/wiki_et_zeroshot_60k_ex_random/train_*.json") parser.add_argument("-dev_data", help="Dev data", default="validation/dev_wiki_et_zeroshot_60k_ex_random_999.json") parser.add_argument("-eval_data", help="Test data", default="") parser.add_argument("-goal", help="category vocab size.", default="60k", choices=["medwiki","60k", "ufet"]) parser.add_argument("-seed", help="Pytorch random Seed", default=113) parser.add_argument("-context_window_size", help="Left and right context size.", default=100) # learning parser.add_argument("-num_epoch", help="The number of epoch", default=5000, type=int) parser.add_argument("-per_gpu_train_batch_size", help="The batch size per GPU", default=8, type=int) parser.add_argument("-per_gpu_eval_batch_size", help="The batch size per GPU", default=8, type=int) parser.add_argument("-learning_rate_enc", help="BERT: start learning rate", default=2e-5, type=float) parser.add_argument("-learning_rate_cls", help="BERT: start learning rate", default=1e-3, type=float) parser.add_argument("-adam_epsilon_enc", default=1e-8, type=float, help="Epsilon for Adam optimizer.") parser.add_argument("-adam_epsilon_cls", default=1e-8, type=float, help="Epsilon for Adam optimizer.") parser.add_argument("-hidden_dropout_prob", help="Dropout rate", default=.1, type=float) parser.add_argument("-warmup_steps", default=0, type=int, help="Linear warmup over warmup_steps.") parser.add_argument( "-gradient_accumulation_steps", type=int, default=1, help="Number of updates steps to accumulate before performing a backward/update pass.", ) # Model parser.add_argument( "-model_type", default="bert-base-uncased", choices=[ "bert-base-uncased", "bert-large-uncased", "bert-large-uncased-whole-word-masking", "roberta-base", "roberta-large", "allenai/biomed_roberta_base", "monologg/biobert_v1.1_pubmed", "allenai/scibert_scivocab_uncased", "microsoft/BiomedNLP-PubMedBERT-base-uncased-abstract-fulltext" ] ) parser.add_argument("-threshold", help="threshold", default=0.5, type=float) parser.add_argument("-avg_pooling", help="Averaging all hidden states instead of using [CLS].", action='store_true') # Save / log related parser.add_argument("-save_period", help="How often to save", default=1000, type=int) parser.add_argument("-eval_period", help="How often to run dev", default=500, type=int) parser.add_argument("-log_period", help="How often to save", default=1000, type=int) parser.add_argument("-eval_after", help="How often to run dev", default=10, type=int) parser.add_argument("-load", help="Load existing model.", action='store_true') parser.add_argument("-reload_model_name", help="") parser.add_argument("-reload_model_name_desc", help="") # Extra param So we can run different data for same goal parser.add_argument("-env", help="data sub for medwiki", default="", choices=["yasu", "0720_3k_full","0720_3k_full_orig", "0720_3k_drugs","0720_600k_full","0720_600k_full_orig","0720_600k_drugs"]) parser.add_argument("-examples_limit", help="How many examples to do eval on in def _val", default=1000, type=int) """ Utils """ SIGMOID = nn.Sigmoid() def set_seed(args): random.seed(args.seed) np.random.seed(args.seed) torch.manual_seed(args.seed) if args.n_gpu > 0: torch.cuda.manual_seed_all(args.seed) def get_data_gen(dataname, mode, args, tokenizer): data_path = transformer_constant.get(args.env, 'FILE_ROOT') + dataname print("load data path", data_path, "with args.env", args.env) dataset = transformer_data_utils.DatasetLoader(data_path, args, tokenizer) if mode == 'train': data_gen = dataset.get_batch(args.train_batch_size, args.max_position_embeddings, args.num_epoch, eval_data=False) else: # test mode data_gen = dataset.get_batch(args.eval_batch_size, args.max_position_embeddings, 1, eval_data=True) return data_gen def get_all_datasets(args, tokenizer): train_gen_list = [] if args.mode in ['train']: if 'wiki_desc' in args.model_id: print("load wiki_desc",) train_gen_list.append(get_data_gen(transformer_constant.get(args.env,'WIKI_TRAIN_DATA'), 'train', args, tokenizer)) else: train_gen_list.append(get_data_gen(transformer_constant.get(args.env,'TRAIN_DATA'), 'train', args, tokenizer)) #train_gen_list.append(get_data_gen(args.train_data, 'train', args, tokenizer)) return train_gen_list def get_datasets(data_lists, args, tokenizer): data_gen_list = [] for dataname, mode in data_lists: data_gen_list.append(get_data_gen(dataname, mode, args, tokenizer)) return data_gen_list def evaluate_data(batch_num, dev_fname, model, args, device): print("in evaluate data, batchnum", batch_num, dev_fname) #print(args) model.eval() dev_gen = get_data_gen(dev_fname, 'test', args, model.transformer_tokenizer) gold_pred = [] eval_loss = 0. total_ex_count = 0 #IMPORTANT since this takes so long sub sample for now 500 for batch in tqdm(dev_gen): if total_ex_count > 500: break total_ex_count += len(batch['targets']) try: inputs, targets = to_torch(batch, device) loss, output_logits = model(inputs, targets) except Exception as e: print("in Eval to torch error so continue: ",e ) continue output_index = get_output_index(output_logits, threshold=args.threshold) gold_pred += get_gold_pred_str(output_index, batch['targets'].data.cpu().clone(), args.goal, args.env) eval_loss += loss.clone().item() print("Gold Pred", len(gold_pred),gold_pred[0:4]) eval_str = get_eval_string(gold_pred) _, _, _, _, _, macro_f1 = macro(gold_pred) eval_loss_str = 'Eval loss: {0:.7f} at step {1:d}'.format(eval_loss, batch_num) print('==> EVAL: seen ' + repr(total_ex_count) + ' examples.') print(eval_loss_str) print(gold_pred[:3]) print('==> ' + eval_str) model.train() dev_gen = None return eval_loss, macro_f1 def f1(p, r): if r == 0.: return 0. return 2 * p * r / float(p + r) def macro(true_and_prediction): num_examples = len(true_and_prediction) p = 0. r = 0. pred_example_count = 0. pred_label_count = 0. gold_label_count = 0. for true_labels, predicted_labels in true_and_prediction: if predicted_labels: pred_example_count += 1 pred_label_count += len(predicted_labels) per_p = len(set(predicted_labels).intersection(set(true_labels))) / float(len(predicted_labels)) p += per_p if len(true_labels): gold_label_count += 1 per_r = len(set(predicted_labels).intersection(set(true_labels))) / float(len(true_labels)) r += per_r if pred_example_count > 0: precision = p / pred_example_count if gold_label_count > 0: recall = r / gold_label_count if pred_example_count == 0: print("In Macro: Pred Example Count == 0") avg_elem_per_pred = 0 else: avg_elem_per_pred = pred_label_count / pred_example_count return num_examples, pred_example_count, avg_elem_per_pred, precision, recall, f1(precision, recall) def micro(true_and_prediction): num_examples = len(true_and_prediction) num_predicted_labels = 0. num_true_labels = 0. num_correct_labels = 0. pred_example_count = 0. for true_labels, predicted_labels in true_and_prediction: if predicted_labels: pred_example_count += 1 num_predicted_labels += len(predicted_labels) num_true_labels += len(true_labels) num_correct_labels += len(set(predicted_labels).intersection(set(true_labels))) if pred_example_count == 0: return num_examples, 0, 0, 0, 0, 0 precision = num_correct_labels / num_predicted_labels recall = num_correct_labels / num_true_labels avg_elem_per_pred = num_predicted_labels / pred_example_count return num_examples, pred_example_count, avg_elem_per_pred, precision, recall, f1(precision, recall) def load_model(reload_model_name, save_dir, model_id, model, optimizer_enc=None, optimizer_cls=None, scheduler_enc=None, scheduler_cls=None): if reload_model_name: model_file_name = '{0:s}/{1:s}.pt'.format(save_dir, reload_model_name) else: model_file_name = '{0:s}/{1:s}.pt'.format(save_dir, model_id) print("Loading ", model_file_name) checkpoint = torch.load(model_file_name) model.load_state_dict(checkpoint['state_dict']) if optimizer_enc and optimizer_cls: # Continue training #if optimizer_enc and optimizer_cls and scheduler_enc and scheduler_cls: # Continue training optimizer_enc.load_state_dict(checkpoint['optimizer_enc']) optimizer_cls.load_state_dict(checkpoint['optimizer_cls']) else: # Test total_params = 0 # Log params for k in checkpoint['state_dict']: elem = checkpoint['state_dict'][k] param_s = 1 for size_dim in elem.size(): param_s = size_dim * param_s #print(k, elem.size()) total_params += param_s param_str = ('Number of total parameters..{0:d}'.format(total_params)) print(param_str) print('Loading model from ... {0:s}'.format(model_file_name)) def get_output_index(outputs, threshold=0.5): """ Given outputs from the decoder, generate prediction index. :param outputs: :return: """ pred_idx = [] outputs = SIGMOID(outputs).data.cpu().clone() for single_dist in outputs: single_dist = single_dist.numpy() arg_max_ind = np.argmax(single_dist) pred_id = [arg_max_ind] pred_id.extend( [i for i in range(len(single_dist)) if single_dist[i] > threshold and i != arg_max_ind]) pred_idx.append(pred_id) return pred_idx def get_gold_pred_str(pred_idx, gold, goal, env): """ Given predicted ids and gold ids, generate a list of (gold, pred) pairs of length batch_size. """ if goal == '60k': id2word_dict = transformer_constant.ID2ANS_DICT_60K elif goal == 'ufet': id2word_dict = transformer_constant.ID2ANS_DICT_UFET elif goal == 'medwiki': id2word_dict = transformer_constant.ID2ANS_MEDWIKI_DICT[env] else: print('ERROR: Invalid input...' + goal) raise gold_strs = [] for gold_i in gold: gold_strs.append([id2word_dict[i] for i in range(len(gold_i)) if gold_i[i] == 1]) pred_strs = [] for pred_idx1 in pred_idx: pred_strs.append([(id2word_dict[ind]) for ind in pred_idx1]) else: return list(zip(gold_strs, pred_strs)) def get_eval_string(true_prediction): """ Given a list of (gold, prediction)s, generate output string. """ count, pred_count, avg_pred_count, p, r, f1 = micro(true_prediction) _, _, _, ma_p, ma_r, ma_f1 = macro(true_prediction) output_str = "Eval: {0} {1} {2:.3f} P:{3:.3f} R:{4:.3f} F1:{5:.3f} Ma_P:{6:.3f} Ma_R:{7:.3f} Ma_F1:{8:.3f}".format( count, pred_count, avg_pred_count, p, r, f1, ma_p, ma_r, ma_f1) accuracy = sum([set(y) == set(yp) for y, yp in true_prediction]) * 1.0 / len(true_prediction) output_str += '\t Dev accuracy: {0:.1f}%'.format(accuracy * 100) return output_str """ Training """ def _train(args, model, device): args.train_batch_size = args.per_gpu_train_batch_size * max(1, args.n_gpu) args.eval_batch_size = args.per_gpu_train_batch_size * max(1, args.n_gpu) print('==> Loading data generator... ') train_gen_list = get_all_datasets(args, model.transformer_tokenizer) print('done. {} data gen(s)'.format(len(train_gen_list))) print('Model Type: {}'.format(args.model_type)) total_loss = 0. batch_num = 0 best_macro_f1 = 0. start_time = time.time() init_time = time.time() print('Total {} named params.'.format(len([n for n, p in model.named_parameters()]))) no_decay = ["bias", "LayerNorm.weight"] classifier_param_name = ["classifier.linear.weight"] encoder_parameters = [ { "params": [p for n, p in model.named_parameters() if not any(nd in n for nd in no_decay) and n not in classifier_param_name], "weight_decay": 0.0 #args.weight_decay, }, { "params": [p for n, p in model.named_parameters() if any(nd in n for nd in no_decay) and n not in classifier_param_name], "weight_decay": 0.0 }, ] classifier_parameters = [ { "params": [p for n, p in model.named_parameters() if n in classifier_param_name], "weight_decay": 0.0 }, ] print( 'Encoder {}, Classifier {}'.format( sum([len(p['params']) for p in encoder_parameters]), sum([len(p['params']) for p in classifier_parameters]) ) ) optimizer_enc = AdamW(encoder_parameters, lr=args.learning_rate_enc, eps=args.adam_epsilon_enc) optimizer_cls = AdamW(classifier_parameters, lr=args.learning_rate_cls, eps=args.adam_epsilon_cls) if args.n_gpu > 1: model = torch.nn.DataParallel(model) if args.load: load_model(args.reload_model_name, transformer_constant.get(args.env,'EXP_ROOT'), args.model_id, model, optimizer_enc, optimizer_cls) optimizer_enc.zero_grad() optimizer_cls.zero_grad() set_seed(args) global_train_sum, global_train_n = 0, 0 global_overlap_train_sum, global_overlap_train_n = 0, 0 while True: batch_num += 1 # single batch composed of all train signal passed by. for data_gen in train_gen_list: try: batch = next(data_gen) inputs, targets = to_torch(batch, device) except StopIteration: print('Done!') torch.save( { 'state_dict': model.state_dict(), 'optimizer_cls': optimizer_cls.state_dict(), 'optimizer_enc': optimizer_enc.state_dict(), 'args': args }, '{0:s}/{1:s}.pt'.format(transformer_constant.get(args.env,'EXP_ROOT'), args.model_id) ) return except Exception as e: print("To torch error so continue: ",e ) print("Batch num",batch_num) print(batch) print(inputs) print(targets) continue model.train() if args.model_type != "distilbert": inputs["token_type_ids"] = ( batch["token_type_ids"] if args.model_type in ["bert", "xlnet", "albert"] else None ) # XLM, DistilBERT, RoBERTa, and XLM-RoBERTa don't use segment_ids try: loss, output_logits = model(inputs, targets) except Exception as e: print("Error computing loss on batch_num: ", batch_num, e) #print("Inputs: ", inputs) <-- even printing this out gives an error #print("Targets: ", targets) # skip batch and try to figure out what happned continue inputs, targets = None, None if args.n_gpu > 1: loss = loss.mean() # mean() to average on multi-gpu parallel training if args.gradient_accumulation_steps > 1: loss = loss / args.gradient_accumulation_steps loss.backward() total_loss += loss.item() if batch_num % args.gradient_accumulation_steps == 0: optimizer_enc.step() optimizer_cls.step() optimizer_enc.zero_grad() optimizer_cls.zero_grad() if batch_num % args.log_period == 0 and batch_num > 0: gc.collect() cur_loss = float(1.0 * loss.clone().item()) elapsed = time.time() - start_time train_loss_str = ('|loss {0:3f} | at {1:d}step | @ {2:.2f} ms/batch'.format(cur_loss, batch_num, elapsed * 1000 / args.log_period)) start_time = time.time() print(train_loss_str) if batch_num % args.eval_period == 0 and batch_num > 0: output_index = get_output_index(output_logits, threshold=args.threshold) batch_targets_clone = batch['targets'].data.cpu().clone() gold_pred_train = get_gold_pred_str(output_index, batch_targets_clone, args.goal, args.env) #print("OUTPUT INDEX:",output_index[:4]) #print("TARGETS:", batch_targets_clone[:4].shape, type(batch_targets_clone), batch_targets_clone[:4]) #print(torch.nonzero(batch_targets_clone[:4])) print("1st ten preds (true cats, pred cats)", [(i,len(v[0]), len(v[1]), len(v[0])==len(v[1]), v[0], v[1]) for i,v in enumerate(gold_pred_train[:10])]) accuracy = sum([set(y) == set(yp) for y, yp in gold_pred_train]) * 1.0 / len(gold_pred_train) print('==> Train accuracy: {0:.1f}%'.format(accuracy * 100)) overlap_accuracy = sum([len(set(y).intersection(set(yp)))/len(yp) for y, yp in gold_pred_train]) * 1.0 / len(gold_pred_train) print('==> Train overlap accuracy: {0:.1f}%'.format(overlap_accuracy * 100)) global_train_sum += sum([set(y) == set(yp) for y, yp in gold_pred_train]) * 1.0 global_train_n += len(gold_pred_train) global_acc = global_train_sum / global_train_n print('==> Global Train accuracy: {0:.1f}%'.format(global_acc * 100)) global_overlap_train_sum += sum([len(set(y).intersection(set(yp)))/len(yp) for y, yp in gold_pred_train]) * 1.0 global_overlap_train_n += len(gold_pred_train) global_overlap_acc = global_overlap_train_sum / global_overlap_train_n print('==> Global Train overlap accuracy: {0:.1f}%'.format(global_overlap_acc * 100)) if batch_num % args.eval_period == 0 and batch_num > args.eval_after: # Evaluate Loss on the Turk Dev dataset. print('---- eval at step {0:d} ---'.format(batch_num)) if 'wiki_desc' in args.model_id: _, macro_f1 = evaluate_data(batch_num, transformer_constant.get(args.env,'WIKI_DEV_DATA'), model, args, device) else: _, macro_f1 = evaluate_data(batch_num, transformer_constant.get(args.env,'DEV_DATA'), model, args, device) if best_macro_f1 < macro_f1: best_macro_f1 = macro_f1 save_fname = '{0:s}/{1:s}_best.pt'.format(transformer_constant.get(args.env,'EXP_ROOT'), args.model_id) torch.save( { 'state_dict': model.state_dict(), 'optimizer_cls': optimizer_cls.state_dict(), 'optimizer_enc': optimizer_enc.state_dict(), 'args': args }, save_fname ) print( 'Total {0:.2f} minutes have passed, saving at {1:s} '.format((time.time() - init_time) / 60, save_fname)) #if batch_num % args.save_period == 0 and batch_num > 30000: if batch_num % args.save_period == 0 and batch_num >= args.eval_after: save_fname = '{0:s}/{1:s}_{2:d}.pt'.format(transformer_constant.get(args.env,'EXP_ROOT'), args.model_id, batch_num) torch.save( { 'state_dict': model.state_dict(), 'optimizer_cls': optimizer_cls.state_dict(), 'optimizer_enc': optimizer_enc.state_dict(), 'args': args }, save_fname ) print( 'Total {0:.2f} minutes have passed, saving at {1:s} '.format((time.time() - init_time) / 60, save_fname)) """ VAL """ def _val(args, model, device): examples_limit = args.examples_limit start_time = time.time() assert args.load dev_fname = transformer_constant.get(args.env,'DEV_DATA') args.eval_batch_size = args.per_gpu_train_batch_size * max(1, args.n_gpu) model.eval() load_model(args.reload_model_name, transformer_constant.get(args.env,'EXP_ROOT'), args.model_id, model) print("in evaluate data, ", dev_fname, args.reload_model_name) dev_gen = get_data_gen(dev_fname, 'test', args, model.transformer_tokenizer) gold_pred = [] eval_loss = 0. total_ex_count = 0 #IMPORTANT since this takes so long sub sample for now 500 for batch in tqdm(dev_gen): if total_ex_count > examples_limit: break total_ex_count += len(batch['targets']) try: inputs, targets = to_torch(batch, device) loss, output_logits = model(inputs, targets) except Exception as e: print("in Eval to torch error so continue: ",e ) continue output_index = get_output_index(output_logits, threshold=args.threshold) gold_pred += get_gold_pred_str(output_index, batch['targets'].data.cpu().clone(), args.goal, args.env) eval_loss += loss.clone().item() print("Gold Pred", len(gold_pred),gold_pred[0:4]) eval_str = get_eval_string(gold_pred) _, _, _, _, _, macro_f1 = macro(gold_pred) elapsed = start_time - time.time() eval_loss_str = 'Eval loss: {0:.7f} at step {1} time elapsed {2}'.format(eval_loss, args.reload_model_name, elapsed) print('==> EVAL: seen ' + repr(total_ex_count) + ' examples.') print(eval_loss_str) print(gold_pred[:3]) print('==> ' + eval_str) """ Test """ def _test(args, model, device): start_time = time.time() assert args.load test_fname = transformer_constant.get(args.env,'EVAL_DATA') #this takes way too long on test, and really we want to see which does best on DEV.. so use _val #test_fname = transformer_constant.get(args.env,'DEV_DATA') args.eval_batch_size = args.per_gpu_train_batch_size * max(1, args.n_gpu) data_gens = get_datasets([(test_fname, 'test')], args, model.transformer_tokenizer) model.eval() load_model(args.reload_model_name, transformer_constant.get(args.env,'EXP_ROOT'), args.model_id, model) if args.n_gpu > 1: model = torch.nn.DataParallel(model) print("==> use", torch.cuda.device_count(), "GPUs.") cur_time = time.time() for name, dataset in [(test_fname, data_gens[0])]: print('Processing... ' + name + " with len ",type(dataset), " Elapsed Time: ", cur_time - start_time) total_gold_pred = [] total_annot_ids = [] total_probs = [] total_ys = [] for batch_num, batch in tqdm(enumerate(dataset)): if batch_num % 1 == 0: print(batch_num) if not isinstance(batch, dict): print('==> batch: ', batch) inputs, targets = to_torch(batch, device) annot_ids = batch.pop('ex_ids') if args.n_gpu > 1: output_logits = model(inputs, targets) else: _, output_logits = model(inputs) output_index = get_output_index(output_logits, threshold=args.threshold) output_prob = model.sigmoid_fn(output_logits).data.cpu().clone().numpy() """ print("Inputs: ",inputs) print("Targets: ", targets) print("Batch: ",batch) print("Annot_ids: ",annot_ids) print("output_index: ",output_index) print("output_prob: ",output_prob) """ #y = inputs['targets'].data.cpu().clone().numpy() #orig y = batch['targets'].data.cpu().clone().numpy() #maybe fix? maybe should be just targets gold_pred = get_gold_pred_str(output_index, y, args.goal, args.env) print("Gold Pred", len(gold_pred),gold_pred[0:3]) eval_str = get_eval_string(gold_pred) _, _, _, _, _, macro_f1 = macro(gold_pred) print('==> ' + eval_str) total_probs.extend(output_prob) total_ys.extend(y) total_gold_pred.extend(gold_pred) total_annot_ids.extend(annot_ids) cur_time2 = time.time() print("DONE SAVING PICKLE. Elapsed Time", cur_time2 - cur_time) pickle.dump({'gold_id_array': total_ys, 'pred_dist': total_probs}, open(transformer_constant.get(args.env,'FILE_ROOT') + '/outputs/{0:s}.pkl'.format(args.model_id), "wb")) print("LENS",len(total_annot_ids), len(total_gold_pred)) with open(transformer_constant.get(args.env, 'FILE_ROOT') + '/outputs/{0:s}.json'.format(args.model_id), 'w') as f_out: output_dict = {} counter = 0 for a_id, (gold, pred) in zip(total_annot_ids, total_gold_pred): output_dict[a_id] = {"gold": gold, "pred": pred} counter += 1 json.dump(output_dict, f_out) #eval_str = get_eval_string(total_gold_pred) eval_str = 'none' print("DONE") print(eval_str) def main(): args = parser.parse_args() # Lower text for BERT uncased models args.do_lower = True if 'uncased' in args.model_type else False # Setup CUDA, GPU & distributed training assert torch.cuda.is_available() if args.local_rank == -1: device = torch.device("cuda") args.n_gpu = torch.cuda.device_count() else: # Initializes the distributed backend which will take care of sychronizing nodes/GPUs torch.cuda.set_device(args.local_rank) device = torch.device("cuda", args.local_rank) torch.distributed.init_process_group(backend="nccl") args.n_gpu = 1 args.device = device set_seed(args) # Load pretrained model and tokenizer if args.local_rank not in [-1, 0]: torch.distributed.barrier() # Make sure only the first process in distributed training will download model & vocab ind = args.goal if args.env == "" else args.env model = TransformerModel(args, transformer_constant.ANSWER_NUM_DICT[ind]) if args.local_rank == 0: torch.distributed.barrier() # Make sure only the first process in distributed training will download model & vocab model.to(args.device) #print(model) args.max_position_embeddings = model.transformer_config.max_position_embeddings print("MAX POSITION EMBEDDINGS: ",args.max_position_embeddings ) print('-' * 80) for k, v in vars(args).items(): print(k, ':', v) print('-' * 80) if args.mode == 'train': print('==> mode: train') _train(args, model, device) elif args.mode == 'val': # helper function 1005 print('==> mode: val') _val(args, model, device) elif args.mode == 'test': print('==> mode: test') _test(args, model, device) else: raise ValueError("invalid value for 'mode': {}".format(args.mode)) if __name__ == '__main__': main()
38.365889
196
0.682587
import argparse import gc import json import numpy as np import pickle import random import time import torch import torch.nn as nn from tqdm import tqdm from transformers import AdamW, get_linear_schedule_with_warmup import transformer_constant import transformer_data_utils from transformer_data_utils import to_torch from models import TransformerModel parser = argparse.ArgumentParser() parser.add_argument("-model_id", help="Identifier for model") parser.add_argument('-device', type=int, default=0, help='CUDA device') parser.add_argument("-n_gpu", help="Number of GPUs.", type=int, default=1) parser.add_argument("-mode", help="Whether to train or test", default="train", choices=["train", "val", "test"]) parser.add_argument("-local_rank", type=int, default=-1, help="For distributed training: local_rank") parser.add_argument("-train_data", help="Train data", default="train/wiki_et_zeroshot_60k_ex_random/train_*.json") parser.add_argument("-dev_data", help="Dev data", default="validation/dev_wiki_et_zeroshot_60k_ex_random_999.json") parser.add_argument("-eval_data", help="Test data", default="") parser.add_argument("-goal", help="category vocab size.", default="60k", choices=["medwiki","60k", "ufet"]) parser.add_argument("-seed", help="Pytorch random Seed", default=113) parser.add_argument("-context_window_size", help="Left and right context size.", default=100) parser.add_argument("-num_epoch", help="The number of epoch", default=5000, type=int) parser.add_argument("-per_gpu_train_batch_size", help="The batch size per GPU", default=8, type=int) parser.add_argument("-per_gpu_eval_batch_size", help="The batch size per GPU", default=8, type=int) parser.add_argument("-learning_rate_enc", help="BERT: start learning rate", default=2e-5, type=float) parser.add_argument("-learning_rate_cls", help="BERT: start learning rate", default=1e-3, type=float) parser.add_argument("-adam_epsilon_enc", default=1e-8, type=float, help="Epsilon for Adam optimizer.") parser.add_argument("-adam_epsilon_cls", default=1e-8, type=float, help="Epsilon for Adam optimizer.") parser.add_argument("-hidden_dropout_prob", help="Dropout rate", default=.1, type=float) parser.add_argument("-warmup_steps", default=0, type=int, help="Linear warmup over warmup_steps.") parser.add_argument( "-gradient_accumulation_steps", type=int, default=1, help="Number of updates steps to accumulate before performing a backward/update pass.", ) parser.add_argument( "-model_type", default="bert-base-uncased", choices=[ "bert-base-uncased", "bert-large-uncased", "bert-large-uncased-whole-word-masking", "roberta-base", "roberta-large", "allenai/biomed_roberta_base", "monologg/biobert_v1.1_pubmed", "allenai/scibert_scivocab_uncased", "microsoft/BiomedNLP-PubMedBERT-base-uncased-abstract-fulltext" ] ) parser.add_argument("-threshold", help="threshold", default=0.5, type=float) parser.add_argument("-avg_pooling", help="Averaging all hidden states instead of using [CLS].", action='store_true') parser.add_argument("-save_period", help="How often to save", default=1000, type=int) parser.add_argument("-eval_period", help="How often to run dev", default=500, type=int) parser.add_argument("-log_period", help="How often to save", default=1000, type=int) parser.add_argument("-eval_after", help="How often to run dev", default=10, type=int) parser.add_argument("-load", help="Load existing model.", action='store_true') parser.add_argument("-reload_model_name", help="") parser.add_argument("-reload_model_name_desc", help="") parser.add_argument("-env", help="data sub for medwiki", default="", choices=["yasu", "0720_3k_full","0720_3k_full_orig", "0720_3k_drugs","0720_600k_full","0720_600k_full_orig","0720_600k_drugs"]) parser.add_argument("-examples_limit", help="How many examples to do eval on in def _val", default=1000, type=int) SIGMOID = nn.Sigmoid() def set_seed(args): random.seed(args.seed) np.random.seed(args.seed) torch.manual_seed(args.seed) if args.n_gpu > 0: torch.cuda.manual_seed_all(args.seed) def get_data_gen(dataname, mode, args, tokenizer): data_path = transformer_constant.get(args.env, 'FILE_ROOT') + dataname print("load data path", data_path, "with args.env", args.env) dataset = transformer_data_utils.DatasetLoader(data_path, args, tokenizer) if mode == 'train': data_gen = dataset.get_batch(args.train_batch_size, args.max_position_embeddings, args.num_epoch, eval_data=False) else: data_gen = dataset.get_batch(args.eval_batch_size, args.max_position_embeddings, 1, eval_data=True) return data_gen def get_all_datasets(args, tokenizer): train_gen_list = [] if args.mode in ['train']: if 'wiki_desc' in args.model_id: print("load wiki_desc",) train_gen_list.append(get_data_gen(transformer_constant.get(args.env,'WIKI_TRAIN_DATA'), 'train', args, tokenizer)) else: train_gen_list.append(get_data_gen(transformer_constant.get(args.env,'TRAIN_DATA'), 'train', args, tokenizer)) return train_gen_list def get_datasets(data_lists, args, tokenizer): data_gen_list = [] for dataname, mode in data_lists: data_gen_list.append(get_data_gen(dataname, mode, args, tokenizer)) return data_gen_list def evaluate_data(batch_num, dev_fname, model, args, device): print("in evaluate data, batchnum", batch_num, dev_fname) model.eval() dev_gen = get_data_gen(dev_fname, 'test', args, model.transformer_tokenizer) gold_pred = [] eval_loss = 0. total_ex_count = 0 for batch in tqdm(dev_gen): if total_ex_count > 500: break total_ex_count += len(batch['targets']) try: inputs, targets = to_torch(batch, device) loss, output_logits = model(inputs, targets) except Exception as e: print("in Eval to torch error so continue: ",e ) continue output_index = get_output_index(output_logits, threshold=args.threshold) gold_pred += get_gold_pred_str(output_index, batch['targets'].data.cpu().clone(), args.goal, args.env) eval_loss += loss.clone().item() print("Gold Pred", len(gold_pred),gold_pred[0:4]) eval_str = get_eval_string(gold_pred) _, _, _, _, _, macro_f1 = macro(gold_pred) eval_loss_str = 'Eval loss: {0:.7f} at step {1:d}'.format(eval_loss, batch_num) print('==> EVAL: seen ' + repr(total_ex_count) + ' examples.') print(eval_loss_str) print(gold_pred[:3]) print('==> ' + eval_str) model.train() dev_gen = None return eval_loss, macro_f1 def f1(p, r): if r == 0.: return 0. return 2 * p * r / float(p + r) def macro(true_and_prediction): num_examples = len(true_and_prediction) p = 0. r = 0. pred_example_count = 0. pred_label_count = 0. gold_label_count = 0. for true_labels, predicted_labels in true_and_prediction: if predicted_labels: pred_example_count += 1 pred_label_count += len(predicted_labels) per_p = len(set(predicted_labels).intersection(set(true_labels))) / float(len(predicted_labels)) p += per_p if len(true_labels): gold_label_count += 1 per_r = len(set(predicted_labels).intersection(set(true_labels))) / float(len(true_labels)) r += per_r if pred_example_count > 0: precision = p / pred_example_count if gold_label_count > 0: recall = r / gold_label_count if pred_example_count == 0: print("In Macro: Pred Example Count == 0") avg_elem_per_pred = 0 else: avg_elem_per_pred = pred_label_count / pred_example_count return num_examples, pred_example_count, avg_elem_per_pred, precision, recall, f1(precision, recall) def micro(true_and_prediction): num_examples = len(true_and_prediction) num_predicted_labels = 0. num_true_labels = 0. num_correct_labels = 0. pred_example_count = 0. for true_labels, predicted_labels in true_and_prediction: if predicted_labels: pred_example_count += 1 num_predicted_labels += len(predicted_labels) num_true_labels += len(true_labels) num_correct_labels += len(set(predicted_labels).intersection(set(true_labels))) if pred_example_count == 0: return num_examples, 0, 0, 0, 0, 0 precision = num_correct_labels / num_predicted_labels recall = num_correct_labels / num_true_labels avg_elem_per_pred = num_predicted_labels / pred_example_count return num_examples, pred_example_count, avg_elem_per_pred, precision, recall, f1(precision, recall) def load_model(reload_model_name, save_dir, model_id, model, optimizer_enc=None, optimizer_cls=None, scheduler_enc=None, scheduler_cls=None): if reload_model_name: model_file_name = '{0:s}/{1:s}.pt'.format(save_dir, reload_model_name) else: model_file_name = '{0:s}/{1:s}.pt'.format(save_dir, model_id) print("Loading ", model_file_name) checkpoint = torch.load(model_file_name) model.load_state_dict(checkpoint['state_dict']) if optimizer_enc and optimizer_cls: load_state_dict(checkpoint['optimizer_enc']) optimizer_cls.load_state_dict(checkpoint['optimizer_cls']) else: total_params = 0 for k in checkpoint['state_dict']: elem = checkpoint['state_dict'][k] param_s = 1 for size_dim in elem.size(): param_s = size_dim * param_s total_params += param_s param_str = ('Number of total parameters..{0:d}'.format(total_params)) print(param_str) print('Loading model from ... {0:s}'.format(model_file_name)) def get_output_index(outputs, threshold=0.5): pred_idx = [] outputs = SIGMOID(outputs).data.cpu().clone() for single_dist in outputs: single_dist = single_dist.numpy() arg_max_ind = np.argmax(single_dist) pred_id = [arg_max_ind] pred_id.extend( [i for i in range(len(single_dist)) if single_dist[i] > threshold and i != arg_max_ind]) pred_idx.append(pred_id) return pred_idx def get_gold_pred_str(pred_idx, gold, goal, env): if goal == '60k': id2word_dict = transformer_constant.ID2ANS_DICT_60K elif goal == 'ufet': id2word_dict = transformer_constant.ID2ANS_DICT_UFET elif goal == 'medwiki': id2word_dict = transformer_constant.ID2ANS_MEDWIKI_DICT[env] else: print('ERROR: Invalid input...' + goal) raise gold_strs = [] for gold_i in gold: gold_strs.append([id2word_dict[i] for i in range(len(gold_i)) if gold_i[i] == 1]) pred_strs = [] for pred_idx1 in pred_idx: pred_strs.append([(id2word_dict[ind]) for ind in pred_idx1]) else: return list(zip(gold_strs, pred_strs)) def get_eval_string(true_prediction): count, pred_count, avg_pred_count, p, r, f1 = micro(true_prediction) _, _, _, ma_p, ma_r, ma_f1 = macro(true_prediction) output_str = "Eval: {0} {1} {2:.3f} P:{3:.3f} R:{4:.3f} F1:{5:.3f} Ma_P:{6:.3f} Ma_R:{7:.3f} Ma_F1:{8:.3f}".format( count, pred_count, avg_pred_count, p, r, f1, ma_p, ma_r, ma_f1) accuracy = sum([set(y) == set(yp) for y, yp in true_prediction]) * 1.0 / len(true_prediction) output_str += '\t Dev accuracy: {0:.1f}%'.format(accuracy * 100) return output_str def _train(args, model, device): args.train_batch_size = args.per_gpu_train_batch_size * max(1, args.n_gpu) args.eval_batch_size = args.per_gpu_train_batch_size * max(1, args.n_gpu) print('==> Loading data generator... ') train_gen_list = get_all_datasets(args, model.transformer_tokenizer) print('done. {} data gen(s)'.format(len(train_gen_list))) print('Model Type: {}'.format(args.model_type)) total_loss = 0. batch_num = 0 best_macro_f1 = 0. start_time = time.time() init_time = time.time() print('Total {} named params.'.format(len([n for n, p in model.named_parameters()]))) no_decay = ["bias", "LayerNorm.weight"] classifier_param_name = ["classifier.linear.weight"] encoder_parameters = [ { "params": [p for n, p in model.named_parameters() if not any(nd in n for nd in no_decay) and n not in classifier_param_name], "weight_decay": 0.0 }, { "params": [p for n, p in model.named_parameters() if any(nd in n for nd in no_decay) and n not in classifier_param_name], "weight_decay": 0.0 }, ] classifier_parameters = [ { "params": [p for n, p in model.named_parameters() if n in classifier_param_name], "weight_decay": 0.0 }, ] print( 'Encoder {}, Classifier {}'.format( sum([len(p['params']) for p in encoder_parameters]), sum([len(p['params']) for p in classifier_parameters]) ) ) optimizer_enc = AdamW(encoder_parameters, lr=args.learning_rate_enc, eps=args.adam_epsilon_enc) optimizer_cls = AdamW(classifier_parameters, lr=args.learning_rate_cls, eps=args.adam_epsilon_cls) if args.n_gpu > 1: model = torch.nn.DataParallel(model) if args.load: load_model(args.reload_model_name, transformer_constant.get(args.env,'EXP_ROOT'), args.model_id, model, optimizer_enc, optimizer_cls) optimizer_enc.zero_grad() optimizer_cls.zero_grad() set_seed(args) global_train_sum, global_train_n = 0, 0 global_overlap_train_sum, global_overlap_train_n = 0, 0 while True: batch_num += 1 for data_gen in train_gen_list: try: batch = next(data_gen) inputs, targets = to_torch(batch, device) except StopIteration: print('Done!') torch.save( { 'state_dict': model.state_dict(), 'optimizer_cls': optimizer_cls.state_dict(), 'optimizer_enc': optimizer_enc.state_dict(), 'args': args }, '{0:s}/{1:s}.pt'.format(transformer_constant.get(args.env,'EXP_ROOT'), args.model_id) ) return except Exception as e: print("To torch error so continue: ",e ) print("Batch num",batch_num) print(batch) print(inputs) print(targets) continue model.train() if args.model_type != "distilbert": inputs["token_type_ids"] = ( batch["token_type_ids"] if args.model_type in ["bert", "xlnet", "albert"] else None ) try: loss, output_logits = model(inputs, targets) except Exception as e: print("Error computing loss on batch_num: ", batch_num, e) #print("Inputs: ", inputs) <-- even printing this out gives an error #print("Targets: ", targets) # skip batch and try to figure out what happned continue inputs, targets = None, None if args.n_gpu > 1: loss = loss.mean() # mean() to average on multi-gpu parallel training if args.gradient_accumulation_steps > 1: loss = loss / args.gradient_accumulation_steps loss.backward() total_loss += loss.item() if batch_num % args.gradient_accumulation_steps == 0: optimizer_enc.step() optimizer_cls.step() optimizer_enc.zero_grad() optimizer_cls.zero_grad() if batch_num % args.log_period == 0 and batch_num > 0: gc.collect() cur_loss = float(1.0 * loss.clone().item()) elapsed = time.time() - start_time train_loss_str = ('|loss {0:3f} | at {1:d}step | @ {2:.2f} ms/batch'.format(cur_loss, batch_num, elapsed * 1000 / args.log_period)) start_time = time.time() print(train_loss_str) if batch_num % args.eval_period == 0 and batch_num > 0: output_index = get_output_index(output_logits, threshold=args.threshold) batch_targets_clone = batch['targets'].data.cpu().clone() gold_pred_train = get_gold_pred_str(output_index, batch_targets_clone, args.goal, args.env) #print("OUTPUT INDEX:",output_index[:4]) #print("TARGETS:", batch_targets_clone[:4].shape, type(batch_targets_clone), batch_targets_clone[:4]) #print(torch.nonzero(batch_targets_clone[:4])) print("1st ten preds (true cats, pred cats)", [(i,len(v[0]), len(v[1]), len(v[0])==len(v[1]), v[0], v[1]) for i,v in enumerate(gold_pred_train[:10])]) accuracy = sum([set(y) == set(yp) for y, yp in gold_pred_train]) * 1.0 / len(gold_pred_train) print('==> Train accuracy: {0:.1f}%'.format(accuracy * 100)) overlap_accuracy = sum([len(set(y).intersection(set(yp)))/len(yp) for y, yp in gold_pred_train]) * 1.0 / len(gold_pred_train) print('==> Train overlap accuracy: {0:.1f}%'.format(overlap_accuracy * 100)) global_train_sum += sum([set(y) == set(yp) for y, yp in gold_pred_train]) * 1.0 global_train_n += len(gold_pred_train) global_acc = global_train_sum / global_train_n print('==> Global Train accuracy: {0:.1f}%'.format(global_acc * 100)) global_overlap_train_sum += sum([len(set(y).intersection(set(yp)))/len(yp) for y, yp in gold_pred_train]) * 1.0 global_overlap_train_n += len(gold_pred_train) global_overlap_acc = global_overlap_train_sum / global_overlap_train_n print('==> Global Train overlap accuracy: {0:.1f}%'.format(global_overlap_acc * 100)) if batch_num % args.eval_period == 0 and batch_num > args.eval_after: # Evaluate Loss on the Turk Dev dataset. print('---- eval at step {0:d} ---'.format(batch_num)) if 'wiki_desc' in args.model_id: _, macro_f1 = evaluate_data(batch_num, transformer_constant.get(args.env,'WIKI_DEV_DATA'), model, args, device) else: _, macro_f1 = evaluate_data(batch_num, transformer_constant.get(args.env,'DEV_DATA'), model, args, device) if best_macro_f1 < macro_f1: best_macro_f1 = macro_f1 save_fname = '{0:s}/{1:s}_best.pt'.format(transformer_constant.get(args.env,'EXP_ROOT'), args.model_id) torch.save( { 'state_dict': model.state_dict(), 'optimizer_cls': optimizer_cls.state_dict(), 'optimizer_enc': optimizer_enc.state_dict(), 'args': args }, save_fname ) print( 'Total {0:.2f} minutes have passed, saving at {1:s} '.format((time.time() - init_time) / 60, save_fname)) #if batch_num % args.save_period == 0 and batch_num > 30000: if batch_num % args.save_period == 0 and batch_num >= args.eval_after: save_fname = '{0:s}/{1:s}_{2:d}.pt'.format(transformer_constant.get(args.env,'EXP_ROOT'), args.model_id, batch_num) torch.save( { 'state_dict': model.state_dict(), 'optimizer_cls': optimizer_cls.state_dict(), 'optimizer_enc': optimizer_enc.state_dict(), 'args': args }, save_fname ) print( 'Total {0:.2f} minutes have passed, saving at {1:s} '.format((time.time() - init_time) / 60, save_fname)) def _val(args, model, device): examples_limit = args.examples_limit start_time = time.time() assert args.load dev_fname = transformer_constant.get(args.env,'DEV_DATA') args.eval_batch_size = args.per_gpu_train_batch_size * max(1, args.n_gpu) model.eval() load_model(args.reload_model_name, transformer_constant.get(args.env,'EXP_ROOT'), args.model_id, model) print("in evaluate data, ", dev_fname, args.reload_model_name) dev_gen = get_data_gen(dev_fname, 'test', args, model.transformer_tokenizer) gold_pred = [] eval_loss = 0. total_ex_count = 0 #IMPORTANT since this takes so long sub sample for now 500 for batch in tqdm(dev_gen): if total_ex_count > examples_limit: break total_ex_count += len(batch['targets']) try: inputs, targets = to_torch(batch, device) loss, output_logits = model(inputs, targets) except Exception as e: print("in Eval to torch error so continue: ",e ) continue output_index = get_output_index(output_logits, threshold=args.threshold) gold_pred += get_gold_pred_str(output_index, batch['targets'].data.cpu().clone(), args.goal, args.env) eval_loss += loss.clone().item() print("Gold Pred", len(gold_pred),gold_pred[0:4]) eval_str = get_eval_string(gold_pred) _, _, _, _, _, macro_f1 = macro(gold_pred) elapsed = start_time - time.time() eval_loss_str = 'Eval loss: {0:.7f} at step {1} time elapsed {2}'.format(eval_loss, args.reload_model_name, elapsed) print('==> EVAL: seen ' + repr(total_ex_count) + ' examples.') print(eval_loss_str) print(gold_pred[:3]) print('==> ' + eval_str) def _test(args, model, device): start_time = time.time() assert args.load test_fname = transformer_constant.get(args.env,'EVAL_DATA') #this takes way too long on test, and really we want to see which does best on DEV.. so use _val #test_fname = transformer_constant.get(args.env,'DEV_DATA') args.eval_batch_size = args.per_gpu_train_batch_size * max(1, args.n_gpu) data_gens = get_datasets([(test_fname, 'test')], args, model.transformer_tokenizer) model.eval() load_model(args.reload_model_name, transformer_constant.get(args.env,'EXP_ROOT'), args.model_id, model) if args.n_gpu > 1: model = torch.nn.DataParallel(model) print("==> use", torch.cuda.device_count(), "GPUs.") cur_time = time.time() for name, dataset in [(test_fname, data_gens[0])]: print('Processing... ' + name + " with len ",type(dataset), " Elapsed Time: ", cur_time - start_time) total_gold_pred = [] total_annot_ids = [] total_probs = [] total_ys = [] for batch_num, batch in tqdm(enumerate(dataset)): if batch_num % 1 == 0: print(batch_num) if not isinstance(batch, dict): print('==> batch: ', batch) inputs, targets = to_torch(batch, device) annot_ids = batch.pop('ex_ids') if args.n_gpu > 1: output_logits = model(inputs, targets) else: _, output_logits = model(inputs) output_index = get_output_index(output_logits, threshold=args.threshold) output_prob = model.sigmoid_fn(output_logits).data.cpu().clone().numpy() #y = inputs['targets'].data.cpu().clone().numpy() #orig y = batch['targets'].data.cpu().clone().numpy() #maybe fix? maybe should be just targets gold_pred = get_gold_pred_str(output_index, y, args.goal, args.env) print("Gold Pred", len(gold_pred),gold_pred[0:3]) eval_str = get_eval_string(gold_pred) _, _, _, _, _, macro_f1 = macro(gold_pred) print('==> ' + eval_str) total_probs.extend(output_prob) total_ys.extend(y) total_gold_pred.extend(gold_pred) total_annot_ids.extend(annot_ids) cur_time2 = time.time() print("DONE SAVING PICKLE. Elapsed Time", cur_time2 - cur_time) pickle.dump({'gold_id_array': total_ys, 'pred_dist': total_probs}, open(transformer_constant.get(args.env,'FILE_ROOT') + '/outputs/{0:s}.pkl'.format(args.model_id), "wb")) print("LENS",len(total_annot_ids), len(total_gold_pred)) with open(transformer_constant.get(args.env, 'FILE_ROOT') + '/outputs/{0:s}.json'.format(args.model_id), 'w') as f_out: output_dict = {} counter = 0 for a_id, (gold, pred) in zip(total_annot_ids, total_gold_pred): output_dict[a_id] = {"gold": gold, "pred": pred} counter += 1 json.dump(output_dict, f_out) #eval_str = get_eval_string(total_gold_pred) eval_str = 'none' print("DONE") print(eval_str) def main(): args = parser.parse_args() # Lower text for BERT uncased models args.do_lower = True if 'uncased' in args.model_type else False # Setup CUDA, GPU & distributed training assert torch.cuda.is_available() if args.local_rank == -1: device = torch.device("cuda") args.n_gpu = torch.cuda.device_count() else: # Initializes the distributed backend which will take care of sychronizing nodes/GPUs torch.cuda.set_device(args.local_rank) device = torch.device("cuda", args.local_rank) torch.distributed.init_process_group(backend="nccl") args.n_gpu = 1 args.device = device set_seed(args) # Load pretrained model and tokenizer if args.local_rank not in [-1, 0]: torch.distributed.barrier() # Make sure only the first process in distributed training will download model & vocab ind = args.goal if args.env == "" else args.env model = TransformerModel(args, transformer_constant.ANSWER_NUM_DICT[ind]) if args.local_rank == 0: torch.distributed.barrier() # Make sure only the first process in distributed training will download model & vocab model.to(args.device) #print(model) args.max_position_embeddings = model.transformer_config.max_position_embeddings print("MAX POSITION EMBEDDINGS: ",args.max_position_embeddings ) print('-' * 80) for k, v in vars(args).items(): print(k, ':', v) print('-' * 80) if args.mode == 'train': print('==> mode: train') _train(args, model, device) elif args.mode == 'val': # helper function 1005 print('==> mode: val') _val(args, model, device) elif args.mode == 'test': print('==> mode: test') _test(args, model, device) else: raise ValueError("invalid value for 'mode': {}".format(args.mode)) if __name__ == '__main__': main()
true
true
1c33f502aebb10efa0fd15dc2ab7e98b4c9b9f82
8,050
py
Python
support/closure-library/closure/bin/build/closurebuilder.py
joe-greenawalt/skulpt
1db078e2f6d453403287233254b012bf31960ef4
[ "MIT" ]
2
2021-01-10T16:19:38.000Z
2021-06-14T22:09:59.000Z
support/closure-library/closure/bin/build/closurebuilder.py
csev/skulpt
9aa25b7dbf29f23ee8d3140d01a6f4353d12e66f
[ "MIT" ]
null
null
null
support/closure-library/closure/bin/build/closurebuilder.py
csev/skulpt
9aa25b7dbf29f23ee8d3140d01a6f4353d12e66f
[ "MIT" ]
1
2015-06-28T18:58:22.000Z
2015-06-28T18:58:22.000Z
#!/usr/bin/env python # # Copyright 2009 The Closure Library Authors. All Rights Reserved. """Utility for Closure Library dependency calculation. ClosureBuilder scans source files to build dependency info. From the dependencies, the script can produce a deps.js file, a manifest in dependency order, a concatenated script, or compiled output from the Closure Compiler. Paths to files can be expressed as individual arguments to the tool (intended for use with find and xargs). As a convenience, --root can be used to specify all JS files below a directory. usage: %prog [options] [file1.js file2.js ...] """ import logging import optparse import os import sys import depstree import jscompiler import source import treescan def _GetOptionsParser(): """Get the options parser.""" parser = optparse.OptionParser(__doc__) parser.add_option('-i', '--input', dest='inputs', action='append', default=[], help='One or more input files to calculate dependencies ' 'for. The namespaces in this file will be combined with ' 'those given with the -n flag to form the set of ' 'namespaces to find dependencies for.') parser.add_option('-n', '--namespace', dest='namespaces', action='append', default=[], help='One or more namespaces to calculate dependencies ' 'for. These namespaces will be combined with those given ' 'with the -i flag to form the set of namespaces to find ' 'dependencies for. A Closure namespace is a ' 'dot-delimited path expression declared with a call to ' 'goog.provide() (e.g. "goog.array" or "foo.bar").') parser.add_option('--root', dest='roots', action='append', help='The paths that should be traversed to build the ' 'dependencies.') parser.add_option('-o', '--output_mode', dest='output_mode', type='choice', action='store', choices=['list', 'script', 'compiled'], default='list', help='The type of output to generate from this script. ' 'Options are "list" for a list of filenames, "script" ' 'for a single script containing the contents of all the ' 'files, or "compiled" to produce compiled output with ' 'the Closure Compiler. Default is "list".') parser.add_option('-c', '--compiler_jar', dest='compiler_jar', action='store', help='The location of the Closure compiler .jar file.') parser.add_option('-f', '--compiler_flags', dest='compiler_flags', default=[], action='append', help='Additional flags to pass to the Closure compiler.') parser.add_option('--output_file', dest='output_file', action='store', help=('If specified, write output to this path instead of ' 'writing to standard output.')) return parser def _GetInputByPath(path, sources): """Get the source identified by a path. Args: path: str, A path to a file that identifies a source. sources: An iterable collection of source objects. Returns: The source from sources identified by path, if found. Converts to absolute paths for comparison. """ for js_source in sources: # Convert both to absolute paths for comparison. if os.path.abspath(path) == os.path.abspath(js_source.GetPath()): return js_source def _GetClosureBaseFile(sources): """Given a set of sources, returns the one base.js file. Note that if zero or two or more base.js files are found, an error message will be written and the program will be exited. Args: sources: An iterable of _PathSource objects. Returns: The _PathSource representing the base Closure file. """ filtered_base_files = filter(_IsClosureBaseFile, sources) if not filtered_base_files: logging.error('No Closure base.js file found.') sys.exit(1) if len(filtered_base_files) > 1: logging.error('More than one Closure base.js files found at these paths:') for base_file in filtered_base_files: logging.error(base_file.GetPath()) sys.exit(1) return filtered_base_files[0] def _IsClosureBaseFile(js_source): """Returns true if the given _PathSource is the Closure base.js source.""" if os.path.basename(js_source.GetPath()) == 'base.js': # Sanity check that this is the Closure base file. Check that this # is where goog is defined. for line in js_source.GetSource().splitlines(): if line.startswith('var goog = goog || {};'): return True return False class _PathSource(source.Source): """Source file subclass that remembers its file path.""" def __init__(self, path): """Initialize a source. Args: path: str, Path to a JavaScript file. The source string will be read from this file. """ super(_PathSource, self).__init__(source.GetFileContents(path)) self._path = path def GetPath(self): """Returns the path.""" return self._path def main(): logging.basicConfig(format=(sys.argv[0] + ': %(message)s'), level=logging.INFO) options, args = _GetOptionsParser().parse_args() # Make our output pipe. if options.output_file: out = open(options.output_file, 'w') else: out = sys.stdout sources = set() logging.info('Scanning paths...') for path in options.roots: for js_path in treescan.ScanTreeForJsFiles(path): sources.add(_PathSource(js_path)) # Add scripts specified on the command line. for path in args: sources.add(source.Source(_PathSource(path))) logging.info('%s sources scanned.', len(sources)) # Though deps output doesn't need to query the tree, we still build it # to validate dependencies. logging.info('Building dependency tree..') tree = depstree.DepsTree(sources) input_namespaces = set() inputs = options.inputs or [] for input_path in inputs: js_input = _GetInputByPath(input_path, sources) if not js_input: logging.error('No source matched input %s', input_path) sys.exit(1) input_namespaces.update(js_input.provides) input_namespaces.update(options.namespaces) if not input_namespaces: logging.error('No namespaces found. At least one namespace must be ' 'specified with the --namespace or --input flags.') sys.exit(2) # The Closure Library base file must go first. base = _GetClosureBaseFile(sources) deps = [base] + tree.GetDependencies(input_namespaces) output_mode = options.output_mode if output_mode == 'list': out.writelines([js_source.GetPath() + '\n' for js_source in deps]) elif output_mode == 'script': out.writelines([js_source.GetSource() for js_source in deps]) elif output_mode == 'compiled': # Make sure a .jar is specified. if not options.compiler_jar: logging.error('--compiler_jar flag must be specified if --output is ' '"compiled"') sys.exit(2) compiled_source = jscompiler.Compile( options.compiler_jar, [js_source.GetPath() for js_source in deps], options.compiler_flags) if compiled_source is None: logging.error('JavaScript compilation failed.') sys.exit(1) else: logging.info('JavaScript compilation succeeded.') out.write(compiled_source) else: logging.error('Invalid value for --output flag.') sys.exit(2) if __name__ == '__main__': main()
32.723577
79
0.623602
import logging import optparse import os import sys import depstree import jscompiler import source import treescan def _GetOptionsParser(): parser = optparse.OptionParser(__doc__) parser.add_option('-i', '--input', dest='inputs', action='append', default=[], help='One or more input files to calculate dependencies ' 'for. The namespaces in this file will be combined with ' 'those given with the -n flag to form the set of ' 'namespaces to find dependencies for.') parser.add_option('-n', '--namespace', dest='namespaces', action='append', default=[], help='One or more namespaces to calculate dependencies ' 'for. These namespaces will be combined with those given ' 'with the -i flag to form the set of namespaces to find ' 'dependencies for. A Closure namespace is a ' 'dot-delimited path expression declared with a call to ' 'goog.provide() (e.g. "goog.array" or "foo.bar").') parser.add_option('--root', dest='roots', action='append', help='The paths that should be traversed to build the ' 'dependencies.') parser.add_option('-o', '--output_mode', dest='output_mode', type='choice', action='store', choices=['list', 'script', 'compiled'], default='list', help='The type of output to generate from this script. ' 'Options are "list" for a list of filenames, "script" ' 'for a single script containing the contents of all the ' 'files, or "compiled" to produce compiled output with ' 'the Closure Compiler. Default is "list".') parser.add_option('-c', '--compiler_jar', dest='compiler_jar', action='store', help='The location of the Closure compiler .jar file.') parser.add_option('-f', '--compiler_flags', dest='compiler_flags', default=[], action='append', help='Additional flags to pass to the Closure compiler.') parser.add_option('--output_file', dest='output_file', action='store', help=('If specified, write output to this path instead of ' 'writing to standard output.')) return parser def _GetInputByPath(path, sources): for js_source in sources: if os.path.abspath(path) == os.path.abspath(js_source.GetPath()): return js_source def _GetClosureBaseFile(sources): filtered_base_files = filter(_IsClosureBaseFile, sources) if not filtered_base_files: logging.error('No Closure base.js file found.') sys.exit(1) if len(filtered_base_files) > 1: logging.error('More than one Closure base.js files found at these paths:') for base_file in filtered_base_files: logging.error(base_file.GetPath()) sys.exit(1) return filtered_base_files[0] def _IsClosureBaseFile(js_source): if os.path.basename(js_source.GetPath()) == 'base.js': for line in js_source.GetSource().splitlines(): if line.startswith('var goog = goog || {};'): return True return False class _PathSource(source.Source): def __init__(self, path): super(_PathSource, self).__init__(source.GetFileContents(path)) self._path = path def GetPath(self): return self._path def main(): logging.basicConfig(format=(sys.argv[0] + ': %(message)s'), level=logging.INFO) options, args = _GetOptionsParser().parse_args() if options.output_file: out = open(options.output_file, 'w') else: out = sys.stdout sources = set() logging.info('Scanning paths...') for path in options.roots: for js_path in treescan.ScanTreeForJsFiles(path): sources.add(_PathSource(js_path)) for path in args: sources.add(source.Source(_PathSource(path))) logging.info('%s sources scanned.', len(sources)) # to validate dependencies. logging.info('Building dependency tree..') tree = depstree.DepsTree(sources) input_namespaces = set() inputs = options.inputs or [] for input_path in inputs: js_input = _GetInputByPath(input_path, sources) if not js_input: logging.error('No source matched input %s', input_path) sys.exit(1) input_namespaces.update(js_input.provides) input_namespaces.update(options.namespaces) if not input_namespaces: logging.error('No namespaces found. At least one namespace must be ' 'specified with the --namespace or --input flags.') sys.exit(2) # The Closure Library base file must go first. base = _GetClosureBaseFile(sources) deps = [base] + tree.GetDependencies(input_namespaces) output_mode = options.output_mode if output_mode == 'list': out.writelines([js_source.GetPath() + '\n' for js_source in deps]) elif output_mode == 'script': out.writelines([js_source.GetSource() for js_source in deps]) elif output_mode == 'compiled': # Make sure a .jar is specified. if not options.compiler_jar: logging.error('--compiler_jar flag must be specified if --output is ' '"compiled"') sys.exit(2) compiled_source = jscompiler.Compile( options.compiler_jar, [js_source.GetPath() for js_source in deps], options.compiler_flags) if compiled_source is None: logging.error('JavaScript compilation failed.') sys.exit(1) else: logging.info('JavaScript compilation succeeded.') out.write(compiled_source) else: logging.error('Invalid value for --output flag.') sys.exit(2) if __name__ == '__main__': main()
true
true
1c33f61ef94624e19a7f0a90cef13310a305cb70
9,181
py
Python
src/nsvqa/nn/interpreter/batch_base_interpreter.py
drewhayward/DFOL-VQA
8c7d403bac560588ab3ac45774a3e4f71fbe9c90
[ "MIT" ]
23
2020-08-17T16:18:33.000Z
2022-03-09T11:47:37.000Z
src/nsvqa/nn/interpreter/batch_base_interpreter.py
drewhayward/DFOL-VQA
8c7d403bac560588ab3ac45774a3e4f71fbe9c90
[ "MIT" ]
1
2021-06-11T15:51:24.000Z
2021-06-11T15:51:24.000Z
src/nsvqa/nn/interpreter/batch_base_interpreter.py
drewhayward/DFOL-VQA
8c7d403bac560588ab3ac45774a3e4f71fbe9c90
[ "MIT" ]
7
2020-11-09T07:25:27.000Z
2022-01-13T04:25:09.000Z
# Copyright (c) Microsoft. All rights reserved. # Licensed under the MIT license. See LICENSE.md file # in the project root for full license information. import torch import torch.nn as nn import os from operator import itemgetter from nsvqa.nn.interpreter import util from nsvqa.nn.interpreter.batch_base_types import BatchWorld, BatchVariableSet, BatchAttentionState from nsvqa.nn.interpreter.data_parallel import gather_results class BatchInterpreterBase(nn.Module): def __init__(self, name, oracle, featurizer=None, attention_transfer_state_dim=0, apply_modulation_everywhere=True, cached=False, visual_rule_learner=None, calibrator=None): #, attention_transfer_modulator=None): super(BatchInterpreterBase, self).__init__() self._featurizer = featurizer self._oracle = oracle self._name = name self._global_step = nn.Parameter(torch.tensor([0], dtype=torch.float), requires_grad=False) # self._atm = attention_transfer_modulator self._has_modulator = False self._attention_transfer_state_dim = attention_transfer_state_dim self._apply_modulation_everywhere = apply_modulation_everywhere self._cached = cached self._visual_rule_learner = visual_rule_learner self._calibrator = calibrator def _execute(self, op_id, world, operator_batch, input_tuple, is_terminal, is_training): pass def _transform_attention(self, op_id, is_forward, world, operator_batch, input_tuple, is_terminal, is_training): pass def parameter_count(self): return sum(p.numel() for p in self.parameters() if p.requires_grad) def save(self, export_path_base): torch.save(self.state_dict(), os.path.join(export_path_base, self._name)) def load(self, import_path_base): self.load_state_dict(torch.load(os.path.join(import_path_base, self._name)), strict=False) def build_scene(self, device, object_features, batch_index, meta_data): if self._featurizer is not None: features = self._featurizer.featurize_scene(device, object_features, batch_index, meta_data) attribute_features = features['attribute_features'] relation_features = features['relation_features'] object_num = features['object_num'] if self._cached: attribute_features, relation_features['features'] = self._oracle.compute_all_log_likelihood_2(attribute_features, relation_features['features']) if self._calibrator is not None: attribute_features[:, self._oracle._ontology._attribute_index], relation_features = self._calibrator(attribute_features[:, self._oracle._ontology._attribute_index], relation_features) if self._visual_rule_learner is not None: relation_features['object_num'] = object_num attribute_features[:, self._oracle._ontology._attribute_index], relation_features = self._visual_rule_learner(attribute_features[:, self._oracle._ontology._attribute_index], relation_features) else: object_num = object_features.size()[0] attribute_features = object_features.view(object_num, -1) arg1 = attribute_features.repeat(1, object_num).view(object_num**2, -1) arg2 = attribute_features.repeat(self._object_num, 1) relation_features = torch.cat([arg1, arg2], dim=1) return BatchWorld(device, object_num, attribute_features, relation_features, batch_index, meta_data, \ attention_transfer_state_dim=self._attention_transfer_state_dim).to(object_features.dtype) def forward(self, program_batch_list, is_training, return_trace=False, modulator_switch=True): # Initialize the trace all_traces = [] all_results = [] device = program_batch_list[0].device # Main loop for program_batch in program_batch_list: # Set the objects features world = self.build_scene(program_batch.device, program_batch._object_features, program_batch._object_batch_index, program_batch._meta_data) # print('---------------------------------------------') # Modulator loops if self._has_modulator and modulator_switch: if not self._apply_modulation_everywhere: for i in range(len(program_batch._op_batch_list) - 1): program_batch._op_batch_list._op_id += 'n' # Forward loop trace = [] for i, op_batch in enumerate(program_batch._op_batch_list): if len(program_batch._dependencies[i]) > 1: input_tuple = tuple(itemgetter(*program_batch._dependencies[i])(trace)) elif len(program_batch._dependencies[i]) == 1: input_tuple = (trace[program_batch._dependencies[i][0]],) else: input_tuple = (None,) x, terminate = self._transform_attention(op_batch._op_id, True, world, op_batch, input_tuple, i == len(program_batch._op_batch_list) - 1, is_training) # Gate the unaffected questions if i < len(program_batch._op_batch_list) - 1 and input_tuple[0] is not None and op_batch._mask is not None: x = x.gate(input_tuple[0], op_batch._mask) trace.append(x) if terminate: break # Backward loop reversed_dependencies = util.reverse_dependencies(program_batch._dependencies) first_attention_state = (BatchAttentionState(trace[-1]._name, device, trace[-1]._state, set_zeros=True).to(world.dtype), ) if not isinstance(trace[-1], (tuple, list)) else \ tuple([BatchAttentionState(att._name, device, att._state, set_zeros=True).to(world.dtype) for att in trace[-1]]) trace = [None for _ in range(len(program_batch._op_batch_list))] for i, op_batch in reversed(list(enumerate(program_batch._op_batch_list))): if len(reversed_dependencies[i]) == 1: temp = trace[reversed_dependencies[i][0]] if isinstance(temp, (tuple, list)): input_tuple = (temp[1],) if i == len(program_batch._op_batch_list) - 2 else (temp[0],) else: input_tuple = (temp,) else: input_tuple = first_attention_state x, terminate = self._transform_attention(op_batch._op_id, False, world, op_batch, input_tuple, i == 0, is_training) # Gate the unaffected questions # print(op_batch._op_name) if len(program_batch._dependencies[i]) > 0 and op_batch._mask is not None and isinstance(x, BatchAttentionState) and i != len(program_batch._op_batch_list) - 1: x = x.gate(input_tuple[0], op_batch._mask) trace[i] = x if terminate: break # if self._atm is not None: # attention_transfer = self._atm(program_batch) # Execution loop trace = [] for i, op_batch in enumerate(program_batch._op_batch_list): # print(op_batch._op_name) if len(program_batch._dependencies[i]) > 1: input_tuple = tuple(itemgetter(*program_batch._dependencies[i])(trace)) elif len(program_batch._dependencies[i]) == 1: input_tuple = (trace[program_batch._dependencies[i][0]],) else: input_tuple = () x, terminate = self._execute(op_batch._op_id, world, op_batch, input_tuple, i == len(program_batch._op_batch_list) - 1, is_training) # # Apply the transfer function if available # if self._atm is not None and isinstance(x, BatchVariableSet): # alpha = attention_transfer[i, :, 0].unsqueeze(1) # beta = attention_transfer[i, :, 1].unsqueeze(1) # temp = alpha * x._log_attention # x._log_attention = temp - util.safe_log((beta * util.log_not(x._log_attention)).exp() + temp.exp()) # Gate the unaffected questions if isinstance(x, BatchVariableSet) and len(input_tuple) > 0 and op_batch._mask is not None: x = x.gate(input_tuple[0], op_batch._mask) trace.append(x) if terminate: break result = trace[-1] if len(trace) > 0 else None all_results.append(result) all_traces.append(trace) result = gather_results(all_results, device, util.is_cuda(device)) if return_trace: return result, all_traces return result
49.896739
216
0.615401
import torch import torch.nn as nn import os from operator import itemgetter from nsvqa.nn.interpreter import util from nsvqa.nn.interpreter.batch_base_types import BatchWorld, BatchVariableSet, BatchAttentionState from nsvqa.nn.interpreter.data_parallel import gather_results class BatchInterpreterBase(nn.Module): def __init__(self, name, oracle, featurizer=None, attention_transfer_state_dim=0, apply_modulation_everywhere=True, cached=False, visual_rule_learner=None, calibrator=None): super(BatchInterpreterBase, self).__init__() self._featurizer = featurizer self._oracle = oracle self._name = name self._global_step = nn.Parameter(torch.tensor([0], dtype=torch.float), requires_grad=False) self._has_modulator = False self._attention_transfer_state_dim = attention_transfer_state_dim self._apply_modulation_everywhere = apply_modulation_everywhere self._cached = cached self._visual_rule_learner = visual_rule_learner self._calibrator = calibrator def _execute(self, op_id, world, operator_batch, input_tuple, is_terminal, is_training): pass def _transform_attention(self, op_id, is_forward, world, operator_batch, input_tuple, is_terminal, is_training): pass def parameter_count(self): return sum(p.numel() for p in self.parameters() if p.requires_grad) def save(self, export_path_base): torch.save(self.state_dict(), os.path.join(export_path_base, self._name)) def load(self, import_path_base): self.load_state_dict(torch.load(os.path.join(import_path_base, self._name)), strict=False) def build_scene(self, device, object_features, batch_index, meta_data): if self._featurizer is not None: features = self._featurizer.featurize_scene(device, object_features, batch_index, meta_data) attribute_features = features['attribute_features'] relation_features = features['relation_features'] object_num = features['object_num'] if self._cached: attribute_features, relation_features['features'] = self._oracle.compute_all_log_likelihood_2(attribute_features, relation_features['features']) if self._calibrator is not None: attribute_features[:, self._oracle._ontology._attribute_index], relation_features = self._calibrator(attribute_features[:, self._oracle._ontology._attribute_index], relation_features) if self._visual_rule_learner is not None: relation_features['object_num'] = object_num attribute_features[:, self._oracle._ontology._attribute_index], relation_features = self._visual_rule_learner(attribute_features[:, self._oracle._ontology._attribute_index], relation_features) else: object_num = object_features.size()[0] attribute_features = object_features.view(object_num, -1) arg1 = attribute_features.repeat(1, object_num).view(object_num**2, -1) arg2 = attribute_features.repeat(self._object_num, 1) relation_features = torch.cat([arg1, arg2], dim=1) return BatchWorld(device, object_num, attribute_features, relation_features, batch_index, meta_data, \ attention_transfer_state_dim=self._attention_transfer_state_dim).to(object_features.dtype) def forward(self, program_batch_list, is_training, return_trace=False, modulator_switch=True): all_traces = [] all_results = [] device = program_batch_list[0].device for program_batch in program_batch_list: world = self.build_scene(program_batch.device, program_batch._object_features, program_batch._object_batch_index, program_batch._meta_data) if self._has_modulator and modulator_switch: if not self._apply_modulation_everywhere: for i in range(len(program_batch._op_batch_list) - 1): program_batch._op_batch_list._op_id += 'n' trace = [] for i, op_batch in enumerate(program_batch._op_batch_list): if len(program_batch._dependencies[i]) > 1: input_tuple = tuple(itemgetter(*program_batch._dependencies[i])(trace)) elif len(program_batch._dependencies[i]) == 1: input_tuple = (trace[program_batch._dependencies[i][0]],) else: input_tuple = (None,) x, terminate = self._transform_attention(op_batch._op_id, True, world, op_batch, input_tuple, i == len(program_batch._op_batch_list) - 1, is_training) if i < len(program_batch._op_batch_list) - 1 and input_tuple[0] is not None and op_batch._mask is not None: x = x.gate(input_tuple[0], op_batch._mask) trace.append(x) if terminate: break reversed_dependencies = util.reverse_dependencies(program_batch._dependencies) first_attention_state = (BatchAttentionState(trace[-1]._name, device, trace[-1]._state, set_zeros=True).to(world.dtype), ) if not isinstance(trace[-1], (tuple, list)) else \ tuple([BatchAttentionState(att._name, device, att._state, set_zeros=True).to(world.dtype) for att in trace[-1]]) trace = [None for _ in range(len(program_batch._op_batch_list))] for i, op_batch in reversed(list(enumerate(program_batch._op_batch_list))): if len(reversed_dependencies[i]) == 1: temp = trace[reversed_dependencies[i][0]] if isinstance(temp, (tuple, list)): input_tuple = (temp[1],) if i == len(program_batch._op_batch_list) - 2 else (temp[0],) else: input_tuple = (temp,) else: input_tuple = first_attention_state x, terminate = self._transform_attention(op_batch._op_id, False, world, op_batch, input_tuple, i == 0, is_training) if len(program_batch._dependencies[i]) > 0 and op_batch._mask is not None and isinstance(x, BatchAttentionState) and i != len(program_batch._op_batch_list) - 1: x = x.gate(input_tuple[0], op_batch._mask) trace[i] = x if terminate: break trace = [] for i, op_batch in enumerate(program_batch._op_batch_list): if len(program_batch._dependencies[i]) > 1: input_tuple = tuple(itemgetter(*program_batch._dependencies[i])(trace)) elif len(program_batch._dependencies[i]) == 1: input_tuple = (trace[program_batch._dependencies[i][0]],) else: input_tuple = () x, terminate = self._execute(op_batch._op_id, world, op_batch, input_tuple, i == len(program_batch._op_batch_list) - 1, is_training) if isinstance(x, BatchVariableSet) and len(input_tuple) > 0 and op_batch._mask is not None: x = x.gate(input_tuple[0], op_batch._mask) trace.append(x) if terminate: break result = trace[-1] if len(trace) > 0 else None all_results.append(result) all_traces.append(trace) result = gather_results(all_results, device, util.is_cuda(device)) if return_trace: return result, all_traces return result
true
true
1c33f62a8d3491e291306562ed3c4d021d62575a
36,400
py
Python
tests/test_transforms.py
weecology/albumentations
cc8fbb6e2fcc4f6a4c87a29b6b0784391b0e2db4
[ "MIT" ]
1
2021-05-22T09:19:31.000Z
2021-05-22T09:19:31.000Z
tests/test_transforms.py
weecology/albumentations
cc8fbb6e2fcc4f6a4c87a29b6b0784391b0e2db4
[ "MIT" ]
null
null
null
tests/test_transforms.py
weecology/albumentations
cc8fbb6e2fcc4f6a4c87a29b6b0784391b0e2db4
[ "MIT" ]
null
null
null
from functools import partial import cv2 import numpy as np import pytest import random import albumentations as A import albumentations.augmentations.functional as F import albumentations.augmentations.geometric.functional as FGeometric from torchvision.transforms import ColorJitter from PIL import Image def set_seed(seed=0): random.seed(seed) np.random.seed(seed) def test_transpose_both_image_and_mask(): image = np.ones((8, 6, 3)) mask = np.ones((8, 6)) augmentation = A.Transpose(p=1) augmented = augmentation(image=image, mask=mask) assert augmented["image"].shape == (6, 8, 3) assert augmented["mask"].shape == (6, 8) @pytest.mark.parametrize("interpolation", [cv2.INTER_NEAREST, cv2.INTER_LINEAR, cv2.INTER_CUBIC]) def test_safe_rotate_interpolation(interpolation): image = np.random.randint(low=0, high=256, size=(100, 100, 3), dtype=np.uint8) mask = np.random.randint(low=0, high=2, size=(100, 100), dtype=np.uint8) aug = A.SafeRotate(limit=(45, 45), interpolation=interpolation, p=1) data = aug(image=image, mask=mask) expected_image = FGeometric.safe_rotate(image, 45, interpolation=interpolation, border_mode=cv2.BORDER_REFLECT_101) expected_mask = FGeometric.safe_rotate( mask, 45, interpolation=cv2.INTER_NEAREST, border_mode=cv2.BORDER_REFLECT_101 ) assert np.array_equal(data["image"], expected_image) assert np.array_equal(data["mask"], expected_mask) @pytest.mark.parametrize("interpolation", [cv2.INTER_NEAREST, cv2.INTER_LINEAR, cv2.INTER_CUBIC]) def test_rotate_interpolation(interpolation): image = np.random.randint(low=0, high=256, size=(100, 100, 3), dtype=np.uint8) mask = np.random.randint(low=0, high=2, size=(100, 100), dtype=np.uint8) aug = A.Rotate(limit=(45, 45), interpolation=interpolation, p=1) data = aug(image=image, mask=mask) expected_image = FGeometric.rotate(image, 45, interpolation=interpolation, border_mode=cv2.BORDER_REFLECT_101) expected_mask = FGeometric.rotate(mask, 45, interpolation=cv2.INTER_NEAREST, border_mode=cv2.BORDER_REFLECT_101) assert np.array_equal(data["image"], expected_image) assert np.array_equal(data["mask"], expected_mask) @pytest.mark.parametrize("interpolation", [cv2.INTER_NEAREST, cv2.INTER_LINEAR, cv2.INTER_CUBIC]) def test_shift_scale_rotate_interpolation(interpolation): image = np.random.randint(low=0, high=256, size=(100, 100, 3), dtype=np.uint8) mask = np.random.randint(low=0, high=2, size=(100, 100), dtype=np.uint8) aug = A.ShiftScaleRotate( shift_limit=(0.2, 0.2), scale_limit=(1.1, 1.1), rotate_limit=(45, 45), interpolation=interpolation, p=1 ) data = aug(image=image, mask=mask) expected_image = FGeometric.shift_scale_rotate( image, angle=45, scale=2.1, dx=0.2, dy=0.2, interpolation=interpolation, border_mode=cv2.BORDER_REFLECT_101 ) expected_mask = FGeometric.shift_scale_rotate( mask, angle=45, scale=2.1, dx=0.2, dy=0.2, interpolation=cv2.INTER_NEAREST, border_mode=cv2.BORDER_REFLECT_101 ) assert np.array_equal(data["image"], expected_image) assert np.array_equal(data["mask"], expected_mask) @pytest.mark.parametrize("interpolation", [cv2.INTER_NEAREST, cv2.INTER_LINEAR, cv2.INTER_CUBIC]) def test_optical_distortion_interpolation(interpolation): image = np.random.randint(low=0, high=256, size=(100, 100, 3), dtype=np.uint8) mask = np.random.randint(low=0, high=2, size=(100, 100), dtype=np.uint8) aug = A.OpticalDistortion(distort_limit=(0.05, 0.05), shift_limit=(0, 0), interpolation=interpolation, p=1) data = aug(image=image, mask=mask) expected_image = F.optical_distortion( image, k=0.05, dx=0, dy=0, interpolation=interpolation, border_mode=cv2.BORDER_REFLECT_101 ) expected_mask = F.optical_distortion( mask, k=0.05, dx=0, dy=0, interpolation=cv2.INTER_NEAREST, border_mode=cv2.BORDER_REFLECT_101 ) assert np.array_equal(data["image"], expected_image) assert np.array_equal(data["mask"], expected_mask) @pytest.mark.parametrize("interpolation", [cv2.INTER_NEAREST, cv2.INTER_LINEAR, cv2.INTER_CUBIC]) def test_grid_distortion_interpolation(interpolation): image = np.random.randint(low=0, high=256, size=(100, 100, 3), dtype=np.uint8) mask = np.random.randint(low=0, high=2, size=(100, 100), dtype=np.uint8) aug = A.GridDistortion(num_steps=1, distort_limit=(0.3, 0.3), interpolation=interpolation, p=1) data = aug(image=image, mask=mask) expected_image = F.grid_distortion( image, num_steps=1, xsteps=[1.3], ysteps=[1.3], interpolation=interpolation, border_mode=cv2.BORDER_REFLECT_101 ) expected_mask = F.grid_distortion( mask, num_steps=1, xsteps=[1.3], ysteps=[1.3], interpolation=cv2.INTER_NEAREST, border_mode=cv2.BORDER_REFLECT_101, ) assert np.array_equal(data["image"], expected_image) assert np.array_equal(data["mask"], expected_mask) @pytest.mark.parametrize("size", [17, 21, 33]) def test_grid_distortion_steps(size): image = np.random.rand(size, size, 3) aug = A.GridDistortion(num_steps=size - 2, p=1) data = aug(image=image) assert np.array_equal(data["image"].shape, (size, size, 3)) @pytest.mark.parametrize("interpolation", [cv2.INTER_NEAREST, cv2.INTER_LINEAR, cv2.INTER_CUBIC]) def test_elastic_transform_interpolation(monkeypatch, interpolation): image = np.random.randint(low=0, high=256, size=(100, 100, 3), dtype=np.uint8) mask = np.random.randint(low=0, high=2, size=(100, 100), dtype=np.uint8) monkeypatch.setattr( "albumentations.augmentations.geometric.ElasticTransform.get_params", lambda *_: {"random_state": 1111} ) aug = A.ElasticTransform(alpha=1, sigma=50, alpha_affine=50, interpolation=interpolation, p=1) data = aug(image=image, mask=mask) expected_image = FGeometric.elastic_transform( image, alpha=1, sigma=50, alpha_affine=50, interpolation=interpolation, border_mode=cv2.BORDER_REFLECT_101, random_state=np.random.RandomState(1111), ) expected_mask = FGeometric.elastic_transform( mask, alpha=1, sigma=50, alpha_affine=50, interpolation=cv2.INTER_NEAREST, border_mode=cv2.BORDER_REFLECT_101, random_state=np.random.RandomState(1111), ) assert np.array_equal(data["image"], expected_image) assert np.array_equal(data["mask"], expected_mask) @pytest.mark.parametrize( ["augmentation_cls", "params"], [ [A.ElasticTransform, {}], [A.GridDistortion, {}], [A.ShiftScaleRotate, {"rotate_limit": 45}], [A.RandomScale, {"scale_limit": 0.5}], [A.RandomSizedCrop, {"min_max_height": (80, 90), "height": 100, "width": 100}], [A.LongestMaxSize, {"max_size": 50}], [A.Rotate, {}], [A.SafeRotate, {}], [A.OpticalDistortion, {}], [A.IAAAffine, {"scale": 1.5}], [A.IAAPiecewiseAffine, {"scale": 1.5}], [A.IAAPerspective, {}], [A.GlassBlur, {}], [A.Perspective, {}], [A.Affine, {}], [A.PiecewiseAffine, {}], ], ) def test_binary_mask_interpolation(augmentation_cls, params): """Checks whether transformations based on DualTransform does not introduce a mask interpolation artifacts""" aug = augmentation_cls(p=1, **params) image = np.random.randint(low=0, high=256, size=(100, 100, 3), dtype=np.uint8) mask = np.random.randint(low=0, high=2, size=(100, 100), dtype=np.uint8) data = aug(image=image, mask=mask) assert np.array_equal(np.unique(data["mask"]), np.array([0, 1])) @pytest.mark.parametrize( ["augmentation_cls", "params"], [ [A.ElasticTransform, {}], [A.GridDistortion, {}], [A.ShiftScaleRotate, {"rotate_limit": 45}], [A.RandomScale, {"scale_limit": 0.5}], [A.RandomSizedCrop, {"min_max_height": (80, 90), "height": 100, "width": 100}], [A.LongestMaxSize, {"max_size": 50}], [A.Rotate, {}], [A.SafeRotate, {}], [A.Resize, {"height": 80, "width": 90}], [A.Resize, {"height": 120, "width": 130}], [A.OpticalDistortion, {}], [A.GlassBlur, {}], [A.Perspective, {}], [A.Affine, {}], [A.PiecewiseAffine, {}], ], ) def test_semantic_mask_interpolation(augmentation_cls, params): """Checks whether transformations based on DualTransform does not introduce a mask interpolation artifacts. Note: IAAAffine, IAAPiecewiseAffine, IAAPerspective does not properly operate if mask has values other than {0;1} """ aug = augmentation_cls(p=1, **params) image = np.random.randint(low=0, high=256, size=(100, 100, 3), dtype=np.uint8) mask = np.random.randint(low=0, high=4, size=(100, 100), dtype=np.uint8) * 64 data = aug(image=image, mask=mask) assert np.array_equal(np.unique(data["mask"]), np.array([0, 64, 128, 192])) def __test_multiprocessing_support_proc(args): x, transform = args return transform(image=x) @pytest.mark.parametrize( ["augmentation_cls", "params"], [ [A.ElasticTransform, {}], [A.GridDistortion, {}], [A.ShiftScaleRotate, {"rotate_limit": 45}], [A.RandomScale, {"scale_limit": 0.5}], [A.RandomSizedCrop, {"min_max_height": (80, 90), "height": 100, "width": 100}], [A.LongestMaxSize, {"max_size": 50}], [A.Rotate, {}], [A.SafeRotate, {}], [A.OpticalDistortion, {}], [A.IAAAffine, {"scale": 1.5}], [A.IAAPiecewiseAffine, {"scale": 1.5}], [A.IAAPerspective, {}], [A.Sharpen, {}], [A.FancyPCA, {}], [A.GlassBlur, {}], [A.Perspective, {}], [A.Affine, {}], [A.PiecewiseAffine, {}], ], ) def test_multiprocessing_support(augmentation_cls, params, multiprocessing_context): """Checks whether we can use augmentations in multiprocessing environments""" aug = augmentation_cls(p=1, **params) image = np.random.randint(low=0, high=256, size=(100, 100, 3), dtype=np.uint8) pool = multiprocessing_context.Pool(8) pool.map(__test_multiprocessing_support_proc, map(lambda x: (x, aug), [image] * 100)) pool.close() pool.join() def test_force_apply(): """ Unit test for https://github.com/albumentations-team/albumentations/issues/189 """ aug = A.Compose( [ A.OneOrOther( A.Compose( [ A.RandomSizedCrop(min_max_height=(256, 1025), height=512, width=512, p=1), A.OneOf( [ A.RandomSizedCrop(min_max_height=(256, 512), height=384, width=384, p=0.5), A.RandomSizedCrop(min_max_height=(256, 512), height=512, width=512, p=0.5), ] ), ] ), A.Compose( [ A.RandomSizedCrop(min_max_height=(256, 1025), height=256, width=256, p=1), A.OneOf([A.HueSaturationValue(p=0.5), A.RGBShift(p=0.7)], p=1), ] ), ), A.HorizontalFlip(p=1), A.RandomBrightnessContrast(p=0.5), ] ) res = aug(image=np.zeros((1248, 1248, 3), dtype=np.uint8)) assert res["image"].shape[0] in (256, 384, 512) assert res["image"].shape[1] in (256, 384, 512) @pytest.mark.parametrize( ["augmentation_cls", "params"], [ [A.ChannelShuffle, {}], [A.GaussNoise, {}], [A.Cutout, {}], [A.CoarseDropout, {}], [A.ImageCompression, {}], [A.HueSaturationValue, {}], [A.RGBShift, {}], [A.RandomBrightnessContrast, {}], [A.Blur, {}], [A.MotionBlur, {}], [A.MedianBlur, {}], [A.CLAHE, {}], [A.InvertImg, {}], [A.RandomGamma, {}], [A.ToGray, {}], [A.VerticalFlip, {}], [A.HorizontalFlip, {}], [A.Flip, {}], [A.Transpose, {}], [A.RandomRotate90, {}], [A.Rotate, {}], [A.SafeRotate, {}], [A.OpticalDistortion, {}], [A.GridDistortion, {}], [A.ElasticTransform, {}], [A.Normalize, {}], [A.ToFloat, {}], [A.FromFloat, {}], [A.ChannelDropout, {}], [A.Solarize, {}], [A.Posterize, {}], [A.Equalize, {}], [A.MultiplicativeNoise, {}], [A.FancyPCA, {}], [A.GlassBlur, {}], [A.GridDropout, {}], [A.ColorJitter, {}], [A.Perspective, {}], [A.Sharpen, {"alpha": [0.2, 0.2], "lightness": [0.5, 0.5]}], ], ) def test_additional_targets_for_image_only(augmentation_cls, params): aug = A.Compose([augmentation_cls(always_apply=True, **params)], additional_targets={"image2": "image"}) for _i in range(10): image1 = np.random.randint(low=0, high=256, size=(100, 100, 3), dtype=np.uint8) image2 = image1.copy() res = aug(image=image1, image2=image2) aug1 = res["image"] aug2 = res["image2"] assert np.array_equal(aug1, aug2) def test_lambda_transform(): def negate_image(image, **kwargs): return -image def one_hot_mask(mask, num_channels, **kwargs): new_mask = np.eye(num_channels, dtype=np.uint8)[mask] return new_mask def vflip_bbox(bbox, **kwargs): return F.bbox_vflip(bbox, **kwargs) def vflip_keypoint(keypoint, **kwargs): return F.keypoint_vflip(keypoint, **kwargs) aug = A.Lambda( image=negate_image, mask=partial(one_hot_mask, num_channels=16), bbox=vflip_bbox, keypoint=vflip_keypoint, p=1 ) output = aug( image=np.ones((10, 10, 3), dtype=np.float32), mask=np.tile(np.arange(0, 10), (10, 1)), bboxes=[(10, 15, 25, 35)], keypoints=[(20, 30, 40, 50)], ) assert (output["image"] < 0).all() assert output["mask"].shape[2] == 16 # num_channels assert output["bboxes"] == [F.bbox_vflip((10, 15, 25, 35), 10, 10)] assert output["keypoints"] == [F.keypoint_vflip((20, 30, 40, 50), 10, 10)] def test_channel_droput(): img = np.ones((10, 10, 3), dtype=np.float32) aug = A.ChannelDropout(channel_drop_range=(1, 1), always_apply=True) # Drop one channel transformed = aug(image=img)["image"] assert sum(transformed[:, :, c].max() for c in range(img.shape[2])) == 2 aug = A.ChannelDropout(channel_drop_range=(2, 2), always_apply=True) # Drop two channels transformed = aug(image=img)["image"] assert sum(transformed[:, :, c].max() for c in range(img.shape[2])) == 1 def test_equalize(): aug = A.Equalize(p=1) img = np.random.randint(0, 256, 256 * 256 * 3, np.uint8).reshape((256, 256, 3)) a = aug(image=img)["image"] b = F.equalize(img) assert np.all(a == b) mask = np.random.randint(0, 2, 256 * 256, np.uint8).reshape((256, 256)) aug = A.Equalize(mask=mask, p=1) a = aug(image=img)["image"] b = F.equalize(img, mask=mask) assert np.all(a == b) def mask_func(image, test): # skipcq: PYL-W0613 return mask aug = A.Equalize(mask=mask_func, mask_params=["test"], p=1) assert np.all(aug(image=img, test=mask)["image"] == F.equalize(img, mask=mask)) def test_crop_non_empty_mask(): def _test_crop(mask, crop, aug, n=1): for _ in range(n): augmented = aug(image=mask, mask=mask) np.testing.assert_array_equal(augmented["image"], crop) np.testing.assert_array_equal(augmented["mask"], crop) # test general case mask_1 = np.zeros([10, 10]) mask_1[0, 0] = 1 crop_1 = np.array([[1]]) aug_1 = A.CropNonEmptyMaskIfExists(1, 1) # test empty mask mask_2 = np.zeros([10, 10]) crop_2 = np.array([[0]]) aug_2 = A.CropNonEmptyMaskIfExists(1, 1) # test ignore values mask_3 = np.ones([2, 2]) mask_3[0, 0] = 2 crop_3 = np.array([[2]]) aug_3 = A.CropNonEmptyMaskIfExists(1, 1, ignore_values=[1]) # test ignore channels mask_4 = np.zeros([2, 2, 2]) mask_4[0, 0, 0] = 1 mask_4[1, 1, 1] = 2 crop_4 = np.array([[[1, 0]]]) aug_4 = A.CropNonEmptyMaskIfExists(1, 1, ignore_channels=[1]) # test full size crop mask_5 = np.random.random([10, 10, 3]) crop_5 = mask_5 aug_5 = A.CropNonEmptyMaskIfExists(10, 10) mask_6 = np.zeros([10, 10, 3]) mask_6[0, 0, 0] = 0 crop_6 = mask_6 aug_6 = A.CropNonEmptyMaskIfExists(10, 10, ignore_values=[1]) _test_crop(mask_1, crop_1, aug_1, n=1) _test_crop(mask_2, crop_2, aug_2, n=1) _test_crop(mask_3, crop_3, aug_3, n=5) _test_crop(mask_4, crop_4, aug_4, n=5) _test_crop(mask_5, crop_5, aug_5, n=1) _test_crop(mask_6, crop_6, aug_6, n=10) @pytest.mark.parametrize("interpolation", [cv2.INTER_NEAREST, cv2.INTER_LINEAR, cv2.INTER_CUBIC]) def test_downscale(interpolation): img_float = np.random.rand(100, 100, 3) img_uint = (img_float * 255).astype("uint8") aug = A.Downscale(scale_min=0.5, scale_max=0.5, interpolation=interpolation, always_apply=True) for img in (img_float, img_uint): transformed = aug(image=img)["image"] func_applied = F.downscale(img, scale=0.5, interpolation=interpolation) np.testing.assert_almost_equal(transformed, func_applied) def test_crop_keypoints(): image = np.random.randint(0, 256, (100, 100), np.uint8) keypoints = [(50, 50, 0, 0)] aug = A.Crop(0, 0, 80, 80, p=1) result = aug(image=image, keypoints=keypoints) assert result["keypoints"] == keypoints aug = A.Crop(50, 50, 100, 100, p=1) result = aug(image=image, keypoints=keypoints) assert result["keypoints"] == [(0, 0, 0, 0)] def test_longest_max_size_keypoints(): img = np.random.randint(0, 256, [50, 10], np.uint8) keypoints = [(9, 5, 0, 0)] aug = A.LongestMaxSize(max_size=100, p=1) result = aug(image=img, keypoints=keypoints) assert result["keypoints"] == [(18, 10, 0, 0)] aug = A.LongestMaxSize(max_size=5, p=1) result = aug(image=img, keypoints=keypoints) assert result["keypoints"] == [(0.9, 0.5, 0, 0)] aug = A.LongestMaxSize(max_size=50, p=1) result = aug(image=img, keypoints=keypoints) assert result["keypoints"] == [(9, 5, 0, 0)] def test_smallest_max_size_keypoints(): img = np.random.randint(0, 256, [50, 10], np.uint8) keypoints = [(9, 5, 0, 0)] aug = A.SmallestMaxSize(max_size=100, p=1) result = aug(image=img, keypoints=keypoints) assert result["keypoints"] == [(90, 50, 0, 0)] aug = A.SmallestMaxSize(max_size=5, p=1) result = aug(image=img, keypoints=keypoints) assert result["keypoints"] == [(4.5, 2.5, 0, 0)] aug = A.SmallestMaxSize(max_size=10, p=1) result = aug(image=img, keypoints=keypoints) assert result["keypoints"] == [(9, 5, 0, 0)] def test_resize_keypoints(): img = np.random.randint(0, 256, [50, 10], np.uint8) keypoints = [(9, 5, 0, 0)] aug = A.Resize(height=100, width=5, p=1) result = aug(image=img, keypoints=keypoints) assert result["keypoints"] == [(4.5, 10, 0, 0)] aug = A.Resize(height=50, width=10, p=1) result = aug(image=img, keypoints=keypoints) assert result["keypoints"] == [(9, 5, 0, 0)] @pytest.mark.parametrize( "image", [ np.random.randint(0, 256, [256, 320], np.uint8), np.random.random([256, 320]).astype(np.float32), np.random.randint(0, 256, [256, 320, 1], np.uint8), np.random.random([256, 320, 1]).astype(np.float32), ], ) def test_multiplicative_noise_grayscale(image): m = 0.5 aug = A.MultiplicativeNoise(m, p=1) result = aug(image=image)["image"] image = F.clip(image * m, image.dtype, F.MAX_VALUES_BY_DTYPE[image.dtype]) assert np.allclose(image, result) aug = A.MultiplicativeNoise(elementwise=True, p=1) params = aug.get_params_dependent_on_targets({"image": image}) mul = params["multiplier"] assert mul.shape == image.shape result = aug.apply(image, mul) dtype = image.dtype image = image.astype(np.float32) * mul image = F.clip(image, dtype, F.MAX_VALUES_BY_DTYPE[dtype]) assert np.allclose(image, result) @pytest.mark.parametrize( "image", [np.random.randint(0, 256, [256, 320, 3], np.uint8), np.random.random([256, 320, 3]).astype(np.float32)] ) def test_multiplicative_noise_rgb(image): dtype = image.dtype m = 0.5 aug = A.MultiplicativeNoise(m, p=1) result = aug(image=image)["image"] image = F.clip(image * m, dtype, F.MAX_VALUES_BY_DTYPE[dtype]) assert np.allclose(image, result) aug = A.MultiplicativeNoise(elementwise=True, p=1) params = aug.get_params_dependent_on_targets({"image": image}) mul = params["multiplier"] assert mul.shape == image.shape[:2] + (1,) result = aug.apply(image, mul) image = F.clip(image.astype(np.float32) * mul, dtype, F.MAX_VALUES_BY_DTYPE[dtype]) assert np.allclose(image, result) aug = A.MultiplicativeNoise(per_channel=True, p=1) params = aug.get_params_dependent_on_targets({"image": image}) mul = params["multiplier"] assert mul.shape == (3,) result = aug.apply(image, mul) image = F.clip(image.astype(np.float32) * mul, dtype, F.MAX_VALUES_BY_DTYPE[dtype]) assert np.allclose(image, result) aug = A.MultiplicativeNoise(elementwise=True, per_channel=True, p=1) params = aug.get_params_dependent_on_targets({"image": image}) mul = params["multiplier"] assert mul.shape == image.shape result = aug.apply(image, mul) image = F.clip(image.astype(np.float32) * mul, image.dtype, F.MAX_VALUES_BY_DTYPE[image.dtype]) assert np.allclose(image, result) def test_mask_dropout(): # In this case we have mask with all ones, so MaskDropout wipe entire mask and image img = np.random.randint(0, 256, [50, 10], np.uint8) mask = np.ones([50, 10], dtype=np.long) aug = A.MaskDropout(p=1) result = aug(image=img, mask=mask) assert np.all(result["image"] == 0) assert np.all(result["mask"] == 0) # In this case we have mask with zeros , so MaskDropout will make no changes img = np.random.randint(0, 256, [50, 10], np.uint8) mask = np.zeros([50, 10], dtype=np.long) aug = A.MaskDropout(p=1) result = aug(image=img, mask=mask) assert np.all(result["image"] == img) assert np.all(result["mask"] == 0) @pytest.mark.parametrize( "image", [np.random.randint(0, 256, [256, 320, 3], np.uint8), np.random.random([256, 320, 3]).astype(np.float32)] ) def test_grid_dropout_mask(image): mask = np.ones([256, 320], dtype=np.uint8) aug = A.GridDropout(p=1, mask_fill_value=0) result = aug(image=image, mask=mask) # with mask on ones and fill_value = 0 the sum of pixels is smaller assert result["image"].sum() < image.sum() assert result["image"].shape == image.shape assert result["mask"].sum() < mask.sum() assert result["mask"].shape == mask.shape # with mask of zeros and fill_value = 0 mask should not change mask = np.zeros([256, 320], dtype=np.uint8) aug = A.GridDropout(p=1, mask_fill_value=0) result = aug(image=image, mask=mask) assert result["image"].sum() < image.sum() assert np.all(result["mask"] == 0) # with mask mask_fill_value=100, mask sum is larger mask = np.random.randint(0, 10, [256, 320], np.uint8) aug = A.GridDropout(p=1, mask_fill_value=100) result = aug(image=image, mask=mask) assert result["image"].sum() < image.sum() assert result["mask"].sum() > mask.sum() # with mask mask_fill_value=None, mask is not changed mask = np.ones([256, 320], dtype=np.uint8) aug = A.GridDropout(p=1, mask_fill_value=None) result = aug(image=image, mask=mask) assert result["image"].sum() < image.sum() assert result["mask"].sum() == mask.sum() @pytest.mark.parametrize( ["ratio", "holes_number_x", "holes_number_y", "unit_size_min", "unit_size_max", "shift_x", "shift_y"], [ (0.00001, 10, 10, 100, 100, 50, 50), (0.9, 100, None, 200, None, 0, 0), (0.4556, 10, 20, None, 200, 0, 0), (0.00004, None, None, 2, 100, None, None), ], ) def test_grid_dropout_params(ratio, holes_number_x, holes_number_y, unit_size_min, unit_size_max, shift_x, shift_y): img = np.random.randint(0, 256, [256, 320], np.uint8) aug = A.GridDropout( ratio=ratio, unit_size_min=unit_size_min, unit_size_max=unit_size_max, holes_number_x=holes_number_x, holes_number_y=holes_number_y, shift_x=shift_x, shift_y=shift_y, random_offset=False, fill_value=0, p=1, ) result = aug(image=img)["image"] # with fill_value = 0 the sum of pixels is smaller assert result.sum() < img.sum() assert result.shape == img.shape params = aug.get_params_dependent_on_targets({"image": img}) holes = params["holes"] assert len(holes[0]) == 4 # check grid offsets if shift_x: assert holes[0][0] == shift_x else: assert holes[0][0] == 0 if shift_y: assert holes[0][1] == shift_y else: assert holes[0][1] == 0 # for grid set with limits if unit_size_min and unit_size_max: assert max(1, unit_size_min * ratio) <= (holes[0][2] - holes[0][0]) <= min(max(1, unit_size_max * ratio), 256) elif holes_number_x and holes_number_y: assert (holes[0][2] - holes[0][0]) == max(1, int(ratio * 320 // holes_number_x)) assert (holes[0][3] - holes[0][1]) == max(1, int(ratio * 256 // holes_number_y)) def test_gauss_noise_incorrect_var_limit_type(): with pytest.raises(TypeError) as exc_info: A.GaussNoise(var_limit={"low": 70, "high": 90}) message = "Expected var_limit type to be one of (int, float, tuple, list), got <class 'dict'>" assert str(exc_info.value) == message @pytest.mark.parametrize( ["blur_limit", "sigma", "result_blur", "result_sigma"], [ [[0, 0], [1, 1], 0, 1], [[1, 1], [0, 0], 1, 0], [[1, 1], [1, 1], 1, 1], [[0, 0], [0, 0], 3, 0], [[0, 3], [0, 0], 3, 0], [[0, 3], [0.1, 0.1], 3, 0.1], ], ) def test_gaus_blur_limits(blur_limit, sigma, result_blur, result_sigma): img = np.zeros([100, 100, 3], dtype=np.uint8) aug = A.Compose([A.GaussianBlur(blur_limit=blur_limit, sigma_limit=sigma, p=1)]) res = aug(image=img)["image"] assert np.allclose(res, F.gaussian_blur(img, result_blur, result_sigma)) @pytest.mark.parametrize( ["brightness", "contrast", "saturation", "hue"], [ [1, 1, 1, 0], [0.123, 1, 1, 0], [1.321, 1, 1, 0], [1, 0.234, 1, 0], [1, 1.432, 1, 0], [1, 1, 0.345, 0], [1, 1, 1.543, 0], ], ) def test_color_jitter(brightness, contrast, saturation, hue): np.random.seed(0) img = np.random.randint(0, 256, [100, 100, 3], dtype=np.uint8) pil_image = Image.fromarray(img) transform = A.Compose( [ A.ColorJitter( brightness=[brightness, brightness], contrast=[contrast, contrast], saturation=[saturation, saturation], hue=[hue, hue], p=1, ) ] ) pil_transform = ColorJitter( brightness=[brightness, brightness], contrast=[contrast, contrast], saturation=[saturation, saturation], hue=[hue, hue], ) res1 = transform(image=img)["image"] res2 = np.array(pil_transform(pil_image)) _max = np.abs(res1.astype(np.int16) - res2.astype(np.int16)).max() assert _max <= 2, "Max: {}".format(_max) @pytest.mark.parametrize( ["brightness", "contrast", "saturation", "hue"], [ [1, 1, 1, 0], [0.123, 1, 1, 0], [1.321, 1, 1, 0], [1, 0.234, 1, 0], [1, 1.432, 1, 0], [1, 1, 0.345, 0], [1, 1, 1.543, 0], [1, 1, 1, 0.456], [1, 1, 1, -0.432], ], ) def test_color_jitter_float_uint8_equal(brightness, contrast, saturation, hue): img = np.random.randint(0, 256, [100, 100, 3], dtype=np.uint8) transform = A.Compose( [ A.ColorJitter( brightness=[brightness, brightness], contrast=[contrast, contrast], saturation=[saturation, saturation], hue=[hue, hue], p=1, ) ] ) res1 = transform(image=img)["image"] res2 = (transform(image=img.astype(np.float32) / 255.0)["image"] * 255).astype(np.uint8) _max = np.abs(res1.astype(np.int16) - res2.astype(np.int16)).max() if hue != 0: assert _max <= 10, "Max: {}".format(_max) else: assert _max <= 2, "Max: {}".format(_max) @pytest.mark.parametrize(["hue", "sat", "val"], [[13, 17, 23], [14, 18, 24], [131, 143, 151], [132, 144, 152]]) def test_hue_saturation_value_float_uint8_equal(hue, sat, val): img = np.random.randint(0, 256, [100, 100, 3], dtype=np.uint8) for i in range(2): sign = 1 if i == 0 else -1 for i in range(4): if i == 0: _hue = hue * sign _sat = 0 _val = 0 elif i == 1: _hue = 0 _sat = sat * sign _val = 0 elif i == 2: _hue = 0 _sat = 0 _val = val * sign else: _hue = hue * sign _sat = sat * sign _val = val * sign t1 = A.Compose( [ A.HueSaturationValue( hue_shift_limit=[_hue, _hue], sat_shift_limit=[_sat, _sat], val_shift_limit=[_val, _val], p=1 ) ] ) t2 = A.Compose( [ A.HueSaturationValue( hue_shift_limit=[_hue / 180 * 360, _hue / 180 * 360], sat_shift_limit=[_sat / 255, _sat / 255], val_shift_limit=[_val / 255, _val / 255], p=1, ) ] ) res1 = t1(image=img)["image"] res2 = (t2(image=img.astype(np.float32) / 255.0)["image"] * 255).astype(np.uint8) _max = np.abs(res1.astype(np.int) - res2).max() assert _max <= 10, "Max value: {}".format(_max) def test_shift_scale_separate_shift_x_shift_y(image, mask): aug = A.ShiftScaleRotate(shift_limit=(0.3, 0.3), shift_limit_y=(0.4, 0.4), scale_limit=0, rotate_limit=0, p=1) data = aug(image=image, mask=mask) expected_image = FGeometric.shift_scale_rotate( image, angle=0, scale=1, dx=0.3, dy=0.4, interpolation=cv2.INTER_LINEAR, border_mode=cv2.BORDER_REFLECT_101 ) expected_mask = FGeometric.shift_scale_rotate( mask, angle=0, scale=1, dx=0.3, dy=0.4, interpolation=cv2.INTER_NEAREST, border_mode=cv2.BORDER_REFLECT_101 ) assert np.array_equal(data["image"], expected_image) assert np.array_equal(data["mask"], expected_mask) @pytest.mark.parametrize(["val_uint8"], [[0], [1], [128], [255]]) def test_glass_blur_float_uint8_diff_less_than_two(val_uint8): x_uint8 = np.zeros((5, 5)).astype(np.uint8) x_uint8[2, 2] = val_uint8 x_float32 = np.zeros((5, 5)).astype(np.float32) x_float32[2, 2] = val_uint8 / 255.0 glassblur = A.GlassBlur(always_apply=True, max_delta=1) np.random.seed(0) blur_uint8 = glassblur(image=x_uint8)["image"] np.random.seed(0) blur_float32 = glassblur(image=x_float32)["image"] # Before comparison, rescale the blur_float32 to [0, 255] diff = np.abs(blur_uint8 - blur_float32 * 255) # The difference between the results of float32 and uint8 will be at most 2. assert np.all(diff <= 2.0) @pytest.mark.parametrize( ["img_dtype", "px", "percent", "pad_mode", "pad_cval", "keep_size"], [ [np.uint8, 10, None, cv2.BORDER_CONSTANT, 0, True], [np.uint8, -10, None, cv2.BORDER_CONSTANT, 0, True], [np.uint8, 10, None, cv2.BORDER_CONSTANT, 0, False], [np.uint8, -10, None, cv2.BORDER_CONSTANT, 0, False], [np.uint8, None, 0.1, cv2.BORDER_CONSTANT, 0, True], [np.uint8, None, -0.1, cv2.BORDER_CONSTANT, 0, True], [np.uint8, None, 0.1, cv2.BORDER_CONSTANT, 0, False], [np.uint8, None, -0.1, cv2.BORDER_CONSTANT, 0, False], [np.float32, None, 0.1, cv2.BORDER_CONSTANT, 0, False], [np.float32, None, -0.1, cv2.BORDER_CONSTANT, 0, False], [np.uint8, None, 0.1, cv2.BORDER_WRAP, 0, False], [np.uint8, None, 0.1, cv2.BORDER_REPLICATE, 0, False], [np.uint8, None, 0.1, cv2.BORDER_REFLECT101, 0, False], ], ) def test_compare_crop_and_pad(img_dtype, px, percent, pad_mode, pad_cval, keep_size): h, w, c = 100, 100, 3 mode_mapping = { cv2.BORDER_CONSTANT: "constant", cv2.BORDER_REPLICATE: "edge", cv2.BORDER_REFLECT101: "reflect", cv2.BORDER_WRAP: "wrap", } pad_mode_iaa = mode_mapping[pad_mode] bbox_params = A.BboxParams(format="pascal_voc") keypoint_params = A.KeypointParams(format="xy", remove_invisible=False) keypoints = np.random.randint(0, min(h, w), [10, 2]) bboxes = [] for i in range(10): x1, y1 = np.random.randint(0, min(h, w) - 2, 2) x2 = np.random.randint(x1 + 1, w - 1) y2 = np.random.randint(y1 + 1, h - 1) bboxes.append([x1, y1, x2, y2, 0]) transform_albu = A.Compose( [ A.CropAndPad( px=px, percent=percent, pad_mode=pad_mode, pad_cval=pad_cval, keep_size=keep_size, p=1, interpolation=cv2.INTER_AREA if (px is not None and px < 0) or (percent is not None and percent < 0) else cv2.INTER_LINEAR, ) ], bbox_params=bbox_params, keypoint_params=keypoint_params, ) transform_iaa = A.Compose( [A.IAACropAndPad(px=px, percent=percent, pad_mode=pad_mode_iaa, pad_cval=pad_cval, keep_size=keep_size, p=1)], bbox_params=bbox_params, keypoint_params=keypoint_params, ) if img_dtype == np.uint8: img = np.random.randint(0, 256, (h, w, c), dtype=np.uint8) else: img = np.random.random((h, w, c)).astype(img_dtype) res_albu = transform_albu(image=img, keypoints=keypoints, bboxes=bboxes) res_iaa = transform_iaa(image=img, keypoints=keypoints, bboxes=bboxes) for key, item in res_albu.items(): if key == "bboxes": bboxes = np.array(res_iaa[key]) h = bboxes[:, 3] - bboxes[:, 1] w = bboxes[:, 2] - bboxes[:, 0] res_iaa[key] = bboxes[(h > 0) & (w > 0)] assert np.allclose(item, res_iaa[key]), f"{key} are not equal" def test_perspective_keep_size(): h, w = 100, 100 img = np.zeros([h, w, 3], dtype=np.uint8) h, w = img.shape[:2] bboxes = [] for _ in range(10): x1 = np.random.randint(0, w - 1) y1 = np.random.randint(0, h - 1) x2 = np.random.randint(x1 + 1, w) y2 = np.random.randint(y1 + 1, h) bboxes.append([x1, y1, x2, y2]) keypoints = [(np.random.randint(0, w), np.random.randint(0, h), np.random.random()) for _ in range(10)] transform_1 = A.Compose( [A.Perspective(keep_size=True, p=1)], keypoint_params=A.KeypointParams("xys"), bbox_params=A.BboxParams("pascal_voc", label_fields=["labels"]), ) transform_2 = A.Compose( [A.Perspective(keep_size=False, p=1), A.Resize(h, w)], keypoint_params=A.KeypointParams("xys"), bbox_params=A.BboxParams("pascal_voc", label_fields=["labels"]), ) set_seed() res_1 = transform_1(image=img, bboxes=bboxes, keypoints=keypoints, labels=[0] * len(bboxes)) set_seed() res_2 = transform_2(image=img, bboxes=bboxes, keypoints=keypoints, labels=[0] * len(bboxes)) assert np.allclose(res_1["bboxes"], res_2["bboxes"]) assert np.allclose(res_1["keypoints"], res_2["keypoints"])
36.291127
119
0.607088
from functools import partial import cv2 import numpy as np import pytest import random import albumentations as A import albumentations.augmentations.functional as F import albumentations.augmentations.geometric.functional as FGeometric from torchvision.transforms import ColorJitter from PIL import Image def set_seed(seed=0): random.seed(seed) np.random.seed(seed) def test_transpose_both_image_and_mask(): image = np.ones((8, 6, 3)) mask = np.ones((8, 6)) augmentation = A.Transpose(p=1) augmented = augmentation(image=image, mask=mask) assert augmented["image"].shape == (6, 8, 3) assert augmented["mask"].shape == (6, 8) @pytest.mark.parametrize("interpolation", [cv2.INTER_NEAREST, cv2.INTER_LINEAR, cv2.INTER_CUBIC]) def test_safe_rotate_interpolation(interpolation): image = np.random.randint(low=0, high=256, size=(100, 100, 3), dtype=np.uint8) mask = np.random.randint(low=0, high=2, size=(100, 100), dtype=np.uint8) aug = A.SafeRotate(limit=(45, 45), interpolation=interpolation, p=1) data = aug(image=image, mask=mask) expected_image = FGeometric.safe_rotate(image, 45, interpolation=interpolation, border_mode=cv2.BORDER_REFLECT_101) expected_mask = FGeometric.safe_rotate( mask, 45, interpolation=cv2.INTER_NEAREST, border_mode=cv2.BORDER_REFLECT_101 ) assert np.array_equal(data["image"], expected_image) assert np.array_equal(data["mask"], expected_mask) @pytest.mark.parametrize("interpolation", [cv2.INTER_NEAREST, cv2.INTER_LINEAR, cv2.INTER_CUBIC]) def test_rotate_interpolation(interpolation): image = np.random.randint(low=0, high=256, size=(100, 100, 3), dtype=np.uint8) mask = np.random.randint(low=0, high=2, size=(100, 100), dtype=np.uint8) aug = A.Rotate(limit=(45, 45), interpolation=interpolation, p=1) data = aug(image=image, mask=mask) expected_image = FGeometric.rotate(image, 45, interpolation=interpolation, border_mode=cv2.BORDER_REFLECT_101) expected_mask = FGeometric.rotate(mask, 45, interpolation=cv2.INTER_NEAREST, border_mode=cv2.BORDER_REFLECT_101) assert np.array_equal(data["image"], expected_image) assert np.array_equal(data["mask"], expected_mask) @pytest.mark.parametrize("interpolation", [cv2.INTER_NEAREST, cv2.INTER_LINEAR, cv2.INTER_CUBIC]) def test_shift_scale_rotate_interpolation(interpolation): image = np.random.randint(low=0, high=256, size=(100, 100, 3), dtype=np.uint8) mask = np.random.randint(low=0, high=2, size=(100, 100), dtype=np.uint8) aug = A.ShiftScaleRotate( shift_limit=(0.2, 0.2), scale_limit=(1.1, 1.1), rotate_limit=(45, 45), interpolation=interpolation, p=1 ) data = aug(image=image, mask=mask) expected_image = FGeometric.shift_scale_rotate( image, angle=45, scale=2.1, dx=0.2, dy=0.2, interpolation=interpolation, border_mode=cv2.BORDER_REFLECT_101 ) expected_mask = FGeometric.shift_scale_rotate( mask, angle=45, scale=2.1, dx=0.2, dy=0.2, interpolation=cv2.INTER_NEAREST, border_mode=cv2.BORDER_REFLECT_101 ) assert np.array_equal(data["image"], expected_image) assert np.array_equal(data["mask"], expected_mask) @pytest.mark.parametrize("interpolation", [cv2.INTER_NEAREST, cv2.INTER_LINEAR, cv2.INTER_CUBIC]) def test_optical_distortion_interpolation(interpolation): image = np.random.randint(low=0, high=256, size=(100, 100, 3), dtype=np.uint8) mask = np.random.randint(low=0, high=2, size=(100, 100), dtype=np.uint8) aug = A.OpticalDistortion(distort_limit=(0.05, 0.05), shift_limit=(0, 0), interpolation=interpolation, p=1) data = aug(image=image, mask=mask) expected_image = F.optical_distortion( image, k=0.05, dx=0, dy=0, interpolation=interpolation, border_mode=cv2.BORDER_REFLECT_101 ) expected_mask = F.optical_distortion( mask, k=0.05, dx=0, dy=0, interpolation=cv2.INTER_NEAREST, border_mode=cv2.BORDER_REFLECT_101 ) assert np.array_equal(data["image"], expected_image) assert np.array_equal(data["mask"], expected_mask) @pytest.mark.parametrize("interpolation", [cv2.INTER_NEAREST, cv2.INTER_LINEAR, cv2.INTER_CUBIC]) def test_grid_distortion_interpolation(interpolation): image = np.random.randint(low=0, high=256, size=(100, 100, 3), dtype=np.uint8) mask = np.random.randint(low=0, high=2, size=(100, 100), dtype=np.uint8) aug = A.GridDistortion(num_steps=1, distort_limit=(0.3, 0.3), interpolation=interpolation, p=1) data = aug(image=image, mask=mask) expected_image = F.grid_distortion( image, num_steps=1, xsteps=[1.3], ysteps=[1.3], interpolation=interpolation, border_mode=cv2.BORDER_REFLECT_101 ) expected_mask = F.grid_distortion( mask, num_steps=1, xsteps=[1.3], ysteps=[1.3], interpolation=cv2.INTER_NEAREST, border_mode=cv2.BORDER_REFLECT_101, ) assert np.array_equal(data["image"], expected_image) assert np.array_equal(data["mask"], expected_mask) @pytest.mark.parametrize("size", [17, 21, 33]) def test_grid_distortion_steps(size): image = np.random.rand(size, size, 3) aug = A.GridDistortion(num_steps=size - 2, p=1) data = aug(image=image) assert np.array_equal(data["image"].shape, (size, size, 3)) @pytest.mark.parametrize("interpolation", [cv2.INTER_NEAREST, cv2.INTER_LINEAR, cv2.INTER_CUBIC]) def test_elastic_transform_interpolation(monkeypatch, interpolation): image = np.random.randint(low=0, high=256, size=(100, 100, 3), dtype=np.uint8) mask = np.random.randint(low=0, high=2, size=(100, 100), dtype=np.uint8) monkeypatch.setattr( "albumentations.augmentations.geometric.ElasticTransform.get_params", lambda *_: {"random_state": 1111} ) aug = A.ElasticTransform(alpha=1, sigma=50, alpha_affine=50, interpolation=interpolation, p=1) data = aug(image=image, mask=mask) expected_image = FGeometric.elastic_transform( image, alpha=1, sigma=50, alpha_affine=50, interpolation=interpolation, border_mode=cv2.BORDER_REFLECT_101, random_state=np.random.RandomState(1111), ) expected_mask = FGeometric.elastic_transform( mask, alpha=1, sigma=50, alpha_affine=50, interpolation=cv2.INTER_NEAREST, border_mode=cv2.BORDER_REFLECT_101, random_state=np.random.RandomState(1111), ) assert np.array_equal(data["image"], expected_image) assert np.array_equal(data["mask"], expected_mask) @pytest.mark.parametrize( ["augmentation_cls", "params"], [ [A.ElasticTransform, {}], [A.GridDistortion, {}], [A.ShiftScaleRotate, {"rotate_limit": 45}], [A.RandomScale, {"scale_limit": 0.5}], [A.RandomSizedCrop, {"min_max_height": (80, 90), "height": 100, "width": 100}], [A.LongestMaxSize, {"max_size": 50}], [A.Rotate, {}], [A.SafeRotate, {}], [A.OpticalDistortion, {}], [A.IAAAffine, {"scale": 1.5}], [A.IAAPiecewiseAffine, {"scale": 1.5}], [A.IAAPerspective, {}], [A.GlassBlur, {}], [A.Perspective, {}], [A.Affine, {}], [A.PiecewiseAffine, {}], ], ) def test_binary_mask_interpolation(augmentation_cls, params): aug = augmentation_cls(p=1, **params) image = np.random.randint(low=0, high=256, size=(100, 100, 3), dtype=np.uint8) mask = np.random.randint(low=0, high=2, size=(100, 100), dtype=np.uint8) data = aug(image=image, mask=mask) assert np.array_equal(np.unique(data["mask"]), np.array([0, 1])) @pytest.mark.parametrize( ["augmentation_cls", "params"], [ [A.ElasticTransform, {}], [A.GridDistortion, {}], [A.ShiftScaleRotate, {"rotate_limit": 45}], [A.RandomScale, {"scale_limit": 0.5}], [A.RandomSizedCrop, {"min_max_height": (80, 90), "height": 100, "width": 100}], [A.LongestMaxSize, {"max_size": 50}], [A.Rotate, {}], [A.SafeRotate, {}], [A.Resize, {"height": 80, "width": 90}], [A.Resize, {"height": 120, "width": 130}], [A.OpticalDistortion, {}], [A.GlassBlur, {}], [A.Perspective, {}], [A.Affine, {}], [A.PiecewiseAffine, {}], ], ) def test_semantic_mask_interpolation(augmentation_cls, params): aug = augmentation_cls(p=1, **params) image = np.random.randint(low=0, high=256, size=(100, 100, 3), dtype=np.uint8) mask = np.random.randint(low=0, high=4, size=(100, 100), dtype=np.uint8) * 64 data = aug(image=image, mask=mask) assert np.array_equal(np.unique(data["mask"]), np.array([0, 64, 128, 192])) def __test_multiprocessing_support_proc(args): x, transform = args return transform(image=x) @pytest.mark.parametrize( ["augmentation_cls", "params"], [ [A.ElasticTransform, {}], [A.GridDistortion, {}], [A.ShiftScaleRotate, {"rotate_limit": 45}], [A.RandomScale, {"scale_limit": 0.5}], [A.RandomSizedCrop, {"min_max_height": (80, 90), "height": 100, "width": 100}], [A.LongestMaxSize, {"max_size": 50}], [A.Rotate, {}], [A.SafeRotate, {}], [A.OpticalDistortion, {}], [A.IAAAffine, {"scale": 1.5}], [A.IAAPiecewiseAffine, {"scale": 1.5}], [A.IAAPerspective, {}], [A.Sharpen, {}], [A.FancyPCA, {}], [A.GlassBlur, {}], [A.Perspective, {}], [A.Affine, {}], [A.PiecewiseAffine, {}], ], ) def test_multiprocessing_support(augmentation_cls, params, multiprocessing_context): aug = augmentation_cls(p=1, **params) image = np.random.randint(low=0, high=256, size=(100, 100, 3), dtype=np.uint8) pool = multiprocessing_context.Pool(8) pool.map(__test_multiprocessing_support_proc, map(lambda x: (x, aug), [image] * 100)) pool.close() pool.join() def test_force_apply(): aug = A.Compose( [ A.OneOrOther( A.Compose( [ A.RandomSizedCrop(min_max_height=(256, 1025), height=512, width=512, p=1), A.OneOf( [ A.RandomSizedCrop(min_max_height=(256, 512), height=384, width=384, p=0.5), A.RandomSizedCrop(min_max_height=(256, 512), height=512, width=512, p=0.5), ] ), ] ), A.Compose( [ A.RandomSizedCrop(min_max_height=(256, 1025), height=256, width=256, p=1), A.OneOf([A.HueSaturationValue(p=0.5), A.RGBShift(p=0.7)], p=1), ] ), ), A.HorizontalFlip(p=1), A.RandomBrightnessContrast(p=0.5), ] ) res = aug(image=np.zeros((1248, 1248, 3), dtype=np.uint8)) assert res["image"].shape[0] in (256, 384, 512) assert res["image"].shape[1] in (256, 384, 512) @pytest.mark.parametrize( ["augmentation_cls", "params"], [ [A.ChannelShuffle, {}], [A.GaussNoise, {}], [A.Cutout, {}], [A.CoarseDropout, {}], [A.ImageCompression, {}], [A.HueSaturationValue, {}], [A.RGBShift, {}], [A.RandomBrightnessContrast, {}], [A.Blur, {}], [A.MotionBlur, {}], [A.MedianBlur, {}], [A.CLAHE, {}], [A.InvertImg, {}], [A.RandomGamma, {}], [A.ToGray, {}], [A.VerticalFlip, {}], [A.HorizontalFlip, {}], [A.Flip, {}], [A.Transpose, {}], [A.RandomRotate90, {}], [A.Rotate, {}], [A.SafeRotate, {}], [A.OpticalDistortion, {}], [A.GridDistortion, {}], [A.ElasticTransform, {}], [A.Normalize, {}], [A.ToFloat, {}], [A.FromFloat, {}], [A.ChannelDropout, {}], [A.Solarize, {}], [A.Posterize, {}], [A.Equalize, {}], [A.MultiplicativeNoise, {}], [A.FancyPCA, {}], [A.GlassBlur, {}], [A.GridDropout, {}], [A.ColorJitter, {}], [A.Perspective, {}], [A.Sharpen, {"alpha": [0.2, 0.2], "lightness": [0.5, 0.5]}], ], ) def test_additional_targets_for_image_only(augmentation_cls, params): aug = A.Compose([augmentation_cls(always_apply=True, **params)], additional_targets={"image2": "image"}) for _i in range(10): image1 = np.random.randint(low=0, high=256, size=(100, 100, 3), dtype=np.uint8) image2 = image1.copy() res = aug(image=image1, image2=image2) aug1 = res["image"] aug2 = res["image2"] assert np.array_equal(aug1, aug2) def test_lambda_transform(): def negate_image(image, **kwargs): return -image def one_hot_mask(mask, num_channels, **kwargs): new_mask = np.eye(num_channels, dtype=np.uint8)[mask] return new_mask def vflip_bbox(bbox, **kwargs): return F.bbox_vflip(bbox, **kwargs) def vflip_keypoint(keypoint, **kwargs): return F.keypoint_vflip(keypoint, **kwargs) aug = A.Lambda( image=negate_image, mask=partial(one_hot_mask, num_channels=16), bbox=vflip_bbox, keypoint=vflip_keypoint, p=1 ) output = aug( image=np.ones((10, 10, 3), dtype=np.float32), mask=np.tile(np.arange(0, 10), (10, 1)), bboxes=[(10, 15, 25, 35)], keypoints=[(20, 30, 40, 50)], ) assert (output["image"] < 0).all() assert output["mask"].shape[2] == 16 assert output["bboxes"] == [F.bbox_vflip((10, 15, 25, 35), 10, 10)] assert output["keypoints"] == [F.keypoint_vflip((20, 30, 40, 50), 10, 10)] def test_channel_droput(): img = np.ones((10, 10, 3), dtype=np.float32) aug = A.ChannelDropout(channel_drop_range=(1, 1), always_apply=True) transformed = aug(image=img)["image"] assert sum(transformed[:, :, c].max() for c in range(img.shape[2])) == 2 aug = A.ChannelDropout(channel_drop_range=(2, 2), always_apply=True) transformed = aug(image=img)["image"] assert sum(transformed[:, :, c].max() for c in range(img.shape[2])) == 1 def test_equalize(): aug = A.Equalize(p=1) img = np.random.randint(0, 256, 256 * 256 * 3, np.uint8).reshape((256, 256, 3)) a = aug(image=img)["image"] b = F.equalize(img) assert np.all(a == b) mask = np.random.randint(0, 2, 256 * 256, np.uint8).reshape((256, 256)) aug = A.Equalize(mask=mask, p=1) a = aug(image=img)["image"] b = F.equalize(img, mask=mask) assert np.all(a == b) def mask_func(image, test): return mask aug = A.Equalize(mask=mask_func, mask_params=["test"], p=1) assert np.all(aug(image=img, test=mask)["image"] == F.equalize(img, mask=mask)) def test_crop_non_empty_mask(): def _test_crop(mask, crop, aug, n=1): for _ in range(n): augmented = aug(image=mask, mask=mask) np.testing.assert_array_equal(augmented["image"], crop) np.testing.assert_array_equal(augmented["mask"], crop) mask_1 = np.zeros([10, 10]) mask_1[0, 0] = 1 crop_1 = np.array([[1]]) aug_1 = A.CropNonEmptyMaskIfExists(1, 1) mask_2 = np.zeros([10, 10]) crop_2 = np.array([[0]]) aug_2 = A.CropNonEmptyMaskIfExists(1, 1) mask_3 = np.ones([2, 2]) mask_3[0, 0] = 2 crop_3 = np.array([[2]]) aug_3 = A.CropNonEmptyMaskIfExists(1, 1, ignore_values=[1]) mask_4 = np.zeros([2, 2, 2]) mask_4[0, 0, 0] = 1 mask_4[1, 1, 1] = 2 crop_4 = np.array([[[1, 0]]]) aug_4 = A.CropNonEmptyMaskIfExists(1, 1, ignore_channels=[1]) mask_5 = np.random.random([10, 10, 3]) crop_5 = mask_5 aug_5 = A.CropNonEmptyMaskIfExists(10, 10) mask_6 = np.zeros([10, 10, 3]) mask_6[0, 0, 0] = 0 crop_6 = mask_6 aug_6 = A.CropNonEmptyMaskIfExists(10, 10, ignore_values=[1]) _test_crop(mask_1, crop_1, aug_1, n=1) _test_crop(mask_2, crop_2, aug_2, n=1) _test_crop(mask_3, crop_3, aug_3, n=5) _test_crop(mask_4, crop_4, aug_4, n=5) _test_crop(mask_5, crop_5, aug_5, n=1) _test_crop(mask_6, crop_6, aug_6, n=10) @pytest.mark.parametrize("interpolation", [cv2.INTER_NEAREST, cv2.INTER_LINEAR, cv2.INTER_CUBIC]) def test_downscale(interpolation): img_float = np.random.rand(100, 100, 3) img_uint = (img_float * 255).astype("uint8") aug = A.Downscale(scale_min=0.5, scale_max=0.5, interpolation=interpolation, always_apply=True) for img in (img_float, img_uint): transformed = aug(image=img)["image"] func_applied = F.downscale(img, scale=0.5, interpolation=interpolation) np.testing.assert_almost_equal(transformed, func_applied) def test_crop_keypoints(): image = np.random.randint(0, 256, (100, 100), np.uint8) keypoints = [(50, 50, 0, 0)] aug = A.Crop(0, 0, 80, 80, p=1) result = aug(image=image, keypoints=keypoints) assert result["keypoints"] == keypoints aug = A.Crop(50, 50, 100, 100, p=1) result = aug(image=image, keypoints=keypoints) assert result["keypoints"] == [(0, 0, 0, 0)] def test_longest_max_size_keypoints(): img = np.random.randint(0, 256, [50, 10], np.uint8) keypoints = [(9, 5, 0, 0)] aug = A.LongestMaxSize(max_size=100, p=1) result = aug(image=img, keypoints=keypoints) assert result["keypoints"] == [(18, 10, 0, 0)] aug = A.LongestMaxSize(max_size=5, p=1) result = aug(image=img, keypoints=keypoints) assert result["keypoints"] == [(0.9, 0.5, 0, 0)] aug = A.LongestMaxSize(max_size=50, p=1) result = aug(image=img, keypoints=keypoints) assert result["keypoints"] == [(9, 5, 0, 0)] def test_smallest_max_size_keypoints(): img = np.random.randint(0, 256, [50, 10], np.uint8) keypoints = [(9, 5, 0, 0)] aug = A.SmallestMaxSize(max_size=100, p=1) result = aug(image=img, keypoints=keypoints) assert result["keypoints"] == [(90, 50, 0, 0)] aug = A.SmallestMaxSize(max_size=5, p=1) result = aug(image=img, keypoints=keypoints) assert result["keypoints"] == [(4.5, 2.5, 0, 0)] aug = A.SmallestMaxSize(max_size=10, p=1) result = aug(image=img, keypoints=keypoints) assert result["keypoints"] == [(9, 5, 0, 0)] def test_resize_keypoints(): img = np.random.randint(0, 256, [50, 10], np.uint8) keypoints = [(9, 5, 0, 0)] aug = A.Resize(height=100, width=5, p=1) result = aug(image=img, keypoints=keypoints) assert result["keypoints"] == [(4.5, 10, 0, 0)] aug = A.Resize(height=50, width=10, p=1) result = aug(image=img, keypoints=keypoints) assert result["keypoints"] == [(9, 5, 0, 0)] @pytest.mark.parametrize( "image", [ np.random.randint(0, 256, [256, 320], np.uint8), np.random.random([256, 320]).astype(np.float32), np.random.randint(0, 256, [256, 320, 1], np.uint8), np.random.random([256, 320, 1]).astype(np.float32), ], ) def test_multiplicative_noise_grayscale(image): m = 0.5 aug = A.MultiplicativeNoise(m, p=1) result = aug(image=image)["image"] image = F.clip(image * m, image.dtype, F.MAX_VALUES_BY_DTYPE[image.dtype]) assert np.allclose(image, result) aug = A.MultiplicativeNoise(elementwise=True, p=1) params = aug.get_params_dependent_on_targets({"image": image}) mul = params["multiplier"] assert mul.shape == image.shape result = aug.apply(image, mul) dtype = image.dtype image = image.astype(np.float32) * mul image = F.clip(image, dtype, F.MAX_VALUES_BY_DTYPE[dtype]) assert np.allclose(image, result) @pytest.mark.parametrize( "image", [np.random.randint(0, 256, [256, 320, 3], np.uint8), np.random.random([256, 320, 3]).astype(np.float32)] ) def test_multiplicative_noise_rgb(image): dtype = image.dtype m = 0.5 aug = A.MultiplicativeNoise(m, p=1) result = aug(image=image)["image"] image = F.clip(image * m, dtype, F.MAX_VALUES_BY_DTYPE[dtype]) assert np.allclose(image, result) aug = A.MultiplicativeNoise(elementwise=True, p=1) params = aug.get_params_dependent_on_targets({"image": image}) mul = params["multiplier"] assert mul.shape == image.shape[:2] + (1,) result = aug.apply(image, mul) image = F.clip(image.astype(np.float32) * mul, dtype, F.MAX_VALUES_BY_DTYPE[dtype]) assert np.allclose(image, result) aug = A.MultiplicativeNoise(per_channel=True, p=1) params = aug.get_params_dependent_on_targets({"image": image}) mul = params["multiplier"] assert mul.shape == (3,) result = aug.apply(image, mul) image = F.clip(image.astype(np.float32) * mul, dtype, F.MAX_VALUES_BY_DTYPE[dtype]) assert np.allclose(image, result) aug = A.MultiplicativeNoise(elementwise=True, per_channel=True, p=1) params = aug.get_params_dependent_on_targets({"image": image}) mul = params["multiplier"] assert mul.shape == image.shape result = aug.apply(image, mul) image = F.clip(image.astype(np.float32) * mul, image.dtype, F.MAX_VALUES_BY_DTYPE[image.dtype]) assert np.allclose(image, result) def test_mask_dropout(): img = np.random.randint(0, 256, [50, 10], np.uint8) mask = np.ones([50, 10], dtype=np.long) aug = A.MaskDropout(p=1) result = aug(image=img, mask=mask) assert np.all(result["image"] == 0) assert np.all(result["mask"] == 0) img = np.random.randint(0, 256, [50, 10], np.uint8) mask = np.zeros([50, 10], dtype=np.long) aug = A.MaskDropout(p=1) result = aug(image=img, mask=mask) assert np.all(result["image"] == img) assert np.all(result["mask"] == 0) @pytest.mark.parametrize( "image", [np.random.randint(0, 256, [256, 320, 3], np.uint8), np.random.random([256, 320, 3]).astype(np.float32)] ) def test_grid_dropout_mask(image): mask = np.ones([256, 320], dtype=np.uint8) aug = A.GridDropout(p=1, mask_fill_value=0) result = aug(image=image, mask=mask) assert result["image"].sum() < image.sum() assert result["image"].shape == image.shape assert result["mask"].sum() < mask.sum() assert result["mask"].shape == mask.shape mask = np.zeros([256, 320], dtype=np.uint8) aug = A.GridDropout(p=1, mask_fill_value=0) result = aug(image=image, mask=mask) assert result["image"].sum() < image.sum() assert np.all(result["mask"] == 0) mask = np.random.randint(0, 10, [256, 320], np.uint8) aug = A.GridDropout(p=1, mask_fill_value=100) result = aug(image=image, mask=mask) assert result["image"].sum() < image.sum() assert result["mask"].sum() > mask.sum() mask = np.ones([256, 320], dtype=np.uint8) aug = A.GridDropout(p=1, mask_fill_value=None) result = aug(image=image, mask=mask) assert result["image"].sum() < image.sum() assert result["mask"].sum() == mask.sum() @pytest.mark.parametrize( ["ratio", "holes_number_x", "holes_number_y", "unit_size_min", "unit_size_max", "shift_x", "shift_y"], [ (0.00001, 10, 10, 100, 100, 50, 50), (0.9, 100, None, 200, None, 0, 0), (0.4556, 10, 20, None, 200, 0, 0), (0.00004, None, None, 2, 100, None, None), ], ) def test_grid_dropout_params(ratio, holes_number_x, holes_number_y, unit_size_min, unit_size_max, shift_x, shift_y): img = np.random.randint(0, 256, [256, 320], np.uint8) aug = A.GridDropout( ratio=ratio, unit_size_min=unit_size_min, unit_size_max=unit_size_max, holes_number_x=holes_number_x, holes_number_y=holes_number_y, shift_x=shift_x, shift_y=shift_y, random_offset=False, fill_value=0, p=1, ) result = aug(image=img)["image"] assert result.sum() < img.sum() assert result.shape == img.shape params = aug.get_params_dependent_on_targets({"image": img}) holes = params["holes"] assert len(holes[0]) == 4 if shift_x: assert holes[0][0] == shift_x else: assert holes[0][0] == 0 if shift_y: assert holes[0][1] == shift_y else: assert holes[0][1] == 0 if unit_size_min and unit_size_max: assert max(1, unit_size_min * ratio) <= (holes[0][2] - holes[0][0]) <= min(max(1, unit_size_max * ratio), 256) elif holes_number_x and holes_number_y: assert (holes[0][2] - holes[0][0]) == max(1, int(ratio * 320 // holes_number_x)) assert (holes[0][3] - holes[0][1]) == max(1, int(ratio * 256 // holes_number_y)) def test_gauss_noise_incorrect_var_limit_type(): with pytest.raises(TypeError) as exc_info: A.GaussNoise(var_limit={"low": 70, "high": 90}) message = "Expected var_limit type to be one of (int, float, tuple, list), got <class 'dict'>" assert str(exc_info.value) == message @pytest.mark.parametrize( ["blur_limit", "sigma", "result_blur", "result_sigma"], [ [[0, 0], [1, 1], 0, 1], [[1, 1], [0, 0], 1, 0], [[1, 1], [1, 1], 1, 1], [[0, 0], [0, 0], 3, 0], [[0, 3], [0, 0], 3, 0], [[0, 3], [0.1, 0.1], 3, 0.1], ], ) def test_gaus_blur_limits(blur_limit, sigma, result_blur, result_sigma): img = np.zeros([100, 100, 3], dtype=np.uint8) aug = A.Compose([A.GaussianBlur(blur_limit=blur_limit, sigma_limit=sigma, p=1)]) res = aug(image=img)["image"] assert np.allclose(res, F.gaussian_blur(img, result_blur, result_sigma)) @pytest.mark.parametrize( ["brightness", "contrast", "saturation", "hue"], [ [1, 1, 1, 0], [0.123, 1, 1, 0], [1.321, 1, 1, 0], [1, 0.234, 1, 0], [1, 1.432, 1, 0], [1, 1, 0.345, 0], [1, 1, 1.543, 0], ], ) def test_color_jitter(brightness, contrast, saturation, hue): np.random.seed(0) img = np.random.randint(0, 256, [100, 100, 3], dtype=np.uint8) pil_image = Image.fromarray(img) transform = A.Compose( [ A.ColorJitter( brightness=[brightness, brightness], contrast=[contrast, contrast], saturation=[saturation, saturation], hue=[hue, hue], p=1, ) ] ) pil_transform = ColorJitter( brightness=[brightness, brightness], contrast=[contrast, contrast], saturation=[saturation, saturation], hue=[hue, hue], ) res1 = transform(image=img)["image"] res2 = np.array(pil_transform(pil_image)) _max = np.abs(res1.astype(np.int16) - res2.astype(np.int16)).max() assert _max <= 2, "Max: {}".format(_max) @pytest.mark.parametrize( ["brightness", "contrast", "saturation", "hue"], [ [1, 1, 1, 0], [0.123, 1, 1, 0], [1.321, 1, 1, 0], [1, 0.234, 1, 0], [1, 1.432, 1, 0], [1, 1, 0.345, 0], [1, 1, 1.543, 0], [1, 1, 1, 0.456], [1, 1, 1, -0.432], ], ) def test_color_jitter_float_uint8_equal(brightness, contrast, saturation, hue): img = np.random.randint(0, 256, [100, 100, 3], dtype=np.uint8) transform = A.Compose( [ A.ColorJitter( brightness=[brightness, brightness], contrast=[contrast, contrast], saturation=[saturation, saturation], hue=[hue, hue], p=1, ) ] ) res1 = transform(image=img)["image"] res2 = (transform(image=img.astype(np.float32) / 255.0)["image"] * 255).astype(np.uint8) _max = np.abs(res1.astype(np.int16) - res2.astype(np.int16)).max() if hue != 0: assert _max <= 10, "Max: {}".format(_max) else: assert _max <= 2, "Max: {}".format(_max) @pytest.mark.parametrize(["hue", "sat", "val"], [[13, 17, 23], [14, 18, 24], [131, 143, 151], [132, 144, 152]]) def test_hue_saturation_value_float_uint8_equal(hue, sat, val): img = np.random.randint(0, 256, [100, 100, 3], dtype=np.uint8) for i in range(2): sign = 1 if i == 0 else -1 for i in range(4): if i == 0: _hue = hue * sign _sat = 0 _val = 0 elif i == 1: _hue = 0 _sat = sat * sign _val = 0 elif i == 2: _hue = 0 _sat = 0 _val = val * sign else: _hue = hue * sign _sat = sat * sign _val = val * sign t1 = A.Compose( [ A.HueSaturationValue( hue_shift_limit=[_hue, _hue], sat_shift_limit=[_sat, _sat], val_shift_limit=[_val, _val], p=1 ) ] ) t2 = A.Compose( [ A.HueSaturationValue( hue_shift_limit=[_hue / 180 * 360, _hue / 180 * 360], sat_shift_limit=[_sat / 255, _sat / 255], val_shift_limit=[_val / 255, _val / 255], p=1, ) ] ) res1 = t1(image=img)["image"] res2 = (t2(image=img.astype(np.float32) / 255.0)["image"] * 255).astype(np.uint8) _max = np.abs(res1.astype(np.int) - res2).max() assert _max <= 10, "Max value: {}".format(_max) def test_shift_scale_separate_shift_x_shift_y(image, mask): aug = A.ShiftScaleRotate(shift_limit=(0.3, 0.3), shift_limit_y=(0.4, 0.4), scale_limit=0, rotate_limit=0, p=1) data = aug(image=image, mask=mask) expected_image = FGeometric.shift_scale_rotate( image, angle=0, scale=1, dx=0.3, dy=0.4, interpolation=cv2.INTER_LINEAR, border_mode=cv2.BORDER_REFLECT_101 ) expected_mask = FGeometric.shift_scale_rotate( mask, angle=0, scale=1, dx=0.3, dy=0.4, interpolation=cv2.INTER_NEAREST, border_mode=cv2.BORDER_REFLECT_101 ) assert np.array_equal(data["image"], expected_image) assert np.array_equal(data["mask"], expected_mask) @pytest.mark.parametrize(["val_uint8"], [[0], [1], [128], [255]]) def test_glass_blur_float_uint8_diff_less_than_two(val_uint8): x_uint8 = np.zeros((5, 5)).astype(np.uint8) x_uint8[2, 2] = val_uint8 x_float32 = np.zeros((5, 5)).astype(np.float32) x_float32[2, 2] = val_uint8 / 255.0 glassblur = A.GlassBlur(always_apply=True, max_delta=1) np.random.seed(0) blur_uint8 = glassblur(image=x_uint8)["image"] np.random.seed(0) blur_float32 = glassblur(image=x_float32)["image"] diff = np.abs(blur_uint8 - blur_float32 * 255) assert np.all(diff <= 2.0) @pytest.mark.parametrize( ["img_dtype", "px", "percent", "pad_mode", "pad_cval", "keep_size"], [ [np.uint8, 10, None, cv2.BORDER_CONSTANT, 0, True], [np.uint8, -10, None, cv2.BORDER_CONSTANT, 0, True], [np.uint8, 10, None, cv2.BORDER_CONSTANT, 0, False], [np.uint8, -10, None, cv2.BORDER_CONSTANT, 0, False], [np.uint8, None, 0.1, cv2.BORDER_CONSTANT, 0, True], [np.uint8, None, -0.1, cv2.BORDER_CONSTANT, 0, True], [np.uint8, None, 0.1, cv2.BORDER_CONSTANT, 0, False], [np.uint8, None, -0.1, cv2.BORDER_CONSTANT, 0, False], [np.float32, None, 0.1, cv2.BORDER_CONSTANT, 0, False], [np.float32, None, -0.1, cv2.BORDER_CONSTANT, 0, False], [np.uint8, None, 0.1, cv2.BORDER_WRAP, 0, False], [np.uint8, None, 0.1, cv2.BORDER_REPLICATE, 0, False], [np.uint8, None, 0.1, cv2.BORDER_REFLECT101, 0, False], ], ) def test_compare_crop_and_pad(img_dtype, px, percent, pad_mode, pad_cval, keep_size): h, w, c = 100, 100, 3 mode_mapping = { cv2.BORDER_CONSTANT: "constant", cv2.BORDER_REPLICATE: "edge", cv2.BORDER_REFLECT101: "reflect", cv2.BORDER_WRAP: "wrap", } pad_mode_iaa = mode_mapping[pad_mode] bbox_params = A.BboxParams(format="pascal_voc") keypoint_params = A.KeypointParams(format="xy", remove_invisible=False) keypoints = np.random.randint(0, min(h, w), [10, 2]) bboxes = [] for i in range(10): x1, y1 = np.random.randint(0, min(h, w) - 2, 2) x2 = np.random.randint(x1 + 1, w - 1) y2 = np.random.randint(y1 + 1, h - 1) bboxes.append([x1, y1, x2, y2, 0]) transform_albu = A.Compose( [ A.CropAndPad( px=px, percent=percent, pad_mode=pad_mode, pad_cval=pad_cval, keep_size=keep_size, p=1, interpolation=cv2.INTER_AREA if (px is not None and px < 0) or (percent is not None and percent < 0) else cv2.INTER_LINEAR, ) ], bbox_params=bbox_params, keypoint_params=keypoint_params, ) transform_iaa = A.Compose( [A.IAACropAndPad(px=px, percent=percent, pad_mode=pad_mode_iaa, pad_cval=pad_cval, keep_size=keep_size, p=1)], bbox_params=bbox_params, keypoint_params=keypoint_params, ) if img_dtype == np.uint8: img = np.random.randint(0, 256, (h, w, c), dtype=np.uint8) else: img = np.random.random((h, w, c)).astype(img_dtype) res_albu = transform_albu(image=img, keypoints=keypoints, bboxes=bboxes) res_iaa = transform_iaa(image=img, keypoints=keypoints, bboxes=bboxes) for key, item in res_albu.items(): if key == "bboxes": bboxes = np.array(res_iaa[key]) h = bboxes[:, 3] - bboxes[:, 1] w = bboxes[:, 2] - bboxes[:, 0] res_iaa[key] = bboxes[(h > 0) & (w > 0)] assert np.allclose(item, res_iaa[key]), f"{key} are not equal" def test_perspective_keep_size(): h, w = 100, 100 img = np.zeros([h, w, 3], dtype=np.uint8) h, w = img.shape[:2] bboxes = [] for _ in range(10): x1 = np.random.randint(0, w - 1) y1 = np.random.randint(0, h - 1) x2 = np.random.randint(x1 + 1, w) y2 = np.random.randint(y1 + 1, h) bboxes.append([x1, y1, x2, y2]) keypoints = [(np.random.randint(0, w), np.random.randint(0, h), np.random.random()) for _ in range(10)] transform_1 = A.Compose( [A.Perspective(keep_size=True, p=1)], keypoint_params=A.KeypointParams("xys"), bbox_params=A.BboxParams("pascal_voc", label_fields=["labels"]), ) transform_2 = A.Compose( [A.Perspective(keep_size=False, p=1), A.Resize(h, w)], keypoint_params=A.KeypointParams("xys"), bbox_params=A.BboxParams("pascal_voc", label_fields=["labels"]), ) set_seed() res_1 = transform_1(image=img, bboxes=bboxes, keypoints=keypoints, labels=[0] * len(bboxes)) set_seed() res_2 = transform_2(image=img, bboxes=bboxes, keypoints=keypoints, labels=[0] * len(bboxes)) assert np.allclose(res_1["bboxes"], res_2["bboxes"]) assert np.allclose(res_1["keypoints"], res_2["keypoints"])
true
true
1c33f7ec4d42c8baa799ae0b07df4c8afb649cf3
12,196
py
Python
ml-agents-envs/mlagents/envs/brain.py
alexcercos/ML-Agents
c096c36b0348e3673b687499e17891cd35168939
[ "Apache-2.0" ]
1
2019-12-29T13:40:16.000Z
2019-12-29T13:40:16.000Z
ml-agents-envs/mlagents/envs/brain.py
alexcercos/ML-Agents
c096c36b0348e3673b687499e17891cd35168939
[ "Apache-2.0" ]
null
null
null
ml-agents-envs/mlagents/envs/brain.py
alexcercos/ML-Agents
c096c36b0348e3673b687499e17891cd35168939
[ "Apache-2.0" ]
2
2020-08-16T14:18:16.000Z
2022-03-18T12:22:54.000Z
import logging import numpy as np import io from mlagents.envs.communicator_objects.agent_info_pb2 import AgentInfoProto from mlagents.envs.communicator_objects.brain_parameters_pb2 import BrainParametersProto from mlagents.envs.timers import hierarchical_timer, timed from typing import Dict, List, NamedTuple, Optional from PIL import Image logger = logging.getLogger("mlagents.envs") class CameraResolution(NamedTuple): height: int width: int num_channels: int @property def gray_scale(self) -> bool: return self.num_channels == 1 class BrainParameters: def __init__( self, brain_name: str, vector_observation_space_size: int, num_stacked_vector_observations: int, camera_resolutions: List[CameraResolution], vector_action_space_size: List[int], vector_action_descriptions: List[str], vector_action_space_type: int, ): """ Contains all brain-specific parameters. """ self.brain_name = brain_name self.vector_observation_space_size = vector_observation_space_size self.num_stacked_vector_observations = num_stacked_vector_observations self.number_visual_observations = len(camera_resolutions) self.camera_resolutions = camera_resolutions self.vector_action_space_size = vector_action_space_size self.vector_action_descriptions = vector_action_descriptions self.vector_action_space_type = ["discrete", "continuous"][ vector_action_space_type ] def __str__(self): return """Unity brain name: {} Number of Visual Observations (per agent): {} Vector Observation space size (per agent): {} Number of stacked Vector Observation: {} Vector Action space type: {} Vector Action space size (per agent): {} Vector Action descriptions: {}""".format( self.brain_name, str(self.number_visual_observations), str(self.vector_observation_space_size), str(self.num_stacked_vector_observations), self.vector_action_space_type, str(self.vector_action_space_size), ", ".join(self.vector_action_descriptions), ) @staticmethod def from_proto( brain_param_proto: BrainParametersProto, agent_info: AgentInfoProto ) -> "BrainParameters": """ Converts brain parameter proto to BrainParameter object. :param brain_param_proto: protobuf object. :return: BrainParameter object. """ resolutions = [ CameraResolution(x.shape[0], x.shape[1], x.shape[2]) for x in agent_info.compressed_observations ] brain_params = BrainParameters( brain_param_proto.brain_name, brain_param_proto.vector_observation_size, brain_param_proto.num_stacked_vector_observations, resolutions, list(brain_param_proto.vector_action_size), list(brain_param_proto.vector_action_descriptions), brain_param_proto.vector_action_space_type, ) return brain_params class BrainInfo: def __init__( self, visual_observation, vector_observation, text_observations, memory=None, reward=None, agents=None, local_done=None, vector_action=None, text_action=None, max_reached=None, action_mask=None, custom_observations=None, ): """ Describes experience at current step of all agents linked to a brain. """ self.visual_observations = visual_observation self.vector_observations = vector_observation self.text_observations = text_observations self.memories = memory self.rewards = reward self.local_done = local_done self.max_reached = max_reached self.agents = agents self.previous_vector_actions = vector_action self.previous_text_actions = text_action self.action_masks = action_mask self.custom_observations = custom_observations def merge(self, other): for i in range(len(self.visual_observations)): self.visual_observations[i].extend(other.visual_observations[i]) self.vector_observations = np.append( self.vector_observations, other.vector_observations, axis=0 ) self.text_observations.extend(other.text_observations) self.memories = self.merge_memories( self.memories, other.memories, self.agents, other.agents ) self.rewards = safe_concat_lists(self.rewards, other.rewards) self.local_done = safe_concat_lists(self.local_done, other.local_done) self.max_reached = safe_concat_lists(self.max_reached, other.max_reached) self.agents = safe_concat_lists(self.agents, other.agents) self.previous_vector_actions = safe_concat_np_ndarray( self.previous_vector_actions, other.previous_vector_actions ) self.previous_text_actions = safe_concat_lists( self.previous_text_actions, other.previous_text_actions ) self.action_masks = safe_concat_np_ndarray( self.action_masks, other.action_masks ) self.custom_observations = safe_concat_lists( self.custom_observations, other.custom_observations ) @staticmethod def merge_memories(m1, m2, agents1, agents2): if len(m1) == 0 and len(m2) != 0: m1 = np.zeros((len(agents1), m2.shape[1])) elif len(m2) == 0 and len(m1) != 0: m2 = np.zeros((len(agents2), m1.shape[1])) elif m2.shape[1] > m1.shape[1]: new_m1 = np.zeros((m1.shape[0], m2.shape[1])) new_m1[0 : m1.shape[0], 0 : m1.shape[1]] = m1 return np.append(new_m1, m2, axis=0) elif m1.shape[1] > m2.shape[1]: new_m2 = np.zeros((m2.shape[0], m1.shape[1])) new_m2[0 : m2.shape[0], 0 : m2.shape[1]] = m2 return np.append(m1, new_m2, axis=0) return np.append(m1, m2, axis=0) @staticmethod @timed def process_pixels(image_bytes: bytes, gray_scale: bool) -> np.ndarray: """ Converts byte array observation image into numpy array, re-sizes it, and optionally converts it to grey scale :param gray_scale: Whether to convert the image to grayscale. :param image_bytes: input byte array corresponding to image :return: processed numpy array of observation from environment """ with hierarchical_timer("image_decompress"): image_bytearray = bytearray(image_bytes) image = Image.open(io.BytesIO(image_bytearray)) # Normally Image loads lazily, this forces it to do loading in the timer scope. image.load() s = np.array(image) / 255.0 if gray_scale: s = np.mean(s, axis=2) s = np.reshape(s, [s.shape[0], s.shape[1], 1]) return s @staticmethod def from_agent_proto( worker_id: int, agent_info_list: List[AgentInfoProto], brain_params: BrainParameters, ) -> "BrainInfo": """ Converts list of agent infos to BrainInfo. """ vis_obs: List[np.ndarray] = [] for i in range(brain_params.number_visual_observations): obs = [ BrainInfo.process_pixels( x.compressed_observations[i].data, brain_params.camera_resolutions[i].gray_scale, ) for x in agent_info_list ] vis_obs += [obs] if len(agent_info_list) == 0: memory_size = 0 else: memory_size = max(len(x.memories) for x in agent_info_list) if memory_size == 0: memory = np.zeros((0, 0)) else: [ x.memories.extend([0] * (memory_size - len(x.memories))) for x in agent_info_list ] memory = np.array([list(x.memories) for x in agent_info_list]) total_num_actions = sum(brain_params.vector_action_space_size) mask_actions = np.ones((len(agent_info_list), total_num_actions)) for agent_index, agent_info in enumerate(agent_info_list): if agent_info.action_mask is not None: if len(agent_info.action_mask) == total_num_actions: mask_actions[agent_index, :] = [ 0 if agent_info.action_mask[k] else 1 for k in range(total_num_actions) ] if any(np.isnan(x.reward) for x in agent_info_list): logger.warning( "An agent had a NaN reward for brain " + brain_params.brain_name ) if len(agent_info_list) == 0: vector_obs = np.zeros( ( 0, brain_params.vector_observation_space_size * brain_params.num_stacked_vector_observations, ) ) else: stacked_obs = [] has_nan = False has_inf = False for x in agent_info_list: np_obs = np.array(x.stacked_vector_observation) # Check for NaNs or infs in the observations # If there's a NaN in the observations, the dot() result will be NaN # If there's an Inf (either sign) then the result will be Inf # See https://stackoverflow.com/questions/6736590/fast-check-for-nan-in-numpy for background # Note that a very large values (larger than sqrt(float_max)) will result in an Inf value here # This is OK though, worst case it results in an unnecessary (but harmless) nan_to_num call. d = np.dot(np_obs, np_obs) has_nan = has_nan or np.isnan(d) has_inf = has_inf or not np.isfinite(d) stacked_obs.append(np_obs) vector_obs = np.array(stacked_obs) # In we have any NaN or Infs, use np.nan_to_num to replace these with finite values if has_nan or has_inf: vector_obs = np.nan_to_num(vector_obs) if has_nan: logger.warning( f"An agent had a NaN observation for brain {brain_params.brain_name}" ) agents = [f"${worker_id}-{x.id}" for x in agent_info_list] brain_info = BrainInfo( visual_observation=vis_obs, vector_observation=vector_obs, text_observations=[x.text_observation for x in agent_info_list], memory=memory, reward=[x.reward if not np.isnan(x.reward) else 0 for x in agent_info_list], agents=agents, local_done=[x.done for x in agent_info_list], vector_action=np.array([x.stored_vector_actions for x in agent_info_list]), text_action=[list(x.stored_text_actions) for x in agent_info_list], max_reached=[x.max_step_reached for x in agent_info_list], custom_observations=[x.custom_observation for x in agent_info_list], action_mask=mask_actions, ) return brain_info def safe_concat_lists(l1: Optional[List], l2: Optional[List]) -> Optional[List]: if l1 is None: if l2 is None: return None else: return l2.copy() else: if l2 is None: return l1.copy() else: copy = l1.copy() copy.extend(l2) return copy def safe_concat_np_ndarray( a1: Optional[np.ndarray], a2: Optional[np.ndarray] ) -> Optional[np.ndarray]: if a1 is not None and a1.size != 0: if a2 is not None and a2.size != 0: return np.append(a1, a2, axis=0) else: return a1.copy() elif a2 is not None and a2.size != 0: return a2.copy() return None # Renaming of dictionary of brain name to BrainInfo for clarity AllBrainInfo = Dict[str, BrainInfo]
38.594937
110
0.616678
import logging import numpy as np import io from mlagents.envs.communicator_objects.agent_info_pb2 import AgentInfoProto from mlagents.envs.communicator_objects.brain_parameters_pb2 import BrainParametersProto from mlagents.envs.timers import hierarchical_timer, timed from typing import Dict, List, NamedTuple, Optional from PIL import Image logger = logging.getLogger("mlagents.envs") class CameraResolution(NamedTuple): height: int width: int num_channels: int @property def gray_scale(self) -> bool: return self.num_channels == 1 class BrainParameters: def __init__( self, brain_name: str, vector_observation_space_size: int, num_stacked_vector_observations: int, camera_resolutions: List[CameraResolution], vector_action_space_size: List[int], vector_action_descriptions: List[str], vector_action_space_type: int, ): self.brain_name = brain_name self.vector_observation_space_size = vector_observation_space_size self.num_stacked_vector_observations = num_stacked_vector_observations self.number_visual_observations = len(camera_resolutions) self.camera_resolutions = camera_resolutions self.vector_action_space_size = vector_action_space_size self.vector_action_descriptions = vector_action_descriptions self.vector_action_space_type = ["discrete", "continuous"][ vector_action_space_type ] def __str__(self): return """Unity brain name: {} Number of Visual Observations (per agent): {} Vector Observation space size (per agent): {} Number of stacked Vector Observation: {} Vector Action space type: {} Vector Action space size (per agent): {} Vector Action descriptions: {}""".format( self.brain_name, str(self.number_visual_observations), str(self.vector_observation_space_size), str(self.num_stacked_vector_observations), self.vector_action_space_type, str(self.vector_action_space_size), ", ".join(self.vector_action_descriptions), ) @staticmethod def from_proto( brain_param_proto: BrainParametersProto, agent_info: AgentInfoProto ) -> "BrainParameters": resolutions = [ CameraResolution(x.shape[0], x.shape[1], x.shape[2]) for x in agent_info.compressed_observations ] brain_params = BrainParameters( brain_param_proto.brain_name, brain_param_proto.vector_observation_size, brain_param_proto.num_stacked_vector_observations, resolutions, list(brain_param_proto.vector_action_size), list(brain_param_proto.vector_action_descriptions), brain_param_proto.vector_action_space_type, ) return brain_params class BrainInfo: def __init__( self, visual_observation, vector_observation, text_observations, memory=None, reward=None, agents=None, local_done=None, vector_action=None, text_action=None, max_reached=None, action_mask=None, custom_observations=None, ): self.visual_observations = visual_observation self.vector_observations = vector_observation self.text_observations = text_observations self.memories = memory self.rewards = reward self.local_done = local_done self.max_reached = max_reached self.agents = agents self.previous_vector_actions = vector_action self.previous_text_actions = text_action self.action_masks = action_mask self.custom_observations = custom_observations def merge(self, other): for i in range(len(self.visual_observations)): self.visual_observations[i].extend(other.visual_observations[i]) self.vector_observations = np.append( self.vector_observations, other.vector_observations, axis=0 ) self.text_observations.extend(other.text_observations) self.memories = self.merge_memories( self.memories, other.memories, self.agents, other.agents ) self.rewards = safe_concat_lists(self.rewards, other.rewards) self.local_done = safe_concat_lists(self.local_done, other.local_done) self.max_reached = safe_concat_lists(self.max_reached, other.max_reached) self.agents = safe_concat_lists(self.agents, other.agents) self.previous_vector_actions = safe_concat_np_ndarray( self.previous_vector_actions, other.previous_vector_actions ) self.previous_text_actions = safe_concat_lists( self.previous_text_actions, other.previous_text_actions ) self.action_masks = safe_concat_np_ndarray( self.action_masks, other.action_masks ) self.custom_observations = safe_concat_lists( self.custom_observations, other.custom_observations ) @staticmethod def merge_memories(m1, m2, agents1, agents2): if len(m1) == 0 and len(m2) != 0: m1 = np.zeros((len(agents1), m2.shape[1])) elif len(m2) == 0 and len(m1) != 0: m2 = np.zeros((len(agents2), m1.shape[1])) elif m2.shape[1] > m1.shape[1]: new_m1 = np.zeros((m1.shape[0], m2.shape[1])) new_m1[0 : m1.shape[0], 0 : m1.shape[1]] = m1 return np.append(new_m1, m2, axis=0) elif m1.shape[1] > m2.shape[1]: new_m2 = np.zeros((m2.shape[0], m1.shape[1])) new_m2[0 : m2.shape[0], 0 : m2.shape[1]] = m2 return np.append(m1, new_m2, axis=0) return np.append(m1, m2, axis=0) @staticmethod @timed def process_pixels(image_bytes: bytes, gray_scale: bool) -> np.ndarray: with hierarchical_timer("image_decompress"): image_bytearray = bytearray(image_bytes) image = Image.open(io.BytesIO(image_bytearray)) image.load() s = np.array(image) / 255.0 if gray_scale: s = np.mean(s, axis=2) s = np.reshape(s, [s.shape[0], s.shape[1], 1]) return s @staticmethod def from_agent_proto( worker_id: int, agent_info_list: List[AgentInfoProto], brain_params: BrainParameters, ) -> "BrainInfo": vis_obs: List[np.ndarray] = [] for i in range(brain_params.number_visual_observations): obs = [ BrainInfo.process_pixels( x.compressed_observations[i].data, brain_params.camera_resolutions[i].gray_scale, ) for x in agent_info_list ] vis_obs += [obs] if len(agent_info_list) == 0: memory_size = 0 else: memory_size = max(len(x.memories) for x in agent_info_list) if memory_size == 0: memory = np.zeros((0, 0)) else: [ x.memories.extend([0] * (memory_size - len(x.memories))) for x in agent_info_list ] memory = np.array([list(x.memories) for x in agent_info_list]) total_num_actions = sum(brain_params.vector_action_space_size) mask_actions = np.ones((len(agent_info_list), total_num_actions)) for agent_index, agent_info in enumerate(agent_info_list): if agent_info.action_mask is not None: if len(agent_info.action_mask) == total_num_actions: mask_actions[agent_index, :] = [ 0 if agent_info.action_mask[k] else 1 for k in range(total_num_actions) ] if any(np.isnan(x.reward) for x in agent_info_list): logger.warning( "An agent had a NaN reward for brain " + brain_params.brain_name ) if len(agent_info_list) == 0: vector_obs = np.zeros( ( 0, brain_params.vector_observation_space_size * brain_params.num_stacked_vector_observations, ) ) else: stacked_obs = [] has_nan = False has_inf = False for x in agent_info_list: np_obs = np.array(x.stacked_vector_observation) # If there's an Inf (either sign) then the result will be Inf d = np.dot(np_obs, np_obs) has_nan = has_nan or np.isnan(d) has_inf = has_inf or not np.isfinite(d) stacked_obs.append(np_obs) vector_obs = np.array(stacked_obs) if has_nan or has_inf: vector_obs = np.nan_to_num(vector_obs) if has_nan: logger.warning( f"An agent had a NaN observation for brain {brain_params.brain_name}" ) agents = [f"${worker_id}-{x.id}" for x in agent_info_list] brain_info = BrainInfo( visual_observation=vis_obs, vector_observation=vector_obs, text_observations=[x.text_observation for x in agent_info_list], memory=memory, reward=[x.reward if not np.isnan(x.reward) else 0 for x in agent_info_list], agents=agents, local_done=[x.done for x in agent_info_list], vector_action=np.array([x.stored_vector_actions for x in agent_info_list]), text_action=[list(x.stored_text_actions) for x in agent_info_list], max_reached=[x.max_step_reached for x in agent_info_list], custom_observations=[x.custom_observation for x in agent_info_list], action_mask=mask_actions, ) return brain_info def safe_concat_lists(l1: Optional[List], l2: Optional[List]) -> Optional[List]: if l1 is None: if l2 is None: return None else: return l2.copy() else: if l2 is None: return l1.copy() else: copy = l1.copy() copy.extend(l2) return copy def safe_concat_np_ndarray( a1: Optional[np.ndarray], a2: Optional[np.ndarray] ) -> Optional[np.ndarray]: if a1 is not None and a1.size != 0: if a2 is not None and a2.size != 0: return np.append(a1, a2, axis=0) else: return a1.copy() elif a2 is not None and a2.size != 0: return a2.copy() return None AllBrainInfo = Dict[str, BrainInfo]
true
true
1c33f8afcd2c14d682697633b0b5b0150094b3ef
956
py
Python
olympicvaxinfo/olympicvaxinfo/urls.py
mueslimak3r/olympicvax
279bb5eda99d34b20477c613471c1ddcbd9dc968
[ "MIT" ]
null
null
null
olympicvaxinfo/olympicvaxinfo/urls.py
mueslimak3r/olympicvax
279bb5eda99d34b20477c613471c1ddcbd9dc968
[ "MIT" ]
null
null
null
olympicvaxinfo/olympicvaxinfo/urls.py
mueslimak3r/olympicvax
279bb5eda99d34b20477c613471c1ddcbd9dc968
[ "MIT" ]
null
null
null
"""olympicvaxinfo URL Configuration The `urlpatterns` list routes URLs to views. For more information please see: https://docs.djangoproject.com/en/3.1/topics/http/urls/ Examples: Function views 1. Add an import: from my_app import views 2. Add a URL to urlpatterns: path('', views.home, name='home') Class-based views 1. Add an import: from other_app.views import Home 2. Add a URL to urlpatterns: path('', Home.as_view(), name='home') Including another URLconf 1. Import the include() function: from django.urls import include, path 2. Add a URL to urlpatterns: path('blog/', include('blog.urls')) """ from django.contrib import admin from django.urls import path from . import views urlpatterns = [ path('admin/', admin.site.urls), path("", views.blog_index, name="blog_index"), path("<int:pk>/", views.blog_detail, name="blog_detail"), path("<category>/", views.blog_category, name="blog_category"), ]
38.24
77
0.703975
from django.contrib import admin from django.urls import path from . import views urlpatterns = [ path('admin/', admin.site.urls), path("", views.blog_index, name="blog_index"), path("<int:pk>/", views.blog_detail, name="blog_detail"), path("<category>/", views.blog_category, name="blog_category"), ]
true
true
1c33f9078d1d81292a0bc042bd045df08b0b6362
12,732
py
Python
models/faster_rcnn.py
hvkwak/simple-faster-rcnn-pytorch
3ea84a789c91ea8d403637026b4a5add19e5343a
[ "MIT" ]
null
null
null
models/faster_rcnn.py
hvkwak/simple-faster-rcnn-pytorch
3ea84a789c91ea8d403637026b4a5add19e5343a
[ "MIT" ]
null
null
null
models/faster_rcnn.py
hvkwak/simple-faster-rcnn-pytorch
3ea84a789c91ea8d403637026b4a5add19e5343a
[ "MIT" ]
null
null
null
import os import sys import torch import torchvision import numpy as np from torch import nn from torch.nn import functional as F # from models.utils.nms import non_maximum_suppression from models.utils.bbox_tools import loc2bbox from utils.array_tool import tonumpy, totensor from data.dataset import preprocess from utils.util import read_image from utils.config import opt class FasterRCNN(nn.Module): """Base class for Faster R-CNN. This is a base class for Faster R-CNN links supporting object detection API [#]_. The following three stages constitute Faster R-CNN. 1. **Feature extraction**: Images are taken and their \ feature maps are calculated. 2. **Region Proposal Networks**: Given the feature maps calculated in \ the previous stage, produce set of RoIs around objects. 3. **Localization and Classification Heads**: Using feature maps that \ belong to the proposed RoIs, classify the categories of the objects \ in the RoIs and improve localizations. Each stage is carried out by one of the callable :class:`torch.nn.Module` objects :obj:`feature`, :obj:`rpn` and :obj:`head`. There are two functions :meth:`predict` and :meth:`__call__` to conduct object detection. :meth:`predict` takes images and returns bounding boxes that are converted to image coordinates. This will be useful for a scenario when Faster R-CNN is treated as a black box function, for instance. :meth:`__call__` is provided for a scnerario when intermediate outputs are needed, for instance, for training and debugging. Links that support obejct detection API have method :meth:`predict` with the same interface. Please refer to :meth:`predict` for further details. .. [#] Shaoqing Ren, Kaiming He, Ross Girshick, Jian Sun. \ Faster R-CNN: Towards Real-Time Object Detection with \ Region Proposal Networks. NIPS 2015. Args: extractor (nn.Module): A module that takes a BCHW image array and returns feature maps. rpn (nn.Module): A module that has the same interface as :class:`model.region_proposal_network.RegionProposalNetwork`. Please refer to the documentation found there. head (nn.Module): A module that takes a BCHW variable, RoIs and batch indices for RoIs. This returns class dependent localization paramters and class scores. loc_normalize_mean (tuple of four floats): Mean values of localization estimates. loc_normalize_std (tupler of four floats): Standard deviation of localization estimates. """ def __init__(self, extractor, rpn, head, loc_normalize_mean = (0., 0., 0., 0.), loc_normalize_std = (0.1, 0.1, 0.2, 0.2)): # in Python3, inheritance and initialize like this: super().__init__() self.extractor = extractor self.rpn = rpn self.head = head # mean and std self.loc_normalize_mean = loc_normalize_mean self.loc_normalize_std = loc_normalize_std self.use_preset('evaluate') # demo_image self.demo_image = "" @property def n_class(self): # Total number of classes including the background. return self.head.n_class def forward(self, x, scale=1.): """Forward Faster R-CNN. Scaling paramter :obj:`scale` is used by RPN to determine the threshold to select small objects, which are going to be rejected irrespective of their confidence scores. Here are notations used. * :math:`N` is the number of batch size * :math:`R'` is the total number of RoIs produced across batches. \ Given :math:`R_i` proposed RoIs from the :math:`i` th image, \ :math:`R' = \\sum _{i=1} ^ N R_i`. * :math:`L` is the number of classes excluding the background. Classes are ordered by the background, the first class, ..., and the :math:`L` th class. Args: x (autograd.Variable): 4D image variable. scale (float): Amount of scaling applied to the raw image during preprocessing. Returns: Variable, Variable, array, array: Returns tuple of four values listed below. * **roi_cls_locs**: Offsets and scalings for the proposed RoIs. \ Its shape is :math:`(R', (L + 1) \\times 4)`. * **roi_scores**: Class predictions for the proposed RoIs. \ Its shape is :math:`(R', L + 1)`. * **rois**: RoIs proposed by RPN. Its shape is \ :math:`(R', 4)`. * **roi_indices**: Batch indices of RoIs. Its shape is \ :math:`(R',)`. """ img_size = x.shape[2:] h = self.extractor(x) # rpn_locs, rpn_scores, rois, roi_indices, anchor = self.rpn(h, img_size, scale) # rpn_locs, rpn_scores, anchors are obsolete _, _, rois, roi_indices, _ = self.rpn(h, img_size, scale) # visualize RPN results to see if they are working correctly: # visualize_RPN(rois, self.scale, self.demo_image) # feed forward weiter: roi_cls_locs, roi_scores = self.head(h, rois, roi_indices) return roi_cls_locs, roi_scores, rois, roi_indices def use_preset(self, preset): """Use the given preset during prediction. This method changes values of :obj:`self.nms_thresh` and :obj:`self.score_thresh`. These values are a threshold value used for non maximum suppression and a threshold value to discard low confidence proposals in :meth:`predict`, respectively. If the attributes need to be changed to something other than the values provided in the presets, please modify them by directly accessing the public attributes. Args: preset ({'visualize', 'evaluate'): A string to determine the preset to use. """ if preset == 'visualize': self.nms_thresh = 0.3 self.score_thresh = 0.9 elif preset == 'evaluate': self.nms_thresh = 0.1 # 0.2 self.score_thresh = 0.9 # 0.05 else: raise ValueError('preset must be visualize or evaluate') def _suppress(self, raw_cls_bbox, raw_prob): # non maximum suppresion before final predictions bbox = list() label = list() score = list() # masks = list() # skip cls_id = 0 because it is the background class for l in range(1, self.n_class): cls_bbox_l = raw_cls_bbox.reshape((-1, self.n_class, 4))[:, l, :] prob_l = raw_prob[:, l] mask = prob_l > self.score_thresh cls_bbox_l = cls_bbox_l[mask] prob_l = prob_l[mask] keep = torchvision.ops.nms(torch.from_numpy(cls_bbox_l), torch.from_numpy(prob_l), self.nms_thresh) # mask = np.where(mask)[0] # import ipdb;ipdb.set_trace() keep = keep.numpy() bbox.append(cls_bbox_l[keep]) # The labels are in [0, self.n_class - 2]. label.append((l - 1) * np.ones((len(keep),))) score.append(prob_l[keep]) # masks.append(mask[keep]) bbox = np.concatenate(bbox, axis=0).astype(np.float32) label = np.concatenate(label, axis=0).astype(np.int32) score = np.concatenate(score, axis=0).astype(np.float32) # masks = np.concatenate(masks, axis = 0) return bbox, label, score @torch.no_grad() def predict(self, imgs, sizes=None, visualize=False): """Detect objects from images. This method predicts objects for each image. Args: imgs (iterable of numpy.ndarray): Arrays holding images. All images are in CHW and RGB format and the range of their value is :math:`[0, 255]`. Returns: tuple of lists: This method returns a tuple of three lists, :obj:`(bboxes, labels, scores)`. * **bboxes**: A list of float arrays of shape :math:`(R, 4)`, \ where :math:`R` is the number of bounding boxes in a image. \ Each bouding box is organized by \ :math:`(y_{min}, x_{min}, y_{max}, x_{max})` \ in the second axis. * **labels** : A list of integer arrays of shape :math:`(R,)`. \ Each value indicates the class of the bounding box. \ Values are in range :math:`[0, L - 1]`, where :math:`L` is the \ number of the foreground classes. * **scores** : A list of float arrays of shape :math:`(R,)`. \ Each value indicates how confident the prediction is. """ self.eval() if visualize: self.use_preset('visualize') # Visualize mode prepared_imgs = list() sizes = list() for img in imgs: size = img.shape[1:] img, scale = preprocess(tonumpy(img)) self.scale = scale prepared_imgs.append(img) sizes.append(size) else: prepared_imgs = imgs # create output lists bboxes = list() labels = list() scores = list() masks = list() for img, size in zip(prepared_imgs, sizes): # change it to tensor # [None] addes up one more dimension img = totensor(img[None]).float() # scale factor scale = img.shape[3] / size[1] # fast forward the image # img -> (extractor+rpn+head) -> roi_cls_loc, roi_scores, rois roi_cls_loc, roi_scores, rois, roi_indices = self(img, scale=scale) # NOTE: # rois.shape = (300, 4) # where 4 corresponds to (y1, x1, y2, x2) # x in [0, 600], y in [0, 800] # We are assuming that batch size is 1. roi_score = roi_scores.data roi_cls_loc = roi_cls_loc.data # change rois to tensor roi = totensor(rois) / scale # check the codes below. # Convert predictions to bounding boxes in image coordinates. # Bounding boxes are scaled to the scale of the input images. mean = torch.Tensor(self.loc_normalize_mean). \ repeat(self.n_class)[None] std = torch.Tensor(self.loc_normalize_std). \ repeat(self.n_class)[None] roi_cls_loc = (roi_cls_loc * std + mean) roi_cls_loc = roi_cls_loc.view(-1, self.n_class, 4) roi = roi.view(-1, 1, 4).expand_as(roi_cls_loc) cls_bbox = loc2bbox(tonumpy(roi).reshape((-1, 4)), tonumpy(roi_cls_loc).reshape((-1, 4))) cls_bbox = totensor(cls_bbox) # change the form (N, 4) cls_bbox = cls_bbox.view(-1, self.n_class * 4) # clamp in range of [0, size[0]] cls_bbox[:, 0::2] = (cls_bbox[:, 0::2]).clamp(min=0, max=size[0]) cls_bbox[:, 1::2] = (cls_bbox[:, 1::2]).clamp(min=0, max=size[1]) prob = tonumpy(F.softmax(totensor(roi_score), dim=1)) # change tensors to numpy raw_cls_bbox = tonumpy(cls_bbox) raw_prob = tonumpy(prob) # non maximum suppression bbox, label, score = self._suppress(raw_cls_bbox, raw_prob) bboxes.append(bbox) labels.append(label) scores.append(score) # masks.append(mask) self.use_preset('evaluate') self.train() # change it back to train mode. return bboxes, labels, scores def visualize_RPN(rois, scale, image): # Visualize RPN results import matplotlib.pyplot as plt import matplotlib.patches as patches from PIL import Image ## load image image_name = image img1 = Image.open('/home/hyobin/Documents/in-facedemo/facerecognition/PyFaceRecClient/simple-faster-rcnn-pytorch/'+image_name) # img1 = read_image(os.path.dirname(os.path.abspath(__file__))+'/demo.jpg') fig, ax = plt.subplots(1) ax.imshow(img1) # visualize top images for i in range(10): y1, x1, y2, x2 = rois[i, :] y1, x1, y2, x2 = y1/scale, x1/scale, y2/scale, x2/scale h = y2 - y1 w = x2 - x1 rect = patches.Rectangle((x1,y1),w,h,linewidth=1,edgecolor='r',facecolor='none') ax.add_patch(rect) plt.show()
39.175385
130
0.592366
import os import sys import torch import torchvision import numpy as np from torch import nn from torch.nn import functional as F from models.utils.bbox_tools import loc2bbox from utils.array_tool import tonumpy, totensor from data.dataset import preprocess from utils.util import read_image from utils.config import opt class FasterRCNN(nn.Module): def __init__(self, extractor, rpn, head, loc_normalize_mean = (0., 0., 0., 0.), loc_normalize_std = (0.1, 0.1, 0.2, 0.2)): super().__init__() self.extractor = extractor self.rpn = rpn self.head = head self.loc_normalize_mean = loc_normalize_mean self.loc_normalize_std = loc_normalize_std self.use_preset('evaluate') self.demo_image = "" @property def n_class(self): return self.head.n_class def forward(self, x, scale=1.): img_size = x.shape[2:] h = self.extractor(x) _, _, rois, roi_indices, _ = self.rpn(h, img_size, scale) roi_cls_locs, roi_scores = self.head(h, rois, roi_indices) return roi_cls_locs, roi_scores, rois, roi_indices def use_preset(self, preset): if preset == 'visualize': self.nms_thresh = 0.3 self.score_thresh = 0.9 elif preset == 'evaluate': self.nms_thresh = 0.1 self.score_thresh = 0.9 else: raise ValueError('preset must be visualize or evaluate') def _suppress(self, raw_cls_bbox, raw_prob): bbox = list() label = list() score = list() for l in range(1, self.n_class): cls_bbox_l = raw_cls_bbox.reshape((-1, self.n_class, 4))[:, l, :] prob_l = raw_prob[:, l] mask = prob_l > self.score_thresh cls_bbox_l = cls_bbox_l[mask] prob_l = prob_l[mask] keep = torchvision.ops.nms(torch.from_numpy(cls_bbox_l), torch.from_numpy(prob_l), self.nms_thresh) keep = keep.numpy() bbox.append(cls_bbox_l[keep]) label.append((l - 1) * np.ones((len(keep),))) score.append(prob_l[keep]) bbox = np.concatenate(bbox, axis=0).astype(np.float32) label = np.concatenate(label, axis=0).astype(np.int32) score = np.concatenate(score, axis=0).astype(np.float32) return bbox, label, score @torch.no_grad() def predict(self, imgs, sizes=None, visualize=False): self.eval() if visualize: self.use_preset('visualize') prepared_imgs = list() sizes = list() for img in imgs: size = img.shape[1:] img, scale = preprocess(tonumpy(img)) self.scale = scale prepared_imgs.append(img) sizes.append(size) else: prepared_imgs = imgs bboxes = list() labels = list() scores = list() masks = list() for img, size in zip(prepared_imgs, sizes): img = totensor(img[None]).float() scale = img.shape[3] / size[1] roi_cls_loc, roi_scores, rois, roi_indices = self(img, scale=scale) roi_score = roi_scores.data roi_cls_loc = roi_cls_loc.data roi = totensor(rois) / scale mean = torch.Tensor(self.loc_normalize_mean). \ repeat(self.n_class)[None] std = torch.Tensor(self.loc_normalize_std). \ repeat(self.n_class)[None] roi_cls_loc = (roi_cls_loc * std + mean) roi_cls_loc = roi_cls_loc.view(-1, self.n_class, 4) roi = roi.view(-1, 1, 4).expand_as(roi_cls_loc) cls_bbox = loc2bbox(tonumpy(roi).reshape((-1, 4)), tonumpy(roi_cls_loc).reshape((-1, 4))) cls_bbox = totensor(cls_bbox) cls_bbox = cls_bbox.view(-1, self.n_class * 4) cls_bbox[:, 0::2] = (cls_bbox[:, 0::2]).clamp(min=0, max=size[0]) cls_bbox[:, 1::2] = (cls_bbox[:, 1::2]).clamp(min=0, max=size[1]) prob = tonumpy(F.softmax(totensor(roi_score), dim=1)) raw_cls_bbox = tonumpy(cls_bbox) raw_prob = tonumpy(prob) bbox, label, score = self._suppress(raw_cls_bbox, raw_prob) bboxes.append(bbox) labels.append(label) scores.append(score) self.use_preset('evaluate') self.train() return bboxes, labels, scores def visualize_RPN(rois, scale, image): import matplotlib.pyplot as plt import matplotlib.patches as patches from PIL import Image ame = image img1 = Image.open('/home/hyobin/Documents/in-facedemo/facerecognition/PyFaceRecClient/simple-faster-rcnn-pytorch/'+image_name) fig, ax = plt.subplots(1) ax.imshow(img1) for i in range(10): y1, x1, y2, x2 = rois[i, :] y1, x1, y2, x2 = y1/scale, x1/scale, y2/scale, x2/scale h = y2 - y1 w = x2 - x1 rect = patches.Rectangle((x1,y1),w,h,linewidth=1,edgecolor='r',facecolor='none') ax.add_patch(rect) plt.show()
true
true
1c33f9ae72ee75467eb64f9ff3a3a2bc0a89a5fb
905
py
Python
interlecture/interauth/migrations/0001_initial.py
afriestad/interlecture
56d3d086ed6d0fd0de599120d12f88d6d1da2271
[ "MIT" ]
null
null
null
interlecture/interauth/migrations/0001_initial.py
afriestad/interlecture
56d3d086ed6d0fd0de599120d12f88d6d1da2271
[ "MIT" ]
null
null
null
interlecture/interauth/migrations/0001_initial.py
afriestad/interlecture
56d3d086ed6d0fd0de599120d12f88d6d1da2271
[ "MIT" ]
null
null
null
# -*- coding: utf-8 -*- # Generated by Django 1.10.5 on 2017-04-25 18:48 from __future__ import unicode_literals from django.conf import settings from django.db import migrations, models import django.db.models.deletion class Migration(migrations.Migration): initial = True dependencies = [ migrations.swappable_dependency(settings.AUTH_USER_MODEL), ] operations = [ migrations.CreateModel( name='UserActivation', fields=[ ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')), ('activation_key', models.CharField(max_length=128)), ('key_expires', models.DateTimeField()), ('user', models.OneToOneField(on_delete=django.db.models.deletion.CASCADE, related_name='profile', to=settings.AUTH_USER_MODEL)), ], ), ]
31.206897
145
0.649724
from __future__ import unicode_literals from django.conf import settings from django.db import migrations, models import django.db.models.deletion class Migration(migrations.Migration): initial = True dependencies = [ migrations.swappable_dependency(settings.AUTH_USER_MODEL), ] operations = [ migrations.CreateModel( name='UserActivation', fields=[ ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')), ('activation_key', models.CharField(max_length=128)), ('key_expires', models.DateTimeField()), ('user', models.OneToOneField(on_delete=django.db.models.deletion.CASCADE, related_name='profile', to=settings.AUTH_USER_MODEL)), ], ), ]
true
true
1c33f9b24d3204ce768b252cf5589524fd7c303b
1,562
py
Python
configs/detection/_base_/models/slowonly_r50_nl.py
Naoki-Wake/mmaction2
a2032605db82509744a18d993c94a06feb1efd15
[ "Apache-2.0" ]
null
null
null
configs/detection/_base_/models/slowonly_r50_nl.py
Naoki-Wake/mmaction2
a2032605db82509744a18d993c94a06feb1efd15
[ "Apache-2.0" ]
null
null
null
configs/detection/_base_/models/slowonly_r50_nl.py
Naoki-Wake/mmaction2
a2032605db82509744a18d993c94a06feb1efd15
[ "Apache-2.0" ]
null
null
null
# model setting model = dict( type='FastRCNN', backbone=dict( type='ResNet3dSlowOnly', depth=50, pretrained=None, pretrained2d=False, lateral=False, num_stages=4, conv1_kernel=(1, 7, 7), conv1_stride_t=1, pool1_stride_t=1, spatial_strides=(1, 2, 2, 1), norm_cfg=dict(type='BN3d', requires_grad=True), non_local=((0, 0, 0), (1, 0, 1, 0), (1, 0, 1, 0, 1, 0), (0, 0, 0)), non_local_cfg=dict( sub_sample=True, use_scale=True, norm_cfg=dict(type='BN3d', requires_grad=True), mode='embedded_gaussian')), roi_head=dict( type='AVARoIHead', bbox_roi_extractor=dict( type='SingleRoIExtractor3D', roi_layer_type='RoIAlign', output_size=8, with_temporal_pool=True), bbox_head=dict( type='BBoxHeadAVA', in_channels=2048, num_classes=81, multilabel=True, dropout_ratio=0.5)), train_cfg=dict( rcnn=dict( assigner=dict( type='MaxIoUAssignerAVA', pos_iou_thr=0.9, neg_iou_thr=0.9, min_pos_iou=0.9), sampler=dict( type='RandomSampler', num=32, pos_fraction=1, neg_pos_ub=-1, add_gt_as_proposals=True), pos_weight=1.0, debug=False)), test_cfg=dict(rcnn=dict(action_thr=0.00)))
30.627451
75
0.508963
model = dict( type='FastRCNN', backbone=dict( type='ResNet3dSlowOnly', depth=50, pretrained=None, pretrained2d=False, lateral=False, num_stages=4, conv1_kernel=(1, 7, 7), conv1_stride_t=1, pool1_stride_t=1, spatial_strides=(1, 2, 2, 1), norm_cfg=dict(type='BN3d', requires_grad=True), non_local=((0, 0, 0), (1, 0, 1, 0), (1, 0, 1, 0, 1, 0), (0, 0, 0)), non_local_cfg=dict( sub_sample=True, use_scale=True, norm_cfg=dict(type='BN3d', requires_grad=True), mode='embedded_gaussian')), roi_head=dict( type='AVARoIHead', bbox_roi_extractor=dict( type='SingleRoIExtractor3D', roi_layer_type='RoIAlign', output_size=8, with_temporal_pool=True), bbox_head=dict( type='BBoxHeadAVA', in_channels=2048, num_classes=81, multilabel=True, dropout_ratio=0.5)), train_cfg=dict( rcnn=dict( assigner=dict( type='MaxIoUAssignerAVA', pos_iou_thr=0.9, neg_iou_thr=0.9, min_pos_iou=0.9), sampler=dict( type='RandomSampler', num=32, pos_fraction=1, neg_pos_ub=-1, add_gt_as_proposals=True), pos_weight=1.0, debug=False)), test_cfg=dict(rcnn=dict(action_thr=0.00)))
true
true
1c33f9b3da0355f5366dab67a8602e113eeb6c9c
863
py
Python
belleflopt/migrations/0030_auto_20200228_2058.py
ucd-cws/eflows_optimization
2eb9f13a042ab81541488358ad0724555a5d57fc
[ "MIT" ]
2
2020-04-19T04:05:51.000Z
2021-04-19T02:47:40.000Z
belleflopt/migrations/0030_auto_20200228_2058.py
ucd-cws/eflows_optimization
2eb9f13a042ab81541488358ad0724555a5d57fc
[ "MIT" ]
7
2019-08-31T05:57:30.000Z
2019-11-27T23:58:13.000Z
belleflopt/migrations/0030_auto_20200228_2058.py
ucd-cws/eflows_optimization
2eb9f13a042ab81541488358ad0724555a5d57fc
[ "MIT" ]
null
null
null
# Generated by Django 2.2.4 on 2020-02-29 04:58 from django.db import migrations, models import django.db.models.deletion class Migration(migrations.Migration): dependencies = [ ('belleflopt', '0029_modelrun_description'), ] operations = [ migrations.AddField( model_name='modelrun', name='water_year', field=models.SmallIntegerField(default=2010), preserve_default=False, ), migrations.AlterField( model_name='dailyflow', name='model_run', field=models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, related_name='daily_flows', to='belleflopt.ModelRun'), ), migrations.AlterUniqueTogether( name='segmentpresence', unique_together={('stream_segment', 'species')}, ), ]
28.766667
135
0.618772
from django.db import migrations, models import django.db.models.deletion class Migration(migrations.Migration): dependencies = [ ('belleflopt', '0029_modelrun_description'), ] operations = [ migrations.AddField( model_name='modelrun', name='water_year', field=models.SmallIntegerField(default=2010), preserve_default=False, ), migrations.AlterField( model_name='dailyflow', name='model_run', field=models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, related_name='daily_flows', to='belleflopt.ModelRun'), ), migrations.AlterUniqueTogether( name='segmentpresence', unique_together={('stream_segment', 'species')}, ), ]
true
true
1c33f9c7f6d84650c468e676ac804f8fae83c447
1,200
py
Python
explorebg/questions/models.py
bvoytash/Quiz-Application
279a029b8e40513642bf002387f813d680a74ed7
[ "MIT" ]
null
null
null
explorebg/questions/models.py
bvoytash/Quiz-Application
279a029b8e40513642bf002387f813d680a74ed7
[ "MIT" ]
null
null
null
explorebg/questions/models.py
bvoytash/Quiz-Application
279a029b8e40513642bf002387f813d680a74ed7
[ "MIT" ]
null
null
null
import random from django.contrib.auth import get_user_model from django.db import models UserModel = get_user_model() class Question(models.Model): text = models.CharField(max_length=500) user = models.ForeignKey( UserModel, on_delete=models.CASCADE, ) def get_answer_quiz(self): answers = [ans for ans in self.answer_set.all()] random.shuffle(answers) return answers def get_answer(self): return self.answer_set.all() def __str__(self): return self.text class Answer(models.Model): text = models.CharField(max_length=200) correct = models.BooleanField(default=False) question = models.ForeignKey(Question, on_delete=models.CASCADE) def __str__(self): return f"question: {self.question.text} answer: {self.text}, correct: {self.correct}" class Like(models.Model): question = models.ForeignKey(Question, on_delete=models.CASCADE) user = models.ForeignKey( UserModel, on_delete=models.CASCADE, ) class Code(models.Model): text = models.CharField(max_length=10) user = models.ForeignKey( UserModel, on_delete=models.CASCADE, )
23.076923
93
0.678333
import random from django.contrib.auth import get_user_model from django.db import models UserModel = get_user_model() class Question(models.Model): text = models.CharField(max_length=500) user = models.ForeignKey( UserModel, on_delete=models.CASCADE, ) def get_answer_quiz(self): answers = [ans for ans in self.answer_set.all()] random.shuffle(answers) return answers def get_answer(self): return self.answer_set.all() def __str__(self): return self.text class Answer(models.Model): text = models.CharField(max_length=200) correct = models.BooleanField(default=False) question = models.ForeignKey(Question, on_delete=models.CASCADE) def __str__(self): return f"question: {self.question.text} answer: {self.text}, correct: {self.correct}" class Like(models.Model): question = models.ForeignKey(Question, on_delete=models.CASCADE) user = models.ForeignKey( UserModel, on_delete=models.CASCADE, ) class Code(models.Model): text = models.CharField(max_length=10) user = models.ForeignKey( UserModel, on_delete=models.CASCADE, )
true
true
1c33f9e9244a342d5f565b8b316868b728c73720
74
py
Python
ast-transformations-core/src/test/resources/org/jetbrains/research/ml/ast/transformations/commentsRemoval/data/out_6.py
JetBrains-Research/ast-transformations
0ab408af3275b520cc87a473f418c4b4dfcb0284
[ "MIT" ]
8
2021-01-19T21:15:54.000Z
2022-02-23T19:16:25.000Z
ast-transformations-core/src/test/resources/org/jetbrains/research/ml/ast/transformations/commentsRemoval/data/out_6.py
JetBrains-Research/ast-transformations
0ab408af3275b520cc87a473f418c4b4dfcb0284
[ "MIT" ]
4
2020-11-17T14:28:25.000Z
2022-02-24T07:54:28.000Z
ast-transformations-core/src/test/resources/org/jetbrains/research/ml/ast/transformations/commentsRemoval/data/out_6.py
nbirillo/ast-transformations
717706765a2da29087a0de768fc851698886dd65
[ "MIT" ]
1
2022-02-23T19:16:30.000Z
2022-02-23T19:16:30.000Z
def main(): b = 5 b = 510 def foo(): pass a = 5
8.222222
14
0.337838
def main(): b = 5 b = 510 def foo(): pass a = 5
true
true
1c33f9f8be2a7dfe451fcc83bd92fdf584bcdc77
14,611
py
Python
static/paddlex/tools/x2seg.py
cheneyveron/PaddleX
86f73fc6a66b12c638f642524bfd1cf730e26c4b
[ "Apache-2.0" ]
3,655
2020-03-28T09:19:50.000Z
2022-03-31T13:28:39.000Z
static/paddlex/tools/x2seg.py
cheneyveron/PaddleX
86f73fc6a66b12c638f642524bfd1cf730e26c4b
[ "Apache-2.0" ]
829
2020-03-28T04:03:18.000Z
2022-03-31T14:34:30.000Z
static/paddlex/tools/x2seg.py
cheneyveron/PaddleX
86f73fc6a66b12c638f642524bfd1cf730e26c4b
[ "Apache-2.0" ]
738
2020-03-28T03:56:46.000Z
2022-03-31T13:11:03.000Z
#!/usr/bin/env python # coding: utf-8 # Copyright (c) 2020 PaddlePaddle Authors. 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. import cv2 import uuid import json import os import os.path as osp import shutil import numpy as np import PIL.Image from .base import MyEncoder, is_pic, get_encoding import math class X2Seg(object): def __init__(self): self.labels2ids = {'_background_': 0} def shapes_to_label(self, img_shape, shapes, label_name_to_value): # 该函数基于https://github.com/wkentaro/labelme/blob/master/labelme/utils/shape.py实现。 def shape_to_mask(img_shape, points, shape_type=None, line_width=10, point_size=5): mask = np.zeros(img_shape[:2], dtype=np.uint8) mask = PIL.Image.fromarray(mask) draw = PIL.ImageDraw.Draw(mask) xy = [tuple(point) for point in points] if shape_type == 'circle': assert len( xy) == 2, 'Shape of shape_type=circle must have 2 points' (cx, cy), (px, py) = xy d = math.sqrt((cx - px)**2 + (cy - py)**2) draw.ellipse( [cx - d, cy - d, cx + d, cy + d], outline=1, fill=1) elif shape_type == 'rectangle': assert len( xy) == 2, 'Shape of shape_type=rectangle must have 2 points' draw.rectangle(xy, outline=1, fill=1) elif shape_type == 'line': assert len( xy) == 2, 'Shape of shape_type=line must have 2 points' draw.line(xy=xy, fill=1, width=line_width) elif shape_type == 'linestrip': draw.line(xy=xy, fill=1, width=line_width) elif shape_type == 'point': assert len( xy) == 1, 'Shape of shape_type=point must have 1 points' cx, cy = xy[0] r = point_size draw.ellipse( [cx - r, cy - r, cx + r, cy + r], outline=1, fill=1) else: assert len(xy) > 2, 'Polygon must have points more than 2' draw.polygon(xy=xy, outline=1, fill=1) mask = np.array(mask, dtype=bool) return mask cls = np.zeros(img_shape[:2], dtype=np.int32) ins = np.zeros_like(cls) instances = [] for shape in shapes: points = shape['points'] label = shape['label'] group_id = shape.get('group_id') if group_id is None: group_id = uuid.uuid1() shape_type = shape.get('shape_type', None) cls_name = label instance = (cls_name, group_id) if instance not in instances: instances.append(instance) ins_id = instances.index(instance) + 1 cls_id = label_name_to_value[cls_name] mask = shape_to_mask(img_shape[:2], points, shape_type) cls[mask] = cls_id ins[mask] = ins_id return cls, ins def get_color_map_list(self, num_classes): color_map = num_classes * [0, 0, 0] for i in range(0, num_classes): j = 0 lab = i while lab: color_map[i * 3] |= (((lab >> 0) & 1) << (7 - j)) color_map[i * 3 + 1] |= (((lab >> 1) & 1) << (7 - j)) color_map[i * 3 + 2] |= (((lab >> 2) & 1) << (7 - j)) j += 1 lab >>= 3 return color_map def convert(self, image_dir, json_dir, dataset_save_dir): """转换。 Args: image_dir (str): 图像文件存放的路径。 json_dir (str): 与每张图像对应的json文件的存放路径。 dataset_save_dir (str): 转换后数据集存放路径。 """ assert osp.exists(image_dir), "The image folder does not exist!" assert osp.exists(json_dir), "The json folder does not exist!" if not osp.exists(dataset_save_dir): os.makedirs(dataset_save_dir) # Convert the image files. new_image_dir = osp.join(dataset_save_dir, "JPEGImages") if osp.exists(new_image_dir): raise Exception( "The directory {} is already exist, please remove the directory first". format(new_image_dir)) os.makedirs(new_image_dir) for img_name in os.listdir(image_dir): if is_pic(img_name): shutil.copyfile( osp.join(image_dir, img_name), osp.join(new_image_dir, img_name)) # Convert the json files. png_dir = osp.join(dataset_save_dir, "Annotations") if osp.exists(png_dir): shutil.rmtree(png_dir) os.makedirs(png_dir) self.get_labels2ids(new_image_dir, json_dir) self.json2png(new_image_dir, json_dir, png_dir) # Generate the labels.txt ids2labels = {v: k for k, v in self.labels2ids.items()} with open(osp.join(dataset_save_dir, 'labels.txt'), 'w') as fw: for i in range(len(ids2labels)): fw.write(ids2labels[i] + '\n') class JingLing2Seg(X2Seg): """将使用标注精灵标注的数据集转换为Seg数据集。 """ def __init__(self): super(JingLing2Seg, self).__init__() def get_labels2ids(self, image_dir, json_dir): for img_name in os.listdir(image_dir): img_name_part = osp.splitext(img_name)[0] json_file = osp.join(json_dir, img_name_part + ".json") if not osp.exists(json_file): os.remove(osp.join(image_dir, img_name)) continue with open(json_file, mode="r", \ encoding=get_encoding(json_file)) as j: json_info = json.load(j) if 'outputs' in json_info: for output in json_info['outputs']['object']: cls_name = output['name'] if cls_name not in self.labels2ids: self.labels2ids[cls_name] = len(self.labels2ids) def json2png(self, image_dir, json_dir, png_dir): color_map = self.get_color_map_list(256) for img_name in os.listdir(image_dir): img_name_part = osp.splitext(img_name)[0] json_file = osp.join(json_dir, img_name_part + ".json") if not osp.exists(json_file): os.remove(osp.join(image_dir, img_name)) continue with open(json_file, mode="r", \ encoding=get_encoding(json_file)) as j: json_info = json.load(j) data_shapes = [] if 'outputs' in json_info: for output in json_info['outputs']['object']: if 'polygon' in output.keys(): polygon = output['polygon'] name = output['name'] points = [] for i in range(1, int(len(polygon) / 2) + 1): points.append([ polygon['x' + str(i)], polygon['y' + str( i)] ]) shape = { 'label': name, 'points': points, 'shape_type': 'polygon' } data_shapes.append(shape) if 'size' not in json_info: continue img_shape = (json_info['size']['height'], json_info['size']['width'], json_info['size']['depth']) lbl, _ = self.shapes_to_label( img_shape=img_shape, shapes=data_shapes, label_name_to_value=self.labels2ids, ) out_png_file = osp.join(png_dir, img_name_part + '.png') if lbl.min() >= 0 and lbl.max() <= 255: lbl_pil = PIL.Image.fromarray(lbl.astype(np.uint8), mode='P') lbl_pil.putpalette(color_map) lbl_pil.save(out_png_file) else: raise ValueError( '[%s] Cannot save the pixel-wise class label as PNG. ' 'Please consider using the .npy format.' % out_png_file) class LabelMe2Seg(X2Seg): """将使用LabelMe标注的数据集转换为Seg数据集。 """ def __init__(self): super(LabelMe2Seg, self).__init__() def get_labels2ids(self, image_dir, json_dir): for img_name in os.listdir(image_dir): img_name_part = osp.splitext(img_name)[0] json_file = osp.join(json_dir, img_name_part + ".json") if not osp.exists(json_file): os.remove(osp.join(image_dir, img_name)) continue with open(json_file, mode="r", \ encoding=get_encoding(json_file)) as j: json_info = json.load(j) for shape in json_info['shapes']: cls_name = shape['label'] if cls_name not in self.labels2ids: self.labels2ids[cls_name] = len(self.labels2ids) def json2png(self, image_dir, json_dir, png_dir): color_map = self.get_color_map_list(256) for img_name in os.listdir(image_dir): img_name_part = osp.splitext(img_name)[0] json_file = osp.join(json_dir, img_name_part + ".json") if not osp.exists(json_file): os.remove(osp.join(image_dir, img_name)) continue img_file = osp.join(image_dir, img_name) img = np.asarray(PIL.Image.open(img_file)) with open(json_file, mode="r", \ encoding=get_encoding(json_file)) as j: json_info = json.load(j) lbl, _ = self.shapes_to_label( img_shape=img.shape, shapes=json_info['shapes'], label_name_to_value=self.labels2ids, ) out_png_file = osp.join(png_dir, img_name_part + '.png') if lbl.min() >= 0 and lbl.max() <= 255: lbl_pil = PIL.Image.fromarray(lbl.astype(np.uint8), mode='P') lbl_pil.putpalette(color_map) lbl_pil.save(out_png_file) else: raise ValueError( '[%s] Cannot save the pixel-wise class label as PNG. ' 'Please consider using the .npy format.' % out_png_file) class EasyData2Seg(X2Seg): """将使用EasyData标注的分割数据集转换为Seg数据集。 """ def __init__(self): super(EasyData2Seg, self).__init__() def get_labels2ids(self, image_dir, json_dir): for img_name in os.listdir(image_dir): img_name_part = osp.splitext(img_name)[0] json_file = osp.join(json_dir, img_name_part + ".json") if not osp.exists(json_file): os.remove(osp.join(image_dir, img_name)) continue with open(json_file, mode="r", \ encoding=get_encoding(json_file)) as j: json_info = json.load(j) for shape in json_info["labels"]: cls_name = shape['name'] if cls_name not in self.labels2ids: self.labels2ids[cls_name] = len(self.labels2ids) def mask2polygon(self, mask, label): contours, hierarchy = cv2.findContours( (mask).astype(np.uint8), cv2.RETR_TREE, cv2.CHAIN_APPROX_SIMPLE) segmentation = [] for contour in contours: contour_list = contour.flatten().tolist() if len(contour_list) > 4: points = [] for i in range(0, len(contour_list), 2): points.append([contour_list[i], contour_list[i + 1]]) shape = { 'label': label, 'points': points, 'shape_type': 'polygon' } segmentation.append(shape) return segmentation def json2png(self, image_dir, json_dir, png_dir): from pycocotools.mask import decode color_map = self.get_color_map_list(256) for img_name in os.listdir(image_dir): img_name_part = osp.splitext(img_name)[0] json_file = osp.join(json_dir, img_name_part + ".json") if not osp.exists(json_file): os.remove(osp.join(image_dir, img_name)) continue img_file = osp.join(image_dir, img_name) img = np.asarray(PIL.Image.open(img_file)) img_h = img.shape[0] img_w = img.shape[1] with open(json_file, mode="r", \ encoding=get_encoding(json_file)) as j: json_info = json.load(j) data_shapes = [] for shape in json_info['labels']: mask_dict = {} mask_dict['size'] = [img_h, img_w] mask_dict['counts'] = shape['mask'].encode() mask = decode(mask_dict) polygon = self.mask2polygon(mask, shape["name"]) data_shapes.extend(polygon) lbl, _ = self.shapes_to_label( img_shape=img.shape, shapes=data_shapes, label_name_to_value=self.labels2ids, ) out_png_file = osp.join(png_dir, img_name_part + '.png') if lbl.min() >= 0 and lbl.max() <= 255: lbl_pil = PIL.Image.fromarray(lbl.astype(np.uint8), mode='P') lbl_pil.putpalette(color_map) lbl_pil.save(out_png_file) else: raise ValueError( '[%s] Cannot save the pixel-wise class label as PNG. ' 'Please consider using the .npy format.' % out_png_file)
42.228324
88
0.524263
import cv2 import uuid import json import os import os.path as osp import shutil import numpy as np import PIL.Image from .base import MyEncoder, is_pic, get_encoding import math class X2Seg(object): def __init__(self): self.labels2ids = {'_background_': 0} def shapes_to_label(self, img_shape, shapes, label_name_to_value): def shape_to_mask(img_shape, points, shape_type=None, line_width=10, point_size=5): mask = np.zeros(img_shape[:2], dtype=np.uint8) mask = PIL.Image.fromarray(mask) draw = PIL.ImageDraw.Draw(mask) xy = [tuple(point) for point in points] if shape_type == 'circle': assert len( xy) == 2, 'Shape of shape_type=circle must have 2 points' (cx, cy), (px, py) = xy d = math.sqrt((cx - px)**2 + (cy - py)**2) draw.ellipse( [cx - d, cy - d, cx + d, cy + d], outline=1, fill=1) elif shape_type == 'rectangle': assert len( xy) == 2, 'Shape of shape_type=rectangle must have 2 points' draw.rectangle(xy, outline=1, fill=1) elif shape_type == 'line': assert len( xy) == 2, 'Shape of shape_type=line must have 2 points' draw.line(xy=xy, fill=1, width=line_width) elif shape_type == 'linestrip': draw.line(xy=xy, fill=1, width=line_width) elif shape_type == 'point': assert len( xy) == 1, 'Shape of shape_type=point must have 1 points' cx, cy = xy[0] r = point_size draw.ellipse( [cx - r, cy - r, cx + r, cy + r], outline=1, fill=1) else: assert len(xy) > 2, 'Polygon must have points more than 2' draw.polygon(xy=xy, outline=1, fill=1) mask = np.array(mask, dtype=bool) return mask cls = np.zeros(img_shape[:2], dtype=np.int32) ins = np.zeros_like(cls) instances = [] for shape in shapes: points = shape['points'] label = shape['label'] group_id = shape.get('group_id') if group_id is None: group_id = uuid.uuid1() shape_type = shape.get('shape_type', None) cls_name = label instance = (cls_name, group_id) if instance not in instances: instances.append(instance) ins_id = instances.index(instance) + 1 cls_id = label_name_to_value[cls_name] mask = shape_to_mask(img_shape[:2], points, shape_type) cls[mask] = cls_id ins[mask] = ins_id return cls, ins def get_color_map_list(self, num_classes): color_map = num_classes * [0, 0, 0] for i in range(0, num_classes): j = 0 lab = i while lab: color_map[i * 3] |= (((lab >> 0) & 1) << (7 - j)) color_map[i * 3 + 1] |= (((lab >> 1) & 1) << (7 - j)) color_map[i * 3 + 2] |= (((lab >> 2) & 1) << (7 - j)) j += 1 lab >>= 3 return color_map def convert(self, image_dir, json_dir, dataset_save_dir): assert osp.exists(image_dir), "The image folder does not exist!" assert osp.exists(json_dir), "The json folder does not exist!" if not osp.exists(dataset_save_dir): os.makedirs(dataset_save_dir) new_image_dir = osp.join(dataset_save_dir, "JPEGImages") if osp.exists(new_image_dir): raise Exception( "The directory {} is already exist, please remove the directory first". format(new_image_dir)) os.makedirs(new_image_dir) for img_name in os.listdir(image_dir): if is_pic(img_name): shutil.copyfile( osp.join(image_dir, img_name), osp.join(new_image_dir, img_name)) png_dir = osp.join(dataset_save_dir, "Annotations") if osp.exists(png_dir): shutil.rmtree(png_dir) os.makedirs(png_dir) self.get_labels2ids(new_image_dir, json_dir) self.json2png(new_image_dir, json_dir, png_dir) ids2labels = {v: k for k, v in self.labels2ids.items()} with open(osp.join(dataset_save_dir, 'labels.txt'), 'w') as fw: for i in range(len(ids2labels)): fw.write(ids2labels[i] + '\n') class JingLing2Seg(X2Seg): def __init__(self): super(JingLing2Seg, self).__init__() def get_labels2ids(self, image_dir, json_dir): for img_name in os.listdir(image_dir): img_name_part = osp.splitext(img_name)[0] json_file = osp.join(json_dir, img_name_part + ".json") if not osp.exists(json_file): os.remove(osp.join(image_dir, img_name)) continue with open(json_file, mode="r", \ encoding=get_encoding(json_file)) as j: json_info = json.load(j) if 'outputs' in json_info: for output in json_info['outputs']['object']: cls_name = output['name'] if cls_name not in self.labels2ids: self.labels2ids[cls_name] = len(self.labels2ids) def json2png(self, image_dir, json_dir, png_dir): color_map = self.get_color_map_list(256) for img_name in os.listdir(image_dir): img_name_part = osp.splitext(img_name)[0] json_file = osp.join(json_dir, img_name_part + ".json") if not osp.exists(json_file): os.remove(osp.join(image_dir, img_name)) continue with open(json_file, mode="r", \ encoding=get_encoding(json_file)) as j: json_info = json.load(j) data_shapes = [] if 'outputs' in json_info: for output in json_info['outputs']['object']: if 'polygon' in output.keys(): polygon = output['polygon'] name = output['name'] points = [] for i in range(1, int(len(polygon) / 2) + 1): points.append([ polygon['x' + str(i)], polygon['y' + str( i)] ]) shape = { 'label': name, 'points': points, 'shape_type': 'polygon' } data_shapes.append(shape) if 'size' not in json_info: continue img_shape = (json_info['size']['height'], json_info['size']['width'], json_info['size']['depth']) lbl, _ = self.shapes_to_label( img_shape=img_shape, shapes=data_shapes, label_name_to_value=self.labels2ids, ) out_png_file = osp.join(png_dir, img_name_part + '.png') if lbl.min() >= 0 and lbl.max() <= 255: lbl_pil = PIL.Image.fromarray(lbl.astype(np.uint8), mode='P') lbl_pil.putpalette(color_map) lbl_pil.save(out_png_file) else: raise ValueError( '[%s] Cannot save the pixel-wise class label as PNG. ' 'Please consider using the .npy format.' % out_png_file) class LabelMe2Seg(X2Seg): def __init__(self): super(LabelMe2Seg, self).__init__() def get_labels2ids(self, image_dir, json_dir): for img_name in os.listdir(image_dir): img_name_part = osp.splitext(img_name)[0] json_file = osp.join(json_dir, img_name_part + ".json") if not osp.exists(json_file): os.remove(osp.join(image_dir, img_name)) continue with open(json_file, mode="r", \ encoding=get_encoding(json_file)) as j: json_info = json.load(j) for shape in json_info['shapes']: cls_name = shape['label'] if cls_name not in self.labels2ids: self.labels2ids[cls_name] = len(self.labels2ids) def json2png(self, image_dir, json_dir, png_dir): color_map = self.get_color_map_list(256) for img_name in os.listdir(image_dir): img_name_part = osp.splitext(img_name)[0] json_file = osp.join(json_dir, img_name_part + ".json") if not osp.exists(json_file): os.remove(osp.join(image_dir, img_name)) continue img_file = osp.join(image_dir, img_name) img = np.asarray(PIL.Image.open(img_file)) with open(json_file, mode="r", \ encoding=get_encoding(json_file)) as j: json_info = json.load(j) lbl, _ = self.shapes_to_label( img_shape=img.shape, shapes=json_info['shapes'], label_name_to_value=self.labels2ids, ) out_png_file = osp.join(png_dir, img_name_part + '.png') if lbl.min() >= 0 and lbl.max() <= 255: lbl_pil = PIL.Image.fromarray(lbl.astype(np.uint8), mode='P') lbl_pil.putpalette(color_map) lbl_pil.save(out_png_file) else: raise ValueError( '[%s] Cannot save the pixel-wise class label as PNG. ' 'Please consider using the .npy format.' % out_png_file) class EasyData2Seg(X2Seg): def __init__(self): super(EasyData2Seg, self).__init__() def get_labels2ids(self, image_dir, json_dir): for img_name in os.listdir(image_dir): img_name_part = osp.splitext(img_name)[0] json_file = osp.join(json_dir, img_name_part + ".json") if not osp.exists(json_file): os.remove(osp.join(image_dir, img_name)) continue with open(json_file, mode="r", \ encoding=get_encoding(json_file)) as j: json_info = json.load(j) for shape in json_info["labels"]: cls_name = shape['name'] if cls_name not in self.labels2ids: self.labels2ids[cls_name] = len(self.labels2ids) def mask2polygon(self, mask, label): contours, hierarchy = cv2.findContours( (mask).astype(np.uint8), cv2.RETR_TREE, cv2.CHAIN_APPROX_SIMPLE) segmentation = [] for contour in contours: contour_list = contour.flatten().tolist() if len(contour_list) > 4: points = [] for i in range(0, len(contour_list), 2): points.append([contour_list[i], contour_list[i + 1]]) shape = { 'label': label, 'points': points, 'shape_type': 'polygon' } segmentation.append(shape) return segmentation def json2png(self, image_dir, json_dir, png_dir): from pycocotools.mask import decode color_map = self.get_color_map_list(256) for img_name in os.listdir(image_dir): img_name_part = osp.splitext(img_name)[0] json_file = osp.join(json_dir, img_name_part + ".json") if not osp.exists(json_file): os.remove(osp.join(image_dir, img_name)) continue img_file = osp.join(image_dir, img_name) img = np.asarray(PIL.Image.open(img_file)) img_h = img.shape[0] img_w = img.shape[1] with open(json_file, mode="r", \ encoding=get_encoding(json_file)) as j: json_info = json.load(j) data_shapes = [] for shape in json_info['labels']: mask_dict = {} mask_dict['size'] = [img_h, img_w] mask_dict['counts'] = shape['mask'].encode() mask = decode(mask_dict) polygon = self.mask2polygon(mask, shape["name"]) data_shapes.extend(polygon) lbl, _ = self.shapes_to_label( img_shape=img.shape, shapes=data_shapes, label_name_to_value=self.labels2ids, ) out_png_file = osp.join(png_dir, img_name_part + '.png') if lbl.min() >= 0 and lbl.max() <= 255: lbl_pil = PIL.Image.fromarray(lbl.astype(np.uint8), mode='P') lbl_pil.putpalette(color_map) lbl_pil.save(out_png_file) else: raise ValueError( '[%s] Cannot save the pixel-wise class label as PNG. ' 'Please consider using the .npy format.' % out_png_file)
true
true
1c33fa15ddbf9c5dfc357e4226f51b2734c6f579
738
py
Python
nodes/List/GetTaskRenderListIndex.py
atticus-lv/RenderNode
8a4797a2186b76fedebc5d634cff298e69089474
[ "Apache-2.0" ]
17
2021-11-21T09:26:55.000Z
2022-03-09T06:56:01.000Z
nodes/List/GetTaskRenderListIndex.py
atticus-lv/RenderNode
8a4797a2186b76fedebc5d634cff298e69089474
[ "Apache-2.0" ]
1
2021-12-05T13:02:48.000Z
2021-12-06T08:02:34.000Z
nodes/List/GetTaskRenderListIndex.py
atticus-lv/RenderNode
8a4797a2186b76fedebc5d634cff298e69089474
[ "Apache-2.0" ]
4
2021-11-23T14:49:34.000Z
2021-12-30T15:04:58.000Z
import bpy from bpy.props import * from ...nodes.BASE.node_base import RenderNodeBase class RenderNodeGetListIndex(RenderNodeBase): """A simple input node""" bl_idname = 'RenderNodeGetListIndex' bl_label = 'Get List Index' def init(self, context): self.create_output('RenderNodeSocketInt', "index", 'Index') def process(self,context,id,path): node = self.id_data.nodes.get(bpy.context.window_manager.rsn_active_list) if not node or node.bl_idname != 'RenderNodeTaskRenderListNode': return self.outputs[0].set_value(node.active_index) def register(): bpy.utils.register_class(RenderNodeGetListIndex) def unregister(): bpy.utils.unregister_class(RenderNodeGetListIndex)
26.357143
81
0.730352
import bpy from bpy.props import * from ...nodes.BASE.node_base import RenderNodeBase class RenderNodeGetListIndex(RenderNodeBase): bl_idname = 'RenderNodeGetListIndex' bl_label = 'Get List Index' def init(self, context): self.create_output('RenderNodeSocketInt', "index", 'Index') def process(self,context,id,path): node = self.id_data.nodes.get(bpy.context.window_manager.rsn_active_list) if not node or node.bl_idname != 'RenderNodeTaskRenderListNode': return self.outputs[0].set_value(node.active_index) def register(): bpy.utils.register_class(RenderNodeGetListIndex) def unregister(): bpy.utils.unregister_class(RenderNodeGetListIndex)
true
true
1c33fa1cca0ea17ed709ee6bbe64293dc43fa107
10,437
py
Python
das_decennial/programs/schema/attributes/hhtype.py
p-b-j/uscb-das-container-public
7f7ba44055da15d13b191180249e656e1bd398c6
[ "MIT" ]
1
2021-11-13T01:35:31.000Z
2021-11-13T01:35:31.000Z
das_decennial/programs/schema/attributes/hhtype.py
p-b-j/uscb-das-container-public
7f7ba44055da15d13b191180249e656e1bd398c6
[ "MIT" ]
1
2021-10-30T00:48:45.000Z
2021-11-01T23:33:46.000Z
das_decennial/programs/schema/attributes/hhtype.py
p-b-j/uscb-das-container-public
7f7ba44055da15d13b191180249e656e1bd398c6
[ "MIT" ]
null
null
null
from programs.schema.attributes.abstractattribute import AbstractAttribute from constants import CC class HHTypeAttr(AbstractAttribute): @staticmethod def getName(): return CC.ATTR_HHTYPE @staticmethod def getLevels(): return { 'Married opposite-sex with own children under 18, under 6 yrs only' : [0], 'Married opposite-sex with own children under 18, between 6 and 17 only': [1], 'Married opposite-sex with own children under 18, both ranges' : [2], 'Married opposite-sex no own children under 18' : [3], 'Married same-sex with own children only under 6 yrs' : [4], 'Married same-sex with own children between 6 and 17' : [5], 'Married same-sex with own children in both ranges' : [6], 'Married same-sex no own children under 18' : [7], 'Cohabiting opposite-sex with own children only under 6 yrs' : [8], 'Cohabiting opposite-sex with own children between 6 and 17' : [9], 'Cohabiting opposite-sex with own children in both ranges' : [10], 'Cohabiting opposite-sex with relatives, no own children under 18' : [11], 'Cohabiting opposite-sex without relatives, no own children under 18' : [12], 'Cohabiting same-sex with own children only under 6 yrs' : [13], 'Cohabiting same-sex with own children between 6 and 17' : [14], 'Cohabiting same-sex with own children in both ranges' : [15], 'Cohabiting same-sex with relatives, no own children under 18' : [16], 'Cohabiting same-sex without relatives, no own children under 18' : [17], 'No spouse or partner, alone' : [18], 'No spouse or partner with own children under 6' : [19], 'No spouse or partner with own children between 6 and 17.' : [20], 'No spouse or partner with own children in both ranges' : [21], 'No spouse or partner living with relatives but no own children' : [22], 'No spouse or partner and no relatives, not alone.' : [23] } @staticmethod def recodeHHtypeOwnChildrenUnderSix(): name = CC.HHTYPE_OWNCHILD_UNDERSIX groupings = { "Householder has own child under 6" : [0, 2, 4, 6, 8, 10, 13, 15, 19, 21] } return name, groupings @staticmethod def recodeHHtypeOwnChildUnder18(): name = CC.HHTYPE_OWNCHILD_UNDER18 groupings = { "Householder has own child under 18" : [0, 1, 2, 4, 5, 6, 8, 9, 10, 13, 14, 15, 19, 20, 21] } return name, groupings @staticmethod def recodeFamily(): name = CC.HHTYPE_FAMILY groupings = { "Family": [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 13, 14, 15, 16, 19, 20, 21, 22] } return name, groupings @staticmethod def recodeNonfamily(): name = CC.HHTYPE_NONFAMILY groupings = { "Non-Family": [12, 17, 18, 23] } return name, groupings @staticmethod def recodeMarriedFamily(): name = CC.HHTYPE_FAMILY_MARRIED groupings = { "Married Family": list(range(0,8)) } return name, groupings @staticmethod def recodeOtherFamily(): name = CC.HHTYPE_FAMILY_OTHER groupings = { "Other Family": [8, 9, 10, 11, 13, 14, 15, 16, 19, 20, 21, 22] } return name, groupings @staticmethod def recodeHHtypeAlone(): name = CC.HHTYPE_ALONE groupings = { "Alone": [18] } return name, groupings @staticmethod def recodeHHtypeNotAlone(): """ everything but living alone """ name = CC.HHTYPE_NOT_ALONE groupings = { "Not alone": [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 19, 20, 21, 22, 23] } return name, groupings @staticmethod def recodeNonfamilyNotAlone(): """ Nonfamily, not alone """ name = CC.HHTYPE_NONFAMILY_NOT_ALONE groupings = { "Nonfamily, Not alone": [12, 17, 23] } return name, groupings @staticmethod def recodeHHtypeNotSize2(): name = CC.HHTYPE_NOT_SIZE_TWO groupings = { "Types inconsistent with size 2": [0, 1, 2, 4, 5, 6, 8, 9, 10, 11, 13, 14, 15, 16, 18, 21] } return name, groupings @staticmethod def recodeHHtypeSizeTwoWithChild(): name = CC.HHTYPE_SIZE_TWO_WITH_CHILD groupings = { "Size 2, householder with child" : [19, 20] } return name, groupings @staticmethod def recodeHHtypeSizeTwoCouple(): name = CC.HHTYPE_SIZE_TWO_COUPLE groupings = { "Size 2, householder with spouse/unmarried partner" : [3, 7, 12, 17] } return name, groupings @staticmethod def recodeHHtypeNotSizeThree(): name = CC.HHTYPE_NOT_SIZE_THREE groupings = { "Type not consistent with size 3": [2, 6, 10, 15, 18] } return name, groupings @staticmethod def recodeHHtypeSizeThreeNotMulti(): name = CC.HHTYPE_SIZE_THREE_NOT_MULTI groupings = { "Size 3, can't be multi": [0, 1, 3, 4, 5, 7, 8, 9, 11, 12, 13, 14, 16, 17, 21, 23] } return name, groupings @staticmethod def recodeHHtypeSizeThreeWithTwoChildren(): name = CC.HHTYPE_SIZE_THREE_WITH_TWO_CHILDREN groupings = { "Size 3, two children": [21] } return name, groupings @staticmethod def recodeHHtypeSizeThreeCoupleWithOneChild(): name = CC.HHTYPE_SIZE_THREE_COUPLE_WITH_ONE_CHILD groupings = { "Size 3, couple with one child": [0, 1, 4, 5, 8, 9, 13, 14] } return name, groupings @staticmethod def recodeHHtypeSizeFourNotMulti(): name = CC.HHTYPE_SIZE_FOUR_NOT_MULTI groupings = { "Size 4, can't be multigen": [2, 6, 10, 12, 15, 17, 23] } return name, groupings @staticmethod def recodeHHtypeSizeFourCoupleWithTwoChildren(): name = CC.HHTYPE_SIZE_FOUR_COUPLE_WITH_TWO_CHILDREN groupings = { "Size 4, couple with two children": [2, 6, 10, 15] } return name, groupings @staticmethod def recodeHHtypeNotMulti(): name = CC.HHTYPE_NOT_MULTI groupings = { "Can never be multigen regardless of size" : [12, 17, 18, 23] } return name, groupings @staticmethod def recodeFamilyMarriedWithChildrenIndicator(): name = CC.HHTYPE_FAMILY_MARRIED_WITH_CHILDREN_INDICATOR groupings = { "Married without own children under 18": [3, 7], "Married with own children under 18" : [0, 1, 2, 4, 5, 6] } return name, groupings @staticmethod def recodeFamilyOtherWithChildrenIndicator(): name = CC.HHTYPE_FAMILY_OTHER_WITH_CHILDREN_INDICATOR groupings = { "Other family without own children under 18": [11, 16], "Other family with own children under 18" : [8, 9, 10, 13, 14, 15] } return name, groupings @staticmethod def recodeHHtypeCohabiting(): name = CC.HHTYPE_COHABITING groupings = { "Cohabiting": list(range(8, 18)) } return name, groupings @staticmethod def recodeHHtypeCohabitingWithChildrenIndicator(): name = CC.HHTYPE_COHABITING_WITH_CHILDREN_INDICATOR groupings = { "Cohabiting without own children under 18" : [11, 12, 16, 17], "Cohabiting with own children under 18" : [8, 9, 10, 13, 14, 15] } return name, groupings @staticmethod def recodeHHtypeNoSpouseOrPartner(): name = CC.HHTYPE_NO_SPOUSE_OR_PARTNER groupings = { "No spouse or partner": list(range(18, 24)) } return name, groupings @staticmethod def recodeHHtypeNoSpouseOrPartnerLevels(): name = CC.HHTYPE_NO_SPOUSE_OR_PARTNER_LEVELS groupings = { "Alone": [18], "With own children": [19, 20, 21], "With relatives, no own children": [22], "No relatives, not alone": [23] } return name, groupings @staticmethod def recodeFamilyMarriedWithChildrenLevels(): name = CC.HHTYPE_FAMILY_MARRIED_WITH_CHILDREN_LEVELS groupings = { "Married with children under 6 only" : [0,4], "Married with children 6 to 17 years only" : [1,5], "Married with children under 6 years and 6 to 17 years": [2,6] } return name, groupings @staticmethod def recodeFamilyOtherWithChildrenLevels(): name = CC.HHTYPE_FAMILY_OTHER_WITH_CHILDREN_LEVELS groupings = { "Other family with children under 6 only" : [8,13,19], "Other family with children 6 to 17 years only" : [9,14,20], "Other family with children under 6 years and 6 to 17 years": [10,15,21] } return name, groupings @staticmethod def recodeHHtypeCoupleLevels(): name = CC.HHTYPE_COUPLE_LEVELS groupings = { "Married": list(range(8)), "Unmarried Partner": list(range(8,18)), "All others": list(range(18,24)) } return name, groupings @staticmethod def recodeHHtypeOppositeSexLevels(): name = CC.HHTYPE_OPPOSITE_SEX_LEVELS groupings = { "Married Opposite": list(range(4)), "Partner Opposite": list(range(8,13)) } return name, groupings @staticmethod def recodeHHtypeSameSexLevels(): name = CC.HHTYPE_SAME_SEX_LEVELS groupings = { "Married Same": list(range(4,8)), "Partner Same": list(range(13,18)) } return name, groupings
35.379661
107
0.562326
from programs.schema.attributes.abstractattribute import AbstractAttribute from constants import CC class HHTypeAttr(AbstractAttribute): @staticmethod def getName(): return CC.ATTR_HHTYPE @staticmethod def getLevels(): return { 'Married opposite-sex with own children under 18, under 6 yrs only' : [0], 'Married opposite-sex with own children under 18, between 6 and 17 only': [1], 'Married opposite-sex with own children under 18, both ranges' : [2], 'Married opposite-sex no own children under 18' : [3], 'Married same-sex with own children only under 6 yrs' : [4], 'Married same-sex with own children between 6 and 17' : [5], 'Married same-sex with own children in both ranges' : [6], 'Married same-sex no own children under 18' : [7], 'Cohabiting opposite-sex with own children only under 6 yrs' : [8], 'Cohabiting opposite-sex with own children between 6 and 17' : [9], 'Cohabiting opposite-sex with own children in both ranges' : [10], 'Cohabiting opposite-sex with relatives, no own children under 18' : [11], 'Cohabiting opposite-sex without relatives, no own children under 18' : [12], 'Cohabiting same-sex with own children only under 6 yrs' : [13], 'Cohabiting same-sex with own children between 6 and 17' : [14], 'Cohabiting same-sex with own children in both ranges' : [15], 'Cohabiting same-sex with relatives, no own children under 18' : [16], 'Cohabiting same-sex without relatives, no own children under 18' : [17], 'No spouse or partner, alone' : [18], 'No spouse or partner with own children under 6' : [19], 'No spouse or partner with own children between 6 and 17.' : [20], 'No spouse or partner with own children in both ranges' : [21], 'No spouse or partner living with relatives but no own children' : [22], 'No spouse or partner and no relatives, not alone.' : [23] } @staticmethod def recodeHHtypeOwnChildrenUnderSix(): name = CC.HHTYPE_OWNCHILD_UNDERSIX groupings = { "Householder has own child under 6" : [0, 2, 4, 6, 8, 10, 13, 15, 19, 21] } return name, groupings @staticmethod def recodeHHtypeOwnChildUnder18(): name = CC.HHTYPE_OWNCHILD_UNDER18 groupings = { "Householder has own child under 18" : [0, 1, 2, 4, 5, 6, 8, 9, 10, 13, 14, 15, 19, 20, 21] } return name, groupings @staticmethod def recodeFamily(): name = CC.HHTYPE_FAMILY groupings = { "Family": [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 13, 14, 15, 16, 19, 20, 21, 22] } return name, groupings @staticmethod def recodeNonfamily(): name = CC.HHTYPE_NONFAMILY groupings = { "Non-Family": [12, 17, 18, 23] } return name, groupings @staticmethod def recodeMarriedFamily(): name = CC.HHTYPE_FAMILY_MARRIED groupings = { "Married Family": list(range(0,8)) } return name, groupings @staticmethod def recodeOtherFamily(): name = CC.HHTYPE_FAMILY_OTHER groupings = { "Other Family": [8, 9, 10, 11, 13, 14, 15, 16, 19, 20, 21, 22] } return name, groupings @staticmethod def recodeHHtypeAlone(): name = CC.HHTYPE_ALONE groupings = { "Alone": [18] } return name, groupings @staticmethod def recodeHHtypeNotAlone(): name = CC.HHTYPE_NOT_ALONE groupings = { "Not alone": [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 19, 20, 21, 22, 23] } return name, groupings @staticmethod def recodeNonfamilyNotAlone(): name = CC.HHTYPE_NONFAMILY_NOT_ALONE groupings = { "Nonfamily, Not alone": [12, 17, 23] } return name, groupings @staticmethod def recodeHHtypeNotSize2(): name = CC.HHTYPE_NOT_SIZE_TWO groupings = { "Types inconsistent with size 2": [0, 1, 2, 4, 5, 6, 8, 9, 10, 11, 13, 14, 15, 16, 18, 21] } return name, groupings @staticmethod def recodeHHtypeSizeTwoWithChild(): name = CC.HHTYPE_SIZE_TWO_WITH_CHILD groupings = { "Size 2, householder with child" : [19, 20] } return name, groupings @staticmethod def recodeHHtypeSizeTwoCouple(): name = CC.HHTYPE_SIZE_TWO_COUPLE groupings = { "Size 2, householder with spouse/unmarried partner" : [3, 7, 12, 17] } return name, groupings @staticmethod def recodeHHtypeNotSizeThree(): name = CC.HHTYPE_NOT_SIZE_THREE groupings = { "Type not consistent with size 3": [2, 6, 10, 15, 18] } return name, groupings @staticmethod def recodeHHtypeSizeThreeNotMulti(): name = CC.HHTYPE_SIZE_THREE_NOT_MULTI groupings = { "Size 3, can't be multi": [0, 1, 3, 4, 5, 7, 8, 9, 11, 12, 13, 14, 16, 17, 21, 23] } return name, groupings @staticmethod def recodeHHtypeSizeThreeWithTwoChildren(): name = CC.HHTYPE_SIZE_THREE_WITH_TWO_CHILDREN groupings = { "Size 3, two children": [21] } return name, groupings @staticmethod def recodeHHtypeSizeThreeCoupleWithOneChild(): name = CC.HHTYPE_SIZE_THREE_COUPLE_WITH_ONE_CHILD groupings = { "Size 3, couple with one child": [0, 1, 4, 5, 8, 9, 13, 14] } return name, groupings @staticmethod def recodeHHtypeSizeFourNotMulti(): name = CC.HHTYPE_SIZE_FOUR_NOT_MULTI groupings = { "Size 4, can't be multigen": [2, 6, 10, 12, 15, 17, 23] } return name, groupings @staticmethod def recodeHHtypeSizeFourCoupleWithTwoChildren(): name = CC.HHTYPE_SIZE_FOUR_COUPLE_WITH_TWO_CHILDREN groupings = { "Size 4, couple with two children": [2, 6, 10, 15] } return name, groupings @staticmethod def recodeHHtypeNotMulti(): name = CC.HHTYPE_NOT_MULTI groupings = { "Can never be multigen regardless of size" : [12, 17, 18, 23] } return name, groupings @staticmethod def recodeFamilyMarriedWithChildrenIndicator(): name = CC.HHTYPE_FAMILY_MARRIED_WITH_CHILDREN_INDICATOR groupings = { "Married without own children under 18": [3, 7], "Married with own children under 18" : [0, 1, 2, 4, 5, 6] } return name, groupings @staticmethod def recodeFamilyOtherWithChildrenIndicator(): name = CC.HHTYPE_FAMILY_OTHER_WITH_CHILDREN_INDICATOR groupings = { "Other family without own children under 18": [11, 16], "Other family with own children under 18" : [8, 9, 10, 13, 14, 15] } return name, groupings @staticmethod def recodeHHtypeCohabiting(): name = CC.HHTYPE_COHABITING groupings = { "Cohabiting": list(range(8, 18)) } return name, groupings @staticmethod def recodeHHtypeCohabitingWithChildrenIndicator(): name = CC.HHTYPE_COHABITING_WITH_CHILDREN_INDICATOR groupings = { "Cohabiting without own children under 18" : [11, 12, 16, 17], "Cohabiting with own children under 18" : [8, 9, 10, 13, 14, 15] } return name, groupings @staticmethod def recodeHHtypeNoSpouseOrPartner(): name = CC.HHTYPE_NO_SPOUSE_OR_PARTNER groupings = { "No spouse or partner": list(range(18, 24)) } return name, groupings @staticmethod def recodeHHtypeNoSpouseOrPartnerLevels(): name = CC.HHTYPE_NO_SPOUSE_OR_PARTNER_LEVELS groupings = { "Alone": [18], "With own children": [19, 20, 21], "With relatives, no own children": [22], "No relatives, not alone": [23] } return name, groupings @staticmethod def recodeFamilyMarriedWithChildrenLevels(): name = CC.HHTYPE_FAMILY_MARRIED_WITH_CHILDREN_LEVELS groupings = { "Married with children under 6 only" : [0,4], "Married with children 6 to 17 years only" : [1,5], "Married with children under 6 years and 6 to 17 years": [2,6] } return name, groupings @staticmethod def recodeFamilyOtherWithChildrenLevels(): name = CC.HHTYPE_FAMILY_OTHER_WITH_CHILDREN_LEVELS groupings = { "Other family with children under 6 only" : [8,13,19], "Other family with children 6 to 17 years only" : [9,14,20], "Other family with children under 6 years and 6 to 17 years": [10,15,21] } return name, groupings @staticmethod def recodeHHtypeCoupleLevels(): name = CC.HHTYPE_COUPLE_LEVELS groupings = { "Married": list(range(8)), "Unmarried Partner": list(range(8,18)), "All others": list(range(18,24)) } return name, groupings @staticmethod def recodeHHtypeOppositeSexLevels(): name = CC.HHTYPE_OPPOSITE_SEX_LEVELS groupings = { "Married Opposite": list(range(4)), "Partner Opposite": list(range(8,13)) } return name, groupings @staticmethod def recodeHHtypeSameSexLevels(): name = CC.HHTYPE_SAME_SEX_LEVELS groupings = { "Married Same": list(range(4,8)), "Partner Same": list(range(13,18)) } return name, groupings
true
true
1c33fbacc173c5443bc0886f17a8de69e63f17c2
196
py
Python
example/myapp/models.py
shamanu4/django-fine-uploader
8b53fdbaa27f749bf103b77d168fdd5e02def4e5
[ "MIT" ]
null
null
null
example/myapp/models.py
shamanu4/django-fine-uploader
8b53fdbaa27f749bf103b77d168fdd5e02def4e5
[ "MIT" ]
null
null
null
example/myapp/models.py
shamanu4/django-fine-uploader
8b53fdbaa27f749bf103b77d168fdd5e02def4e5
[ "MIT" ]
null
null
null
from __future__ import unicode_literals from django.db import models class FineFile(models.Model): fine_file = models.FileField() def __str__(self): return self.fine_file.name
17.818182
39
0.739796
from __future__ import unicode_literals from django.db import models class FineFile(models.Model): fine_file = models.FileField() def __str__(self): return self.fine_file.name
true
true
1c33fc85f24467f19a7d8f96bb4425aba7affc44
24,545
py
Python
src/garage/torch/modules/gaussian_mlp_module.py
waldow90/garage
1ea04b8b90d2da0d7da10e8604a144018b61b81c
[ "MIT" ]
1
2020-02-19T00:01:29.000Z
2020-02-19T00:01:29.000Z
src/garage/torch/modules/gaussian_mlp_module.py
Ashutosh-Adhikari/garage
482a26a07d46091f878c41b582f1478588e397ff
[ "MIT" ]
null
null
null
src/garage/torch/modules/gaussian_mlp_module.py
Ashutosh-Adhikari/garage
482a26a07d46091f878c41b582f1478588e397ff
[ "MIT" ]
1
2020-02-13T12:05:35.000Z
2020-02-13T12:05:35.000Z
"""GaussianMLPModule.""" import abc import torch from torch import nn from torch.distributions import Normal from torch.distributions.independent import Independent from garage.torch.modules.mlp_module import MLPModule from garage.torch.modules.multi_headed_mlp_module import MultiHeadedMLPModule class GaussianMLPBaseModule(nn.Module): """Base of GaussianMLPModel. Args: input_dim (int): Input dimension of the model. output_dim (int): Output dimension of the model. hidden_sizes (list[int]): Output dimension of dense layer(s) for the MLP for mean. For example, (32, 32) means the MLP consists of two hidden layers, each with 32 hidden units. hidden_nonlinearity (callable): Activation function for intermediate dense layer(s). It should return a torch.Tensor. Set it to None to maintain a linear activation. hidden_w_init (callable): Initializer function for the weight of intermediate dense layer(s). The function should return a torch.Tensor. hidden_b_init (callable): Initializer function for the bias of intermediate dense layer(s). The function should return a torch.Tensor. output_nonlinearity (callable): Activation function for output dense layer. It should return a torch.Tensor. Set it to None to maintain a linear activation. output_w_init (callable): Initializer function for the weight of output dense layer(s). The function should return a torch.Tensor. output_b_init (callable): Initializer function for the bias of output dense layer(s). The function should return a torch.Tensor. learn_std (bool): Is std trainable. init_std (float): Initial value for std. (plain value - not log or exponentiated). std_hidden_sizes (list[int]): Output dimension of dense layer(s) for the MLP for std. For example, (32, 32) means the MLP consists of two hidden layers, each with 32 hidden units. min_std (float): If not None, the std is at least the value of min_std, to avoid numerical issues (plain value - not log or exponentiated). max_std (float): If not None, the std is at most the value of max_std, to avoid numerical issues (plain value - not log or exponentiated). std_hidden_nonlinearity (callable): Nonlinearity for each hidden layer in the std network. std_hidden_w_init (callable): Initializer function for the weight of hidden layer (s). std_hidden_b_init (callable): Initializer function for the bias of intermediate dense layer(s). std_output_nonlinearity (callable): Activation function for output dense layer in the std network. It should return a torch.Tensor. Set it to None to maintain a linear activation. std_output_w_init (callable): Initializer function for the weight of output dense layer(s) in the std network. std_parameterization (str): How the std should be parametrized. There are two options: - exp: the logarithm of the std will be stored, and applied a exponential transformation. - softplus: the std will be computed as log(1+exp(x)). layer_normalization (bool): Bool for using layer normalization or not. """ def __init__(self, input_dim, output_dim, hidden_sizes=(32, 32), hidden_nonlinearity=torch.tanh, hidden_w_init=nn.init.xavier_uniform_, hidden_b_init=nn.init.zeros_, output_nonlinearity=None, output_w_init=nn.init.xavier_uniform_, output_b_init=nn.init.zeros_, learn_std=True, init_std=1.0, min_std=1e-6, max_std=None, std_hidden_sizes=(32, 32), std_hidden_nonlinearity=torch.tanh, std_hidden_w_init=nn.init.xavier_uniform_, std_hidden_b_init=nn.init.zeros_, std_output_nonlinearity=None, std_output_w_init=nn.init.xavier_uniform_, std_parameterization='exp', layer_normalization=False): super().__init__() self._input_dim = input_dim self._hidden_sizes = hidden_sizes self._action_dim = output_dim self._learn_std = learn_std self._std_hidden_sizes = std_hidden_sizes self._min_std = min_std self._max_std = max_std self._std_hidden_nonlinearity = std_hidden_nonlinearity self._std_hidden_w_init = std_hidden_w_init self._std_hidden_b_init = std_hidden_b_init self._std_output_nonlinearity = std_output_nonlinearity self._std_output_w_init = std_output_w_init self._std_parameterization = std_parameterization self._hidden_nonlinearity = hidden_nonlinearity self._hidden_w_init = hidden_w_init self._hidden_b_init = hidden_b_init self._output_nonlinearity = output_nonlinearity self._output_w_init = output_w_init self._output_b_init = output_b_init self._layer_normalization = layer_normalization if self._std_parameterization not in ('exp', 'softplus'): raise NotImplementedError init_std_param = torch.Tensor([init_std]).log() if self._learn_std: self._init_std = torch.nn.Parameter(init_std_param) else: self._init_std = init_std_param self._min_std_param = self._max_std_param = None if min_std is not None: self._min_std_param = torch.Tensor([min_std]).log() if max_std is not None: self._max_std_param = torch.Tensor([max_std]).log() @abc.abstractmethod def _get_mean_and_log_std(self, *inputs): pass def forward(self, *inputs): """Forward method. Args: *inputs: Input to the module. Returns: torch.Tensor: Module output. """ mean, log_std_uncentered = self._get_mean_and_log_std(*inputs) if self._min_std_param or self._max_std_param: log_std_uncentered = log_std_uncentered.clamp( min=self._to_scalar_if_not_none(self._min_std_param), max=self._to_scalar_if_not_none(self._max_std_param)) if self._std_parameterization == 'exp': std = log_std_uncentered.exp() else: std = log_std_uncentered.exp().exp().add(1.).log() dist = Independent(Normal(mean, std), 1) return dist # pylint: disable=no-self-use def _to_scalar_if_not_none(self, tensor): """Convert torch.Tensor of a single value to a Python number. Args: tensor (torch.Tensor): A torch.Tensor of a single value. Returns: float: The value of tensor. """ return None if tensor is None else tensor.item() class GaussianMLPModule(GaussianMLPBaseModule): """GaussianMLPModule that mean and std share the same network. Args: input_dim (int): Input dimension of the model. output_dim (int): Output dimension of the model. hidden_sizes (list[int]): Output dimension of dense layer(s) for the MLP for mean. For example, (32, 32) means the MLP consists of two hidden layers, each with 32 hidden units. hidden_nonlinearity (callable): Activation function for intermediate dense layer(s). It should return a torch.Tensor. Set it to None to maintain a linear activation. hidden_w_init (callable): Initializer function for the weight of intermediate dense layer(s). The function should return a torch.Tensor. hidden_b_init (callable): Initializer function for the bias of intermediate dense layer(s). The function should return a torch.Tensor. output_nonlinearity (callable): Activation function for output dense layer. It should return a torch.Tensor. Set it to None to maintain a linear activation. output_w_init (callable): Initializer function for the weight of output dense layer(s). The function should return a torch.Tensor. output_b_init (callable): Initializer function for the bias of output dense layer(s). The function should return a torch.Tensor. learn_std (bool): Is std trainable. init_std (float): Initial value for std. (plain value - not log or exponentiated). min_std (float): If not None, the std is at least the value of min_std, to avoid numerical issues (plain value - not log or exponentiated). max_std (float): If not None, the std is at most the value of max_std, to avoid numerical issues (plain value - not log or exponentiated). std_parameterization (str): How the std should be parametrized. There are two options: - exp: the logarithm of the std will be stored, and applied a exponential transformation - softplus: the std will be computed as log(1+exp(x)) layer_normalization (bool): Bool for using layer normalization or not. """ def __init__(self, input_dim, output_dim, hidden_sizes=(32, 32), hidden_nonlinearity=torch.tanh, hidden_w_init=nn.init.xavier_uniform_, hidden_b_init=nn.init.zeros_, output_nonlinearity=None, output_w_init=nn.init.xavier_uniform_, output_b_init=nn.init.zeros_, learn_std=True, init_std=1.0, min_std=1e-6, max_std=None, std_parameterization='exp', layer_normalization=False): super(GaussianMLPModule, self).__init__(input_dim=input_dim, output_dim=output_dim, hidden_sizes=hidden_sizes, hidden_nonlinearity=hidden_nonlinearity, hidden_w_init=hidden_w_init, hidden_b_init=hidden_b_init, output_nonlinearity=output_nonlinearity, output_w_init=output_w_init, output_b_init=output_b_init, learn_std=learn_std, init_std=init_std, min_std=min_std, max_std=max_std, std_parameterization=std_parameterization, layer_normalization=layer_normalization) self._mean_module = MLPModule( input_dim=self._input_dim, output_dim=self._action_dim, hidden_sizes=self._hidden_sizes, hidden_nonlinearity=self._hidden_nonlinearity, hidden_w_init=self._hidden_w_init, hidden_b_init=self._hidden_b_init, output_nonlinearity=self._output_nonlinearity, output_w_init=self._output_w_init, output_b_init=self._output_b_init, layer_normalization=self._layer_normalization) def _get_mean_and_log_std(self, *inputs): """Get mean and std of Gaussian distribution given inputs. Args: *inputs: Input to the module. Returns: tuple: * mean (torch.Tensor): The mean of Gaussian distribution. * std (torch.Tensor): The variance of Gaussian distribution. """ assert len(inputs) == 1 mean = self._mean_module(*inputs) broadcast_shape = list(inputs[0].shape[:-1]) + [self._action_dim] uncentered_log_std = torch.zeros(*broadcast_shape) + self._init_std return mean, uncentered_log_std class GaussianMLPIndependentStdModule(GaussianMLPBaseModule): """GaussianMLPModule which has two different mean and std network. Args: input_dim (int): Input dimension of the model. output_dim (int): Output dimension of the model. hidden_sizes (list[int]): Output dimension of dense layer(s) for the MLP for mean. For example, (32, 32) means the MLP consists of two hidden layers, each with 32 hidden units. hidden_nonlinearity (callable): Activation function for intermediate dense layer(s). It should return a torch.Tensor. Set it to None to maintain a linear activation. hidden_w_init (callable): Initializer function for the weight of intermediate dense layer(s). The function should return a torch.Tensor. hidden_b_init (callable): Initializer function for the bias of intermediate dense layer(s). The function should return a torch.Tensor. output_nonlinearity (callable): Activation function for output dense layer. It should return a torch.Tensor. Set it to None to maintain a linear activation. output_w_init (callable): Initializer function for the weight of output dense layer(s). The function should return a torch.Tensor. output_b_init (callable): Initializer function for the bias of output dense layer(s). The function should return a torch.Tensor. learn_std (bool): Is std trainable. init_std (float): Initial value for std. (plain value - not log or exponentiated). min_std (float): If not None, the std is at least the value of min_std, to avoid numerical issues (plain value - not log or exponentiated). max_std (float): If not None, the std is at most the value of max_std, to avoid numerical issues (plain value - not log or exponentiated). std_hidden_sizes (list[int]): Output dimension of dense layer(s) for the MLP for std. For example, (32, 32) means the MLP consists of two hidden layers, each with 32 hidden units. std_hidden_nonlinearity (callable): Nonlinearity for each hidden layer in the std network. std_hidden_w_init (callable): Initializer function for the weight of hidden layer (s). std_hidden_b_init (callable): Initializer function for the bias of intermediate dense layer(s). std_output_nonlinearity (callable): Activation function for output dense layer in the std network. It should return a torch.Tensor. Set it to None to maintain a linear activation. std_output_w_init (callable): Initializer function for the weight of output dense layer(s) in the std network. std_parameterization (str): How the std should be parametrized. There are two options: - exp: the logarithm of the std will be stored, and applied a exponential transformation - softplus: the std will be computed as log(1+exp(x)) layer_normalization (bool): Bool for using layer normalization or not. """ def __init__(self, input_dim, output_dim, hidden_sizes=(32, 32), hidden_nonlinearity=torch.tanh, hidden_w_init=nn.init.xavier_uniform_, hidden_b_init=nn.init.zeros_, output_nonlinearity=None, output_w_init=nn.init.xavier_uniform_, output_b_init=nn.init.zeros_, learn_std=True, init_std=1.0, min_std=1e-6, max_std=None, std_hidden_sizes=(32, 32), std_hidden_nonlinearity=torch.tanh, std_hidden_w_init=nn.init.xavier_uniform_, std_hidden_b_init=nn.init.zeros_, std_output_nonlinearity=None, std_output_w_init=nn.init.xavier_uniform_, std_parameterization='exp', layer_normalization=False): super(GaussianMLPIndependentStdModule, self).__init__(input_dim=input_dim, output_dim=output_dim, hidden_sizes=hidden_sizes, hidden_nonlinearity=hidden_nonlinearity, hidden_w_init=hidden_w_init, hidden_b_init=hidden_b_init, output_nonlinearity=output_nonlinearity, output_w_init=output_w_init, output_b_init=output_b_init, learn_std=learn_std, init_std=init_std, min_std=min_std, max_std=max_std, std_hidden_sizes=std_hidden_sizes, std_hidden_nonlinearity=std_hidden_nonlinearity, std_hidden_w_init=std_hidden_w_init, std_hidden_b_init=std_hidden_b_init, std_output_nonlinearity=std_output_nonlinearity, std_output_w_init=std_output_w_init, std_parameterization=std_parameterization, layer_normalization=layer_normalization) self._mean_module = MLPModule( input_dim=self._input_dim, output_dim=self._action_dim, hidden_sizes=self._hidden_sizes, hidden_nonlinearity=self._hidden_nonlinearity, hidden_w_init=self._hidden_w_init, hidden_b_init=self._hidden_b_init, output_nonlinearity=self._output_nonlinearity, output_w_init=self._output_w_init, output_b_init=self._output_b_init, layer_normalization=self._layer_normalization) self._log_std_module = MLPModule( input_dim=self._input_dim, output_dim=self._action_dim, hidden_sizes=self._std_hidden_sizes, hidden_nonlinearity=self._std_hidden_nonlinearity, hidden_w_init=self._std_hidden_w_init, hidden_b_init=self._std_hidden_b_init, output_nonlinearity=self._std_output_nonlinearity, output_w_init=self._std_output_w_init, output_b_init=self._init_std_b, layer_normalization=self._layer_normalization) def _init_std_b(self, b): """Default bias initialization function. Args: b (torch.Tensor): The bias tensor. Returns: torch.Tensor: The bias tensor itself. """ return nn.init.constant_(b, self._init_std.item()) def _get_mean_and_log_std(self, *inputs): """Get mean and std of Gaussian distribution given inputs. Args: *inputs: Input to the module. Returns: tuple: * mean (torch.Tensor): The mean of Gaussian distribution. * std (torch.Tensor): The variance of Gaussian distribution. """ return self._mean_module(*inputs), self._log_std_module(*inputs) class GaussianMLPTwoHeadedModule(GaussianMLPBaseModule): """GaussianMLPModule which has only one mean network. Args: input_dim (int): Input dimension of the model. output_dim (int): Output dimension of the model. hidden_sizes (list[int]): Output dimension of dense layer(s) for the MLP for mean. For example, (32, 32) means the MLP consists of two hidden layers, each with 32 hidden units. hidden_nonlinearity (callable): Activation function for intermediate dense layer(s). It should return a torch.Tensor. Set it to None to maintain a linear activation. hidden_w_init (callable): Initializer function for the weight of intermediate dense layer(s). The function should return a torch.Tensor. hidden_b_init (callable): Initializer function for the bias of intermediate dense layer(s). The function should return a torch.Tensor. output_nonlinearity (callable): Activation function for output dense layer. It should return a torch.Tensor. Set it to None to maintain a linear activation. output_w_init (callable): Initializer function for the weight of output dense layer(s). The function should return a torch.Tensor. output_b_init (callable): Initializer function for the bias of output dense layer(s). The function should return a torch.Tensor. learn_std (bool): Is std trainable. init_std (float): Initial value for std. (plain value - not log or exponentiated). min_std (float): If not None, the std is at least the value of min_std, to avoid numerical issues (plain value - not log or exponentiated). max_std (float): If not None, the std is at most the value of max_std, to avoid numerical issues (plain value - not log or exponentiated). std_parameterization (str): How the std should be parametrized. There are two options: - exp: the logarithm of the std will be stored, and applied a exponential transformation - softplus: the std will be computed as log(1+exp(x)) layer_normalization (bool): Bool for using layer normalization or not. """ def __init__(self, input_dim, output_dim, hidden_sizes=(32, 32), hidden_nonlinearity=torch.tanh, hidden_w_init=nn.init.xavier_uniform_, hidden_b_init=nn.init.zeros_, output_nonlinearity=None, output_w_init=nn.init.xavier_uniform_, output_b_init=nn.init.zeros_, learn_std=True, init_std=1.0, min_std=1e-6, max_std=None, std_parameterization='exp', layer_normalization=False): super(GaussianMLPTwoHeadedModule, self).__init__(input_dim=input_dim, output_dim=output_dim, hidden_sizes=hidden_sizes, hidden_nonlinearity=hidden_nonlinearity, hidden_w_init=hidden_w_init, hidden_b_init=hidden_b_init, output_nonlinearity=output_nonlinearity, output_w_init=output_w_init, output_b_init=output_b_init, learn_std=learn_std, init_std=init_std, min_std=min_std, max_std=max_std, std_parameterization=std_parameterization, layer_normalization=layer_normalization) self._shared_mean_log_std_network = MultiHeadedMLPModule( n_heads=2, input_dim=self._input_dim, output_dims=self._action_dim, hidden_sizes=self._hidden_sizes, hidden_nonlinearity=self._hidden_nonlinearity, hidden_w_init=self._hidden_w_init, hidden_b_init=self._hidden_b_init, output_nonlinearities=self._output_nonlinearity, output_w_inits=self._output_w_init, output_b_inits=[ nn.init.zeros_, lambda x: nn.init.constant_(x, self._init_std.item()) ], layer_normalization=self._layer_normalization) def _get_mean_and_log_std(self, *inputs): """Get mean and std of Gaussian distribution given inputs. Args: *inputs: Input to the module. Returns: tuple: * mean (torch.Tensor): The mean of Gaussian distribution. * std (torch.Tensor): The variance of Gaussian distribution. """ return self._shared_mean_log_std_network(*inputs)
45.369686
79
0.612508
import abc import torch from torch import nn from torch.distributions import Normal from torch.distributions.independent import Independent from garage.torch.modules.mlp_module import MLPModule from garage.torch.modules.multi_headed_mlp_module import MultiHeadedMLPModule class GaussianMLPBaseModule(nn.Module): def __init__(self, input_dim, output_dim, hidden_sizes=(32, 32), hidden_nonlinearity=torch.tanh, hidden_w_init=nn.init.xavier_uniform_, hidden_b_init=nn.init.zeros_, output_nonlinearity=None, output_w_init=nn.init.xavier_uniform_, output_b_init=nn.init.zeros_, learn_std=True, init_std=1.0, min_std=1e-6, max_std=None, std_hidden_sizes=(32, 32), std_hidden_nonlinearity=torch.tanh, std_hidden_w_init=nn.init.xavier_uniform_, std_hidden_b_init=nn.init.zeros_, std_output_nonlinearity=None, std_output_w_init=nn.init.xavier_uniform_, std_parameterization='exp', layer_normalization=False): super().__init__() self._input_dim = input_dim self._hidden_sizes = hidden_sizes self._action_dim = output_dim self._learn_std = learn_std self._std_hidden_sizes = std_hidden_sizes self._min_std = min_std self._max_std = max_std self._std_hidden_nonlinearity = std_hidden_nonlinearity self._std_hidden_w_init = std_hidden_w_init self._std_hidden_b_init = std_hidden_b_init self._std_output_nonlinearity = std_output_nonlinearity self._std_output_w_init = std_output_w_init self._std_parameterization = std_parameterization self._hidden_nonlinearity = hidden_nonlinearity self._hidden_w_init = hidden_w_init self._hidden_b_init = hidden_b_init self._output_nonlinearity = output_nonlinearity self._output_w_init = output_w_init self._output_b_init = output_b_init self._layer_normalization = layer_normalization if self._std_parameterization not in ('exp', 'softplus'): raise NotImplementedError init_std_param = torch.Tensor([init_std]).log() if self._learn_std: self._init_std = torch.nn.Parameter(init_std_param) else: self._init_std = init_std_param self._min_std_param = self._max_std_param = None if min_std is not None: self._min_std_param = torch.Tensor([min_std]).log() if max_std is not None: self._max_std_param = torch.Tensor([max_std]).log() @abc.abstractmethod def _get_mean_and_log_std(self, *inputs): pass def forward(self, *inputs): mean, log_std_uncentered = self._get_mean_and_log_std(*inputs) if self._min_std_param or self._max_std_param: log_std_uncentered = log_std_uncentered.clamp( min=self._to_scalar_if_not_none(self._min_std_param), max=self._to_scalar_if_not_none(self._max_std_param)) if self._std_parameterization == 'exp': std = log_std_uncentered.exp() else: std = log_std_uncentered.exp().exp().add(1.).log() dist = Independent(Normal(mean, std), 1) return dist def _to_scalar_if_not_none(self, tensor): return None if tensor is None else tensor.item() class GaussianMLPModule(GaussianMLPBaseModule): def __init__(self, input_dim, output_dim, hidden_sizes=(32, 32), hidden_nonlinearity=torch.tanh, hidden_w_init=nn.init.xavier_uniform_, hidden_b_init=nn.init.zeros_, output_nonlinearity=None, output_w_init=nn.init.xavier_uniform_, output_b_init=nn.init.zeros_, learn_std=True, init_std=1.0, min_std=1e-6, max_std=None, std_parameterization='exp', layer_normalization=False): super(GaussianMLPModule, self).__init__(input_dim=input_dim, output_dim=output_dim, hidden_sizes=hidden_sizes, hidden_nonlinearity=hidden_nonlinearity, hidden_w_init=hidden_w_init, hidden_b_init=hidden_b_init, output_nonlinearity=output_nonlinearity, output_w_init=output_w_init, output_b_init=output_b_init, learn_std=learn_std, init_std=init_std, min_std=min_std, max_std=max_std, std_parameterization=std_parameterization, layer_normalization=layer_normalization) self._mean_module = MLPModule( input_dim=self._input_dim, output_dim=self._action_dim, hidden_sizes=self._hidden_sizes, hidden_nonlinearity=self._hidden_nonlinearity, hidden_w_init=self._hidden_w_init, hidden_b_init=self._hidden_b_init, output_nonlinearity=self._output_nonlinearity, output_w_init=self._output_w_init, output_b_init=self._output_b_init, layer_normalization=self._layer_normalization) def _get_mean_and_log_std(self, *inputs): assert len(inputs) == 1 mean = self._mean_module(*inputs) broadcast_shape = list(inputs[0].shape[:-1]) + [self._action_dim] uncentered_log_std = torch.zeros(*broadcast_shape) + self._init_std return mean, uncentered_log_std class GaussianMLPIndependentStdModule(GaussianMLPBaseModule): def __init__(self, input_dim, output_dim, hidden_sizes=(32, 32), hidden_nonlinearity=torch.tanh, hidden_w_init=nn.init.xavier_uniform_, hidden_b_init=nn.init.zeros_, output_nonlinearity=None, output_w_init=nn.init.xavier_uniform_, output_b_init=nn.init.zeros_, learn_std=True, init_std=1.0, min_std=1e-6, max_std=None, std_hidden_sizes=(32, 32), std_hidden_nonlinearity=torch.tanh, std_hidden_w_init=nn.init.xavier_uniform_, std_hidden_b_init=nn.init.zeros_, std_output_nonlinearity=None, std_output_w_init=nn.init.xavier_uniform_, std_parameterization='exp', layer_normalization=False): super(GaussianMLPIndependentStdModule, self).__init__(input_dim=input_dim, output_dim=output_dim, hidden_sizes=hidden_sizes, hidden_nonlinearity=hidden_nonlinearity, hidden_w_init=hidden_w_init, hidden_b_init=hidden_b_init, output_nonlinearity=output_nonlinearity, output_w_init=output_w_init, output_b_init=output_b_init, learn_std=learn_std, init_std=init_std, min_std=min_std, max_std=max_std, std_hidden_sizes=std_hidden_sizes, std_hidden_nonlinearity=std_hidden_nonlinearity, std_hidden_w_init=std_hidden_w_init, std_hidden_b_init=std_hidden_b_init, std_output_nonlinearity=std_output_nonlinearity, std_output_w_init=std_output_w_init, std_parameterization=std_parameterization, layer_normalization=layer_normalization) self._mean_module = MLPModule( input_dim=self._input_dim, output_dim=self._action_dim, hidden_sizes=self._hidden_sizes, hidden_nonlinearity=self._hidden_nonlinearity, hidden_w_init=self._hidden_w_init, hidden_b_init=self._hidden_b_init, output_nonlinearity=self._output_nonlinearity, output_w_init=self._output_w_init, output_b_init=self._output_b_init, layer_normalization=self._layer_normalization) self._log_std_module = MLPModule( input_dim=self._input_dim, output_dim=self._action_dim, hidden_sizes=self._std_hidden_sizes, hidden_nonlinearity=self._std_hidden_nonlinearity, hidden_w_init=self._std_hidden_w_init, hidden_b_init=self._std_hidden_b_init, output_nonlinearity=self._std_output_nonlinearity, output_w_init=self._std_output_w_init, output_b_init=self._init_std_b, layer_normalization=self._layer_normalization) def _init_std_b(self, b): return nn.init.constant_(b, self._init_std.item()) def _get_mean_and_log_std(self, *inputs): return self._mean_module(*inputs), self._log_std_module(*inputs) class GaussianMLPTwoHeadedModule(GaussianMLPBaseModule): def __init__(self, input_dim, output_dim, hidden_sizes=(32, 32), hidden_nonlinearity=torch.tanh, hidden_w_init=nn.init.xavier_uniform_, hidden_b_init=nn.init.zeros_, output_nonlinearity=None, output_w_init=nn.init.xavier_uniform_, output_b_init=nn.init.zeros_, learn_std=True, init_std=1.0, min_std=1e-6, max_std=None, std_parameterization='exp', layer_normalization=False): super(GaussianMLPTwoHeadedModule, self).__init__(input_dim=input_dim, output_dim=output_dim, hidden_sizes=hidden_sizes, hidden_nonlinearity=hidden_nonlinearity, hidden_w_init=hidden_w_init, hidden_b_init=hidden_b_init, output_nonlinearity=output_nonlinearity, output_w_init=output_w_init, output_b_init=output_b_init, learn_std=learn_std, init_std=init_std, min_std=min_std, max_std=max_std, std_parameterization=std_parameterization, layer_normalization=layer_normalization) self._shared_mean_log_std_network = MultiHeadedMLPModule( n_heads=2, input_dim=self._input_dim, output_dims=self._action_dim, hidden_sizes=self._hidden_sizes, hidden_nonlinearity=self._hidden_nonlinearity, hidden_w_init=self._hidden_w_init, hidden_b_init=self._hidden_b_init, output_nonlinearities=self._output_nonlinearity, output_w_inits=self._output_w_init, output_b_inits=[ nn.init.zeros_, lambda x: nn.init.constant_(x, self._init_std.item()) ], layer_normalization=self._layer_normalization) def _get_mean_and_log_std(self, *inputs): return self._shared_mean_log_std_network(*inputs)
true
true
1c33fcc9c8a2484f4594c3812636622d2fa80cda
4,296
py
Python
lm_eval/tasks/pile.py
ucinlp/lm-evaluation-harness
52bb90e2a161dc7c5d93478406c4cfe489caf2b2
[ "MIT" ]
null
null
null
lm_eval/tasks/pile.py
ucinlp/lm-evaluation-harness
52bb90e2a161dc7c5d93478406c4cfe489caf2b2
[ "MIT" ]
null
null
null
lm_eval/tasks/pile.py
ucinlp/lm-evaluation-harness
52bb90e2a161dc7c5d93478406c4cfe489caf2b2
[ "MIT" ]
null
null
null
""" The Pile: An 800GB Dataset of Diverse Text for Language Modeling https://arxiv.org/pdf/2101.00027.pdf The Pile is a 825 GiB diverse, open source language modelling data set that consists of 22 smaller, high-quality datasets combined together. To score well on Pile BPB (bits per byte), a model must be able to understand many disparate domains including books, github repositories, webpages, chat logs, and medical, physics, math, computer science, and philosophy papers. Homepage: https://pile.eleuther.ai/ """ import os import lm_dataformat import abc import numpy as np from lm_eval.base import rf, PerplexityTask from ..metrics import mean, matthews_corrcoef, f1_score from ..utils import general_detokenize from best_download import download_file _CITATION = """ @article{pile, title={The {P}ile: An 800GB Dataset of Diverse Text for Language Modeling}, author={Gao, Leo and Biderman, Stella and Black, Sid and Golding, Laurence and Hoppe, Travis and Foster, Charles and Phang, Jason and He, Horace and Thite, Anish and Nabeshima, Noa and Presser, Shawn and Leahy, Connor}, journal={arXiv preprint arXiv:2101.00027}, year={2020} } """ class PilePerplexityTask(PerplexityTask, abc.ABC): VERSION = 1 PILE_SET_NAME = None VAL_PATH = 'data/pile/val.jsonl.zst' TEST_PATH = 'data/pile/test.jsonl.zst' def download(self): # TODO: separate pile val/test out by component so we don't have to scan the entire file once per set if not os.path.exists("data/pile/test.jsonl.zst"): # todo use new best_download fallback api os.makedirs("data/pile/", exist_ok=True) download_file("http://eaidata.bmk.sh/data/pile/val.jsonl.zst", local_file=self.VAL_PATH, expected_checksum="264c875d8bbd355d8daa9d032b75fd8fb91606218bb84dd1155b203fcd5fab92") download_file("http://eaidata.bmk.sh/data/pile/test.jsonl.zst", local_file=self.TEST_PATH, expected_checksum="0bb28c52d0b5596d389bf179ce2d43bf7f7ffae76b0d2d20b180c97f62e0975e") def validation_docs(self): rdr = lm_dataformat.Reader(self.VAL_PATH) for doc, metadata in rdr.stream_data(get_meta=True): if metadata["pile_set_name"] == self.PILE_SET_NAME: yield doc def test_docs(self): rdr = lm_dataformat.Reader(self.TEST_PATH) for doc, metadata in rdr.stream_data(get_meta=True): if metadata["pile_set_name"] == self.PILE_SET_NAME: yield doc def has_validation_docs(self): return True def has_test_docs(self): return True class PileArxiv(PilePerplexityTask): PILE_SET_NAME = "ArXiv" class PileBooks3(PilePerplexityTask): PILE_SET_NAME = "Books3" class PileBookCorpus2(PilePerplexityTask): PILE_SET_NAME = "BookCorpus2" class PileDmMathematics(PilePerplexityTask): PILE_SET_NAME = "DM Mathematics" class PileEnron(PilePerplexityTask): PILE_SET_NAME = "Enron Emails" class PileEuroparl(PilePerplexityTask): PILE_SET_NAME = "EuroParl" class PileFreeLaw(PilePerplexityTask): PILE_SET_NAME = "FreeLaw" class PileGithub(PilePerplexityTask): PILE_SET_NAME = "Github" class PileGutenberg(PilePerplexityTask): PILE_SET_NAME = "Gutenberg (PG-19)" class PileHackernews(PilePerplexityTask): PILE_SET_NAME = "HackerNews" class PileNIHExporter(PilePerplexityTask): PILE_SET_NAME = "NIH ExPorter" class PileOpenSubtitles(PilePerplexityTask): PILE_SET_NAME = "OpenSubtitles" class PileOpenWebText2(PilePerplexityTask): PILE_SET_NAME = "OpenWebText2" class PilePhilPapers(PilePerplexityTask): PILE_SET_NAME = "PhilPapers" class PilePileCc(PilePerplexityTask): PILE_SET_NAME = "Pile-CC" class PilePubmedAbstracts(PilePerplexityTask): PILE_SET_NAME = "PubMed Abstracts" class PilePubmedCentral(PilePerplexityTask): PILE_SET_NAME = "PubMed Central" class PileStackExchange(PilePerplexityTask): PILE_SET_NAME = "StackExchange" class PileUspto(PilePerplexityTask): PILE_SET_NAME = "USPTO Backgrounds" class PileUbuntuIrc(PilePerplexityTask): PILE_SET_NAME = "Ubuntu IRC" class PileWikipedia(PilePerplexityTask): PILE_SET_NAME = "Wikipedia (en)" class PileYoutubeSubtitles(PilePerplexityTask): PILE_SET_NAME = "YoutubeSubtitles"
27.896104
221
0.744646
import os import lm_dataformat import abc import numpy as np from lm_eval.base import rf, PerplexityTask from ..metrics import mean, matthews_corrcoef, f1_score from ..utils import general_detokenize from best_download import download_file _CITATION = """ @article{pile, title={The {P}ile: An 800GB Dataset of Diverse Text for Language Modeling}, author={Gao, Leo and Biderman, Stella and Black, Sid and Golding, Laurence and Hoppe, Travis and Foster, Charles and Phang, Jason and He, Horace and Thite, Anish and Nabeshima, Noa and Presser, Shawn and Leahy, Connor}, journal={arXiv preprint arXiv:2101.00027}, year={2020} } """ class PilePerplexityTask(PerplexityTask, abc.ABC): VERSION = 1 PILE_SET_NAME = None VAL_PATH = 'data/pile/val.jsonl.zst' TEST_PATH = 'data/pile/test.jsonl.zst' def download(self): if not os.path.exists("data/pile/test.jsonl.zst"): # todo use new best_download fallback api os.makedirs("data/pile/", exist_ok=True) download_file("http://eaidata.bmk.sh/data/pile/val.jsonl.zst", local_file=self.VAL_PATH, expected_checksum="264c875d8bbd355d8daa9d032b75fd8fb91606218bb84dd1155b203fcd5fab92") download_file("http://eaidata.bmk.sh/data/pile/test.jsonl.zst", local_file=self.TEST_PATH, expected_checksum="0bb28c52d0b5596d389bf179ce2d43bf7f7ffae76b0d2d20b180c97f62e0975e") def validation_docs(self): rdr = lm_dataformat.Reader(self.VAL_PATH) for doc, metadata in rdr.stream_data(get_meta=True): if metadata["pile_set_name"] == self.PILE_SET_NAME: yield doc def test_docs(self): rdr = lm_dataformat.Reader(self.TEST_PATH) for doc, metadata in rdr.stream_data(get_meta=True): if metadata["pile_set_name"] == self.PILE_SET_NAME: yield doc def has_validation_docs(self): return True def has_test_docs(self): return True class PileArxiv(PilePerplexityTask): PILE_SET_NAME = "ArXiv" class PileBooks3(PilePerplexityTask): PILE_SET_NAME = "Books3" class PileBookCorpus2(PilePerplexityTask): PILE_SET_NAME = "BookCorpus2" class PileDmMathematics(PilePerplexityTask): PILE_SET_NAME = "DM Mathematics" class PileEnron(PilePerplexityTask): PILE_SET_NAME = "Enron Emails" class PileEuroparl(PilePerplexityTask): PILE_SET_NAME = "EuroParl" class PileFreeLaw(PilePerplexityTask): PILE_SET_NAME = "FreeLaw" class PileGithub(PilePerplexityTask): PILE_SET_NAME = "Github" class PileGutenberg(PilePerplexityTask): PILE_SET_NAME = "Gutenberg (PG-19)" class PileHackernews(PilePerplexityTask): PILE_SET_NAME = "HackerNews" class PileNIHExporter(PilePerplexityTask): PILE_SET_NAME = "NIH ExPorter" class PileOpenSubtitles(PilePerplexityTask): PILE_SET_NAME = "OpenSubtitles" class PileOpenWebText2(PilePerplexityTask): PILE_SET_NAME = "OpenWebText2" class PilePhilPapers(PilePerplexityTask): PILE_SET_NAME = "PhilPapers" class PilePileCc(PilePerplexityTask): PILE_SET_NAME = "Pile-CC" class PilePubmedAbstracts(PilePerplexityTask): PILE_SET_NAME = "PubMed Abstracts" class PilePubmedCentral(PilePerplexityTask): PILE_SET_NAME = "PubMed Central" class PileStackExchange(PilePerplexityTask): PILE_SET_NAME = "StackExchange" class PileUspto(PilePerplexityTask): PILE_SET_NAME = "USPTO Backgrounds" class PileUbuntuIrc(PilePerplexityTask): PILE_SET_NAME = "Ubuntu IRC" class PileWikipedia(PilePerplexityTask): PILE_SET_NAME = "Wikipedia (en)" class PileYoutubeSubtitles(PilePerplexityTask): PILE_SET_NAME = "YoutubeSubtitles"
true
true
1c33fd7758a8b0634c999edfd18b304199a911dc
75,657
py
Python
sdk/python/pulumi_azure_native/compute/v20200930/outputs.py
pulumi-bot/pulumi-azure-native
f7b9490b5211544318e455e5cceafe47b628e12c
[ "Apache-2.0" ]
31
2020-09-21T09:41:01.000Z
2021-02-26T13:21:59.000Z
sdk/python/pulumi_azure_native/compute/v20200930/outputs.py
pulumi-bot/pulumi-azure-native
f7b9490b5211544318e455e5cceafe47b628e12c
[ "Apache-2.0" ]
231
2020-09-21T09:38:45.000Z
2021-03-01T11:16:03.000Z
sdk/python/pulumi_azure_native/compute/v20200930/outputs.py
pulumi-bot/pulumi-azure-native
f7b9490b5211544318e455e5cceafe47b628e12c
[ "Apache-2.0" ]
4
2020-09-29T14:14:59.000Z
2021-02-10T20:38:16.000Z
# coding=utf-8 # *** WARNING: this file was generated by the Pulumi SDK Generator. *** # *** Do not edit by hand unless you're certain you know what you are doing! *** import warnings import pulumi import pulumi.runtime from typing import Any, Mapping, Optional, Sequence, Union from ... import _utilities, _tables from . import outputs from ._enums import * __all__ = [ 'CreationDataResponse', 'DataDiskImageEncryptionResponse', 'DisallowedResponse', 'DiskSkuResponse', 'EncryptionImagesResponse', 'EncryptionResponse', 'EncryptionSetIdentityResponse', 'EncryptionSettingsCollectionResponse', 'EncryptionSettingsElementResponse', 'ExtendedLocationResponse', 'GalleryApplicationVersionPublishingProfileResponse', 'GalleryArtifactVersionSourceResponse', 'GalleryDataDiskImageResponse', 'GalleryIdentifierResponse', 'GalleryImageFeatureResponse', 'GalleryImageIdentifierResponse', 'GalleryImageVersionPublishingProfileResponse', 'GalleryImageVersionStorageProfileResponse', 'GalleryOSDiskImageResponse', 'ImageDiskReferenceResponse', 'ImagePurchasePlanResponse', 'KeyForDiskEncryptionSetResponse', 'KeyVaultAndKeyReferenceResponse', 'KeyVaultAndSecretReferenceResponse', 'OSDiskImageEncryptionResponse', 'PrivateEndpointConnectionResponse', 'PrivateEndpointResponse', 'PrivateLinkServiceConnectionStateResponse', 'PurchasePlanResponse', 'RecommendedMachineConfigurationResponse', 'RegionalReplicationStatusResponse', 'ReplicationStatusResponse', 'ResourceRangeResponse', 'ShareInfoElementResponse', 'SharingProfileGroupResponse', 'SharingProfileResponse', 'SnapshotSkuResponse', 'SourceVaultResponse', 'TargetRegionResponse', 'UserArtifactManageResponse', 'UserArtifactSourceResponse', ] @pulumi.output_type class CreationDataResponse(dict): """ Data used when creating a disk. """ def __init__(__self__, *, create_option: str, source_unique_id: str, gallery_image_reference: Optional['outputs.ImageDiskReferenceResponse'] = None, image_reference: Optional['outputs.ImageDiskReferenceResponse'] = None, logical_sector_size: Optional[int] = None, source_resource_id: Optional[str] = None, source_uri: Optional[str] = None, storage_account_id: Optional[str] = None, upload_size_bytes: Optional[float] = None): """ Data used when creating a disk. :param str create_option: This enumerates the possible sources of a disk's creation. :param str source_unique_id: If this field is set, this is the unique id identifying the source of this resource. :param 'ImageDiskReferenceResponseArgs' gallery_image_reference: Required if creating from a Gallery Image. The id of the ImageDiskReference will be the ARM id of the shared galley image version from which to create a disk. :param 'ImageDiskReferenceResponseArgs' image_reference: Disk source information. :param int logical_sector_size: Logical sector size in bytes for Ultra disks. Supported values are 512 ad 4096. 4096 is the default. :param str source_resource_id: If createOption is Copy, this is the ARM id of the source snapshot or disk. :param str source_uri: If createOption is Import, this is the URI of a blob to be imported into a managed disk. :param str storage_account_id: Required if createOption is Import. The Azure Resource Manager identifier of the storage account containing the blob to import as a disk. :param float upload_size_bytes: If createOption is Upload, this is the size of the contents of the upload including the VHD footer. This value should be between 20972032 (20 MiB + 512 bytes for the VHD footer) and 35183298347520 bytes (32 TiB + 512 bytes for the VHD footer). """ pulumi.set(__self__, "create_option", create_option) pulumi.set(__self__, "source_unique_id", source_unique_id) if gallery_image_reference is not None: pulumi.set(__self__, "gallery_image_reference", gallery_image_reference) if image_reference is not None: pulumi.set(__self__, "image_reference", image_reference) if logical_sector_size is not None: pulumi.set(__self__, "logical_sector_size", logical_sector_size) if source_resource_id is not None: pulumi.set(__self__, "source_resource_id", source_resource_id) if source_uri is not None: pulumi.set(__self__, "source_uri", source_uri) if storage_account_id is not None: pulumi.set(__self__, "storage_account_id", storage_account_id) if upload_size_bytes is not None: pulumi.set(__self__, "upload_size_bytes", upload_size_bytes) @property @pulumi.getter(name="createOption") def create_option(self) -> str: """ This enumerates the possible sources of a disk's creation. """ return pulumi.get(self, "create_option") @property @pulumi.getter(name="sourceUniqueId") def source_unique_id(self) -> str: """ If this field is set, this is the unique id identifying the source of this resource. """ return pulumi.get(self, "source_unique_id") @property @pulumi.getter(name="galleryImageReference") def gallery_image_reference(self) -> Optional['outputs.ImageDiskReferenceResponse']: """ Required if creating from a Gallery Image. The id of the ImageDiskReference will be the ARM id of the shared galley image version from which to create a disk. """ return pulumi.get(self, "gallery_image_reference") @property @pulumi.getter(name="imageReference") def image_reference(self) -> Optional['outputs.ImageDiskReferenceResponse']: """ Disk source information. """ return pulumi.get(self, "image_reference") @property @pulumi.getter(name="logicalSectorSize") def logical_sector_size(self) -> Optional[int]: """ Logical sector size in bytes for Ultra disks. Supported values are 512 ad 4096. 4096 is the default. """ return pulumi.get(self, "logical_sector_size") @property @pulumi.getter(name="sourceResourceId") def source_resource_id(self) -> Optional[str]: """ If createOption is Copy, this is the ARM id of the source snapshot or disk. """ return pulumi.get(self, "source_resource_id") @property @pulumi.getter(name="sourceUri") def source_uri(self) -> Optional[str]: """ If createOption is Import, this is the URI of a blob to be imported into a managed disk. """ return pulumi.get(self, "source_uri") @property @pulumi.getter(name="storageAccountId") def storage_account_id(self) -> Optional[str]: """ Required if createOption is Import. The Azure Resource Manager identifier of the storage account containing the blob to import as a disk. """ return pulumi.get(self, "storage_account_id") @property @pulumi.getter(name="uploadSizeBytes") def upload_size_bytes(self) -> Optional[float]: """ If createOption is Upload, this is the size of the contents of the upload including the VHD footer. This value should be between 20972032 (20 MiB + 512 bytes for the VHD footer) and 35183298347520 bytes (32 TiB + 512 bytes for the VHD footer). """ return pulumi.get(self, "upload_size_bytes") def _translate_property(self, prop): return _tables.CAMEL_TO_SNAKE_CASE_TABLE.get(prop) or prop @pulumi.output_type class DataDiskImageEncryptionResponse(dict): """ Contains encryption settings for a data disk image. """ def __init__(__self__, *, lun: int, disk_encryption_set_id: Optional[str] = None): """ Contains encryption settings for a data disk image. :param int lun: This property specifies the logical unit number of the data disk. This value is used to identify data disks within the Virtual Machine and therefore must be unique for each data disk attached to the Virtual Machine. :param str disk_encryption_set_id: A relative URI containing the resource ID of the disk encryption set. """ pulumi.set(__self__, "lun", lun) if disk_encryption_set_id is not None: pulumi.set(__self__, "disk_encryption_set_id", disk_encryption_set_id) @property @pulumi.getter def lun(self) -> int: """ This property specifies the logical unit number of the data disk. This value is used to identify data disks within the Virtual Machine and therefore must be unique for each data disk attached to the Virtual Machine. """ return pulumi.get(self, "lun") @property @pulumi.getter(name="diskEncryptionSetId") def disk_encryption_set_id(self) -> Optional[str]: """ A relative URI containing the resource ID of the disk encryption set. """ return pulumi.get(self, "disk_encryption_set_id") def _translate_property(self, prop): return _tables.CAMEL_TO_SNAKE_CASE_TABLE.get(prop) or prop @pulumi.output_type class DisallowedResponse(dict): """ Describes the disallowed disk types. """ def __init__(__self__, *, disk_types: Optional[Sequence[str]] = None): """ Describes the disallowed disk types. :param Sequence[str] disk_types: A list of disk types. """ if disk_types is not None: pulumi.set(__self__, "disk_types", disk_types) @property @pulumi.getter(name="diskTypes") def disk_types(self) -> Optional[Sequence[str]]: """ A list of disk types. """ return pulumi.get(self, "disk_types") def _translate_property(self, prop): return _tables.CAMEL_TO_SNAKE_CASE_TABLE.get(prop) or prop @pulumi.output_type class DiskSkuResponse(dict): """ The disks sku name. Can be Standard_LRS, Premium_LRS, StandardSSD_LRS, or UltraSSD_LRS. """ def __init__(__self__, *, tier: str, name: Optional[str] = None): """ The disks sku name. Can be Standard_LRS, Premium_LRS, StandardSSD_LRS, or UltraSSD_LRS. :param str tier: The sku tier. :param str name: The sku name. """ pulumi.set(__self__, "tier", tier) if name is not None: pulumi.set(__self__, "name", name) @property @pulumi.getter def tier(self) -> str: """ The sku tier. """ return pulumi.get(self, "tier") @property @pulumi.getter def name(self) -> Optional[str]: """ The sku name. """ return pulumi.get(self, "name") def _translate_property(self, prop): return _tables.CAMEL_TO_SNAKE_CASE_TABLE.get(prop) or prop @pulumi.output_type class EncryptionImagesResponse(dict): """ Optional. Allows users to provide customer managed keys for encrypting the OS and data disks in the gallery artifact. """ def __init__(__self__, *, data_disk_images: Optional[Sequence['outputs.DataDiskImageEncryptionResponse']] = None, os_disk_image: Optional['outputs.OSDiskImageEncryptionResponse'] = None): """ Optional. Allows users to provide customer managed keys for encrypting the OS and data disks in the gallery artifact. :param Sequence['DataDiskImageEncryptionResponseArgs'] data_disk_images: A list of encryption specifications for data disk images. :param 'OSDiskImageEncryptionResponseArgs' os_disk_image: Contains encryption settings for an OS disk image. """ if data_disk_images is not None: pulumi.set(__self__, "data_disk_images", data_disk_images) if os_disk_image is not None: pulumi.set(__self__, "os_disk_image", os_disk_image) @property @pulumi.getter(name="dataDiskImages") def data_disk_images(self) -> Optional[Sequence['outputs.DataDiskImageEncryptionResponse']]: """ A list of encryption specifications for data disk images. """ return pulumi.get(self, "data_disk_images") @property @pulumi.getter(name="osDiskImage") def os_disk_image(self) -> Optional['outputs.OSDiskImageEncryptionResponse']: """ Contains encryption settings for an OS disk image. """ return pulumi.get(self, "os_disk_image") def _translate_property(self, prop): return _tables.CAMEL_TO_SNAKE_CASE_TABLE.get(prop) or prop @pulumi.output_type class EncryptionResponse(dict): """ Encryption at rest settings for disk or snapshot """ def __init__(__self__, *, disk_encryption_set_id: Optional[str] = None, type: Optional[str] = None): """ Encryption at rest settings for disk or snapshot :param str disk_encryption_set_id: ResourceId of the disk encryption set to use for enabling encryption at rest. :param str type: The type of key used to encrypt the data of the disk. """ if disk_encryption_set_id is not None: pulumi.set(__self__, "disk_encryption_set_id", disk_encryption_set_id) if type is not None: pulumi.set(__self__, "type", type) @property @pulumi.getter(name="diskEncryptionSetId") def disk_encryption_set_id(self) -> Optional[str]: """ ResourceId of the disk encryption set to use for enabling encryption at rest. """ return pulumi.get(self, "disk_encryption_set_id") @property @pulumi.getter def type(self) -> Optional[str]: """ The type of key used to encrypt the data of the disk. """ return pulumi.get(self, "type") def _translate_property(self, prop): return _tables.CAMEL_TO_SNAKE_CASE_TABLE.get(prop) or prop @pulumi.output_type class EncryptionSetIdentityResponse(dict): """ The managed identity for the disk encryption set. It should be given permission on the key vault before it can be used to encrypt disks. """ def __init__(__self__, *, principal_id: str, tenant_id: str, type: Optional[str] = None): """ The managed identity for the disk encryption set. It should be given permission on the key vault before it can be used to encrypt disks. :param str principal_id: The object id of the Managed Identity Resource. This will be sent to the RP from ARM via the x-ms-identity-principal-id header in the PUT request if the resource has a systemAssigned(implicit) identity :param str tenant_id: The tenant id of the Managed Identity Resource. This will be sent to the RP from ARM via the x-ms-client-tenant-id header in the PUT request if the resource has a systemAssigned(implicit) identity :param str type: The type of Managed Identity used by the DiskEncryptionSet. Only SystemAssigned is supported for new creations. Disk Encryption Sets can be updated with Identity type None during migration of subscription to a new Azure Active Directory tenant; it will cause the encrypted resources to lose access to the keys. """ pulumi.set(__self__, "principal_id", principal_id) pulumi.set(__self__, "tenant_id", tenant_id) if type is not None: pulumi.set(__self__, "type", type) @property @pulumi.getter(name="principalId") def principal_id(self) -> str: """ The object id of the Managed Identity Resource. This will be sent to the RP from ARM via the x-ms-identity-principal-id header in the PUT request if the resource has a systemAssigned(implicit) identity """ return pulumi.get(self, "principal_id") @property @pulumi.getter(name="tenantId") def tenant_id(self) -> str: """ The tenant id of the Managed Identity Resource. This will be sent to the RP from ARM via the x-ms-client-tenant-id header in the PUT request if the resource has a systemAssigned(implicit) identity """ return pulumi.get(self, "tenant_id") @property @pulumi.getter def type(self) -> Optional[str]: """ The type of Managed Identity used by the DiskEncryptionSet. Only SystemAssigned is supported for new creations. Disk Encryption Sets can be updated with Identity type None during migration of subscription to a new Azure Active Directory tenant; it will cause the encrypted resources to lose access to the keys. """ return pulumi.get(self, "type") def _translate_property(self, prop): return _tables.CAMEL_TO_SNAKE_CASE_TABLE.get(prop) or prop @pulumi.output_type class EncryptionSettingsCollectionResponse(dict): """ Encryption settings for disk or snapshot """ def __init__(__self__, *, enabled: bool, encryption_settings: Optional[Sequence['outputs.EncryptionSettingsElementResponse']] = None, encryption_settings_version: Optional[str] = None): """ Encryption settings for disk or snapshot :param bool enabled: Set this flag to true and provide DiskEncryptionKey and optional KeyEncryptionKey to enable encryption. Set this flag to false and remove DiskEncryptionKey and KeyEncryptionKey to disable encryption. If EncryptionSettings is null in the request object, the existing settings remain unchanged. :param Sequence['EncryptionSettingsElementResponseArgs'] encryption_settings: A collection of encryption settings, one for each disk volume. :param str encryption_settings_version: Describes what type of encryption is used for the disks. Once this field is set, it cannot be overwritten. '1.0' corresponds to Azure Disk Encryption with AAD app.'1.1' corresponds to Azure Disk Encryption. """ pulumi.set(__self__, "enabled", enabled) if encryption_settings is not None: pulumi.set(__self__, "encryption_settings", encryption_settings) if encryption_settings_version is not None: pulumi.set(__self__, "encryption_settings_version", encryption_settings_version) @property @pulumi.getter def enabled(self) -> bool: """ Set this flag to true and provide DiskEncryptionKey and optional KeyEncryptionKey to enable encryption. Set this flag to false and remove DiskEncryptionKey and KeyEncryptionKey to disable encryption. If EncryptionSettings is null in the request object, the existing settings remain unchanged. """ return pulumi.get(self, "enabled") @property @pulumi.getter(name="encryptionSettings") def encryption_settings(self) -> Optional[Sequence['outputs.EncryptionSettingsElementResponse']]: """ A collection of encryption settings, one for each disk volume. """ return pulumi.get(self, "encryption_settings") @property @pulumi.getter(name="encryptionSettingsVersion") def encryption_settings_version(self) -> Optional[str]: """ Describes what type of encryption is used for the disks. Once this field is set, it cannot be overwritten. '1.0' corresponds to Azure Disk Encryption with AAD app.'1.1' corresponds to Azure Disk Encryption. """ return pulumi.get(self, "encryption_settings_version") def _translate_property(self, prop): return _tables.CAMEL_TO_SNAKE_CASE_TABLE.get(prop) or prop @pulumi.output_type class EncryptionSettingsElementResponse(dict): """ Encryption settings for one disk volume. """ def __init__(__self__, *, disk_encryption_key: Optional['outputs.KeyVaultAndSecretReferenceResponse'] = None, key_encryption_key: Optional['outputs.KeyVaultAndKeyReferenceResponse'] = None): """ Encryption settings for one disk volume. :param 'KeyVaultAndSecretReferenceResponseArgs' disk_encryption_key: Key Vault Secret Url and vault id of the disk encryption key :param 'KeyVaultAndKeyReferenceResponseArgs' key_encryption_key: Key Vault Key Url and vault id of the key encryption key. KeyEncryptionKey is optional and when provided is used to unwrap the disk encryption key. """ if disk_encryption_key is not None: pulumi.set(__self__, "disk_encryption_key", disk_encryption_key) if key_encryption_key is not None: pulumi.set(__self__, "key_encryption_key", key_encryption_key) @property @pulumi.getter(name="diskEncryptionKey") def disk_encryption_key(self) -> Optional['outputs.KeyVaultAndSecretReferenceResponse']: """ Key Vault Secret Url and vault id of the disk encryption key """ return pulumi.get(self, "disk_encryption_key") @property @pulumi.getter(name="keyEncryptionKey") def key_encryption_key(self) -> Optional['outputs.KeyVaultAndKeyReferenceResponse']: """ Key Vault Key Url and vault id of the key encryption key. KeyEncryptionKey is optional and when provided is used to unwrap the disk encryption key. """ return pulumi.get(self, "key_encryption_key") def _translate_property(self, prop): return _tables.CAMEL_TO_SNAKE_CASE_TABLE.get(prop) or prop @pulumi.output_type class ExtendedLocationResponse(dict): """ The complex type of the extended location. """ def __init__(__self__, *, name: Optional[str] = None, type: Optional[str] = None): """ The complex type of the extended location. :param str name: The name of the extended location. :param str type: The type of the extended location. """ if name is not None: pulumi.set(__self__, "name", name) if type is not None: pulumi.set(__self__, "type", type) @property @pulumi.getter def name(self) -> Optional[str]: """ The name of the extended location. """ return pulumi.get(self, "name") @property @pulumi.getter def type(self) -> Optional[str]: """ The type of the extended location. """ return pulumi.get(self, "type") def _translate_property(self, prop): return _tables.CAMEL_TO_SNAKE_CASE_TABLE.get(prop) or prop @pulumi.output_type class GalleryApplicationVersionPublishingProfileResponse(dict): """ The publishing profile of a gallery image version. """ def __init__(__self__, *, published_date: str, source: 'outputs.UserArtifactSourceResponse', enable_health_check: Optional[bool] = None, end_of_life_date: Optional[str] = None, exclude_from_latest: Optional[bool] = None, manage_actions: Optional['outputs.UserArtifactManageResponse'] = None, replica_count: Optional[int] = None, storage_account_type: Optional[str] = None, target_regions: Optional[Sequence['outputs.TargetRegionResponse']] = None): """ The publishing profile of a gallery image version. :param str published_date: The timestamp for when the gallery image version is published. :param 'UserArtifactSourceResponseArgs' source: The source image from which the Image Version is going to be created. :param bool enable_health_check: Optional. Whether or not this application reports health. :param str end_of_life_date: The end of life date of the gallery image version. This property can be used for decommissioning purposes. This property is updatable. :param bool exclude_from_latest: If set to true, Virtual Machines deployed from the latest version of the Image Definition won't use this Image Version. :param int replica_count: The number of replicas of the Image Version to be created per region. This property would take effect for a region when regionalReplicaCount is not specified. This property is updatable. :param str storage_account_type: Specifies the storage account type to be used to store the image. This property is not updatable. :param Sequence['TargetRegionResponseArgs'] target_regions: The target regions where the Image Version is going to be replicated to. This property is updatable. """ pulumi.set(__self__, "published_date", published_date) pulumi.set(__self__, "source", source) if enable_health_check is not None: pulumi.set(__self__, "enable_health_check", enable_health_check) if end_of_life_date is not None: pulumi.set(__self__, "end_of_life_date", end_of_life_date) if exclude_from_latest is not None: pulumi.set(__self__, "exclude_from_latest", exclude_from_latest) if manage_actions is not None: pulumi.set(__self__, "manage_actions", manage_actions) if replica_count is not None: pulumi.set(__self__, "replica_count", replica_count) if storage_account_type is not None: pulumi.set(__self__, "storage_account_type", storage_account_type) if target_regions is not None: pulumi.set(__self__, "target_regions", target_regions) @property @pulumi.getter(name="publishedDate") def published_date(self) -> str: """ The timestamp for when the gallery image version is published. """ return pulumi.get(self, "published_date") @property @pulumi.getter def source(self) -> 'outputs.UserArtifactSourceResponse': """ The source image from which the Image Version is going to be created. """ return pulumi.get(self, "source") @property @pulumi.getter(name="enableHealthCheck") def enable_health_check(self) -> Optional[bool]: """ Optional. Whether or not this application reports health. """ return pulumi.get(self, "enable_health_check") @property @pulumi.getter(name="endOfLifeDate") def end_of_life_date(self) -> Optional[str]: """ The end of life date of the gallery image version. This property can be used for decommissioning purposes. This property is updatable. """ return pulumi.get(self, "end_of_life_date") @property @pulumi.getter(name="excludeFromLatest") def exclude_from_latest(self) -> Optional[bool]: """ If set to true, Virtual Machines deployed from the latest version of the Image Definition won't use this Image Version. """ return pulumi.get(self, "exclude_from_latest") @property @pulumi.getter(name="manageActions") def manage_actions(self) -> Optional['outputs.UserArtifactManageResponse']: return pulumi.get(self, "manage_actions") @property @pulumi.getter(name="replicaCount") def replica_count(self) -> Optional[int]: """ The number of replicas of the Image Version to be created per region. This property would take effect for a region when regionalReplicaCount is not specified. This property is updatable. """ return pulumi.get(self, "replica_count") @property @pulumi.getter(name="storageAccountType") def storage_account_type(self) -> Optional[str]: """ Specifies the storage account type to be used to store the image. This property is not updatable. """ return pulumi.get(self, "storage_account_type") @property @pulumi.getter(name="targetRegions") def target_regions(self) -> Optional[Sequence['outputs.TargetRegionResponse']]: """ The target regions where the Image Version is going to be replicated to. This property is updatable. """ return pulumi.get(self, "target_regions") def _translate_property(self, prop): return _tables.CAMEL_TO_SNAKE_CASE_TABLE.get(prop) or prop @pulumi.output_type class GalleryArtifactVersionSourceResponse(dict): """ The gallery artifact version source. """ def __init__(__self__, *, id: Optional[str] = None, uri: Optional[str] = None): """ The gallery artifact version source. :param str id: The id of the gallery artifact version source. Can specify a disk uri, snapshot uri, user image or storage account resource. :param str uri: The uri of the gallery artifact version source. Currently used to specify vhd/blob source. """ if id is not None: pulumi.set(__self__, "id", id) if uri is not None: pulumi.set(__self__, "uri", uri) @property @pulumi.getter def id(self) -> Optional[str]: """ The id of the gallery artifact version source. Can specify a disk uri, snapshot uri, user image or storage account resource. """ return pulumi.get(self, "id") @property @pulumi.getter def uri(self) -> Optional[str]: """ The uri of the gallery artifact version source. Currently used to specify vhd/blob source. """ return pulumi.get(self, "uri") def _translate_property(self, prop): return _tables.CAMEL_TO_SNAKE_CASE_TABLE.get(prop) or prop @pulumi.output_type class GalleryDataDiskImageResponse(dict): """ This is the data disk image. """ def __init__(__self__, *, lun: int, size_in_gb: int, host_caching: Optional[str] = None, source: Optional['outputs.GalleryArtifactVersionSourceResponse'] = None): """ This is the data disk image. :param int lun: This property specifies the logical unit number of the data disk. This value is used to identify data disks within the Virtual Machine and therefore must be unique for each data disk attached to the Virtual Machine. :param int size_in_gb: This property indicates the size of the VHD to be created. :param str host_caching: The host caching of the disk. Valid values are 'None', 'ReadOnly', and 'ReadWrite' :param 'GalleryArtifactVersionSourceResponseArgs' source: The gallery artifact version source. """ pulumi.set(__self__, "lun", lun) pulumi.set(__self__, "size_in_gb", size_in_gb) if host_caching is not None: pulumi.set(__self__, "host_caching", host_caching) if source is not None: pulumi.set(__self__, "source", source) @property @pulumi.getter def lun(self) -> int: """ This property specifies the logical unit number of the data disk. This value is used to identify data disks within the Virtual Machine and therefore must be unique for each data disk attached to the Virtual Machine. """ return pulumi.get(self, "lun") @property @pulumi.getter(name="sizeInGB") def size_in_gb(self) -> int: """ This property indicates the size of the VHD to be created. """ return pulumi.get(self, "size_in_gb") @property @pulumi.getter(name="hostCaching") def host_caching(self) -> Optional[str]: """ The host caching of the disk. Valid values are 'None', 'ReadOnly', and 'ReadWrite' """ return pulumi.get(self, "host_caching") @property @pulumi.getter def source(self) -> Optional['outputs.GalleryArtifactVersionSourceResponse']: """ The gallery artifact version source. """ return pulumi.get(self, "source") def _translate_property(self, prop): return _tables.CAMEL_TO_SNAKE_CASE_TABLE.get(prop) or prop @pulumi.output_type class GalleryIdentifierResponse(dict): """ Describes the gallery unique name. """ def __init__(__self__, *, unique_name: str): """ Describes the gallery unique name. :param str unique_name: The unique name of the Shared Image Gallery. This name is generated automatically by Azure. """ pulumi.set(__self__, "unique_name", unique_name) @property @pulumi.getter(name="uniqueName") def unique_name(self) -> str: """ The unique name of the Shared Image Gallery. This name is generated automatically by Azure. """ return pulumi.get(self, "unique_name") def _translate_property(self, prop): return _tables.CAMEL_TO_SNAKE_CASE_TABLE.get(prop) or prop @pulumi.output_type class GalleryImageFeatureResponse(dict): """ A feature for gallery image. """ def __init__(__self__, *, name: Optional[str] = None, value: Optional[str] = None): """ A feature for gallery image. :param str name: The name of the gallery image feature. :param str value: The value of the gallery image feature. """ if name is not None: pulumi.set(__self__, "name", name) if value is not None: pulumi.set(__self__, "value", value) @property @pulumi.getter def name(self) -> Optional[str]: """ The name of the gallery image feature. """ return pulumi.get(self, "name") @property @pulumi.getter def value(self) -> Optional[str]: """ The value of the gallery image feature. """ return pulumi.get(self, "value") def _translate_property(self, prop): return _tables.CAMEL_TO_SNAKE_CASE_TABLE.get(prop) or prop @pulumi.output_type class GalleryImageIdentifierResponse(dict): """ This is the gallery image definition identifier. """ def __init__(__self__, *, offer: str, publisher: str, sku: str): """ This is the gallery image definition identifier. :param str offer: The name of the gallery image definition offer. :param str publisher: The name of the gallery image definition publisher. :param str sku: The name of the gallery image definition SKU. """ pulumi.set(__self__, "offer", offer) pulumi.set(__self__, "publisher", publisher) pulumi.set(__self__, "sku", sku) @property @pulumi.getter def offer(self) -> str: """ The name of the gallery image definition offer. """ return pulumi.get(self, "offer") @property @pulumi.getter def publisher(self) -> str: """ The name of the gallery image definition publisher. """ return pulumi.get(self, "publisher") @property @pulumi.getter def sku(self) -> str: """ The name of the gallery image definition SKU. """ return pulumi.get(self, "sku") def _translate_property(self, prop): return _tables.CAMEL_TO_SNAKE_CASE_TABLE.get(prop) or prop @pulumi.output_type class GalleryImageVersionPublishingProfileResponse(dict): """ The publishing profile of a gallery image Version. """ def __init__(__self__, *, published_date: str, end_of_life_date: Optional[str] = None, exclude_from_latest: Optional[bool] = None, replica_count: Optional[int] = None, storage_account_type: Optional[str] = None, target_regions: Optional[Sequence['outputs.TargetRegionResponse']] = None): """ The publishing profile of a gallery image Version. :param str published_date: The timestamp for when the gallery image version is published. :param str end_of_life_date: The end of life date of the gallery image version. This property can be used for decommissioning purposes. This property is updatable. :param bool exclude_from_latest: If set to true, Virtual Machines deployed from the latest version of the Image Definition won't use this Image Version. :param int replica_count: The number of replicas of the Image Version to be created per region. This property would take effect for a region when regionalReplicaCount is not specified. This property is updatable. :param str storage_account_type: Specifies the storage account type to be used to store the image. This property is not updatable. :param Sequence['TargetRegionResponseArgs'] target_regions: The target regions where the Image Version is going to be replicated to. This property is updatable. """ pulumi.set(__self__, "published_date", published_date) if end_of_life_date is not None: pulumi.set(__self__, "end_of_life_date", end_of_life_date) if exclude_from_latest is not None: pulumi.set(__self__, "exclude_from_latest", exclude_from_latest) if replica_count is not None: pulumi.set(__self__, "replica_count", replica_count) if storage_account_type is not None: pulumi.set(__self__, "storage_account_type", storage_account_type) if target_regions is not None: pulumi.set(__self__, "target_regions", target_regions) @property @pulumi.getter(name="publishedDate") def published_date(self) -> str: """ The timestamp for when the gallery image version is published. """ return pulumi.get(self, "published_date") @property @pulumi.getter(name="endOfLifeDate") def end_of_life_date(self) -> Optional[str]: """ The end of life date of the gallery image version. This property can be used for decommissioning purposes. This property is updatable. """ return pulumi.get(self, "end_of_life_date") @property @pulumi.getter(name="excludeFromLatest") def exclude_from_latest(self) -> Optional[bool]: """ If set to true, Virtual Machines deployed from the latest version of the Image Definition won't use this Image Version. """ return pulumi.get(self, "exclude_from_latest") @property @pulumi.getter(name="replicaCount") def replica_count(self) -> Optional[int]: """ The number of replicas of the Image Version to be created per region. This property would take effect for a region when regionalReplicaCount is not specified. This property is updatable. """ return pulumi.get(self, "replica_count") @property @pulumi.getter(name="storageAccountType") def storage_account_type(self) -> Optional[str]: """ Specifies the storage account type to be used to store the image. This property is not updatable. """ return pulumi.get(self, "storage_account_type") @property @pulumi.getter(name="targetRegions") def target_regions(self) -> Optional[Sequence['outputs.TargetRegionResponse']]: """ The target regions where the Image Version is going to be replicated to. This property is updatable. """ return pulumi.get(self, "target_regions") def _translate_property(self, prop): return _tables.CAMEL_TO_SNAKE_CASE_TABLE.get(prop) or prop @pulumi.output_type class GalleryImageVersionStorageProfileResponse(dict): """ This is the storage profile of a Gallery Image Version. """ def __init__(__self__, *, data_disk_images: Optional[Sequence['outputs.GalleryDataDiskImageResponse']] = None, os_disk_image: Optional['outputs.GalleryOSDiskImageResponse'] = None, source: Optional['outputs.GalleryArtifactVersionSourceResponse'] = None): """ This is the storage profile of a Gallery Image Version. :param Sequence['GalleryDataDiskImageResponseArgs'] data_disk_images: A list of data disk images. :param 'GalleryOSDiskImageResponseArgs' os_disk_image: This is the OS disk image. :param 'GalleryArtifactVersionSourceResponseArgs' source: The gallery artifact version source. """ if data_disk_images is not None: pulumi.set(__self__, "data_disk_images", data_disk_images) if os_disk_image is not None: pulumi.set(__self__, "os_disk_image", os_disk_image) if source is not None: pulumi.set(__self__, "source", source) @property @pulumi.getter(name="dataDiskImages") def data_disk_images(self) -> Optional[Sequence['outputs.GalleryDataDiskImageResponse']]: """ A list of data disk images. """ return pulumi.get(self, "data_disk_images") @property @pulumi.getter(name="osDiskImage") def os_disk_image(self) -> Optional['outputs.GalleryOSDiskImageResponse']: """ This is the OS disk image. """ return pulumi.get(self, "os_disk_image") @property @pulumi.getter def source(self) -> Optional['outputs.GalleryArtifactVersionSourceResponse']: """ The gallery artifact version source. """ return pulumi.get(self, "source") def _translate_property(self, prop): return _tables.CAMEL_TO_SNAKE_CASE_TABLE.get(prop) or prop @pulumi.output_type class GalleryOSDiskImageResponse(dict): """ This is the OS disk image. """ def __init__(__self__, *, size_in_gb: int, host_caching: Optional[str] = None, source: Optional['outputs.GalleryArtifactVersionSourceResponse'] = None): """ This is the OS disk image. :param int size_in_gb: This property indicates the size of the VHD to be created. :param str host_caching: The host caching of the disk. Valid values are 'None', 'ReadOnly', and 'ReadWrite' :param 'GalleryArtifactVersionSourceResponseArgs' source: The gallery artifact version source. """ pulumi.set(__self__, "size_in_gb", size_in_gb) if host_caching is not None: pulumi.set(__self__, "host_caching", host_caching) if source is not None: pulumi.set(__self__, "source", source) @property @pulumi.getter(name="sizeInGB") def size_in_gb(self) -> int: """ This property indicates the size of the VHD to be created. """ return pulumi.get(self, "size_in_gb") @property @pulumi.getter(name="hostCaching") def host_caching(self) -> Optional[str]: """ The host caching of the disk. Valid values are 'None', 'ReadOnly', and 'ReadWrite' """ return pulumi.get(self, "host_caching") @property @pulumi.getter def source(self) -> Optional['outputs.GalleryArtifactVersionSourceResponse']: """ The gallery artifact version source. """ return pulumi.get(self, "source") def _translate_property(self, prop): return _tables.CAMEL_TO_SNAKE_CASE_TABLE.get(prop) or prop @pulumi.output_type class ImageDiskReferenceResponse(dict): """ The source image used for creating the disk. """ def __init__(__self__, *, id: str, lun: Optional[int] = None): """ The source image used for creating the disk. :param str id: A relative uri containing either a Platform Image Repository or user image reference. :param int lun: If the disk is created from an image's data disk, this is an index that indicates which of the data disks in the image to use. For OS disks, this field is null. """ pulumi.set(__self__, "id", id) if lun is not None: pulumi.set(__self__, "lun", lun) @property @pulumi.getter def id(self) -> str: """ A relative uri containing either a Platform Image Repository or user image reference. """ return pulumi.get(self, "id") @property @pulumi.getter def lun(self) -> Optional[int]: """ If the disk is created from an image's data disk, this is an index that indicates which of the data disks in the image to use. For OS disks, this field is null. """ return pulumi.get(self, "lun") def _translate_property(self, prop): return _tables.CAMEL_TO_SNAKE_CASE_TABLE.get(prop) or prop @pulumi.output_type class ImagePurchasePlanResponse(dict): """ Describes the gallery image definition purchase plan. This is used by marketplace images. """ def __init__(__self__, *, name: Optional[str] = None, product: Optional[str] = None, publisher: Optional[str] = None): """ Describes the gallery image definition purchase plan. This is used by marketplace images. :param str name: The plan ID. :param str product: The product ID. :param str publisher: The publisher ID. """ if name is not None: pulumi.set(__self__, "name", name) if product is not None: pulumi.set(__self__, "product", product) if publisher is not None: pulumi.set(__self__, "publisher", publisher) @property @pulumi.getter def name(self) -> Optional[str]: """ The plan ID. """ return pulumi.get(self, "name") @property @pulumi.getter def product(self) -> Optional[str]: """ The product ID. """ return pulumi.get(self, "product") @property @pulumi.getter def publisher(self) -> Optional[str]: """ The publisher ID. """ return pulumi.get(self, "publisher") def _translate_property(self, prop): return _tables.CAMEL_TO_SNAKE_CASE_TABLE.get(prop) or prop @pulumi.output_type class KeyForDiskEncryptionSetResponse(dict): """ Key Vault Key Url to be used for server side encryption of Managed Disks and Snapshots """ def __init__(__self__, *, key_url: str, source_vault: Optional['outputs.SourceVaultResponse'] = None): """ Key Vault Key Url to be used for server side encryption of Managed Disks and Snapshots :param str key_url: Fully versioned Key Url pointing to a key in KeyVault :param 'SourceVaultResponseArgs' source_vault: Resource id of the KeyVault containing the key or secret. This property is optional and cannot be used if the KeyVault subscription is not the same as the Disk Encryption Set subscription. """ pulumi.set(__self__, "key_url", key_url) if source_vault is not None: pulumi.set(__self__, "source_vault", source_vault) @property @pulumi.getter(name="keyUrl") def key_url(self) -> str: """ Fully versioned Key Url pointing to a key in KeyVault """ return pulumi.get(self, "key_url") @property @pulumi.getter(name="sourceVault") def source_vault(self) -> Optional['outputs.SourceVaultResponse']: """ Resource id of the KeyVault containing the key or secret. This property is optional and cannot be used if the KeyVault subscription is not the same as the Disk Encryption Set subscription. """ return pulumi.get(self, "source_vault") def _translate_property(self, prop): return _tables.CAMEL_TO_SNAKE_CASE_TABLE.get(prop) or prop @pulumi.output_type class KeyVaultAndKeyReferenceResponse(dict): """ Key Vault Key Url and vault id of KeK, KeK is optional and when provided is used to unwrap the encryptionKey """ def __init__(__self__, *, key_url: str, source_vault: 'outputs.SourceVaultResponse'): """ Key Vault Key Url and vault id of KeK, KeK is optional and when provided is used to unwrap the encryptionKey :param str key_url: Url pointing to a key or secret in KeyVault :param 'SourceVaultResponseArgs' source_vault: Resource id of the KeyVault containing the key or secret """ pulumi.set(__self__, "key_url", key_url) pulumi.set(__self__, "source_vault", source_vault) @property @pulumi.getter(name="keyUrl") def key_url(self) -> str: """ Url pointing to a key or secret in KeyVault """ return pulumi.get(self, "key_url") @property @pulumi.getter(name="sourceVault") def source_vault(self) -> 'outputs.SourceVaultResponse': """ Resource id of the KeyVault containing the key or secret """ return pulumi.get(self, "source_vault") def _translate_property(self, prop): return _tables.CAMEL_TO_SNAKE_CASE_TABLE.get(prop) or prop @pulumi.output_type class KeyVaultAndSecretReferenceResponse(dict): """ Key Vault Secret Url and vault id of the encryption key """ def __init__(__self__, *, secret_url: str, source_vault: 'outputs.SourceVaultResponse'): """ Key Vault Secret Url and vault id of the encryption key :param str secret_url: Url pointing to a key or secret in KeyVault :param 'SourceVaultResponseArgs' source_vault: Resource id of the KeyVault containing the key or secret """ pulumi.set(__self__, "secret_url", secret_url) pulumi.set(__self__, "source_vault", source_vault) @property @pulumi.getter(name="secretUrl") def secret_url(self) -> str: """ Url pointing to a key or secret in KeyVault """ return pulumi.get(self, "secret_url") @property @pulumi.getter(name="sourceVault") def source_vault(self) -> 'outputs.SourceVaultResponse': """ Resource id of the KeyVault containing the key or secret """ return pulumi.get(self, "source_vault") def _translate_property(self, prop): return _tables.CAMEL_TO_SNAKE_CASE_TABLE.get(prop) or prop @pulumi.output_type class OSDiskImageEncryptionResponse(dict): """ Contains encryption settings for an OS disk image. """ def __init__(__self__, *, disk_encryption_set_id: Optional[str] = None): """ Contains encryption settings for an OS disk image. :param str disk_encryption_set_id: A relative URI containing the resource ID of the disk encryption set. """ if disk_encryption_set_id is not None: pulumi.set(__self__, "disk_encryption_set_id", disk_encryption_set_id) @property @pulumi.getter(name="diskEncryptionSetId") def disk_encryption_set_id(self) -> Optional[str]: """ A relative URI containing the resource ID of the disk encryption set. """ return pulumi.get(self, "disk_encryption_set_id") def _translate_property(self, prop): return _tables.CAMEL_TO_SNAKE_CASE_TABLE.get(prop) or prop @pulumi.output_type class PrivateEndpointConnectionResponse(dict): """ The Private Endpoint Connection resource. """ def __init__(__self__, *, id: str, name: str, private_link_service_connection_state: 'outputs.PrivateLinkServiceConnectionStateResponse', provisioning_state: str, type: str, private_endpoint: Optional['outputs.PrivateEndpointResponse'] = None): """ The Private Endpoint Connection resource. :param str id: private endpoint connection Id :param str name: private endpoint connection name :param 'PrivateLinkServiceConnectionStateResponseArgs' private_link_service_connection_state: A collection of information about the state of the connection between DiskAccess and Virtual Network. :param str provisioning_state: The provisioning state of the private endpoint connection resource. :param str type: private endpoint connection type :param 'PrivateEndpointResponseArgs' private_endpoint: The resource of private end point. """ pulumi.set(__self__, "id", id) pulumi.set(__self__, "name", name) pulumi.set(__self__, "private_link_service_connection_state", private_link_service_connection_state) pulumi.set(__self__, "provisioning_state", provisioning_state) pulumi.set(__self__, "type", type) if private_endpoint is not None: pulumi.set(__self__, "private_endpoint", private_endpoint) @property @pulumi.getter def id(self) -> str: """ private endpoint connection Id """ return pulumi.get(self, "id") @property @pulumi.getter def name(self) -> str: """ private endpoint connection name """ return pulumi.get(self, "name") @property @pulumi.getter(name="privateLinkServiceConnectionState") def private_link_service_connection_state(self) -> 'outputs.PrivateLinkServiceConnectionStateResponse': """ A collection of information about the state of the connection between DiskAccess and Virtual Network. """ return pulumi.get(self, "private_link_service_connection_state") @property @pulumi.getter(name="provisioningState") def provisioning_state(self) -> str: """ The provisioning state of the private endpoint connection resource. """ return pulumi.get(self, "provisioning_state") @property @pulumi.getter def type(self) -> str: """ private endpoint connection type """ return pulumi.get(self, "type") @property @pulumi.getter(name="privateEndpoint") def private_endpoint(self) -> Optional['outputs.PrivateEndpointResponse']: """ The resource of private end point. """ return pulumi.get(self, "private_endpoint") def _translate_property(self, prop): return _tables.CAMEL_TO_SNAKE_CASE_TABLE.get(prop) or prop @pulumi.output_type class PrivateEndpointResponse(dict): """ The Private Endpoint resource. """ def __init__(__self__, *, id: str): """ The Private Endpoint resource. :param str id: The ARM identifier for Private Endpoint """ pulumi.set(__self__, "id", id) @property @pulumi.getter def id(self) -> str: """ The ARM identifier for Private Endpoint """ return pulumi.get(self, "id") def _translate_property(self, prop): return _tables.CAMEL_TO_SNAKE_CASE_TABLE.get(prop) or prop @pulumi.output_type class PrivateLinkServiceConnectionStateResponse(dict): """ A collection of information about the state of the connection between service consumer and provider. """ def __init__(__self__, *, actions_required: Optional[str] = None, description: Optional[str] = None, status: Optional[str] = None): """ A collection of information about the state of the connection between service consumer and provider. :param str actions_required: A message indicating if changes on the service provider require any updates on the consumer. :param str description: The reason for approval/rejection of the connection. :param str status: Indicates whether the connection has been Approved/Rejected/Removed by the owner of the service. """ if actions_required is not None: pulumi.set(__self__, "actions_required", actions_required) if description is not None: pulumi.set(__self__, "description", description) if status is not None: pulumi.set(__self__, "status", status) @property @pulumi.getter(name="actionsRequired") def actions_required(self) -> Optional[str]: """ A message indicating if changes on the service provider require any updates on the consumer. """ return pulumi.get(self, "actions_required") @property @pulumi.getter def description(self) -> Optional[str]: """ The reason for approval/rejection of the connection. """ return pulumi.get(self, "description") @property @pulumi.getter def status(self) -> Optional[str]: """ Indicates whether the connection has been Approved/Rejected/Removed by the owner of the service. """ return pulumi.get(self, "status") def _translate_property(self, prop): return _tables.CAMEL_TO_SNAKE_CASE_TABLE.get(prop) or prop @pulumi.output_type class PurchasePlanResponse(dict): """ Used for establishing the purchase context of any 3rd Party artifact through MarketPlace. """ def __init__(__self__, *, name: str, product: str, publisher: str, promotion_code: Optional[str] = None): """ Used for establishing the purchase context of any 3rd Party artifact through MarketPlace. :param str name: The plan ID. :param str product: Specifies the product of the image from the marketplace. This is the same value as Offer under the imageReference element. :param str publisher: The publisher ID. :param str promotion_code: The Offer Promotion Code. """ pulumi.set(__self__, "name", name) pulumi.set(__self__, "product", product) pulumi.set(__self__, "publisher", publisher) if promotion_code is not None: pulumi.set(__self__, "promotion_code", promotion_code) @property @pulumi.getter def name(self) -> str: """ The plan ID. """ return pulumi.get(self, "name") @property @pulumi.getter def product(self) -> str: """ Specifies the product of the image from the marketplace. This is the same value as Offer under the imageReference element. """ return pulumi.get(self, "product") @property @pulumi.getter def publisher(self) -> str: """ The publisher ID. """ return pulumi.get(self, "publisher") @property @pulumi.getter(name="promotionCode") def promotion_code(self) -> Optional[str]: """ The Offer Promotion Code. """ return pulumi.get(self, "promotion_code") def _translate_property(self, prop): return _tables.CAMEL_TO_SNAKE_CASE_TABLE.get(prop) or prop @pulumi.output_type class RecommendedMachineConfigurationResponse(dict): """ The properties describe the recommended machine configuration for this Image Definition. These properties are updatable. """ def __init__(__self__, *, memory: Optional['outputs.ResourceRangeResponse'] = None, v_cpus: Optional['outputs.ResourceRangeResponse'] = None): """ The properties describe the recommended machine configuration for this Image Definition. These properties are updatable. :param 'ResourceRangeResponseArgs' memory: Describes the resource range. :param 'ResourceRangeResponseArgs' v_cpus: Describes the resource range. """ if memory is not None: pulumi.set(__self__, "memory", memory) if v_cpus is not None: pulumi.set(__self__, "v_cpus", v_cpus) @property @pulumi.getter def memory(self) -> Optional['outputs.ResourceRangeResponse']: """ Describes the resource range. """ return pulumi.get(self, "memory") @property @pulumi.getter(name="vCPUs") def v_cpus(self) -> Optional['outputs.ResourceRangeResponse']: """ Describes the resource range. """ return pulumi.get(self, "v_cpus") def _translate_property(self, prop): return _tables.CAMEL_TO_SNAKE_CASE_TABLE.get(prop) or prop @pulumi.output_type class RegionalReplicationStatusResponse(dict): """ This is the regional replication status. """ def __init__(__self__, *, details: str, progress: int, region: str, state: str): """ This is the regional replication status. :param str details: The details of the replication status. :param int progress: It indicates progress of the replication job. :param str region: The region to which the gallery image version is being replicated to. :param str state: This is the regional replication state. """ pulumi.set(__self__, "details", details) pulumi.set(__self__, "progress", progress) pulumi.set(__self__, "region", region) pulumi.set(__self__, "state", state) @property @pulumi.getter def details(self) -> str: """ The details of the replication status. """ return pulumi.get(self, "details") @property @pulumi.getter def progress(self) -> int: """ It indicates progress of the replication job. """ return pulumi.get(self, "progress") @property @pulumi.getter def region(self) -> str: """ The region to which the gallery image version is being replicated to. """ return pulumi.get(self, "region") @property @pulumi.getter def state(self) -> str: """ This is the regional replication state. """ return pulumi.get(self, "state") def _translate_property(self, prop): return _tables.CAMEL_TO_SNAKE_CASE_TABLE.get(prop) or prop @pulumi.output_type class ReplicationStatusResponse(dict): """ This is the replication status of the gallery image version. """ def __init__(__self__, *, aggregated_state: str, summary: Sequence['outputs.RegionalReplicationStatusResponse']): """ This is the replication status of the gallery image version. :param str aggregated_state: This is the aggregated replication status based on all the regional replication status flags. :param Sequence['RegionalReplicationStatusResponseArgs'] summary: This is a summary of replication status for each region. """ pulumi.set(__self__, "aggregated_state", aggregated_state) pulumi.set(__self__, "summary", summary) @property @pulumi.getter(name="aggregatedState") def aggregated_state(self) -> str: """ This is the aggregated replication status based on all the regional replication status flags. """ return pulumi.get(self, "aggregated_state") @property @pulumi.getter def summary(self) -> Sequence['outputs.RegionalReplicationStatusResponse']: """ This is a summary of replication status for each region. """ return pulumi.get(self, "summary") def _translate_property(self, prop): return _tables.CAMEL_TO_SNAKE_CASE_TABLE.get(prop) or prop @pulumi.output_type class ResourceRangeResponse(dict): """ Describes the resource range. """ def __init__(__self__, *, max: Optional[int] = None, min: Optional[int] = None): """ Describes the resource range. :param int max: The maximum number of the resource. :param int min: The minimum number of the resource. """ if max is not None: pulumi.set(__self__, "max", max) if min is not None: pulumi.set(__self__, "min", min) @property @pulumi.getter def max(self) -> Optional[int]: """ The maximum number of the resource. """ return pulumi.get(self, "max") @property @pulumi.getter def min(self) -> Optional[int]: """ The minimum number of the resource. """ return pulumi.get(self, "min") def _translate_property(self, prop): return _tables.CAMEL_TO_SNAKE_CASE_TABLE.get(prop) or prop @pulumi.output_type class ShareInfoElementResponse(dict): def __init__(__self__, *, vm_uri: str): """ :param str vm_uri: A relative URI containing the ID of the VM that has the disk attached. """ pulumi.set(__self__, "vm_uri", vm_uri) @property @pulumi.getter(name="vmUri") def vm_uri(self) -> str: """ A relative URI containing the ID of the VM that has the disk attached. """ return pulumi.get(self, "vm_uri") def _translate_property(self, prop): return _tables.CAMEL_TO_SNAKE_CASE_TABLE.get(prop) or prop @pulumi.output_type class SharingProfileGroupResponse(dict): """ Group of the gallery sharing profile """ def __init__(__self__, *, ids: Optional[Sequence[str]] = None, type: Optional[str] = None): """ Group of the gallery sharing profile :param Sequence[str] ids: A list of subscription/tenant ids the gallery is aimed to be shared to. :param str type: This property allows you to specify the type of sharing group. <br><br> Possible values are: <br><br> **Subscriptions** <br><br> **AADTenants** """ if ids is not None: pulumi.set(__self__, "ids", ids) if type is not None: pulumi.set(__self__, "type", type) @property @pulumi.getter def ids(self) -> Optional[Sequence[str]]: """ A list of subscription/tenant ids the gallery is aimed to be shared to. """ return pulumi.get(self, "ids") @property @pulumi.getter def type(self) -> Optional[str]: """ This property allows you to specify the type of sharing group. <br><br> Possible values are: <br><br> **Subscriptions** <br><br> **AADTenants** """ return pulumi.get(self, "type") def _translate_property(self, prop): return _tables.CAMEL_TO_SNAKE_CASE_TABLE.get(prop) or prop @pulumi.output_type class SharingProfileResponse(dict): """ Profile for gallery sharing to subscription or tenant """ def __init__(__self__, *, groups: Sequence['outputs.SharingProfileGroupResponse'], permissions: Optional[str] = None): """ Profile for gallery sharing to subscription or tenant :param Sequence['SharingProfileGroupResponseArgs'] groups: A list of sharing profile groups. :param str permissions: This property allows you to specify the permission of sharing gallery. <br><br> Possible values are: <br><br> **Private** <br><br> **Groups** """ pulumi.set(__self__, "groups", groups) if permissions is not None: pulumi.set(__self__, "permissions", permissions) @property @pulumi.getter def groups(self) -> Sequence['outputs.SharingProfileGroupResponse']: """ A list of sharing profile groups. """ return pulumi.get(self, "groups") @property @pulumi.getter def permissions(self) -> Optional[str]: """ This property allows you to specify the permission of sharing gallery. <br><br> Possible values are: <br><br> **Private** <br><br> **Groups** """ return pulumi.get(self, "permissions") def _translate_property(self, prop): return _tables.CAMEL_TO_SNAKE_CASE_TABLE.get(prop) or prop @pulumi.output_type class SnapshotSkuResponse(dict): """ The snapshots sku name. Can be Standard_LRS, Premium_LRS, or Standard_ZRS. This is an optional parameter for incremental snapshot and the default behavior is the SKU will be set to the same sku as the previous snapshot """ def __init__(__self__, *, tier: str, name: Optional[str] = None): """ The snapshots sku name. Can be Standard_LRS, Premium_LRS, or Standard_ZRS. This is an optional parameter for incremental snapshot and the default behavior is the SKU will be set to the same sku as the previous snapshot :param str tier: The sku tier. :param str name: The sku name. """ pulumi.set(__self__, "tier", tier) if name is not None: pulumi.set(__self__, "name", name) @property @pulumi.getter def tier(self) -> str: """ The sku tier. """ return pulumi.get(self, "tier") @property @pulumi.getter def name(self) -> Optional[str]: """ The sku name. """ return pulumi.get(self, "name") def _translate_property(self, prop): return _tables.CAMEL_TO_SNAKE_CASE_TABLE.get(prop) or prop @pulumi.output_type class SourceVaultResponse(dict): """ The vault id is an Azure Resource Manager Resource id in the form /subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.KeyVault/vaults/{vaultName} """ def __init__(__self__, *, id: Optional[str] = None): """ The vault id is an Azure Resource Manager Resource id in the form /subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.KeyVault/vaults/{vaultName} :param str id: Resource Id """ if id is not None: pulumi.set(__self__, "id", id) @property @pulumi.getter def id(self) -> Optional[str]: """ Resource Id """ return pulumi.get(self, "id") def _translate_property(self, prop): return _tables.CAMEL_TO_SNAKE_CASE_TABLE.get(prop) or prop @pulumi.output_type class TargetRegionResponse(dict): """ Describes the target region information. """ def __init__(__self__, *, name: str, encryption: Optional['outputs.EncryptionImagesResponse'] = None, regional_replica_count: Optional[int] = None, storage_account_type: Optional[str] = None): """ Describes the target region information. :param str name: The name of the region. :param 'EncryptionImagesResponseArgs' encryption: Optional. Allows users to provide customer managed keys for encrypting the OS and data disks in the gallery artifact. :param int regional_replica_count: The number of replicas of the Image Version to be created per region. This property is updatable. :param str storage_account_type: Specifies the storage account type to be used to store the image. This property is not updatable. """ pulumi.set(__self__, "name", name) if encryption is not None: pulumi.set(__self__, "encryption", encryption) if regional_replica_count is not None: pulumi.set(__self__, "regional_replica_count", regional_replica_count) if storage_account_type is not None: pulumi.set(__self__, "storage_account_type", storage_account_type) @property @pulumi.getter def name(self) -> str: """ The name of the region. """ return pulumi.get(self, "name") @property @pulumi.getter def encryption(self) -> Optional['outputs.EncryptionImagesResponse']: """ Optional. Allows users to provide customer managed keys for encrypting the OS and data disks in the gallery artifact. """ return pulumi.get(self, "encryption") @property @pulumi.getter(name="regionalReplicaCount") def regional_replica_count(self) -> Optional[int]: """ The number of replicas of the Image Version to be created per region. This property is updatable. """ return pulumi.get(self, "regional_replica_count") @property @pulumi.getter(name="storageAccountType") def storage_account_type(self) -> Optional[str]: """ Specifies the storage account type to be used to store the image. This property is not updatable. """ return pulumi.get(self, "storage_account_type") def _translate_property(self, prop): return _tables.CAMEL_TO_SNAKE_CASE_TABLE.get(prop) or prop @pulumi.output_type class UserArtifactManageResponse(dict): def __init__(__self__, *, install: str, remove: str, update: Optional[str] = None): """ :param str install: Required. The path and arguments to install the gallery application. This is limited to 4096 characters. :param str remove: Required. The path and arguments to remove the gallery application. This is limited to 4096 characters. :param str update: Optional. The path and arguments to update the gallery application. If not present, then update operation will invoke remove command on the previous version and install command on the current version of the gallery application. This is limited to 4096 characters. """ pulumi.set(__self__, "install", install) pulumi.set(__self__, "remove", remove) if update is not None: pulumi.set(__self__, "update", update) @property @pulumi.getter def install(self) -> str: """ Required. The path and arguments to install the gallery application. This is limited to 4096 characters. """ return pulumi.get(self, "install") @property @pulumi.getter def remove(self) -> str: """ Required. The path and arguments to remove the gallery application. This is limited to 4096 characters. """ return pulumi.get(self, "remove") @property @pulumi.getter def update(self) -> Optional[str]: """ Optional. The path and arguments to update the gallery application. If not present, then update operation will invoke remove command on the previous version and install command on the current version of the gallery application. This is limited to 4096 characters. """ return pulumi.get(self, "update") def _translate_property(self, prop): return _tables.CAMEL_TO_SNAKE_CASE_TABLE.get(prop) or prop @pulumi.output_type class UserArtifactSourceResponse(dict): """ The source image from which the Image Version is going to be created. """ def __init__(__self__, *, media_link: str, default_configuration_link: Optional[str] = None): """ The source image from which the Image Version is going to be created. :param str media_link: Required. The mediaLink of the artifact, must be a readable storage page blob. :param str default_configuration_link: Optional. The defaultConfigurationLink of the artifact, must be a readable storage page blob. """ pulumi.set(__self__, "media_link", media_link) if default_configuration_link is not None: pulumi.set(__self__, "default_configuration_link", default_configuration_link) @property @pulumi.getter(name="mediaLink") def media_link(self) -> str: """ Required. The mediaLink of the artifact, must be a readable storage page blob. """ return pulumi.get(self, "media_link") @property @pulumi.getter(name="defaultConfigurationLink") def default_configuration_link(self) -> Optional[str]: """ Optional. The defaultConfigurationLink of the artifact, must be a readable storage page blob. """ return pulumi.get(self, "default_configuration_link") def _translate_property(self, prop): return _tables.CAMEL_TO_SNAKE_CASE_TABLE.get(prop) or prop
38.95829
335
0.657718
import warnings import pulumi import pulumi.runtime from typing import Any, Mapping, Optional, Sequence, Union from ... import _utilities, _tables from . import outputs from ._enums import * __all__ = [ 'CreationDataResponse', 'DataDiskImageEncryptionResponse', 'DisallowedResponse', 'DiskSkuResponse', 'EncryptionImagesResponse', 'EncryptionResponse', 'EncryptionSetIdentityResponse', 'EncryptionSettingsCollectionResponse', 'EncryptionSettingsElementResponse', 'ExtendedLocationResponse', 'GalleryApplicationVersionPublishingProfileResponse', 'GalleryArtifactVersionSourceResponse', 'GalleryDataDiskImageResponse', 'GalleryIdentifierResponse', 'GalleryImageFeatureResponse', 'GalleryImageIdentifierResponse', 'GalleryImageVersionPublishingProfileResponse', 'GalleryImageVersionStorageProfileResponse', 'GalleryOSDiskImageResponse', 'ImageDiskReferenceResponse', 'ImagePurchasePlanResponse', 'KeyForDiskEncryptionSetResponse', 'KeyVaultAndKeyReferenceResponse', 'KeyVaultAndSecretReferenceResponse', 'OSDiskImageEncryptionResponse', 'PrivateEndpointConnectionResponse', 'PrivateEndpointResponse', 'PrivateLinkServiceConnectionStateResponse', 'PurchasePlanResponse', 'RecommendedMachineConfigurationResponse', 'RegionalReplicationStatusResponse', 'ReplicationStatusResponse', 'ResourceRangeResponse', 'ShareInfoElementResponse', 'SharingProfileGroupResponse', 'SharingProfileResponse', 'SnapshotSkuResponse', 'SourceVaultResponse', 'TargetRegionResponse', 'UserArtifactManageResponse', 'UserArtifactSourceResponse', ] @pulumi.output_type class CreationDataResponse(dict): def __init__(__self__, *, create_option: str, source_unique_id: str, gallery_image_reference: Optional['outputs.ImageDiskReferenceResponse'] = None, image_reference: Optional['outputs.ImageDiskReferenceResponse'] = None, logical_sector_size: Optional[int] = None, source_resource_id: Optional[str] = None, source_uri: Optional[str] = None, storage_account_id: Optional[str] = None, upload_size_bytes: Optional[float] = None): pulumi.set(__self__, "create_option", create_option) pulumi.set(__self__, "source_unique_id", source_unique_id) if gallery_image_reference is not None: pulumi.set(__self__, "gallery_image_reference", gallery_image_reference) if image_reference is not None: pulumi.set(__self__, "image_reference", image_reference) if logical_sector_size is not None: pulumi.set(__self__, "logical_sector_size", logical_sector_size) if source_resource_id is not None: pulumi.set(__self__, "source_resource_id", source_resource_id) if source_uri is not None: pulumi.set(__self__, "source_uri", source_uri) if storage_account_id is not None: pulumi.set(__self__, "storage_account_id", storage_account_id) if upload_size_bytes is not None: pulumi.set(__self__, "upload_size_bytes", upload_size_bytes) @property @pulumi.getter(name="createOption") def create_option(self) -> str: return pulumi.get(self, "create_option") @property @pulumi.getter(name="sourceUniqueId") def source_unique_id(self) -> str: return pulumi.get(self, "source_unique_id") @property @pulumi.getter(name="galleryImageReference") def gallery_image_reference(self) -> Optional['outputs.ImageDiskReferenceResponse']: return pulumi.get(self, "gallery_image_reference") @property @pulumi.getter(name="imageReference") def image_reference(self) -> Optional['outputs.ImageDiskReferenceResponse']: return pulumi.get(self, "image_reference") @property @pulumi.getter(name="logicalSectorSize") def logical_sector_size(self) -> Optional[int]: return pulumi.get(self, "logical_sector_size") @property @pulumi.getter(name="sourceResourceId") def source_resource_id(self) -> Optional[str]: return pulumi.get(self, "source_resource_id") @property @pulumi.getter(name="sourceUri") def source_uri(self) -> Optional[str]: return pulumi.get(self, "source_uri") @property @pulumi.getter(name="storageAccountId") def storage_account_id(self) -> Optional[str]: return pulumi.get(self, "storage_account_id") @property @pulumi.getter(name="uploadSizeBytes") def upload_size_bytes(self) -> Optional[float]: return pulumi.get(self, "upload_size_bytes") def _translate_property(self, prop): return _tables.CAMEL_TO_SNAKE_CASE_TABLE.get(prop) or prop @pulumi.output_type class DataDiskImageEncryptionResponse(dict): def __init__(__self__, *, lun: int, disk_encryption_set_id: Optional[str] = None): pulumi.set(__self__, "lun", lun) if disk_encryption_set_id is not None: pulumi.set(__self__, "disk_encryption_set_id", disk_encryption_set_id) @property @pulumi.getter def lun(self) -> int: return pulumi.get(self, "lun") @property @pulumi.getter(name="diskEncryptionSetId") def disk_encryption_set_id(self) -> Optional[str]: return pulumi.get(self, "disk_encryption_set_id") def _translate_property(self, prop): return _tables.CAMEL_TO_SNAKE_CASE_TABLE.get(prop) or prop @pulumi.output_type class DisallowedResponse(dict): def __init__(__self__, *, disk_types: Optional[Sequence[str]] = None): if disk_types is not None: pulumi.set(__self__, "disk_types", disk_types) @property @pulumi.getter(name="diskTypes") def disk_types(self) -> Optional[Sequence[str]]: return pulumi.get(self, "disk_types") def _translate_property(self, prop): return _tables.CAMEL_TO_SNAKE_CASE_TABLE.get(prop) or prop @pulumi.output_type class DiskSkuResponse(dict): def __init__(__self__, *, tier: str, name: Optional[str] = None): pulumi.set(__self__, "tier", tier) if name is not None: pulumi.set(__self__, "name", name) @property @pulumi.getter def tier(self) -> str: return pulumi.get(self, "tier") @property @pulumi.getter def name(self) -> Optional[str]: return pulumi.get(self, "name") def _translate_property(self, prop): return _tables.CAMEL_TO_SNAKE_CASE_TABLE.get(prop) or prop @pulumi.output_type class EncryptionImagesResponse(dict): def __init__(__self__, *, data_disk_images: Optional[Sequence['outputs.DataDiskImageEncryptionResponse']] = None, os_disk_image: Optional['outputs.OSDiskImageEncryptionResponse'] = None): if data_disk_images is not None: pulumi.set(__self__, "data_disk_images", data_disk_images) if os_disk_image is not None: pulumi.set(__self__, "os_disk_image", os_disk_image) @property @pulumi.getter(name="dataDiskImages") def data_disk_images(self) -> Optional[Sequence['outputs.DataDiskImageEncryptionResponse']]: return pulumi.get(self, "data_disk_images") @property @pulumi.getter(name="osDiskImage") def os_disk_image(self) -> Optional['outputs.OSDiskImageEncryptionResponse']: return pulumi.get(self, "os_disk_image") def _translate_property(self, prop): return _tables.CAMEL_TO_SNAKE_CASE_TABLE.get(prop) or prop @pulumi.output_type class EncryptionResponse(dict): def __init__(__self__, *, disk_encryption_set_id: Optional[str] = None, type: Optional[str] = None): if disk_encryption_set_id is not None: pulumi.set(__self__, "disk_encryption_set_id", disk_encryption_set_id) if type is not None: pulumi.set(__self__, "type", type) @property @pulumi.getter(name="diskEncryptionSetId") def disk_encryption_set_id(self) -> Optional[str]: return pulumi.get(self, "disk_encryption_set_id") @property @pulumi.getter def type(self) -> Optional[str]: return pulumi.get(self, "type") def _translate_property(self, prop): return _tables.CAMEL_TO_SNAKE_CASE_TABLE.get(prop) or prop @pulumi.output_type class EncryptionSetIdentityResponse(dict): def __init__(__self__, *, principal_id: str, tenant_id: str, type: Optional[str] = None): pulumi.set(__self__, "principal_id", principal_id) pulumi.set(__self__, "tenant_id", tenant_id) if type is not None: pulumi.set(__self__, "type", type) @property @pulumi.getter(name="principalId") def principal_id(self) -> str: return pulumi.get(self, "principal_id") @property @pulumi.getter(name="tenantId") def tenant_id(self) -> str: return pulumi.get(self, "tenant_id") @property @pulumi.getter def type(self) -> Optional[str]: return pulumi.get(self, "type") def _translate_property(self, prop): return _tables.CAMEL_TO_SNAKE_CASE_TABLE.get(prop) or prop @pulumi.output_type class EncryptionSettingsCollectionResponse(dict): def __init__(__self__, *, enabled: bool, encryption_settings: Optional[Sequence['outputs.EncryptionSettingsElementResponse']] = None, encryption_settings_version: Optional[str] = None): pulumi.set(__self__, "enabled", enabled) if encryption_settings is not None: pulumi.set(__self__, "encryption_settings", encryption_settings) if encryption_settings_version is not None: pulumi.set(__self__, "encryption_settings_version", encryption_settings_version) @property @pulumi.getter def enabled(self) -> bool: return pulumi.get(self, "enabled") @property @pulumi.getter(name="encryptionSettings") def encryption_settings(self) -> Optional[Sequence['outputs.EncryptionSettingsElementResponse']]: return pulumi.get(self, "encryption_settings") @property @pulumi.getter(name="encryptionSettingsVersion") def encryption_settings_version(self) -> Optional[str]: return pulumi.get(self, "encryption_settings_version") def _translate_property(self, prop): return _tables.CAMEL_TO_SNAKE_CASE_TABLE.get(prop) or prop @pulumi.output_type class EncryptionSettingsElementResponse(dict): def __init__(__self__, *, disk_encryption_key: Optional['outputs.KeyVaultAndSecretReferenceResponse'] = None, key_encryption_key: Optional['outputs.KeyVaultAndKeyReferenceResponse'] = None): if disk_encryption_key is not None: pulumi.set(__self__, "disk_encryption_key", disk_encryption_key) if key_encryption_key is not None: pulumi.set(__self__, "key_encryption_key", key_encryption_key) @property @pulumi.getter(name="diskEncryptionKey") def disk_encryption_key(self) -> Optional['outputs.KeyVaultAndSecretReferenceResponse']: return pulumi.get(self, "disk_encryption_key") @property @pulumi.getter(name="keyEncryptionKey") def key_encryption_key(self) -> Optional['outputs.KeyVaultAndKeyReferenceResponse']: return pulumi.get(self, "key_encryption_key") def _translate_property(self, prop): return _tables.CAMEL_TO_SNAKE_CASE_TABLE.get(prop) or prop @pulumi.output_type class ExtendedLocationResponse(dict): def __init__(__self__, *, name: Optional[str] = None, type: Optional[str] = None): if name is not None: pulumi.set(__self__, "name", name) if type is not None: pulumi.set(__self__, "type", type) @property @pulumi.getter def name(self) -> Optional[str]: return pulumi.get(self, "name") @property @pulumi.getter def type(self) -> Optional[str]: return pulumi.get(self, "type") def _translate_property(self, prop): return _tables.CAMEL_TO_SNAKE_CASE_TABLE.get(prop) or prop @pulumi.output_type class GalleryApplicationVersionPublishingProfileResponse(dict): def __init__(__self__, *, published_date: str, source: 'outputs.UserArtifactSourceResponse', enable_health_check: Optional[bool] = None, end_of_life_date: Optional[str] = None, exclude_from_latest: Optional[bool] = None, manage_actions: Optional['outputs.UserArtifactManageResponse'] = None, replica_count: Optional[int] = None, storage_account_type: Optional[str] = None, target_regions: Optional[Sequence['outputs.TargetRegionResponse']] = None): pulumi.set(__self__, "published_date", published_date) pulumi.set(__self__, "source", source) if enable_health_check is not None: pulumi.set(__self__, "enable_health_check", enable_health_check) if end_of_life_date is not None: pulumi.set(__self__, "end_of_life_date", end_of_life_date) if exclude_from_latest is not None: pulumi.set(__self__, "exclude_from_latest", exclude_from_latest) if manage_actions is not None: pulumi.set(__self__, "manage_actions", manage_actions) if replica_count is not None: pulumi.set(__self__, "replica_count", replica_count) if storage_account_type is not None: pulumi.set(__self__, "storage_account_type", storage_account_type) if target_regions is not None: pulumi.set(__self__, "target_regions", target_regions) @property @pulumi.getter(name="publishedDate") def published_date(self) -> str: return pulumi.get(self, "published_date") @property @pulumi.getter def source(self) -> 'outputs.UserArtifactSourceResponse': return pulumi.get(self, "source") @property @pulumi.getter(name="enableHealthCheck") def enable_health_check(self) -> Optional[bool]: return pulumi.get(self, "enable_health_check") @property @pulumi.getter(name="endOfLifeDate") def end_of_life_date(self) -> Optional[str]: return pulumi.get(self, "end_of_life_date") @property @pulumi.getter(name="excludeFromLatest") def exclude_from_latest(self) -> Optional[bool]: return pulumi.get(self, "exclude_from_latest") @property @pulumi.getter(name="manageActions") def manage_actions(self) -> Optional['outputs.UserArtifactManageResponse']: return pulumi.get(self, "manage_actions") @property @pulumi.getter(name="replicaCount") def replica_count(self) -> Optional[int]: return pulumi.get(self, "replica_count") @property @pulumi.getter(name="storageAccountType") def storage_account_type(self) -> Optional[str]: return pulumi.get(self, "storage_account_type") @property @pulumi.getter(name="targetRegions") def target_regions(self) -> Optional[Sequence['outputs.TargetRegionResponse']]: return pulumi.get(self, "target_regions") def _translate_property(self, prop): return _tables.CAMEL_TO_SNAKE_CASE_TABLE.get(prop) or prop @pulumi.output_type class GalleryArtifactVersionSourceResponse(dict): def __init__(__self__, *, id: Optional[str] = None, uri: Optional[str] = None): if id is not None: pulumi.set(__self__, "id", id) if uri is not None: pulumi.set(__self__, "uri", uri) @property @pulumi.getter def id(self) -> Optional[str]: return pulumi.get(self, "id") @property @pulumi.getter def uri(self) -> Optional[str]: return pulumi.get(self, "uri") def _translate_property(self, prop): return _tables.CAMEL_TO_SNAKE_CASE_TABLE.get(prop) or prop @pulumi.output_type class GalleryDataDiskImageResponse(dict): def __init__(__self__, *, lun: int, size_in_gb: int, host_caching: Optional[str] = None, source: Optional['outputs.GalleryArtifactVersionSourceResponse'] = None): pulumi.set(__self__, "lun", lun) pulumi.set(__self__, "size_in_gb", size_in_gb) if host_caching is not None: pulumi.set(__self__, "host_caching", host_caching) if source is not None: pulumi.set(__self__, "source", source) @property @pulumi.getter def lun(self) -> int: return pulumi.get(self, "lun") @property @pulumi.getter(name="sizeInGB") def size_in_gb(self) -> int: return pulumi.get(self, "size_in_gb") @property @pulumi.getter(name="hostCaching") def host_caching(self) -> Optional[str]: return pulumi.get(self, "host_caching") @property @pulumi.getter def source(self) -> Optional['outputs.GalleryArtifactVersionSourceResponse']: return pulumi.get(self, "source") def _translate_property(self, prop): return _tables.CAMEL_TO_SNAKE_CASE_TABLE.get(prop) or prop @pulumi.output_type class GalleryIdentifierResponse(dict): def __init__(__self__, *, unique_name: str): pulumi.set(__self__, "unique_name", unique_name) @property @pulumi.getter(name="uniqueName") def unique_name(self) -> str: return pulumi.get(self, "unique_name") def _translate_property(self, prop): return _tables.CAMEL_TO_SNAKE_CASE_TABLE.get(prop) or prop @pulumi.output_type class GalleryImageFeatureResponse(dict): def __init__(__self__, *, name: Optional[str] = None, value: Optional[str] = None): if name is not None: pulumi.set(__self__, "name", name) if value is not None: pulumi.set(__self__, "value", value) @property @pulumi.getter def name(self) -> Optional[str]: return pulumi.get(self, "name") @property @pulumi.getter def value(self) -> Optional[str]: return pulumi.get(self, "value") def _translate_property(self, prop): return _tables.CAMEL_TO_SNAKE_CASE_TABLE.get(prop) or prop @pulumi.output_type class GalleryImageIdentifierResponse(dict): def __init__(__self__, *, offer: str, publisher: str, sku: str): pulumi.set(__self__, "offer", offer) pulumi.set(__self__, "publisher", publisher) pulumi.set(__self__, "sku", sku) @property @pulumi.getter def offer(self) -> str: return pulumi.get(self, "offer") @property @pulumi.getter def publisher(self) -> str: return pulumi.get(self, "publisher") @property @pulumi.getter def sku(self) -> str: return pulumi.get(self, "sku") def _translate_property(self, prop): return _tables.CAMEL_TO_SNAKE_CASE_TABLE.get(prop) or prop @pulumi.output_type class GalleryImageVersionPublishingProfileResponse(dict): def __init__(__self__, *, published_date: str, end_of_life_date: Optional[str] = None, exclude_from_latest: Optional[bool] = None, replica_count: Optional[int] = None, storage_account_type: Optional[str] = None, target_regions: Optional[Sequence['outputs.TargetRegionResponse']] = None): pulumi.set(__self__, "published_date", published_date) if end_of_life_date is not None: pulumi.set(__self__, "end_of_life_date", end_of_life_date) if exclude_from_latest is not None: pulumi.set(__self__, "exclude_from_latest", exclude_from_latest) if replica_count is not None: pulumi.set(__self__, "replica_count", replica_count) if storage_account_type is not None: pulumi.set(__self__, "storage_account_type", storage_account_type) if target_regions is not None: pulumi.set(__self__, "target_regions", target_regions) @property @pulumi.getter(name="publishedDate") def published_date(self) -> str: return pulumi.get(self, "published_date") @property @pulumi.getter(name="endOfLifeDate") def end_of_life_date(self) -> Optional[str]: return pulumi.get(self, "end_of_life_date") @property @pulumi.getter(name="excludeFromLatest") def exclude_from_latest(self) -> Optional[bool]: return pulumi.get(self, "exclude_from_latest") @property @pulumi.getter(name="replicaCount") def replica_count(self) -> Optional[int]: return pulumi.get(self, "replica_count") @property @pulumi.getter(name="storageAccountType") def storage_account_type(self) -> Optional[str]: return pulumi.get(self, "storage_account_type") @property @pulumi.getter(name="targetRegions") def target_regions(self) -> Optional[Sequence['outputs.TargetRegionResponse']]: return pulumi.get(self, "target_regions") def _translate_property(self, prop): return _tables.CAMEL_TO_SNAKE_CASE_TABLE.get(prop) or prop @pulumi.output_type class GalleryImageVersionStorageProfileResponse(dict): def __init__(__self__, *, data_disk_images: Optional[Sequence['outputs.GalleryDataDiskImageResponse']] = None, os_disk_image: Optional['outputs.GalleryOSDiskImageResponse'] = None, source: Optional['outputs.GalleryArtifactVersionSourceResponse'] = None): if data_disk_images is not None: pulumi.set(__self__, "data_disk_images", data_disk_images) if os_disk_image is not None: pulumi.set(__self__, "os_disk_image", os_disk_image) if source is not None: pulumi.set(__self__, "source", source) @property @pulumi.getter(name="dataDiskImages") def data_disk_images(self) -> Optional[Sequence['outputs.GalleryDataDiskImageResponse']]: return pulumi.get(self, "data_disk_images") @property @pulumi.getter(name="osDiskImage") def os_disk_image(self) -> Optional['outputs.GalleryOSDiskImageResponse']: return pulumi.get(self, "os_disk_image") @property @pulumi.getter def source(self) -> Optional['outputs.GalleryArtifactVersionSourceResponse']: return pulumi.get(self, "source") def _translate_property(self, prop): return _tables.CAMEL_TO_SNAKE_CASE_TABLE.get(prop) or prop @pulumi.output_type class GalleryOSDiskImageResponse(dict): def __init__(__self__, *, size_in_gb: int, host_caching: Optional[str] = None, source: Optional['outputs.GalleryArtifactVersionSourceResponse'] = None): pulumi.set(__self__, "size_in_gb", size_in_gb) if host_caching is not None: pulumi.set(__self__, "host_caching", host_caching) if source is not None: pulumi.set(__self__, "source", source) @property @pulumi.getter(name="sizeInGB") def size_in_gb(self) -> int: return pulumi.get(self, "size_in_gb") @property @pulumi.getter(name="hostCaching") def host_caching(self) -> Optional[str]: return pulumi.get(self, "host_caching") @property @pulumi.getter def source(self) -> Optional['outputs.GalleryArtifactVersionSourceResponse']: return pulumi.get(self, "source") def _translate_property(self, prop): return _tables.CAMEL_TO_SNAKE_CASE_TABLE.get(prop) or prop @pulumi.output_type class ImageDiskReferenceResponse(dict): def __init__(__self__, *, id: str, lun: Optional[int] = None): pulumi.set(__self__, "id", id) if lun is not None: pulumi.set(__self__, "lun", lun) @property @pulumi.getter def id(self) -> str: return pulumi.get(self, "id") @property @pulumi.getter def lun(self) -> Optional[int]: return pulumi.get(self, "lun") def _translate_property(self, prop): return _tables.CAMEL_TO_SNAKE_CASE_TABLE.get(prop) or prop @pulumi.output_type class ImagePurchasePlanResponse(dict): def __init__(__self__, *, name: Optional[str] = None, product: Optional[str] = None, publisher: Optional[str] = None): if name is not None: pulumi.set(__self__, "name", name) if product is not None: pulumi.set(__self__, "product", product) if publisher is not None: pulumi.set(__self__, "publisher", publisher) @property @pulumi.getter def name(self) -> Optional[str]: return pulumi.get(self, "name") @property @pulumi.getter def product(self) -> Optional[str]: return pulumi.get(self, "product") @property @pulumi.getter def publisher(self) -> Optional[str]: return pulumi.get(self, "publisher") def _translate_property(self, prop): return _tables.CAMEL_TO_SNAKE_CASE_TABLE.get(prop) or prop @pulumi.output_type class KeyForDiskEncryptionSetResponse(dict): def __init__(__self__, *, key_url: str, source_vault: Optional['outputs.SourceVaultResponse'] = None): pulumi.set(__self__, "key_url", key_url) if source_vault is not None: pulumi.set(__self__, "source_vault", source_vault) @property @pulumi.getter(name="keyUrl") def key_url(self) -> str: return pulumi.get(self, "key_url") @property @pulumi.getter(name="sourceVault") def source_vault(self) -> Optional['outputs.SourceVaultResponse']: return pulumi.get(self, "source_vault") def _translate_property(self, prop): return _tables.CAMEL_TO_SNAKE_CASE_TABLE.get(prop) or prop @pulumi.output_type class KeyVaultAndKeyReferenceResponse(dict): def __init__(__self__, *, key_url: str, source_vault: 'outputs.SourceVaultResponse'): pulumi.set(__self__, "key_url", key_url) pulumi.set(__self__, "source_vault", source_vault) @property @pulumi.getter(name="keyUrl") def key_url(self) -> str: return pulumi.get(self, "key_url") @property @pulumi.getter(name="sourceVault") def source_vault(self) -> 'outputs.SourceVaultResponse': return pulumi.get(self, "source_vault") def _translate_property(self, prop): return _tables.CAMEL_TO_SNAKE_CASE_TABLE.get(prop) or prop @pulumi.output_type class KeyVaultAndSecretReferenceResponse(dict): def __init__(__self__, *, secret_url: str, source_vault: 'outputs.SourceVaultResponse'): pulumi.set(__self__, "secret_url", secret_url) pulumi.set(__self__, "source_vault", source_vault) @property @pulumi.getter(name="secretUrl") def secret_url(self) -> str: return pulumi.get(self, "secret_url") @property @pulumi.getter(name="sourceVault") def source_vault(self) -> 'outputs.SourceVaultResponse': return pulumi.get(self, "source_vault") def _translate_property(self, prop): return _tables.CAMEL_TO_SNAKE_CASE_TABLE.get(prop) or prop @pulumi.output_type class OSDiskImageEncryptionResponse(dict): def __init__(__self__, *, disk_encryption_set_id: Optional[str] = None): if disk_encryption_set_id is not None: pulumi.set(__self__, "disk_encryption_set_id", disk_encryption_set_id) @property @pulumi.getter(name="diskEncryptionSetId") def disk_encryption_set_id(self) -> Optional[str]: return pulumi.get(self, "disk_encryption_set_id") def _translate_property(self, prop): return _tables.CAMEL_TO_SNAKE_CASE_TABLE.get(prop) or prop @pulumi.output_type class PrivateEndpointConnectionResponse(dict): def __init__(__self__, *, id: str, name: str, private_link_service_connection_state: 'outputs.PrivateLinkServiceConnectionStateResponse', provisioning_state: str, type: str, private_endpoint: Optional['outputs.PrivateEndpointResponse'] = None): pulumi.set(__self__, "id", id) pulumi.set(__self__, "name", name) pulumi.set(__self__, "private_link_service_connection_state", private_link_service_connection_state) pulumi.set(__self__, "provisioning_state", provisioning_state) pulumi.set(__self__, "type", type) if private_endpoint is not None: pulumi.set(__self__, "private_endpoint", private_endpoint) @property @pulumi.getter def id(self) -> str: return pulumi.get(self, "id") @property @pulumi.getter def name(self) -> str: return pulumi.get(self, "name") @property @pulumi.getter(name="privateLinkServiceConnectionState") def private_link_service_connection_state(self) -> 'outputs.PrivateLinkServiceConnectionStateResponse': return pulumi.get(self, "private_link_service_connection_state") @property @pulumi.getter(name="provisioningState") def provisioning_state(self) -> str: return pulumi.get(self, "provisioning_state") @property @pulumi.getter def type(self) -> str: return pulumi.get(self, "type") @property @pulumi.getter(name="privateEndpoint") def private_endpoint(self) -> Optional['outputs.PrivateEndpointResponse']: return pulumi.get(self, "private_endpoint") def _translate_property(self, prop): return _tables.CAMEL_TO_SNAKE_CASE_TABLE.get(prop) or prop @pulumi.output_type class PrivateEndpointResponse(dict): def __init__(__self__, *, id: str): pulumi.set(__self__, "id", id) @property @pulumi.getter def id(self) -> str: return pulumi.get(self, "id") def _translate_property(self, prop): return _tables.CAMEL_TO_SNAKE_CASE_TABLE.get(prop) or prop @pulumi.output_type class PrivateLinkServiceConnectionStateResponse(dict): def __init__(__self__, *, actions_required: Optional[str] = None, description: Optional[str] = None, status: Optional[str] = None): if actions_required is not None: pulumi.set(__self__, "actions_required", actions_required) if description is not None: pulumi.set(__self__, "description", description) if status is not None: pulumi.set(__self__, "status", status) @property @pulumi.getter(name="actionsRequired") def actions_required(self) -> Optional[str]: return pulumi.get(self, "actions_required") @property @pulumi.getter def description(self) -> Optional[str]: return pulumi.get(self, "description") @property @pulumi.getter def status(self) -> Optional[str]: return pulumi.get(self, "status") def _translate_property(self, prop): return _tables.CAMEL_TO_SNAKE_CASE_TABLE.get(prop) or prop @pulumi.output_type class PurchasePlanResponse(dict): def __init__(__self__, *, name: str, product: str, publisher: str, promotion_code: Optional[str] = None): pulumi.set(__self__, "name", name) pulumi.set(__self__, "product", product) pulumi.set(__self__, "publisher", publisher) if promotion_code is not None: pulumi.set(__self__, "promotion_code", promotion_code) @property @pulumi.getter def name(self) -> str: return pulumi.get(self, "name") @property @pulumi.getter def product(self) -> str: return pulumi.get(self, "product") @property @pulumi.getter def publisher(self) -> str: return pulumi.get(self, "publisher") @property @pulumi.getter(name="promotionCode") def promotion_code(self) -> Optional[str]: return pulumi.get(self, "promotion_code") def _translate_property(self, prop): return _tables.CAMEL_TO_SNAKE_CASE_TABLE.get(prop) or prop @pulumi.output_type class RecommendedMachineConfigurationResponse(dict): def __init__(__self__, *, memory: Optional['outputs.ResourceRangeResponse'] = None, v_cpus: Optional['outputs.ResourceRangeResponse'] = None): if memory is not None: pulumi.set(__self__, "memory", memory) if v_cpus is not None: pulumi.set(__self__, "v_cpus", v_cpus) @property @pulumi.getter def memory(self) -> Optional['outputs.ResourceRangeResponse']: return pulumi.get(self, "memory") @property @pulumi.getter(name="vCPUs") def v_cpus(self) -> Optional['outputs.ResourceRangeResponse']: return pulumi.get(self, "v_cpus") def _translate_property(self, prop): return _tables.CAMEL_TO_SNAKE_CASE_TABLE.get(prop) or prop @pulumi.output_type class RegionalReplicationStatusResponse(dict): def __init__(__self__, *, details: str, progress: int, region: str, state: str): pulumi.set(__self__, "details", details) pulumi.set(__self__, "progress", progress) pulumi.set(__self__, "region", region) pulumi.set(__self__, "state", state) @property @pulumi.getter def details(self) -> str: return pulumi.get(self, "details") @property @pulumi.getter def progress(self) -> int: return pulumi.get(self, "progress") @property @pulumi.getter def region(self) -> str: return pulumi.get(self, "region") @property @pulumi.getter def state(self) -> str: return pulumi.get(self, "state") def _translate_property(self, prop): return _tables.CAMEL_TO_SNAKE_CASE_TABLE.get(prop) or prop @pulumi.output_type class ReplicationStatusResponse(dict): def __init__(__self__, *, aggregated_state: str, summary: Sequence['outputs.RegionalReplicationStatusResponse']): pulumi.set(__self__, "aggregated_state", aggregated_state) pulumi.set(__self__, "summary", summary) @property @pulumi.getter(name="aggregatedState") def aggregated_state(self) -> str: return pulumi.get(self, "aggregated_state") @property @pulumi.getter def summary(self) -> Sequence['outputs.RegionalReplicationStatusResponse']: return pulumi.get(self, "summary") def _translate_property(self, prop): return _tables.CAMEL_TO_SNAKE_CASE_TABLE.get(prop) or prop @pulumi.output_type class ResourceRangeResponse(dict): def __init__(__self__, *, max: Optional[int] = None, min: Optional[int] = None): if max is not None: pulumi.set(__self__, "max", max) if min is not None: pulumi.set(__self__, "min", min) @property @pulumi.getter def max(self) -> Optional[int]: return pulumi.get(self, "max") @property @pulumi.getter def min(self) -> Optional[int]: return pulumi.get(self, "min") def _translate_property(self, prop): return _tables.CAMEL_TO_SNAKE_CASE_TABLE.get(prop) or prop @pulumi.output_type class ShareInfoElementResponse(dict): def __init__(__self__, *, vm_uri: str): pulumi.set(__self__, "vm_uri", vm_uri) @property @pulumi.getter(name="vmUri") def vm_uri(self) -> str: return pulumi.get(self, "vm_uri") def _translate_property(self, prop): return _tables.CAMEL_TO_SNAKE_CASE_TABLE.get(prop) or prop @pulumi.output_type class SharingProfileGroupResponse(dict): def __init__(__self__, *, ids: Optional[Sequence[str]] = None, type: Optional[str] = None): if ids is not None: pulumi.set(__self__, "ids", ids) if type is not None: pulumi.set(__self__, "type", type) @property @pulumi.getter def ids(self) -> Optional[Sequence[str]]: return pulumi.get(self, "ids") @property @pulumi.getter def type(self) -> Optional[str]: return pulumi.get(self, "type") def _translate_property(self, prop): return _tables.CAMEL_TO_SNAKE_CASE_TABLE.get(prop) or prop @pulumi.output_type class SharingProfileResponse(dict): def __init__(__self__, *, groups: Sequence['outputs.SharingProfileGroupResponse'], permissions: Optional[str] = None): pulumi.set(__self__, "groups", groups) if permissions is not None: pulumi.set(__self__, "permissions", permissions) @property @pulumi.getter def groups(self) -> Sequence['outputs.SharingProfileGroupResponse']: return pulumi.get(self, "groups") @property @pulumi.getter def permissions(self) -> Optional[str]: return pulumi.get(self, "permissions") def _translate_property(self, prop): return _tables.CAMEL_TO_SNAKE_CASE_TABLE.get(prop) or prop @pulumi.output_type class SnapshotSkuResponse(dict): def __init__(__self__, *, tier: str, name: Optional[str] = None): pulumi.set(__self__, "tier", tier) if name is not None: pulumi.set(__self__, "name", name) @property @pulumi.getter def tier(self) -> str: return pulumi.get(self, "tier") @property @pulumi.getter def name(self) -> Optional[str]: return pulumi.get(self, "name") def _translate_property(self, prop): return _tables.CAMEL_TO_SNAKE_CASE_TABLE.get(prop) or prop @pulumi.output_type class SourceVaultResponse(dict): def __init__(__self__, *, id: Optional[str] = None): if id is not None: pulumi.set(__self__, "id", id) @property @pulumi.getter def id(self) -> Optional[str]: return pulumi.get(self, "id") def _translate_property(self, prop): return _tables.CAMEL_TO_SNAKE_CASE_TABLE.get(prop) or prop @pulumi.output_type class TargetRegionResponse(dict): def __init__(__self__, *, name: str, encryption: Optional['outputs.EncryptionImagesResponse'] = None, regional_replica_count: Optional[int] = None, storage_account_type: Optional[str] = None): pulumi.set(__self__, "name", name) if encryption is not None: pulumi.set(__self__, "encryption", encryption) if regional_replica_count is not None: pulumi.set(__self__, "regional_replica_count", regional_replica_count) if storage_account_type is not None: pulumi.set(__self__, "storage_account_type", storage_account_type) @property @pulumi.getter def name(self) -> str: return pulumi.get(self, "name") @property @pulumi.getter def encryption(self) -> Optional['outputs.EncryptionImagesResponse']: return pulumi.get(self, "encryption") @property @pulumi.getter(name="regionalReplicaCount") def regional_replica_count(self) -> Optional[int]: return pulumi.get(self, "regional_replica_count") @property @pulumi.getter(name="storageAccountType") def storage_account_type(self) -> Optional[str]: return pulumi.get(self, "storage_account_type") def _translate_property(self, prop): return _tables.CAMEL_TO_SNAKE_CASE_TABLE.get(prop) or prop @pulumi.output_type class UserArtifactManageResponse(dict): def __init__(__self__, *, install: str, remove: str, update: Optional[str] = None): pulumi.set(__self__, "install", install) pulumi.set(__self__, "remove", remove) if update is not None: pulumi.set(__self__, "update", update) @property @pulumi.getter def install(self) -> str: return pulumi.get(self, "install") @property @pulumi.getter def remove(self) -> str: return pulumi.get(self, "remove") @property @pulumi.getter def update(self) -> Optional[str]: return pulumi.get(self, "update") def _translate_property(self, prop): return _tables.CAMEL_TO_SNAKE_CASE_TABLE.get(prop) or prop @pulumi.output_type class UserArtifactSourceResponse(dict): def __init__(__self__, *, media_link: str, default_configuration_link: Optional[str] = None): pulumi.set(__self__, "media_link", media_link) if default_configuration_link is not None: pulumi.set(__self__, "default_configuration_link", default_configuration_link) @property @pulumi.getter(name="mediaLink") def media_link(self) -> str: return pulumi.get(self, "media_link") @property @pulumi.getter(name="defaultConfigurationLink") def default_configuration_link(self) -> Optional[str]: return pulumi.get(self, "default_configuration_link") def _translate_property(self, prop): return _tables.CAMEL_TO_SNAKE_CASE_TABLE.get(prop) or prop
true
true
1c33fdb7cffa7a94b8db97932f625aeac2f2911b
4,987
py
Python
helper_nodes/display_poses.py
apl-ocean-engineering/visual_odom
6e88c8d5a098585f7b12e4934f47494414824b4d
[ "MIT" ]
1
2020-11-22T20:09:53.000Z
2020-11-22T20:09:53.000Z
helper_nodes/display_poses.py
apl-ocean-engineering/stereo_visual_odom
6e88c8d5a098585f7b12e4934f47494414824b4d
[ "MIT" ]
null
null
null
helper_nodes/display_poses.py
apl-ocean-engineering/stereo_visual_odom
6e88c8d5a098585f7b12e4934f47494414824b4d
[ "MIT" ]
null
null
null
import matplotlib.pyplot as plt import copy import numpy as np import argparse def get_eucld_error(x1, x2, y1, y2, z1, z2): error = [] for i in range(len(x1)): p1 = np.array([x1[i], y1[i], z1[i]]) p2 = np.array([x2[i], y2[i], z2[i]]) error.append(float(np.sum(np.subtract(p1, p2)))) return error def get_data(f, ignore_count=[]): count = 0 idx = [] time = [] x = [] y = [] z = [] roll = [] pitch = [] yaw = [] for line in f: idx.append(count) count += 1 time.append(line.split(',')[0]) x.append(float(line.split(',')[1])) y.append(float(line.split(',')[2])) z.append(float(line.split(',')[3])) roll.append(float(line.split(',')[4])) pitch.append(float(line.split(',')[5])) yaw.append(float(line.split(',')[6])) return idx, time, x, y, z, roll, pitch, yaw def check_val(l1, l2, idx, ind, max_val, min_val): if l1[ind] > max_val or l2[ind] > max_val: l1.pop(ind) l2.pop(ind) idx.pop(ind) elif l1[ind] < min_val or l2[ind] < min_val: l1.pop(ind) l2.pop(ind) idx.pop(ind) else: ind += 1 return l1, l2, idx, ind def check_error_val(error, idx, ind, max_val, min_val): if error[ind] > max_val: error.pop(ind) idx.pop(ind) elif error[ind] < min_val: error.pop(ind) idx.pop(ind) else: ind += 1 return error, idx, ind def plot(idx_list, v1, v2, v3=None, title=" ", label1="1", label2="2", label3="3", dump=False, y_min=None, y_max=None): fig1, ax1 = plt.subplots() ax1.scatter(idx_list, v1, c='k', label=label1) ax1.scatter(idx_list, v2, c='g', label=label2) if v3 is not None: ax1.scatter(idx_list, v3, c='b', label=label3) ax1.set_title(title) if y_min is not None and y_max is not None: ax1.set_ylim((y_min, y_max)) ax1.legend() if dump: fig1.savefig(title + ".png") def plot_error(idx_list, error, title=" ", dump=False, y_min=None, y_max=None): fig1, ax1 = plt.subplots() ax1.scatter(idx_list, error, c='k') ax1.set_title(title) if y_min is not None and y_max is not None: ax1.set_ylim((y_min, y_max)) if dump: fig1.savefig(title + ".png") def integrate(lst): total = 0 for v in lst: total += v return total def main(fname1, fname2, display_integration=False, fname3 = None): print(fname1, fname2, fname3) f1 = open(fname1, 'r') f2 = open(fname2, 'r') if fname3 is not None: f3 = open(fname3, 'r') idx1, time1, x1, y1, z1, roll1, pitch1, yaw1 = get_data(f1) idx2, time2, x2, y2, z2, roll2, pitch2, yaw2 = get_data(f2) if fname3 is not None: idx3, time3, x3, y3, z3, roll3, pitch3, yaw3 = get_data(f3) error = get_eucld_error(x1, x2, y1, y2, z1, z2) idx_x = copy.deepcopy(idx1) idx_y = copy.deepcopy(idx1) idx_z = copy.deepcopy(idx1) idx_error = copy.deepcopy(idx1) # i = 0 # while i < len(x1): # x1, x2, idx_x, i = check_val(x1, x2, idx_x, i, 100.0, -100.0) # i = 0 # while i < len(y1): # y1, y2, idx_y, i = check_val(y1, y2, idx_y, i, 100.0, -100.0) # i = 0 # while i < len(z1): # z1, z2, idx_z, i = check_val(z1, z2, idx_z, i, 100.0, -100.0) # i = 0 # while i < len(error): # error, idx_error, i = check_error_val(error, # idx_error, i, 100.0, -100.0) if display_integration: print('X') print(integrate(x1), integrate(x2)) print('Y') print(integrate(y1), integrate(y2)) print('Z') print(integrate(z1), integrate(z2)) print('Error') print(integrate(error)/len(error)) plot(idx_x, x1, x2, v3=x3, title="x", label1=fname1.split('/')[-1].replace('.txt', ''), label2=fname2.split('/')[-1].replace('.txt', ''), label3=fname3.split('/')[-1].replace('.txt', ''), dump=True) plot(idx_y, y1, y2, v3=y3, title="y", label1=fname1.split('/')[-1].replace('.txt', ''), label2=fname2.split('/')[-1].replace('.txt', ''), label3=fname3.split('/')[-1].replace('.txt', ''), dump=True) plot(idx_z, z1, z2, v3=z3, title="z", label1=fname1.split('/')[-1].replace('.txt', ''), label2=fname2.split('/')[-1].replace('.txt', ''), label3=fname3.split('/')[-1].replace('.txt', ''), dump=True) plot_error(idx_error, error) plt.show() if __name__ == '__main__': parser = argparse.ArgumentParser('Display twist') parser.add_argument('file1') parser.add_argument('file2') parser.add_argument('--file3') parser.add_argument('--show_final_pose', type=bool, default=False) args = parser.parse_args() main(args.file1, args.file2, args.show_final_pose, fname3=args.file3)
28.175141
76
0.548626
import matplotlib.pyplot as plt import copy import numpy as np import argparse def get_eucld_error(x1, x2, y1, y2, z1, z2): error = [] for i in range(len(x1)): p1 = np.array([x1[i], y1[i], z1[i]]) p2 = np.array([x2[i], y2[i], z2[i]]) error.append(float(np.sum(np.subtract(p1, p2)))) return error def get_data(f, ignore_count=[]): count = 0 idx = [] time = [] x = [] y = [] z = [] roll = [] pitch = [] yaw = [] for line in f: idx.append(count) count += 1 time.append(line.split(',')[0]) x.append(float(line.split(',')[1])) y.append(float(line.split(',')[2])) z.append(float(line.split(',')[3])) roll.append(float(line.split(',')[4])) pitch.append(float(line.split(',')[5])) yaw.append(float(line.split(',')[6])) return idx, time, x, y, z, roll, pitch, yaw def check_val(l1, l2, idx, ind, max_val, min_val): if l1[ind] > max_val or l2[ind] > max_val: l1.pop(ind) l2.pop(ind) idx.pop(ind) elif l1[ind] < min_val or l2[ind] < min_val: l1.pop(ind) l2.pop(ind) idx.pop(ind) else: ind += 1 return l1, l2, idx, ind def check_error_val(error, idx, ind, max_val, min_val): if error[ind] > max_val: error.pop(ind) idx.pop(ind) elif error[ind] < min_val: error.pop(ind) idx.pop(ind) else: ind += 1 return error, idx, ind def plot(idx_list, v1, v2, v3=None, title=" ", label1="1", label2="2", label3="3", dump=False, y_min=None, y_max=None): fig1, ax1 = plt.subplots() ax1.scatter(idx_list, v1, c='k', label=label1) ax1.scatter(idx_list, v2, c='g', label=label2) if v3 is not None: ax1.scatter(idx_list, v3, c='b', label=label3) ax1.set_title(title) if y_min is not None and y_max is not None: ax1.set_ylim((y_min, y_max)) ax1.legend() if dump: fig1.savefig(title + ".png") def plot_error(idx_list, error, title=" ", dump=False, y_min=None, y_max=None): fig1, ax1 = plt.subplots() ax1.scatter(idx_list, error, c='k') ax1.set_title(title) if y_min is not None and y_max is not None: ax1.set_ylim((y_min, y_max)) if dump: fig1.savefig(title + ".png") def integrate(lst): total = 0 for v in lst: total += v return total def main(fname1, fname2, display_integration=False, fname3 = None): print(fname1, fname2, fname3) f1 = open(fname1, 'r') f2 = open(fname2, 'r') if fname3 is not None: f3 = open(fname3, 'r') idx1, time1, x1, y1, z1, roll1, pitch1, yaw1 = get_data(f1) idx2, time2, x2, y2, z2, roll2, pitch2, yaw2 = get_data(f2) if fname3 is not None: idx3, time3, x3, y3, z3, roll3, pitch3, yaw3 = get_data(f3) error = get_eucld_error(x1, x2, y1, y2, z1, z2) idx_x = copy.deepcopy(idx1) idx_y = copy.deepcopy(idx1) idx_z = copy.deepcopy(idx1) idx_error = copy.deepcopy(idx1) if display_integration: print('X') print(integrate(x1), integrate(x2)) print('Y') print(integrate(y1), integrate(y2)) print('Z') print(integrate(z1), integrate(z2)) print('Error') print(integrate(error)/len(error)) plot(idx_x, x1, x2, v3=x3, title="x", label1=fname1.split('/')[-1].replace('.txt', ''), label2=fname2.split('/')[-1].replace('.txt', ''), label3=fname3.split('/')[-1].replace('.txt', ''), dump=True) plot(idx_y, y1, y2, v3=y3, title="y", label1=fname1.split('/')[-1].replace('.txt', ''), label2=fname2.split('/')[-1].replace('.txt', ''), label3=fname3.split('/')[-1].replace('.txt', ''), dump=True) plot(idx_z, z1, z2, v3=z3, title="z", label1=fname1.split('/')[-1].replace('.txt', ''), label2=fname2.split('/')[-1].replace('.txt', ''), label3=fname3.split('/')[-1].replace('.txt', ''), dump=True) plot_error(idx_error, error) plt.show() if __name__ == '__main__': parser = argparse.ArgumentParser('Display twist') parser.add_argument('file1') parser.add_argument('file2') parser.add_argument('--file3') parser.add_argument('--show_final_pose', type=bool, default=False) args = parser.parse_args() main(args.file1, args.file2, args.show_final_pose, fname3=args.file3)
true
true
1c33fdc9d99aa7d333404785340880afd23b60d3
3,678
py
Python
models/plain_lstm.py
TalkToTheGAN/RelaxTextGAN
6d0846392c8a1267eaa103dd70492cb80024079e
[ "Apache-2.0" ]
3
2019-05-30T03:40:38.000Z
2021-04-12T06:50:41.000Z
models/plain_lstm.py
TalkToTheGAN/RelaxTextGAN
6d0846392c8a1267eaa103dd70492cb80024079e
[ "Apache-2.0" ]
1
2020-06-15T12:27:56.000Z
2020-06-15T12:27:56.000Z
models/plain_lstm.py
TalkToTheGAN/RelaxTextGAN
6d0846392c8a1267eaa103dd70492cb80024079e
[ "Apache-2.0" ]
null
null
null
import os import random import numpy as np import torch import torch.nn as nn import torch.nn.functional as F from torch.autograd import Variable class PlainLSTM(nn.Module): """PlainLSTM """ def __init__(self, vocab_size, emb_dim, hidden_dim, use_cuda=False): super(PlainLSTM, self).__init__() self.vocab_size = vocab_size self.emb_dim = emb_dim self.hidden_dim = hidden_dim self.use_cuda = use_cuda self.emb = nn.Embedding(vocab_size, emb_dim) self.lstm = nn.LSTM(emb_dim, hidden_dim, batch_first=True) self.lin = nn.Linear(hidden_dim, vocab_size) self.log_softmax = nn.LogSoftmax(dim=1) self.init_params() def forward(self, x): emb = self.emb(x) # emb dim: (batch_size, seq_len, emb_dim) h0, c0 = self.init_hidden(x.size(0)) # input to lstm dimensions: (batch, seq_len, input_size) output, (h, c) = self.lstm(emb, (h0, c0)) # output dim = (batch_size x seq_len, x hidden_dim) seq_len = output.size()[1] batch_size = output.size()[0] pred = self.log_softmax(self.lin(output.contiguous().view(-1, self.hidden_dim))) pred = pred.view(batch_size, seq_len, self.vocab_size) return pred def step(self, x, h, c): """ Args: x: (batch_size, 1), sequence of tokens generated by lstm h: (1, batch_size, hidden_dim), lstm hidden state c: (1, batch_size, hidden_dim), lstm cell state """ emb = self.emb(x) output, (h, c) = self.lstm(emb, (h, c)) pred = F.softmax(self.lin(output.view(-1, self.hidden_dim)), dim=1) return pred, h, c def init_hidden(self, batch_size): h = Variable(torch.zeros((1, batch_size, self.hidden_dim))) c = Variable(torch.zeros((1, batch_size, self.hidden_dim))) if self.use_cuda: h, c = h.cuda(), c.cuda() return h, c def init_params(self): for param in self.parameters(): param.data.uniform_(-0.05, 0.05) def sample(self, batch_size, seq_len, x=None): res = [] flag = False # whether sample from zero if x is None: flag = True if flag: x = Variable(torch.zeros((batch_size, 1)).long()) if self.use_cuda: x = x.cuda() h, c = self.init_hidden(batch_size) samples = [] if flag: for i in range(seq_len): output, h, c = self.step(x, h, c) x = output.multinomial(1) samples.append(x) else: given_len = x.size(1) lis = x.chunk(x.size(1), dim=1) for i in range(given_len): output, h, c = self.step(lis[i], h, c) samples.append(lis[i]) x = output.multinomial(1) for i in range(given_len, seq_len): samples.append(x) output, h, c = self.step(x, h, c) x = output.multinomial(1) output = torch.cat(samples, dim=1) return output def test_sample(self, batch_size, seq_len, vocab_size): big_list = [] x = Variable(torch.zeros((batch_size, 1)).long()) h, c = self.init_hidden(batch_size) for i in range(seq_len): output, h, c = self.step(x, h, c) g = Variable(torch.zeros(output.size())) # print(g.size()) g.data[:,0] = 1 # R*pij # output.backward(g) big_list.append((output, g)) for p, g in big_list: p.backward(g) return output
32.263158
104
0.54894
import os import random import numpy as np import torch import torch.nn as nn import torch.nn.functional as F from torch.autograd import Variable class PlainLSTM(nn.Module): def __init__(self, vocab_size, emb_dim, hidden_dim, use_cuda=False): super(PlainLSTM, self).__init__() self.vocab_size = vocab_size self.emb_dim = emb_dim self.hidden_dim = hidden_dim self.use_cuda = use_cuda self.emb = nn.Embedding(vocab_size, emb_dim) self.lstm = nn.LSTM(emb_dim, hidden_dim, batch_first=True) self.lin = nn.Linear(hidden_dim, vocab_size) self.log_softmax = nn.LogSoftmax(dim=1) self.init_params() def forward(self, x): emb = self.emb(x) h0, c0 = self.init_hidden(x.size(0)) output, (h, c) = self.lstm(emb, (h0, c0)) seq_len = output.size()[1] batch_size = output.size()[0] pred = self.log_softmax(self.lin(output.contiguous().view(-1, self.hidden_dim))) pred = pred.view(batch_size, seq_len, self.vocab_size) return pred def step(self, x, h, c): emb = self.emb(x) output, (h, c) = self.lstm(emb, (h, c)) pred = F.softmax(self.lin(output.view(-1, self.hidden_dim)), dim=1) return pred, h, c def init_hidden(self, batch_size): h = Variable(torch.zeros((1, batch_size, self.hidden_dim))) c = Variable(torch.zeros((1, batch_size, self.hidden_dim))) if self.use_cuda: h, c = h.cuda(), c.cuda() return h, c def init_params(self): for param in self.parameters(): param.data.uniform_(-0.05, 0.05) def sample(self, batch_size, seq_len, x=None): res = [] flag = False if x is None: flag = True if flag: x = Variable(torch.zeros((batch_size, 1)).long()) if self.use_cuda: x = x.cuda() h, c = self.init_hidden(batch_size) samples = [] if flag: for i in range(seq_len): output, h, c = self.step(x, h, c) x = output.multinomial(1) samples.append(x) else: given_len = x.size(1) lis = x.chunk(x.size(1), dim=1) for i in range(given_len): output, h, c = self.step(lis[i], h, c) samples.append(lis[i]) x = output.multinomial(1) for i in range(given_len, seq_len): samples.append(x) output, h, c = self.step(x, h, c) x = output.multinomial(1) output = torch.cat(samples, dim=1) return output def test_sample(self, batch_size, seq_len, vocab_size): big_list = [] x = Variable(torch.zeros((batch_size, 1)).long()) h, c = self.init_hidden(batch_size) for i in range(seq_len): output, h, c = self.step(x, h, c) g = Variable(torch.zeros(output.size())) g.data[:,0] = 1 big_list.append((output, g)) for p, g in big_list: p.backward(g) return output
true
true
1c33fe2b2b38a27cad60e2b1413c587bdf493fa1
317
py
Python
venv/Lib/site-packages/nipype/interfaces/minc/testdata.py
richung99/digitizePlots
6b408c820660a415a289726e3223e8f558d3e18b
[ "MIT" ]
585
2015-01-12T16:06:47.000Z
2022-03-26T14:51:08.000Z
nipype/interfaces/minc/testdata.py
tamires-consulting/nipype
b7879d75a63b6500b2e7d2c3eba5aa7670339274
[ "Apache-2.0" ]
2,329
2015-01-01T09:56:41.000Z
2022-03-30T14:24:49.000Z
nipype/interfaces/minc/testdata.py
tamires-consulting/nipype
b7879d75a63b6500b2e7d2c3eba5aa7670339274
[ "Apache-2.0" ]
487
2015-01-20T01:04:52.000Z
2022-03-21T21:22:47.000Z
# -*- coding: utf-8 -*- import os from ...testing import example_data minc2Dfile = example_data("minc_test_2D_00.mnc") minc3Dfile = example_data("minc_test_3D_00.mnc") nlp_config = example_data("minc_nlp.conf") def nonempty_minc_data(i, shape="2D"): return example_data("minc_test_%s_%.2d.mnc" % (shape, i))
22.642857
61
0.728707
import os from ...testing import example_data minc2Dfile = example_data("minc_test_2D_00.mnc") minc3Dfile = example_data("minc_test_3D_00.mnc") nlp_config = example_data("minc_nlp.conf") def nonempty_minc_data(i, shape="2D"): return example_data("minc_test_%s_%.2d.mnc" % (shape, i))
true
true
1c33fe6b373149f67b58af2338d67477648d458f
6,134
py
Python
server_normal_Flask_beautiful/routes/routes_user.py
KiwiShow/PythonWeb
a489bc2ab16f06f7cc4524bab6b45b2653bfb1bd
[ "MIT" ]
7
2018-02-24T13:41:21.000Z
2022-02-06T04:59:13.000Z
server_normal_Flask_beautiful/routes/routes_user.py
KiwiShow/PythonWeb
a489bc2ab16f06f7cc4524bab6b45b2653bfb1bd
[ "MIT" ]
6
2018-02-25T11:50:42.000Z
2021-12-13T19:55:13.000Z
server_normal_Flask_beautiful/routes/routes_user.py
KiwiShow/PythonWeb
a489bc2ab16f06f7cc4524bab6b45b2653bfb1bd
[ "MIT" ]
1
2018-03-01T02:43:15.000Z
2018-03-01T02:43:15.000Z
from utils import log from config import gg, image_file_dir from routes import ( current_user, login_required, ) from flask import ( request, Blueprint, render_template, redirect, url_for, session, make_response, send_from_directory, abort, flash, ) from models.user import User from models.board import Board from models.mail import Mail main = Blueprint('user', __name__) @main.route('/', methods=['GET']) def index(): return render_template('blog/blog_index.html') @main.route('/admin', methods=['GET']) @login_required def admin(): """ 只有用户id为1的用户有权限 :return: 返回所有用户的信息 """ user = current_user() User.check_admin() print('from admin before', gg.csrf_tokens) gg.reset_value(user.id) print('from admin after', gg.csrf_tokens) return render_template('user/admin.html', token=gg.token[user.id], mails=Mail.find_all(), user=user, users=User.find_all(), boards=Board.find_all()) @main.route('/admin/edit/<int:user_id>', methods=['GET']) @login_required def admin_edit(user_id): """ 只有用户id为1的用户有权限,输入需要修改的id和password :return: 返回修改过的所有用户的信息 """ user = current_user() if User.check_token(): User.check_admin() u = User.find(user_id) return render_template('user/admin_edit.html', token=gg.token[user.id], user=user, u=u) @main.route('/admin/update', methods=['POST']) @login_required def admin_update(): """ 只有用户id为1的用户有权限,输入需要修改的id和password :return: 返回修改过的所有用户的信息 """ if User.check_token(): User.check_admin() form = request.form User.update(form) return redirect(url_for('.admin')) # 增加一个register的路由函数 @main.route('/admin/register', methods=['POST']) def admin_register(): """ 允许GET是因为在地址栏输入地址转到register页面需要 POST是因为在register页面输入账号密码点击register按钮需要 主要的bug是转到register页面和register页面都都是同一个路由函数 :return: 返回register页面,并显示所有用户信息 """ if User.check_token(): User.check_admin() form = request.form if User.validate_register(form): return redirect(url_for('.admin')) @main.route('/admin/delete/<int:user_id>') @login_required def user_delete(user_id): if User.check_token(): User.check_admin() User.remove(user_id) return redirect(url_for('.admin')) # 所有用户上传头像,先存在本地得到路径之后上传至七牛云,并删除本地图片 @main.route('/add_image', methods=['POST']) @login_required def add_img(): user = current_user() if User.check_token(): file = request.files['avatar'] user.save_and_up(file) return redirect(url_for('.user_setting', id=user.id, token=gg.token[user.id])) # web后端上传头像,后续可以改成Nginx+图床 # 本地只有default.png一张图片 @main.route('/uploads/<filename>') @login_required def uploads(filename): return send_from_directory(image_file_dir, filename) # 在知乎console输入 # var c = document.cookie # var img = `<img src='http://localhost:4000/hack?cookie=${c}'>` # document.body.innerHTML += img @main.route('/hack') def hack(): # xss 攻击的后台 cookie = request.args.get('cookie') print('cookie', cookie) # 增加一个可以看到任意user的路由函数 # 不需要check token,CRUD中除了查不需要验证token,但是需要传递token # 需要传递 u: 我想要看的用户 和 user: current_user() @main.route('/user/<int:id>') # @login_required def user_detail(id): user = current_user() u = User.find(id) if u is None: abort(404) if user is not None: # 保证每次调用index函数时清空gg,保证每次调用index函数时都有新的token可用 print('from profile before', gg.csrf_tokens) gg.reset_value(user.id) print('from profile after', gg.csrf_tokens) return render_template('user/profile.html', u=u, token=gg.token[user.id], user=user) return render_template('user/profile.html', u=u, user=user) # update方法需要重新写,统一到model父类中 # 增加一个在setting页面update的路由函数 @main.route('/user/update', methods=['POST']) @login_required def user_update(): user = current_user() if User.check_token(): form = request.form user.password_update(form) return redirect(url_for('user.user_setting', id=user.id, token=gg.token[user.id])) # 增加一个去setting页面的路由函数 @main.route('/setting') @login_required def user_setting(): user = current_user() if user is not None: # 保证每次调用index函数时清空gg,保证每次调用index函数时都有新的token可用 print('from setting before', gg.csrf_tokens) gg.reset_value(user.id) print('from setting after', gg.csrf_tokens) return render_template('user/setting.html', user=user, token=gg.token[user.id], bid=-1) # GET 去 登陆 页面, POST 提交表单 @main.route('/login', methods=['GET', 'POST']) def user_login(): form = request.form log('from route_login --> cookies: ', request.cookies) # ImmutableMultiDict([])是什么鬼? if form.get('username', None): if User.validate_login(form): u = User.find_by(username=form.get('username')) print('from signin before', session) session['user_id'] = u.id print('from signin after', session) return redirect(url_for('tweet.index')) else: flash('账号密码输入错误,请核对后再输入') return redirect(url_for('.user_login')) else: return render_template('user/login.html') # GET 去 注册 页面, POST 提交表单 @main.route('/register', methods=['GET', 'POST']) def user_register(): """ 允许GET是因为在地址栏输入地址转到register页面需要 POST是因为在register页面输入账号密码点击register按钮需要 主要的bug是转到register页面和register页面都都是同一个路由函数 :return: 返回register页面,并显示所有用户信息 """ form = request.form if form.get('username', None): if User.validate_register(form): return redirect(url_for('user.user_login')) else: flash('用户名和密码长度必须大于2,请核对后再输入') return redirect(url_for('.user_register')) else: return render_template('user/register.html') @main.route('/signout') def user_signout(): """ 在session中删除当前登录的user_id :return: 返回login页面 """ if User.check_token(): print('from signout before', session) session.pop('user_id') print('from signout after', session) return redirect(url_for('tweet.index'))
27.141593
152
0.662048
from utils import log from config import gg, image_file_dir from routes import ( current_user, login_required, ) from flask import ( request, Blueprint, render_template, redirect, url_for, session, make_response, send_from_directory, abort, flash, ) from models.user import User from models.board import Board from models.mail import Mail main = Blueprint('user', __name__) @main.route('/', methods=['GET']) def index(): return render_template('blog/blog_index.html') @main.route('/admin', methods=['GET']) @login_required def admin(): user = current_user() User.check_admin() print('from admin before', gg.csrf_tokens) gg.reset_value(user.id) print('from admin after', gg.csrf_tokens) return render_template('user/admin.html', token=gg.token[user.id], mails=Mail.find_all(), user=user, users=User.find_all(), boards=Board.find_all()) @main.route('/admin/edit/<int:user_id>', methods=['GET']) @login_required def admin_edit(user_id): user = current_user() if User.check_token(): User.check_admin() u = User.find(user_id) return render_template('user/admin_edit.html', token=gg.token[user.id], user=user, u=u) @main.route('/admin/update', methods=['POST']) @login_required def admin_update(): if User.check_token(): User.check_admin() form = request.form User.update(form) return redirect(url_for('.admin')) @main.route('/admin/register', methods=['POST']) def admin_register(): if User.check_token(): User.check_admin() form = request.form if User.validate_register(form): return redirect(url_for('.admin')) @main.route('/admin/delete/<int:user_id>') @login_required def user_delete(user_id): if User.check_token(): User.check_admin() User.remove(user_id) return redirect(url_for('.admin')) @main.route('/add_image', methods=['POST']) @login_required def add_img(): user = current_user() if User.check_token(): file = request.files['avatar'] user.save_and_up(file) return redirect(url_for('.user_setting', id=user.id, token=gg.token[user.id])) @main.route('/uploads/<filename>') @login_required def uploads(filename): return send_from_directory(image_file_dir, filename) @main.route('/hack') def hack(): cookie = request.args.get('cookie') print('cookie', cookie) @main.route('/user/<int:id>') def user_detail(id): user = current_user() u = User.find(id) if u is None: abort(404) if user is not None: print('from profile before', gg.csrf_tokens) gg.reset_value(user.id) print('from profile after', gg.csrf_tokens) return render_template('user/profile.html', u=u, token=gg.token[user.id], user=user) return render_template('user/profile.html', u=u, user=user) @main.route('/user/update', methods=['POST']) @login_required def user_update(): user = current_user() if User.check_token(): form = request.form user.password_update(form) return redirect(url_for('user.user_setting', id=user.id, token=gg.token[user.id])) @main.route('/setting') @login_required def user_setting(): user = current_user() if user is not None: print('from setting before', gg.csrf_tokens) gg.reset_value(user.id) print('from setting after', gg.csrf_tokens) return render_template('user/setting.html', user=user, token=gg.token[user.id], bid=-1) @main.route('/login', methods=['GET', 'POST']) def user_login(): form = request.form log('from route_login --> cookies: ', request.cookies) if form.get('username', None): if User.validate_login(form): u = User.find_by(username=form.get('username')) print('from signin before', session) session['user_id'] = u.id print('from signin after', session) return redirect(url_for('tweet.index')) else: flash('账号密码输入错误,请核对后再输入') return redirect(url_for('.user_login')) else: return render_template('user/login.html') @main.route('/register', methods=['GET', 'POST']) def user_register(): form = request.form if form.get('username', None): if User.validate_register(form): return redirect(url_for('user.user_login')) else: flash('用户名和密码长度必须大于2,请核对后再输入') return redirect(url_for('.user_register')) else: return render_template('user/register.html') @main.route('/signout') def user_signout(): if User.check_token(): print('from signout before', session) session.pop('user_id') print('from signout after', session) return redirect(url_for('tweet.index'))
true
true
1c33ff10010a98d8a99a1b158c70877e9d59678f
997
py
Python
setup.py
brandonvfx/flask-lambda
29bb0d728037af076019cfbe398e084cd58821bb
[ "Apache-2.0" ]
6
2018-10-16T13:34:26.000Z
2020-06-15T22:20:15.000Z
setup.py
brandonvfx/flask-lambda
29bb0d728037af076019cfbe398e084cd58821bb
[ "Apache-2.0" ]
2
2019-07-08T09:22:25.000Z
2020-12-16T12:47:22.000Z
setup.py
brandonvfx/flask-lambda
29bb0d728037af076019cfbe398e084cd58821bb
[ "Apache-2.0" ]
5
2018-12-20T14:07:14.000Z
2021-05-15T02:14:29.000Z
from setuptools import setup, find_packages with open('README.rst') as f: long_description = f.read() setup( name='flask-lambda-support', version='0.1.5', description='Python 3.6+ module to make Flask compatible with AWS Lambda', long_description=long_description, keywords='flask aws amazon lambda', author='Jochen Van de Velde', author_email='jochen.vandevelde@cloudway.be', url='https://github.com/becloudway/flask-lambda', license='Apache License, Version 2.0', packages=find_packages(), py_modules=['flask_lambda'], install_requires=['Flask>=0.10'], classifiers=[ 'Development Status :: 5 - Production/Stable', 'Programming Language :: Python', 'Environment :: Console', 'Operating System :: POSIX', 'Programming Language :: Python :: 3.6', 'Intended Audience :: Developers', 'Natural Language :: English', 'License :: OSI Approved :: Apache Software License', ] )
32.16129
78
0.652959
from setuptools import setup, find_packages with open('README.rst') as f: long_description = f.read() setup( name='flask-lambda-support', version='0.1.5', description='Python 3.6+ module to make Flask compatible with AWS Lambda', long_description=long_description, keywords='flask aws amazon lambda', author='Jochen Van de Velde', author_email='jochen.vandevelde@cloudway.be', url='https://github.com/becloudway/flask-lambda', license='Apache License, Version 2.0', packages=find_packages(), py_modules=['flask_lambda'], install_requires=['Flask>=0.10'], classifiers=[ 'Development Status :: 5 - Production/Stable', 'Programming Language :: Python', 'Environment :: Console', 'Operating System :: POSIX', 'Programming Language :: Python :: 3.6', 'Intended Audience :: Developers', 'Natural Language :: English', 'License :: OSI Approved :: Apache Software License', ] )
true
true
1c33ff237e9a5bed9d42985f51dcd2d5a656d2e9
174
py
Python
Unit 2/2.8/2.8.4 Beaded Bracelet.py
shashwat73/cse
60e49307e57105cf9916c7329f53f891c5e81fdb
[ "MIT" ]
1
2021-04-08T14:02:49.000Z
2021-04-08T14:02:49.000Z
Unit 2/2.8/2.8.4 Beaded Bracelet.py
shashwat73/cse
60e49307e57105cf9916c7329f53f891c5e81fdb
[ "MIT" ]
null
null
null
Unit 2/2.8/2.8.4 Beaded Bracelet.py
shashwat73/cse
60e49307e57105cf9916c7329f53f891c5e81fdb
[ "MIT" ]
null
null
null
speed(0) def make_bead(): forward(100) pendown() circle(10) penup() backward(100) penup() for i in range(36): make_bead() left(10)
12.428571
20
0.528736
speed(0) def make_bead(): forward(100) pendown() circle(10) penup() backward(100) penup() for i in range(36): make_bead() left(10)
true
true
1c33ffe24ec1e81536cab928d5fd3f8679749726
6,856
py
Python
cardea/fhir/Media.py
sarahmish/Cardea
85c4246c12178e6d1b9cc12eb39c264f3c20f3e9
[ "MIT" ]
69
2021-01-28T22:25:10.000Z
2022-03-15T00:23:33.000Z
cardea/fhir/Media.py
sarahmish/Cardea
85c4246c12178e6d1b9cc12eb39c264f3c20f3e9
[ "MIT" ]
30
2018-08-29T12:45:23.000Z
2019-12-24T11:08:12.000Z
cardea/fhir/Media.py
sarahmish/Cardea
85c4246c12178e6d1b9cc12eb39c264f3c20f3e9
[ "MIT" ]
14
2021-03-24T01:21:25.000Z
2022-03-12T11:53:40.000Z
from .fhirbase import fhirbase class Media(fhirbase): """ A photo, video, or audio recording acquired or used in healthcare. The actual content may be inline or provided by direct reference. Args: resourceType: This is a Media resource identifier: Identifiers associated with the image - these may include identifiers for the image itself, identifiers for the context of its collection (e.g. series ids) and context ids such as accession numbers or other workflow identifiers. basedOn: A procedure that is fulfilled in whole or in part by the creation of this media. type: Whether the media is a photo (still image), an audio recording, or a video recording. subtype: Details of the type of the media - usually, how it was acquired (what type of device). If images sourced from a DICOM system, are wrapped in a Media resource, then this is the modality. view: The name of the imaging view e.g. Lateral or Antero-posterior (AP). subject: Who/What this Media is a record of. context: The encounter or episode of care that establishes the context for this media. occurrenceDateTime: The date and time(s) at which the media was collected. occurrencePeriod: The date and time(s) at which the media was collected. operator: The person who administered the collection of the image. reasonCode: Describes why the event occurred in coded or textual form. bodySite: Indicates the site on the subject's body where the media was collected (i.e. the target site). device: The device used to collect the media. height: Height of the image in pixels (photo/video). width: Width of the image in pixels (photo/video). frames: The number of frames in a photo. This is used with a multi-page fax, or an imaging acquisition context that takes multiple slices in a single image, or an animated gif. If there is more than one frame, this SHALL have a value in order to alert interface software that a multi-frame capable rendering widget is required. duration: The duration of the recording in seconds - for audio and video. content: The actual content of the media - inline or by direct reference to the media source file. note: Comments made about the media by the performer, subject or other participants. """ __name__ = 'Media' def __init__(self, dict_values=None): self.resourceType = 'Media' # type: str # possible values: Media self.basedOn = None # type: list # reference to Reference: identifier self.type = None # type: str # possible values: photo, video, audio self.subtype = None # reference to CodeableConcept self.view = None # reference to CodeableConcept self.subject = None # reference to Reference: identifier self.context = None # reference to Reference: identifier self.occurrenceDateTime = None # type: str self.occurrencePeriod = None # reference to Period self.operator = None # reference to Reference: identifier self.reasonCode = None # type: list # reference to CodeableConcept self.bodySite = None # reference to CodeableConcept self.device = None # reference to Reference: identifier self.height = None # type: int self.width = None # type: int self.frames = None # type: int self.duration = None # type: int self.content = None # reference to Attachment self.note = None # type: list # reference to Annotation self.identifier = None # type: list # reference to Identifier if dict_values: self.set_attributes(dict_values) self.assert_type() def assert_type(self): if self.type is not None: for value in self.type: if value is not None and value.lower() not in [ 'photo', 'video', 'audio']: raise ValueError('"{}" does not match possible values: {}'.format( value, 'photo, video, audio')) def get_relationships(self): return [ {'parent_entity': 'Period', 'parent_variable': 'object_id', 'child_entity': 'Media', 'child_variable': 'occurrencePeriod'}, {'parent_entity': 'Annotation', 'parent_variable': 'object_id', 'child_entity': 'Media', 'child_variable': 'note'}, {'parent_entity': 'CodeableConcept', 'parent_variable': 'object_id', 'child_entity': 'Media', 'child_variable': 'subtype'}, {'parent_entity': 'Reference', 'parent_variable': 'identifier', 'child_entity': 'Media', 'child_variable': 'subject'}, {'parent_entity': 'Attachment', 'parent_variable': 'object_id', 'child_entity': 'Media', 'child_variable': 'content'}, {'parent_entity': 'CodeableConcept', 'parent_variable': 'object_id', 'child_entity': 'Media', 'child_variable': 'bodySite'}, {'parent_entity': 'Identifier', 'parent_variable': 'object_id', 'child_entity': 'Media', 'child_variable': 'identifier'}, {'parent_entity': 'CodeableConcept', 'parent_variable': 'object_id', 'child_entity': 'Media', 'child_variable': 'reasonCode'}, {'parent_entity': 'Reference', 'parent_variable': 'identifier', 'child_entity': 'Media', 'child_variable': 'operator'}, {'parent_entity': 'Reference', 'parent_variable': 'identifier', 'child_entity': 'Media', 'child_variable': 'basedOn'}, {'parent_entity': 'Reference', 'parent_variable': 'identifier', 'child_entity': 'Media', 'child_variable': 'context'}, {'parent_entity': 'Reference', 'parent_variable': 'identifier', 'child_entity': 'Media', 'child_variable': 'device'}, {'parent_entity': 'CodeableConcept', 'parent_variable': 'object_id', 'child_entity': 'Media', 'child_variable': 'view'}, ]
34.109453
86
0.575117
from .fhirbase import fhirbase class Media(fhirbase): __name__ = 'Media' def __init__(self, dict_values=None): self.resourceType = 'Media' self.basedOn = None self.type = None self.subtype = None self.view = None self.subject = None self.context = None self.occurrenceDateTime = None self.occurrencePeriod = None self.operator = None self.reasonCode = None self.bodySite = None self.device = None self.height = None self.width = None self.frames = None self.duration = None self.content = None self.note = None self.identifier = None if dict_values: self.set_attributes(dict_values) self.assert_type() def assert_type(self): if self.type is not None: for value in self.type: if value is not None and value.lower() not in [ 'photo', 'video', 'audio']: raise ValueError('"{}" does not match possible values: {}'.format( value, 'photo, video, audio')) def get_relationships(self): return [ {'parent_entity': 'Period', 'parent_variable': 'object_id', 'child_entity': 'Media', 'child_variable': 'occurrencePeriod'}, {'parent_entity': 'Annotation', 'parent_variable': 'object_id', 'child_entity': 'Media', 'child_variable': 'note'}, {'parent_entity': 'CodeableConcept', 'parent_variable': 'object_id', 'child_entity': 'Media', 'child_variable': 'subtype'}, {'parent_entity': 'Reference', 'parent_variable': 'identifier', 'child_entity': 'Media', 'child_variable': 'subject'}, {'parent_entity': 'Attachment', 'parent_variable': 'object_id', 'child_entity': 'Media', 'child_variable': 'content'}, {'parent_entity': 'CodeableConcept', 'parent_variable': 'object_id', 'child_entity': 'Media', 'child_variable': 'bodySite'}, {'parent_entity': 'Identifier', 'parent_variable': 'object_id', 'child_entity': 'Media', 'child_variable': 'identifier'}, {'parent_entity': 'CodeableConcept', 'parent_variable': 'object_id', 'child_entity': 'Media', 'child_variable': 'reasonCode'}, {'parent_entity': 'Reference', 'parent_variable': 'identifier', 'child_entity': 'Media', 'child_variable': 'operator'}, {'parent_entity': 'Reference', 'parent_variable': 'identifier', 'child_entity': 'Media', 'child_variable': 'basedOn'}, {'parent_entity': 'Reference', 'parent_variable': 'identifier', 'child_entity': 'Media', 'child_variable': 'context'}, {'parent_entity': 'Reference', 'parent_variable': 'identifier', 'child_entity': 'Media', 'child_variable': 'device'}, {'parent_entity': 'CodeableConcept', 'parent_variable': 'object_id', 'child_entity': 'Media', 'child_variable': 'view'}, ]
true
true
1c340161e4b6f7a3fc08face097e2d2cd16fb14c
735
py
Python
chap03/author-manager/src/api/config/config.py
matadorchw/rest_flask
b5b643d72e63e654f2d893621158e2e5db870b15
[ "MIT" ]
2
2020-10-21T14:04:42.000Z
2020-10-21T14:05:01.000Z
chap03/author-manager/src/api/config/config.py
matadorchw/rest_flask
b5b643d72e63e654f2d893621158e2e5db870b15
[ "MIT" ]
null
null
null
chap03/author-manager/src/api/config/config.py
matadorchw/rest_flask
b5b643d72e63e654f2d893621158e2e5db870b15
[ "MIT" ]
null
null
null
class Config(object): DEBUG = False TESTING = False SQLALCHEMY_TRACK_MODIFICATIONS = False class ProductionConfig(Config): SQLALCHEMY_DATABASE_URI = '' class DevelopmentConfig(Config): DEBUG = True SQLALCHEMY_DATABASE_URI = 'mysql+pymysql://root:123456@localhost:3306/flaskrest' SECRET_KEY = 'sunshine' SECURITY_PASSWORD_SALT = 'dawn' SQLALCHEMY_ECHO = False MAIL_DEFAULT_SENDER = 'menglj@we-wins.com' MAIL_SERVER = 'smtp.263.net' MAIL_PORT = 25 MAIL_USE_TLS = True MAIL_USERNAME = 'menglj@we-wins.com' MAIL_PASSWORD = 'Lte5563' UPLOAD_FOLDER = 'images' class TestingConfig(Config): TESTING = True SQLALCHEMY_DATABASE_URI = '' SQLALCHEMY_ECHO = False
22.96875
84
0.706122
class Config(object): DEBUG = False TESTING = False SQLALCHEMY_TRACK_MODIFICATIONS = False class ProductionConfig(Config): SQLALCHEMY_DATABASE_URI = '' class DevelopmentConfig(Config): DEBUG = True SQLALCHEMY_DATABASE_URI = 'mysql+pymysql://root:123456@localhost:3306/flaskrest' SECRET_KEY = 'sunshine' SECURITY_PASSWORD_SALT = 'dawn' SQLALCHEMY_ECHO = False MAIL_DEFAULT_SENDER = 'menglj@we-wins.com' MAIL_SERVER = 'smtp.263.net' MAIL_PORT = 25 MAIL_USE_TLS = True MAIL_USERNAME = 'menglj@we-wins.com' MAIL_PASSWORD = 'Lte5563' UPLOAD_FOLDER = 'images' class TestingConfig(Config): TESTING = True SQLALCHEMY_DATABASE_URI = '' SQLALCHEMY_ECHO = False
true
true
1c3402eecc1efe7833e69b853785cb075e895c8e
132
py
Python
blogmods/models/__init__.py
stonescar/multi-user-blog
a402dafde1f7d94031129638aa072ce39223e80e
[ "MIT" ]
null
null
null
blogmods/models/__init__.py
stonescar/multi-user-blog
a402dafde1f7d94031129638aa072ce39223e80e
[ "MIT" ]
null
null
null
blogmods/models/__init__.py
stonescar/multi-user-blog
a402dafde1f7d94031129638aa072ce39223e80e
[ "MIT" ]
null
null
null
from database import Database from users import Users from posts import Posts from comments import Comments from votes import Votes
22
29
0.848485
from database import Database from users import Users from posts import Posts from comments import Comments from votes import Votes
true
true
1c3404f181a064281760dfa67f303c16422cd5c3
529
py
Python
commands/upgrader/commands/blockdata.py
Red-Teapot/mc-commandblock-1.13-update
64106e1ecb5adca2aff1eeb3a1fcc11486940000
[ "MIT" ]
1
2020-07-27T16:53:26.000Z
2020-07-27T16:53:26.000Z
commands/upgrader/commands/blockdata.py
Red-Teapot/mc-commandblock-1.13-update
64106e1ecb5adca2aff1eeb3a1fcc11486940000
[ "MIT" ]
5
2019-01-02T14:21:32.000Z
2019-07-07T05:39:39.000Z
commands/upgrader/commands/blockdata.py
Red-Teapot/mc-commandblock-1.13-update
64106e1ecb5adca2aff1eeb3a1fcc11486940000
[ "MIT" ]
null
null
null
from commands.pre_1_13.cmdex import CMDEx from commands.upgrader.utils import command_upgrader_base CMDEXS = [ CMDEx('blockdata {coordinate:x} {coordinate:y} {coordinate:z} {nbtstr:nbt}'), ] def __upgrade(order, props): result = 'data merge block ' result += str(props['x']) + ' ' + str(props['y']) + ' ' + str(props['z']) + ' ' # TODO Maybe upgrade NBT stuff? result += str(props['nbt']) return result def upgrade(command: str): return command_upgrader_base.upgrade(CMDEXS, command, __upgrade)
26.45
83
0.669187
from commands.pre_1_13.cmdex import CMDEx from commands.upgrader.utils import command_upgrader_base CMDEXS = [ CMDEx('blockdata {coordinate:x} {coordinate:y} {coordinate:z} {nbtstr:nbt}'), ] def __upgrade(order, props): result = 'data merge block ' result += str(props['x']) + ' ' + str(props['y']) + ' ' + str(props['z']) + ' ' result += str(props['nbt']) return result def upgrade(command: str): return command_upgrader_base.upgrade(CMDEXS, command, __upgrade)
true
true
1c3404f28196271ef1b09445916e0d69195037e1
16,628
py
Python
utils.py
creol-io/machine-manager
01108f0c26c15f515c1d9d3361f1c1a27c03d8ab
[ "Apache-2.0" ]
null
null
null
utils.py
creol-io/machine-manager
01108f0c26c15f515c1d9d3361f1c1a27c03d8ab
[ "Apache-2.0" ]
null
null
null
utils.py
creol-io/machine-manager
01108f0c26c15f515c1d9d3361f1c1a27c03d8ab
[ "Apache-2.0" ]
null
null
null
""" Copyright 2019 Cartesi Pte. Ltd. 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 subprocess import logging import logging.config import logging.handlers import traceback import grpc import json import time import os import cartesi_machine_pb2_grpc import cartesi_machine_pb2 import machine_manager_pb2 LOG_FILENAME = "manager.log" RUN_CYCLES_BATCH_SIZE = 10**7 UNIX = "unix" TCP = "tcp" SOCKET_TYPE = UNIX def get_new_logger(name): return logging.getLogger(name) def configure_log(logger): logger.setLevel(logging.DEBUG) #Setting format formatter = logging.Formatter('%(asctime)s %(thread)d %(levelname)-s %(name)s %(lineno)s - %(funcName)s: %(message)s') #File rotation log handler rotating_file_handler = logging.handlers.RotatingFileHandler( LOG_FILENAME, maxBytes=2**20, backupCount=5) rotating_file_handler.setFormatter(formatter) rotating_file_handler.setLevel(logging.DEBUG) #Stream log handler stream_handler = logging.StreamHandler() stream_handler.setLevel(logging.DEBUG) stream_handler.setFormatter(formatter) logger.addHandler(rotating_file_handler) logger.addHandler(stream_handler) return logger def new_cartesi_machine_server(session_id, manager_address): LOGGER.info("Creating a cartesi machine server with session_id '{}'".format(session_id)) cmd_line = ["/opt/cartesi/bin/cartesi-machine-server", "-t", SOCKET_TYPE, "-s", session_id, "-m", manager_address] LOGGER.debug("Executing {}".format(" ".join(cmd_line))) proc = None try: proc = subprocess.Popen(cmd_line, stderr=subprocess.PIPE, stdout=subprocess.PIPE, env=os.environ) out, err = proc.communicate() LOGGER.debug("\nStdout:\n{}\nStderr:\n{}".format(out.decode("utf-8"), err.decode("utf-8"))) except Exception as e: err_msg = "Cartesi machine server creation process failed for session_id '{}'".format(session_id) LOGGER.info(err_msg) if (proc): out, err = proc.communicate() LOGGER.debug("\nStdout:\n{}\nStderr:\n{}".format(out.decode("utf-8"), err.decode("utf-8"))) raise CartesiMachineServerException(err_msg) if (proc.returncode == 0): LOGGER.info("Cartesi machine server creation process returned for session_id '{}'".format(session_id)) LOGGER.debug("\nStdout:\n{}\nStderr:\n{}".format(out.decode("utf-8"), err.decode("utf-8"))) else: err_msg = "Cartesi machine server creation process returned non-zero code for session_id '{}'".format(session_id) LOGGER.error(err_msg) LOGGER.error("\nStdout:\n{}\nStderr:\n{}".format(out.decode("utf-8"), err.decode("utf-8"))) raise CartesiMachineServerException(err_msg) def new_machine(session_id, address, machine_req): LOGGER.debug("Connecting to cartesi machine server from session '{}' in address '{}'".format(session_id, address)) with grpc.insecure_channel(address) as channel: stub = cartesi_machine_pb2_grpc.MachineStub(channel) response = stub.Machine(machine_req) LOGGER.debug("Cartesi machine created for session_id '{}'".format(session_id)) def shutdown_cartesi_machine_server(session_id, address): LOGGER.debug("Connecting to cartesi machine server from session '{}' in address '{}'".format(session_id, address)) with grpc.insecure_channel(address) as channel: stub = cartesi_machine_pb2_grpc.MachineStub(channel) response = stub.Shutdown(cartesi_machine_pb2.Void()) LOGGER.debug("Cartesi machine server shutdown for session_id '{}'".format(session_id)) def get_machine_hash(session_id, address): LOGGER.debug("Connecting to cartesi machine server from session '{}' in address '{}'".format(session_id, address)) with grpc.insecure_channel(address) as channel: stub = cartesi_machine_pb2_grpc.MachineStub(channel) LOGGER.debug("Asking for cartesi machine root hash for session_id '{}'".format(session_id)) response = stub.GetRootHash(cartesi_machine_pb2.Void()) LOGGER.debug("Cartesi machine root hash retrieved for session_id '{}'".format(session_id)) return response.hash def create_machine_snapshot(session_id, address): LOGGER.debug("Connecting to cartesi machine server from session '{}' in address '{}'".format(session_id, address)) with grpc.insecure_channel(address) as channel: stub = cartesi_machine_pb2_grpc.MachineStub(channel) stub.Snapshot(cartesi_machine_pb2.Void()) LOGGER.debug("Cartesi machine snapshot created for session_id '{}'".format(session_id)) def rollback_machine(session_id, address): LOGGER.debug("Connecting to cartesi machine server from session '{}' in address '{}'".format(session_id, address)) with grpc.insecure_channel(address) as channel: stub = cartesi_machine_pb2_grpc.MachineStub(channel) stub.Rollback(cartesi_machine_pb2.Void()) LOGGER.debug("Cartesi machine rolledback for session_id '{}'".format(session_id)) def run_machine(session_id, session_context, desired_cycle): ''' This function must be called only when the lock for the given session is held by the caller ''' current_cycle = session_context.cycle LOGGER.debug("Current cycle: {}\nDesired cycle: {}".format(current_cycle, desired_cycle)) if (desired_cycle < current_cycle): raise ValueError("The given desired_cycle must not be smaller than the current_cycle") response = None LOGGER.debug("Connecting to cartesi machine server from session '{}' in address '{}'".format(session_id, session_context.address)) with grpc.insecure_channel(session_context.address) as channel: stub = cartesi_machine_pb2_grpc.MachineStub(channel) #Setting cycle for run batch target_cycle = session_context.cycle + RUN_CYCLES_BATCH_SIZE #If it`s beyond the desired cycle, truncate if (target_cycle > desired_cycle): target_cycle = desired_cycle #Run loop while (True): #Run LOGGER.debug("Running cartesi machine for session id {} with target cycle of {}, current cycle is {}".format(session_id, target_cycle, session_context.cycle)) response = stub.Run(cartesi_machine_pb2.RunRequest(limit=target_cycle)) #Update tracked cycle and updated_at timestamp in the session context session_context.cycle = response.mcycle session_context.updated_at = time.time() LOGGER.debug("Updated cycle of session '{}' to {}".format(session_id, response.mcycle)) #Checking if machine halted if response.iflags_h: #Storing the halting cycle in session context to use in progress calculations session_context.halt_cycle = session_context.cycle LOGGER.debug("Session {} halted with payload {}".format(session_id, int.from_bytes(response.tohost.to_bytes(8, 'big')[2:], byteorder='big'))) break #Checking if the machine yielded elif response.iflags_y: #Parsing tohost to see if a progress command was given #The command is the second byte in the tohost 8bytes register cmd = response.tohost.to_bytes(8, 'big')[1] payload = int.from_bytes(response.tohost.to_bytes(8, 'big')[2:], byteorder='big') if (cmd==0): #It was a progress command, storing the progress session_context.app_progress = payload LOGGER.debug("New progress for session {}: {}".format(session_id, payload)) else: #Wasn't a progress command, just logging LOGGER.debug("Session {} yielded with command {} and payload {}".format(session_id, cmd, payload)) else: #The machine reached the target_cycle, setting next one if it wasn't the desired cycle if target_cycle == desired_cycle: #It was, break the loop break #It wasn't, set the next target cycle target_cycle += RUN_CYCLES_BATCH_SIZE #If it`s beyond the desired cycle, truncate if (target_cycle > desired_cycle): target_cycle = desired_cycle LOGGER.debug("Cartesi machine ran for session_id '{}' and desired final cycle of {}, current cycle is {}".format(session_id, desired_cycle, session_context.cycle)) return response def step_machine(session_id, address, step_params): LOGGER.debug("Connecting to cartesi machine server from session '{}' in address '{}'".format(session_id, address)) with grpc.insecure_channel(address) as channel: stub = cartesi_machine_pb2_grpc.MachineStub(channel) response = stub.Step(step_params) LOGGER.debug("Cartesi machine step complete for session_id '{}'".format(session_id)) return response.log def store_machine(session_id, address, store_req): LOGGER.debug("Connecting to cartesi machine server from session '{}' in address '{}'".format(session_id, address)) with grpc.insecure_channel(address) as channel: stub = cartesi_machine_pb2_grpc.MachineStub(channel) response = stub.Store(store_req) LOGGER.debug("Stored Cartesi machine for session_id '{}', desired directory '{}'".format(session_id, store_req.directory)) return response def read_machine_memory(session_id, address, read_mem_req): LOGGER.debug("Connecting to cartesi machine server from session '{}' in address '{}'".format(session_id, address)) with grpc.insecure_channel(address) as channel: stub = cartesi_machine_pb2_grpc.MachineStub(channel) response = stub.ReadMemory(read_mem_req) LOGGER.debug("Cartesi machine memory read for session_id '{}', desired mem address {} and length {}".format(session_id, read_mem_req.address, read_mem_req.length)) return response def write_machine_memory(session_id, address, write_mem_req): LOGGER.debug("Connecting to cartesi machine server from session '{}' in address '{}'".format(session_id, address)) with grpc.insecure_channel(address) as channel: stub = cartesi_machine_pb2_grpc.MachineStub(channel) response = stub.WriteMemory(write_mem_req) LOGGER.debug("Cartesi machine memory written for session_id '{}', desired mem address {} and data {}".format(session_id, write_mem_req.address, write_mem_req.data)) return response def get_machine_proof(session_id, address, proof_req): LOGGER.debug("Connecting to cartesi machine server from session '{}' in address '{}'".format(session_id, address)) with grpc.insecure_channel(address) as channel: stub = cartesi_machine_pb2_grpc.MachineStub(channel) response = stub.GetProof(proof_req) LOGGER.debug("Got Cartesi machine proof for session_id '{}', desired mem address {} and log2_size {}".format(session_id, proof_req.address, proof_req.log2_size)) return response def make_session_run_result(summaries, hashes): return machine_manager_pb2.SessionRunResponse(result=machine_manager_pb2.SessionRunResult(summaries=summaries, hashes=hashes)) def make_session_step_result(access_log): return machine_manager_pb2.SessionStepResponse(log=access_log) def make_session_read_memory_result(read_mem_resp): return machine_manager_pb2.SessionReadMemoryResponse(read_content=read_mem_resp) class CycleException(Exception): pass class CartesiMachineServerException(Exception): pass def validate_cycles(values): last_value = None #Checking if at least one value was passed if values: for value in values: if (value < 0): raise CycleException("Positive values expected, first offending value: {}".format(value)) if last_value: if value < last_value: raise CycleException("Provide cycle values in crescent order, received {} after {}".format(value, last_value)) last_value = value else: raise CycleException("Provide a cycle value") #Debugging functions def dump_step_response_to_json(access_log): access_log_dict = {'accesses':[], 'notes':[], 'brackets':[]} for note in access_log.log.notes: access_log_dict['notes'].append(note) for bracket in access_log.log.brackets: access_log_dict['brackets'].append( { 'type': cartesi_machine_pb2._BRACKETNOTE_BRACKETNOTETYPE.values_by_number[bracket.type].name, 'where': bracket.where, 'text' : bracket.text }) for access in access_log.log.accesses: access_dict = { 'read': "0x{}".format(access.read.data.hex()), 'written' : "0x{}".format(access.written.data.hex()), 'operation' : cartesi_machine_pb2._ACCESSOPERATION.values_by_number[access.operation].name, 'proof' : { 'address': access.proof.address, 'log2_size': access.proof.log2_size, 'target_hash': "0x{}".format(access.proof.target_hash.data.hex()), 'root_hash': "0x{}".format(access.proof.root_hash.data.hex()), 'sibling_hashes' : [] } } for sibling in access.proof.sibling_hashes: access_dict['proof']['sibling_hashes'].append("0x{}".format(sibling.data.hex())) access_log_dict['accesses'].append(access_dict) return json.dumps(access_log_dict, indent=4, sort_keys=True) def dump_step_response_to_file(access_log, open_dump_file): json_dump = dump_step_response_to_json(access_log) open_dump_file.write("\n\n" + '#'*80 + json_dump) def dump_run_response_to_json(run_resp): resp_dict = None #Checking which of the oneof fields were set oneof_fieldname = run_resp.WhichOneof("run_oneof") if oneof_fieldname == "result": resp_dict = {"summaries": [], "hashes": []} for val in run_resp.result.summaries: resp_dict["summaries"].append({ 'tohost': val.tohost, 'mcycle': val.mcycle }) for val in run_resp.result.hashes: resp_dict["hashes"].append("0x{}".format(val.data.hex())) elif oneof_fieldname == "progress": resp_dict = { "progress": run_resp.progress.progress, "application_progress": run_resp.progress.application_progress, "updated_at": run_resp.progress.updated_at, "cycle": run_resp.progress.cycle } return json.dumps(resp_dict, indent=4, sort_keys=True) def dump_run_response_to_file(run_resp, open_dump_file): json_dump = dump_run_response_to_json(run_resp) open_dump_file.write("\n\n" + '#'*80 + json_dump) def dump_get_proof_response_to_json(proof_resp): proof = proof_resp.proof resp_dict = { 'proof': { 'address': proof.address, 'log2_size': proof.log2_size, 'target_hash': "0x{}".format(proof.target_hash.data.hex()), 'root_hash': "0x{}".format(proof.root_hash.data.hex()), 'sibling_hashes' : [] } } for sibling in proof.sibling_hashes: resp_dict['proof']['sibling_hashes'].append("0x{}".format(sibling.data.hex())) return json.dumps(resp_dict, indent=4, sort_keys=True) def dump_read_mem_response_to_json(read_mem_resp): resp_dict = {"data": "0x{}".format(read_mem_resp.read_content.data.hex())} return json.dumps(resp_dict, indent=4, sort_keys=True) def dump_write_mem_response_to_json(write_mem_resp): return json.dumps("{}".format(write_mem_resp), indent=4, sort_keys=True) #Initializing log LOGGER = get_new_logger(__name__) LOGGER = configure_log(LOGGER)
45.062331
172
0.674886
import subprocess import logging import logging.config import logging.handlers import traceback import grpc import json import time import os import cartesi_machine_pb2_grpc import cartesi_machine_pb2 import machine_manager_pb2 LOG_FILENAME = "manager.log" RUN_CYCLES_BATCH_SIZE = 10**7 UNIX = "unix" TCP = "tcp" SOCKET_TYPE = UNIX def get_new_logger(name): return logging.getLogger(name) def configure_log(logger): logger.setLevel(logging.DEBUG) formatter = logging.Formatter('%(asctime)s %(thread)d %(levelname)-s %(name)s %(lineno)s - %(funcName)s: %(message)s') rotating_file_handler = logging.handlers.RotatingFileHandler( LOG_FILENAME, maxBytes=2**20, backupCount=5) rotating_file_handler.setFormatter(formatter) rotating_file_handler.setLevel(logging.DEBUG) stream_handler = logging.StreamHandler() stream_handler.setLevel(logging.DEBUG) stream_handler.setFormatter(formatter) logger.addHandler(rotating_file_handler) logger.addHandler(stream_handler) return logger def new_cartesi_machine_server(session_id, manager_address): LOGGER.info("Creating a cartesi machine server with session_id '{}'".format(session_id)) cmd_line = ["/opt/cartesi/bin/cartesi-machine-server", "-t", SOCKET_TYPE, "-s", session_id, "-m", manager_address] LOGGER.debug("Executing {}".format(" ".join(cmd_line))) proc = None try: proc = subprocess.Popen(cmd_line, stderr=subprocess.PIPE, stdout=subprocess.PIPE, env=os.environ) out, err = proc.communicate() LOGGER.debug("\nStdout:\n{}\nStderr:\n{}".format(out.decode("utf-8"), err.decode("utf-8"))) except Exception as e: err_msg = "Cartesi machine server creation process failed for session_id '{}'".format(session_id) LOGGER.info(err_msg) if (proc): out, err = proc.communicate() LOGGER.debug("\nStdout:\n{}\nStderr:\n{}".format(out.decode("utf-8"), err.decode("utf-8"))) raise CartesiMachineServerException(err_msg) if (proc.returncode == 0): LOGGER.info("Cartesi machine server creation process returned for session_id '{}'".format(session_id)) LOGGER.debug("\nStdout:\n{}\nStderr:\n{}".format(out.decode("utf-8"), err.decode("utf-8"))) else: err_msg = "Cartesi machine server creation process returned non-zero code for session_id '{}'".format(session_id) LOGGER.error(err_msg) LOGGER.error("\nStdout:\n{}\nStderr:\n{}".format(out.decode("utf-8"), err.decode("utf-8"))) raise CartesiMachineServerException(err_msg) def new_machine(session_id, address, machine_req): LOGGER.debug("Connecting to cartesi machine server from session '{}' in address '{}'".format(session_id, address)) with grpc.insecure_channel(address) as channel: stub = cartesi_machine_pb2_grpc.MachineStub(channel) response = stub.Machine(machine_req) LOGGER.debug("Cartesi machine created for session_id '{}'".format(session_id)) def shutdown_cartesi_machine_server(session_id, address): LOGGER.debug("Connecting to cartesi machine server from session '{}' in address '{}'".format(session_id, address)) with grpc.insecure_channel(address) as channel: stub = cartesi_machine_pb2_grpc.MachineStub(channel) response = stub.Shutdown(cartesi_machine_pb2.Void()) LOGGER.debug("Cartesi machine server shutdown for session_id '{}'".format(session_id)) def get_machine_hash(session_id, address): LOGGER.debug("Connecting to cartesi machine server from session '{}' in address '{}'".format(session_id, address)) with grpc.insecure_channel(address) as channel: stub = cartesi_machine_pb2_grpc.MachineStub(channel) LOGGER.debug("Asking for cartesi machine root hash for session_id '{}'".format(session_id)) response = stub.GetRootHash(cartesi_machine_pb2.Void()) LOGGER.debug("Cartesi machine root hash retrieved for session_id '{}'".format(session_id)) return response.hash def create_machine_snapshot(session_id, address): LOGGER.debug("Connecting to cartesi machine server from session '{}' in address '{}'".format(session_id, address)) with grpc.insecure_channel(address) as channel: stub = cartesi_machine_pb2_grpc.MachineStub(channel) stub.Snapshot(cartesi_machine_pb2.Void()) LOGGER.debug("Cartesi machine snapshot created for session_id '{}'".format(session_id)) def rollback_machine(session_id, address): LOGGER.debug("Connecting to cartesi machine server from session '{}' in address '{}'".format(session_id, address)) with grpc.insecure_channel(address) as channel: stub = cartesi_machine_pb2_grpc.MachineStub(channel) stub.Rollback(cartesi_machine_pb2.Void()) LOGGER.debug("Cartesi machine rolledback for session_id '{}'".format(session_id)) def run_machine(session_id, session_context, desired_cycle): current_cycle = session_context.cycle LOGGER.debug("Current cycle: {}\nDesired cycle: {}".format(current_cycle, desired_cycle)) if (desired_cycle < current_cycle): raise ValueError("The given desired_cycle must not be smaller than the current_cycle") response = None LOGGER.debug("Connecting to cartesi machine server from session '{}' in address '{}'".format(session_id, session_context.address)) with grpc.insecure_channel(session_context.address) as channel: stub = cartesi_machine_pb2_grpc.MachineStub(channel) target_cycle = session_context.cycle + RUN_CYCLES_BATCH_SIZE if (target_cycle > desired_cycle): target_cycle = desired_cycle while (True): LOGGER.debug("Running cartesi machine for session id {} with target cycle of {}, current cycle is {}".format(session_id, target_cycle, session_context.cycle)) response = stub.Run(cartesi_machine_pb2.RunRequest(limit=target_cycle)) session_context.cycle = response.mcycle session_context.updated_at = time.time() LOGGER.debug("Updated cycle of session '{}' to {}".format(session_id, response.mcycle)) if response.iflags_h: session_context.halt_cycle = session_context.cycle LOGGER.debug("Session {} halted with payload {}".format(session_id, int.from_bytes(response.tohost.to_bytes(8, 'big')[2:], byteorder='big'))) break elif response.iflags_y: cmd = response.tohost.to_bytes(8, 'big')[1] payload = int.from_bytes(response.tohost.to_bytes(8, 'big')[2:], byteorder='big') if (cmd==0): session_context.app_progress = payload LOGGER.debug("New progress for session {}: {}".format(session_id, payload)) else: LOGGER.debug("Session {} yielded with command {} and payload {}".format(session_id, cmd, payload)) else: #The machine reached the target_cycle, setting next one if it wasn't the desired cycle if target_cycle == desired_cycle: break target_cycle += RUN_CYCLES_BATCH_SIZE #If it`s beyond the desired cycle, truncate if (target_cycle > desired_cycle): target_cycle = desired_cycle LOGGER.debug("Cartesi machine ran for session_id '{}' and desired final cycle of {}, current cycle is {}".format(session_id, desired_cycle, session_context.cycle)) return response def step_machine(session_id, address, step_params): LOGGER.debug("Connecting to cartesi machine server from session '{}' in address '{}'".format(session_id, address)) with grpc.insecure_channel(address) as channel: stub = cartesi_machine_pb2_grpc.MachineStub(channel) response = stub.Step(step_params) LOGGER.debug("Cartesi machine step complete for session_id '{}'".format(session_id)) return response.log def store_machine(session_id, address, store_req): LOGGER.debug("Connecting to cartesi machine server from session '{}' in address '{}'".format(session_id, address)) with grpc.insecure_channel(address) as channel: stub = cartesi_machine_pb2_grpc.MachineStub(channel) response = stub.Store(store_req) LOGGER.debug("Stored Cartesi machine for session_id '{}', desired directory '{}'".format(session_id, store_req.directory)) return response def read_machine_memory(session_id, address, read_mem_req): LOGGER.debug("Connecting to cartesi machine server from session '{}' in address '{}'".format(session_id, address)) with grpc.insecure_channel(address) as channel: stub = cartesi_machine_pb2_grpc.MachineStub(channel) response = stub.ReadMemory(read_mem_req) LOGGER.debug("Cartesi machine memory read for session_id '{}', desired mem address {} and length {}".format(session_id, read_mem_req.address, read_mem_req.length)) return response def write_machine_memory(session_id, address, write_mem_req): LOGGER.debug("Connecting to cartesi machine server from session '{}' in address '{}'".format(session_id, address)) with grpc.insecure_channel(address) as channel: stub = cartesi_machine_pb2_grpc.MachineStub(channel) response = stub.WriteMemory(write_mem_req) LOGGER.debug("Cartesi machine memory written for session_id '{}', desired mem address {} and data {}".format(session_id, write_mem_req.address, write_mem_req.data)) return response def get_machine_proof(session_id, address, proof_req): LOGGER.debug("Connecting to cartesi machine server from session '{}' in address '{}'".format(session_id, address)) with grpc.insecure_channel(address) as channel: stub = cartesi_machine_pb2_grpc.MachineStub(channel) response = stub.GetProof(proof_req) LOGGER.debug("Got Cartesi machine proof for session_id '{}', desired mem address {} and log2_size {}".format(session_id, proof_req.address, proof_req.log2_size)) return response def make_session_run_result(summaries, hashes): return machine_manager_pb2.SessionRunResponse(result=machine_manager_pb2.SessionRunResult(summaries=summaries, hashes=hashes)) def make_session_step_result(access_log): return machine_manager_pb2.SessionStepResponse(log=access_log) def make_session_read_memory_result(read_mem_resp): return machine_manager_pb2.SessionReadMemoryResponse(read_content=read_mem_resp) class CycleException(Exception): pass class CartesiMachineServerException(Exception): pass def validate_cycles(values): last_value = None #Checking if at least one value was passed if values: for value in values: if (value < 0): raise CycleException("Positive values expected, first offending value: {}".format(value)) if last_value: if value < last_value: raise CycleException("Provide cycle values in crescent order, received {} after {}".format(value, last_value)) last_value = value else: raise CycleException("Provide a cycle value") #Debugging functions def dump_step_response_to_json(access_log): access_log_dict = {'accesses':[], 'notes':[], 'brackets':[]} for note in access_log.log.notes: access_log_dict['notes'].append(note) for bracket in access_log.log.brackets: access_log_dict['brackets'].append( { 'type': cartesi_machine_pb2._BRACKETNOTE_BRACKETNOTETYPE.values_by_number[bracket.type].name, 'where': bracket.where, 'text' : bracket.text }) for access in access_log.log.accesses: access_dict = { 'read': "0x{}".format(access.read.data.hex()), 'written' : "0x{}".format(access.written.data.hex()), 'operation' : cartesi_machine_pb2._ACCESSOPERATION.values_by_number[access.operation].name, 'proof' : { 'address': access.proof.address, 'log2_size': access.proof.log2_size, 'target_hash': "0x{}".format(access.proof.target_hash.data.hex()), 'root_hash': "0x{}".format(access.proof.root_hash.data.hex()), 'sibling_hashes' : [] } } for sibling in access.proof.sibling_hashes: access_dict['proof']['sibling_hashes'].append("0x{}".format(sibling.data.hex())) access_log_dict['accesses'].append(access_dict) return json.dumps(access_log_dict, indent=4, sort_keys=True) def dump_step_response_to_file(access_log, open_dump_file): json_dump = dump_step_response_to_json(access_log) open_dump_file.write("\n\n" + ' def dump_run_response_to_json(run_resp): resp_dict = None #Checking which of the oneof fields were set oneof_fieldname = run_resp.WhichOneof("run_oneof") if oneof_fieldname == "result": resp_dict = {"summaries": [], "hashes": []} for val in run_resp.result.summaries: resp_dict["summaries"].append({ 'tohost': val.tohost, 'mcycle': val.mcycle }) for val in run_resp.result.hashes: resp_dict["hashes"].append("0x{}".format(val.data.hex())) elif oneof_fieldname == "progress": resp_dict = { "progress": run_resp.progress.progress, "application_progress": run_resp.progress.application_progress, "updated_at": run_resp.progress.updated_at, "cycle": run_resp.progress.cycle } return json.dumps(resp_dict, indent=4, sort_keys=True) def dump_run_response_to_file(run_resp, open_dump_file): json_dump = dump_run_response_to_json(run_resp) open_dump_file.write("\n\n" + ' def dump_get_proof_response_to_json(proof_resp): proof = proof_resp.proof resp_dict = { 'proof': { 'address': proof.address, 'log2_size': proof.log2_size, 'target_hash': "0x{}".format(proof.target_hash.data.hex()), 'root_hash': "0x{}".format(proof.root_hash.data.hex()), 'sibling_hashes' : [] } } for sibling in proof.sibling_hashes: resp_dict['proof']['sibling_hashes'].append("0x{}".format(sibling.data.hex())) return json.dumps(resp_dict, indent=4, sort_keys=True) def dump_read_mem_response_to_json(read_mem_resp): resp_dict = {"data": "0x{}".format(read_mem_resp.read_content.data.hex())} return json.dumps(resp_dict, indent=4, sort_keys=True) def dump_write_mem_response_to_json(write_mem_resp): return json.dumps("{}".format(write_mem_resp), indent=4, sort_keys=True) #Initializing log LOGGER = get_new_logger(__name__) LOGGER = configure_log(LOGGER)
true
true
1c34061109ca350266eae9e1a19f7c8cd8d30559
150
py
Python
terrascript/resource/dnsimple.py
amlodzianowski/python-terrascript
1111affe6cd30d9b8b7bc74ae4e27590f7d4dc49
[ "BSD-2-Clause" ]
null
null
null
terrascript/resource/dnsimple.py
amlodzianowski/python-terrascript
1111affe6cd30d9b8b7bc74ae4e27590f7d4dc49
[ "BSD-2-Clause" ]
null
null
null
terrascript/resource/dnsimple.py
amlodzianowski/python-terrascript
1111affe6cd30d9b8b7bc74ae4e27590f7d4dc49
[ "BSD-2-Clause" ]
null
null
null
# terrascript/resource/dnsimple.py import terrascript class dnsimple_record(terrascript.Resource): pass __all__ = [ "dnsimple_record", ]
11.538462
44
0.74
import terrascript class dnsimple_record(terrascript.Resource): pass __all__ = [ "dnsimple_record", ]
true
true
1c34064210bf3bb84e61b0d3413700caef45e132
2,375
py
Python
app/kaznlplib/tokenization/tokhmm.py
n1EzeR/reviews_tazalau
973b0a8ad1c4f54ad13e767424cf3d42fb1a0bbf
[ "CC0-1.0" ]
null
null
null
app/kaznlplib/tokenization/tokhmm.py
n1EzeR/reviews_tazalau
973b0a8ad1c4f54ad13e767424cf3d42fb1a0bbf
[ "CC0-1.0" ]
1
2021-06-02T00:47:32.000Z
2021-06-02T00:47:32.000Z
app/kaznlplib/tokenization/tokhmm.py
n1EzeR/reviews_tazalau
973b0a8ad1c4f54ad13e767424cf3d42fb1a0bbf
[ "CC0-1.0" ]
null
null
null
# -*- coding: UTF-8 -*- import re from kaznlp.models.hmm import HMM_DI # character processing regex with replacements CPREX = { # uppercase mathcer and replacer re.compile(u"[A-ZА-ЯЁӘІҢҒҮҰҚӨҺ]", re.U): "CAP", # lowercase mathcer and replacer re.compile(u"[a-zа-яёәіңғүұқөһ]", re.U): "LOW", # sentence-final punctuation matcher and replacer re.compile(u"[\.\?\!]", re.U): "SFL", # spaces (tab, whitespace, new line, carrier) matcher and replacer re.compile(u"\s", re.U): "SPC", # digit matcher and replacer re.compile(u"\d", re.U): "DIG", } class TokenizerHMM: def __init__(self, implementation=HMM_DI, model=None): self.hmm = implementation() if model: self.hmm.load_model(model) def get_sequence(slef, txt): ret = [] for c in txt: for rex, rep in CPREX.items(): if rex.match(c): c = rep break ret.append(c) return ret def tokenize(self, txt, lower=False): ret = [] curr_sen = [] curr_tok = [] for i, label in enumerate(self.hmm.generate(self.get_sequence(txt))): char = txt[i] if label == "S": if curr_tok: curr_tok = "".join(curr_tok) curr_tok = curr_tok.lower() if lower else curr_tok curr_sen.append(curr_tok) if curr_sen: ret.append(curr_sen) curr_sen = [] curr_tok = [char] elif label == "T": if curr_tok: curr_tok = "".join(curr_tok) curr_tok = curr_tok.lower() if lower else curr_tok curr_sen.append(curr_tok) curr_tok = [char] elif label == "I": curr_tok.append(char) elif label == "O": if curr_tok: curr_tok = "".join(curr_tok) curr_tok = curr_tok.lower() if lower else curr_tok curr_sen.append(curr_tok) curr_tok = [] if curr_tok: curr_tok = "".join(curr_tok) curr_tok = curr_tok.lower() if lower else curr_tok curr_sen.append(curr_tok) ret.append(curr_sen) return ret
32.534247
77
0.507368
import re from kaznlp.models.hmm import HMM_DI CPREX = { re.compile(u"[A-ZА-ЯЁӘІҢҒҮҰҚӨҺ]", re.U): "CAP", re.compile(u"[a-zа-яёәіңғүұқөһ]", re.U): "LOW", re.compile(u"[\.\?\!]", re.U): "SFL", re.compile(u"\s", re.U): "SPC", re.compile(u"\d", re.U): "DIG", } class TokenizerHMM: def __init__(self, implementation=HMM_DI, model=None): self.hmm = implementation() if model: self.hmm.load_model(model) def get_sequence(slef, txt): ret = [] for c in txt: for rex, rep in CPREX.items(): if rex.match(c): c = rep break ret.append(c) return ret def tokenize(self, txt, lower=False): ret = [] curr_sen = [] curr_tok = [] for i, label in enumerate(self.hmm.generate(self.get_sequence(txt))): char = txt[i] if label == "S": if curr_tok: curr_tok = "".join(curr_tok) curr_tok = curr_tok.lower() if lower else curr_tok curr_sen.append(curr_tok) if curr_sen: ret.append(curr_sen) curr_sen = [] curr_tok = [char] elif label == "T": if curr_tok: curr_tok = "".join(curr_tok) curr_tok = curr_tok.lower() if lower else curr_tok curr_sen.append(curr_tok) curr_tok = [char] elif label == "I": curr_tok.append(char) elif label == "O": if curr_tok: curr_tok = "".join(curr_tok) curr_tok = curr_tok.lower() if lower else curr_tok curr_sen.append(curr_tok) curr_tok = [] if curr_tok: curr_tok = "".join(curr_tok) curr_tok = curr_tok.lower() if lower else curr_tok curr_sen.append(curr_tok) ret.append(curr_sen) return ret
true
true
1c34065aa7e70f2a9d46f68e522f48e8db1adb12
25,852
py
Python
userbot/modules/scrapers.py
Saksham033/PaperplaneExtended
1480e25bcd2e012ba1e2d78c1ba29a3cbc449a23
[ "Naumen", "Condor-1.1", "MS-PL" ]
null
null
null
userbot/modules/scrapers.py
Saksham033/PaperplaneExtended
1480e25bcd2e012ba1e2d78c1ba29a3cbc449a23
[ "Naumen", "Condor-1.1", "MS-PL" ]
null
null
null
userbot/modules/scrapers.py
Saksham033/PaperplaneExtended
1480e25bcd2e012ba1e2d78c1ba29a3cbc449a23
[ "Naumen", "Condor-1.1", "MS-PL" ]
null
null
null
# Copyright (C) 2019 The Raphielscape Company LLC. # # Licensed under the Raphielscape Public License, Version 1.c (the "License"); # you may not use this file except in compliance with the License. # """ Userbot module containing various scrapers. """ import os import time import asyncio import shutil from bs4 import BeautifulSoup import re from time import sleep from html import unescape from re import findall from selenium import webdriver from urllib.parse import quote_plus from urllib.error import HTTPError from selenium.webdriver.support.ui import Select from selenium.webdriver.chrome.options import Options from wikipedia import summary from wikipedia.exceptions import DisambiguationError, PageError import asyncurban from requests import get from search_engine_parser import GoogleSearch from google_images_download import google_images_download from googleapiclient.discovery import build from googleapiclient.errors import HttpError from googletrans import LANGUAGES, Translator from gtts import gTTS from gtts.lang import tts_langs from emoji import get_emoji_regexp from youtube_dl import YoutubeDL from youtube_dl.utils import (DownloadError, ContentTooShortError, ExtractorError, GeoRestrictedError, MaxDownloadsReached, PostProcessingError, UnavailableVideoError, XAttrMetadataError) from asyncio import sleep from userbot import CMD_HELP, BOTLOG, BOTLOG_CHATID, YOUTUBE_API_KEY, CHROME_DRIVER, GOOGLE_CHROME_BIN from userbot.events import register from telethon.tl.types import DocumentAttributeAudio from userbot.modules.upload_download import progress, humanbytes, time_formatter CARBONLANG = "auto" TTS_LANG = "en" TRT_LANG = "en" @register(outgoing=True, pattern="^.crblang (.*)") async def setlang(prog): global CARBONLANG CARBONLANG = prog.pattern_match.group(1) await prog.edit(f"Language for carbon.now.sh set to {CARBONLANG}") @register(outgoing=True, pattern="^.carbon") async def carbon_api(e): """ A Wrapper for carbon.now.sh """ await e.edit("`Processing..`") CARBON = 'https://carbon.now.sh/?l={lang}&code={code}' global CARBONLANG textx = await e.get_reply_message() pcode = e.text if pcode[8:]: pcode = str(pcode[8:]) elif textx: pcode = str(textx.message) # Importing message to module code = quote_plus(pcode) # Converting to urlencoded await e.edit("`Processing..\n25%`") if os.path.isfile("./carbon.png"): os.remove("./carbon.png") url = CARBON.format(code=code, lang=CARBONLANG) chrome_options = Options() chrome_options.add_argument("--headless") chrome_options.binary_location = GOOGLE_CHROME_BIN chrome_options.add_argument("--window-size=1920x1080") chrome_options.add_argument("--disable-dev-shm-usage") chrome_options.add_argument("--no-sandbox") chrome_options.add_argument("--disable-gpu") prefs = {'download.default_directory': './'} chrome_options.add_experimental_option('prefs', prefs) driver = webdriver.Chrome(executable_path=CHROME_DRIVER, options=chrome_options) driver.get(url) await e.edit("`Processing..\n50%`") download_path = './' driver.command_executor._commands["send_command"] = ( "POST", '/session/$sessionId/chromium/send_command') params = { 'cmd': 'Page.setDownloadBehavior', 'params': { 'behavior': 'allow', 'downloadPath': download_path } } command_result = driver.execute("send_command", params) driver.find_element_by_xpath("//button[contains(text(),'Export')]").click() driver.find_element_by_xpath("//button[contains(text(),'4x')]").click() driver.find_element_by_xpath("//button[contains(text(),'PNG')]").click() await e.edit("`Processing..\n75%`") # Waiting for downloading while not os.path.isfile("./carbon.png"): await sleep(0.5) await e.edit("`Processing..\n100%`") file = './carbon.png' await e.edit("`Uploading..`") await e.client.send_file( e.chat_id, file, caption="Made using [Carbon](https://carbon.now.sh/about/),\ \na project by [Dawn Labs](https://dawnlabs.io/)", force_document=True, reply_to=e.message.reply_to_msg_id, ) os.remove('./carbon.png') driver.quit() # Removing carbon.png after uploading await e.delete() # Deleting msg @register(outgoing=True, pattern="^.img (.*)") async def img_sampler(event): """ For .img command, search and return images matching the query. """ await event.edit("Processing...") query = event.pattern_match.group(1) lim = findall(r"lim=\d+", query) try: lim = lim[0] lim = lim.replace("lim=", "") query = query.replace("lim=" + lim[0], "") except IndexError: lim = 3 response = google_images_download.googleimagesdownload() # creating list of arguments arguments = { "keywords": query, "limit": lim, "format": "jpg", "no_directory": "no_directory" } # passing the arguments to the function paths = response.download(arguments) lst = paths[0][query] await event.client.send_file( await event.client.get_input_entity(event.chat_id), lst) shutil.rmtree(os.path.dirname(os.path.abspath(lst[0]))) await event.delete() @register(outgoing=True, pattern="^.currency (.*)") async def moni(event): input_str = event.pattern_match.group(1) input_sgra = input_str.split(" ") if len(input_sgra) == 3: try: number = float(input_sgra[0]) currency_from = input_sgra[1].upper() currency_to = input_sgra[2].upper() request_url = "https://api.exchangeratesapi.io/latest?base={}".format( currency_from) current_response = get(request_url).json() if currency_to in current_response["rates"]: current_rate = float(current_response["rates"][currency_to]) rebmun = round(number * current_rate, 2) await event.edit("{} {} = {} {}".format( number, currency_from, rebmun, currency_to)) else: await event.edit( "`This seems to be some alien currency, which I can't convert right now.`" ) except Exception as e: await event.edit(str(e)) else: await event.edit("`Invalid syntax.`") return @register(outgoing=True, pattern=r"^.google (.*)") async def gsearch(q_event): """ For .google command, do a Google search. """ match = q_event.pattern_match.group(1) page = findall(r"page=\d+", match) try: page = page[0] page = page.replace("page=", "") match = match.replace("page=" + page[0], "") except IndexError: page = 1 search_args = (str(match), int(page)) gsearch = GoogleSearch() gresults = await gsearch.async_search(*search_args) msg = "" for i in range(len(gresults["links"])): try: title = gresults["titles"][i] link = gresults["links"][i] desc = gresults["descriptions"][i] msg += f"[{title}]({link})\n`{desc}`\n\n" except IndexError: break await q_event.edit("**Search Query:**\n`" + match + "`\n\n**Results:**\n" + msg, link_preview=False) if BOTLOG: await q_event.client.send_message( BOTLOG_CHATID, "Google Search query `" + match + "` was executed successfully", ) @register(outgoing=True, pattern=r"^.wiki (.*)") async def wiki(wiki_q): """ For .wiki command, fetch content from Wikipedia. """ match = wiki_q.pattern_match.group(1) try: summary(match) except DisambiguationError as error: await wiki_q.edit(f"Disambiguated page found.\n\n{error}") return except PageError as pageerror: await wiki_q.edit(f"Page not found.\n\n{pageerror}") return result = summary(match) if len(result) >= 4096: file = open("output.txt", "w+") file.write(result) file.close() await wiki_q.client.send_file( wiki_q.chat_id, "output.txt", reply_to=wiki_q.id, caption="`Output too large, sending as file`", ) if os.path.exists("output.txt"): os.remove("output.txt") return await wiki_q.edit("**Search:**\n`" + match + "`\n\n**Result:**\n" + result) if BOTLOG: await wiki_q.client.send_message( BOTLOG_CHATID, f"Wiki query `{match}` was executed successfully") @register(outgoing=True, pattern="^.ud (.*)") async def urban_dict(ud_e): """ For .ud command, fetch content from Urban Dictionary. """ await ud_e.edit("Processing...") query = ud_e.pattern_match.group(1) urban_dict_helper = asyncurban.UrbanDictionary() try: urban_def = await urban_dict_helper.get_word(query) except asyncurban.WordNotFoundError: await ud_e.edit(f"Sorry, couldn't find any results for: {query}") return deflen = sum(len(i) for i in urban_def.definition) exalen = sum(len(i) for i in urban_def.example) meanlen = deflen + exalen if int(meanlen) >= 0: if int(meanlen) >= 4096: await ud_e.edit("`Output too large, sending as file.`") file = open("output.txt", "w+") file.write("Text: " + query + "\n\nMeaning: " + urban_def.definition + "\n\n" + "Example: \n" + urban_def.example) file.close() await ud_e.client.send_file( ud_e.chat_id, "output.txt", caption="`Output was too large, sent it as a file.`") if os.path.exists("output.txt"): os.remove("output.txt") await ud_e.delete() return await ud_e.edit("Text: **" + query + "**\n\nMeaning: **" + urban_def.definition + "**\n\n" + "Example: \n__" + urban_def.example + "__") if BOTLOG: await ud_e.client.send_message( BOTLOG_CHATID, "UrbanDictionary query for `" + query + "` executed successfully.") else: await ud_e.edit("No result found for **" + query + "**") @register(outgoing=True, pattern=r"^.tts(?: |$)([\s\S]*)") async def text_to_speech(query): """ For .tts command, a wrapper for Google Text-to-Speech. """ textx = await query.get_reply_message() message = query.pattern_match.group(1) if message: pass elif textx: message = textx.text else: await query.edit( "`Give a text or reply to a message for Text-to-Speech!`") return try: gTTS(message, TTS_LANG) except AssertionError: await query.edit( 'The text is empty.\n' 'Nothing left to speak after pre-precessing, tokenizing and cleaning.' ) return except ValueError: await query.edit('Language is not supported.') return except RuntimeError: await query.edit('Error loading the languages dictionary.') return tts = gTTS(message, TTS_LANG) tts.save("k.mp3") with open("k.mp3", "rb") as audio: linelist = list(audio) linecount = len(linelist) if linecount == 1: tts = gTTS(message, TTS_LANG) tts.save("k.mp3") with open("k.mp3", "r"): await query.client.send_file(query.chat_id, "k.mp3", voice_note=True) os.remove("k.mp3") if BOTLOG: await query.client.send_message( BOTLOG_CHATID, "Text to Speech executed successfully !") await query.delete() # kanged from Blank-x ;---; @register(outgoing=True, pattern="^.imdb (.*)") async def imdb(e): try: movie_name = e.pattern_match.group(1) remove_space = movie_name.split(' ') final_name = '+'.join(remove_space) page = get("https://www.imdb.com/find?ref_=nv_sr_fn&q=" + final_name + "&s=all") lnk = str(page.status_code) soup = BeautifulSoup(page.content, 'lxml') odds = soup.findAll("tr", "odd") mov_title = odds[0].findNext('td').findNext('td').text mov_link = "http://www.imdb.com/" + \ odds[0].findNext('td').findNext('td').a['href'] page1 = get(mov_link) soup = BeautifulSoup(page1.content, 'lxml') if soup.find('div', 'poster'): poster = soup.find('div', 'poster').img['src'] else: poster = '' if soup.find('div', 'title_wrapper'): pg = soup.find('div', 'title_wrapper').findNext('div').text mov_details = re.sub(r'\s+', ' ', pg) else: mov_details = '' credits = soup.findAll('div', 'credit_summary_item') if len(credits) == 1: director = credits[0].a.text writer = 'Not available' stars = 'Not available' elif len(credits) > 2: director = credits[0].a.text writer = credits[1].a.text actors = [] for x in credits[2].findAll('a'): actors.append(x.text) actors.pop() stars = actors[0] + ',' + actors[1] + ',' + actors[2] else: director = credits[0].a.text writer = 'Not available' actors = [] for x in credits[1].findAll('a'): actors.append(x.text) actors.pop() stars = actors[0] + ',' + actors[1] + ',' + actors[2] if soup.find('div', "inline canwrap"): story_line = soup.find('div', "inline canwrap").findAll('p')[0].text else: story_line = 'Not available' info = soup.findAll('div', "txt-block") if info: mov_country = [] mov_language = [] for node in info: a = node.findAll('a') for i in a: if "country_of_origin" in i['href']: mov_country.append(i.text) elif "primary_language" in i['href']: mov_language.append(i.text) if soup.findAll('div', "ratingValue"): for r in soup.findAll('div', "ratingValue"): mov_rating = r.strong['title'] else: mov_rating = 'Not available' await e.edit('<a href=' + poster + '>&#8203;</a>' '<b>Title : </b><code>' + mov_title + '</code>\n<code>' + mov_details + '</code>\n<b>Rating : </b><code>' + mov_rating + '</code>\n<b>Country : </b><code>' + mov_country[0] + '</code>\n<b>Language : </b><code>' + mov_language[0] + '</code>\n<b>Director : </b><code>' + director + '</code>\n<b>Writer : </b><code>' + writer + '</code>\n<b>Stars : </b><code>' + stars + '</code>\n<b>IMDB Url : </b>' + mov_link + '\n<b>Story Line : </b>' + story_line, link_preview=True, parse_mode='HTML') except IndexError: await e.edit("Plox enter **Valid movie name** kthx") @register(outgoing=True, pattern=r"^.trt(?: |$)([\s\S]*)") async def translateme(trans): """ For .trt command, translate the given text using Google Translate. """ translator = Translator() textx = await trans.get_reply_message() message = trans.pattern_match.group(1) if message: pass elif textx: message = textx.text else: await trans.edit("`Give a text or reply to a message to translate!`") return try: reply_text = translator.translate(deEmojify(message), dest=TRT_LANG) except ValueError: await trans.edit("Invalid destination language.") return source_lan = LANGUAGES[f'{reply_text.src.lower()}'] transl_lan = LANGUAGES[f'{reply_text.dest.lower()}'] reply_text = f"From **{source_lan.title()}**\nTo **{transl_lan.title()}:**\n\n{reply_text.text}" await trans.edit(reply_text) if BOTLOG: await trans.client.send_message( BOTLOG_CHATID, f"Translated some {source_lan.title()} stuff to {transl_lan.title()} just now.", ) @register(pattern="^.lang (trt|tts) (.*)", outgoing=True) async def lang(value): """ For .lang command, change the default langauge of userbot scrapers. """ util = value.pattern_match.group(1).lower() if util == "trt": scraper = "Translator" global TRT_LANG arg = value.pattern_match.group(2).lower() if arg in LANGUAGES: TRT_LANG = arg LANG = LANGUAGES[arg] else: await value.edit( f"`Invalid Language code !!`\n`Available language codes for TRT`:\n\n`{LANGUAGES}`" ) return elif util == "tts": scraper = "Text to Speech" global TTS_LANG arg = value.pattern_match.group(2).lower() if arg in tts_langs(): TTS_LANG = arg LANG = tts_langs()[arg] else: await value.edit( f"`Invalid Language code !!`\n`Available language codes for TTS`:\n\n`{tts_langs()}`" ) return await value.edit(f"`Language for {scraper} changed to {LANG.title()}.`") if BOTLOG: await value.client.send_message( BOTLOG_CHATID, f"`Language for {scraper} changed to {LANG.title()}.`") @register(outgoing=True, pattern="^.yt (.*)") async def yt_search(video_q): """ For .yt command, do a YouTube search from Telegram. """ query = video_q.pattern_match.group(1) result = '' if not YOUTUBE_API_KEY: await video_q.edit( "`Error: YouTube API key missing! Add it to environment vars or config.env.`" ) return await video_q.edit("```Processing...```") full_response = await youtube_search(query) videos_json = full_response[1] for video in videos_json: title = f"{unescape(video['snippet']['title'])}" link = f"https://youtu.be/{video['id']['videoId']}" result += f"{title}\n{link}\n\n" reply_text = f"**Search Query:**\n`{query}`\n\n**Results:**\n\n{result}" await video_q.edit(reply_text) async def youtube_search(query, order="relevance", token=None, location=None, location_radius=None): """ Do a YouTube search. """ youtube = build('youtube', 'v3', developerKey=YOUTUBE_API_KEY, cache_discovery=False) search_response = youtube.search().list( q=query, type="video", pageToken=token, order=order, part="id,snippet", maxResults=10, location=location, locationRadius=location_radius).execute() videos = [] for search_result in search_response.get("items", []): if search_result["id"]["kind"] == "youtube#video": videos.append(search_result) try: nexttok = search_response["nextPageToken"] return (nexttok, videos) except HttpError: nexttok = "last_page" return (nexttok, videos) except KeyError: nexttok = "KeyError, try again." return (nexttok, videos) @register(outgoing=True, pattern=r"^.rip(audio|video) (.*)") async def download_video(v_url): """ For .rip command, download media from YouTube and many other sites. """ url = v_url.pattern_match.group(2) type = v_url.pattern_match.group(1).lower() await v_url.edit("`Preparing to download...`") if type == "audio": opts = { 'format': 'bestaudio', 'addmetadata': True, 'key': 'FFmpegMetadata', 'writethumbnail': True, 'prefer_ffmpeg': True, 'geo_bypass': True, 'nocheckcertificate': True, 'postprocessors': [{ 'key': 'FFmpegExtractAudio', 'preferredcodec': 'mp3', 'preferredquality': '320', }], 'outtmpl': '%(id)s.mp3', 'quiet': True, 'logtostderr': False } video = False song = True elif type == "video": opts = { 'format': 'best', 'addmetadata': True, 'key': 'FFmpegMetadata', 'prefer_ffmpeg': True, 'geo_bypass': True, 'nocheckcertificate': True, 'postprocessors': [{ 'key': 'FFmpegVideoConvertor', 'preferedformat': 'mp4' }], 'outtmpl': '%(id)s.mp4', 'logtostderr': False, 'quiet': True } song = False video = True try: await v_url.edit("`Fetching data, please wait..`") with YoutubeDL(opts) as rip: rip_data = rip.extract_info(url) except DownloadError as DE: await v_url.edit(f"`{str(DE)}`") return except ContentTooShortError: await v_url.edit("`The download content was too short.`") return except GeoRestrictedError: await v_url.edit( "`Video is not available from your geographic location due to geographic restrictions imposed by a website.`" ) return except MaxDownloadsReached: await v_url.edit("`Max-downloads limit has been reached.`") return except PostProcessingError: await v_url.edit("`There was an error during post processing.`") return except UnavailableVideoError: await v_url.edit("`Media is not available in the requested format.`") return except XAttrMetadataError as XAME: await v_url.edit(f"`{XAME.code}: {XAME.msg}\n{XAME.reason}`") return except ExtractorError: await v_url.edit("`There was an error during info extraction.`") return except Exception as e: await v_url.edit(f"{str(type(e)): {str(e)}}") return c_time = time.time() if song: await v_url.edit(f"`Preparing to upload song:`\ \n**{rip_data['title']}**\ \nby __{rip_data['uploader']}__") await v_url.client.send_file( v_url.chat_id, f"{rip_data['id']}.mp3", supports_streaming=True, attributes=[ DocumentAttributeAudio(duration=int(rip_data['duration']), title=str(rip_data['title']), performer=str(rip_data['uploader'])) ], progress_callback=lambda d, t: asyncio.get_event_loop( ).create_task( progress(d, t, v_url, c_time, "Uploading..", f"{rip_data['title']}.mp3"))) os.remove(f"{rip_data['id']}.mp3") await v_url.delete() elif video: await v_url.edit(f"`Preparing to upload video:`\ \n**{rip_data['title']}**\ \nby __{rip_data['uploader']}__") await v_url.client.send_file( v_url.chat_id, f"{rip_data['id']}.mp4", supports_streaming=True, caption=rip_data['title'], progress_callback=lambda d, t: asyncio.get_event_loop( ).create_task( progress(d, t, v_url, c_time, "Uploading..", f"{rip_data['title']}.mp4"))) os.remove(f"{rip_data['id']}.mp4") await v_url.delete() def deEmojify(inputString): """ Remove emojis and other non-safe characters from string """ return get_emoji_regexp().sub(u'', inputString) CMD_HELP.update({ 'img': '.img <search_query>\ \nUsage: Does an image search on Google and shows 5 images.' }) CMD_HELP.update({ 'currency': '.currency <amount> <from> <to>\ \nUsage: Converts various currencies for you.' }) CMD_HELP.update({ 'carbon': '.carbon <text> [or reply]\ \nUsage: Beautify your code using carbon.now.sh\nUse .crblang <text> to set language for your code.' }) CMD_HELP.update( {'google': '.google <query>\ \nUsage: Does a search on Google.'}) CMD_HELP.update( {'wiki': '.wiki <query>\ \nUsage: Does a search on Wikipedia.'}) CMD_HELP.update( {'ud': '.ud <query>\ \nUsage: Does a search on Urban Dictionary.'}) CMD_HELP.update({ 'tts': '.tts <text> [or reply]\ \nUsage: Translates text to speech for the language which is set.\nUse .lang tts <language code> to set language for tts. (Default is English.)' }) CMD_HELP.update({ 'trt': '.trt <text> [or reply]\ \nUsage: Translates text to the language which is set.\nUse .lang trt <language code> to set language for trt. (Default is English)' }) CMD_HELP.update({'yt': '.yt <text>\ \nUsage: Does a YouTube search.'}) CMD_HELP.update( {"imdb": ".imdb <movie-name>\nShows movie info and other stuff."}) CMD_HELP.update({ 'rip': '.ripaudio <url> or ripvideo <url>\ \nUsage: Download videos and songs from YouTube (and [many other sites](https://ytdl-org.github.io/youtube-dl/supportedsites.html)).' })
35.268759
152
0.572567
import os import time import asyncio import shutil from bs4 import BeautifulSoup import re from time import sleep from html import unescape from re import findall from selenium import webdriver from urllib.parse import quote_plus from urllib.error import HTTPError from selenium.webdriver.support.ui import Select from selenium.webdriver.chrome.options import Options from wikipedia import summary from wikipedia.exceptions import DisambiguationError, PageError import asyncurban from requests import get from search_engine_parser import GoogleSearch from google_images_download import google_images_download from googleapiclient.discovery import build from googleapiclient.errors import HttpError from googletrans import LANGUAGES, Translator from gtts import gTTS from gtts.lang import tts_langs from emoji import get_emoji_regexp from youtube_dl import YoutubeDL from youtube_dl.utils import (DownloadError, ContentTooShortError, ExtractorError, GeoRestrictedError, MaxDownloadsReached, PostProcessingError, UnavailableVideoError, XAttrMetadataError) from asyncio import sleep from userbot import CMD_HELP, BOTLOG, BOTLOG_CHATID, YOUTUBE_API_KEY, CHROME_DRIVER, GOOGLE_CHROME_BIN from userbot.events import register from telethon.tl.types import DocumentAttributeAudio from userbot.modules.upload_download import progress, humanbytes, time_formatter CARBONLANG = "auto" TTS_LANG = "en" TRT_LANG = "en" @register(outgoing=True, pattern="^.crblang (.*)") async def setlang(prog): global CARBONLANG CARBONLANG = prog.pattern_match.group(1) await prog.edit(f"Language for carbon.now.sh set to {CARBONLANG}") @register(outgoing=True, pattern="^.carbon") async def carbon_api(e): await e.edit("`Processing..`") CARBON = 'https://carbon.now.sh/?l={lang}&code={code}' global CARBONLANG textx = await e.get_reply_message() pcode = e.text if pcode[8:]: pcode = str(pcode[8:]) elif textx: pcode = str(textx.message) code = quote_plus(pcode) await e.edit("`Processing..\n25%`") if os.path.isfile("./carbon.png"): os.remove("./carbon.png") url = CARBON.format(code=code, lang=CARBONLANG) chrome_options = Options() chrome_options.add_argument("--headless") chrome_options.binary_location = GOOGLE_CHROME_BIN chrome_options.add_argument("--window-size=1920x1080") chrome_options.add_argument("--disable-dev-shm-usage") chrome_options.add_argument("--no-sandbox") chrome_options.add_argument("--disable-gpu") prefs = {'download.default_directory': './'} chrome_options.add_experimental_option('prefs', prefs) driver = webdriver.Chrome(executable_path=CHROME_DRIVER, options=chrome_options) driver.get(url) await e.edit("`Processing..\n50%`") download_path = './' driver.command_executor._commands["send_command"] = ( "POST", '/session/$sessionId/chromium/send_command') params = { 'cmd': 'Page.setDownloadBehavior', 'params': { 'behavior': 'allow', 'downloadPath': download_path } } command_result = driver.execute("send_command", params) driver.find_element_by_xpath("//button[contains(text(),'Export')]").click() driver.find_element_by_xpath("//button[contains(text(),'4x')]").click() driver.find_element_by_xpath("//button[contains(text(),'PNG')]").click() await e.edit("`Processing..\n75%`") while not os.path.isfile("./carbon.png"): await sleep(0.5) await e.edit("`Processing..\n100%`") file = './carbon.png' await e.edit("`Uploading..`") await e.client.send_file( e.chat_id, file, caption="Made using [Carbon](https://carbon.now.sh/about/),\ \na project by [Dawn Labs](https://dawnlabs.io/)", force_document=True, reply_to=e.message.reply_to_msg_id, ) os.remove('./carbon.png') driver.quit() await e.delete() @register(outgoing=True, pattern="^.img (.*)") async def img_sampler(event): await event.edit("Processing...") query = event.pattern_match.group(1) lim = findall(r"lim=\d+", query) try: lim = lim[0] lim = lim.replace("lim=", "") query = query.replace("lim=" + lim[0], "") except IndexError: lim = 3 response = google_images_download.googleimagesdownload() arguments = { "keywords": query, "limit": lim, "format": "jpg", "no_directory": "no_directory" } paths = response.download(arguments) lst = paths[0][query] await event.client.send_file( await event.client.get_input_entity(event.chat_id), lst) shutil.rmtree(os.path.dirname(os.path.abspath(lst[0]))) await event.delete() @register(outgoing=True, pattern="^.currency (.*)") async def moni(event): input_str = event.pattern_match.group(1) input_sgra = input_str.split(" ") if len(input_sgra) == 3: try: number = float(input_sgra[0]) currency_from = input_sgra[1].upper() currency_to = input_sgra[2].upper() request_url = "https://api.exchangeratesapi.io/latest?base={}".format( currency_from) current_response = get(request_url).json() if currency_to in current_response["rates"]: current_rate = float(current_response["rates"][currency_to]) rebmun = round(number * current_rate, 2) await event.edit("{} {} = {} {}".format( number, currency_from, rebmun, currency_to)) else: await event.edit( "`This seems to be some alien currency, which I can't convert right now.`" ) except Exception as e: await event.edit(str(e)) else: await event.edit("`Invalid syntax.`") return @register(outgoing=True, pattern=r"^.google (.*)") async def gsearch(q_event): match = q_event.pattern_match.group(1) page = findall(r"page=\d+", match) try: page = page[0] page = page.replace("page=", "") match = match.replace("page=" + page[0], "") except IndexError: page = 1 search_args = (str(match), int(page)) gsearch = GoogleSearch() gresults = await gsearch.async_search(*search_args) msg = "" for i in range(len(gresults["links"])): try: title = gresults["titles"][i] link = gresults["links"][i] desc = gresults["descriptions"][i] msg += f"[{title}]({link})\n`{desc}`\n\n" except IndexError: break await q_event.edit("**Search Query:**\n`" + match + "`\n\n**Results:**\n" + msg, link_preview=False) if BOTLOG: await q_event.client.send_message( BOTLOG_CHATID, "Google Search query `" + match + "` was executed successfully", ) @register(outgoing=True, pattern=r"^.wiki (.*)") async def wiki(wiki_q): match = wiki_q.pattern_match.group(1) try: summary(match) except DisambiguationError as error: await wiki_q.edit(f"Disambiguated page found.\n\n{error}") return except PageError as pageerror: await wiki_q.edit(f"Page not found.\n\n{pageerror}") return result = summary(match) if len(result) >= 4096: file = open("output.txt", "w+") file.write(result) file.close() await wiki_q.client.send_file( wiki_q.chat_id, "output.txt", reply_to=wiki_q.id, caption="`Output too large, sending as file`", ) if os.path.exists("output.txt"): os.remove("output.txt") return await wiki_q.edit("**Search:**\n`" + match + "`\n\n**Result:**\n" + result) if BOTLOG: await wiki_q.client.send_message( BOTLOG_CHATID, f"Wiki query `{match}` was executed successfully") @register(outgoing=True, pattern="^.ud (.*)") async def urban_dict(ud_e): await ud_e.edit("Processing...") query = ud_e.pattern_match.group(1) urban_dict_helper = asyncurban.UrbanDictionary() try: urban_def = await urban_dict_helper.get_word(query) except asyncurban.WordNotFoundError: await ud_e.edit(f"Sorry, couldn't find any results for: {query}") return deflen = sum(len(i) for i in urban_def.definition) exalen = sum(len(i) for i in urban_def.example) meanlen = deflen + exalen if int(meanlen) >= 0: if int(meanlen) >= 4096: await ud_e.edit("`Output too large, sending as file.`") file = open("output.txt", "w+") file.write("Text: " + query + "\n\nMeaning: " + urban_def.definition + "\n\n" + "Example: \n" + urban_def.example) file.close() await ud_e.client.send_file( ud_e.chat_id, "output.txt", caption="`Output was too large, sent it as a file.`") if os.path.exists("output.txt"): os.remove("output.txt") await ud_e.delete() return await ud_e.edit("Text: **" + query + "**\n\nMeaning: **" + urban_def.definition + "**\n\n" + "Example: \n__" + urban_def.example + "__") if BOTLOG: await ud_e.client.send_message( BOTLOG_CHATID, "UrbanDictionary query for `" + query + "` executed successfully.") else: await ud_e.edit("No result found for **" + query + "**") @register(outgoing=True, pattern=r"^.tts(?: |$)([\s\S]*)") async def text_to_speech(query): textx = await query.get_reply_message() message = query.pattern_match.group(1) if message: pass elif textx: message = textx.text else: await query.edit( "`Give a text or reply to a message for Text-to-Speech!`") return try: gTTS(message, TTS_LANG) except AssertionError: await query.edit( 'The text is empty.\n' 'Nothing left to speak after pre-precessing, tokenizing and cleaning.' ) return except ValueError: await query.edit('Language is not supported.') return except RuntimeError: await query.edit('Error loading the languages dictionary.') return tts = gTTS(message, TTS_LANG) tts.save("k.mp3") with open("k.mp3", "rb") as audio: linelist = list(audio) linecount = len(linelist) if linecount == 1: tts = gTTS(message, TTS_LANG) tts.save("k.mp3") with open("k.mp3", "r"): await query.client.send_file(query.chat_id, "k.mp3", voice_note=True) os.remove("k.mp3") if BOTLOG: await query.client.send_message( BOTLOG_CHATID, "Text to Speech executed successfully !") await query.delete() @register(outgoing=True, pattern="^.imdb (.*)") async def imdb(e): try: movie_name = e.pattern_match.group(1) remove_space = movie_name.split(' ') final_name = '+'.join(remove_space) page = get("https://www.imdb.com/find?ref_=nv_sr_fn&q=" + final_name + "&s=all") lnk = str(page.status_code) soup = BeautifulSoup(page.content, 'lxml') odds = soup.findAll("tr", "odd") mov_title = odds[0].findNext('td').findNext('td').text mov_link = "http://www.imdb.com/" + \ odds[0].findNext('td').findNext('td').a['href'] page1 = get(mov_link) soup = BeautifulSoup(page1.content, 'lxml') if soup.find('div', 'poster'): poster = soup.find('div', 'poster').img['src'] else: poster = '' if soup.find('div', 'title_wrapper'): pg = soup.find('div', 'title_wrapper').findNext('div').text mov_details = re.sub(r'\s+', ' ', pg) else: mov_details = '' credits = soup.findAll('div', 'credit_summary_item') if len(credits) == 1: director = credits[0].a.text writer = 'Not available' stars = 'Not available' elif len(credits) > 2: director = credits[0].a.text writer = credits[1].a.text actors = [] for x in credits[2].findAll('a'): actors.append(x.text) actors.pop() stars = actors[0] + ',' + actors[1] + ',' + actors[2] else: director = credits[0].a.text writer = 'Not available' actors = [] for x in credits[1].findAll('a'): actors.append(x.text) actors.pop() stars = actors[0] + ',' + actors[1] + ',' + actors[2] if soup.find('div', "inline canwrap"): story_line = soup.find('div', "inline canwrap").findAll('p')[0].text else: story_line = 'Not available' info = soup.findAll('div', "txt-block") if info: mov_country = [] mov_language = [] for node in info: a = node.findAll('a') for i in a: if "country_of_origin" in i['href']: mov_country.append(i.text) elif "primary_language" in i['href']: mov_language.append(i.text) if soup.findAll('div', "ratingValue"): for r in soup.findAll('div', "ratingValue"): mov_rating = r.strong['title'] else: mov_rating = 'Not available' await e.edit('<a href=' + poster + '>&#8203;</a>' '<b>Title : </b><code>' + mov_title + '</code>\n<code>' + mov_details + '</code>\n<b>Rating : </b><code>' + mov_rating + '</code>\n<b>Country : </b><code>' + mov_country[0] + '</code>\n<b>Language : </b><code>' + mov_language[0] + '</code>\n<b>Director : </b><code>' + director + '</code>\n<b>Writer : </b><code>' + writer + '</code>\n<b>Stars : </b><code>' + stars + '</code>\n<b>IMDB Url : </b>' + mov_link + '\n<b>Story Line : </b>' + story_line, link_preview=True, parse_mode='HTML') except IndexError: await e.edit("Plox enter **Valid movie name** kthx") @register(outgoing=True, pattern=r"^.trt(?: |$)([\s\S]*)") async def translateme(trans): translator = Translator() textx = await trans.get_reply_message() message = trans.pattern_match.group(1) if message: pass elif textx: message = textx.text else: await trans.edit("`Give a text or reply to a message to translate!`") return try: reply_text = translator.translate(deEmojify(message), dest=TRT_LANG) except ValueError: await trans.edit("Invalid destination language.") return source_lan = LANGUAGES[f'{reply_text.src.lower()}'] transl_lan = LANGUAGES[f'{reply_text.dest.lower()}'] reply_text = f"From **{source_lan.title()}**\nTo **{transl_lan.title()}:**\n\n{reply_text.text}" await trans.edit(reply_text) if BOTLOG: await trans.client.send_message( BOTLOG_CHATID, f"Translated some {source_lan.title()} stuff to {transl_lan.title()} just now.", ) @register(pattern="^.lang (trt|tts) (.*)", outgoing=True) async def lang(value): util = value.pattern_match.group(1).lower() if util == "trt": scraper = "Translator" global TRT_LANG arg = value.pattern_match.group(2).lower() if arg in LANGUAGES: TRT_LANG = arg LANG = LANGUAGES[arg] else: await value.edit( f"`Invalid Language code !!`\n`Available language codes for TRT`:\n\n`{LANGUAGES}`" ) return elif util == "tts": scraper = "Text to Speech" global TTS_LANG arg = value.pattern_match.group(2).lower() if arg in tts_langs(): TTS_LANG = arg LANG = tts_langs()[arg] else: await value.edit( f"`Invalid Language code !!`\n`Available language codes for TTS`:\n\n`{tts_langs()}`" ) return await value.edit(f"`Language for {scraper} changed to {LANG.title()}.`") if BOTLOG: await value.client.send_message( BOTLOG_CHATID, f"`Language for {scraper} changed to {LANG.title()}.`") @register(outgoing=True, pattern="^.yt (.*)") async def yt_search(video_q): query = video_q.pattern_match.group(1) result = '' if not YOUTUBE_API_KEY: await video_q.edit( "`Error: YouTube API key missing! Add it to environment vars or config.env.`" ) return await video_q.edit("```Processing...```") full_response = await youtube_search(query) videos_json = full_response[1] for video in videos_json: title = f"{unescape(video['snippet']['title'])}" link = f"https://youtu.be/{video['id']['videoId']}" result += f"{title}\n{link}\n\n" reply_text = f"**Search Query:**\n`{query}`\n\n**Results:**\n\n{result}" await video_q.edit(reply_text) async def youtube_search(query, order="relevance", token=None, location=None, location_radius=None): youtube = build('youtube', 'v3', developerKey=YOUTUBE_API_KEY, cache_discovery=False) search_response = youtube.search().list( q=query, type="video", pageToken=token, order=order, part="id,snippet", maxResults=10, location=location, locationRadius=location_radius).execute() videos = [] for search_result in search_response.get("items", []): if search_result["id"]["kind"] == "youtube#video": videos.append(search_result) try: nexttok = search_response["nextPageToken"] return (nexttok, videos) except HttpError: nexttok = "last_page" return (nexttok, videos) except KeyError: nexttok = "KeyError, try again." return (nexttok, videos) @register(outgoing=True, pattern=r"^.rip(audio|video) (.*)") async def download_video(v_url): url = v_url.pattern_match.group(2) type = v_url.pattern_match.group(1).lower() await v_url.edit("`Preparing to download...`") if type == "audio": opts = { 'format': 'bestaudio', 'addmetadata': True, 'key': 'FFmpegMetadata', 'writethumbnail': True, 'prefer_ffmpeg': True, 'geo_bypass': True, 'nocheckcertificate': True, 'postprocessors': [{ 'key': 'FFmpegExtractAudio', 'preferredcodec': 'mp3', 'preferredquality': '320', }], 'outtmpl': '%(id)s.mp3', 'quiet': True, 'logtostderr': False } video = False song = True elif type == "video": opts = { 'format': 'best', 'addmetadata': True, 'key': 'FFmpegMetadata', 'prefer_ffmpeg': True, 'geo_bypass': True, 'nocheckcertificate': True, 'postprocessors': [{ 'key': 'FFmpegVideoConvertor', 'preferedformat': 'mp4' }], 'outtmpl': '%(id)s.mp4', 'logtostderr': False, 'quiet': True } song = False video = True try: await v_url.edit("`Fetching data, please wait..`") with YoutubeDL(opts) as rip: rip_data = rip.extract_info(url) except DownloadError as DE: await v_url.edit(f"`{str(DE)}`") return except ContentTooShortError: await v_url.edit("`The download content was too short.`") return except GeoRestrictedError: await v_url.edit( "`Video is not available from your geographic location due to geographic restrictions imposed by a website.`" ) return except MaxDownloadsReached: await v_url.edit("`Max-downloads limit has been reached.`") return except PostProcessingError: await v_url.edit("`There was an error during post processing.`") return except UnavailableVideoError: await v_url.edit("`Media is not available in the requested format.`") return except XAttrMetadataError as XAME: await v_url.edit(f"`{XAME.code}: {XAME.msg}\n{XAME.reason}`") return except ExtractorError: await v_url.edit("`There was an error during info extraction.`") return except Exception as e: await v_url.edit(f"{str(type(e)): {str(e)}}") return c_time = time.time() if song: await v_url.edit(f"`Preparing to upload song:`\ \n**{rip_data['title']}**\ \nby __{rip_data['uploader']}__") await v_url.client.send_file( v_url.chat_id, f"{rip_data['id']}.mp3", supports_streaming=True, attributes=[ DocumentAttributeAudio(duration=int(rip_data['duration']), title=str(rip_data['title']), performer=str(rip_data['uploader'])) ], progress_callback=lambda d, t: asyncio.get_event_loop( ).create_task( progress(d, t, v_url, c_time, "Uploading..", f"{rip_data['title']}.mp3"))) os.remove(f"{rip_data['id']}.mp3") await v_url.delete() elif video: await v_url.edit(f"`Preparing to upload video:`\ \n**{rip_data['title']}**\ \nby __{rip_data['uploader']}__") await v_url.client.send_file( v_url.chat_id, f"{rip_data['id']}.mp4", supports_streaming=True, caption=rip_data['title'], progress_callback=lambda d, t: asyncio.get_event_loop( ).create_task( progress(d, t, v_url, c_time, "Uploading..", f"{rip_data['title']}.mp4"))) os.remove(f"{rip_data['id']}.mp4") await v_url.delete() def deEmojify(inputString): return get_emoji_regexp().sub(u'', inputString) CMD_HELP.update({ 'img': '.img <search_query>\ \nUsage: Does an image search on Google and shows 5 images.' }) CMD_HELP.update({ 'currency': '.currency <amount> <from> <to>\ \nUsage: Converts various currencies for you.' }) CMD_HELP.update({ 'carbon': '.carbon <text> [or reply]\ \nUsage: Beautify your code using carbon.now.sh\nUse .crblang <text> to set language for your code.' }) CMD_HELP.update( {'google': '.google <query>\ \nUsage: Does a search on Google.'}) CMD_HELP.update( {'wiki': '.wiki <query>\ \nUsage: Does a search on Wikipedia.'}) CMD_HELP.update( {'ud': '.ud <query>\ \nUsage: Does a search on Urban Dictionary.'}) CMD_HELP.update({ 'tts': '.tts <text> [or reply]\ \nUsage: Translates text to speech for the language which is set.\nUse .lang tts <language code> to set language for tts. (Default is English.)' }) CMD_HELP.update({ 'trt': '.trt <text> [or reply]\ \nUsage: Translates text to the language which is set.\nUse .lang trt <language code> to set language for trt. (Default is English)' }) CMD_HELP.update({'yt': '.yt <text>\ \nUsage: Does a YouTube search.'}) CMD_HELP.update( {"imdb": ".imdb <movie-name>\nShows movie info and other stuff."}) CMD_HELP.update({ 'rip': '.ripaudio <url> or ripvideo <url>\ \nUsage: Download videos and songs from YouTube (and [many other sites](https://ytdl-org.github.io/youtube-dl/supportedsites.html)).' })
true
true
1c34067ecf84e3d35f17b9865cf821ee9efe0073
7,473
py
Python
account/tests/test_password.py
AHDCreative/django_user_accounts
5ab37c5298123189a29fb4c7048ea6a69e2509ff
[ "MIT" ]
null
null
null
account/tests/test_password.py
AHDCreative/django_user_accounts
5ab37c5298123189a29fb4c7048ea6a69e2509ff
[ "MIT" ]
null
null
null
account/tests/test_password.py
AHDCreative/django_user_accounts
5ab37c5298123189a29fb4c7048ea6a69e2509ff
[ "MIT" ]
null
null
null
import datetime import django from django.contrib.auth.hashers import check_password, make_password from django.contrib.auth.models import User from django.test import TestCase, modify_settings, override_settings import pytz from account.compat import reverse from account.models import PasswordExpiry, PasswordHistory from account.utils import check_password_expired def middleware_kwarg(value): if django.VERSION >= (1, 10): kwarg = "MIDDLEWARE" else: kwarg = "MIDDLEWARE_CLASSES" return {kwarg: value} @override_settings( ACCOUNT_PASSWORD_USE_HISTORY=True ) @modify_settings( **middleware_kwarg({ "append": "account.middleware.ExpiredPasswordMiddleware" }) ) class PasswordExpirationTestCase(TestCase): def setUp(self): self.username = "user1" self.email = "user1@example.com" self.password = "changeme" self.user = User.objects.create_user( self.username, email=self.email, password=self.password, ) # create PasswordExpiry for user self.expiry = PasswordExpiry.objects.create( user=self.user, expiry=60, # password expires after sixty seconds ) # create PasswordHistory for user self.history = PasswordHistory.objects.create( user=self.user, password=make_password(self.password) ) def test_signup(self): """ Ensure new user has one PasswordHistory and no PasswordExpiry. """ email = "foobar@example.com" password = "bar" post_data = { "username": "foo", "password": password, "password_confirm": password, "email": email, } response = self.client.post(reverse("account_signup"), post_data) self.assertEqual(response.status_code, 302) user = User.objects.get(email=email) self.assertFalse(hasattr(user, "password_expiry")) latest_history = user.password_history.latest("timestamp") self.assertTrue(latest_history) # verify password is not expired self.assertFalse(check_password_expired(user)) # verify raw password matches encrypted password in history self.assertTrue(check_password(password, latest_history.password)) def test_get_not_expired(self): """ Ensure authenticated user can retrieve account settings page without "password change" redirect. """ self.client.login(username=self.username, password=self.password) # get account settings page (could be any application page) response = self.client.get(reverse("account_settings")) self.assertEquals(response.status_code, 200) def test_get_expired(self): """ Ensure authenticated user is redirected to change password when retrieving account settings page if password is expired. """ # set PasswordHistory timestamp in past so password is expired. self.history.timestamp = datetime.datetime.now(tz=pytz.UTC) - datetime.timedelta(days=1, seconds=self.expiry.expiry) self.history.save() self.client.login(username=self.username, password=self.password) # get account settings page (could be any application page) url_name = "account_settings" response = self.client.get(reverse(url_name)) # verify desired page is set as "?next=" in redirect URL redirect_url = "{}?next={}".format(reverse("account_password"), url_name) self.assertRedirects(response, redirect_url) def test_password_expiration_reset(self): """ Ensure changing password results in new PasswordHistory. """ history_count = self.user.password_history.count() # get login self.client.login(username=self.username, password=self.password) # post new password to reset PasswordHistory new_password = "lynyrdskynyrd" post_data = { "password_current": self.password, "password_new": new_password, "password_new_confirm": new_password, } self.client.post( reverse("account_password"), post_data ) # Should see one more history entry for this user self.assertEquals(self.user.password_history.count(), history_count + 1) latest = PasswordHistory.objects.latest("timestamp") self.assertTrue(latest != self.history) self.assertTrue(latest.timestamp > self.history.timestamp) @modify_settings( **middleware_kwarg({ "append": "account.middleware.ExpiredPasswordMiddleware" }) ) class ExistingUserNoHistoryTestCase(TestCase): """ Tests where user has no PasswordHistory. """ def setUp(self): self.username = "user1" self.email = "user1@example.com" self.password = "changeme" self.user = User.objects.create_user( self.username, email=self.email, password=self.password, ) def test_get_no_history(self): """ Ensure authenticated user without password history can retrieve account settings page without "password change" redirect. """ self.client.login(username=self.username, password=self.password) with override_settings( ACCOUNT_PASSWORD_USE_HISTORY=True ): # get account settings page (could be any application page) response = self.client.get(reverse("account_settings")) self.assertEquals(response.status_code, 200) def test_password_expiration_reset(self): """ Ensure changing password results in new PasswordHistory, even when no PasswordHistory exists. """ history_count = self.user.password_history.count() # get login self.client.login(username=self.username, password=self.password) # post new password to reset PasswordHistory new_password = "lynyrdskynyrd" post_data = { "password_current": self.password, "password_new": new_password, "password_new_confirm": new_password, } with override_settings( ACCOUNT_PASSWORD_USE_HISTORY=True ): self.client.post( reverse("account_password"), post_data ) # Should see one more history entry for this user self.assertEquals(self.user.password_history.count(), history_count + 1) def test_password_reset(self): """ Ensure changing password results in NO new PasswordHistory when ACCOUNT_PASSWORD_USE_HISTORY == False. """ # get login self.client.login(username=self.username, password=self.password) # post new password to reset PasswordHistory new_password = "lynyrdskynyrd" post_data = { "password_current": self.password, "password_new": new_password, "password_new_confirm": new_password, } with override_settings( ACCOUNT_PASSWORD_USE_HISTORY=False ): self.client.post( reverse("account_password"), post_data ) # history count should be zero self.assertEquals(self.user.password_history.count(), 0)
34.597222
124
0.63977
import datetime import django from django.contrib.auth.hashers import check_password, make_password from django.contrib.auth.models import User from django.test import TestCase, modify_settings, override_settings import pytz from account.compat import reverse from account.models import PasswordExpiry, PasswordHistory from account.utils import check_password_expired def middleware_kwarg(value): if django.VERSION >= (1, 10): kwarg = "MIDDLEWARE" else: kwarg = "MIDDLEWARE_CLASSES" return {kwarg: value} @override_settings( ACCOUNT_PASSWORD_USE_HISTORY=True ) @modify_settings( **middleware_kwarg({ "append": "account.middleware.ExpiredPasswordMiddleware" }) ) class PasswordExpirationTestCase(TestCase): def setUp(self): self.username = "user1" self.email = "user1@example.com" self.password = "changeme" self.user = User.objects.create_user( self.username, email=self.email, password=self.password, ) self.expiry = PasswordExpiry.objects.create( user=self.user, expiry=60, ) self.history = PasswordHistory.objects.create( user=self.user, password=make_password(self.password) ) def test_signup(self): email = "foobar@example.com" password = "bar" post_data = { "username": "foo", "password": password, "password_confirm": password, "email": email, } response = self.client.post(reverse("account_signup"), post_data) self.assertEqual(response.status_code, 302) user = User.objects.get(email=email) self.assertFalse(hasattr(user, "password_expiry")) latest_history = user.password_history.latest("timestamp") self.assertTrue(latest_history) self.assertFalse(check_password_expired(user)) self.assertTrue(check_password(password, latest_history.password)) def test_get_not_expired(self): self.client.login(username=self.username, password=self.password) response = self.client.get(reverse("account_settings")) self.assertEquals(response.status_code, 200) def test_get_expired(self): self.history.timestamp = datetime.datetime.now(tz=pytz.UTC) - datetime.timedelta(days=1, seconds=self.expiry.expiry) self.history.save() self.client.login(username=self.username, password=self.password) url_name = "account_settings" response = self.client.get(reverse(url_name)) redirect_url = "{}?next={}".format(reverse("account_password"), url_name) self.assertRedirects(response, redirect_url) def test_password_expiration_reset(self): history_count = self.user.password_history.count() self.client.login(username=self.username, password=self.password) new_password = "lynyrdskynyrd" post_data = { "password_current": self.password, "password_new": new_password, "password_new_confirm": new_password, } self.client.post( reverse("account_password"), post_data ) self.assertEquals(self.user.password_history.count(), history_count + 1) latest = PasswordHistory.objects.latest("timestamp") self.assertTrue(latest != self.history) self.assertTrue(latest.timestamp > self.history.timestamp) @modify_settings( **middleware_kwarg({ "append": "account.middleware.ExpiredPasswordMiddleware" }) ) class ExistingUserNoHistoryTestCase(TestCase): def setUp(self): self.username = "user1" self.email = "user1@example.com" self.password = "changeme" self.user = User.objects.create_user( self.username, email=self.email, password=self.password, ) def test_get_no_history(self): self.client.login(username=self.username, password=self.password) with override_settings( ACCOUNT_PASSWORD_USE_HISTORY=True ): response = self.client.get(reverse("account_settings")) self.assertEquals(response.status_code, 200) def test_password_expiration_reset(self): history_count = self.user.password_history.count() self.client.login(username=self.username, password=self.password) new_password = "lynyrdskynyrd" post_data = { "password_current": self.password, "password_new": new_password, "password_new_confirm": new_password, } with override_settings( ACCOUNT_PASSWORD_USE_HISTORY=True ): self.client.post( reverse("account_password"), post_data ) self.assertEquals(self.user.password_history.count(), history_count + 1) def test_password_reset(self): self.client.login(username=self.username, password=self.password) new_password = "lynyrdskynyrd" post_data = { "password_current": self.password, "password_new": new_password, "password_new_confirm": new_password, } with override_settings( ACCOUNT_PASSWORD_USE_HISTORY=False ): self.client.post( reverse("account_password"), post_data ) self.assertEquals(self.user.password_history.count(), 0)
true
true
1c3406c0154dcae2ad9030f6a2382d96e6ce407b
13,130
py
Python
extra_foam/special_suite/tests/test_gotthard.py
ebadkamil/EXtra-foam
8e58143040c788dc70ea98ea5adc1fb63b7cfe0d
[ "BSD-3-Clause" ]
7
2019-11-27T09:31:37.000Z
2022-02-12T21:28:49.000Z
extra_foam/special_suite/tests/test_gotthard.py
ebadkamil/EXtra-foam
8e58143040c788dc70ea98ea5adc1fb63b7cfe0d
[ "BSD-3-Clause" ]
172
2019-12-03T07:56:02.000Z
2022-03-25T15:46:45.000Z
extra_foam/special_suite/tests/test_gotthard.py
ebadkamil/EXtra-foam
8e58143040c788dc70ea98ea5adc1fb63b7cfe0d
[ "BSD-3-Clause" ]
9
2019-11-27T09:32:38.000Z
2022-01-05T09:56:10.000Z
import unittest from unittest.mock import MagicMock, patch, PropertyMock from collections import Counter import pytest import numpy as np from xarray import DataArray from PyQt5.QtCore import Qt from PyQt5.QtTest import QSignalSpy, QTest from extra_foam.pipeline.tests import _RawDataMixin from extra_foam.special_suite import logger, mkQApp from extra_foam.special_suite.gotthard_proc import GotthardProcessor from extra_foam.special_suite.gotthard_w import ( GotthardWindow, GotthardImageView, GotthardAvgPlot, GotthardPulsePlot, GotthardHist ) from extra_foam.special_suite.special_analysis_base import ( ProcessingError ) from . import _SpecialSuiteWindowTestBase, _SpecialSuiteProcessorTestBase app = mkQApp() logger.setLevel('INFO') class TestGotthardWindow(_SpecialSuiteWindowTestBase): _window_type = GotthardWindow @staticmethod def data4visualization(n_pulses=4): """Override.""" return { "x": None, "spectrum": np.arange(10 * n_pulses).reshape(n_pulses, 10), "spectrum_ma": np.arange(10 * n_pulses).reshape(n_pulses, 10), "spectrum_mean": np.arange(10), "spectrum_ma_mean": np.arange(10), "poi_index": 0, "hist": (np.arange(5), np.arange(5), 1, 1, 1), } def testWindow(self): win = self._win self.assertEqual(4, len(win._plot_widgets_st)) counter = Counter() for key in win._plot_widgets_st: counter[key.__class__] += 1 self.assertEqual(1, counter[GotthardImageView]) self.assertEqual(1, counter[GotthardAvgPlot]) self.assertEqual(1, counter[GotthardPulsePlot]) self.assertEqual(1, counter[GotthardHist]) self._check_update_plots() def testCtrl(self): from extra_foam.special_suite.gotthard_w import _DEFAULT_N_BINS, _DEFAULT_BIN_RANGE win = self._win ctrl_widget = win._ctrl_widget_st proc = win._worker_st # test default values self.assertTrue(proc._output_channel) self.assertEqual(slice(None, None), proc._pulse_slicer) self.assertEqual(0, proc._poi_index) self.assertEqual(1, proc.__class__._raw_ma.window) self.assertEqual(0, proc._scale) self.assertEqual(0, proc._offset) self.assertTupleEqual(tuple(float(v) for v in _DEFAULT_BIN_RANGE.split(',')), proc._bin_range) self.assertEqual(int(_DEFAULT_N_BINS), proc._n_bins) self.assertFalse(proc._hist_over_ma) # test set new values widget = ctrl_widget.output_ch_le widget.clear() QTest.keyClicks(widget, "new/output/channel") QTest.keyPress(widget, Qt.Key_Enter) self.assertEqual("new/output/channel", proc._output_channel) widget = ctrl_widget.pulse_slicer_le widget.clear() QTest.keyClicks(widget, "::2") QTest.keyPress(widget, Qt.Key_Enter) self.assertEqual(slice(None, None, 2), proc._pulse_slicer) widget = ctrl_widget.poi_index_le widget.clear() QTest.keyClicks(widget, "120") QTest.keyPress(widget, Qt.Key_Enter) self.assertEqual(0, proc._poi_index) # maximum is 119 and one can still type "120" widget.clear() QTest.keyClicks(widget, "119") QTest.keyPress(widget, Qt.Key_Enter) self.assertEqual(119, proc._poi_index) widget = ctrl_widget.ma_window_le widget.clear() QTest.keyClicks(widget, "9") QTest.keyPress(widget, Qt.Key_Enter) self.assertEqual(9, proc.__class__._raw_ma.window) widget = ctrl_widget.scale_le widget.clear() QTest.keyClicks(widget, "0.002") QTest.keyPress(widget, Qt.Key_Enter) self.assertEqual(0.002, proc._scale) widget.clear() QTest.keyClicks(widget, "-1") QTest.keyPress(widget, Qt.Key_Enter) self.assertEqual(1, proc._scale) # cannot enter '-' widget = ctrl_widget.offset_le widget.clear() QTest.keyClicks(widget, "-0.18") QTest.keyPress(widget, Qt.Key_Enter) self.assertEqual(-0.18, proc._offset) widget = ctrl_widget.bin_range_le widget.clear() QTest.keyClicks(widget, "-1.0, 1.0") QTest.keyPress(widget, Qt.Key_Enter) self.assertTupleEqual((-1.0, 1.0), proc._bin_range) widget = ctrl_widget.n_bins_le widget.clear() QTest.keyClicks(widget, "1000") QTest.keyPress(widget, Qt.Key_Enter) self.assertEqual(100, proc._n_bins) # maximum is 999 and one can not put the 3rd 0 in widget.clear() QTest.keyClicks(widget, "999") QTest.keyPress(widget, Qt.Key_Enter) self.assertEqual(999, proc._n_bins) ctrl_widget.hist_over_ma_cb.setChecked(True) self.assertTrue(proc._hist_over_ma) class TestGotthardProcessor(_RawDataMixin, _SpecialSuiteProcessorTestBase): @pytest.fixture(autouse=True) def setUp(self): self._proc = GotthardProcessor(object(), object()) self._proc._output_channel = "gotthard:output" self._adc = np.random.randint(0, 100, size=(4, 4), dtype=np.uint16) def _get_data(self, tid, times=1): # data, meta return self._gen_data(tid, { "gotthard:output": [ ("data.adc", times * self._adc), ("data.3d", np.ones((4, 2, 2))) ]}) def testPreProcessing(self): proc = self._proc data = self._get_data(12345) with pytest.raises(ProcessingError, match="actual 3D"): with patch.object(GotthardProcessor, "_ppt", new_callable=PropertyMock, create=True, return_value="data.3d"): proc.process(data) with pytest.raises(ProcessingError, match="out of boundary"): proc._poi_index = 100 processed = proc.process(data) assert processed is None # test not raise proc._poi_index = 3 proc.process(data) with pytest.raises(ProcessingError, match="out of boundary"): # test with slicer proc._pulse_slicer = slice(None, None, 2) proc.process(data) @patch("extra_foam.special_suite.special_analysis_base.QThreadWorker._loadRunDirectoryST") def testLoadDarkRun(self, load_run): proc = self._proc load_run.return_value = None # nothing should happen proc.onLoadDarkRun("run/path") data_collection = MagicMock() load_run.return_value = data_collection with patch.object(proc.log, "error") as error: # get_array returns a wrong shape data_collection.get_array.return_value = DataArray(np.random.randn(4, 3)) proc.onLoadDarkRun("run/path") error.assert_called_once() assert "Data must be a 3D array" in error.call_args[0][0] error.reset_mock() # get_array returns a correct shape data_collection.get_array.return_value = DataArray(np.random.randn(4, 3, 2)) with patch.object(proc.log, "info") as info: proc.onLoadDarkRun("run/path") info.assert_called_once() assert "Found dark data with shape" in info.call_args[0][0] error.assert_not_called() def testProcessingWhenRecordingDark(self): from extra_foam.special_suite.gotthard_proc import _PIXEL_DTYPE proc = self._proc assert 2147483647 == proc.__class__._dark_ma.window proc._recording_dark_st = True proc._subtract_dark_st = True # take no effect proc._poi_index = 0 adc_gt = self._adc.astype(_PIXEL_DTYPE) adc_gt2 = 2.0 * self._adc adc_gt_avg = 1.5 * self._adc # 1st train processed = proc.process(self._get_data(12345)) np.testing.assert_array_almost_equal(adc_gt, proc._dark_ma) np.testing.assert_array_almost_equal(np.mean(adc_gt, axis=0), proc._dark_mean_ma) assert 0 == processed["poi_index"] np.testing.assert_array_almost_equal(adc_gt, processed["spectrum"]) np.testing.assert_array_almost_equal(adc_gt, processed["spectrum_ma"]) np.testing.assert_array_almost_equal(np.mean(adc_gt, axis=0), processed["spectrum_mean"]) np.testing.assert_array_almost_equal(np.mean(adc_gt, axis=0), processed["spectrum_ma_mean"]) assert np.mean(adc_gt) == processed["hist"][2] # 2nd train processed = proc.process(self._get_data(12346, 2)) np.testing.assert_array_almost_equal(adc_gt_avg, proc._dark_ma) np.testing.assert_array_almost_equal(np.mean(adc_gt_avg, axis=0), proc._dark_mean_ma) assert 0 == processed["poi_index"] np.testing.assert_array_almost_equal(adc_gt2, processed["spectrum"]) np.testing.assert_array_almost_equal(adc_gt_avg, processed["spectrum_ma"]) np.testing.assert_array_almost_equal(np.mean(adc_gt2, axis=0), processed["spectrum_mean"]) np.testing.assert_array_almost_equal(np.mean(adc_gt_avg, axis=0), processed["spectrum_ma_mean"]) assert np.mean(adc_gt2) == processed["hist"][2] # 3nd train proc._hist_over_ma = True processed = proc.process(self._get_data(12347, 3)) np.testing.assert_array_almost_equal(adc_gt2, proc._dark_ma) np.testing.assert_array_almost_equal(np.mean(adc_gt2, axis=0), proc._dark_mean_ma) assert np.mean(adc_gt2) == processed["hist"][2] # reset proc.reset() assert proc._dark_ma is None @pytest.mark.parametrize("subtract_dark", [(True, ), (False,)]) def testProcessing(self, subtract_dark): from extra_foam.special_suite.gotthard_proc import _PIXEL_DTYPE proc = self._proc proc._recording_dark = False proc._poi_index = 1 proc._scale = 0.1 proc._offset = 0.2 proc._subtract_dark = subtract_dark offset = np.ones(self._adc.shape[1]).astype(np.float32) proc._dark_mean_ma = offset proc._hist_over_ma = False adc_gt = self._adc.astype(_PIXEL_DTYPE) adc_gt2 = 2.0 * self._adc adc_gt_avg = 1.5 * self._adc if subtract_dark: adc_gt -= offset adc_gt2 -= offset adc_gt_avg -= offset # 1st train processed = proc.process(self._get_data(12345)) self._check_processed_data_structure(processed) assert 1 == processed["poi_index"] np.testing.assert_array_almost_equal(adc_gt, processed["spectrum"]) np.testing.assert_array_almost_equal(adc_gt, processed["spectrum_ma"]) np.testing.assert_array_almost_equal(np.mean(adc_gt, axis=0), processed["spectrum_mean"]) np.testing.assert_array_almost_equal(np.mean(adc_gt, axis=0), processed["spectrum_ma_mean"]) assert np.mean(adc_gt) == processed["hist"][2] # 2nd train proc.__class__._raw_ma.window = 3 processed = proc.process(self._get_data(12346, 2)) assert 1 == processed["poi_index"] np.testing.assert_array_almost_equal(adc_gt2, processed["spectrum"]) np.testing.assert_array_almost_equal(adc_gt_avg, processed["spectrum_ma"]) np.testing.assert_array_almost_equal(np.mean(adc_gt2, axis=0), processed["spectrum_mean"]) np.testing.assert_array_almost_equal(np.mean(adc_gt_avg, axis=0), processed["spectrum_ma_mean"]) assert np.mean(adc_gt2) == processed["hist"][2] # 3nd train proc._hist_over_ma = True processed = proc.process(self._get_data(12347, 3)) assert np.mean(adc_gt2) == processed["hist"][2] # reset proc.reset() assert proc._raw_ma is None def testCalibration(self): proc = self._proc processed = proc.process(self._get_data(12345)) assert processed["x"] is None proc._scale = 0.1 proc._offset = 0.2 processed = proc.process(self._get_data(12345)) np.testing.assert_array_almost_equal(np.arange(len(self._adc)) * 0.1 - 0.2, processed['x']) def testPulseSlicerChange(self): proc = self._proc del proc._dark_ma proc._dark_mean_ma = None proc._pulse_slicer = slice(None, None) proc.onPulseSlicerChanged([None, 4]) assert proc._dark_mean_ma is None proc._dark_ma = np.random.randn(4, 2) proc.onPulseSlicerChanged([None, None, 2]) # test _dark_mean_ma was re-calculated np.testing.assert_array_almost_equal(np.mean(proc._dark_ma[::2], axis=0), proc._dark_mean_ma) def testRemoveDark(self): proc = self._proc proc._dark_ma = np.ones((2, 2)) proc._dark_mean_ma = np.ones((2, 2)) proc.onRemoveDark() assert proc._dark_ma is None assert proc._dark_mean_ma is None def _check_processed_data_structure(self, ret): """Override.""" data_gt = TestGotthardWindow.data4visualization().keys() assert set(ret.keys()) == set(data_gt)
37.947977
104
0.651942
import unittest from unittest.mock import MagicMock, patch, PropertyMock from collections import Counter import pytest import numpy as np from xarray import DataArray from PyQt5.QtCore import Qt from PyQt5.QtTest import QSignalSpy, QTest from extra_foam.pipeline.tests import _RawDataMixin from extra_foam.special_suite import logger, mkQApp from extra_foam.special_suite.gotthard_proc import GotthardProcessor from extra_foam.special_suite.gotthard_w import ( GotthardWindow, GotthardImageView, GotthardAvgPlot, GotthardPulsePlot, GotthardHist ) from extra_foam.special_suite.special_analysis_base import ( ProcessingError ) from . import _SpecialSuiteWindowTestBase, _SpecialSuiteProcessorTestBase app = mkQApp() logger.setLevel('INFO') class TestGotthardWindow(_SpecialSuiteWindowTestBase): _window_type = GotthardWindow @staticmethod def data4visualization(n_pulses=4): return { "x": None, "spectrum": np.arange(10 * n_pulses).reshape(n_pulses, 10), "spectrum_ma": np.arange(10 * n_pulses).reshape(n_pulses, 10), "spectrum_mean": np.arange(10), "spectrum_ma_mean": np.arange(10), "poi_index": 0, "hist": (np.arange(5), np.arange(5), 1, 1, 1), } def testWindow(self): win = self._win self.assertEqual(4, len(win._plot_widgets_st)) counter = Counter() for key in win._plot_widgets_st: counter[key.__class__] += 1 self.assertEqual(1, counter[GotthardImageView]) self.assertEqual(1, counter[GotthardAvgPlot]) self.assertEqual(1, counter[GotthardPulsePlot]) self.assertEqual(1, counter[GotthardHist]) self._check_update_plots() def testCtrl(self): from extra_foam.special_suite.gotthard_w import _DEFAULT_N_BINS, _DEFAULT_BIN_RANGE win = self._win ctrl_widget = win._ctrl_widget_st proc = win._worker_st self.assertTrue(proc._output_channel) self.assertEqual(slice(None, None), proc._pulse_slicer) self.assertEqual(0, proc._poi_index) self.assertEqual(1, proc.__class__._raw_ma.window) self.assertEqual(0, proc._scale) self.assertEqual(0, proc._offset) self.assertTupleEqual(tuple(float(v) for v in _DEFAULT_BIN_RANGE.split(',')), proc._bin_range) self.assertEqual(int(_DEFAULT_N_BINS), proc._n_bins) self.assertFalse(proc._hist_over_ma) widget = ctrl_widget.output_ch_le widget.clear() QTest.keyClicks(widget, "new/output/channel") QTest.keyPress(widget, Qt.Key_Enter) self.assertEqual("new/output/channel", proc._output_channel) widget = ctrl_widget.pulse_slicer_le widget.clear() QTest.keyClicks(widget, "::2") QTest.keyPress(widget, Qt.Key_Enter) self.assertEqual(slice(None, None, 2), proc._pulse_slicer) widget = ctrl_widget.poi_index_le widget.clear() QTest.keyClicks(widget, "120") QTest.keyPress(widget, Qt.Key_Enter) self.assertEqual(0, proc._poi_index) widget.clear() QTest.keyClicks(widget, "119") QTest.keyPress(widget, Qt.Key_Enter) self.assertEqual(119, proc._poi_index) widget = ctrl_widget.ma_window_le widget.clear() QTest.keyClicks(widget, "9") QTest.keyPress(widget, Qt.Key_Enter) self.assertEqual(9, proc.__class__._raw_ma.window) widget = ctrl_widget.scale_le widget.clear() QTest.keyClicks(widget, "0.002") QTest.keyPress(widget, Qt.Key_Enter) self.assertEqual(0.002, proc._scale) widget.clear() QTest.keyClicks(widget, "-1") QTest.keyPress(widget, Qt.Key_Enter) self.assertEqual(1, proc._scale) widget = ctrl_widget.offset_le widget.clear() QTest.keyClicks(widget, "-0.18") QTest.keyPress(widget, Qt.Key_Enter) self.assertEqual(-0.18, proc._offset) widget = ctrl_widget.bin_range_le widget.clear() QTest.keyClicks(widget, "-1.0, 1.0") QTest.keyPress(widget, Qt.Key_Enter) self.assertTupleEqual((-1.0, 1.0), proc._bin_range) widget = ctrl_widget.n_bins_le widget.clear() QTest.keyClicks(widget, "1000") QTest.keyPress(widget, Qt.Key_Enter) self.assertEqual(100, proc._n_bins) widget.clear() QTest.keyClicks(widget, "999") QTest.keyPress(widget, Qt.Key_Enter) self.assertEqual(999, proc._n_bins) ctrl_widget.hist_over_ma_cb.setChecked(True) self.assertTrue(proc._hist_over_ma) class TestGotthardProcessor(_RawDataMixin, _SpecialSuiteProcessorTestBase): @pytest.fixture(autouse=True) def setUp(self): self._proc = GotthardProcessor(object(), object()) self._proc._output_channel = "gotthard:output" self._adc = np.random.randint(0, 100, size=(4, 4), dtype=np.uint16) def _get_data(self, tid, times=1): return self._gen_data(tid, { "gotthard:output": [ ("data.adc", times * self._adc), ("data.3d", np.ones((4, 2, 2))) ]}) def testPreProcessing(self): proc = self._proc data = self._get_data(12345) with pytest.raises(ProcessingError, match="actual 3D"): with patch.object(GotthardProcessor, "_ppt", new_callable=PropertyMock, create=True, return_value="data.3d"): proc.process(data) with pytest.raises(ProcessingError, match="out of boundary"): proc._poi_index = 100 processed = proc.process(data) assert processed is None proc._poi_index = 3 proc.process(data) with pytest.raises(ProcessingError, match="out of boundary"): proc._pulse_slicer = slice(None, None, 2) proc.process(data) @patch("extra_foam.special_suite.special_analysis_base.QThreadWorker._loadRunDirectoryST") def testLoadDarkRun(self, load_run): proc = self._proc load_run.return_value = None proc.onLoadDarkRun("run/path") data_collection = MagicMock() load_run.return_value = data_collection with patch.object(proc.log, "error") as error: data_collection.get_array.return_value = DataArray(np.random.randn(4, 3)) proc.onLoadDarkRun("run/path") error.assert_called_once() assert "Data must be a 3D array" in error.call_args[0][0] error.reset_mock() data_collection.get_array.return_value = DataArray(np.random.randn(4, 3, 2)) with patch.object(proc.log, "info") as info: proc.onLoadDarkRun("run/path") info.assert_called_once() assert "Found dark data with shape" in info.call_args[0][0] error.assert_not_called() def testProcessingWhenRecordingDark(self): from extra_foam.special_suite.gotthard_proc import _PIXEL_DTYPE proc = self._proc assert 2147483647 == proc.__class__._dark_ma.window proc._recording_dark_st = True proc._subtract_dark_st = True proc._poi_index = 0 adc_gt = self._adc.astype(_PIXEL_DTYPE) adc_gt2 = 2.0 * self._adc adc_gt_avg = 1.5 * self._adc processed = proc.process(self._get_data(12345)) np.testing.assert_array_almost_equal(adc_gt, proc._dark_ma) np.testing.assert_array_almost_equal(np.mean(adc_gt, axis=0), proc._dark_mean_ma) assert 0 == processed["poi_index"] np.testing.assert_array_almost_equal(adc_gt, processed["spectrum"]) np.testing.assert_array_almost_equal(adc_gt, processed["spectrum_ma"]) np.testing.assert_array_almost_equal(np.mean(adc_gt, axis=0), processed["spectrum_mean"]) np.testing.assert_array_almost_equal(np.mean(adc_gt, axis=0), processed["spectrum_ma_mean"]) assert np.mean(adc_gt) == processed["hist"][2] processed = proc.process(self._get_data(12346, 2)) np.testing.assert_array_almost_equal(adc_gt_avg, proc._dark_ma) np.testing.assert_array_almost_equal(np.mean(adc_gt_avg, axis=0), proc._dark_mean_ma) assert 0 == processed["poi_index"] np.testing.assert_array_almost_equal(adc_gt2, processed["spectrum"]) np.testing.assert_array_almost_equal(adc_gt_avg, processed["spectrum_ma"]) np.testing.assert_array_almost_equal(np.mean(adc_gt2, axis=0), processed["spectrum_mean"]) np.testing.assert_array_almost_equal(np.mean(adc_gt_avg, axis=0), processed["spectrum_ma_mean"]) assert np.mean(adc_gt2) == processed["hist"][2] proc._hist_over_ma = True processed = proc.process(self._get_data(12347, 3)) np.testing.assert_array_almost_equal(adc_gt2, proc._dark_ma) np.testing.assert_array_almost_equal(np.mean(adc_gt2, axis=0), proc._dark_mean_ma) assert np.mean(adc_gt2) == processed["hist"][2] proc.reset() assert proc._dark_ma is None @pytest.mark.parametrize("subtract_dark", [(True, ), (False,)]) def testProcessing(self, subtract_dark): from extra_foam.special_suite.gotthard_proc import _PIXEL_DTYPE proc = self._proc proc._recording_dark = False proc._poi_index = 1 proc._scale = 0.1 proc._offset = 0.2 proc._subtract_dark = subtract_dark offset = np.ones(self._adc.shape[1]).astype(np.float32) proc._dark_mean_ma = offset proc._hist_over_ma = False adc_gt = self._adc.astype(_PIXEL_DTYPE) adc_gt2 = 2.0 * self._adc adc_gt_avg = 1.5 * self._adc if subtract_dark: adc_gt -= offset adc_gt2 -= offset adc_gt_avg -= offset processed = proc.process(self._get_data(12345)) self._check_processed_data_structure(processed) assert 1 == processed["poi_index"] np.testing.assert_array_almost_equal(adc_gt, processed["spectrum"]) np.testing.assert_array_almost_equal(adc_gt, processed["spectrum_ma"]) np.testing.assert_array_almost_equal(np.mean(adc_gt, axis=0), processed["spectrum_mean"]) np.testing.assert_array_almost_equal(np.mean(adc_gt, axis=0), processed["spectrum_ma_mean"]) assert np.mean(adc_gt) == processed["hist"][2] proc.__class__._raw_ma.window = 3 processed = proc.process(self._get_data(12346, 2)) assert 1 == processed["poi_index"] np.testing.assert_array_almost_equal(adc_gt2, processed["spectrum"]) np.testing.assert_array_almost_equal(adc_gt_avg, processed["spectrum_ma"]) np.testing.assert_array_almost_equal(np.mean(adc_gt2, axis=0), processed["spectrum_mean"]) np.testing.assert_array_almost_equal(np.mean(adc_gt_avg, axis=0), processed["spectrum_ma_mean"]) assert np.mean(adc_gt2) == processed["hist"][2] proc._hist_over_ma = True processed = proc.process(self._get_data(12347, 3)) assert np.mean(adc_gt2) == processed["hist"][2] proc.reset() assert proc._raw_ma is None def testCalibration(self): proc = self._proc processed = proc.process(self._get_data(12345)) assert processed["x"] is None proc._scale = 0.1 proc._offset = 0.2 processed = proc.process(self._get_data(12345)) np.testing.assert_array_almost_equal(np.arange(len(self._adc)) * 0.1 - 0.2, processed['x']) def testPulseSlicerChange(self): proc = self._proc del proc._dark_ma proc._dark_mean_ma = None proc._pulse_slicer = slice(None, None) proc.onPulseSlicerChanged([None, 4]) assert proc._dark_mean_ma is None proc._dark_ma = np.random.randn(4, 2) proc.onPulseSlicerChanged([None, None, 2]) np.testing.assert_array_almost_equal(np.mean(proc._dark_ma[::2], axis=0), proc._dark_mean_ma) def testRemoveDark(self): proc = self._proc proc._dark_ma = np.ones((2, 2)) proc._dark_mean_ma = np.ones((2, 2)) proc.onRemoveDark() assert proc._dark_ma is None assert proc._dark_mean_ma is None def _check_processed_data_structure(self, ret): data_gt = TestGotthardWindow.data4visualization().keys() assert set(ret.keys()) == set(data_gt)
true
true
1c3406df759000e6ee4b53c4ee71e09130029fa6
3,304
py
Python
openstack/network/v2/certificate.py
IamFive/sdk-python
223b04f90477f7de0f00b3e652d8672ba73271c8
[ "ECL-2.0", "Apache-2.0" ]
null
null
null
openstack/network/v2/certificate.py
IamFive/sdk-python
223b04f90477f7de0f00b3e652d8672ba73271c8
[ "ECL-2.0", "Apache-2.0" ]
null
null
null
openstack/network/v2/certificate.py
IamFive/sdk-python
223b04f90477f7de0f00b3e652d8672ba73271c8
[ "ECL-2.0", "Apache-2.0" ]
null
null
null
# 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 openstack.network import network_service from openstack import resource2 class Certificate(resource2.Resource): resource_key = 'certificate' resources_key = 'certificates' base_path = '/lbaas/certificates' service = network_service.NetworkService() allow_create = True allow_get = True allow_update = True allow_delete = True allow_list = True # SSL certificate ID id = resource2.Body("id") # SSL certificate name. # Value range: a string of 0-64 characters in length, # consisting of Chinese, English letters, numbers, "_" or "-" name = resource2.Body("name") # SSL certificate description. # Value range: A string of 0-128 characters in length. # The string cannot contain two characters, "<" and ">". # Chinese characters must be UTF-8 or unicode encoded description = resource2.Body("description") # Certificate type. # Ranges: # server # client: The value is reserved. It is not enabled yet. # Default: server type = resource2.Body("type") # The domain name signed by the server certificate. # Value range: A string of 0-100 characters in length. # A string can only contain English letters, digits, "-", or ".". # It must begin or end with a letter or number. # This field is valid only when type is server. domain = resource2.Body("domain") # Server-side private key in PEM format. # Format: The private key is in PEM format. # This field is valid only when type is server and is mandatory private_key = resource2.Body("private_key") # Server-side public key in PEM format certificate = resource2.Body("certificate") # creat time create_time = resource2.Body("create_time") # update time update_time = resource2.Body("update_time") def _translate_response(self, response, has_body=True): """Given a KSA response, inflate this instance with its data DELETE operations don't return a body, so only try to work with a body when has_body is True. This method updates attributes that correspond to headers and body on this instance and clears the dirty set. """ if has_body: body = response.json() if self.resource_key and self.resource_key in body and isinstance(body[self.resource_key], dict): body = body[self.resource_key] body = self._filter_component(body, self._body_mapping()) self._body.attributes.update(body) self._body.clean() headers = self._filter_component(response.headers, self._header_mapping()) self._header.attributes.update(headers) self._header.clean()
39.807229
109
0.681901
from openstack.network import network_service from openstack import resource2 class Certificate(resource2.Resource): resource_key = 'certificate' resources_key = 'certificates' base_path = '/lbaas/certificates' service = network_service.NetworkService() allow_create = True allow_get = True allow_update = True allow_delete = True allow_list = True id = resource2.Body("id") name = resource2.Body("name") description = resource2.Body("description") type = resource2.Body("type") domain = resource2.Body("domain") private_key = resource2.Body("private_key") certificate = resource2.Body("certificate") create_time = resource2.Body("create_time") update_time = resource2.Body("update_time") def _translate_response(self, response, has_body=True): if has_body: body = response.json() if self.resource_key and self.resource_key in body and isinstance(body[self.resource_key], dict): body = body[self.resource_key] body = self._filter_component(body, self._body_mapping()) self._body.attributes.update(body) self._body.clean() headers = self._filter_component(response.headers, self._header_mapping()) self._header.attributes.update(headers) self._header.clean()
true
true
1c3407eb73e0eefc84b416e84e029f9171d5bc7d
1,522
py
Python
bioinformatics_stronghold/tests/test_revc.py
nathaliagg/my_rosalind_answers
f5c95c63051360a34e2b599648d4d57cbaf693a8
[ "MIT" ]
null
null
null
bioinformatics_stronghold/tests/test_revc.py
nathaliagg/my_rosalind_answers
f5c95c63051360a34e2b599648d4d57cbaf693a8
[ "MIT" ]
null
null
null
bioinformatics_stronghold/tests/test_revc.py
nathaliagg/my_rosalind_answers
f5c95c63051360a34e2b599648d4d57cbaf693a8
[ "MIT" ]
null
null
null
#!/usr/bin/env python3 """tests for revc .py""" import os import re from subprocess import getstatusoutput prg = '../revc.py' good_input = 'test_data/good_input_revc.txt' bad_input = 'test_data/bad_input_revc.txt' good_output = 'ACCGGGTTTT' # -------------------------------------------------- def test_exists(): """Exists""" assert os.path.isfile(prg) # -------------------------------------------------- def test_usage(): """Usage""" for flag in ['-h', '--help']: rv, out = getstatusoutput(f'{prg} {flag}') assert rv == 0 assert re.match("usage", out, re.IGNORECASE) # -------------------------------------------------- def test_no_args(): """Output when no args are provided""" rv, out = getstatusoutput(f'{prg}') assert rv != 0 error_string = 'following arguments are required: FILE' assert re.findall(error_string, out, re.IGNORECASE) # -------------------------------------------------- def test_bad_args(): """Test with a bad string == other than A, T, C, G""" rv, out = getstatusoutput(f'{prg} "{bad_input}"') assert rv != 0 error_string = "Bad nucleotide sequence. Only ATCG allowed." assert re.findall(error_string, out, re.IGNORECASE) # -------------------------------------------------- def test_good_output(): """Test output with a good string""" rv, out = getstatusoutput(f'{prg} "{good_input}"') assert rv == 0 assert out == good_output # --------------------------------------------------
24.15873
64
0.508541
import os import re from subprocess import getstatusoutput prg = '../revc.py' good_input = 'test_data/good_input_revc.txt' bad_input = 'test_data/bad_input_revc.txt' good_output = 'ACCGGGTTTT' def test_exists(): assert os.path.isfile(prg) def test_usage(): for flag in ['-h', '--help']: rv, out = getstatusoutput(f'{prg} {flag}') assert rv == 0 assert re.match("usage", out, re.IGNORECASE) def test_no_args(): rv, out = getstatusoutput(f'{prg}') assert rv != 0 error_string = 'following arguments are required: FILE' assert re.findall(error_string, out, re.IGNORECASE) def test_bad_args(): rv, out = getstatusoutput(f'{prg} "{bad_input}"') assert rv != 0 error_string = "Bad nucleotide sequence. Only ATCG allowed." assert re.findall(error_string, out, re.IGNORECASE) def test_good_output(): rv, out = getstatusoutput(f'{prg} "{good_input}"') assert rv == 0 assert out == good_output
true
true
1c3407ecd357dfc5ca2a544cbb74615755d2699b
1,696
py
Python
src/study/config.py
ppmzhang2/gpt3-study
1c4e34238301e06da8cbda23eb4e473567e15c80
[ "MIT" ]
null
null
null
src/study/config.py
ppmzhang2/gpt3-study
1c4e34238301e06da8cbda23eb4e473567e15c80
[ "MIT" ]
null
null
null
src/study/config.py
ppmzhang2/gpt3-study
1c4e34238301e06da8cbda23eb4e473567e15c80
[ "MIT" ]
null
null
null
"""project config""" import os import sys from logging.config import dictConfig basedir = os.path.abspath(os.path.dirname(__file__)) class Config: # pylint: disable=too-few-public-methods """default config""" # token OPENAI_KEY = os.getenv("OPENAI_KEY", "") # logging LOG_LEVEL = "WARNING" LOG_LINE_FORMAT = "%(asctime)s %(levelname)-5s %(threadName)s: %(message)s" LOG_DATETIME_FORMAT = "%Y/%m/%d %H:%M:%S" TOKEN_BPE = os.path.join(basedir, 'tokenizer/vocab.bpe') TOKEN_ID = os.path.join(basedir, 'tokenizer/encoder.json') TOKEN_ALPHABET = os.path.join(basedir, 'tokenizer/alphabet_utf8.json') @classmethod def configure_logger(cls, root_module_name): """configure logging""" dictConfig({ "version": 1, "disable_existing_loggers": False, "formatters": { "stdout_formatter": { "format": cls.LOG_LINE_FORMAT, "datefmt": cls.LOG_DATETIME_FORMAT, }, }, "handlers": { "stdout_handler": { "level": cls.LOG_LEVEL, "formatter": "stdout_formatter", "class": "logging.StreamHandler", "stream": sys.stdout, }, }, "loggers": { root_module_name: { "handlers": ["stdout_handler"], "level": cls.LOG_LEVEL, "propagate": True, }, }, }) class TestConfig(Config): # pylint: disable=too-few-public-methods """testing config""" LOG_LEVEL = "DEBUG"
29.241379
79
0.524175
import os import sys from logging.config import dictConfig basedir = os.path.abspath(os.path.dirname(__file__)) class Config: OPENAI_KEY = os.getenv("OPENAI_KEY", "") LOG_LEVEL = "WARNING" LOG_LINE_FORMAT = "%(asctime)s %(levelname)-5s %(threadName)s: %(message)s" LOG_DATETIME_FORMAT = "%Y/%m/%d %H:%M:%S" TOKEN_BPE = os.path.join(basedir, 'tokenizer/vocab.bpe') TOKEN_ID = os.path.join(basedir, 'tokenizer/encoder.json') TOKEN_ALPHABET = os.path.join(basedir, 'tokenizer/alphabet_utf8.json') @classmethod def configure_logger(cls, root_module_name): dictConfig({ "version": 1, "disable_existing_loggers": False, "formatters": { "stdout_formatter": { "format": cls.LOG_LINE_FORMAT, "datefmt": cls.LOG_DATETIME_FORMAT, }, }, "handlers": { "stdout_handler": { "level": cls.LOG_LEVEL, "formatter": "stdout_formatter", "class": "logging.StreamHandler", "stream": sys.stdout, }, }, "loggers": { root_module_name: { "handlers": ["stdout_handler"], "level": cls.LOG_LEVEL, "propagate": True, }, }, }) class TestConfig(Config): LOG_LEVEL = "DEBUG"
true
true
1c340895d8ff7e0e155b6637d09d7adf5472fe3b
8,420
py
Python
notes/mainwithfacade.py
yeezysmem/notes.io
9ca7c2251f0fc4e38b6f50e0f0411ebf5ee132da
[ "MIT" ]
1
2020-12-02T14:31:02.000Z
2020-12-02T14:31:02.000Z
notes/mainwithfacade.py
yeezysmem/notes.io
9ca7c2251f0fc4e38b6f50e0f0411ebf5ee132da
[ "MIT" ]
null
null
null
notes/mainwithfacade.py
yeezysmem/notes.io
9ca7c2251f0fc4e38b6f50e0f0411ebf5ee132da
[ "MIT" ]
null
null
null
import time from prettytable import PrettyTable # from PIL import Image import tkinter as t from tkinter.filedialog import askopenfilename import webbrowser from sqlalchemy import create_engine from sqlalchemy.orm.session import sessionmaker engine = create_engine('sqlite:///DataBaseForNotes.db' , echo=False) from sqlalchemy import Column, Integer, ForeignKey, String # from sqlalchemy.orm import relationship from sqlalchemy.ext.declarative import declarative_base base = declarative_base() # class Note_Container(base): # __tablename__= "notes_container" # id = Column(Integer, primary_key=True) # name = Column(String) # sub_note = relationship("Note") class Note(base): __tablename__="note" id = Column(Integer, primary_key=True) name = Column(String) data = Column(String) type = Column(String) time = Column(String) # container_id = Column(ForeignKey('notes_container.id')) # note = relationship("Note_Container") __mapper_args__ = {'polymorphic_identity': 'note'} def get_time(self): self.time = time.ctime() def set_data(self, data): self.data = data def print(self): print(self.data) def delete_note(self): session = sessionmaker(bind=engine)() print("Enter the name of note you want to delete:") title = input() q = session.query(Note).filter_by(name=title).first() session.delete(q) session.commit() class Table_Note(Note): __tablename__="tablenote" id = Column(Integer, ForeignKey('note.id'), primary_key=True) def set_type(self): self.type = "table" def create_table(self): self.data = PrettyTable() return self.data def insert_field_names(self, names): self.data.field_names = names def insert_rows(self, rows): self.data.add_row(rows) def insert_column(self, new_table): column = input().split() new_table.add_column(column) def create_tablenote(self): print("Enter a name for new note:") name = input() session = sessionmaker(bind=engine)() New_Note = Table_Note() New_Note.name = name New_Note.set_type() New_Note.create_table() New_Note.get_time() print("Enter the fields names for your table:") field_names = input().split() New_Note.insert_field_names(field_names) print("Enter the rows of you table") rows = input().split() New_Note.insert_rows(rows) table_string = New_Note.data.get_string() New_Note.data = table_string session.add(New_Note) session.commit() def show_tablenote(self): session = sessionmaker(bind=engine)() print("Enter the name of table you want to show:") title = input() q = session.query(Table_Note).filter_by(name=title) other_note = q.first() other_note.print() class Text_Note(Note): __tablename__ = "textnote" id = Column(Integer, ForeignKey('note.id'), primary_key=True) def set_type(self): self.type = "text" def create_textnote(self): print("Enter a name for new note:") name = input() session = sessionmaker(bind=engine)() New_Note = Text_Note() New_Note.name = name New_Note.set_type() New_Note.get_time() print("Enter the text of your note:") text = input() New_Note.set_data(text) session.add(New_Note) session.commit() class List_Note(Note): __tablename__ = "listnote" id = Column(Integer, ForeignKey('note.id'), primary_key=True) type = "list" list_heading = Column(String) listt = Column(String) def set_type(self): self.type = "list" def create_list_heading(self, heading): self.list_heading = heading def add_element(self, string): self.listt.append(string) def print(self): print(self.list_heading) for i in range(len(self.listt)): print(i+1,".", self.listt[i]) def create_listnote(self): print("Enter a name for new note:") name = input() session = sessionmaker(bind=engine)() New_Note = List_Note() New_Note.name = name New_Note.set_type() New_Note.get_time() print("Enter the list heading:") heading = input() New_Note.create_list_heading(heading) print("Enter the amount of items in list:") num = int(input()) for i in range(num): print("Enter list item:") item = input() New_Note.add_element(item) session.add(New_Note) session.commit() class Image_Note(Note): __tablename__ = "imagenote" id = Column(Integer, ForeignKey('note.id'), primary_key=True) path = Column(String) def set_type(self): self.type = "image" def set_path(self): self.path = input() # def print(self): # self.data.show() def import_pict_binary(self): f = open(self.path, "rb") pict_binary = f.read() self.data = pict_binary def create_imagenote(self): print("Enter a name for new note:") name = input() session = sessionmaker(bind=engine)() New_Note = Image_Note() New_Note.name = name New_Note.set_type() New_Note.get_time() print("Enter the path to your image:") New_Note.import_pict_binary() session.add(New_Note) session.commit() class File_Note(Note): __tablename__ = "filenote" id = Column(Integer, ForeignKey('note.id'), primary_key=True) path = Column(String) def set_type(self): self.type = "file" def import_file_binary(self): self.path = input() f = open(self.path, "rb") file_binary = f.read() self.data = file_binary def create_filenote(self): print("Enter a name for new note:") name = input() session = sessionmaker(bind=engine)() New_Note = File_Note() New_Note.name = name New_Note.set_type() New_Note.get_time() print("Enter the path to your file:") New_Note.import_file_binary() session.add(New_Note) session.commit() class Link_Note(Note): __tablename__ = "linknote" id = Column(Integer, ForeignKey('note.id'), primary_key=True) def set_type(self): self.type = "link" def new_URL(self): self.data = input() def follow_the_link(self): webbrowser.open_new(self.data) def create_linknote(self): print("Enter a name for new note:") name = input() session = sessionmaker(bind=engine)() New_Note = Link_Note() New_Note.name = name New_Note.set_type() New_Note.get_time() print("Enter a link to save in note:") New_Note.new_URL() session.add(New_Note) session.commit() base.metadata.create_all(engine) # def show_all_notes(): # session = sessionmaker(bind=engine)() # q = session.query(Note).all() # for i in range(len(q)): # # def edit_note(): # pass class Facade(object): def __init__(self): self._note = Note() self._tablenote = Table_Note() self._textnote = Text_Note() self._listnote = List_Note() self._imagenote = Image_Note() self._filenote = File_Note() self._linknote = Link_Note() def subsystem(self): # self._tablenote.create_tablenote() # self._textnote.create_textnote() # self._listnote.create_listnote() # self._imagenote.create_imagenote() # self._filenote.create_filenote() # self._tablenote.show_tablenote() self._linknote.create_linknote() self._linknote.new_URL() self._linknote.follow_the_link() # Клиентская часть if __name__ == "__main__": facade = Facade() facade.subsystem() # /Users/vadimarko/Desktop/Exams.png # create_tablenote() # show_tablenote() # class Note_Container(): # # def __init__(self, name): # # self.name = name # # self.objects = [] # # # # def add_object(self, object): # # self.objects.append(object)
23.852691
68
0.610095
import time from prettytable import PrettyTable import tkinter as t from tkinter.filedialog import askopenfilename import webbrowser from sqlalchemy import create_engine from sqlalchemy.orm.session import sessionmaker engine = create_engine('sqlite:///DataBaseForNotes.db' , echo=False) from sqlalchemy import Column, Integer, ForeignKey, String from sqlalchemy.ext.declarative import declarative_base base = declarative_base() class Note(base): __tablename__="note" id = Column(Integer, primary_key=True) name = Column(String) data = Column(String) type = Column(String) time = Column(String) __mapper_args__ = {'polymorphic_identity': 'note'} def get_time(self): self.time = time.ctime() def set_data(self, data): self.data = data def print(self): print(self.data) def delete_note(self): session = sessionmaker(bind=engine)() print("Enter the name of note you want to delete:") title = input() q = session.query(Note).filter_by(name=title).first() session.delete(q) session.commit() class Table_Note(Note): __tablename__="tablenote" id = Column(Integer, ForeignKey('note.id'), primary_key=True) def set_type(self): self.type = "table" def create_table(self): self.data = PrettyTable() return self.data def insert_field_names(self, names): self.data.field_names = names def insert_rows(self, rows): self.data.add_row(rows) def insert_column(self, new_table): column = input().split() new_table.add_column(column) def create_tablenote(self): print("Enter a name for new note:") name = input() session = sessionmaker(bind=engine)() New_Note = Table_Note() New_Note.name = name New_Note.set_type() New_Note.create_table() New_Note.get_time() print("Enter the fields names for your table:") field_names = input().split() New_Note.insert_field_names(field_names) print("Enter the rows of you table") rows = input().split() New_Note.insert_rows(rows) table_string = New_Note.data.get_string() New_Note.data = table_string session.add(New_Note) session.commit() def show_tablenote(self): session = sessionmaker(bind=engine)() print("Enter the name of table you want to show:") title = input() q = session.query(Table_Note).filter_by(name=title) other_note = q.first() other_note.print() class Text_Note(Note): __tablename__ = "textnote" id = Column(Integer, ForeignKey('note.id'), primary_key=True) def set_type(self): self.type = "text" def create_textnote(self): print("Enter a name for new note:") name = input() session = sessionmaker(bind=engine)() New_Note = Text_Note() New_Note.name = name New_Note.set_type() New_Note.get_time() print("Enter the text of your note:") text = input() New_Note.set_data(text) session.add(New_Note) session.commit() class List_Note(Note): __tablename__ = "listnote" id = Column(Integer, ForeignKey('note.id'), primary_key=True) type = "list" list_heading = Column(String) listt = Column(String) def set_type(self): self.type = "list" def create_list_heading(self, heading): self.list_heading = heading def add_element(self, string): self.listt.append(string) def print(self): print(self.list_heading) for i in range(len(self.listt)): print(i+1,".", self.listt[i]) def create_listnote(self): print("Enter a name for new note:") name = input() session = sessionmaker(bind=engine)() New_Note = List_Note() New_Note.name = name New_Note.set_type() New_Note.get_time() print("Enter the list heading:") heading = input() New_Note.create_list_heading(heading) print("Enter the amount of items in list:") num = int(input()) for i in range(num): print("Enter list item:") item = input() New_Note.add_element(item) session.add(New_Note) session.commit() class Image_Note(Note): __tablename__ = "imagenote" id = Column(Integer, ForeignKey('note.id'), primary_key=True) path = Column(String) def set_type(self): self.type = "image" def set_path(self): self.path = input() def import_pict_binary(self): f = open(self.path, "rb") pict_binary = f.read() self.data = pict_binary def create_imagenote(self): print("Enter a name for new note:") name = input() session = sessionmaker(bind=engine)() New_Note = Image_Note() New_Note.name = name New_Note.set_type() New_Note.get_time() print("Enter the path to your image:") New_Note.import_pict_binary() session.add(New_Note) session.commit() class File_Note(Note): __tablename__ = "filenote" id = Column(Integer, ForeignKey('note.id'), primary_key=True) path = Column(String) def set_type(self): self.type = "file" def import_file_binary(self): self.path = input() f = open(self.path, "rb") file_binary = f.read() self.data = file_binary def create_filenote(self): print("Enter a name for new note:") name = input() session = sessionmaker(bind=engine)() New_Note = File_Note() New_Note.name = name New_Note.set_type() New_Note.get_time() print("Enter the path to your file:") New_Note.import_file_binary() session.add(New_Note) session.commit() class Link_Note(Note): __tablename__ = "linknote" id = Column(Integer, ForeignKey('note.id'), primary_key=True) def set_type(self): self.type = "link" def new_URL(self): self.data = input() def follow_the_link(self): webbrowser.open_new(self.data) def create_linknote(self): print("Enter a name for new note:") name = input() session = sessionmaker(bind=engine)() New_Note = Link_Note() New_Note.name = name New_Note.set_type() New_Note.get_time() print("Enter a link to save in note:") New_Note.new_URL() session.add(New_Note) session.commit() base.metadata.create_all(engine) class Facade(object): def __init__(self): self._note = Note() self._tablenote = Table_Note() self._textnote = Text_Note() self._listnote = List_Note() self._imagenote = Image_Note() self._filenote = File_Note() self._linknote = Link_Note() def subsystem(self): self._linknote.create_linknote() self._linknote.new_URL() self._linknote.follow_the_link() if __name__ == "__main__": facade = Facade() facade.subsystem()
true
true
1c340923dc4ec14bb7428534234c2587080e5110
7,169
py
Python
src/read_actual_data.py
gdalle/PartiallyObservedVectorAutoRegressions
28c9d34d7b6e45679e442721daf4946867fd5fb0
[ "MIT" ]
null
null
null
src/read_actual_data.py
gdalle/PartiallyObservedVectorAutoRegressions
28c9d34d7b6e45679e442721daf4946867fd5fb0
[ "MIT" ]
null
null
null
src/read_actual_data.py
gdalle/PartiallyObservedVectorAutoRegressions
28c9d34d7b6e45679e442721daf4946867fd5fb0
[ "MIT" ]
null
null
null
import itertools import os import zipfile from joblib import Parallel, delayed import pandas as pd from tqdm.notebook import tqdm # Constants YEARS = ["2018", "2019", "2020", "2021"] MONTHS = ["01", "02", "03", "04", "05", "06", "07", "08", "09", "10", "11", "12"] DATA_COLUMNS = { "BETRIEBSTAG": ("date", "string"), "FAHRT_BEZEICHNER": ("trip_id", "category"), "BETREIBER_ID": ("agency_id", "category"), "BETREIBER_ABK": ("agency_short_name", "category"), "BETREIBER_NAME": ("agency_name", "category"), "PRODUKT_ID": ("transportation_type", "category"), "LINIEN_ID": ("line_id", "category"), "LINIEN_TEXT": ("line_name", "category"), "UMLAUF_ID": ("circuit_transfer", "category"), "VERKEHRSMITTEL_TEXT": ("transportation_subtype", "category"), "ZUSATZFAHRT_TF": ("unplanned_trip", "category"), "FAELLT_AUS_TF": ("cancelled_trip", "category"), "BPUIC": ("stop_id", "category"), "HALTESTELLEN_NAME": ("stop_name_unofficial", "category"), "ANKUNFTSZEIT": ("arrival_time_planned", "string"), "AN_PROGNOSE": ("arrival_time_real", "string"), "AN_PROGNOSE_STATUS": ("arrival_time_status", "category"), "ABFAHRTSZEIT": ("departure_time_planned", "string"), "AB_PROGNOSE": ("departure_time_real", "string"), "AB_PROGNOSE_STATUS": ("departure_time_status", "category"), "DURCHFAHRT_TF": ("skipped_stop", "category"), } AGENCY_NAMES = ["Verkehrsbetriebe Zürich", "Verkehrsbetriebe Zürich INFO+"] TRANSPORTATION_TYPES = ["Tram"] # Utils def concat_preserving_categorical(dfs): """Concatenate while preserving categorical columns.""" columns, dtypes = dfs[0].columns, dfs[0].dtypes res = pd.DataFrame() for c in tqdm(columns, desc="Concatenation "): if str(dtypes[c]) == "category": res[c] = pd.api.types.union_categoricals( [df[c].astype("category") for df in dfs] ) else: res[c] = pd.concat([df[c] for df in dfs]) return res # Read CSV files def read_day_csv(daily_csv_path): """Read daily csv in the right format.""" try: data = pd.read_csv( daily_csv_path, sep=";", dtype={c: DATA_COLUMNS[c][1] for c in DATA_COLUMNS.keys()}, ) except UnicodeDecodeError: print("Skipped (UTF-8 error): ", daily_csv_path) return None # Rename columns data = data.rename( mapper={c: DATA_COLUMNS[c][0] for c in DATA_COLUMNS.keys()}, axis=1 ) # Convert datetime columns for timecol in ["date"]: data[timecol] = pd.to_datetime( data[timecol], format="%d.%m.%Y", errors="coerce" ) for timecol in ["arrival_time_planned", "departure_time_planned"]: data[timecol] = pd.to_datetime( data[timecol], format="%d.%m.%Y %H:%M", errors="coerce" ) for timecol in ["arrival_time_real", "departure_time_real"]: data[timecol] = pd.to_datetime( data[timecol], format="%d.%m.%Y %H:%M:%S", errors="coerce" ) # Translate columns in German for status_col in ["arrival_time_status", "departure_time_status"]: data[status_col] = ( data[status_col] .replace( { "PROGNOSE": "Forecast", "GESCHAETZT": "Estimated", "UNBEKANNT": "Unknown", "REAL": "Real", } ) .fillna("Forecast") .astype("category") ) data["transportation_type"] = ( data["transportation_type"] .replace( { "Zug": "Train", "Bus": "Bus", "BUS": "Bus", "Schiff": "Boat", "Tram": "Tram", } ) .fillna("Unknown") .astype("category") ) return data # A pyramid of decompression and recompression def unzip_single_month_store_days( monthly_zip_dir_path, monthly_zip_name, daily_parquet_dir_path ): """Read a single zipped month full of csv and split it into parquet days.""" monthly_zip_path = os.path.join(monthly_zip_dir_path, monthly_zip_name) with zipfile.ZipFile(monthly_zip_path) as monthly_zip_file: # Loop over all days of the month for daily_csv_name in monthly_zip_file.namelist(): # Skip additional files if ".csv" not in daily_csv_name: continue # Open and parse csv with monthly_zip_file.open(daily_csv_name, "r") as daily_csv_file: daily_data = read_day_csv(daily_csv_file) # Filter if daily_data is not None: daily_data = daily_data[ daily_data["agency_name"].isin(AGENCY_NAMES) & daily_data["transportation_type"].isin(TRANSPORTATION_TYPES) ] # Save as parquet file parquet_file_name = daily_csv_name.split("/")[-1][:10] + ".parquet" daily_data.to_parquet( os.path.join(daily_parquet_dir_path, parquet_file_name) ) def unzip_months_store_days( monthly_zip_dir_path, daily_parquet_dir_path, ): """Read all zipped months full of csv and split them into parquet days.""" monthly_zip_names = [ name for name in sorted(os.listdir(monthly_zip_dir_path)) if name.startswith("19_") or name.startswith("18_") ] Parallel(n_jobs=6)( delayed(unzip_single_month_store_days)( monthly_zip_dir_path, monthly_zip_name, daily_parquet_dir_path ) for monthly_zip_name in tqdm( monthly_zip_names, desc="Decompressing months for 2018-2019" ) ) def read_days_store_months(daily_parquet_dir_path, monthly_parquet_dir_path): """Read parquet days and put them together into months.""" for (year, month) in list(itertools.product(YEARS, MONTHS)): yearmonth = "{}-{}".format(year, month) daily_files = sorted( [file for file in os.listdir(daily_parquet_dir_path) if yearmonth in file] ) if daily_files: monthly_data_list = [] for date in tqdm(daily_files, desc="Reading " + yearmonth): daily_data = pd.read_parquet(os.path.join(daily_parquet_dir_path, date)) monthly_data_list.append(daily_data) monthly_data = concat_preserving_categorical(monthly_data_list) monthly_data.to_parquet( os.path.join(monthly_parquet_dir_path, yearmonth + ".parquet") ) def read_months_return_full( monthly_parquet_dir_path, years=[2018, 2019] ): """Read parquet months and put them together into a full dataframe.""" data = concat_preserving_categorical( [ pd.read_parquet(os.path.join(monthly_parquet_dir_path, monthly_file)) for monthly_file in tqdm( sorted(os.listdir(monthly_parquet_dir_path)), desc="Reading files " ) if any(str(year) in monthly_file for year in years) ] ) return data
35.490099
88
0.600921
import itertools import os import zipfile from joblib import Parallel, delayed import pandas as pd from tqdm.notebook import tqdm YEARS = ["2018", "2019", "2020", "2021"] MONTHS = ["01", "02", "03", "04", "05", "06", "07", "08", "09", "10", "11", "12"] DATA_COLUMNS = { "BETRIEBSTAG": ("date", "string"), "FAHRT_BEZEICHNER": ("trip_id", "category"), "BETREIBER_ID": ("agency_id", "category"), "BETREIBER_ABK": ("agency_short_name", "category"), "BETREIBER_NAME": ("agency_name", "category"), "PRODUKT_ID": ("transportation_type", "category"), "LINIEN_ID": ("line_id", "category"), "LINIEN_TEXT": ("line_name", "category"), "UMLAUF_ID": ("circuit_transfer", "category"), "VERKEHRSMITTEL_TEXT": ("transportation_subtype", "category"), "ZUSATZFAHRT_TF": ("unplanned_trip", "category"), "FAELLT_AUS_TF": ("cancelled_trip", "category"), "BPUIC": ("stop_id", "category"), "HALTESTELLEN_NAME": ("stop_name_unofficial", "category"), "ANKUNFTSZEIT": ("arrival_time_planned", "string"), "AN_PROGNOSE": ("arrival_time_real", "string"), "AN_PROGNOSE_STATUS": ("arrival_time_status", "category"), "ABFAHRTSZEIT": ("departure_time_planned", "string"), "AB_PROGNOSE": ("departure_time_real", "string"), "AB_PROGNOSE_STATUS": ("departure_time_status", "category"), "DURCHFAHRT_TF": ("skipped_stop", "category"), } AGENCY_NAMES = ["Verkehrsbetriebe Zürich", "Verkehrsbetriebe Zürich INFO+"] TRANSPORTATION_TYPES = ["Tram"] def concat_preserving_categorical(dfs): columns, dtypes = dfs[0].columns, dfs[0].dtypes res = pd.DataFrame() for c in tqdm(columns, desc="Concatenation "): if str(dtypes[c]) == "category": res[c] = pd.api.types.union_categoricals( [df[c].astype("category") for df in dfs] ) else: res[c] = pd.concat([df[c] for df in dfs]) return res def read_day_csv(daily_csv_path): try: data = pd.read_csv( daily_csv_path, sep=";", dtype={c: DATA_COLUMNS[c][1] for c in DATA_COLUMNS.keys()}, ) except UnicodeDecodeError: print("Skipped (UTF-8 error): ", daily_csv_path) return None data = data.rename( mapper={c: DATA_COLUMNS[c][0] for c in DATA_COLUMNS.keys()}, axis=1 ) for timecol in ["date"]: data[timecol] = pd.to_datetime( data[timecol], format="%d.%m.%Y", errors="coerce" ) for timecol in ["arrival_time_planned", "departure_time_planned"]: data[timecol] = pd.to_datetime( data[timecol], format="%d.%m.%Y %H:%M", errors="coerce" ) for timecol in ["arrival_time_real", "departure_time_real"]: data[timecol] = pd.to_datetime( data[timecol], format="%d.%m.%Y %H:%M:%S", errors="coerce" ) for status_col in ["arrival_time_status", "departure_time_status"]: data[status_col] = ( data[status_col] .replace( { "PROGNOSE": "Forecast", "GESCHAETZT": "Estimated", "UNBEKANNT": "Unknown", "REAL": "Real", } ) .fillna("Forecast") .astype("category") ) data["transportation_type"] = ( data["transportation_type"] .replace( { "Zug": "Train", "Bus": "Bus", "BUS": "Bus", "Schiff": "Boat", "Tram": "Tram", } ) .fillna("Unknown") .astype("category") ) return data def unzip_single_month_store_days( monthly_zip_dir_path, monthly_zip_name, daily_parquet_dir_path ): monthly_zip_path = os.path.join(monthly_zip_dir_path, monthly_zip_name) with zipfile.ZipFile(monthly_zip_path) as monthly_zip_file: for daily_csv_name in monthly_zip_file.namelist(): if ".csv" not in daily_csv_name: continue with monthly_zip_file.open(daily_csv_name, "r") as daily_csv_file: daily_data = read_day_csv(daily_csv_file) if daily_data is not None: daily_data = daily_data[ daily_data["agency_name"].isin(AGENCY_NAMES) & daily_data["transportation_type"].isin(TRANSPORTATION_TYPES) ] parquet_file_name = daily_csv_name.split("/")[-1][:10] + ".parquet" daily_data.to_parquet( os.path.join(daily_parquet_dir_path, parquet_file_name) ) def unzip_months_store_days( monthly_zip_dir_path, daily_parquet_dir_path, ): monthly_zip_names = [ name for name in sorted(os.listdir(monthly_zip_dir_path)) if name.startswith("19_") or name.startswith("18_") ] Parallel(n_jobs=6)( delayed(unzip_single_month_store_days)( monthly_zip_dir_path, monthly_zip_name, daily_parquet_dir_path ) for monthly_zip_name in tqdm( monthly_zip_names, desc="Decompressing months for 2018-2019" ) ) def read_days_store_months(daily_parquet_dir_path, monthly_parquet_dir_path): for (year, month) in list(itertools.product(YEARS, MONTHS)): yearmonth = "{}-{}".format(year, month) daily_files = sorted( [file for file in os.listdir(daily_parquet_dir_path) if yearmonth in file] ) if daily_files: monthly_data_list = [] for date in tqdm(daily_files, desc="Reading " + yearmonth): daily_data = pd.read_parquet(os.path.join(daily_parquet_dir_path, date)) monthly_data_list.append(daily_data) monthly_data = concat_preserving_categorical(monthly_data_list) monthly_data.to_parquet( os.path.join(monthly_parquet_dir_path, yearmonth + ".parquet") ) def read_months_return_full( monthly_parquet_dir_path, years=[2018, 2019] ): data = concat_preserving_categorical( [ pd.read_parquet(os.path.join(monthly_parquet_dir_path, monthly_file)) for monthly_file in tqdm( sorted(os.listdir(monthly_parquet_dir_path)), desc="Reading files " ) if any(str(year) in monthly_file for year in years) ] ) return data
true
true
1c340959bfcf319ad547abc637ac8cd4909c2e99
667
py
Python
LeetCode/347 Top K Frequent Elements.py
gesuwen/Algorithms
0c9cf4412d76f8b69ef68cc80636323f5a0e5786
[ "MIT" ]
null
null
null
LeetCode/347 Top K Frequent Elements.py
gesuwen/Algorithms
0c9cf4412d76f8b69ef68cc80636323f5a0e5786
[ "MIT" ]
null
null
null
LeetCode/347 Top K Frequent Elements.py
gesuwen/Algorithms
0c9cf4412d76f8b69ef68cc80636323f5a0e5786
[ "MIT" ]
null
null
null
# Hash Table; Heap # Given a non-empty array of integers, return the k most frequent elements. # # Example 1: # # Input: nums = [1,1,1,2,2,3], k = 2 # Output: [1,2] # Example 2: # # Input: nums = [1], k = 1 # Output: [1] # Note: # # You may assume k is always valid, 1 ≤ k ≤ number of unique elements. # Your algorithm's time complexity must be better than O(n log n), where n is the array's size. class Solution: def topKFrequent(self, nums, k): """ :type nums: List[int] :type k: int :rtype: List[int] """ numsDictKCommon = collections.Counter(nums).most_common(k) return [x[0] for x in numsDictKCommon]
25.653846
95
0.610195
class Solution: def topKFrequent(self, nums, k): numsDictKCommon = collections.Counter(nums).most_common(k) return [x[0] for x in numsDictKCommon]
true
true
1c3409b40d34943b071152c0968e0e9175ed142c
405
py
Python
exproject/cli.py
yatin-darbar/exproject
5cac45a28dc71d83215dabe33211dd758b83191a
[ "MIT" ]
null
null
null
exproject/cli.py
yatin-darbar/exproject
5cac45a28dc71d83215dabe33211dd758b83191a
[ "MIT" ]
null
null
null
exproject/cli.py
yatin-darbar/exproject
5cac45a28dc71d83215dabe33211dd758b83191a
[ "MIT" ]
null
null
null
"""Console script for exproject.""" import sys import click @click.command() def main(args=None): """Console script for exproject.""" click.echo("Replace this message by putting your code into " "exproject.cli.main") click.echo("See click documentation at https://click.palletsprojects.com/") return 0 if __name__ == "__main__": sys.exit(main()) # pragma: no cover
23.823529
79
0.666667
import sys import click @click.command() def main(args=None): click.echo("Replace this message by putting your code into " "exproject.cli.main") click.echo("See click documentation at https://click.palletsprojects.com/") return 0 if __name__ == "__main__": sys.exit(main())
true
true
1c3409fa0f2cac32d7f09305197d2875ed50d8f8
1,325
py
Python
aiotdlib/api/functions/request_qr_code_authentication.py
jraylan/aiotdlib
4528fcfca7c5c69b54a878ce6ce60e934a2dcc73
[ "MIT" ]
37
2021-05-04T10:41:41.000Z
2022-03-30T13:48:05.000Z
aiotdlib/api/functions/request_qr_code_authentication.py
jraylan/aiotdlib
4528fcfca7c5c69b54a878ce6ce60e934a2dcc73
[ "MIT" ]
13
2021-07-17T19:54:51.000Z
2022-02-26T06:50:00.000Z
aiotdlib/api/functions/request_qr_code_authentication.py
jraylan/aiotdlib
4528fcfca7c5c69b54a878ce6ce60e934a2dcc73
[ "MIT" ]
7
2021-09-22T21:27:11.000Z
2022-02-20T02:33:19.000Z
# =============================================================================== # # # # This file has been generated automatically!! Do not change this manually! # # # # =============================================================================== # from __future__ import annotations from pydantic import Field from ..base_object import BaseObject class RequestQrCodeAuthentication(BaseObject): """ Requests QR code authentication by scanning a QR code on another logged in device. Works only when the current authorization state is authorizationStateWaitPhoneNumber, or if there is no pending authentication query and the current authorization state is authorizationStateWaitCode, authorizationStateWaitRegistration, or authorizationStateWaitPassword :param other_user_ids: List of user identifiers of other users currently using the application :type other_user_ids: :class:`list[int]` """ ID: str = Field("requestQrCodeAuthentication", alias="@type") other_user_ids: list[int] @staticmethod def read(q: dict) -> RequestQrCodeAuthentication: return RequestQrCodeAuthentication.construct(**q)
47.321429
356
0.578113
from __future__ import annotations from pydantic import Field from ..base_object import BaseObject class RequestQrCodeAuthentication(BaseObject): ID: str = Field("requestQrCodeAuthentication", alias="@type") other_user_ids: list[int] @staticmethod def read(q: dict) -> RequestQrCodeAuthentication: return RequestQrCodeAuthentication.construct(**q)
true
true
1c340a57c3769de9448e4dae1c6352d7f424212f
15,644
py
Python
PaddleCV/PaddleGAN/trainer/Pix2pix.py
heavengate/models
f05c910f8a8e3105de8c2f1d81e83ca00d2c7ec7
[ "Apache-2.0" ]
2
2021-06-11T06:48:20.000Z
2021-09-02T10:23:07.000Z
PaddleCV/PaddleGAN/trainer/Pix2pix.py
heavengate/models
f05c910f8a8e3105de8c2f1d81e83ca00d2c7ec7
[ "Apache-2.0" ]
null
null
null
PaddleCV/PaddleGAN/trainer/Pix2pix.py
heavengate/models
f05c910f8a8e3105de8c2f1d81e83ca00d2c7ec7
[ "Apache-2.0" ]
1
2019-08-27T11:19:09.000Z
2019-08-27T11:19:09.000Z
#copyright (c) 2019 PaddlePaddle Authors. All Rights Reserve. # #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 __future__ import absolute_import from __future__ import division from __future__ import print_function from network.Pix2pix_network import Pix2pix_model from util import utility import paddle.fluid as fluid from paddle.fluid import profiler import sys import time import numpy as np class GTrainer(): def __init__(self, input_A, input_B, cfg, step_per_epoch): self.program = fluid.default_main_program().clone() with fluid.program_guard(self.program): model = Pix2pix_model() self.fake_B = model.network_G(input_A, "generator", cfg=cfg) self.fake_B.persistable = True self.infer_program = self.program.clone() AB = fluid.layers.concat([input_A, self.fake_B], 1) self.pred = model.network_D(AB, "discriminator", cfg) if cfg.gan_mode == "lsgan": ones = fluid.layers.fill_constant_batch_size_like( input=self.pred, shape=self.pred.shape, value=1, dtype='float32') self.g_loss_gan = fluid.layers.reduce_mean( fluid.layers.square( fluid.layers.elementwise_sub( x=self.pred, y=ones))) elif cfg.gan_mode == "vanilla": pred_shape = self.pred.shape self.pred = fluid.layers.reshape( self.pred, [-1, pred_shape[1] * pred_shape[2] * pred_shape[3]], inplace=True) ones = fluid.layers.fill_constant_batch_size_like( input=self.pred, shape=self.pred.shape, value=1, dtype='float32') self.g_loss_gan = fluid.layers.mean( fluid.layers.sigmoid_cross_entropy_with_logits( x=self.pred, label=ones)) else: raise NotImplementedError("gan_mode {} is not support!".format( cfg.gan_mode)) self.g_loss_L1 = fluid.layers.reduce_mean( fluid.layers.abs( fluid.layers.elementwise_sub( x=input_B, y=self.fake_B))) * cfg.lambda_L1 self.g_loss = fluid.layers.elementwise_add(self.g_loss_L1, self.g_loss_gan) lr = cfg.learning_rate vars = [] for var in self.program.list_vars(): if fluid.io.is_parameter(var) and var.name.startswith( "generator"): vars.append(var.name) self.param = vars if cfg.epoch <= 100: optimizer = fluid.optimizer.Adam( learning_rate=lr, beta1=0.5, beta2=0.999, name="net_G") else: optimizer = fluid.optimizer.Adam( learning_rate=fluid.layers.piecewise_decay( boundaries=[99 * step_per_epoch] + [ x * step_per_epoch for x in range(100, cfg.epoch - 1) ], values=[lr] + [ lr * (1.0 - (x - 99.0) / 101.0) for x in range(100, cfg.epoch) ]), beta1=0.5, beta2=0.999, name="net_G") optimizer.minimize(self.g_loss, parameter_list=vars) class DTrainer(): def __init__(self, input_A, input_B, fake_B, cfg, step_per_epoch): self.program = fluid.default_main_program().clone() lr = cfg.learning_rate with fluid.program_guard(self.program): model = Pix2pix_model() self.real_AB = fluid.layers.concat([input_A, input_B], 1) self.fake_AB = fluid.layers.concat([input_A, fake_B], 1) self.pred_real = model.network_D( self.real_AB, "discriminator", cfg=cfg) self.pred_fake = model.network_D( self.fake_AB, "discriminator", cfg=cfg) if cfg.gan_mode == "lsgan": ones = fluid.layers.fill_constant_batch_size_like( input=self.pred_real, shape=self.pred_real.shape, value=1, dtype='float32') self.d_loss_real = fluid.layers.reduce_mean( fluid.layers.square( fluid.layers.elementwise_sub( x=self.pred_real, y=ones))) self.d_loss_fake = fluid.layers.reduce_mean( fluid.layers.square(x=self.pred_fake)) elif cfg.gan_mode == "vanilla": pred_shape = self.pred_real.shape self.pred_real = fluid.layers.reshape( self.pred_real, [-1, pred_shape[1] * pred_shape[2] * pred_shape[3]], inplace=True) self.pred_fake = fluid.layers.reshape( self.pred_fake, [-1, pred_shape[1] * pred_shape[2] * pred_shape[3]], inplace=True) zeros = fluid.layers.fill_constant_batch_size_like( input=self.pred_fake, shape=self.pred_fake.shape, value=0, dtype='float32') ones = fluid.layers.fill_constant_batch_size_like( input=self.pred_real, shape=self.pred_real.shape, value=1, dtype='float32') self.d_loss_real = fluid.layers.mean( fluid.layers.sigmoid_cross_entropy_with_logits( x=self.pred_real, label=ones)) self.d_loss_fake = fluid.layers.mean( fluid.layers.sigmoid_cross_entropy_with_logits( x=self.pred_fake, label=zeros)) else: raise NotImplementedError("gan_mode {} is not support!".format( cfg.gan_mode)) self.d_loss = 0.5 * (self.d_loss_real + self.d_loss_fake) vars = [] for var in self.program.list_vars(): if fluid.io.is_parameter(var) and var.name.startswith( "discriminator"): vars.append(var.name) self.param = vars if cfg.epoch <= 100: optimizer = fluid.optimizer.Adam( learning_rate=lr, beta1=0.5, beta2=0.999, name="net_D") else: optimizer = fluid.optimizer.Adam( learning_rate=fluid.layers.piecewise_decay( boundaries=[99 * step_per_epoch] + [ x * step_per_epoch for x in range(100, cfg.epoch - 1) ], values=[lr] + [ lr * (1.0 - (x - 99.0) / 101.0) for x in range(100, cfg.epoch) ]), beta1=0.5, beta2=0.999, name="net_D") optimizer.minimize(self.d_loss, parameter_list=vars) class Pix2pix(object): def add_special_args(self, parser): parser.add_argument( '--net_G', type=str, default="unet_256", help="Choose the Pix2pix generator's network, choose in [resnet_9block|resnet_6block|unet_128|unet_256]" ) parser.add_argument( '--net_D', type=str, default="basic", help="Choose the Pix2pix discriminator's network, choose in [basic|nlayers|pixel]" ) parser.add_argument( '--d_nlayers', type=int, default=3, help="only used when Pix2pix discriminator is nlayers") parser.add_argument( '--enable_ce', action='store_true', help="if set, run the tasks with continuous evaluation logs") return parser def __init__(self, cfg=None, train_reader=None, test_reader=None, batch_num=1, id2name=None): self.cfg = cfg self.train_reader = train_reader self.test_reader = test_reader self.batch_num = batch_num self.id2name = id2name def build_model(self): data_shape = [None, 3, self.cfg.crop_size, self.cfg.crop_size] input_A = fluid.data(name='input_A', shape=data_shape, dtype='float32') input_B = fluid.data(name='input_B', shape=data_shape, dtype='float32') input_fake = fluid.data( name='input_fake', shape=data_shape, dtype='float32') # used for continuous evaluation if self.cfg.enable_ce: fluid.default_startup_program().random_seed = 90 loader = fluid.io.DataLoader.from_generator( feed_list=[input_A, input_B], capacity=4, iterable=True, use_double_buffer=True) gen_trainer = GTrainer(input_A, input_B, self.cfg, self.batch_num) dis_trainer = DTrainer(input_A, input_B, input_fake, self.cfg, self.batch_num) # prepare environment place = fluid.CUDAPlace(0) if self.cfg.use_gpu else fluid.CPUPlace() loader.set_batch_generator( self.train_reader, places=fluid.cuda_places() if self.cfg.use_gpu else fluid.cpu_places()) exe = fluid.Executor(place) exe.run(fluid.default_startup_program()) if self.cfg.init_model: utility.init_checkpoints(self.cfg, exe, gen_trainer, "net_G") utility.init_checkpoints(self.cfg, exe, dis_trainer, "net_D") ### memory optim build_strategy = fluid.BuildStrategy() gen_trainer_program = fluid.CompiledProgram( gen_trainer.program).with_data_parallel( loss_name=gen_trainer.g_loss.name, build_strategy=build_strategy) dis_trainer_program = fluid.CompiledProgram( dis_trainer.program).with_data_parallel( loss_name=dis_trainer.d_loss.name, build_strategy=build_strategy) t_time = 0 total_train_batch = 0 # used for benchmark for epoch_id in range(self.cfg.epoch): batch_id = 0 for tensor in loader(): if self.cfg.max_iter and total_train_batch == self.cfg.max_iter: # used for benchmark return s_time = time.time() # optimize the generator network g_loss_gan, g_loss_l1, fake_B_tmp = exe.run( gen_trainer_program, fetch_list=[ gen_trainer.g_loss_gan, gen_trainer.g_loss_L1, gen_trainer.fake_B ], feed=tensor) devices_num = utility.get_device_num(self.cfg) fake_per_device = int(len(fake_B_tmp) / devices_num) for dev in range(devices_num): tensor[dev]['input_fake'] = fake_B_tmp[dev * fake_per_device : (dev+1) * fake_per_device] # optimize the discriminator network d_loss_real, d_loss_fake = exe.run(dis_trainer_program, fetch_list=[ dis_trainer.d_loss_real, dis_trainer.d_loss_fake ], feed=tensor) batch_time = time.time() - s_time t_time += batch_time if batch_id % self.cfg.print_freq == 0: print("epoch{}: batch{}: \n\ g_loss_gan: {}; g_loss_l1: {}; \n\ d_loss_real: {}; d_loss_fake: {}; \n\ Batch_time_cost: {}" .format(epoch_id, batch_id, g_loss_gan[0], g_loss_l1[ 0], d_loss_real[0], d_loss_fake[0], batch_time)) sys.stdout.flush() batch_id += 1 total_train_batch += 1 # used for benchmark # profiler tools if self.cfg.profile and epoch_id == 0 and batch_id == self.cfg.print_freq: profiler.reset_profiler() elif self.cfg.profile and epoch_id == 0 and batch_id == self.cfg.print_freq + 5: return if self.cfg.run_test: image_name = fluid.data( name='image_name', shape=[None, self.cfg.batch_size], dtype="int32") test_loader = fluid.io.DataLoader.from_generator( feed_list=[input_A, input_B, image_name], capacity=4, iterable=True, use_double_buffer=True) test_loader.set_batch_generator( self.test_reader, places=fluid.cuda_places() if self.cfg.use_gpu else fluid.cpu_places()) test_program = gen_trainer.infer_program utility.save_test_image( epoch_id, self.cfg, exe, place, test_program, gen_trainer, test_loader, A_id2name=self.id2name) if self.cfg.save_checkpoints: utility.checkpoints(epoch_id, self.cfg, exe, gen_trainer, "net_G") utility.checkpoints(epoch_id, self.cfg, exe, dis_trainer, "net_D") if self.cfg.enable_ce: device_num = fluid.core.get_cuda_device_count( ) if self.cfg.use_gpu else 1 print("kpis\tpix2pix_g_loss_gan_card{}\t{}".format(device_num, g_loss_gan[0])) print("kpis\tpix2pix_g_loss_l1_card{}\t{}".format(device_num, g_loss_l1[0])) print("kpis\tpix2pix_d_loss_real_card{}\t{}".format(device_num, d_loss_real[0])) print("kpis\tpix2pix_d_loss_fake_card{}\t{}".format(device_num, d_loss_fake[0])) print("kpis\tpix2pix_Batch_time_cost_card{}\t{}".format(device_num, batch_time))
43.576602
116
0.510483
from __future__ import absolute_import from __future__ import division from __future__ import print_function from network.Pix2pix_network import Pix2pix_model from util import utility import paddle.fluid as fluid from paddle.fluid import profiler import sys import time import numpy as np class GTrainer(): def __init__(self, input_A, input_B, cfg, step_per_epoch): self.program = fluid.default_main_program().clone() with fluid.program_guard(self.program): model = Pix2pix_model() self.fake_B = model.network_G(input_A, "generator", cfg=cfg) self.fake_B.persistable = True self.infer_program = self.program.clone() AB = fluid.layers.concat([input_A, self.fake_B], 1) self.pred = model.network_D(AB, "discriminator", cfg) if cfg.gan_mode == "lsgan": ones = fluid.layers.fill_constant_batch_size_like( input=self.pred, shape=self.pred.shape, value=1, dtype='float32') self.g_loss_gan = fluid.layers.reduce_mean( fluid.layers.square( fluid.layers.elementwise_sub( x=self.pred, y=ones))) elif cfg.gan_mode == "vanilla": pred_shape = self.pred.shape self.pred = fluid.layers.reshape( self.pred, [-1, pred_shape[1] * pred_shape[2] * pred_shape[3]], inplace=True) ones = fluid.layers.fill_constant_batch_size_like( input=self.pred, shape=self.pred.shape, value=1, dtype='float32') self.g_loss_gan = fluid.layers.mean( fluid.layers.sigmoid_cross_entropy_with_logits( x=self.pred, label=ones)) else: raise NotImplementedError("gan_mode {} is not support!".format( cfg.gan_mode)) self.g_loss_L1 = fluid.layers.reduce_mean( fluid.layers.abs( fluid.layers.elementwise_sub( x=input_B, y=self.fake_B))) * cfg.lambda_L1 self.g_loss = fluid.layers.elementwise_add(self.g_loss_L1, self.g_loss_gan) lr = cfg.learning_rate vars = [] for var in self.program.list_vars(): if fluid.io.is_parameter(var) and var.name.startswith( "generator"): vars.append(var.name) self.param = vars if cfg.epoch <= 100: optimizer = fluid.optimizer.Adam( learning_rate=lr, beta1=0.5, beta2=0.999, name="net_G") else: optimizer = fluid.optimizer.Adam( learning_rate=fluid.layers.piecewise_decay( boundaries=[99 * step_per_epoch] + [ x * step_per_epoch for x in range(100, cfg.epoch - 1) ], values=[lr] + [ lr * (1.0 - (x - 99.0) / 101.0) for x in range(100, cfg.epoch) ]), beta1=0.5, beta2=0.999, name="net_G") optimizer.minimize(self.g_loss, parameter_list=vars) class DTrainer(): def __init__(self, input_A, input_B, fake_B, cfg, step_per_epoch): self.program = fluid.default_main_program().clone() lr = cfg.learning_rate with fluid.program_guard(self.program): model = Pix2pix_model() self.real_AB = fluid.layers.concat([input_A, input_B], 1) self.fake_AB = fluid.layers.concat([input_A, fake_B], 1) self.pred_real = model.network_D( self.real_AB, "discriminator", cfg=cfg) self.pred_fake = model.network_D( self.fake_AB, "discriminator", cfg=cfg) if cfg.gan_mode == "lsgan": ones = fluid.layers.fill_constant_batch_size_like( input=self.pred_real, shape=self.pred_real.shape, value=1, dtype='float32') self.d_loss_real = fluid.layers.reduce_mean( fluid.layers.square( fluid.layers.elementwise_sub( x=self.pred_real, y=ones))) self.d_loss_fake = fluid.layers.reduce_mean( fluid.layers.square(x=self.pred_fake)) elif cfg.gan_mode == "vanilla": pred_shape = self.pred_real.shape self.pred_real = fluid.layers.reshape( self.pred_real, [-1, pred_shape[1] * pred_shape[2] * pred_shape[3]], inplace=True) self.pred_fake = fluid.layers.reshape( self.pred_fake, [-1, pred_shape[1] * pred_shape[2] * pred_shape[3]], inplace=True) zeros = fluid.layers.fill_constant_batch_size_like( input=self.pred_fake, shape=self.pred_fake.shape, value=0, dtype='float32') ones = fluid.layers.fill_constant_batch_size_like( input=self.pred_real, shape=self.pred_real.shape, value=1, dtype='float32') self.d_loss_real = fluid.layers.mean( fluid.layers.sigmoid_cross_entropy_with_logits( x=self.pred_real, label=ones)) self.d_loss_fake = fluid.layers.mean( fluid.layers.sigmoid_cross_entropy_with_logits( x=self.pred_fake, label=zeros)) else: raise NotImplementedError("gan_mode {} is not support!".format( cfg.gan_mode)) self.d_loss = 0.5 * (self.d_loss_real + self.d_loss_fake) vars = [] for var in self.program.list_vars(): if fluid.io.is_parameter(var) and var.name.startswith( "discriminator"): vars.append(var.name) self.param = vars if cfg.epoch <= 100: optimizer = fluid.optimizer.Adam( learning_rate=lr, beta1=0.5, beta2=0.999, name="net_D") else: optimizer = fluid.optimizer.Adam( learning_rate=fluid.layers.piecewise_decay( boundaries=[99 * step_per_epoch] + [ x * step_per_epoch for x in range(100, cfg.epoch - 1) ], values=[lr] + [ lr * (1.0 - (x - 99.0) / 101.0) for x in range(100, cfg.epoch) ]), beta1=0.5, beta2=0.999, name="net_D") optimizer.minimize(self.d_loss, parameter_list=vars) class Pix2pix(object): def add_special_args(self, parser): parser.add_argument( '--net_G', type=str, default="unet_256", help="Choose the Pix2pix generator's network, choose in [resnet_9block|resnet_6block|unet_128|unet_256]" ) parser.add_argument( '--net_D', type=str, default="basic", help="Choose the Pix2pix discriminator's network, choose in [basic|nlayers|pixel]" ) parser.add_argument( '--d_nlayers', type=int, default=3, help="only used when Pix2pix discriminator is nlayers") parser.add_argument( '--enable_ce', action='store_true', help="if set, run the tasks with continuous evaluation logs") return parser def __init__(self, cfg=None, train_reader=None, test_reader=None, batch_num=1, id2name=None): self.cfg = cfg self.train_reader = train_reader self.test_reader = test_reader self.batch_num = batch_num self.id2name = id2name def build_model(self): data_shape = [None, 3, self.cfg.crop_size, self.cfg.crop_size] input_A = fluid.data(name='input_A', shape=data_shape, dtype='float32') input_B = fluid.data(name='input_B', shape=data_shape, dtype='float32') input_fake = fluid.data( name='input_fake', shape=data_shape, dtype='float32') if self.cfg.enable_ce: fluid.default_startup_program().random_seed = 90 loader = fluid.io.DataLoader.from_generator( feed_list=[input_A, input_B], capacity=4, iterable=True, use_double_buffer=True) gen_trainer = GTrainer(input_A, input_B, self.cfg, self.batch_num) dis_trainer = DTrainer(input_A, input_B, input_fake, self.cfg, self.batch_num) place = fluid.CUDAPlace(0) if self.cfg.use_gpu else fluid.CPUPlace() loader.set_batch_generator( self.train_reader, places=fluid.cuda_places() if self.cfg.use_gpu else fluid.cpu_places()) exe = fluid.Executor(place) exe.run(fluid.default_startup_program()) if self.cfg.init_model: utility.init_checkpoints(self.cfg, exe, gen_trainer, "net_G") utility.init_checkpoints(self.cfg, exe, dis_trainer, "net_D") id.BuildStrategy() gen_trainer_program = fluid.CompiledProgram( gen_trainer.program).with_data_parallel( loss_name=gen_trainer.g_loss.name, build_strategy=build_strategy) dis_trainer_program = fluid.CompiledProgram( dis_trainer.program).with_data_parallel( loss_name=dis_trainer.d_loss.name, build_strategy=build_strategy) t_time = 0 total_train_batch = 0 for epoch_id in range(self.cfg.epoch): batch_id = 0 for tensor in loader(): if self.cfg.max_iter and total_train_batch == self.cfg.max_iter: return s_time = time.time() g_loss_gan, g_loss_l1, fake_B_tmp = exe.run( gen_trainer_program, fetch_list=[ gen_trainer.g_loss_gan, gen_trainer.g_loss_L1, gen_trainer.fake_B ], feed=tensor) devices_num = utility.get_device_num(self.cfg) fake_per_device = int(len(fake_B_tmp) / devices_num) for dev in range(devices_num): tensor[dev]['input_fake'] = fake_B_tmp[dev * fake_per_device : (dev+1) * fake_per_device] d_loss_real, d_loss_fake = exe.run(dis_trainer_program, fetch_list=[ dis_trainer.d_loss_real, dis_trainer.d_loss_fake ], feed=tensor) batch_time = time.time() - s_time t_time += batch_time if batch_id % self.cfg.print_freq == 0: print("epoch{}: batch{}: \n\ g_loss_gan: {}; g_loss_l1: {}; \n\ d_loss_real: {}; d_loss_fake: {}; \n\ Batch_time_cost: {}" .format(epoch_id, batch_id, g_loss_gan[0], g_loss_l1[ 0], d_loss_real[0], d_loss_fake[0], batch_time)) sys.stdout.flush() batch_id += 1 total_train_batch += 1 if self.cfg.profile and epoch_id == 0 and batch_id == self.cfg.print_freq: profiler.reset_profiler() elif self.cfg.profile and epoch_id == 0 and batch_id == self.cfg.print_freq + 5: return if self.cfg.run_test: image_name = fluid.data( name='image_name', shape=[None, self.cfg.batch_size], dtype="int32") test_loader = fluid.io.DataLoader.from_generator( feed_list=[input_A, input_B, image_name], capacity=4, iterable=True, use_double_buffer=True) test_loader.set_batch_generator( self.test_reader, places=fluid.cuda_places() if self.cfg.use_gpu else fluid.cpu_places()) test_program = gen_trainer.infer_program utility.save_test_image( epoch_id, self.cfg, exe, place, test_program, gen_trainer, test_loader, A_id2name=self.id2name) if self.cfg.save_checkpoints: utility.checkpoints(epoch_id, self.cfg, exe, gen_trainer, "net_G") utility.checkpoints(epoch_id, self.cfg, exe, dis_trainer, "net_D") if self.cfg.enable_ce: device_num = fluid.core.get_cuda_device_count( ) if self.cfg.use_gpu else 1 print("kpis\tpix2pix_g_loss_gan_card{}\t{}".format(device_num, g_loss_gan[0])) print("kpis\tpix2pix_g_loss_l1_card{}\t{}".format(device_num, g_loss_l1[0])) print("kpis\tpix2pix_d_loss_real_card{}\t{}".format(device_num, d_loss_real[0])) print("kpis\tpix2pix_d_loss_fake_card{}\t{}".format(device_num, d_loss_fake[0])) print("kpis\tpix2pix_Batch_time_cost_card{}\t{}".format(device_num, batch_time))
true
true
1c340a6352846a6f94a05e23657cc0dadbe2b9f6
24,811
py
Python
test/functional/feature_csv_activation.py
Dollar-coin/Dollar
4b84e5d14408f3985d527aaccac21472b47c91d5
[ "MIT" ]
1
2021-02-06T22:18:29.000Z
2021-02-06T22:18:29.000Z
test/functional/feature_csv_activation.py
Dollar-coin/Dollar
4b84e5d14408f3985d527aaccac21472b47c91d5
[ "MIT" ]
1
2021-02-07T00:57:29.000Z
2021-02-07T10:22:29.000Z
test/functional/feature_csv_activation.py
Dollar-coin/Dollar
4b84e5d14408f3985d527aaccac21472b47c91d5
[ "MIT" ]
1
2021-02-26T22:29:45.000Z
2021-02-26T22:29:45.000Z
#!/usr/bin/env python3 # Copyright (c) 2015-2018 The Bitcoin Core developers # Distributed under the MIT software license, see the accompanying # file COPYING or http://www.opensource.org/licenses/mit-license.php. """Test activation of the first version bits soft fork. This soft fork will activate the following BIPS: BIP 68 - nSequence relative lock times BIP 112 - CHECKSEQUENCEVERIFY BIP 113 - MedianTimePast semantics for nLockTime regtest lock-in with 108/144 block signalling activation after a further 144 blocks mine 82 blocks whose coinbases will be used to generate inputs for our tests mine 61 blocks to transition from DEFINED to STARTED mine 144 blocks only 100 of which are signaling readiness in order to fail to change state this period mine 144 blocks with 108 signaling and verify STARTED->LOCKED_IN mine 140 blocks and seed block chain with the 82 inputs will use for our tests at height 572 mine 3 blocks and verify still at LOCKED_IN and test that enforcement has not triggered mine 1 block and test that enforcement has triggered (which triggers ACTIVE) Test BIP 113 is enforced Mine 4 blocks so next height is 580 and test BIP 68 is enforced for time and height Mine 1 block so next height is 581 and test BIP 68 now passes time but not height Mine 1 block so next height is 582 and test BIP 68 now passes time and height Test that BIP 112 is enforced Various transactions will be used to test that the BIPs rules are not enforced before the soft fork activates And that after the soft fork activates transactions pass and fail as they should according to the rules. For each BIP, transactions of versions 1 and 2 will be tested. ---------------- BIP 113: bip113tx - modify the nLocktime variable BIP 68: bip68txs - 16 txs with nSequence relative locktime of 10 with various bits set as per the relative_locktimes below BIP 112: bip112txs_vary_nSequence - 16 txs with nSequence relative_locktimes of 10 evaluated against 10 OP_CSV OP_DROP bip112txs_vary_nSequence_9 - 16 txs with nSequence relative_locktimes of 9 evaluated against 10 OP_CSV OP_DROP bip112txs_vary_OP_CSV - 16 txs with nSequence = 10 evaluated against varying {relative_locktimes of 10} OP_CSV OP_DROP bip112txs_vary_OP_CSV_9 - 16 txs with nSequence = 9 evaluated against varying {relative_locktimes of 10} OP_CSV OP_DROP bip112tx_special - test negative argument to OP_CSV """ from decimal import Decimal from itertools import product from io import BytesIO import time from test_framework.blocktools import create_coinbase, create_block, create_transaction from test_framework.messages import ToHex, CTransaction from test_framework.mininode import P2PDataStore from test_framework.script import ( CScript, OP_CHECKSEQUENCEVERIFY, OP_DROP, ) from test_framework.test_framework import DollarTestFramework from test_framework.util import ( assert_equal, get_bip9_status, hex_str_to_bytes, ) BASE_RELATIVE_LOCKTIME = 10 SEQ_DISABLE_FLAG = 1 << 31 SEQ_RANDOM_HIGH_BIT = 1 << 25 SEQ_TYPE_FLAG = 1 << 22 SEQ_RANDOM_LOW_BIT = 1 << 18 def relative_locktime(sdf, srhb, stf, srlb): """Returns a locktime with certain bits set.""" locktime = BASE_RELATIVE_LOCKTIME if sdf: locktime |= SEQ_DISABLE_FLAG if srhb: locktime |= SEQ_RANDOM_HIGH_BIT if stf: locktime |= SEQ_TYPE_FLAG if srlb: locktime |= SEQ_RANDOM_LOW_BIT return locktime def all_rlt_txs(txs): return [tx['tx'] for tx in txs] def sign_transaction(node, unsignedtx): rawtx = ToHex(unsignedtx) signresult = node.signrawtransactionwithwallet(rawtx) tx = CTransaction() f = BytesIO(hex_str_to_bytes(signresult['hex'])) tx.deserialize(f) return tx def create_bip112special(node, input, txversion, address): tx = create_transaction(node, input, address, amount=Decimal("49.98")) tx.nVersion = txversion signtx = sign_transaction(node, tx) signtx.vin[0].scriptSig = CScript([-1, OP_CHECKSEQUENCEVERIFY, OP_DROP] + list(CScript(signtx.vin[0].scriptSig))) return signtx def send_generic_input_tx(node, coinbases, address): return node.sendrawtransaction(ToHex(sign_transaction(node, create_transaction(node, node.getblock(coinbases.pop())['tx'][0], address, amount=Decimal("49.99"))))) def create_bip68txs(node, bip68inputs, txversion, address, locktime_delta=0): """Returns a list of bip68 transactions with different bits set.""" txs = [] assert(len(bip68inputs) >= 16) for i, (sdf, srhb, stf, srlb) in enumerate(product(*[[True, False]] * 4)): locktime = relative_locktime(sdf, srhb, stf, srlb) tx = create_transaction(node, bip68inputs[i], address, amount=Decimal("49.98")) tx.nVersion = txversion tx.vin[0].nSequence = locktime + locktime_delta tx = sign_transaction(node, tx) tx.rehash() txs.append({'tx': tx, 'sdf': sdf, 'stf': stf}) return txs def create_bip112txs(node, bip112inputs, varyOP_CSV, txversion, address, locktime_delta=0): """Returns a list of bip68 transactions with different bits set.""" txs = [] assert(len(bip112inputs) >= 16) for i, (sdf, srhb, stf, srlb) in enumerate(product(*[[True, False]] * 4)): locktime = relative_locktime(sdf, srhb, stf, srlb) tx = create_transaction(node, bip112inputs[i], address, amount=Decimal("49.98")) if (varyOP_CSV): # if varying OP_CSV, nSequence is fixed tx.vin[0].nSequence = BASE_RELATIVE_LOCKTIME + locktime_delta else: # vary nSequence instead, OP_CSV is fixed tx.vin[0].nSequence = locktime + locktime_delta tx.nVersion = txversion signtx = sign_transaction(node, tx) if (varyOP_CSV): signtx.vin[0].scriptSig = CScript([locktime, OP_CHECKSEQUENCEVERIFY, OP_DROP] + list(CScript(signtx.vin[0].scriptSig))) else: signtx.vin[0].scriptSig = CScript([BASE_RELATIVE_LOCKTIME, OP_CHECKSEQUENCEVERIFY, OP_DROP] + list(CScript(signtx.vin[0].scriptSig))) tx.rehash() txs.append({'tx': signtx, 'sdf': sdf, 'stf': stf}) return txs class BIP68_112_113Test(DollarTestFramework): def set_test_params(self): self.num_nodes = 1 self.setup_clean_chain = True self.extra_args = [['-whitelist=127.0.0.1', '-blockversion=4', '-addresstype=legacy']] def skip_test_if_missing_module(self): self.skip_if_no_wallet() def generate_blocks(self, number, version, test_blocks=None): if test_blocks is None: test_blocks = [] for i in range(number): block = self.create_test_block([], version) test_blocks.append(block) self.last_block_time += 600 self.tip = block.sha256 self.tipheight += 1 return test_blocks def create_test_block(self, txs, version=536870912): block = create_block(self.tip, create_coinbase(self.tipheight + 1), self.last_block_time + 600) block.nVersion = version block.vtx.extend(txs) block.hashMerkleRoot = block.calc_merkle_root() block.rehash() block.solve() return block def sync_blocks(self, blocks, success=True, reject_code=None, reject_reason=None, request_block=True): """Sends blocks to test node. Syncs and verifies that tip has advanced to most recent block. Call with success = False if the tip shouldn't advance to the most recent block.""" self.nodes[0].p2p.send_blocks_and_test(blocks, self.nodes[0], success=success, reject_code=reject_code, reject_reason=reject_reason, request_block=request_block) def run_test(self): self.nodes[0].add_p2p_connection(P2PDataStore()) self.log.info("Generate blocks in the past for coinbase outputs.") long_past_time = int(time.time()) - 600 * 1000 # enough to build up to 1000 blocks 10 minutes apart without worrying about getting into the future self.nodes[0].setmocktime(long_past_time - 100) # enough so that the generated blocks will still all be before long_past_time self.coinbase_blocks = self.nodes[0].generate(1 + 16 + 2 * 32 + 1) # 82 blocks generated for inputs self.nodes[0].setmocktime(0) # set time back to present so yielded blocks aren't in the future as we advance last_block_time self.tipheight = 82 # height of the next block to build self.last_block_time = long_past_time self.tip = int(self.nodes[0].getbestblockhash(), 16) self.nodeaddress = self.nodes[0].getnewaddress() self.log.info("Test that the csv softfork is DEFINED") assert_equal(get_bip9_status(self.nodes[0], 'csv')['status'], 'defined') test_blocks = self.generate_blocks(61, 4) self.sync_blocks(test_blocks) self.log.info("Advance from DEFINED to STARTED, height = 143") assert_equal(get_bip9_status(self.nodes[0], 'csv')['status'], 'started') self.log.info("Fail to achieve LOCKED_IN") # 100 out of 144 signal bit 0. Use a variety of bits to simulate multiple parallel softforks test_blocks = self.generate_blocks(50, 536870913) # 0x20000001 (signalling ready) test_blocks = self.generate_blocks(20, 4, test_blocks) # 0x00000004 (signalling not) test_blocks = self.generate_blocks(50, 536871169, test_blocks) # 0x20000101 (signalling ready) test_blocks = self.generate_blocks(24, 536936448, test_blocks) # 0x20010000 (signalling not) self.sync_blocks(test_blocks) self.log.info("Failed to advance past STARTED, height = 287") assert_equal(get_bip9_status(self.nodes[0], 'csv')['status'], 'started') self.log.info("Generate blocks to achieve LOCK-IN") # 108 out of 144 signal bit 0 to achieve lock-in # using a variety of bits to simulate multiple parallel softforks test_blocks = self.generate_blocks(58, 536870913) # 0x20000001 (signalling ready) test_blocks = self.generate_blocks(26, 4, test_blocks) # 0x00000004 (signalling not) test_blocks = self.generate_blocks(50, 536871169, test_blocks) # 0x20000101 (signalling ready) test_blocks = self.generate_blocks(10, 536936448, test_blocks) # 0x20010000 (signalling not) self.sync_blocks(test_blocks) self.log.info("Advanced from STARTED to LOCKED_IN, height = 431") assert_equal(get_bip9_status(self.nodes[0], 'csv')['status'], 'locked_in') # Generate 140 more version 4 blocks test_blocks = self.generate_blocks(140, 4) self.sync_blocks(test_blocks) # Inputs at height = 572 # # Put inputs for all tests in the chain at height 572 (tip now = 571) (time increases by 600s per block) # Note we reuse inputs for v1 and v2 txs so must test these separately # 16 normal inputs bip68inputs = [] for i in range(16): bip68inputs.append(send_generic_input_tx(self.nodes[0], self.coinbase_blocks, self.nodeaddress)) # 2 sets of 16 inputs with 10 OP_CSV OP_DROP (actually will be prepended to spending scriptSig) bip112basicinputs = [] for j in range(2): inputs = [] for i in range(16): inputs.append(send_generic_input_tx(self.nodes[0], self.coinbase_blocks, self.nodeaddress)) bip112basicinputs.append(inputs) # 2 sets of 16 varied inputs with (relative_lock_time) OP_CSV OP_DROP (actually will be prepended to spending scriptSig) bip112diverseinputs = [] for j in range(2): inputs = [] for i in range(16): inputs.append(send_generic_input_tx(self.nodes[0], self.coinbase_blocks, self.nodeaddress)) bip112diverseinputs.append(inputs) # 1 special input with -1 OP_CSV OP_DROP (actually will be prepended to spending scriptSig) bip112specialinput = send_generic_input_tx(self.nodes[0], self.coinbase_blocks, self.nodeaddress) # 1 normal input bip113input = send_generic_input_tx(self.nodes[0], self.coinbase_blocks, self.nodeaddress) self.nodes[0].setmocktime(self.last_block_time + 600) inputblockhash = self.nodes[0].generate(1)[0] # 1 block generated for inputs to be in chain at height 572 self.nodes[0].setmocktime(0) self.tip = int(inputblockhash, 16) self.tipheight += 1 self.last_block_time += 600 assert_equal(len(self.nodes[0].getblock(inputblockhash, True)["tx"]), 82 + 1) # 2 more version 4 blocks test_blocks = self.generate_blocks(2, 4) self.sync_blocks(test_blocks) self.log.info("Not yet advanced to ACTIVE, height = 574 (will activate for block 576, not 575)") assert_equal(get_bip9_status(self.nodes[0], 'csv')['status'], 'locked_in') # Test both version 1 and version 2 transactions for all tests # BIP113 test transaction will be modified before each use to put in appropriate block time bip113tx_v1 = create_transaction(self.nodes[0], bip113input, self.nodeaddress, amount=Decimal("49.98")) bip113tx_v1.vin[0].nSequence = 0xFFFFFFFE bip113tx_v1.nVersion = 1 bip113tx_v2 = create_transaction(self.nodes[0], bip113input, self.nodeaddress, amount=Decimal("49.98")) bip113tx_v2.vin[0].nSequence = 0xFFFFFFFE bip113tx_v2.nVersion = 2 # For BIP68 test all 16 relative sequence locktimes bip68txs_v1 = create_bip68txs(self.nodes[0], bip68inputs, 1, self.nodeaddress) bip68txs_v2 = create_bip68txs(self.nodes[0], bip68inputs, 2, self.nodeaddress) # For BIP112 test: # 16 relative sequence locktimes of 10 against 10 OP_CSV OP_DROP inputs bip112txs_vary_nSequence_v1 = create_bip112txs(self.nodes[0], bip112basicinputs[0], False, 1, self.nodeaddress) bip112txs_vary_nSequence_v2 = create_bip112txs(self.nodes[0], bip112basicinputs[0], False, 2, self.nodeaddress) # 16 relative sequence locktimes of 9 against 10 OP_CSV OP_DROP inputs bip112txs_vary_nSequence_9_v1 = create_bip112txs(self.nodes[0], bip112basicinputs[1], False, 1, self.nodeaddress, -1) bip112txs_vary_nSequence_9_v2 = create_bip112txs(self.nodes[0], bip112basicinputs[1], False, 2, self.nodeaddress, -1) # sequence lock time of 10 against 16 (relative_lock_time) OP_CSV OP_DROP inputs bip112txs_vary_OP_CSV_v1 = create_bip112txs(self.nodes[0], bip112diverseinputs[0], True, 1, self.nodeaddress) bip112txs_vary_OP_CSV_v2 = create_bip112txs(self.nodes[0], bip112diverseinputs[0], True, 2, self.nodeaddress) # sequence lock time of 9 against 16 (relative_lock_time) OP_CSV OP_DROP inputs bip112txs_vary_OP_CSV_9_v1 = create_bip112txs(self.nodes[0], bip112diverseinputs[1], True, 1, self.nodeaddress, -1) bip112txs_vary_OP_CSV_9_v2 = create_bip112txs(self.nodes[0], bip112diverseinputs[1], True, 2, self.nodeaddress, -1) # -1 OP_CSV OP_DROP input bip112tx_special_v1 = create_bip112special(self.nodes[0], bip112specialinput, 1, self.nodeaddress) bip112tx_special_v2 = create_bip112special(self.nodes[0], bip112specialinput, 2, self.nodeaddress) self.log.info("TESTING") self.log.info("Pre-Soft Fork Tests. All txs should pass.") self.log.info("Test version 1 txs") success_txs = [] # add BIP113 tx and -1 CSV tx bip113tx_v1.nLockTime = self.last_block_time - 600 * 5 # = MTP of prior block (not <) but < time put on current block bip113signed1 = sign_transaction(self.nodes[0], bip113tx_v1) success_txs.append(bip113signed1) success_txs.append(bip112tx_special_v1) # add BIP 68 txs success_txs.extend(all_rlt_txs(bip68txs_v1)) # add BIP 112 with seq=10 txs success_txs.extend(all_rlt_txs(bip112txs_vary_nSequence_v1)) success_txs.extend(all_rlt_txs(bip112txs_vary_OP_CSV_v1)) # try BIP 112 with seq=9 txs success_txs.extend(all_rlt_txs(bip112txs_vary_nSequence_9_v1)) success_txs.extend(all_rlt_txs(bip112txs_vary_OP_CSV_9_v1)) self.sync_blocks([self.create_test_block(success_txs)]) self.nodes[0].invalidateblock(self.nodes[0].getbestblockhash()) self.log.info("Test version 2 txs") success_txs = [] # add BIP113 tx and -1 CSV tx bip113tx_v2.nLockTime = self.last_block_time - 600 * 5 # = MTP of prior block (not <) but < time put on current block bip113signed2 = sign_transaction(self.nodes[0], bip113tx_v2) success_txs.append(bip113signed2) success_txs.append(bip112tx_special_v2) # add BIP 68 txs success_txs.extend(all_rlt_txs(bip68txs_v2)) # add BIP 112 with seq=10 txs success_txs.extend(all_rlt_txs(bip112txs_vary_nSequence_v2)) success_txs.extend(all_rlt_txs(bip112txs_vary_OP_CSV_v2)) # try BIP 112 with seq=9 txs success_txs.extend(all_rlt_txs(bip112txs_vary_nSequence_9_v2)) success_txs.extend(all_rlt_txs(bip112txs_vary_OP_CSV_9_v2)) self.sync_blocks([self.create_test_block(success_txs)]) self.nodes[0].invalidateblock(self.nodes[0].getbestblockhash()) # 1 more version 4 block to get us to height 575 so the fork should now be active for the next block test_blocks = self.generate_blocks(1, 4) self.sync_blocks(test_blocks) assert_equal(get_bip9_status(self.nodes[0], 'csv')['status'], 'active') self.log.info("Post-Soft Fork Tests.") self.log.info("BIP 113 tests") # BIP 113 tests should now fail regardless of version number if nLockTime isn't satisfied by new rules bip113tx_v1.nLockTime = self.last_block_time - 600 * 5 # = MTP of prior block (not <) but < time put on current block bip113signed1 = sign_transaction(self.nodes[0], bip113tx_v1) bip113tx_v2.nLockTime = self.last_block_time - 600 * 5 # = MTP of prior block (not <) but < time put on current block bip113signed2 = sign_transaction(self.nodes[0], bip113tx_v2) for bip113tx in [bip113signed1, bip113signed2]: self.sync_blocks([self.create_test_block([bip113tx])], success=False) # BIP 113 tests should now pass if the locktime is < MTP bip113tx_v1.nLockTime = self.last_block_time - 600 * 5 - 1 # < MTP of prior block bip113signed1 = sign_transaction(self.nodes[0], bip113tx_v1) bip113tx_v2.nLockTime = self.last_block_time - 600 * 5 - 1 # < MTP of prior block bip113signed2 = sign_transaction(self.nodes[0], bip113tx_v2) for bip113tx in [bip113signed1, bip113signed2]: self.sync_blocks([self.create_test_block([bip113tx])]) self.nodes[0].invalidateblock(self.nodes[0].getbestblockhash()) # Next block height = 580 after 4 blocks of random version test_blocks = self.generate_blocks(4, 1234) self.sync_blocks(test_blocks) self.log.info("BIP 68 tests") self.log.info("Test version 1 txs - all should still pass") success_txs = [] success_txs.extend(all_rlt_txs(bip68txs_v1)) self.sync_blocks([self.create_test_block(success_txs)]) self.nodes[0].invalidateblock(self.nodes[0].getbestblockhash()) self.log.info("Test version 2 txs") # All txs with SEQUENCE_LOCKTIME_DISABLE_FLAG set pass bip68success_txs = [tx['tx'] for tx in bip68txs_v2 if tx['sdf']] self.sync_blocks([self.create_test_block(bip68success_txs)]) self.nodes[0].invalidateblock(self.nodes[0].getbestblockhash()) # All txs without flag fail as we are at delta height = 8 < 10 and delta time = 8 * 600 < 10 * 512 bip68timetxs = [tx['tx'] for tx in bip68txs_v2 if not tx['sdf'] and tx['stf']] for tx in bip68timetxs: self.sync_blocks([self.create_test_block([tx])], success=False) bip68heighttxs = [tx['tx'] for tx in bip68txs_v2 if not tx['sdf'] and not tx['stf']] for tx in bip68heighttxs: self.sync_blocks([self.create_test_block([tx])], success=False) # Advance one block to 581 test_blocks = self.generate_blocks(1, 1234) self.sync_blocks(test_blocks) # Height txs should fail and time txs should now pass 9 * 600 > 10 * 512 bip68success_txs.extend(bip68timetxs) self.sync_blocks([self.create_test_block(bip68success_txs)]) self.nodes[0].invalidateblock(self.nodes[0].getbestblockhash()) for tx in bip68heighttxs: self.sync_blocks([self.create_test_block([tx])], success=False) # Advance one block to 582 test_blocks = self.generate_blocks(1, 1234) self.sync_blocks(test_blocks) # All BIP 68 txs should pass bip68success_txs.extend(bip68heighttxs) self.sync_blocks([self.create_test_block(bip68success_txs)]) self.nodes[0].invalidateblock(self.nodes[0].getbestblockhash()) self.log.info("BIP 112 tests") self.log.info("Test version 1 txs") # -1 OP_CSV tx should fail self.sync_blocks([self.create_test_block([bip112tx_special_v1])], success=False) # If SEQUENCE_LOCKTIME_DISABLE_FLAG is set in argument to OP_CSV, version 1 txs should still pass success_txs = [tx['tx'] for tx in bip112txs_vary_OP_CSV_v1 if tx['sdf']] success_txs += [tx['tx'] for tx in bip112txs_vary_OP_CSV_9_v1 if tx['sdf']] self.sync_blocks([self.create_test_block(success_txs)]) self.nodes[0].invalidateblock(self.nodes[0].getbestblockhash()) # If SEQUENCE_LOCKTIME_DISABLE_FLAG is unset in argument to OP_CSV, version 1 txs should now fail fail_txs = all_rlt_txs(bip112txs_vary_nSequence_v1) fail_txs += all_rlt_txs(bip112txs_vary_nSequence_9_v1) fail_txs += [tx['tx'] for tx in bip112txs_vary_OP_CSV_9_v1 if not tx['sdf']] fail_txs += [tx['tx'] for tx in bip112txs_vary_OP_CSV_9_v1 if not tx['sdf']] for tx in fail_txs: self.sync_blocks([self.create_test_block([tx])], success=False) self.log.info("Test version 2 txs") # -1 OP_CSV tx should fail self.sync_blocks([self.create_test_block([bip112tx_special_v2])], success=False) # If SEQUENCE_LOCKTIME_DISABLE_FLAG is set in argument to OP_CSV, version 2 txs should pass (all sequence locks are met) success_txs = [tx['tx'] for tx in bip112txs_vary_OP_CSV_v2 if tx['sdf']] success_txs += [tx['tx'] for tx in bip112txs_vary_OP_CSV_9_v2 if tx['sdf']] self.sync_blocks([self.create_test_block(success_txs)]) self.nodes[0].invalidateblock(self.nodes[0].getbestblockhash()) # SEQUENCE_LOCKTIME_DISABLE_FLAG is unset in argument to OP_CSV for all remaining txs ## # All txs with nSequence 9 should fail either due to earlier mismatch or failing the CSV check fail_txs = all_rlt_txs(bip112txs_vary_nSequence_9_v2) fail_txs += [tx['tx'] for tx in bip112txs_vary_OP_CSV_9_v2 if not tx['sdf']] for tx in fail_txs: self.sync_blocks([self.create_test_block([tx])], success=False) # If SEQUENCE_LOCKTIME_DISABLE_FLAG is set in nSequence, tx should fail fail_txs = [tx['tx'] for tx in bip112txs_vary_nSequence_v2 if tx['sdf']] for tx in fail_txs: self.sync_blocks([self.create_test_block([tx])], success=False) # If sequencelock types mismatch, tx should fail fail_txs = [tx['tx'] for tx in bip112txs_vary_nSequence_v2 if not tx['sdf'] and tx['stf']] fail_txs += [tx['tx'] for tx in bip112txs_vary_OP_CSV_v2 if not tx['sdf'] and tx['stf']] for tx in fail_txs: self.sync_blocks([self.create_test_block([tx])], success=False) # Remaining txs should pass, just test masking works properly success_txs = [tx['tx'] for tx in bip112txs_vary_nSequence_v2 if not tx['sdf'] and not tx['stf']] success_txs += [tx['tx'] for tx in bip112txs_vary_OP_CSV_v2 if not tx['sdf'] and not tx['stf']] self.sync_blocks([self.create_test_block(success_txs)]) self.nodes[0].invalidateblock(self.nodes[0].getbestblockhash()) # Additional test, of checking that comparison of two time types works properly time_txs = [] for tx in [tx['tx'] for tx in bip112txs_vary_OP_CSV_v2 if not tx['sdf'] and tx['stf']]: tx.vin[0].nSequence = BASE_RELATIVE_LOCKTIME | SEQ_TYPE_FLAG signtx = sign_transaction(self.nodes[0], tx) time_txs.append(signtx) self.sync_blocks([self.create_test_block(time_txs)]) self.nodes[0].invalidateblock(self.nodes[0].getbestblockhash()) # TODO: Test empty stack fails if __name__ == '__main__': BIP68_112_113Test().main()
51.05144
169
0.696506
from decimal import Decimal from itertools import product from io import BytesIO import time from test_framework.blocktools import create_coinbase, create_block, create_transaction from test_framework.messages import ToHex, CTransaction from test_framework.mininode import P2PDataStore from test_framework.script import ( CScript, OP_CHECKSEQUENCEVERIFY, OP_DROP, ) from test_framework.test_framework import DollarTestFramework from test_framework.util import ( assert_equal, get_bip9_status, hex_str_to_bytes, ) BASE_RELATIVE_LOCKTIME = 10 SEQ_DISABLE_FLAG = 1 << 31 SEQ_RANDOM_HIGH_BIT = 1 << 25 SEQ_TYPE_FLAG = 1 << 22 SEQ_RANDOM_LOW_BIT = 1 << 18 def relative_locktime(sdf, srhb, stf, srlb): locktime = BASE_RELATIVE_LOCKTIME if sdf: locktime |= SEQ_DISABLE_FLAG if srhb: locktime |= SEQ_RANDOM_HIGH_BIT if stf: locktime |= SEQ_TYPE_FLAG if srlb: locktime |= SEQ_RANDOM_LOW_BIT return locktime def all_rlt_txs(txs): return [tx['tx'] for tx in txs] def sign_transaction(node, unsignedtx): rawtx = ToHex(unsignedtx) signresult = node.signrawtransactionwithwallet(rawtx) tx = CTransaction() f = BytesIO(hex_str_to_bytes(signresult['hex'])) tx.deserialize(f) return tx def create_bip112special(node, input, txversion, address): tx = create_transaction(node, input, address, amount=Decimal("49.98")) tx.nVersion = txversion signtx = sign_transaction(node, tx) signtx.vin[0].scriptSig = CScript([-1, OP_CHECKSEQUENCEVERIFY, OP_DROP] + list(CScript(signtx.vin[0].scriptSig))) return signtx def send_generic_input_tx(node, coinbases, address): return node.sendrawtransaction(ToHex(sign_transaction(node, create_transaction(node, node.getblock(coinbases.pop())['tx'][0], address, amount=Decimal("49.99"))))) def create_bip68txs(node, bip68inputs, txversion, address, locktime_delta=0): txs = [] assert(len(bip68inputs) >= 16) for i, (sdf, srhb, stf, srlb) in enumerate(product(*[[True, False]] * 4)): locktime = relative_locktime(sdf, srhb, stf, srlb) tx = create_transaction(node, bip68inputs[i], address, amount=Decimal("49.98")) tx.nVersion = txversion tx.vin[0].nSequence = locktime + locktime_delta tx = sign_transaction(node, tx) tx.rehash() txs.append({'tx': tx, 'sdf': sdf, 'stf': stf}) return txs def create_bip112txs(node, bip112inputs, varyOP_CSV, txversion, address, locktime_delta=0): txs = [] assert(len(bip112inputs) >= 16) for i, (sdf, srhb, stf, srlb) in enumerate(product(*[[True, False]] * 4)): locktime = relative_locktime(sdf, srhb, stf, srlb) tx = create_transaction(node, bip112inputs[i], address, amount=Decimal("49.98")) if (varyOP_CSV): tx.vin[0].nSequence = BASE_RELATIVE_LOCKTIME + locktime_delta else: tx.vin[0].nSequence = locktime + locktime_delta tx.nVersion = txversion signtx = sign_transaction(node, tx) if (varyOP_CSV): signtx.vin[0].scriptSig = CScript([locktime, OP_CHECKSEQUENCEVERIFY, OP_DROP] + list(CScript(signtx.vin[0].scriptSig))) else: signtx.vin[0].scriptSig = CScript([BASE_RELATIVE_LOCKTIME, OP_CHECKSEQUENCEVERIFY, OP_DROP] + list(CScript(signtx.vin[0].scriptSig))) tx.rehash() txs.append({'tx': signtx, 'sdf': sdf, 'stf': stf}) return txs class BIP68_112_113Test(DollarTestFramework): def set_test_params(self): self.num_nodes = 1 self.setup_clean_chain = True self.extra_args = [['-whitelist=127.0.0.1', '-blockversion=4', '-addresstype=legacy']] def skip_test_if_missing_module(self): self.skip_if_no_wallet() def generate_blocks(self, number, version, test_blocks=None): if test_blocks is None: test_blocks = [] for i in range(number): block = self.create_test_block([], version) test_blocks.append(block) self.last_block_time += 600 self.tip = block.sha256 self.tipheight += 1 return test_blocks def create_test_block(self, txs, version=536870912): block = create_block(self.tip, create_coinbase(self.tipheight + 1), self.last_block_time + 600) block.nVersion = version block.vtx.extend(txs) block.hashMerkleRoot = block.calc_merkle_root() block.rehash() block.solve() return block def sync_blocks(self, blocks, success=True, reject_code=None, reject_reason=None, request_block=True): self.nodes[0].p2p.send_blocks_and_test(blocks, self.nodes[0], success=success, reject_code=reject_code, reject_reason=reject_reason, request_block=request_block) def run_test(self): self.nodes[0].add_p2p_connection(P2PDataStore()) self.log.info("Generate blocks in the past for coinbase outputs.") long_past_time = int(time.time()) - 600 * 1000 self.nodes[0].setmocktime(long_past_time - 100) self.coinbase_blocks = self.nodes[0].generate(1 + 16 + 2 * 32 + 1) self.nodes[0].setmocktime(0) self.tipheight = 82 # height of the next block to build self.last_block_time = long_past_time self.tip = int(self.nodes[0].getbestblockhash(), 16) self.nodeaddress = self.nodes[0].getnewaddress() self.log.info("Test that the csv softfork is DEFINED") assert_equal(get_bip9_status(self.nodes[0], 'csv')['status'], 'defined') test_blocks = self.generate_blocks(61, 4) self.sync_blocks(test_blocks) self.log.info("Advance from DEFINED to STARTED, height = 143") assert_equal(get_bip9_status(self.nodes[0], 'csv')['status'], 'started') self.log.info("Fail to achieve LOCKED_IN") # 100 out of 144 signal bit 0. Use a variety of bits to simulate multiple parallel softforks test_blocks = self.generate_blocks(50, 536870913) # 0x20000001 (signalling ready) test_blocks = self.generate_blocks(20, 4, test_blocks) # 0x00000004 (signalling not) test_blocks = self.generate_blocks(50, 536871169, test_blocks) # 0x20000101 (signalling ready) test_blocks = self.generate_blocks(24, 536936448, test_blocks) # 0x20010000 (signalling not) self.sync_blocks(test_blocks) self.log.info("Failed to advance past STARTED, height = 287") assert_equal(get_bip9_status(self.nodes[0], 'csv')['status'], 'started') self.log.info("Generate blocks to achieve LOCK-IN") # 108 out of 144 signal bit 0 to achieve lock-in # using a variety of bits to simulate multiple parallel softforks test_blocks = self.generate_blocks(58, 536870913) # 0x20000001 (signalling ready) test_blocks = self.generate_blocks(26, 4, test_blocks) # 0x00000004 (signalling not) test_blocks = self.generate_blocks(50, 536871169, test_blocks) # 0x20000101 (signalling ready) test_blocks = self.generate_blocks(10, 536936448, test_blocks) # 0x20010000 (signalling not) self.sync_blocks(test_blocks) self.log.info("Advanced from STARTED to LOCKED_IN, height = 431") assert_equal(get_bip9_status(self.nodes[0], 'csv')['status'], 'locked_in') # Generate 140 more version 4 blocks test_blocks = self.generate_blocks(140, 4) self.sync_blocks(test_blocks) # Inputs at height = 572 # # Put inputs for all tests in the chain at height 572 (tip now = 571) (time increases by 600s per block) # Note we reuse inputs for v1 and v2 txs so must test these separately # 16 normal inputs bip68inputs = [] for i in range(16): bip68inputs.append(send_generic_input_tx(self.nodes[0], self.coinbase_blocks, self.nodeaddress)) # 2 sets of 16 inputs with 10 OP_CSV OP_DROP (actually will be prepended to spending scriptSig) bip112basicinputs = [] for j in range(2): inputs = [] for i in range(16): inputs.append(send_generic_input_tx(self.nodes[0], self.coinbase_blocks, self.nodeaddress)) bip112basicinputs.append(inputs) # 2 sets of 16 varied inputs with (relative_lock_time) OP_CSV OP_DROP (actually will be prepended to spending scriptSig) bip112diverseinputs = [] for j in range(2): inputs = [] for i in range(16): inputs.append(send_generic_input_tx(self.nodes[0], self.coinbase_blocks, self.nodeaddress)) bip112diverseinputs.append(inputs) # 1 special input with -1 OP_CSV OP_DROP (actually will be prepended to spending scriptSig) bip112specialinput = send_generic_input_tx(self.nodes[0], self.coinbase_blocks, self.nodeaddress) # 1 normal input bip113input = send_generic_input_tx(self.nodes[0], self.coinbase_blocks, self.nodeaddress) self.nodes[0].setmocktime(self.last_block_time + 600) inputblockhash = self.nodes[0].generate(1)[0] # 1 block generated for inputs to be in chain at height 572 self.nodes[0].setmocktime(0) self.tip = int(inputblockhash, 16) self.tipheight += 1 self.last_block_time += 600 assert_equal(len(self.nodes[0].getblock(inputblockhash, True)["tx"]), 82 + 1) # 2 more version 4 blocks test_blocks = self.generate_blocks(2, 4) self.sync_blocks(test_blocks) self.log.info("Not yet advanced to ACTIVE, height = 574 (will activate for block 576, not 575)") assert_equal(get_bip9_status(self.nodes[0], 'csv')['status'], 'locked_in') # Test both version 1 and version 2 transactions for all tests # BIP113 test transaction will be modified before each use to put in appropriate block time bip113tx_v1 = create_transaction(self.nodes[0], bip113input, self.nodeaddress, amount=Decimal("49.98")) bip113tx_v1.vin[0].nSequence = 0xFFFFFFFE bip113tx_v1.nVersion = 1 bip113tx_v2 = create_transaction(self.nodes[0], bip113input, self.nodeaddress, amount=Decimal("49.98")) bip113tx_v2.vin[0].nSequence = 0xFFFFFFFE bip113tx_v2.nVersion = 2 # For BIP68 test all 16 relative sequence locktimes bip68txs_v1 = create_bip68txs(self.nodes[0], bip68inputs, 1, self.nodeaddress) bip68txs_v2 = create_bip68txs(self.nodes[0], bip68inputs, 2, self.nodeaddress) # For BIP112 test: # 16 relative sequence locktimes of 10 against 10 OP_CSV OP_DROP inputs bip112txs_vary_nSequence_v1 = create_bip112txs(self.nodes[0], bip112basicinputs[0], False, 1, self.nodeaddress) bip112txs_vary_nSequence_v2 = create_bip112txs(self.nodes[0], bip112basicinputs[0], False, 2, self.nodeaddress) # 16 relative sequence locktimes of 9 against 10 OP_CSV OP_DROP inputs bip112txs_vary_nSequence_9_v1 = create_bip112txs(self.nodes[0], bip112basicinputs[1], False, 1, self.nodeaddress, -1) bip112txs_vary_nSequence_9_v2 = create_bip112txs(self.nodes[0], bip112basicinputs[1], False, 2, self.nodeaddress, -1) # sequence lock time of 10 against 16 (relative_lock_time) OP_CSV OP_DROP inputs bip112txs_vary_OP_CSV_v1 = create_bip112txs(self.nodes[0], bip112diverseinputs[0], True, 1, self.nodeaddress) bip112txs_vary_OP_CSV_v2 = create_bip112txs(self.nodes[0], bip112diverseinputs[0], True, 2, self.nodeaddress) # sequence lock time of 9 against 16 (relative_lock_time) OP_CSV OP_DROP inputs bip112txs_vary_OP_CSV_9_v1 = create_bip112txs(self.nodes[0], bip112diverseinputs[1], True, 1, self.nodeaddress, -1) bip112txs_vary_OP_CSV_9_v2 = create_bip112txs(self.nodes[0], bip112diverseinputs[1], True, 2, self.nodeaddress, -1) # -1 OP_CSV OP_DROP input bip112tx_special_v1 = create_bip112special(self.nodes[0], bip112specialinput, 1, self.nodeaddress) bip112tx_special_v2 = create_bip112special(self.nodes[0], bip112specialinput, 2, self.nodeaddress) self.log.info("TESTING") self.log.info("Pre-Soft Fork Tests. All txs should pass.") self.log.info("Test version 1 txs") success_txs = [] # add BIP113 tx and -1 CSV tx bip113tx_v1.nLockTime = self.last_block_time - 600 * 5 # = MTP of prior block (not <) but < time put on current block bip113signed1 = sign_transaction(self.nodes[0], bip113tx_v1) success_txs.append(bip113signed1) success_txs.append(bip112tx_special_v1) # add BIP 68 txs success_txs.extend(all_rlt_txs(bip68txs_v1)) # add BIP 112 with seq=10 txs success_txs.extend(all_rlt_txs(bip112txs_vary_nSequence_v1)) success_txs.extend(all_rlt_txs(bip112txs_vary_OP_CSV_v1)) # try BIP 112 with seq=9 txs success_txs.extend(all_rlt_txs(bip112txs_vary_nSequence_9_v1)) success_txs.extend(all_rlt_txs(bip112txs_vary_OP_CSV_9_v1)) self.sync_blocks([self.create_test_block(success_txs)]) self.nodes[0].invalidateblock(self.nodes[0].getbestblockhash()) self.log.info("Test version 2 txs") success_txs = [] # add BIP113 tx and -1 CSV tx bip113tx_v2.nLockTime = self.last_block_time - 600 * 5 # = MTP of prior block (not <) but < time put on current block bip113signed2 = sign_transaction(self.nodes[0], bip113tx_v2) success_txs.append(bip113signed2) success_txs.append(bip112tx_special_v2) # add BIP 68 txs success_txs.extend(all_rlt_txs(bip68txs_v2)) # add BIP 112 with seq=10 txs success_txs.extend(all_rlt_txs(bip112txs_vary_nSequence_v2)) success_txs.extend(all_rlt_txs(bip112txs_vary_OP_CSV_v2)) # try BIP 112 with seq=9 txs success_txs.extend(all_rlt_txs(bip112txs_vary_nSequence_9_v2)) success_txs.extend(all_rlt_txs(bip112txs_vary_OP_CSV_9_v2)) self.sync_blocks([self.create_test_block(success_txs)]) self.nodes[0].invalidateblock(self.nodes[0].getbestblockhash()) # 1 more version 4 block to get us to height 575 so the fork should now be active for the next block test_blocks = self.generate_blocks(1, 4) self.sync_blocks(test_blocks) assert_equal(get_bip9_status(self.nodes[0], 'csv')['status'], 'active') self.log.info("Post-Soft Fork Tests.") self.log.info("BIP 113 tests") # BIP 113 tests should now fail regardless of version number if nLockTime isn't satisfied by new rules bip113tx_v1.nLockTime = self.last_block_time - 600 * 5 bip113signed1 = sign_transaction(self.nodes[0], bip113tx_v1) bip113tx_v2.nLockTime = self.last_block_time - 600 * 5 bip113signed2 = sign_transaction(self.nodes[0], bip113tx_v2) for bip113tx in [bip113signed1, bip113signed2]: self.sync_blocks([self.create_test_block([bip113tx])], success=False) bip113tx_v1.nLockTime = self.last_block_time - 600 * 5 - 1 bip113signed1 = sign_transaction(self.nodes[0], bip113tx_v1) bip113tx_v2.nLockTime = self.last_block_time - 600 * 5 - 1 bip113signed2 = sign_transaction(self.nodes[0], bip113tx_v2) for bip113tx in [bip113signed1, bip113signed2]: self.sync_blocks([self.create_test_block([bip113tx])]) self.nodes[0].invalidateblock(self.nodes[0].getbestblockhash()) test_blocks = self.generate_blocks(4, 1234) self.sync_blocks(test_blocks) self.log.info("BIP 68 tests") self.log.info("Test version 1 txs - all should still pass") success_txs = [] success_txs.extend(all_rlt_txs(bip68txs_v1)) self.sync_blocks([self.create_test_block(success_txs)]) self.nodes[0].invalidateblock(self.nodes[0].getbestblockhash()) self.log.info("Test version 2 txs") bip68success_txs = [tx['tx'] for tx in bip68txs_v2 if tx['sdf']] self.sync_blocks([self.create_test_block(bip68success_txs)]) self.nodes[0].invalidateblock(self.nodes[0].getbestblockhash()) bip68timetxs = [tx['tx'] for tx in bip68txs_v2 if not tx['sdf'] and tx['stf']] for tx in bip68timetxs: self.sync_blocks([self.create_test_block([tx])], success=False) bip68heighttxs = [tx['tx'] for tx in bip68txs_v2 if not tx['sdf'] and not tx['stf']] for tx in bip68heighttxs: self.sync_blocks([self.create_test_block([tx])], success=False) test_blocks = self.generate_blocks(1, 1234) self.sync_blocks(test_blocks) bip68success_txs.extend(bip68timetxs) self.sync_blocks([self.create_test_block(bip68success_txs)]) self.nodes[0].invalidateblock(self.nodes[0].getbestblockhash()) for tx in bip68heighttxs: self.sync_blocks([self.create_test_block([tx])], success=False) test_blocks = self.generate_blocks(1, 1234) self.sync_blocks(test_blocks) bip68success_txs.extend(bip68heighttxs) self.sync_blocks([self.create_test_block(bip68success_txs)]) self.nodes[0].invalidateblock(self.nodes[0].getbestblockhash()) self.log.info("BIP 112 tests") self.log.info("Test version 1 txs") self.sync_blocks([self.create_test_block([bip112tx_special_v1])], success=False) success_txs = [tx['tx'] for tx in bip112txs_vary_OP_CSV_v1 if tx['sdf']] success_txs += [tx['tx'] for tx in bip112txs_vary_OP_CSV_9_v1 if tx['sdf']] self.sync_blocks([self.create_test_block(success_txs)]) self.nodes[0].invalidateblock(self.nodes[0].getbestblockhash()) fail_txs = all_rlt_txs(bip112txs_vary_nSequence_v1) fail_txs += all_rlt_txs(bip112txs_vary_nSequence_9_v1) fail_txs += [tx['tx'] for tx in bip112txs_vary_OP_CSV_9_v1 if not tx['sdf']] fail_txs += [tx['tx'] for tx in bip112txs_vary_OP_CSV_9_v1 if not tx['sdf']] for tx in fail_txs: self.sync_blocks([self.create_test_block([tx])], success=False) self.log.info("Test version 2 txs") self.sync_blocks([self.create_test_block([bip112tx_special_v2])], success=False) success_txs = [tx['tx'] for tx in bip112txs_vary_OP_CSV_v2 if tx['sdf']] success_txs += [tx['tx'] for tx in bip112txs_vary_OP_CSV_9_v2 if tx['sdf']] self.sync_blocks([self.create_test_block(success_txs)]) self.nodes[0].invalidateblock(self.nodes[0].getbestblockhash()) fail_txs = all_rlt_txs(bip112txs_vary_nSequence_9_v2) fail_txs += [tx['tx'] for tx in bip112txs_vary_OP_CSV_9_v2 if not tx['sdf']] for tx in fail_txs: self.sync_blocks([self.create_test_block([tx])], success=False) fail_txs = [tx['tx'] for tx in bip112txs_vary_nSequence_v2 if tx['sdf']] for tx in fail_txs: self.sync_blocks([self.create_test_block([tx])], success=False) fail_txs = [tx['tx'] for tx in bip112txs_vary_nSequence_v2 if not tx['sdf'] and tx['stf']] fail_txs += [tx['tx'] for tx in bip112txs_vary_OP_CSV_v2 if not tx['sdf'] and tx['stf']] for tx in fail_txs: self.sync_blocks([self.create_test_block([tx])], success=False) success_txs = [tx['tx'] for tx in bip112txs_vary_nSequence_v2 if not tx['sdf'] and not tx['stf']] success_txs += [tx['tx'] for tx in bip112txs_vary_OP_CSV_v2 if not tx['sdf'] and not tx['stf']] self.sync_blocks([self.create_test_block(success_txs)]) self.nodes[0].invalidateblock(self.nodes[0].getbestblockhash()) time_txs = [] for tx in [tx['tx'] for tx in bip112txs_vary_OP_CSV_v2 if not tx['sdf'] and tx['stf']]: tx.vin[0].nSequence = BASE_RELATIVE_LOCKTIME | SEQ_TYPE_FLAG signtx = sign_transaction(self.nodes[0], tx) time_txs.append(signtx) self.sync_blocks([self.create_test_block(time_txs)]) self.nodes[0].invalidateblock(self.nodes[0].getbestblockhash()) if __name__ == '__main__': BIP68_112_113Test().main()
true
true
1c340b1f2cbd9486c82f411e8186992ec5ca287f
3,885
py
Python
edb/edgeql/compiler/options.py
sfermigier/edgedb
13aff7004aa682777287157dea52642c374967e8
[ "Apache-2.0" ]
7,302
2018-05-10T18:36:31.000Z
2022-03-31T17:49:36.000Z
edb/edgeql/compiler/options.py
sfermigier/edgedb
13aff7004aa682777287157dea52642c374967e8
[ "Apache-2.0" ]
1,602
2018-05-10T17:45:38.000Z
2022-03-31T23:46:19.000Z
edb/edgeql/compiler/options.py
sfermigier/edgedb
13aff7004aa682777287157dea52642c374967e8
[ "Apache-2.0" ]
236
2018-05-13T14:15:29.000Z
2022-03-29T19:39:19.000Z
# # This source file is part of the EdgeDB open source project. # # Copyright 2008-present MagicStack Inc. and the EdgeDB authors. # # 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. # """EdgeQL compiler options.""" from __future__ import annotations from typing import * from dataclasses import dataclass, field as dc_field if TYPE_CHECKING: from edb.schema import functions as s_func from edb.schema import objects as s_obj from edb.schema import name as s_name from edb.schema import types as s_types from edb.schema import pointers as s_pointers @dataclass class GlobalCompilerOptions: """Compiler toggles that affect compilation as a whole.""" #: Whether to allow the expression to be of a generic type. allow_generic_type_output: bool = False #: Allow writing to protected pointers in INSERT. allow_writing_protected_pointers: bool = False #: Whether to apply various query rewrites, including access policy. apply_query_rewrites: bool = True #: Enables constant folding optimization (enabled by default). constant_folding: bool = True #: Force types of all parameters to std::json json_parameters: bool = False #: Use material types for pointer targets in schema views. schema_view_mode: bool = False #: Whether to track which subexpressions reference each schema object. track_schema_ref_exprs: bool = False #: If the expression is being processed in the context of a certain #: schema object, i.e. a constraint expression, or a pointer default, #: this contains the type of the schema object. schema_object_context: Optional[Type[s_obj.Object]] = None #: When compiling a function body, specifies function parameter #: definitions. func_params: Optional[s_func.ParameterLikeList] = None #: The name that can be used in a "DML is disallowed in ..." #: error. When this is not None, any DML should cause an error. in_ddl_context_name: Optional[str] = None #: Sometimes (like in queries compiled form GraphQL) it may be OK #: to contain DML in the top-level shape computables. allow_top_level_shape_dml: bool = False @dataclass class CompilerOptions(GlobalCompilerOptions): #: Module name aliases. modaliases: Mapping[Optional[str], str] = dc_field(default_factory=dict) #: External symbol table. anchors: Mapping[str, Any] = dc_field(default_factory=dict) #: The symbol to assume as the prefix for abbreviated paths. path_prefix_anchor: Optional[str] = None #: Module to put derived schema objects to. derived_target_module: Optional[str] = None #: The name to use for the top-level type variant. result_view_name: Optional[s_name.QualName] = None #: If > 0, Inject implicit LIMIT to every SELECT query. implicit_limit: int = 0 #: Include id property in every shape implicitly. implicit_id_in_shapes: bool = False #: Include __tid__ computable (.__type__.id) in every shape implicitly. implicit_tid_in_shapes: bool = False #: Include __tname__ computable (.__type__.name) in every shape implicitly. implicit_tname_in_shapes: bool = False #: A set of schema types and links that should be treated #: as singletons in the context of this compilation. singletons: FrozenSet[Union[s_types.Type, s_pointers.Pointer]] = ( frozenset())
34.380531
79
0.732046
from __future__ import annotations from typing import * from dataclasses import dataclass, field as dc_field if TYPE_CHECKING: from edb.schema import functions as s_func from edb.schema import objects as s_obj from edb.schema import name as s_name from edb.schema import types as s_types from edb.schema import pointers as s_pointers @dataclass class GlobalCompilerOptions: allow_generic_type_output: bool = False allow_writing_protected_pointers: bool = False apply_query_rewrites: bool = True constant_folding: bool = True json_parameters: bool = False schema_view_mode: bool = False track_schema_ref_exprs: bool = False schema_object_context: Optional[Type[s_obj.Object]] = None func_params: Optional[s_func.ParameterLikeList] = None in_ddl_context_name: Optional[str] = None allow_top_level_shape_dml: bool = False @dataclass class CompilerOptions(GlobalCompilerOptions): modaliases: Mapping[Optional[str], str] = dc_field(default_factory=dict) anchors: Mapping[str, Any] = dc_field(default_factory=dict) path_prefix_anchor: Optional[str] = None derived_target_module: Optional[str] = None result_view_name: Optional[s_name.QualName] = None implicit_limit: int = 0 implicit_id_in_shapes: bool = False implicit_tid_in_shapes: bool = False implicit_tname_in_shapes: bool = False singletons: FrozenSet[Union[s_types.Type, s_pointers.Pointer]] = ( frozenset())
true
true
1c340c823663b0eb355585b2deb48e95a2779621
182
py
Python
pyretri/models/__init__.py
dongan-beta/PyRetri
8756d5d5813a5211b58855373b6c6cd33d7a11f6
[ "Apache-2.0" ]
1,063
2020-04-21T12:42:05.000Z
2022-03-31T06:32:50.000Z
pyretri/models/__init__.py
dongan-beta/PyRetri
8756d5d5813a5211b58855373b6c6cd33d7a11f6
[ "Apache-2.0" ]
39
2020-05-07T07:24:19.000Z
2022-02-02T23:49:23.000Z
pyretri/models/__init__.py
dongan-beta/PyRetri
8756d5d5813a5211b58855373b6c6cd33d7a11f6
[ "Apache-2.0" ]
174
2020-04-26T04:33:11.000Z
2022-03-17T02:58:45.000Z
# -*- coding: utf-8 -*- from yacs.config import CfgNode from .config import get_model_cfg from .builder import build_model __all__ = [ 'get_model_cfg', 'build_model', ]
13
33
0.686813
from yacs.config import CfgNode from .config import get_model_cfg from .builder import build_model __all__ = [ 'get_model_cfg', 'build_model', ]
true
true
1c340cac809b176c6009ba616e4eda9d096d8527
722
py
Python
nazgul/messages/google_chat.py
avara1986/nazgul
21e32262acac2acda0232c3eb71b8aaa292e63b5
[ "Apache-2.0" ]
1
2019-06-17T20:28:24.000Z
2019-06-17T20:28:24.000Z
nazgul/messages/google_chat.py
avara1986/nazgul
21e32262acac2acda0232c3eb71b8aaa292e63b5
[ "Apache-2.0" ]
null
null
null
nazgul/messages/google_chat.py
avara1986/nazgul
21e32262acac2acda0232c3eb71b8aaa292e63b5
[ "Apache-2.0" ]
null
null
null
from nazgul.message import DriverMessage from nazgul.response import GoogleChatResponse class Message(DriverMessage): response = GoogleChatResponse use_ids = True def set_values(self): self.user_id = self.msg["user"]["name"] self.user_name = self.users.get(self.user_id, {}).get("name", False) if not self.user_name: self.user_name = self.msg["user"]["displayName"] if self.users.get(self.user_id, {}).get("alias", False): self.user_id = self.users[self.user_id]["alias"] self.text = self.msg["message"]["text"] def is_valid_msg(self): return self.msg.get("message", False) and self.msg.get("message", {}).get("text", False)
34.380952
96
0.641274
from nazgul.message import DriverMessage from nazgul.response import GoogleChatResponse class Message(DriverMessage): response = GoogleChatResponse use_ids = True def set_values(self): self.user_id = self.msg["user"]["name"] self.user_name = self.users.get(self.user_id, {}).get("name", False) if not self.user_name: self.user_name = self.msg["user"]["displayName"] if self.users.get(self.user_id, {}).get("alias", False): self.user_id = self.users[self.user_id]["alias"] self.text = self.msg["message"]["text"] def is_valid_msg(self): return self.msg.get("message", False) and self.msg.get("message", {}).get("text", False)
true
true
1c340da185a24d00ef78622ff2aacf41ea532c61
4,453
py
Python
tools/face/__make_cs6_split_annot.py
AruniRC/detectron-self-train
a5d0edc51aeab92b953948ef2401294e87efb719
[ "MIT" ]
128
2019-04-12T17:06:27.000Z
2022-02-26T10:24:43.000Z
tools/face/__make_cs6_split_annot.py
AruniRC/detectron-self-train
a5d0edc51aeab92b953948ef2401294e87efb719
[ "MIT" ]
15
2019-06-12T03:55:48.000Z
2021-03-12T07:09:53.000Z
tools/face/__make_cs6_split_annot.py
AruniRC/detectron-self-train
a5d0edc51aeab92b953948ef2401294e87efb719
[ "MIT" ]
24
2019-04-12T17:06:30.000Z
2021-07-12T12:38:20.000Z
""" Create ground-truth annotation files for IJBC-style evaluation on CS6. By default the "val" split is considered, using validation videos listed in data/CS6/list_video_val.txt. NOTE: create symlink to "/mnt/nfs/work1/elm/arunirc/Data/CS6_annots/" at "data/CS6_annots". Usage: srun --pty --mem 50000 python tools/face/make_cs6_split_annot.py --split val Output files: data/CS6_annots cs6_annot_eval_imlist_val.txt cs6_annot_eval_val.txt """ from __future__ import absolute_import from __future__ import division import matplotlib matplotlib.use('Agg') import sys sys.path.append('./tools') import _init_paths import numpy as np import os import argparse import os.path as osp import time from six.moves import xrange import utils.face_utils as face_utils GT_VIDEO_LIST = 'data/CS6/list_video_%s.txt' GT_ANNOT_DIR = '/mnt/nfs/work1/elm/arunirc/Data/CS6_annots/video_annots' DET_DIR = '/mnt/nfs/work1/elm/arunirc/Research/face-faster-rcnn-ohem/output/CS6/dets-resnet101-baseline-frames' NUM_IM_VID = 20 # number of images to be sampled per video (for subset creation) DEBUG = False def parse_args(): parser = argparse.ArgumentParser(description='Creating CS6 ground truth data') parser.add_argument( '--gt_dir', help='Path to CS6 ground-truth', default=GT_ANNOT_DIR ) parser.add_argument( '--split', help='Split (train, val, test)', default='val' ) parser.add_argument( '--video_list', help='Path to CS6 videos listed in split', default=GT_VIDEO_LIST ) # parser.add_argument( # '--subset', help='Create a subset for quick eval', action='store_true', # default=False # ) return parser.parse_args() if __name__ == '__main__': args = parse_args() args.video_list = args.video_list % args.split np.random.seed(0) # ----------------------------------------------------------------------------------- # Data setup # ----------------------------------------------------------------------------------- # Ground truth vid_list = np.loadtxt(args.video_list, dtype=str) # Outputs gt_out_dir = osp.dirname(args.gt_dir) gt_out_file = osp.join(gt_out_dir, 'cs6_annot_eval_%s.txt' % args.split) gt_imlist_file = osp.join(gt_out_dir, 'cs6_annot_eval_imlist_%s.txt' % args.split) # ----------------------------------------------------------------------------------- # Eval-format ground-truth annots for CS6 # ----------------------------------------------------------------------------------- with open(gt_out_file, 'w') as fid_gt: with open(gt_imlist_file, 'w') as fid_imlist: for video_name in vid_list: # Load ground-truth annots for that video gt_file = osp.join(args.gt_dir, video_name.split('.')[0] + '.txt') gt_annots = face_utils.parse_wider_gt(gt_file) if len(gt_annots) == 0: continue # no gt faces in this video image_list = np.array( list(gt_annots.keys()) ) # # Select a subset of frames, or use all frames (much slower) # if args.subset: # assert len(image_list) != 0 # subset_size = min( (NUM_IM_VID, len(image_list)) ) # sel = np.random.randint(len(image_list), size=NUM_IM_VID) # image_list = image_list[sel] print('Video annot: %s' % gt_file) # Output bboxes lists for evaluation for i, im_name in enumerate(image_list): # Writing to ground-truth text file annot = np.array( gt_annots[im_name] ) fid_gt.write(im_name + '\n') fid_gt.write(str(annot.shape[0]) + '\n') for j in xrange(annot.shape[0]): fid_gt.write('%f %f %f %f\n' % ( annot[j, 0], annot[j, 1], annot[j, 2], annot[j, 3]) ) # Writing image names (order of images must match for imlist and annots) fid_imlist.write(im_name + '\n') if ((i + 1) % 100) == 0: sys.stdout.write('. ') sys.stdout.flush() print('\n')
32.268116
111
0.543454
from __future__ import absolute_import from __future__ import division import matplotlib matplotlib.use('Agg') import sys sys.path.append('./tools') import _init_paths import numpy as np import os import argparse import os.path as osp import time from six.moves import xrange import utils.face_utils as face_utils GT_VIDEO_LIST = 'data/CS6/list_video_%s.txt' GT_ANNOT_DIR = '/mnt/nfs/work1/elm/arunirc/Data/CS6_annots/video_annots' DET_DIR = '/mnt/nfs/work1/elm/arunirc/Research/face-faster-rcnn-ohem/output/CS6/dets-resnet101-baseline-frames' NUM_IM_VID = 20 DEBUG = False def parse_args(): parser = argparse.ArgumentParser(description='Creating CS6 ground truth data') parser.add_argument( '--gt_dir', help='Path to CS6 ground-truth', default=GT_ANNOT_DIR ) parser.add_argument( '--split', help='Split (train, val, test)', default='val' ) parser.add_argument( '--video_list', help='Path to CS6 videos listed in split', default=GT_VIDEO_LIST ) return parser.parse_args() if __name__ == '__main__': args = parse_args() args.video_list = args.video_list % args.split np.random.seed(0) vid_list = np.loadtxt(args.video_list, dtype=str) gt_out_dir = osp.dirname(args.gt_dir) gt_out_file = osp.join(gt_out_dir, 'cs6_annot_eval_%s.txt' % args.split) gt_imlist_file = osp.join(gt_out_dir, 'cs6_annot_eval_imlist_%s.txt' % args.split) with open(gt_out_file, 'w') as fid_gt: with open(gt_imlist_file, 'w') as fid_imlist: for video_name in vid_list: gt_file = osp.join(args.gt_dir, video_name.split('.')[0] + '.txt') gt_annots = face_utils.parse_wider_gt(gt_file) if len(gt_annots) == 0: continue image_list = np.array( list(gt_annots.keys()) ) print('Video annot: %s' % gt_file) for i, im_name in enumerate(image_list): annot = np.array( gt_annots[im_name] ) fid_gt.write(im_name + '\n') fid_gt.write(str(annot.shape[0]) + '\n') for j in xrange(annot.shape[0]): fid_gt.write('%f %f %f %f\n' % ( annot[j, 0], annot[j, 1], annot[j, 2], annot[j, 3]) ) fid_imlist.write(im_name + '\n') if ((i + 1) % 100) == 0: sys.stdout.write('. ') sys.stdout.flush() print('\n')
true
true
1c340e1d1cf5c12e33fe0ec46bb8d38eb17ee24d
1,016
py
Python
src/OFS/tests/testLockable.py
rbanffy/Zope
ecf6770219052e7c7f8c9634ddf187a1e6280742
[ "ZPL-2.1" ]
289
2015-01-05T12:38:21.000Z
2022-03-05T21:20:39.000Z
src/OFS/tests/testLockable.py
rbanffy/Zope
ecf6770219052e7c7f8c9634ddf187a1e6280742
[ "ZPL-2.1" ]
732
2015-02-09T23:35:57.000Z
2022-03-31T09:10:13.000Z
src/OFS/tests/testLockable.py
rbanffy/Zope
ecf6770219052e7c7f8c9634ddf187a1e6280742
[ "ZPL-2.1" ]
102
2015-01-12T14:03:35.000Z
2022-03-30T11:02:44.000Z
import unittest from OFS.interfaces import IWriteLock from zope.interface import implementer @implementer(IWriteLock) class LockableResource: def __init__(self, locked): self.locked = locked def wl_isLocked(self): return self.locked class UnlockableResource: pass class TestUtilFunctions(unittest.TestCase): def test_wl_isLocked(self): from OFS.Lockable import wl_isLocked unlockable = UnlockableResource() self.assertFalse(wl_isLocked(unlockable)) lockable_unlocked = LockableResource(locked=False) self.assertFalse(wl_isLocked(lockable_unlocked)) lockable_locked = LockableResource(locked=True) self.assertTrue(wl_isLocked(lockable_locked)) def test_wl_isLockable(self): from OFS.Lockable import wl_isLockable unlockable = UnlockableResource() self.assertFalse(wl_isLockable(unlockable)) lockable = LockableResource(locked=False) self.assertTrue(wl_isLockable(lockable))
26.736842
58
0.729331
import unittest from OFS.interfaces import IWriteLock from zope.interface import implementer @implementer(IWriteLock) class LockableResource: def __init__(self, locked): self.locked = locked def wl_isLocked(self): return self.locked class UnlockableResource: pass class TestUtilFunctions(unittest.TestCase): def test_wl_isLocked(self): from OFS.Lockable import wl_isLocked unlockable = UnlockableResource() self.assertFalse(wl_isLocked(unlockable)) lockable_unlocked = LockableResource(locked=False) self.assertFalse(wl_isLocked(lockable_unlocked)) lockable_locked = LockableResource(locked=True) self.assertTrue(wl_isLocked(lockable_locked)) def test_wl_isLockable(self): from OFS.Lockable import wl_isLockable unlockable = UnlockableResource() self.assertFalse(wl_isLockable(unlockable)) lockable = LockableResource(locked=False) self.assertTrue(wl_isLockable(lockable))
true
true
1c340e8db8d7a89fc4a7b2e9665f3d46e309f7d4
1,061
py
Python
git_gopher/DeleteTagRemote.py
derekhamilton/git-gud
7fd377a39796b0aa1268e7ecda6808e8e45173fe
[ "MIT" ]
15
2019-11-13T20:59:53.000Z
2020-12-15T05:21:21.000Z
git_gopher/DeleteTagRemote.py
derekhamilton/git-gud
7fd377a39796b0aa1268e7ecda6808e8e45173fe
[ "MIT" ]
50
2019-10-12T16:57:11.000Z
2019-10-27T21:03:22.000Z
git_gopher/DeleteTagRemote.py
derekhamilton/git-gud
7fd377a39796b0aa1268e7ecda6808e8e45173fe
[ "MIT" ]
1
2019-11-14T03:20:21.000Z
2019-11-14T03:20:21.000Z
from git_gopher.CommandInterface import CommandInterface from git_gopher.HistoryCommandRunner import HistoryCommandRunner from git_gopher.GitDataGetter import GitDataGetter class DeleteTagRemote(CommandInterface): def __init__(self, hist_command_runner: HistoryCommandRunner, git_data_getter: GitDataGetter): self._hist_command_runner = hist_command_runner self._git_data_getter = git_data_getter def run(self): remote = self._git_data_getter.get_remote_name(preview='echo "No action is taken until selecting a tag."') if not remote: return tags = self._git_data_getter.get_tag_names_remote(remote, preview='echo "git tag -d {2} && git push "' + remote + ' {2}"') if tags: output = '' for tag in tags: self._hist_command_runner.run(['git', 'tag', '-d', tag]) self._hist_command_runner.run(['git', 'push', '--delete', remote, tag]) output = output + "\nDeleted tag " + tag + " on " + remote return output
42.44
130
0.664467
from git_gopher.CommandInterface import CommandInterface from git_gopher.HistoryCommandRunner import HistoryCommandRunner from git_gopher.GitDataGetter import GitDataGetter class DeleteTagRemote(CommandInterface): def __init__(self, hist_command_runner: HistoryCommandRunner, git_data_getter: GitDataGetter): self._hist_command_runner = hist_command_runner self._git_data_getter = git_data_getter def run(self): remote = self._git_data_getter.get_remote_name(preview='echo "No action is taken until selecting a tag."') if not remote: return tags = self._git_data_getter.get_tag_names_remote(remote, preview='echo "git tag -d {2} && git push "' + remote + ' {2}"') if tags: output = '' for tag in tags: self._hist_command_runner.run(['git', 'tag', '-d', tag]) self._hist_command_runner.run(['git', 'push', '--delete', remote, tag]) output = output + "\nDeleted tag " + tag + " on " + remote return output
true
true
1c34115300559310ebe35a731ce334a5b031a186
1,907
py
Python
deepspeech_pytorch/loss.py
welgazil/DeDTW
05d46c68122521dfe706736aaff24d6f99807e6e
[ "MIT" ]
null
null
null
deepspeech_pytorch/loss.py
welgazil/DeDTW
05d46c68122521dfe706736aaff24d6f99807e6e
[ "MIT" ]
null
null
null
deepspeech_pytorch/loss.py
welgazil/DeDTW
05d46c68122521dfe706736aaff24d6f99807e6e
[ "MIT" ]
null
null
null
#!/usr/bin/env python3 # -*- coding: utf-8 -*- """ Created on Tue Aug 3 11:53:32 2021 @author: louisbard """ # import numpy as np import torch import torch.nn as nn # import torch.nn.functional as F from deepspeech_pytorch.soft_dtw import SoftDTW from deepspeech_pytorch.gauss import distcos class DTWLosslabels(nn.Module): def __init__(self, representation): super(DTWLosslabels, self).__init__() self.sdtw = SoftDTW(gamma=1.0, normalize=True, dist="cosine") self.criterion = nn.MSELoss() self.representation = representation def forward(self, TGT, OTH, X, labels): TGT, OTH, X = TGT.to(torch.float32), OTH.to(torch.float32), X.to(torch.float32) labels = torch.as_tensor(labels[0], dtype=torch.float) if self.representation == "gauss": diff = distcos(OTH, X) - distcos(TGT, X) loss = self.criterion(diff, labels) #print(labels, diff, loss) else: diff = self.sdtw(OTH, X) - self.sdtw(TGT, X) #print(diff, labels) loss = self.criterion(diff, labels) #print(loss) return loss class DTWLosswithoutlabels(nn.Module): def __init__(self, representation): super(DTWLosswithoutlabels, self).__init__() self.sdtw = SoftDTW(gamma=1.0, normalize=True, dist="cosine") self.representation = representation def forward(self, TGT, OTH, X, labels): TGT, OTH, X = TGT.to(torch.float32), OTH.to(torch.float32), X.to(torch.float32) # labels = torch.as_tensor(labels[0], dtype=torch.float) if self.representation == "gauss": loss = distcos(TGT, X) - distcos(OTH, X) else: loss = self.sdtw(TGT, X) - self.sdtw(OTH, X) # it is ok to put it this way because we want to minimize this # otherwise, the delta value is the other way around return loss
32.87931
120
0.629261
import torch import torch.nn as nn from deepspeech_pytorch.soft_dtw import SoftDTW from deepspeech_pytorch.gauss import distcos class DTWLosslabels(nn.Module): def __init__(self, representation): super(DTWLosslabels, self).__init__() self.sdtw = SoftDTW(gamma=1.0, normalize=True, dist="cosine") self.criterion = nn.MSELoss() self.representation = representation def forward(self, TGT, OTH, X, labels): TGT, OTH, X = TGT.to(torch.float32), OTH.to(torch.float32), X.to(torch.float32) labels = torch.as_tensor(labels[0], dtype=torch.float) if self.representation == "gauss": diff = distcos(OTH, X) - distcos(TGT, X) loss = self.criterion(diff, labels) else: diff = self.sdtw(OTH, X) - self.sdtw(TGT, X) loss = self.criterion(diff, labels) return loss class DTWLosswithoutlabels(nn.Module): def __init__(self, representation): super(DTWLosswithoutlabels, self).__init__() self.sdtw = SoftDTW(gamma=1.0, normalize=True, dist="cosine") self.representation = representation def forward(self, TGT, OTH, X, labels): TGT, OTH, X = TGT.to(torch.float32), OTH.to(torch.float32), X.to(torch.float32) if self.representation == "gauss": loss = distcos(TGT, X) - distcos(OTH, X) else: loss = self.sdtw(TGT, X) - self.sdtw(OTH, X) return loss
true
true
1c341224ea77f0c0bf517aac747cfaae30d1066b
4,287
py
Python
tools/lib-alert-tree/lib_alert_tree/prometheus.py
SaintLoong/metalk8s
06fa3a731f35ab0f9ad8d3443fd8f8c4e7037432
[ "Apache-2.0" ]
23
2018-03-16T09:06:46.000Z
2018-08-02T00:02:07.000Z
tools/lib-alert-tree/lib_alert_tree/prometheus.py
SaintLoong/metalk8s
06fa3a731f35ab0f9ad8d3443fd8f8c4e7037432
[ "Apache-2.0" ]
131
2018-03-13T07:31:34.000Z
2018-08-02T21:57:18.000Z
tools/lib-alert-tree/lib_alert_tree/prometheus.py
SaintLoong/metalk8s
06fa3a731f35ab0f9ad8d3443fd8f8c4e7037432
[ "Apache-2.0" ]
4
2018-04-03T07:18:39.000Z
2018-07-02T22:56:56.000Z
"""Classes for storing and serializing Prometheus alert rules.""" import abc import operator import yaml EXACT_MATCH_LABELS = frozenset(["alertstate", "alertname", "severity"]) class Serializable(metaclass=abc.ABCMeta): """Base-class for data serializable into YAML strings.""" @abc.abstractmethod def serialize(self): """Serialize this data container into a dict.""" return {} def dump(self, out=None): """Dump the serialized data in YAML format.""" return yaml.safe_dump( self.serialize(), stream=out, sort_keys=True, default_flow_style=False ) def __repr__(self): return self.dump() class AlertRule(Serializable): """A single alerting rule.""" def __init__( self, name, expr=None, duration=None, annotations=None, labels=None, severity=None, summary=None, ): self.name = name self.expr = expr self.duration = duration self.labels = labels or {} self.annotations = annotations or {} if severity: self.labels["severity"] = severity if summary: self.annotations["summary"] = summary def serialize(self): for attr in ["expr", "duration"]: assert ( getattr(self, attr) is not None ), f"Cannot serialize '{self.name}': `{attr}` must not be None" return { "alert": self.name, "expr": self.expr, "for": self.duration, "annotations": self.annotations, "labels": self.labels, } def format_labels(self, **updates): """Format labels (and optional updates) as a string.""" return ", ".join( f"{key}='{val}'" if key in EXACT_MATCH_LABELS else f"{key}=~'{val}'" for key, val in sorted( dict(self.labels, **updates).items(), key=operator.itemgetter(0), ) ) def labels_to_json_path_filters(self, **updates): """Build JSON Path filters matching the labels.""" return " && ".join( f"@.labels.{key} === '{val}'" if key in EXACT_MATCH_LABELS else f"@.labels.{key}.match(new RegExp('^(?:{val})$'))" for key, val in sorted( dict(self.labels, **updates).items(), key=operator.itemgetter(0), ) ) @property def query(self): """The PromQL query for selecting this alert.""" labels_str = self.format_labels(alertname=self.name, alertstate="firing") return f"ALERTS{{{labels_str}}}" @property def child_id(self): """A short representation of this alert, for use in annotations.""" return f"{self.name}{{{self.format_labels()}}}" @property def child_json_path(self): """A JSONPath filter expression for selecting this alert as a child. This expression will be combined into a full JSONPath query for retrieving all children of a derived alert, exposed in an annotation for consumption by clients (such as UIs). """ labels_filters = self.labels_to_json_path_filters(alertname=self.name) return f"({labels_filters})" class RulesGroup(Serializable): """A group of alerting rules.""" def __init__(self, name, rules=None): self.rules = rules or [] self.name = name def serialize(self): return { "name": self.name, "rules": [r.serialize() for r in self.rules], } class PrometheusRule(Serializable): """A complete PrometheusRule custom resource.""" def __init__(self, name, namespace, labels=None, groups=None): self.name = name self.namespace = namespace self.labels = labels or {} self.groups = groups or [] def serialize(self): return { "apiVersion": "monitoring.coreos.com/v1", "kind": "PrometheusRule", "metadata": { "labels": self.labels, "name": self.name, "namespace": self.namespace, }, "spec": {"groups": [g.serialize() for g in self.groups]}, }
29.163265
82
0.563798
import abc import operator import yaml EXACT_MATCH_LABELS = frozenset(["alertstate", "alertname", "severity"]) class Serializable(metaclass=abc.ABCMeta): @abc.abstractmethod def serialize(self): return {} def dump(self, out=None): return yaml.safe_dump( self.serialize(), stream=out, sort_keys=True, default_flow_style=False ) def __repr__(self): return self.dump() class AlertRule(Serializable): def __init__( self, name, expr=None, duration=None, annotations=None, labels=None, severity=None, summary=None, ): self.name = name self.expr = expr self.duration = duration self.labels = labels or {} self.annotations = annotations or {} if severity: self.labels["severity"] = severity if summary: self.annotations["summary"] = summary def serialize(self): for attr in ["expr", "duration"]: assert ( getattr(self, attr) is not None ), f"Cannot serialize '{self.name}': `{attr}` must not be None" return { "alert": self.name, "expr": self.expr, "for": self.duration, "annotations": self.annotations, "labels": self.labels, } def format_labels(self, **updates): return ", ".join( f"{key}='{val}'" if key in EXACT_MATCH_LABELS else f"{key}=~'{val}'" for key, val in sorted( dict(self.labels, **updates).items(), key=operator.itemgetter(0), ) ) def labels_to_json_path_filters(self, **updates): return " && ".join( f"@.labels.{key} === '{val}'" if key in EXACT_MATCH_LABELS else f"@.labels.{key}.match(new RegExp('^(?:{val})$'))" for key, val in sorted( dict(self.labels, **updates).items(), key=operator.itemgetter(0), ) ) @property def query(self): labels_str = self.format_labels(alertname=self.name, alertstate="firing") return f"ALERTS{{{labels_str}}}" @property def child_id(self): return f"{self.name}{{{self.format_labels()}}}" @property def child_json_path(self): labels_filters = self.labels_to_json_path_filters(alertname=self.name) return f"({labels_filters})" class RulesGroup(Serializable): def __init__(self, name, rules=None): self.rules = rules or [] self.name = name def serialize(self): return { "name": self.name, "rules": [r.serialize() for r in self.rules], } class PrometheusRule(Serializable): def __init__(self, name, namespace, labels=None, groups=None): self.name = name self.namespace = namespace self.labels = labels or {} self.groups = groups or [] def serialize(self): return { "apiVersion": "monitoring.coreos.com/v1", "kind": "PrometheusRule", "metadata": { "labels": self.labels, "name": self.name, "namespace": self.namespace, }, "spec": {"groups": [g.serialize() for g in self.groups]}, }
true
true
1c34131c9f689c78e777d6970a99f16b0f8b4b23
512
py
Python
src/Plot_tools/__init__.py
nishantsule/PyRsw
753788608a0d227b5c8dc8b863d85bfc3a907310
[ "MIT" ]
null
null
null
src/Plot_tools/__init__.py
nishantsule/PyRsw
753788608a0d227b5c8dc8b863d85bfc3a907310
[ "MIT" ]
null
null
null
src/Plot_tools/__init__.py
nishantsule/PyRsw
753788608a0d227b5c8dc8b863d85bfc3a907310
[ "MIT" ]
null
null
null
# Plot_tools # This module provides the functions used # for visualizing results from a PyRSW # simulation # Import the plotting tools from Plot_tools.initialize_plots_animsave_1D import initialize_plots_animsave_1D from Plot_tools.initialize_plots_animsave_2D import initialize_plots_animsave_2D from Plot_tools.initialize_plots_hov import initialize_plots_hov from Plot_tools.plot_hov import plot_hov from Plot_tools.update_hov import update_hov from Plot_tools.smart_time import smart_time
39.384615
80
0.849609
from Plot_tools.initialize_plots_animsave_1D import initialize_plots_animsave_1D from Plot_tools.initialize_plots_animsave_2D import initialize_plots_animsave_2D from Plot_tools.initialize_plots_hov import initialize_plots_hov from Plot_tools.plot_hov import plot_hov from Plot_tools.update_hov import update_hov from Plot_tools.smart_time import smart_time
true
true
1c34131f5d8c76c9c56c1b80ea4408150a7a4aab
1,706
py
Python
ooobuild/lo/uno/x_reference.py
Amourspirit/ooo_uno_tmpl
64e0c86fd68f24794acc22d63d8d32ae05dd12b8
[ "Apache-2.0" ]
null
null
null
ooobuild/lo/uno/x_reference.py
Amourspirit/ooo_uno_tmpl
64e0c86fd68f24794acc22d63d8d32ae05dd12b8
[ "Apache-2.0" ]
null
null
null
ooobuild/lo/uno/x_reference.py
Amourspirit/ooo_uno_tmpl
64e0c86fd68f24794acc22d63d8d32ae05dd12b8
[ "Apache-2.0" ]
null
null
null
# coding: utf-8 # # Copyright 2022 :Barry-Thomas-Paul: Moss # # 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. # # Interface Class # this is a auto generated file generated by Cheetah # Libre Office Version: 7.3 # Namespace: com.sun.star.uno from abc import abstractmethod from .x_interface import XInterface as XInterface_8f010a43 class XReference(XInterface_8f010a43): """ must be implemented by anyone who holds the adapter on the client side. See Also: `API XReference <https://api.libreoffice.org/docs/idl/ref/interfacecom_1_1sun_1_1star_1_1uno_1_1XReference.html>`_ """ __ooo_ns__: str = 'com.sun.star.uno' __ooo_full_ns__: str = 'com.sun.star.uno.XReference' __ooo_type_name__: str = 'interface' __pyunointerface__: str = 'com.sun.star.uno.XReference' @abstractmethod def dispose(self) -> None: """ removes all references to the adapter. This method is called when the adapted object dies. The implementation of the client-side's weak reference must include removal of all references to the adapter. Otherwise, the adapted object will be destroyed, but the adapter will be alive. """ __all__ = ['XReference']
37.086957
249
0.732708
from abc import abstractmethod from .x_interface import XInterface as XInterface_8f010a43 class XReference(XInterface_8f010a43): __ooo_ns__: str = 'com.sun.star.uno' __ooo_full_ns__: str = 'com.sun.star.uno.XReference' __ooo_type_name__: str = 'interface' __pyunointerface__: str = 'com.sun.star.uno.XReference' @abstractmethod def dispose(self) -> None: __all__ = ['XReference']
true
true
1c3413eb37c6a11a85248a02655f54824f19eeec
17,089
py
Python
tests/test_graceful_reload.py
twu/pypicloud
1ff40b8bcb2f123acab93248368e114cca123504
[ "MIT" ]
336
2016-10-05T14:15:23.000Z
2022-03-17T12:42:10.000Z
tests/test_graceful_reload.py
twu/pypicloud
1ff40b8bcb2f123acab93248368e114cca123504
[ "MIT" ]
215
2016-10-03T20:17:09.000Z
2022-03-29T18:03:46.000Z
tests/test_graceful_reload.py
twu/pypicloud
1ff40b8bcb2f123acab93248368e114cca123504
[ "MIT" ]
104
2016-10-03T18:58:26.000Z
2022-02-10T00:23:28.000Z
""" Tests for gracefully reloading the caches """ import unittest from datetime import timedelta import redis import transaction from mock import MagicMock from pyramid.testing import DummyRequest from sqlalchemy.exc import OperationalError from pypicloud.cache import RedisCache, SQLCache from pypicloud.cache.dynamo import DynamoCache, DynamoPackage, PackageSummary from pypicloud.cache.sql import SQLPackage from pypicloud.dateutil import utcnow from pypicloud.storage import IStorage from pypicloud.util import EnvironSettings from . import make_package from .db_utils import get_mysql_url, get_postgres_url, get_sqlite_url # pylint: disable=W0707 class TestDynamoCache(unittest.TestCase): """Tests for the DynamoCache""" dynamo = None @classmethod def setUpClass(cls): super(TestDynamoCache, cls).setUpClass() host = cls.dynamo.host[cls.dynamo.host.index("//") + 2 :] host, port = host.split(":") settings = { "pypi.storage": "tests.DummyStorage", "db.region_name": "us-east-1", "db.host": host, "db.port": port, "db.namespace": "test.", "db.aws_access_key_id": "", "db.aws_secret_access_key": "", "db.graceful_reload": True, } cls.kwargs = DynamoCache.configure(settings) cls.engine = cls.kwargs["engine"] @classmethod def tearDownClass(cls): super(TestDynamoCache, cls).tearDownClass() cls.engine.delete_schema() def setUp(self): super(TestDynamoCache, self).setUp() self.db = DynamoCache(DummyRequest(), **self.kwargs) self.storage = self.db.storage = MagicMock(spec=IStorage) def tearDown(self): super(TestDynamoCache, self).tearDown() for model in (DynamoPackage, PackageSummary): self.engine.scan(model).delete() def _save_pkgs(self, *pkgs): """Save a DynamoPackage to the db""" for pkg in pkgs: self.engine.save(pkg) summary = PackageSummary(pkg) self.engine.save(summary, overwrite=True) def test_add_missing(self): """Add missing packages to cache""" keys = [make_package(factory=DynamoPackage)] self.storage.list.return_value = keys self.db.reload_from_storage() all_pkgs = self.engine.scan(DynamoPackage).all() self.assertCountEqual(all_pkgs, keys) all_summaries = self.engine.scan(PackageSummary).all() self.assertEqual(len(all_summaries), 1) def test_remove_extra(self): """Remove extra packages from cache""" keys = [ make_package(factory=DynamoPackage), make_package("mypkg2", "1.3.4", factory=DynamoPackage), ] self.db.save(keys[0]) self.db.save(keys[1]) self.storage.list.return_value = keys[:1] self.db.reload_from_storage() all_pkgs = self.engine.scan(DynamoPackage).all() self.assertCountEqual(all_pkgs, keys[:1]) # It should have removed the summary as well self.assertEqual(self.engine.scan(PackageSummary).count(), 1) def test_remove_extra_leave_concurrent(self): """Removing extra packages will leave packages that were uploaded concurrently""" pkgs = [ make_package(factory=DynamoPackage), make_package("mypkg2", factory=DynamoPackage), ] self.db.save(pkgs[0]) self.db.save(pkgs[1]) # Return first pkgs[1], then pkgs[1:] because the second time we list # we will have "uploaded" pkgs[2] return_values = [lambda: pkgs[1:2], lambda: pkgs[1:]] def list_storage(factory): """mocked method for listing storage packages""" # The first time we list from storage, concurrently "upload" # pkgs[2] if len(return_values) == 2: pkg = make_package("mypkg3", factory=DynamoPackage) pkgs.append(pkg) self.db.save(pkg) return return_values.pop(0)() self.storage.list.side_effect = list_storage self.db.reload_from_storage() all_pkgs = self.engine.scan(DynamoPackage).all() self.assertCountEqual(all_pkgs, pkgs[1:]) self.assertEqual(self.engine.scan(PackageSummary).count(), 2) def test_remove_extra_concurrent_deletes(self): """Remove packages from cache that were concurrently deleted""" pkgs = [ make_package(factory=DynamoPackage), make_package("mypkg2", factory=DynamoPackage), ] self.db.save(pkgs[0]) # Return first pkgs[:], then pkgs[:1] because the second time we list # we will have "deleted" pkgs[1] return_values = [pkgs[:], pkgs[:1]] self.storage.list.side_effect = lambda _: return_values.pop(0) self.db.reload_from_storage() all_pkgs = self.engine.scan(DynamoPackage).all() self.assertCountEqual(all_pkgs, pkgs[:1]) self.assertEqual(self.engine.scan(PackageSummary).count(), 1) def test_add_missing_more_recent(self): """If we sync a more recent package, update the summary""" pkgs = [ make_package( last_modified=utcnow() - timedelta(hours=1), factory=DynamoPackage, ), make_package(version="1.5", factory=DynamoPackage), ] self.db.save(pkgs[0]) self.storage.list.return_value = pkgs self.db.reload_from_storage() all_pkgs = self.engine.scan(DynamoPackage).all() self.assertCountEqual(all_pkgs, pkgs) summaries = self.db.summary() self.assertEqual(len(summaries), 1) summary = summaries[0] self.assertEqual(summary["last_modified"], pkgs[1].last_modified) def test_same_package_name_version(self): """Storage can have packages with the same name and version (different filename)""" pkgs = [ make_package(filename="mypkg-1.1-win32.whl", factory=DynamoPackage), make_package(filename="mypkg-1.1-macosx.whl", factory=DynamoPackage), make_package(filename="mypkg-1.1-x86_64.whl", factory=DynamoPackage), ] self.storage.list.return_value = pkgs self.db.reload_from_storage() all_pkgs = self.engine.scan(DynamoPackage).all() self.assertCountEqual(all_pkgs, pkgs) summaries = self.db.summary() self.assertEqual(len(summaries), 1) class TestRedisCache(unittest.TestCase): """Tests for the RedisCache""" @classmethod def setUpClass(cls): super(TestRedisCache, cls).setUpClass() settings = { "pypi.storage": "tests.DummyStorage", "db.url": "redis://localhost", "db.graceful_reload": True, } cls.kwargs = RedisCache.configure(settings) cls.redis = cls.kwargs["db"] try: cls.redis.flushdb() except redis.exceptions.ConnectionError: msg = "Redis not found on port 6379" setattr(cls, "setUp", lambda cls: unittest.TestCase.skipTest(cls, msg)) @classmethod def tearDownClass(cls): super(TestRedisCache, cls).tearDownClass() def setUp(self): super(TestRedisCache, self).setUp() self.db = RedisCache(DummyRequest(), **self.kwargs) self.storage = self.db.storage = MagicMock(spec=IStorage) def tearDown(self): super(TestRedisCache, self).tearDown() self.redis.flushdb() def _save_pkgs(self, *pkgs): """Save packages to the db""" pipe = self.redis.pipeline() for pkg in pkgs: self.db.save(pkg, pipe) pipe.execute() def test_add_missing(self): """Add missing packages to cache""" keys = [make_package()] self.storage.list.return_value = keys self.db.reload_from_storage() all_pkgs = self.db._load_all_packages() self.assertCountEqual(all_pkgs, keys) self.assertEqual(len(self.db.summary()), 1) def test_remove_extra(self): """Remove extra packages from cache""" keys = [make_package(), make_package("mypkg2", "1.3.4")] self.db.save(keys[0]) self.db.save(keys[1]) self.storage.list.return_value = keys[:1] self.db.reload_from_storage() all_pkgs = self.db._load_all_packages() self.assertCountEqual(all_pkgs, keys[:1]) # It should have removed the summary as well self.assertEqual(len(self.db.summary()), 1) def test_remove_extra_leave_concurrent(self): """Removing extra packages will leave packages that were uploaded concurrently""" pkgs = [make_package(), make_package("mypkg2")] self.db.save(pkgs[0]) self.db.save(pkgs[1]) # Return first pkgs[1], then pkgs[1:] because the second time we list # we will have "uploaded" pkgs[2] return_values = [lambda: pkgs[1:2], lambda: pkgs[1:]] def list_storage(factory): """mocked method for listing storage packages""" # The first time we list from storage, concurrently "upload" # pkgs[2] if len(return_values) == 2: pkg = make_package("mypkg3") pkgs.append(pkg) self.db.save(pkg) return return_values.pop(0)() self.storage.list.side_effect = list_storage self.db.reload_from_storage() all_pkgs = self.db._load_all_packages() self.assertCountEqual(all_pkgs, pkgs[1:]) self.assertEqual(len(self.db.summary()), 2) def test_remove_extra_concurrent_deletes(self): """Remove packages from cache that were concurrently deleted""" pkgs = [make_package(), make_package("mypkg2")] self.db.save(pkgs[0]) # Return first pkgs[:], then pkgs[:1] because the second time we list # we will have "deleted" pkgs[1] return_values = [pkgs[:], pkgs[:1]] self.storage.list.side_effect = lambda _: return_values.pop(0) self.db.reload_from_storage() all_pkgs = self.db._load_all_packages() self.assertCountEqual(all_pkgs, pkgs[:1]) self.assertEqual(len(self.db.summary()), 1) def test_add_missing_more_recent(self): """If we sync a more recent package, update the summary""" pkgs = [ make_package(last_modified=utcnow() - timedelta(hours=1)), make_package(version="1.5"), ] self.db.save(pkgs[0]) self.storage.list.return_value = pkgs self.db.reload_from_storage() all_pkgs = self.db._load_all_packages() self.assertCountEqual(all_pkgs, pkgs) summaries = self.db.summary() self.assertEqual(len(summaries), 1) summary = summaries[0] self.assertEqual(summary["last_modified"].hour, pkgs[1].last_modified.hour) def test_same_package_name_version(self): """Storage can have packages with the same name and version (different filename)""" pkgs = [ make_package(filename="mypkg-1.1-win32.whl"), make_package(filename="mypkg-1.1-macosx.whl"), make_package(filename="mypkg-1.1-x86_64.whl"), ] self.storage.list.return_value = pkgs self.db.reload_from_storage() all_pkgs = self.db._load_all_packages() self.assertCountEqual(all_pkgs, pkgs) summaries = self.db.summary() self.assertEqual(len(summaries), 1) class TestSQLiteCache(unittest.TestCase): """Tests for the SQLCache""" @classmethod def get_db_url(cls) -> str: return get_sqlite_url() @classmethod def setUpClass(cls): super(TestSQLiteCache, cls).setUpClass() db_url = cls.get_db_url() settings = EnvironSettings( { "pypi.storage": "tests.DummyStorage", "db.url": db_url, "db.graceful_reload": True, }, {}, ) try: cls.kwargs = SQLCache.configure(settings) except OperationalError: raise unittest.SkipTest(f"Couldn't connect to database {db_url}") def setUp(self): super(TestSQLiteCache, self).setUp() transaction.begin() self.request = DummyRequest() self.request.tm = transaction.manager self.db = SQLCache(self.request, **self.kwargs) self.sql = self.db.db self.storage = self.db.storage = MagicMock(spec=IStorage) def tearDown(self): super(TestSQLiteCache, self).tearDown() transaction.abort() self.sql.query(SQLPackage).delete() transaction.commit() self.request._process_finished_callbacks() def _make_package(self, *args, **kwargs): """Wrapper around make_package""" # Some SQL dbs are rounding the timestamps (looking at you MySQL >:| # which is a problem if they round UP to the future, as our # calculations depend on the timestamps being monotonically increasing. now = utcnow() - timedelta(seconds=1) kwargs.setdefault("last_modified", now) kwargs.setdefault("factory", SQLPackage) return make_package(*args, **kwargs) def test_add_missing(self): """Add missing packages to cache""" keys = [self._make_package()] self.storage.list.return_value = keys self.db.reload_from_storage() all_pkgs = self.sql.query(SQLPackage).all() self.assertCountEqual(all_pkgs, keys) def test_remove_extra(self): """Remove extra packages from cache""" keys = [self._make_package(), self._make_package("mypkg2", "1.3.4")] self.db.save(keys[0]) self.db.save(keys[1]) self.storage.list.return_value = keys[:1] self.db.reload_from_storage() all_pkgs = self.sql.query(SQLPackage).all() self.assertCountEqual(all_pkgs, keys[:1]) def test_remove_extra_leave_concurrent(self): """Removing extra packages will leave packages that were uploaded concurrently""" pkgs = [self._make_package(), self._make_package("mypkg2")] self.db.save(pkgs[0]) self.db.save(pkgs[1]) # Return first pkgs[1], then pkgs[1:] because the second time we list # we will have "uploaded" pkgs[2] return_values = [lambda: pkgs[1:2], lambda: pkgs[1:]] def list_storage(factory): """mocked method for listing storage packages""" # The first time we list from storage, concurrently "upload" # pkgs[2] if len(return_values) == 2: nowish = utcnow() + timedelta(seconds=1) pkg = self._make_package("mypkg3", last_modified=nowish) pkgs.append(pkg) self.db.save(pkg) return return_values.pop(0)() self.storage.list.side_effect = list_storage self.db.reload_from_storage() all_pkgs = self.sql.query(SQLPackage).all() self.assertCountEqual(all_pkgs, pkgs[1:]) def test_remove_extra_concurrent_deletes(self): """Remove packages from cache that were concurrently deleted""" pkgs = [self._make_package(), self._make_package("mypkg2")] self.db.save(pkgs[0]) # Return first pkgs[:], then pkgs[:1] because the second time we list # we will have "deleted" pkgs[1] return_values = [pkgs[:], pkgs[:1]] self.storage.list.side_effect = lambda _: return_values.pop(0) self.db.reload_from_storage() all_pkgs = self.sql.query(SQLPackage).all() self.assertCountEqual(all_pkgs, pkgs[:1]) def test_add_missing_more_recent(self): """If we sync a more recent package, update the summary""" pkgs = [ self._make_package(last_modified=utcnow() - timedelta(hours=1)), self._make_package(version="1.5"), ] self.db.save(pkgs[0]) self.storage.list.return_value = pkgs self.db.reload_from_storage() all_pkgs = self.sql.query(SQLPackage).all() self.assertCountEqual(all_pkgs, pkgs) def test_same_package_name_version(self): """Storage can have packages with the same name and version (different filename)""" pkgs = [ self._make_package(filename="mypkg-1.1-win32.whl"), self._make_package(filename="mypkg-1.1-macosx.whl"), self._make_package(filename="mypkg-1.1-x86_64.whl"), ] self.storage.list.return_value = pkgs self.db.reload_from_storage() all_pkgs = self.sql.query(SQLPackage).all() self.assertCountEqual(all_pkgs, pkgs) class TestMySQLCache(TestSQLiteCache): """Test the SQLAlchemy cache on a MySQL DB""" @classmethod def get_db_url(cls) -> str: return get_mysql_url() class TestPostgresCache(TestSQLiteCache): """Test the SQLAlchemy cache on a Postgres DB""" @classmethod def get_db_url(cls) -> str: return get_postgres_url()
37.069414
91
0.6259
import unittest from datetime import timedelta import redis import transaction from mock import MagicMock from pyramid.testing import DummyRequest from sqlalchemy.exc import OperationalError from pypicloud.cache import RedisCache, SQLCache from pypicloud.cache.dynamo import DynamoCache, DynamoPackage, PackageSummary from pypicloud.cache.sql import SQLPackage from pypicloud.dateutil import utcnow from pypicloud.storage import IStorage from pypicloud.util import EnvironSettings from . import make_package from .db_utils import get_mysql_url, get_postgres_url, get_sqlite_url class TestDynamoCache(unittest.TestCase): dynamo = None @classmethod def setUpClass(cls): super(TestDynamoCache, cls).setUpClass() host = cls.dynamo.host[cls.dynamo.host.index("//") + 2 :] host, port = host.split(":") settings = { "pypi.storage": "tests.DummyStorage", "db.region_name": "us-east-1", "db.host": host, "db.port": port, "db.namespace": "test.", "db.aws_access_key_id": "", "db.aws_secret_access_key": "", "db.graceful_reload": True, } cls.kwargs = DynamoCache.configure(settings) cls.engine = cls.kwargs["engine"] @classmethod def tearDownClass(cls): super(TestDynamoCache, cls).tearDownClass() cls.engine.delete_schema() def setUp(self): super(TestDynamoCache, self).setUp() self.db = DynamoCache(DummyRequest(), **self.kwargs) self.storage = self.db.storage = MagicMock(spec=IStorage) def tearDown(self): super(TestDynamoCache, self).tearDown() for model in (DynamoPackage, PackageSummary): self.engine.scan(model).delete() def _save_pkgs(self, *pkgs): for pkg in pkgs: self.engine.save(pkg) summary = PackageSummary(pkg) self.engine.save(summary, overwrite=True) def test_add_missing(self): keys = [make_package(factory=DynamoPackage)] self.storage.list.return_value = keys self.db.reload_from_storage() all_pkgs = self.engine.scan(DynamoPackage).all() self.assertCountEqual(all_pkgs, keys) all_summaries = self.engine.scan(PackageSummary).all() self.assertEqual(len(all_summaries), 1) def test_remove_extra(self): keys = [ make_package(factory=DynamoPackage), make_package("mypkg2", "1.3.4", factory=DynamoPackage), ] self.db.save(keys[0]) self.db.save(keys[1]) self.storage.list.return_value = keys[:1] self.db.reload_from_storage() all_pkgs = self.engine.scan(DynamoPackage).all() self.assertCountEqual(all_pkgs, keys[:1]) self.assertEqual(self.engine.scan(PackageSummary).count(), 1) def test_remove_extra_leave_concurrent(self): pkgs = [ make_package(factory=DynamoPackage), make_package("mypkg2", factory=DynamoPackage), ] self.db.save(pkgs[0]) self.db.save(pkgs[1]) return_values = [lambda: pkgs[1:2], lambda: pkgs[1:]] def list_storage(factory): if len(return_values) == 2: pkg = make_package("mypkg3", factory=DynamoPackage) pkgs.append(pkg) self.db.save(pkg) return return_values.pop(0)() self.storage.list.side_effect = list_storage self.db.reload_from_storage() all_pkgs = self.engine.scan(DynamoPackage).all() self.assertCountEqual(all_pkgs, pkgs[1:]) self.assertEqual(self.engine.scan(PackageSummary).count(), 2) def test_remove_extra_concurrent_deletes(self): pkgs = [ make_package(factory=DynamoPackage), make_package("mypkg2", factory=DynamoPackage), ] self.db.save(pkgs[0]) return_values = [pkgs[:], pkgs[:1]] self.storage.list.side_effect = lambda _: return_values.pop(0) self.db.reload_from_storage() all_pkgs = self.engine.scan(DynamoPackage).all() self.assertCountEqual(all_pkgs, pkgs[:1]) self.assertEqual(self.engine.scan(PackageSummary).count(), 1) def test_add_missing_more_recent(self): pkgs = [ make_package( last_modified=utcnow() - timedelta(hours=1), factory=DynamoPackage, ), make_package(version="1.5", factory=DynamoPackage), ] self.db.save(pkgs[0]) self.storage.list.return_value = pkgs self.db.reload_from_storage() all_pkgs = self.engine.scan(DynamoPackage).all() self.assertCountEqual(all_pkgs, pkgs) summaries = self.db.summary() self.assertEqual(len(summaries), 1) summary = summaries[0] self.assertEqual(summary["last_modified"], pkgs[1].last_modified) def test_same_package_name_version(self): pkgs = [ make_package(filename="mypkg-1.1-win32.whl", factory=DynamoPackage), make_package(filename="mypkg-1.1-macosx.whl", factory=DynamoPackage), make_package(filename="mypkg-1.1-x86_64.whl", factory=DynamoPackage), ] self.storage.list.return_value = pkgs self.db.reload_from_storage() all_pkgs = self.engine.scan(DynamoPackage).all() self.assertCountEqual(all_pkgs, pkgs) summaries = self.db.summary() self.assertEqual(len(summaries), 1) class TestRedisCache(unittest.TestCase): @classmethod def setUpClass(cls): super(TestRedisCache, cls).setUpClass() settings = { "pypi.storage": "tests.DummyStorage", "db.url": "redis://localhost", "db.graceful_reload": True, } cls.kwargs = RedisCache.configure(settings) cls.redis = cls.kwargs["db"] try: cls.redis.flushdb() except redis.exceptions.ConnectionError: msg = "Redis not found on port 6379" setattr(cls, "setUp", lambda cls: unittest.TestCase.skipTest(cls, msg)) @classmethod def tearDownClass(cls): super(TestRedisCache, cls).tearDownClass() def setUp(self): super(TestRedisCache, self).setUp() self.db = RedisCache(DummyRequest(), **self.kwargs) self.storage = self.db.storage = MagicMock(spec=IStorage) def tearDown(self): super(TestRedisCache, self).tearDown() self.redis.flushdb() def _save_pkgs(self, *pkgs): pipe = self.redis.pipeline() for pkg in pkgs: self.db.save(pkg, pipe) pipe.execute() def test_add_missing(self): keys = [make_package()] self.storage.list.return_value = keys self.db.reload_from_storage() all_pkgs = self.db._load_all_packages() self.assertCountEqual(all_pkgs, keys) self.assertEqual(len(self.db.summary()), 1) def test_remove_extra(self): keys = [make_package(), make_package("mypkg2", "1.3.4")] self.db.save(keys[0]) self.db.save(keys[1]) self.storage.list.return_value = keys[:1] self.db.reload_from_storage() all_pkgs = self.db._load_all_packages() self.assertCountEqual(all_pkgs, keys[:1]) self.assertEqual(len(self.db.summary()), 1) def test_remove_extra_leave_concurrent(self): pkgs = [make_package(), make_package("mypkg2")] self.db.save(pkgs[0]) self.db.save(pkgs[1]) return_values = [lambda: pkgs[1:2], lambda: pkgs[1:]] def list_storage(factory): if len(return_values) == 2: pkg = make_package("mypkg3") pkgs.append(pkg) self.db.save(pkg) return return_values.pop(0)() self.storage.list.side_effect = list_storage self.db.reload_from_storage() all_pkgs = self.db._load_all_packages() self.assertCountEqual(all_pkgs, pkgs[1:]) self.assertEqual(len(self.db.summary()), 2) def test_remove_extra_concurrent_deletes(self): pkgs = [make_package(), make_package("mypkg2")] self.db.save(pkgs[0]) return_values = [pkgs[:], pkgs[:1]] self.storage.list.side_effect = lambda _: return_values.pop(0) self.db.reload_from_storage() all_pkgs = self.db._load_all_packages() self.assertCountEqual(all_pkgs, pkgs[:1]) self.assertEqual(len(self.db.summary()), 1) def test_add_missing_more_recent(self): pkgs = [ make_package(last_modified=utcnow() - timedelta(hours=1)), make_package(version="1.5"), ] self.db.save(pkgs[0]) self.storage.list.return_value = pkgs self.db.reload_from_storage() all_pkgs = self.db._load_all_packages() self.assertCountEqual(all_pkgs, pkgs) summaries = self.db.summary() self.assertEqual(len(summaries), 1) summary = summaries[0] self.assertEqual(summary["last_modified"].hour, pkgs[1].last_modified.hour) def test_same_package_name_version(self): pkgs = [ make_package(filename="mypkg-1.1-win32.whl"), make_package(filename="mypkg-1.1-macosx.whl"), make_package(filename="mypkg-1.1-x86_64.whl"), ] self.storage.list.return_value = pkgs self.db.reload_from_storage() all_pkgs = self.db._load_all_packages() self.assertCountEqual(all_pkgs, pkgs) summaries = self.db.summary() self.assertEqual(len(summaries), 1) class TestSQLiteCache(unittest.TestCase): @classmethod def get_db_url(cls) -> str: return get_sqlite_url() @classmethod def setUpClass(cls): super(TestSQLiteCache, cls).setUpClass() db_url = cls.get_db_url() settings = EnvironSettings( { "pypi.storage": "tests.DummyStorage", "db.url": db_url, "db.graceful_reload": True, }, {}, ) try: cls.kwargs = SQLCache.configure(settings) except OperationalError: raise unittest.SkipTest(f"Couldn't connect to database {db_url}") def setUp(self): super(TestSQLiteCache, self).setUp() transaction.begin() self.request = DummyRequest() self.request.tm = transaction.manager self.db = SQLCache(self.request, **self.kwargs) self.sql = self.db.db self.storage = self.db.storage = MagicMock(spec=IStorage) def tearDown(self): super(TestSQLiteCache, self).tearDown() transaction.abort() self.sql.query(SQLPackage).delete() transaction.commit() self.request._process_finished_callbacks() def _make_package(self, *args, **kwargs): # Some SQL dbs are rounding the timestamps (looking at you MySQL >:| # which is a problem if they round UP to the future, as our # calculations depend on the timestamps being monotonically increasing. now = utcnow() - timedelta(seconds=1) kwargs.setdefault("last_modified", now) kwargs.setdefault("factory", SQLPackage) return make_package(*args, **kwargs) def test_add_missing(self): keys = [self._make_package()] self.storage.list.return_value = keys self.db.reload_from_storage() all_pkgs = self.sql.query(SQLPackage).all() self.assertCountEqual(all_pkgs, keys) def test_remove_extra(self): keys = [self._make_package(), self._make_package("mypkg2", "1.3.4")] self.db.save(keys[0]) self.db.save(keys[1]) self.storage.list.return_value = keys[:1] self.db.reload_from_storage() all_pkgs = self.sql.query(SQLPackage).all() self.assertCountEqual(all_pkgs, keys[:1]) def test_remove_extra_leave_concurrent(self): pkgs = [self._make_package(), self._make_package("mypkg2")] self.db.save(pkgs[0]) self.db.save(pkgs[1]) # Return first pkgs[1], then pkgs[1:] because the second time we list # we will have "uploaded" pkgs[2] return_values = [lambda: pkgs[1:2], lambda: pkgs[1:]] def list_storage(factory): # The first time we list from storage, concurrently "upload" # pkgs[2] if len(return_values) == 2: nowish = utcnow() + timedelta(seconds=1) pkg = self._make_package("mypkg3", last_modified=nowish) pkgs.append(pkg) self.db.save(pkg) return return_values.pop(0)() self.storage.list.side_effect = list_storage self.db.reload_from_storage() all_pkgs = self.sql.query(SQLPackage).all() self.assertCountEqual(all_pkgs, pkgs[1:]) def test_remove_extra_concurrent_deletes(self): pkgs = [self._make_package(), self._make_package("mypkg2")] self.db.save(pkgs[0]) # Return first pkgs[:], then pkgs[:1] because the second time we list # we will have "deleted" pkgs[1] return_values = [pkgs[:], pkgs[:1]] self.storage.list.side_effect = lambda _: return_values.pop(0) self.db.reload_from_storage() all_pkgs = self.sql.query(SQLPackage).all() self.assertCountEqual(all_pkgs, pkgs[:1]) def test_add_missing_more_recent(self): pkgs = [ self._make_package(last_modified=utcnow() - timedelta(hours=1)), self._make_package(version="1.5"), ] self.db.save(pkgs[0]) self.storage.list.return_value = pkgs self.db.reload_from_storage() all_pkgs = self.sql.query(SQLPackage).all() self.assertCountEqual(all_pkgs, pkgs) def test_same_package_name_version(self): pkgs = [ self._make_package(filename="mypkg-1.1-win32.whl"), self._make_package(filename="mypkg-1.1-macosx.whl"), self._make_package(filename="mypkg-1.1-x86_64.whl"), ] self.storage.list.return_value = pkgs self.db.reload_from_storage() all_pkgs = self.sql.query(SQLPackage).all() self.assertCountEqual(all_pkgs, pkgs) class TestMySQLCache(TestSQLiteCache): @classmethod def get_db_url(cls) -> str: return get_mysql_url() class TestPostgresCache(TestSQLiteCache): @classmethod def get_db_url(cls) -> str: return get_postgres_url()
true
true
1c34149b9cfd658fb4f97781ad55439fe6439063
1,442
py
Python
Electronic Station/timeConverter12Hto24H.py
amatsuraki/CheckiO-Elementary-
e041ea41b1f5ff59618c810468dec005bb797883
[ "MIT" ]
null
null
null
Electronic Station/timeConverter12Hto24H.py
amatsuraki/CheckiO-Elementary-
e041ea41b1f5ff59618c810468dec005bb797883
[ "MIT" ]
null
null
null
Electronic Station/timeConverter12Hto24H.py
amatsuraki/CheckiO-Elementary-
e041ea41b1f5ff59618c810468dec005bb797883
[ "MIT" ]
null
null
null
#!/usr/bin/python # -*- Coding: utf-8 -*- """ [Time converter 12h to 24h] You are the modern man who prefers the 24-hour time format. But the 12-hour format is used in some places. Your task is to convert the time from the 12-h format into 24-h by following the next rules: - the output format should be 'hh:mm' - if the output hour is less than 10 - write '0' before it. For example: '09:05' """ def time_converter(time): time = time.split(" ") time0 = time[0].split(":") hour = int(time0[0]) minute = time0[1] if time[1] == "a.m.": if hour is not 12: hour = "{0:02d}".format(hour) else: hour = "00" else: if hour is not 12: hour = "{0:02d}".format(hour + 12) else: hour = "12" return str(hour + ":" + minute) if __name__ == '__main__': print("Example:") print(time_converter('12:30 p.m.')) #These "asserts" using only for self-checking and not necessary for auto-testing assert time_converter('12:30 p.m.') == '12:30' assert time_converter('9:00 a.m.') == '09:00' assert time_converter('11:15 p.m.') == '23:15' print("Coding complete? Click 'Check' to earn cool rewards!") """ メモ 12:00am = 00:00 12:00pm = 12:00 if time[1] is "a.m.": ->false if time[1] == "a.m.": ->true isは同じオブジェクトではなくidが異なるためfalseになる datetime.strptimeを使うと良い """
28.84
200
0.574896
def time_converter(time): time = time.split(" ") time0 = time[0].split(":") hour = int(time0[0]) minute = time0[1] if time[1] == "a.m.": if hour is not 12: hour = "{0:02d}".format(hour) else: hour = "00" else: if hour is not 12: hour = "{0:02d}".format(hour + 12) else: hour = "12" return str(hour + ":" + minute) if __name__ == '__main__': print("Example:") print(time_converter('12:30 p.m.')) assert time_converter('12:30 p.m.') == '12:30' assert time_converter('9:00 a.m.') == '09:00' assert time_converter('11:15 p.m.') == '23:15' print("Coding complete? Click 'Check' to earn cool rewards!")
true
true
1c3415006f05237c1c53f3c865f96ea8235e73ac
2,684
py
Python
plot_grid.py
jonasvj/TFDE
c5d25947b28524c7a40626f797ca8c157fa70a53
[ "MIT" ]
null
null
null
plot_grid.py
jonasvj/TFDE
c5d25947b28524c7a40626f797ca8c157fa70a53
[ "MIT" ]
null
null
null
plot_grid.py
jonasvj/TFDE
c5d25947b28524c7a40626f797ca8c157fa70a53
[ "MIT" ]
null
null
null
#!/usr/bin/env python3 import sys import numpy as np import pandas as pd import matplotlib.pyplot as plt def tt_params(K, M): return K + 3*M*K**2 def tt_dof(K, M): return (K-1) + M*K*(K-1) + 2*M*K**2 def bic(n, k, nllh_per_sample): log_lh = -1*nllh_per_sample*n return k*np.log(n) - 2*log_lh def aic(n, k, nllh_per_sample): log_lh = -1*nllh_per_sample*n return 2*k - 2*log_lh def n_params(model, K, M): if model == 'TT': return (K-1) + M*K*(K-1) + 2*M*K*K elif model == 'CP': return (K-1) + 2*M*K elif model == 'GMM': return (K-1) + (2*M + M*(M-1)/2)*K sizes = { 'power': {'n_train': 1659917, 'n_val': 184435, 'n_test': 204928, 'M': 6}, 'gas': {'n_train': 852174, 'n_val': 94685, 'n_test': 105206, 'M': 8}, 'hepmass': {'n_train': 315123, 'n_val': 35013, 'n_test': 174987, 'M': 21}, 'miniboone': {'n_train': 29556, 'n_val': 3284, 'n_test': 3648, 'M': 43}, 'bsds300': {'n_train': 1000000, 'n_val': 50000, 'n_test': 250000, 'M': 63}, '8gaussians': {'n_train': 30000, 'n_val': 30000, 'n_test': 30000, 'M': 2}, 'checkerboard': {'n_train': 30000, 'n_val': 30000, 'n_test': 30000, 'M': 2}, '2spirals': {'n_train': 30000, 'n_val': 30000, 'n_test': 30000, 'M': 2} } df = pd.read_csv('results/grid_results.txt', index_col=0) df_gmm = pd.read_csv('results/gmm_results.txt', index_col=0) df = df.append(df_gmm, ignore_index=True) df = df[df.optimal_order == 1] print(df) # Add new columns df['M'] = df.apply(lambda row: sizes[row.dataset]['M'], axis=1) df['dof'] = df.apply(lambda row: n_params(row.model_type, row.K, row.M), axis=1) datasets = ['hepmass', 'miniboone'] subsample_sizes = [1750, 7000, 28000] groups = df.groupby(['dataset', 'subsample_size']) fig, axes = plt.subplots(nrows=2, ncols=3, figsize=(24, 12), sharex='all', sharey='row') for i, (group, frame) in enumerate(groups): row_idx = datasets.index(group[0]) col_idx = subsample_sizes.index(group[1]) model_groups = frame.groupby(['model_type']) for model, model_frame in model_groups: mean = model_frame.groupby('dof').mean() sem = model_frame.groupby('dof').sem() min_ = model_frame.groupby('dof').min() axes[row_idx, col_idx].errorbar( mean.index, mean.nllh_test, yerr=sem.nllh_test, fmt='.:', label=model, alpha=.75, capsize=3, capthick=1) axes[row_idx, col_idx].set_xlabel('Free parameters') axes[row_idx, col_idx].set_ylabel(f'Test NLLH per sample ({group[0]})') axes[row_idx, col_idx].set_title(f'Subsample size: {group[1]}') axes[row_idx, col_idx].legend() fig.savefig('plots/' + 'grid_plot.pdf') plt.close()
33.974684
80
0.618107
import sys import numpy as np import pandas as pd import matplotlib.pyplot as plt def tt_params(K, M): return K + 3*M*K**2 def tt_dof(K, M): return (K-1) + M*K*(K-1) + 2*M*K**2 def bic(n, k, nllh_per_sample): log_lh = -1*nllh_per_sample*n return k*np.log(n) - 2*log_lh def aic(n, k, nllh_per_sample): log_lh = -1*nllh_per_sample*n return 2*k - 2*log_lh def n_params(model, K, M): if model == 'TT': return (K-1) + M*K*(K-1) + 2*M*K*K elif model == 'CP': return (K-1) + 2*M*K elif model == 'GMM': return (K-1) + (2*M + M*(M-1)/2)*K sizes = { 'power': {'n_train': 1659917, 'n_val': 184435, 'n_test': 204928, 'M': 6}, 'gas': {'n_train': 852174, 'n_val': 94685, 'n_test': 105206, 'M': 8}, 'hepmass': {'n_train': 315123, 'n_val': 35013, 'n_test': 174987, 'M': 21}, 'miniboone': {'n_train': 29556, 'n_val': 3284, 'n_test': 3648, 'M': 43}, 'bsds300': {'n_train': 1000000, 'n_val': 50000, 'n_test': 250000, 'M': 63}, '8gaussians': {'n_train': 30000, 'n_val': 30000, 'n_test': 30000, 'M': 2}, 'checkerboard': {'n_train': 30000, 'n_val': 30000, 'n_test': 30000, 'M': 2}, '2spirals': {'n_train': 30000, 'n_val': 30000, 'n_test': 30000, 'M': 2} } df = pd.read_csv('results/grid_results.txt', index_col=0) df_gmm = pd.read_csv('results/gmm_results.txt', index_col=0) df = df.append(df_gmm, ignore_index=True) df = df[df.optimal_order == 1] print(df) df['M'] = df.apply(lambda row: sizes[row.dataset]['M'], axis=1) df['dof'] = df.apply(lambda row: n_params(row.model_type, row.K, row.M), axis=1) datasets = ['hepmass', 'miniboone'] subsample_sizes = [1750, 7000, 28000] groups = df.groupby(['dataset', 'subsample_size']) fig, axes = plt.subplots(nrows=2, ncols=3, figsize=(24, 12), sharex='all', sharey='row') for i, (group, frame) in enumerate(groups): row_idx = datasets.index(group[0]) col_idx = subsample_sizes.index(group[1]) model_groups = frame.groupby(['model_type']) for model, model_frame in model_groups: mean = model_frame.groupby('dof').mean() sem = model_frame.groupby('dof').sem() min_ = model_frame.groupby('dof').min() axes[row_idx, col_idx].errorbar( mean.index, mean.nllh_test, yerr=sem.nllh_test, fmt='.:', label=model, alpha=.75, capsize=3, capthick=1) axes[row_idx, col_idx].set_xlabel('Free parameters') axes[row_idx, col_idx].set_ylabel(f'Test NLLH per sample ({group[0]})') axes[row_idx, col_idx].set_title(f'Subsample size: {group[1]}') axes[row_idx, col_idx].legend() fig.savefig('plots/' + 'grid_plot.pdf') plt.close()
true
true
1c341554ac9b7a0b6cb004b22f6f12d6d712fcb7
267
py
Python
jp.atcoder/abc136/abc136_c/12000304.py
kagemeka/atcoder-submissions
91d8ad37411ea2ec582b10ba41b1e3cae01d4d6e
[ "MIT" ]
1
2022-02-09T03:06:25.000Z
2022-02-09T03:06:25.000Z
jp.atcoder/abc136/abc136_c/12000304.py
kagemeka/atcoder-submissions
91d8ad37411ea2ec582b10ba41b1e3cae01d4d6e
[ "MIT" ]
1
2022-02-05T22:53:18.000Z
2022-02-09T01:29:30.000Z
jp.atcoder/abc136/abc136_c/12000304.py
kagemeka/atcoder-submissions
91d8ad37411ea2ec582b10ba41b1e3cae01d4d6e
[ "MIT" ]
null
null
null
import sys n, *h = map(int, sys.stdin.read().split()) def main(): ans = 'Yes' for i in range(n - 1, 0, -1): if h[i-1] > h[i]: h[i-1] -= 1 if h[i-1] > h[i]: ans = 'No'; break print(ans) if __name__ == '__main__': main()
19.071429
44
0.449438
import sys n, *h = map(int, sys.stdin.read().split()) def main(): ans = 'Yes' for i in range(n - 1, 0, -1): if h[i-1] > h[i]: h[i-1] -= 1 if h[i-1] > h[i]: ans = 'No'; break print(ans) if __name__ == '__main__': main()
true
true
1c34161cb6d656bb855f3974b66bc85b05c6f779
6,909
py
Python
test/test_catalog.py
mickybart/openbrokerapi
a2d57334da0061425731adc4e10376f2123f71f1
[ "MIT" ]
null
null
null
test/test_catalog.py
mickybart/openbrokerapi
a2d57334da0061425731adc4e10376f2123f71f1
[ "MIT" ]
null
null
null
test/test_catalog.py
mickybart/openbrokerapi
a2d57334da0061425731adc4e10376f2123f71f1
[ "MIT" ]
null
null
null
import http from openbrokerapi.catalog import ( ServiceDashboardClient, ServiceMetadata, ServicePlan, ServicePlanCost, ServicePlanMetaData, ) from openbrokerapi.service_broker import Service from test import BrokerTestCase class CatalogTest(BrokerTestCase): service = Service( id="s1", name="service_name", description="service_description", bindable=True, plans=[ServicePlan(id="p1", name="default", description="plan_description")] ) def test_catalog_called_with_the_right_values(self): self.broker.catalog.return_value = self.service self.client.get( "/v2/catalog", headers={ 'X-Broker-Api-Version': '2.13', 'Authorization': self.auth_header }) self.assertTrue(self.broker.catalog.called) def test_catalog_ignores_request_headers(self): self.broker.catalog.return_value = self.service self.client.get( "/v2/catalog", headers={ 'X-Broker-Api-Version': '2.13', 'Authorization': self.auth_header, "unknown": "unknown" }) self.assertTrue(self.broker.catalog.called) def test_catalog_returns_200_with_service_information(self): self.broker.catalog.return_value = Service( id="s1", name="service_name", description="service_description", bindable=True, plans=[ServicePlan( id="p1", name="default", description="plan_description", metadata=ServicePlanMetaData( displayName="displayName", bullets=["bullet1"], costs=[ServicePlanCost( amount={"requests": 1}, unit="unit" )] ), free=True, bindable=True )], tags=['tag1', 'tag2'], requires=['something'], metadata=ServiceMetadata( displayName="displayName", imageUrl="imageUrl", longDescription="longDescription", providerDisplayName="providerDisplayName", documentationUrl="documentationUrl", supportUrl="supportUrl" ), dashboard_client=ServiceDashboardClient( id="id", secret="secret", redirect_uri="redirect_uri" ), plan_updateable=True ) response = self.client.get( "/v2/catalog", headers={ 'X-Broker-Api-Version': '2.13', 'Authorization': self.auth_header, "unknown": "unknown" }) self.assertEqual(response.status_code, http.HTTPStatus.OK) self.assertEqual(response.json, dict( services=[ dict(id="s1", name="service_name", description="service_description", bindable=True, plans=[dict( id="p1", name="default", description="plan_description", metadata=dict( displayName="displayName", bullets=["bullet1"], costs=[dict( amount={"requests": 1}, unit="unit" )] ), free=True, bindable=True )], tags=['tag1', 'tag2'], requires=['something'], metadata=dict( displayName="displayName", imageUrl="imageUrl", longDescription="longDescription", providerDisplayName="providerDisplayName", documentationUrl="documentationUrl", supportUrl="supportUrl" ), dashboard_client=dict( id="id", secret="secret", redirect_uri="redirect_uri" ), plan_updateable=True ) ] )) def test_catalog_returns_200_with_minimal_service_information(self): self.broker.catalog.return_value = self.service response = self.client.get( "/v2/catalog", headers={ 'X-Broker-Api-Version': '2.13', 'Authorization': self.auth_header, "unknown": "unknown" }) self.assertEqual(response.status_code, http.HTTPStatus.OK) self.assertEqual(response.json, dict( services=[ dict( id="s1", name="service_name", description="service_description", bindable=True, plan_updateable=False, plans=[dict(id="p1", name="default", description="plan_description")] ) ] )) def test_catalog_returns_500_if_error_raised(self): self.broker.catalog.side_effect = Exception("ERROR") response = self.client.get( "/v2/catalog", headers={ 'X-Broker-Api-Version': '2.13', 'Authorization': self.auth_header, "unknown": "unknown" }) self.assertEqual(response.status_code, http.HTTPStatus.INTERNAL_SERVER_ERROR) self.assertEqual(response.json, dict( description="ERROR" ))
38.383333
106
0.4099
import http from openbrokerapi.catalog import ( ServiceDashboardClient, ServiceMetadata, ServicePlan, ServicePlanCost, ServicePlanMetaData, ) from openbrokerapi.service_broker import Service from test import BrokerTestCase class CatalogTest(BrokerTestCase): service = Service( id="s1", name="service_name", description="service_description", bindable=True, plans=[ServicePlan(id="p1", name="default", description="plan_description")] ) def test_catalog_called_with_the_right_values(self): self.broker.catalog.return_value = self.service self.client.get( "/v2/catalog", headers={ 'X-Broker-Api-Version': '2.13', 'Authorization': self.auth_header }) self.assertTrue(self.broker.catalog.called) def test_catalog_ignores_request_headers(self): self.broker.catalog.return_value = self.service self.client.get( "/v2/catalog", headers={ 'X-Broker-Api-Version': '2.13', 'Authorization': self.auth_header, "unknown": "unknown" }) self.assertTrue(self.broker.catalog.called) def test_catalog_returns_200_with_service_information(self): self.broker.catalog.return_value = Service( id="s1", name="service_name", description="service_description", bindable=True, plans=[ServicePlan( id="p1", name="default", description="plan_description", metadata=ServicePlanMetaData( displayName="displayName", bullets=["bullet1"], costs=[ServicePlanCost( amount={"requests": 1}, unit="unit" )] ), free=True, bindable=True )], tags=['tag1', 'tag2'], requires=['something'], metadata=ServiceMetadata( displayName="displayName", imageUrl="imageUrl", longDescription="longDescription", providerDisplayName="providerDisplayName", documentationUrl="documentationUrl", supportUrl="supportUrl" ), dashboard_client=ServiceDashboardClient( id="id", secret="secret", redirect_uri="redirect_uri" ), plan_updateable=True ) response = self.client.get( "/v2/catalog", headers={ 'X-Broker-Api-Version': '2.13', 'Authorization': self.auth_header, "unknown": "unknown" }) self.assertEqual(response.status_code, http.HTTPStatus.OK) self.assertEqual(response.json, dict( services=[ dict(id="s1", name="service_name", description="service_description", bindable=True, plans=[dict( id="p1", name="default", description="plan_description", metadata=dict( displayName="displayName", bullets=["bullet1"], costs=[dict( amount={"requests": 1}, unit="unit" )] ), free=True, bindable=True )], tags=['tag1', 'tag2'], requires=['something'], metadata=dict( displayName="displayName", imageUrl="imageUrl", longDescription="longDescription", providerDisplayName="providerDisplayName", documentationUrl="documentationUrl", supportUrl="supportUrl" ), dashboard_client=dict( id="id", secret="secret", redirect_uri="redirect_uri" ), plan_updateable=True ) ] )) def test_catalog_returns_200_with_minimal_service_information(self): self.broker.catalog.return_value = self.service response = self.client.get( "/v2/catalog", headers={ 'X-Broker-Api-Version': '2.13', 'Authorization': self.auth_header, "unknown": "unknown" }) self.assertEqual(response.status_code, http.HTTPStatus.OK) self.assertEqual(response.json, dict( services=[ dict( id="s1", name="service_name", description="service_description", bindable=True, plan_updateable=False, plans=[dict(id="p1", name="default", description="plan_description")] ) ] )) def test_catalog_returns_500_if_error_raised(self): self.broker.catalog.side_effect = Exception("ERROR") response = self.client.get( "/v2/catalog", headers={ 'X-Broker-Api-Version': '2.13', 'Authorization': self.auth_header, "unknown": "unknown" }) self.assertEqual(response.status_code, http.HTTPStatus.INTERNAL_SERVER_ERROR) self.assertEqual(response.json, dict( description="ERROR" ))
true
true
1c3416ab88fda022aac2cf4ef1c028fed8372863
427
py
Python
Problem Solving/Search Algorithms/Data Structure Examples/Stack.py
cholazzzb/A-Study-of-AI
b069d536eb344a363d1b042086926d026afc0360
[ "MIT" ]
null
null
null
Problem Solving/Search Algorithms/Data Structure Examples/Stack.py
cholazzzb/A-Study-of-AI
b069d536eb344a363d1b042086926d026afc0360
[ "MIT" ]
null
null
null
Problem Solving/Search Algorithms/Data Structure Examples/Stack.py
cholazzzb/A-Study-of-AI
b069d536eb344a363d1b042086926d026afc0360
[ "MIT" ]
null
null
null
class Stack(object): 'Stack' def __init__(self, build): self.data = [build] print("Stack :", self.data) def push(self, new): self.data.append(new) print("Stack :", self.data) def pop(self): out = self.data.pop(-1) print("Stack :", self.data) return out data = Stack(5) data.pop() data.push(3) data.push(23) data.push(3) data.push(234) data.pop()
17.08
35
0.552693
class Stack(object): def __init__(self, build): self.data = [build] print("Stack :", self.data) def push(self, new): self.data.append(new) print("Stack :", self.data) def pop(self): out = self.data.pop(-1) print("Stack :", self.data) return out data = Stack(5) data.pop() data.push(3) data.push(23) data.push(3) data.push(234) data.pop()
true
true
1c34177280393478e3fc7c88fc4d2eed5f5f808e
524
py
Python
backend/home/migrations/0002_homme1.py
crowdbotics-dev/retyetuytrd-dev-23670
ed9bf7a6d019152274452ca82896664771233b81
[ "FTL", "AML", "RSA-MD" ]
null
null
null
backend/home/migrations/0002_homme1.py
crowdbotics-dev/retyetuytrd-dev-23670
ed9bf7a6d019152274452ca82896664771233b81
[ "FTL", "AML", "RSA-MD" ]
null
null
null
backend/home/migrations/0002_homme1.py
crowdbotics-dev/retyetuytrd-dev-23670
ed9bf7a6d019152274452ca82896664771233b81
[ "FTL", "AML", "RSA-MD" ]
null
null
null
# Generated by Django 2.2.26 on 2022-03-11 07:27 from django.db import migrations, models class Migration(migrations.Migration): initial = True dependencies = [ ('home', '0001_load_initial_data'), ] operations = [ migrations.CreateModel( name='Homme1', fields=[ ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')), ('phone', models.BigIntegerField()), ], ), ]
22.782609
114
0.572519
from django.db import migrations, models class Migration(migrations.Migration): initial = True dependencies = [ ('home', '0001_load_initial_data'), ] operations = [ migrations.CreateModel( name='Homme1', fields=[ ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')), ('phone', models.BigIntegerField()), ], ), ]
true
true
1c3418889fe5c8db858f699a6da7c157d7e3c801
8,302
py
Python
src/m5r_fancy_iterating.py
munnamn/11-Sequences
8e03697d635fb7121e393402462b1caa341ba45b
[ "MIT" ]
null
null
null
src/m5r_fancy_iterating.py
munnamn/11-Sequences
8e03697d635fb7121e393402462b1caa341ba45b
[ "MIT" ]
null
null
null
src/m5r_fancy_iterating.py
munnamn/11-Sequences
8e03697d635fb7121e393402462b1caa341ba45b
[ "MIT" ]
null
null
null
""" This module shows how to ITERATE (i.e. loop) through a SEQUENCE in ways OTHER than just going thru the sequence from BEGINNING to END. It also shows how to SELECT items in a sequence, e.g.: -- the items that are strings -- the items that are even integers (e.g. 2, 4, 6, ...) Note that: -- SELECTING items that ARE even integers is different from: -- LOOKING only at items AT even-numbered indices. Authors: David Mutchler, Vibha Alangar, Matt Boutell, Dave Fisher, Mark Hays, Amanda Stouder, Aaron Wilkin, their colleagues, and Nihaar Munnamgi. """ # DONE: 1. PUT YOUR NAME IN THE ABOVE LINE. ############################################################################### # DONE: 2. READ the program below and RUN it. # # When you have read it, asking questions as needed, # and you feel that you understand: # -- how to loop through a sequence # in ways OTHER than just from BEGINNING to END, # -- how to SELECT items in sequence # -- the distinction between: # -- SELECTING items that ARE even integers and # -- LOOKING only at items AT even-numbered indices. # then: # change the above _TODO to DONE. ############################################################################### def main(): """ Calls the TEST functions in this module. """ run_test_sum_string_lengths() run_test_sum_even_integers() run_test_sum_items_at_even_indices() ############################################################################### # The TEST functions are further down in the file, # so that you can focus on the following examples. ############################################################################### def sum_string_lengths(sequence, m, n): """ What comes in: -- A sequence of strings -- Integers m and n, where 0 <= m <= n < length of the sequence (which ensures that you can safely use m and n as indices) What goes out: Returns the sum of the lengths of the strings at indices m to n, inclusive, with the restriction that the loop must go thru the sequence BACKWARDS. Side effects: None. Examples: Suppose that sequence is: ['five', 'OK', 'songs', 'roxanne', 'the police', '', 'three'] Then: -- sum_string_lengths(sequence, 1, 3) returns the length of 'roxanne' plus the length of 'songs' plus the length of 'OK', which is 7 + 5 + 2, which is 14. -- sum_string_lengths(sequence, 2, 6) returns the length of 'three' plus the length of '' plus the length of 'the police' plus the length of 'roxanne' plus the length of 'songs, which is 5 + 0 + 10 + 7 + 5, which is 27. Type hints: :type sequence: list or tuple (of strings) :type m: int :type n: int """ # ------------------------------------------------------------------------- # EXAMPLE 1. Iterates through PART of a sequence, BACKWARDS. # ------------------------------------------------------------------------- total = 0 for k in range(n, m - 1, -1): s = sequence[k] total = total + len(s) return total # Here is an alternative (there are other alternatives as well): total = 0 for k in range(m, n + 1): total = total + len(sequence[m + n - k]) return total def sum_even_integers(sequence): """ What comes in: -- A sequence What goes out: Returns the sum of the items in the sequence that: -- are integers AND -- are even. Side effects: None. Examples: sum_even_integers([3, 10, 6, 5, 5, 10]) returns 10 + 6 + 10, which is 26 sum_even_integers([3, 9, 10, 99, 101, 5, 6, 5, 5, 10]) still returns 10 + 6 + 10, which is 26 sum_even_integers(['hello', 3, 10, 6, 'bye', 5, 7.33, 5, 10]) still returns 10 + 6 + 10, which is 26 Type hints: :type sequence: list or tuple """ # ------------------------------------------------------------------------- # EXAMPLE 2. Iterates through a sequence, # identifying and summing the items that are EVEN INTEGERS. # # Note how: # -- The TYPE function returns the TYPE of its argument. # -- An integer X is EVEN if the remainder is 0 # when you divide X by 2 and take the remainder. # ------------------------------------------------------------------------- total = 0 for k in range(len(sequence)): item = sequence[k] if type(item) is int: if item % 2 == 0: total = total + item return total # Here is an alternative (there are other alternatives as well): total = 0 for k in range(len(sequence)): if (type(sequence[k]) is int) and (sequence[k] % 2 == 0): total = total + sequence[k] return total def sum_items_at_even_indices(sequence): """ What comes in: -- A sequence of numbers. What goes out: Returns the sum of the numbers in the list that: -- are at EVEN INDICES. Side effects: None. Examples: sum_items_at_even_indices([3, 10, 6, 5, 5, 10]) returns 3 + 6 + 5, which is 14 sum_items_at_even_indices([5.5, 10, 3, 2, 10, 0, 1]) returns 5.5 + 3 + 10 + 1, which is 19.5 Type hints: :type sequence: list or tuple (of numbers) """ # ------------------------------------------------------------------------- # EXAMPLE 3. Iterates through and sums the items in a list # of numbers that are at even INDICES. # # Constrast this example with the previous example. # ------------------------------------------------------------------------- total = 0 for k in range(0, len(sequence), 2): total = total + sequence[k] return total # Here is a ** BAD alternative ** that computes the right result # but takes twice as long to do so as needed. total = 0 for k in range(len(sequence)): # This is a BAD solution if k % 2 == 0: total = total + sequence[k] return total ############################################################################### # Just TEST functions below here. ############################################################################### def run_test_sum_string_lengths(): """ Tests the sum_string_lengths function. """ print() print('--------------------------------------------------') print('Testing the sum_string_lengths function:') print('--------------------------------------------------') seq = ['five', 'OK', 'songs', 'roxanne', 'the police', '', 'three'] total1 = sum_string_lengths(seq, 1, 3) total2 = sum_string_lengths(seq, 2, 6) print('Returned, expected:', total1, 14) print('Returned, expected:', total2, 27) def run_test_sum_even_integers(): """ Tests the sum_even_integers function. """ print() print('--------------------------------------------------') print('Testing the sum_even_integers function:') print('--------------------------------------------------') total1 = sum_even_integers([3, 10, 6, 5, 5, 10]) total2 = sum_even_integers(['hello', 3, 10, 6, 'bye', 5, 7.33, 5, 10]) total3 = sum_even_integers([3, 9, 10, 99, 101, 5, 6, 5, 5, 10]) print('Returned, expected:', total1, 26) print('Returned, expected:', total2, 26) print('Returned, expected:', total3, 26) def run_test_sum_items_at_even_indices(): """ Tests the sum_items_at_even_indices function. """ print() print('--------------------------------------------------') print('Testing the sum_items_at_even_indices function:') print('--------------------------------------------------') total1 = sum_items_at_even_indices([3, 10, 6, 5, 5, 10]) total2 = sum_items_at_even_indices([5.5, 10, 3, 2, 10, 0, 1]) print('Returned, expected:', total1, 14) print('Returned, expected:', total2, 19.5) # ----------------------------------------------------------------------------- # Calls main to start the ball rolling. # ----------------------------------------------------------------------------- main()
34.448133
79
0.503252
true
true
1c3418a9ba18af2f77f23c15c0404c43548e23c4
1,446
py
Python
setup.py
ChaitanyaSinghBisht/PyWhatKit
ff4b876fb8846f3afa4c9a84b1aa1bd676225207
[ "MIT" ]
1
2021-01-27T11:34:24.000Z
2021-01-27T11:34:24.000Z
setup.py
AshleyAlexJacob/PyWhatKit
866f960f6309378959d9a47e1e2d6854952ca273
[ "MIT" ]
3
2021-09-08T03:19:26.000Z
2022-03-12T00:58:05.000Z
setup.py
AshleyAlexJacob/PyWhatKit
866f960f6309378959d9a47e1e2d6854952ca273
[ "MIT" ]
null
null
null
from distutils.core import setup import setuptools def readme(): with open(r'README.md') as f: README = f.read() return README setup( name = 'pywhatkit', packages = setuptools.find_packages(), version = '2.9', license='MIT', description = 'pywhatkit is a Python library for Sending whatsapp message at certain time, it has several other features too.', author = 'Ankit Raj Mahapatra', author_email = 'ankitrajjitendra816@gmail.com', url = 'https://github.com/Ankit404butfound/awesomepy', download_url = 'https://github.com/Ankit404butfound/awesomepy/archive/1.0.tar.gz', keywords = ['sendwhatmsg', 'info', 'playonyt', 'search','watch_tutorial'], install_requires=[ 'pyautogui', 'beautifulsoup4', 'wikipedia', 'requests', 'Pillow', 'numpy', 'opencv-python', ], include_package_data=True, long_description=readme(), long_description_content_type="text/markdown", classifiers=[ 'Development Status :: 3 - Alpha', 'Intended Audience :: Developers', 'Topic :: Software Development :: Build Tools', 'License :: OSI Approved :: MIT License', 'Programming Language :: Python :: 3', 'Programming Language :: Python :: 3.4', 'Programming Language :: Python :: 3.5', 'Programming Language :: Python :: 3.6', ], )
32.863636
132
0.609267
from distutils.core import setup import setuptools def readme(): with open(r'README.md') as f: README = f.read() return README setup( name = 'pywhatkit', packages = setuptools.find_packages(), version = '2.9', license='MIT', description = 'pywhatkit is a Python library for Sending whatsapp message at certain time, it has several other features too.', author = 'Ankit Raj Mahapatra', author_email = 'ankitrajjitendra816@gmail.com', url = 'https://github.com/Ankit404butfound/awesomepy', download_url = 'https://github.com/Ankit404butfound/awesomepy/archive/1.0.tar.gz', keywords = ['sendwhatmsg', 'info', 'playonyt', 'search','watch_tutorial'], install_requires=[ 'pyautogui', 'beautifulsoup4', 'wikipedia', 'requests', 'Pillow', 'numpy', 'opencv-python', ], include_package_data=True, long_description=readme(), long_description_content_type="text/markdown", classifiers=[ 'Development Status :: 3 - Alpha', 'Intended Audience :: Developers', 'Topic :: Software Development :: Build Tools', 'License :: OSI Approved :: MIT License', 'Programming Language :: Python :: 3', 'Programming Language :: Python :: 3.4', 'Programming Language :: Python :: 3.5', 'Programming Language :: Python :: 3.6', ], )
true
true
1c341977f01cd73a75c3fd0b665b08c602d34f78
1,857
py
Python
Python-Programs/Sorting Algorithms/pancakeSort.py
naschwin/Simple-Programs
a06e62b7280890cc8e3b9d2dfac9b7fd90706af3
[ "MIT" ]
null
null
null
Python-Programs/Sorting Algorithms/pancakeSort.py
naschwin/Simple-Programs
a06e62b7280890cc8e3b9d2dfac9b7fd90706af3
[ "MIT" ]
null
null
null
Python-Programs/Sorting Algorithms/pancakeSort.py
naschwin/Simple-Programs
a06e62b7280890cc8e3b9d2dfac9b7fd90706af3
[ "MIT" ]
1
2021-10-09T09:51:22.000Z
2021-10-09T09:51:22.000Z
import pygame, sys, random WHITE = (255, 255, 255) BLACK = (0, 0, 0) WIDTH = 720 HEIGHT = 400 win_size = (WIDTH, HEIGHT) pygame.init() win = pygame.display.set_mode(win_size) pygame.display.set_caption('Pancake Sort') clock = pygame.time.Clock() #width of the bars n = 4 w = int(WIDTH/n) h_arr = [] states = [] for i in range(w): #height of the bars height = random.randint(10, HEIGHT) h_arr.append(height) states.append(0) def maps(num, in_min, in_max, out_min, out_max): return (num - in_min) * (out_max - out_min) / (in_max - in_min) + out_min def flip(arr, i): start = 0 while start < i: temp = arr[start] arr[start] = arr[i] arr[i] = temp start += 1 i -= 1 flag = False cur_size = len(h_arr) while True: win.fill(BLACK) if flag: if cur_size > 1: mi = h_arr.index(max(h_arr[:cur_size])) states[cur_size - 1] = 2 if mi != cur_size - 1: flip(h_arr, mi) flip(h_arr, cur_size - 1) cur_size -= 1 else: states[0] = 2 for i in range(len(h_arr)): # if states[i] == 0: # color = (255, 0, 0) # elif states[i] == 2: # color = (0, 255, 0) # else: # color = WHITE h_ar = maps(h_arr[i], 0, HEIGHT, 20, 255) pygame.draw.rect(win, (h_ar//3, h_ar, h_ar//4), pygame.Rect(int(i*n), (HEIGHT - h_arr[i])//2, n, h_arr[i])) for event in pygame.event.get(): if event.type == pygame.QUIT: pygame.quit() sys.exit() if event.type == pygame.KEYDOWN: if event.key == pygame.K_RETURN: flag = True clock.tick(20) pygame.display.flip()
22.925926
116
0.501885
import pygame, sys, random WHITE = (255, 255, 255) BLACK = (0, 0, 0) WIDTH = 720 HEIGHT = 400 win_size = (WIDTH, HEIGHT) pygame.init() win = pygame.display.set_mode(win_size) pygame.display.set_caption('Pancake Sort') clock = pygame.time.Clock() n = 4 w = int(WIDTH/n) h_arr = [] states = [] for i in range(w): height = random.randint(10, HEIGHT) h_arr.append(height) states.append(0) def maps(num, in_min, in_max, out_min, out_max): return (num - in_min) * (out_max - out_min) / (in_max - in_min) + out_min def flip(arr, i): start = 0 while start < i: temp = arr[start] arr[start] = arr[i] arr[i] = temp start += 1 i -= 1 flag = False cur_size = len(h_arr) while True: win.fill(BLACK) if flag: if cur_size > 1: mi = h_arr.index(max(h_arr[:cur_size])) states[cur_size - 1] = 2 if mi != cur_size - 1: flip(h_arr, mi) flip(h_arr, cur_size - 1) cur_size -= 1 else: states[0] = 2 for i in range(len(h_arr)): h_ar = maps(h_arr[i], 0, HEIGHT, 20, 255) pygame.draw.rect(win, (h_ar//3, h_ar, h_ar//4), pygame.Rect(int(i*n), (HEIGHT - h_arr[i])//2, n, h_arr[i])) for event in pygame.event.get(): if event.type == pygame.QUIT: pygame.quit() sys.exit() if event.type == pygame.KEYDOWN: if event.key == pygame.K_RETURN: flag = True clock.tick(20) pygame.display.flip()
true
true
1c341a125f820f2c895baafa6db006a93966988e
6,374
py
Python
tempest/api/image/base.py
BeenzSyed/tempest
7a64ee1216d844f6b99928b53f5c665b84cb8719
[ "Apache-2.0" ]
null
null
null
tempest/api/image/base.py
BeenzSyed/tempest
7a64ee1216d844f6b99928b53f5c665b84cb8719
[ "Apache-2.0" ]
null
null
null
tempest/api/image/base.py
BeenzSyed/tempest
7a64ee1216d844f6b99928b53f5c665b84cb8719
[ "Apache-2.0" ]
null
null
null
# Copyright 2013 IBM Corp. # # 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 cStringIO as StringIO from tempest import clients from tempest.common import isolated_creds from tempest.common.utils import data_utils from tempest import exceptions from tempest.openstack.common import log as logging import tempest.test LOG = logging.getLogger(__name__) class BaseImageTest(tempest.test.BaseTestCase): """Base test class for Image API tests.""" @classmethod def setUpClass(cls): cls.set_network_resources() super(BaseImageTest, cls).setUpClass() cls.created_images = [] cls._interface = 'json' cls.isolated_creds = isolated_creds.IsolatedCreds( cls.__name__, network_resources=cls.network_resources) if not cls.config.service_available.glance: skip_msg = ("%s skipped as glance is not available" % cls.__name__) raise cls.skipException(skip_msg) if cls.config.compute.allow_tenant_isolation: creds = cls.isolated_creds.get_primary_creds() username, tenant_name, password = creds cls.os = clients.Manager(username=username, password=password, tenant_name=tenant_name) else: cls.os = clients.Manager() @classmethod def tearDownClass(cls): for image_id in cls.created_images: try: cls.client.delete_image(image_id) except exceptions.NotFound: pass for image_id in cls.created_images: cls.client.wait_for_resource_deletion(image_id) cls.isolated_creds.clear_isolated_creds() super(BaseImageTest, cls).tearDownClass() @classmethod def create_image(cls, **kwargs): """Wrapper that returns a test image.""" name = data_utils.rand_name(cls.__name__ + "-instance") if 'name' in kwargs: name = kwargs.pop('name') container_format = kwargs.pop('container_format') disk_format = kwargs.pop('disk_format') resp, image = cls.client.create_image(name, container_format, disk_format, **kwargs) cls.created_images.append(image['id']) return resp, image class BaseV1ImageTest(BaseImageTest): @classmethod def setUpClass(cls): super(BaseV1ImageTest, cls).setUpClass() cls.client = cls.os.image_client if not cls.config.image_feature_enabled.api_v1: msg = "Glance API v1 not supported" raise cls.skipException(msg) class BaseV1ImageMembersTest(BaseV1ImageTest): @classmethod def setUpClass(cls): super(BaseV1ImageMembersTest, cls).setUpClass() if cls.config.compute.allow_tenant_isolation: creds = cls.isolated_creds.get_alt_creds() username, tenant_name, password = creds cls.os_alt = clients.Manager(username=username, password=password, tenant_name=tenant_name) cls.alt_tenant_id = cls.isolated_creds.get_alt_tenant()['id'] else: cls.os_alt = clients.AltManager() identity_client = cls._get_identity_admin_client() cls.alt_tenant_id = identity_client.get_tenant_by_name( cls.os_alt.tenant_name)['id'] cls.alt_img_cli = cls.os_alt.image_client def _create_image(self): image_file = StringIO.StringIO('*' * 1024) resp, image = self.create_image(container_format='bare', disk_format='raw', is_public=False, data=image_file) self.assertEqual(201, resp.status) image_id = image['id'] return image_id class BaseV2ImageTest(BaseImageTest): @classmethod def setUpClass(cls): super(BaseV2ImageTest, cls).setUpClass() cls.client = cls.os.image_client_v2 if not cls.config.image_feature_enabled.api_v2: msg = "Glance API v2 not supported" raise cls.skipException(msg) class BaseV2MemeberImageTest(BaseV2ImageTest): @classmethod def setUpClass(cls): super(BaseV2MemeberImageTest, cls).setUpClass() if cls.config.compute.allow_tenant_isolation: creds = cls.isolated_creds.get_alt_creds() username, tenant_name, password = creds cls.os_alt = clients.Manager(username=username, password=password, tenant_name=tenant_name, interface=cls._interface) cls.alt_tenant_id = cls.isolated_creds.get_alt_tenant()['id'] else: cls.os_alt = clients.AltManager() alt_tenant_name = cls.os_alt.tenant_name identity_client = cls._get_identity_admin_client() cls.alt_tenant_id = identity_client.get_tenant_by_name( alt_tenant_name)['id'] cls.os_img_client = cls.os.image_client_v2 cls.alt_img_client = cls.os_alt.image_client_v2 def _list_image_ids_as_alt(self): _, image_list = self.alt_img_client.image_list() image_ids = map(lambda x: x['id'], image_list) return image_ids def _create_image(self): name = data_utils.rand_name('image') resp, image = self.os_img_client.create_image(name, container_format='bare', disk_format='raw') image_id = image['id'] self.addCleanup(self.os_img_client.delete_image, image_id) return image_id
38.167665
79
0.617038
import cStringIO as StringIO from tempest import clients from tempest.common import isolated_creds from tempest.common.utils import data_utils from tempest import exceptions from tempest.openstack.common import log as logging import tempest.test LOG = logging.getLogger(__name__) class BaseImageTest(tempest.test.BaseTestCase): @classmethod def setUpClass(cls): cls.set_network_resources() super(BaseImageTest, cls).setUpClass() cls.created_images = [] cls._interface = 'json' cls.isolated_creds = isolated_creds.IsolatedCreds( cls.__name__, network_resources=cls.network_resources) if not cls.config.service_available.glance: skip_msg = ("%s skipped as glance is not available" % cls.__name__) raise cls.skipException(skip_msg) if cls.config.compute.allow_tenant_isolation: creds = cls.isolated_creds.get_primary_creds() username, tenant_name, password = creds cls.os = clients.Manager(username=username, password=password, tenant_name=tenant_name) else: cls.os = clients.Manager() @classmethod def tearDownClass(cls): for image_id in cls.created_images: try: cls.client.delete_image(image_id) except exceptions.NotFound: pass for image_id in cls.created_images: cls.client.wait_for_resource_deletion(image_id) cls.isolated_creds.clear_isolated_creds() super(BaseImageTest, cls).tearDownClass() @classmethod def create_image(cls, **kwargs): name = data_utils.rand_name(cls.__name__ + "-instance") if 'name' in kwargs: name = kwargs.pop('name') container_format = kwargs.pop('container_format') disk_format = kwargs.pop('disk_format') resp, image = cls.client.create_image(name, container_format, disk_format, **kwargs) cls.created_images.append(image['id']) return resp, image class BaseV1ImageTest(BaseImageTest): @classmethod def setUpClass(cls): super(BaseV1ImageTest, cls).setUpClass() cls.client = cls.os.image_client if not cls.config.image_feature_enabled.api_v1: msg = "Glance API v1 not supported" raise cls.skipException(msg) class BaseV1ImageMembersTest(BaseV1ImageTest): @classmethod def setUpClass(cls): super(BaseV1ImageMembersTest, cls).setUpClass() if cls.config.compute.allow_tenant_isolation: creds = cls.isolated_creds.get_alt_creds() username, tenant_name, password = creds cls.os_alt = clients.Manager(username=username, password=password, tenant_name=tenant_name) cls.alt_tenant_id = cls.isolated_creds.get_alt_tenant()['id'] else: cls.os_alt = clients.AltManager() identity_client = cls._get_identity_admin_client() cls.alt_tenant_id = identity_client.get_tenant_by_name( cls.os_alt.tenant_name)['id'] cls.alt_img_cli = cls.os_alt.image_client def _create_image(self): image_file = StringIO.StringIO('*' * 1024) resp, image = self.create_image(container_format='bare', disk_format='raw', is_public=False, data=image_file) self.assertEqual(201, resp.status) image_id = image['id'] return image_id class BaseV2ImageTest(BaseImageTest): @classmethod def setUpClass(cls): super(BaseV2ImageTest, cls).setUpClass() cls.client = cls.os.image_client_v2 if not cls.config.image_feature_enabled.api_v2: msg = "Glance API v2 not supported" raise cls.skipException(msg) class BaseV2MemeberImageTest(BaseV2ImageTest): @classmethod def setUpClass(cls): super(BaseV2MemeberImageTest, cls).setUpClass() if cls.config.compute.allow_tenant_isolation: creds = cls.isolated_creds.get_alt_creds() username, tenant_name, password = creds cls.os_alt = clients.Manager(username=username, password=password, tenant_name=tenant_name, interface=cls._interface) cls.alt_tenant_id = cls.isolated_creds.get_alt_tenant()['id'] else: cls.os_alt = clients.AltManager() alt_tenant_name = cls.os_alt.tenant_name identity_client = cls._get_identity_admin_client() cls.alt_tenant_id = identity_client.get_tenant_by_name( alt_tenant_name)['id'] cls.os_img_client = cls.os.image_client_v2 cls.alt_img_client = cls.os_alt.image_client_v2 def _list_image_ids_as_alt(self): _, image_list = self.alt_img_client.image_list() image_ids = map(lambda x: x['id'], image_list) return image_ids def _create_image(self): name = data_utils.rand_name('image') resp, image = self.os_img_client.create_image(name, container_format='bare', disk_format='raw') image_id = image['id'] self.addCleanup(self.os_img_client.delete_image, image_id) return image_id
true
true
1c341a4678e8e2200ae0b0556e8e280719fa2b93
8,103
py
Python
wrappers/python/virgil_crypto_lib/foundation/aes256_cbc.py
odidev/virgil-crypto-c
3d5d5cb19fdcf81eab08cdc63647f040117ecbd8
[ "BSD-3-Clause" ]
26
2018-12-17T13:45:25.000Z
2022-01-16T20:00:04.000Z
wrappers/python/virgil_crypto_lib/foundation/aes256_cbc.py
odidev/virgil-crypto-c
3d5d5cb19fdcf81eab08cdc63647f040117ecbd8
[ "BSD-3-Clause" ]
4
2019-01-03T12:08:52.000Z
2021-12-02T05:21:13.000Z
wrappers/python/virgil_crypto_lib/foundation/aes256_cbc.py
odidev/virgil-crypto-c
3d5d5cb19fdcf81eab08cdc63647f040117ecbd8
[ "BSD-3-Clause" ]
8
2019-01-24T08:22:06.000Z
2022-02-07T11:37:00.000Z
# Copyright (C) 2015-2021 Virgil Security, 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 AUTHOR ''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 AUTHOR 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. # # Lead Maintainer: Virgil Security Inc. <support@virgilsecurity.com> from ctypes import * from ._c_bridge import VscfAes256Cbc from ._c_bridge import VscfImplTag from ._c_bridge import VscfStatus from virgil_crypto_lib.common._c_bridge import Data from virgil_crypto_lib.common._c_bridge import Buffer from .alg import Alg from .encrypt import Encrypt from .decrypt import Decrypt from .cipher_info import CipherInfo from .cipher import Cipher class Aes256Cbc(Alg, Encrypt, Decrypt, CipherInfo, Cipher): """Implementation of the symmetric cipher AES-256 bit in a CBC mode. Note, this implementation contains dynamic memory allocations, this should be improved in the future releases.""" # Cipher nfonce length or IV length in bytes, or 0 if nonce is not required. NONCE_LEN = 16 # Cipher key length in bytes. KEY_LEN = 32 # Cipher key length in bits. KEY_BITLEN = 256 # Cipher block length in bytes. BLOCK_LEN = 16 def __init__(self): """Create underlying C context.""" self._lib_vscf_aes256_cbc = VscfAes256Cbc() self._c_impl = None self._ctx = None self.ctx = self._lib_vscf_aes256_cbc.vscf_aes256_cbc_new() def __delete__(self, instance): """Destroy underlying C context.""" self._lib_vscf_aes256_cbc.vscf_aes256_cbc_delete(self.ctx) def alg_id(self): """Provide algorithm identificator.""" result = self._lib_vscf_aes256_cbc.vscf_aes256_cbc_alg_id(self.ctx) return result def produce_alg_info(self): """Produce object with algorithm information and configuration parameters.""" result = self._lib_vscf_aes256_cbc.vscf_aes256_cbc_produce_alg_info(self.ctx) instance = VscfImplTag.get_type(result)[0].take_c_ctx(cast(result, POINTER(VscfImplTag.get_type(result)[1]))) return instance def restore_alg_info(self, alg_info): """Restore algorithm configuration from the given object.""" status = self._lib_vscf_aes256_cbc.vscf_aes256_cbc_restore_alg_info(self.ctx, alg_info.c_impl) VscfStatus.handle_status(status) def encrypt(self, data): """Encrypt given data.""" d_data = Data(data) out = Buffer(self.encrypted_len(data_len=len(data))) status = self._lib_vscf_aes256_cbc.vscf_aes256_cbc_encrypt(self.ctx, d_data.data, out.c_buffer) VscfStatus.handle_status(status) return out.get_bytes() def encrypted_len(self, data_len): """Calculate required buffer length to hold the encrypted data.""" result = self._lib_vscf_aes256_cbc.vscf_aes256_cbc_encrypted_len(self.ctx, data_len) return result def precise_encrypted_len(self, data_len): """Precise length calculation of encrypted data.""" result = self._lib_vscf_aes256_cbc.vscf_aes256_cbc_precise_encrypted_len(self.ctx, data_len) return result def decrypt(self, data): """Decrypt given data.""" d_data = Data(data) out = Buffer(self.decrypted_len(data_len=len(data))) status = self._lib_vscf_aes256_cbc.vscf_aes256_cbc_decrypt(self.ctx, d_data.data, out.c_buffer) VscfStatus.handle_status(status) return out.get_bytes() def decrypted_len(self, data_len): """Calculate required buffer length to hold the decrypted data.""" result = self._lib_vscf_aes256_cbc.vscf_aes256_cbc_decrypted_len(self.ctx, data_len) return result def set_nonce(self, nonce): """Setup IV or nonce.""" d_nonce = Data(nonce) self._lib_vscf_aes256_cbc.vscf_aes256_cbc_set_nonce(self.ctx, d_nonce.data) def set_key(self, key): """Set cipher encryption / decryption key.""" d_key = Data(key) self._lib_vscf_aes256_cbc.vscf_aes256_cbc_set_key(self.ctx, d_key.data) def start_encryption(self): """Start sequential encryption.""" self._lib_vscf_aes256_cbc.vscf_aes256_cbc_start_encryption(self.ctx) def start_decryption(self): """Start sequential decryption.""" self._lib_vscf_aes256_cbc.vscf_aes256_cbc_start_decryption(self.ctx) def update(self, data): """Process encryption or decryption of the given data chunk.""" d_data = Data(data) out = Buffer(self.out_len(data_len=len(data))) self._lib_vscf_aes256_cbc.vscf_aes256_cbc_update(self.ctx, d_data.data, out.c_buffer) return out.get_bytes() def out_len(self, data_len): """Return buffer length required to hold an output of the methods "update" or "finish" in an current mode. Pass zero length to define buffer length of the method "finish".""" result = self._lib_vscf_aes256_cbc.vscf_aes256_cbc_out_len(self.ctx, data_len) return result def encrypted_out_len(self, data_len): """Return buffer length required to hold an output of the methods "update" or "finish" in an encryption mode. Pass zero length to define buffer length of the method "finish".""" result = self._lib_vscf_aes256_cbc.vscf_aes256_cbc_encrypted_out_len(self.ctx, data_len) return result def decrypted_out_len(self, data_len): """Return buffer length required to hold an output of the methods "update" or "finish" in an decryption mode. Pass zero length to define buffer length of the method "finish".""" result = self._lib_vscf_aes256_cbc.vscf_aes256_cbc_decrypted_out_len(self.ctx, data_len) return result def finish(self): """Accomplish encryption or decryption process.""" out = Buffer(self.out_len(data_len=0)) status = self._lib_vscf_aes256_cbc.vscf_aes256_cbc_finish(self.ctx, out.c_buffer) VscfStatus.handle_status(status) return out.get_bytes() @classmethod def take_c_ctx(cls, c_ctx): inst = cls.__new__(cls) inst._lib_vscf_aes256_cbc = VscfAes256Cbc() inst.ctx = c_ctx return inst @classmethod def use_c_ctx(cls, c_ctx): inst = cls.__new__(cls) inst._lib_vscf_aes256_cbc = VscfAes256Cbc() inst.ctx = inst._lib_vscf_aes256_cbc.vscf_aes256_cbc_shallow_copy(c_ctx) return inst @property def c_impl(self): return self._c_impl @property def ctx(self): return self._ctx @ctx.setter def ctx(self, value): self._ctx = self._lib_vscf_aes256_cbc.vscf_aes256_cbc_shallow_copy(value) self._c_impl = self._lib_vscf_aes256_cbc.vscf_aes256_cbc_impl(self.ctx)
40.515
117
0.710971
from ctypes import * from ._c_bridge import VscfAes256Cbc from ._c_bridge import VscfImplTag from ._c_bridge import VscfStatus from virgil_crypto_lib.common._c_bridge import Data from virgil_crypto_lib.common._c_bridge import Buffer from .alg import Alg from .encrypt import Encrypt from .decrypt import Decrypt from .cipher_info import CipherInfo from .cipher import Cipher class Aes256Cbc(Alg, Encrypt, Decrypt, CipherInfo, Cipher): NONCE_LEN = 16 KEY_LEN = 32 KEY_BITLEN = 256 BLOCK_LEN = 16 def __init__(self): self._lib_vscf_aes256_cbc = VscfAes256Cbc() self._c_impl = None self._ctx = None self.ctx = self._lib_vscf_aes256_cbc.vscf_aes256_cbc_new() def __delete__(self, instance): self._lib_vscf_aes256_cbc.vscf_aes256_cbc_delete(self.ctx) def alg_id(self): result = self._lib_vscf_aes256_cbc.vscf_aes256_cbc_alg_id(self.ctx) return result def produce_alg_info(self): result = self._lib_vscf_aes256_cbc.vscf_aes256_cbc_produce_alg_info(self.ctx) instance = VscfImplTag.get_type(result)[0].take_c_ctx(cast(result, POINTER(VscfImplTag.get_type(result)[1]))) return instance def restore_alg_info(self, alg_info): status = self._lib_vscf_aes256_cbc.vscf_aes256_cbc_restore_alg_info(self.ctx, alg_info.c_impl) VscfStatus.handle_status(status) def encrypt(self, data): d_data = Data(data) out = Buffer(self.encrypted_len(data_len=len(data))) status = self._lib_vscf_aes256_cbc.vscf_aes256_cbc_encrypt(self.ctx, d_data.data, out.c_buffer) VscfStatus.handle_status(status) return out.get_bytes() def encrypted_len(self, data_len): result = self._lib_vscf_aes256_cbc.vscf_aes256_cbc_encrypted_len(self.ctx, data_len) return result def precise_encrypted_len(self, data_len): result = self._lib_vscf_aes256_cbc.vscf_aes256_cbc_precise_encrypted_len(self.ctx, data_len) return result def decrypt(self, data): d_data = Data(data) out = Buffer(self.decrypted_len(data_len=len(data))) status = self._lib_vscf_aes256_cbc.vscf_aes256_cbc_decrypt(self.ctx, d_data.data, out.c_buffer) VscfStatus.handle_status(status) return out.get_bytes() def decrypted_len(self, data_len): result = self._lib_vscf_aes256_cbc.vscf_aes256_cbc_decrypted_len(self.ctx, data_len) return result def set_nonce(self, nonce): d_nonce = Data(nonce) self._lib_vscf_aes256_cbc.vscf_aes256_cbc_set_nonce(self.ctx, d_nonce.data) def set_key(self, key): d_key = Data(key) self._lib_vscf_aes256_cbc.vscf_aes256_cbc_set_key(self.ctx, d_key.data) def start_encryption(self): self._lib_vscf_aes256_cbc.vscf_aes256_cbc_start_encryption(self.ctx) def start_decryption(self): self._lib_vscf_aes256_cbc.vscf_aes256_cbc_start_decryption(self.ctx) def update(self, data): d_data = Data(data) out = Buffer(self.out_len(data_len=len(data))) self._lib_vscf_aes256_cbc.vscf_aes256_cbc_update(self.ctx, d_data.data, out.c_buffer) return out.get_bytes() def out_len(self, data_len): result = self._lib_vscf_aes256_cbc.vscf_aes256_cbc_out_len(self.ctx, data_len) return result def encrypted_out_len(self, data_len): result = self._lib_vscf_aes256_cbc.vscf_aes256_cbc_encrypted_out_len(self.ctx, data_len) return result def decrypted_out_len(self, data_len): result = self._lib_vscf_aes256_cbc.vscf_aes256_cbc_decrypted_out_len(self.ctx, data_len) return result def finish(self): out = Buffer(self.out_len(data_len=0)) status = self._lib_vscf_aes256_cbc.vscf_aes256_cbc_finish(self.ctx, out.c_buffer) VscfStatus.handle_status(status) return out.get_bytes() @classmethod def take_c_ctx(cls, c_ctx): inst = cls.__new__(cls) inst._lib_vscf_aes256_cbc = VscfAes256Cbc() inst.ctx = c_ctx return inst @classmethod def use_c_ctx(cls, c_ctx): inst = cls.__new__(cls) inst._lib_vscf_aes256_cbc = VscfAes256Cbc() inst.ctx = inst._lib_vscf_aes256_cbc.vscf_aes256_cbc_shallow_copy(c_ctx) return inst @property def c_impl(self): return self._c_impl @property def ctx(self): return self._ctx @ctx.setter def ctx(self, value): self._ctx = self._lib_vscf_aes256_cbc.vscf_aes256_cbc_shallow_copy(value) self._c_impl = self._lib_vscf_aes256_cbc.vscf_aes256_cbc_impl(self.ctx)
true
true
1c341b88dfddbd4f7080f9bdde084e142e7f3d29
1,008
py
Python
code/Solution_0447_numberOfBoomerangs.py
qizhenkang/myLeetCode
cb9edce69567eba9d96ce756507a5a7ac6e74293
[ "MIT" ]
null
null
null
code/Solution_0447_numberOfBoomerangs.py
qizhenkang/myLeetCode
cb9edce69567eba9d96ce756507a5a7ac6e74293
[ "MIT" ]
null
null
null
code/Solution_0447_numberOfBoomerangs.py
qizhenkang/myLeetCode
cb9edce69567eba9d96ce756507a5a7ac6e74293
[ "MIT" ]
null
null
null
# -*- coding: utf-8 -*- """ Created on Mon Sep 13 09:43:47 2021 @author: qizhe """ class Solution: def numberOfBoomerangs(self, points) -> int: result = 0 for pi in points: distdict = {} for pj in points: dist = (pi[0] - pj[0])**2 + (pi[1] - pj[1])**2 if dist not in distdict: distdict[dist] = 1 else: distdict[dist] += 1 for m in distdict.values(): # print(distdict) result += m*(m-1) return result if __name__ == '__main__': solu = Solution() input_Str = str('hello') input_List =[[0,0],[1,0],[2,0]] # input_List = TreeNode(1) # input_List.left = TreeNode(2) # input_List.right = TreeNode(3) result = solu.numberOfBoomerangs(input_List) # output_Str = 'result = ' + solu.intToRoman(input_int) output_Str = ' result = ' + str(result) print(output_Str)
24
62
0.499008
class Solution: def numberOfBoomerangs(self, points) -> int: result = 0 for pi in points: distdict = {} for pj in points: dist = (pi[0] - pj[0])**2 + (pi[1] - pj[1])**2 if dist not in distdict: distdict[dist] = 1 else: distdict[dist] += 1 for m in distdict.values(): result += m*(m-1) return result if __name__ == '__main__': solu = Solution() input_Str = str('hello') input_List =[[0,0],[1,0],[2,0]] result = solu.numberOfBoomerangs(input_List) output_Str = ' result = ' + str(result) print(output_Str)
true
true
1c341bbaa6104c7364e7f7be8428c56c2f7c75d0
8,832
py
Python
sdk/python/pulumi_azure/network/virtual_hub_connection.py
adnang/pulumi-azure
32360d2f1e41e27d7fdd6522cb26d65e531f279f
[ "ECL-2.0", "Apache-2.0" ]
null
null
null
sdk/python/pulumi_azure/network/virtual_hub_connection.py
adnang/pulumi-azure
32360d2f1e41e27d7fdd6522cb26d65e531f279f
[ "ECL-2.0", "Apache-2.0" ]
null
null
null
sdk/python/pulumi_azure/network/virtual_hub_connection.py
adnang/pulumi-azure
32360d2f1e41e27d7fdd6522cb26d65e531f279f
[ "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 json import warnings import pulumi import pulumi.runtime from typing import Union from .. import utilities, tables class VirtualHubConnection(pulumi.CustomResource): hub_to_vitual_network_traffic_allowed: pulumi.Output[bool] """ Is the Virtual Hub traffic allowed to transit via the Remote Virtual Network? Changing this forces a new resource to be created. """ internet_security_enabled: pulumi.Output[bool] """ Should Internet Security be enabled to secure internet traffic? Changing this forces a new resource to be created. """ name: pulumi.Output[str] """ The Name which should be used for this Connection, which must be unique within the Virtual Hub. Changing this forces a new resource to be created. """ remote_virtual_network_id: pulumi.Output[str] """ The ID of the Virtual Network which the Virtual Hub should be connected to. Changing this forces a new resource to be created. """ virtual_hub_id: pulumi.Output[str] """ The ID of the Virtual Hub within which this connection should be created. Changing this forces a new resource to be created. """ vitual_network_to_hub_gateways_traffic_allowed: pulumi.Output[bool] """ Is Remote Virtual Network traffic allowed to transit the Hub's Virtual Network Gateway's? Changing this forces a new resource to be created. """ def __init__(__self__, resource_name, opts=None, hub_to_vitual_network_traffic_allowed=None, internet_security_enabled=None, name=None, remote_virtual_network_id=None, virtual_hub_id=None, vitual_network_to_hub_gateways_traffic_allowed=None, __props__=None, __name__=None, __opts__=None): """ Manages a Connection for a Virtual Hub. ## Example Usage ```python import pulumi import pulumi_azure as azure example_resource_group = azure.core.ResourceGroup("exampleResourceGroup", location="West Europe") example_virtual_network = azure.network.VirtualNetwork("exampleVirtualNetwork", address_spaces=["172.0.0.0/16"], location=example_resource_group.location, resource_group_name=example_resource_group.name) test = azure.network.VirtualWan("test", resource_group_name=example_resource_group.name, location=example_resource_group.location) example_virtual_hub = azure.network.VirtualHub("exampleVirtualHub", resource_group_name=example_resource_group.name, location=example_resource_group.location, virtual_wan_id=azurerm_virtual_wan["example"]["id"], address_prefix="10.0.1.0/24") example_virtual_hub_connection = azure.network.VirtualHubConnection("exampleVirtualHubConnection", virtual_hub_id=example_virtual_hub.id, remote_virtual_network_id=example_virtual_network.id) ``` :param str resource_name: The name of the resource. :param pulumi.ResourceOptions opts: Options for the resource. :param pulumi.Input[bool] hub_to_vitual_network_traffic_allowed: Is the Virtual Hub traffic allowed to transit via the Remote Virtual Network? Changing this forces a new resource to be created. :param pulumi.Input[bool] internet_security_enabled: Should Internet Security be enabled to secure internet traffic? Changing this forces a new resource to be created. :param pulumi.Input[str] name: The Name which should be used for this Connection, which must be unique within the Virtual Hub. Changing this forces a new resource to be created. :param pulumi.Input[str] remote_virtual_network_id: The ID of the Virtual Network which the Virtual Hub should be connected to. Changing this forces a new resource to be created. :param pulumi.Input[str] virtual_hub_id: The ID of the Virtual Hub within which this connection should be created. Changing this forces a new resource to be created. :param pulumi.Input[bool] vitual_network_to_hub_gateways_traffic_allowed: Is Remote Virtual Network traffic allowed to transit the Hub's Virtual Network Gateway's? Changing this forces a new resource to be created. """ if __name__ is not None: warnings.warn("explicit use of __name__ is deprecated", DeprecationWarning) resource_name = __name__ if __opts__ is not None: warnings.warn("explicit use of __opts__ is deprecated, use 'opts' instead", DeprecationWarning) opts = __opts__ if opts is None: opts = pulumi.ResourceOptions() if not isinstance(opts, pulumi.ResourceOptions): raise TypeError('Expected resource options to be a ResourceOptions instance') if opts.version is None: opts.version = utilities.get_version() if opts.id is None: if __props__ is not None: raise TypeError('__props__ is only valid when passed in combination with a valid opts.id to get an existing resource') __props__ = dict() __props__['hub_to_vitual_network_traffic_allowed'] = hub_to_vitual_network_traffic_allowed __props__['internet_security_enabled'] = internet_security_enabled __props__['name'] = name if remote_virtual_network_id is None: raise TypeError("Missing required property 'remote_virtual_network_id'") __props__['remote_virtual_network_id'] = remote_virtual_network_id if virtual_hub_id is None: raise TypeError("Missing required property 'virtual_hub_id'") __props__['virtual_hub_id'] = virtual_hub_id __props__['vitual_network_to_hub_gateways_traffic_allowed'] = vitual_network_to_hub_gateways_traffic_allowed super(VirtualHubConnection, __self__).__init__( 'azure:network/virtualHubConnection:VirtualHubConnection', resource_name, __props__, opts) @staticmethod def get(resource_name, id, opts=None, hub_to_vitual_network_traffic_allowed=None, internet_security_enabled=None, name=None, remote_virtual_network_id=None, virtual_hub_id=None, vitual_network_to_hub_gateways_traffic_allowed=None): """ Get an existing VirtualHubConnection resource's state with the given name, id, and optional extra properties used to qualify the lookup. :param str resource_name: The unique name of the resulting resource. :param str id: The unique provider ID of the resource to lookup. :param pulumi.ResourceOptions opts: Options for the resource. :param pulumi.Input[bool] hub_to_vitual_network_traffic_allowed: Is the Virtual Hub traffic allowed to transit via the Remote Virtual Network? Changing this forces a new resource to be created. :param pulumi.Input[bool] internet_security_enabled: Should Internet Security be enabled to secure internet traffic? Changing this forces a new resource to be created. :param pulumi.Input[str] name: The Name which should be used for this Connection, which must be unique within the Virtual Hub. Changing this forces a new resource to be created. :param pulumi.Input[str] remote_virtual_network_id: The ID of the Virtual Network which the Virtual Hub should be connected to. Changing this forces a new resource to be created. :param pulumi.Input[str] virtual_hub_id: The ID of the Virtual Hub within which this connection should be created. Changing this forces a new resource to be created. :param pulumi.Input[bool] vitual_network_to_hub_gateways_traffic_allowed: Is Remote Virtual Network traffic allowed to transit the Hub's Virtual Network Gateway's? Changing this forces a new resource to be created. """ opts = pulumi.ResourceOptions.merge(opts, pulumi.ResourceOptions(id=id)) __props__ = dict() __props__["hub_to_vitual_network_traffic_allowed"] = hub_to_vitual_network_traffic_allowed __props__["internet_security_enabled"] = internet_security_enabled __props__["name"] = name __props__["remote_virtual_network_id"] = remote_virtual_network_id __props__["virtual_hub_id"] = virtual_hub_id __props__["vitual_network_to_hub_gateways_traffic_allowed"] = vitual_network_to_hub_gateways_traffic_allowed return VirtualHubConnection(resource_name, opts=opts, __props__=__props__) 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
61.762238
292
0.733809
import json import warnings import pulumi import pulumi.runtime from typing import Union from .. import utilities, tables class VirtualHubConnection(pulumi.CustomResource): hub_to_vitual_network_traffic_allowed: pulumi.Output[bool] internet_security_enabled: pulumi.Output[bool] name: pulumi.Output[str] remote_virtual_network_id: pulumi.Output[str] virtual_hub_id: pulumi.Output[str] vitual_network_to_hub_gateways_traffic_allowed: pulumi.Output[bool] def __init__(__self__, resource_name, opts=None, hub_to_vitual_network_traffic_allowed=None, internet_security_enabled=None, name=None, remote_virtual_network_id=None, virtual_hub_id=None, vitual_network_to_hub_gateways_traffic_allowed=None, __props__=None, __name__=None, __opts__=None): if __name__ is not None: warnings.warn("explicit use of __name__ is deprecated", DeprecationWarning) resource_name = __name__ if __opts__ is not None: warnings.warn("explicit use of __opts__ is deprecated, use 'opts' instead", DeprecationWarning) opts = __opts__ if opts is None: opts = pulumi.ResourceOptions() if not isinstance(opts, pulumi.ResourceOptions): raise TypeError('Expected resource options to be a ResourceOptions instance') if opts.version is None: opts.version = utilities.get_version() if opts.id is None: if __props__ is not None: raise TypeError('__props__ is only valid when passed in combination with a valid opts.id to get an existing resource') __props__ = dict() __props__['hub_to_vitual_network_traffic_allowed'] = hub_to_vitual_network_traffic_allowed __props__['internet_security_enabled'] = internet_security_enabled __props__['name'] = name if remote_virtual_network_id is None: raise TypeError("Missing required property 'remote_virtual_network_id'") __props__['remote_virtual_network_id'] = remote_virtual_network_id if virtual_hub_id is None: raise TypeError("Missing required property 'virtual_hub_id'") __props__['virtual_hub_id'] = virtual_hub_id __props__['vitual_network_to_hub_gateways_traffic_allowed'] = vitual_network_to_hub_gateways_traffic_allowed super(VirtualHubConnection, __self__).__init__( 'azure:network/virtualHubConnection:VirtualHubConnection', resource_name, __props__, opts) @staticmethod def get(resource_name, id, opts=None, hub_to_vitual_network_traffic_allowed=None, internet_security_enabled=None, name=None, remote_virtual_network_id=None, virtual_hub_id=None, vitual_network_to_hub_gateways_traffic_allowed=None): opts = pulumi.ResourceOptions.merge(opts, pulumi.ResourceOptions(id=id)) __props__ = dict() __props__["hub_to_vitual_network_traffic_allowed"] = hub_to_vitual_network_traffic_allowed __props__["internet_security_enabled"] = internet_security_enabled __props__["name"] = name __props__["remote_virtual_network_id"] = remote_virtual_network_id __props__["virtual_hub_id"] = virtual_hub_id __props__["vitual_network_to_hub_gateways_traffic_allowed"] = vitual_network_to_hub_gateways_traffic_allowed return VirtualHubConnection(resource_name, opts=opts, __props__=__props__) 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
true
true
1c341e35933bcdb0812891953bdb7c49dedc7b37
578
py
Python
text/color/_rgb/_rgba.py
jedhsu/text
8525b602d304ac571a629104c48703443244545c
[ "Apache-2.0" ]
null
null
null
text/color/_rgb/_rgba.py
jedhsu/text
8525b602d304ac571a629104c48703443244545c
[ "Apache-2.0" ]
null
null
null
text/color/_rgb/_rgba.py
jedhsu/text
8525b602d304ac571a629104c48703443244545c
[ "Apache-2.0" ]
null
null
null
""" *Rgba* The color spectral measure using the RGBA system. """ from dataclasses import dataclass # from wich.measure.spectral import Spectral from .red import Red from .green import Green from .blue import Blue __all__ = [ "Rgba", ] @dataclass class Rgba( # Spectral, # GraphicalColor, ): red: Red green: Green blue: Blue @classmethod def create( cls, red: int, green: int, blue: int, ): return cls( Red(red), Green(green), Blue(blue), )
12.844444
51
0.550173
from dataclasses import dataclass from .red import Red from .green import Green from .blue import Blue __all__ = [ "Rgba", ] @dataclass class Rgba( ): red: Red green: Green blue: Blue @classmethod def create( cls, red: int, green: int, blue: int, ): return cls( Red(red), Green(green), Blue(blue), )
true
true
1c341e9953b24c6332cd370640c276a8aedd7d2e
1,687
py
Python
kontenjan.py
abkkl/me
a0ba942d02c5d503f977c2db62c21e3083c8e5cb
[ "Apache-2.0" ]
null
null
null
kontenjan.py
abkkl/me
a0ba942d02c5d503f977c2db62c21e3083c8e5cb
[ "Apache-2.0" ]
null
null
null
kontenjan.py
abkkl/me
a0ba942d02c5d503f977c2db62c21e3083c8e5cb
[ "Apache-2.0" ]
null
null
null
import mechanize from bs4 import BeautifulSoup import openpyxl import time import ctypes wb = openpyxl.Workbook() ws = wb.active print("Course Capacity Checker Created by Ahmet Bakkal 2022\n") ders = input("Course Code (i.e. END458E):").upper() crn = input("CRN Number (i.e. 21268):") def itukont(ders,crn): browser = mechanize.Browser() browser.set_handle_robots(False) browser.open("https://www.sis.itu.edu.tr/TR/ogrenci/ders-programi/ders-programi.php?seviye=LS") browser.select_form(nr=0) browser.form["derskodu"]=[ders[:3]] browser.submit() soup_table=BeautifulSoup(browser.response().read(),'html.parser') table = soup_table.find('table') a = 0 c = 0 for i in table.find_all('tr'): b = 0 c += 1 if c == 1 or c == 2: pass else: a += 1 for j in i.find_all('td'): b += 1 if c == 1 or c == 2: pass else: ws.cell(column=b, row=a).value = j.get_text(strip=True) for row in ws.rows: if row[0].value == crn: for cell in row: if int(row[9].value) > int(row[10].value): check = "Course is available" ctypes.windll.user32.MessageBoxW(0,"Course is available, run forest run :)", "Attention from Course Capacity Checker",0x40000) print(check) break else: check = "Course is full" print(check) break while True: itukont(ders,crn) time.sleep(5)
27.209677
147
0.5246
import mechanize from bs4 import BeautifulSoup import openpyxl import time import ctypes wb = openpyxl.Workbook() ws = wb.active print("Course Capacity Checker Created by Ahmet Bakkal 2022\n") ders = input("Course Code (i.e. END458E):").upper() crn = input("CRN Number (i.e. 21268):") def itukont(ders,crn): browser = mechanize.Browser() browser.set_handle_robots(False) browser.open("https://www.sis.itu.edu.tr/TR/ogrenci/ders-programi/ders-programi.php?seviye=LS") browser.select_form(nr=0) browser.form["derskodu"]=[ders[:3]] browser.submit() soup_table=BeautifulSoup(browser.response().read(),'html.parser') table = soup_table.find('table') a = 0 c = 0 for i in table.find_all('tr'): b = 0 c += 1 if c == 1 or c == 2: pass else: a += 1 for j in i.find_all('td'): b += 1 if c == 1 or c == 2: pass else: ws.cell(column=b, row=a).value = j.get_text(strip=True) for row in ws.rows: if row[0].value == crn: for cell in row: if int(row[9].value) > int(row[10].value): check = "Course is available" ctypes.windll.user32.MessageBoxW(0,"Course is available, run forest run :)", "Attention from Course Capacity Checker",0x40000) print(check) break else: check = "Course is full" print(check) break while True: itukont(ders,crn) time.sleep(5)
true
true
1c341ec043178dd20596c680ef1491f1e21f2686
12,564
py
Python
python/ccxt/async_support/base/exchange.py
1Konto/ccxt
817eace045a87b441f009c2303827b3df5e1f339
[ "MIT" ]
null
null
null
python/ccxt/async_support/base/exchange.py
1Konto/ccxt
817eace045a87b441f009c2303827b3df5e1f339
[ "MIT" ]
1
2019-09-19T06:38:21.000Z
2019-09-19T06:38:21.000Z
python/ccxt/async_support/base/exchange.py
1Konto/ccxt
817eace045a87b441f009c2303827b3df5e1f339
[ "MIT" ]
null
null
null
# -*- coding: utf-8 -*- # ----------------------------------------------------------------------------- __version__ = '1.18.1165' # ----------------------------------------------------------------------------- import asyncio import concurrent import socket import time import math import random import certifi import aiohttp import ssl import sys import yarl # ----------------------------------------------------------------------------- from ccxt.async_support.base.throttle import throttle # ----------------------------------------------------------------------------- from ccxt.base.errors import ExchangeError from ccxt.base.errors import ExchangeNotAvailable from ccxt.base.errors import RequestTimeout from ccxt.base.errors import NotSupported # ----------------------------------------------------------------------------- from ccxt.base.exchange import Exchange as BaseExchange # ----------------------------------------------------------------------------- __all__ = [ 'BaseExchange', 'Exchange', ] # ----------------------------------------------------------------------------- class Exchange(BaseExchange): def __init__(self, config={}): if 'asyncio_loop' in config: self.asyncio_loop = config['asyncio_loop'] self.asyncio_loop = self.asyncio_loop or asyncio.get_event_loop() self.aiohttp_trust_env = config.get('aiohttp_trust_env', self.aiohttp_trust_env) self.verify = config.get('verify', self.verify) self.own_session = 'session' not in config self.cafile = config.get('cafile', certifi.where()) self.open() super(Exchange, self).__init__(config) self.init_rest_rate_limiter() def init_rest_rate_limiter(self): self.throttle = throttle(self.extend({ 'loop': self.asyncio_loop, }, self.tokenBucket)) def __del__(self): if self.session is not None: self.logger.warning(self.id + " requires to release all resources with an explicit call to the .close() coroutine. If you are using the exchange instance with async coroutines, add exchange.close() to your code into a place when you're done with the exchange and don't need the exchange instance anymore (at the end of your async coroutine).") if sys.version_info >= (3, 5): async def __aenter__(self): self.open() return self async def __aexit__(self, exc_type, exc, tb): await self.close() def open(self): if self.own_session and self.session is None: # Create our SSL context object with our CA cert file context = ssl.create_default_context(cafile=self.cafile) if self.verify else self.verify # Pass this SSL context to aiohttp and create a TCPConnector connector = aiohttp.TCPConnector(ssl=context, loop=self.asyncio_loop) self.session = aiohttp.ClientSession(loop=self.asyncio_loop, connector=connector, trust_env=self.aiohttp_trust_env) async def close(self): if self.session is not None: if self.own_session: await self.session.close() self.session = None async def wait_for_token(self): while self.rateLimitTokens <= 1: # if self.verbose: # print('Waiting for tokens: Exchange: {0}'.format(self.id)) self.add_new_tokens() seconds_delays = [0.001, 0.005, 0.022, 0.106, 0.5] delay = random.choice(seconds_delays) await asyncio.sleep(delay) self.rateLimitTokens -= 1 def add_new_tokens(self): # if self.verbose: # print('Adding new tokens: Exchange: {0}'.format(self.id)) now = time.monotonic() time_since_update = now - self.rateLimitUpdateTime new_tokens = math.floor((0.8 * 1000.0 * time_since_update) / self.rateLimit) if new_tokens > 1: self.rateLimitTokens = min(self.rateLimitTokens + new_tokens, self.rateLimitMaxTokens) self.rateLimitUpdateTime = now async def fetch2(self, path, api='public', method='GET', params={}, headers=None, body=None): """A better wrapper over request for deferred signing""" if self.enableRateLimit: await self.throttle() self.lastRestRequestTimestamp = self.milliseconds() request = self.sign(path, api, method, params, headers, body) return await self.fetch(request['url'], request['method'], request['headers'], request['body']) async def fetch(self, url, method='GET', headers=None, body=None): """Perform a HTTP request and return decoded JSON data""" request_headers = self.prepare_request_headers(headers) url = self.proxy + url if self.verbose: print("\nRequest:", method, url, headers, body) self.logger.debug("%s %s, Request: %s %s", method, url, headers, body) request_body = body encoded_body = body.encode() if body else None session_method = getattr(self.session, method.lower()) http_response = None http_status_code = None http_status_text = None json_response = None try: async with session_method(yarl.URL(url, encoded=True), data=encoded_body, headers=request_headers, timeout=(self.timeout / 1000), proxy=self.aiohttp_proxy) as response: http_response = await response.text() http_status_code = response.status http_status_text = response.reason json_response = self.parse_json(http_response) headers = response.headers if self.enableLastHttpResponse: self.last_http_response = http_response if self.enableLastResponseHeaders: self.last_response_headers = headers if self.enableLastJsonResponse: self.last_json_response = json_response if self.verbose: print("\nResponse:", method, url, http_status_code, headers, http_response) self.logger.debug("%s %s, Response: %s %s %s", method, url, http_status_code, headers, http_response) except socket.gaierror as e: raise ExchangeNotAvailable(method + ' ' + url) except concurrent.futures._base.TimeoutError as e: raise RequestTimeout(method + ' ' + url) except aiohttp.client_exceptions.ClientConnectionError as e: raise ExchangeNotAvailable(method + ' ' + url) except aiohttp.client_exceptions.ClientError as e: # base exception class raise ExchangeError(method + ' ' + url) self.handle_errors(http_status_code, http_status_text, url, method, headers, http_response, json_response, request_headers, request_body) self.handle_rest_errors(http_status_code, http_status_text, http_response, url, method) self.handle_rest_response(http_response, json_response, url, method) if json_response is not None: return json_response return http_response async def load_markets(self, reload=False, params={}): if not reload: if self.markets: if not self.markets_by_id: return self.set_markets(self.markets) return self.markets currencies = None if self.has['fetchCurrencies']: currencies = await self.fetch_currencies() markets = await self.fetch_markets(params) return self.set_markets(markets, currencies) async def fetch_fees(self): trading = {} funding = {} if self.has['fetchTradingFees']: trading = await self.fetch_trading_fees() if self.has['fetchFundingFees']: funding = await self.fetch_funding_fees() return { 'trading': trading, 'funding': funding, } async def load_fees(self, reload=False): if not reload: if self.loaded_fees != Exchange.loaded_fees: return self.loaded_fees self.loaded_fees = self.deep_extend(self.loaded_fees, await self.fetch_fees()) return self.loaded_fees async def fetch_markets(self, params={}): # markets are returned as a list # currencies are returned as a dict # this is for historical reasons # and may be changed for consistency later return self.to_array(self.markets) async def fetch_currencies(self, params={}): # markets are returned as a list # currencies are returned as a dict # this is for historical reasons # and may be changed for consistency later return self.currencies async def fetch_status(self, params={}): if self.has['fetchTime']: updated = await self.fetch_time(params) self.status['updated'] = updated return self.status async def fetch_order_status(self, id, symbol=None, params={}): order = await self.fetch_order(id, symbol, params) return order['status'] async def fetch_partial_balance(self, part, params={}): balance = await self.fetch_balance(params) return balance[part] async def fetch_l2_order_book(self, symbol, limit=None, params={}): orderbook = await self.fetch_order_book(symbol, limit, params) return self.extend(orderbook, { 'bids': self.sort_by(self.aggregate(orderbook['bids']), 0, True), 'asks': self.sort_by(self.aggregate(orderbook['asks']), 0), }) async def perform_order_book_request(self, market, limit=None, params={}): raise NotSupported(self.id + ' performOrderBookRequest not supported yet') async def fetch_order_book(self, symbol, limit=None, params={}): await self.load_markets() market = self.market(symbol) orderbook = await self.perform_order_book_request(market, limit, params) return self.parse_order_book(orderbook, market, limit, params) async def fetch_ohlcv(self, symbol, timeframe='1m', since=None, limit=None, params={}): if not self.has['fetchTrades']: raise NotSupported('fetch_ohlcv() not implemented yet') await self.load_markets() trades = await self.fetch_trades(symbol, since, limit, params) return self.build_ohlcv(trades, timeframe, since, limit) async def fetchOHLCV(self, symbol, timeframe='1m', since=None, limit=None, params={}): return await self.fetch_ohlcv(symbol, timeframe, since, limit, params) async def fetch_full_tickers(self, symbols=None, params={}): return await self.fetch_tickers(symbols, params) async def edit_order(self, id, symbol, *args): if not self.enableRateLimit: raise ExchangeError('updateOrder() requires enableRateLimit = true') await self.cancel_order(id, symbol) return await self.create_order(symbol, *args) async def fetch_trading_fees(self, params={}): raise NotSupported('fetch_trading_fees() not supported yet') async def fetch_trading_fee(self, symbol, params={}): if not self.has['fetchTradingFees']: raise NotSupported('fetch_trading_fee() not supported yet') return await self.fetch_trading_fees(params) async def load_trading_limits(self, symbols=None, reload=False, params={}): if self.has['fetchTradingLimits']: if reload or not('limitsLoaded' in list(self.options.keys())): response = await self.fetch_trading_limits(symbols) for i in range(0, len(symbols)): symbol = symbols[i] self.markets[symbol] = self.deep_extend(self.markets[symbol], response[symbol]) self.options['limitsLoaded'] = self.milliseconds() return self.markets async def load_accounts(self, reload=False, params={}): if reload: self.accounts = await self.fetch_accounts(params) else: if self.accounts: return self.accounts else: self.accounts = await self.fetch_accounts(params) self.accountsById = self.index_by(self.accounts, 'id') return self.accounts async def fetch_ticker(self, symbol, params={}): raise NotSupported('fetch_ticker() not supported yet')
41.740864
355
0.610236
__version__ = '1.18.1165' import asyncio import concurrent import socket import time import math import random import certifi import aiohttp import ssl import sys import yarl from ccxt.async_support.base.throttle import throttle from ccxt.base.errors import ExchangeError from ccxt.base.errors import ExchangeNotAvailable from ccxt.base.errors import RequestTimeout from ccxt.base.errors import NotSupported from ccxt.base.exchange import Exchange as BaseExchange __all__ = [ 'BaseExchange', 'Exchange', ] class Exchange(BaseExchange): def __init__(self, config={}): if 'asyncio_loop' in config: self.asyncio_loop = config['asyncio_loop'] self.asyncio_loop = self.asyncio_loop or asyncio.get_event_loop() self.aiohttp_trust_env = config.get('aiohttp_trust_env', self.aiohttp_trust_env) self.verify = config.get('verify', self.verify) self.own_session = 'session' not in config self.cafile = config.get('cafile', certifi.where()) self.open() super(Exchange, self).__init__(config) self.init_rest_rate_limiter() def init_rest_rate_limiter(self): self.throttle = throttle(self.extend({ 'loop': self.asyncio_loop, }, self.tokenBucket)) def __del__(self): if self.session is not None: self.logger.warning(self.id + " requires to release all resources with an explicit call to the .close() coroutine. If you are using the exchange instance with async coroutines, add exchange.close() to your code into a place when you're done with the exchange and don't need the exchange instance anymore (at the end of your async coroutine).") if sys.version_info >= (3, 5): async def __aenter__(self): self.open() return self async def __aexit__(self, exc_type, exc, tb): await self.close() def open(self): if self.own_session and self.session is None: context = ssl.create_default_context(cafile=self.cafile) if self.verify else self.verify connector = aiohttp.TCPConnector(ssl=context, loop=self.asyncio_loop) self.session = aiohttp.ClientSession(loop=self.asyncio_loop, connector=connector, trust_env=self.aiohttp_trust_env) async def close(self): if self.session is not None: if self.own_session: await self.session.close() self.session = None async def wait_for_token(self): while self.rateLimitTokens <= 1: self.add_new_tokens() seconds_delays = [0.001, 0.005, 0.022, 0.106, 0.5] delay = random.choice(seconds_delays) await asyncio.sleep(delay) self.rateLimitTokens -= 1 def add_new_tokens(self): now = time.monotonic() time_since_update = now - self.rateLimitUpdateTime new_tokens = math.floor((0.8 * 1000.0 * time_since_update) / self.rateLimit) if new_tokens > 1: self.rateLimitTokens = min(self.rateLimitTokens + new_tokens, self.rateLimitMaxTokens) self.rateLimitUpdateTime = now async def fetch2(self, path, api='public', method='GET', params={}, headers=None, body=None): if self.enableRateLimit: await self.throttle() self.lastRestRequestTimestamp = self.milliseconds() request = self.sign(path, api, method, params, headers, body) return await self.fetch(request['url'], request['method'], request['headers'], request['body']) async def fetch(self, url, method='GET', headers=None, body=None): request_headers = self.prepare_request_headers(headers) url = self.proxy + url if self.verbose: print("\nRequest:", method, url, headers, body) self.logger.debug("%s %s, Request: %s %s", method, url, headers, body) request_body = body encoded_body = body.encode() if body else None session_method = getattr(self.session, method.lower()) http_response = None http_status_code = None http_status_text = None json_response = None try: async with session_method(yarl.URL(url, encoded=True), data=encoded_body, headers=request_headers, timeout=(self.timeout / 1000), proxy=self.aiohttp_proxy) as response: http_response = await response.text() http_status_code = response.status http_status_text = response.reason json_response = self.parse_json(http_response) headers = response.headers if self.enableLastHttpResponse: self.last_http_response = http_response if self.enableLastResponseHeaders: self.last_response_headers = headers if self.enableLastJsonResponse: self.last_json_response = json_response if self.verbose: print("\nResponse:", method, url, http_status_code, headers, http_response) self.logger.debug("%s %s, Response: %s %s %s", method, url, http_status_code, headers, http_response) except socket.gaierror as e: raise ExchangeNotAvailable(method + ' ' + url) except concurrent.futures._base.TimeoutError as e: raise RequestTimeout(method + ' ' + url) except aiohttp.client_exceptions.ClientConnectionError as e: raise ExchangeNotAvailable(method + ' ' + url) except aiohttp.client_exceptions.ClientError as e: raise ExchangeError(method + ' ' + url) self.handle_errors(http_status_code, http_status_text, url, method, headers, http_response, json_response, request_headers, request_body) self.handle_rest_errors(http_status_code, http_status_text, http_response, url, method) self.handle_rest_response(http_response, json_response, url, method) if json_response is not None: return json_response return http_response async def load_markets(self, reload=False, params={}): if not reload: if self.markets: if not self.markets_by_id: return self.set_markets(self.markets) return self.markets currencies = None if self.has['fetchCurrencies']: currencies = await self.fetch_currencies() markets = await self.fetch_markets(params) return self.set_markets(markets, currencies) async def fetch_fees(self): trading = {} funding = {} if self.has['fetchTradingFees']: trading = await self.fetch_trading_fees() if self.has['fetchFundingFees']: funding = await self.fetch_funding_fees() return { 'trading': trading, 'funding': funding, } async def load_fees(self, reload=False): if not reload: if self.loaded_fees != Exchange.loaded_fees: return self.loaded_fees self.loaded_fees = self.deep_extend(self.loaded_fees, await self.fetch_fees()) return self.loaded_fees async def fetch_markets(self, params={}): return self.to_array(self.markets) async def fetch_currencies(self, params={}): return self.currencies async def fetch_status(self, params={}): if self.has['fetchTime']: updated = await self.fetch_time(params) self.status['updated'] = updated return self.status async def fetch_order_status(self, id, symbol=None, params={}): order = await self.fetch_order(id, symbol, params) return order['status'] async def fetch_partial_balance(self, part, params={}): balance = await self.fetch_balance(params) return balance[part] async def fetch_l2_order_book(self, symbol, limit=None, params={}): orderbook = await self.fetch_order_book(symbol, limit, params) return self.extend(orderbook, { 'bids': self.sort_by(self.aggregate(orderbook['bids']), 0, True), 'asks': self.sort_by(self.aggregate(orderbook['asks']), 0), }) async def perform_order_book_request(self, market, limit=None, params={}): raise NotSupported(self.id + ' performOrderBookRequest not supported yet') async def fetch_order_book(self, symbol, limit=None, params={}): await self.load_markets() market = self.market(symbol) orderbook = await self.perform_order_book_request(market, limit, params) return self.parse_order_book(orderbook, market, limit, params) async def fetch_ohlcv(self, symbol, timeframe='1m', since=None, limit=None, params={}): if not self.has['fetchTrades']: raise NotSupported('fetch_ohlcv() not implemented yet') await self.load_markets() trades = await self.fetch_trades(symbol, since, limit, params) return self.build_ohlcv(trades, timeframe, since, limit) async def fetchOHLCV(self, symbol, timeframe='1m', since=None, limit=None, params={}): return await self.fetch_ohlcv(symbol, timeframe, since, limit, params) async def fetch_full_tickers(self, symbols=None, params={}): return await self.fetch_tickers(symbols, params) async def edit_order(self, id, symbol, *args): if not self.enableRateLimit: raise ExchangeError('updateOrder() requires enableRateLimit = true') await self.cancel_order(id, symbol) return await self.create_order(symbol, *args) async def fetch_trading_fees(self, params={}): raise NotSupported('fetch_trading_fees() not supported yet') async def fetch_trading_fee(self, symbol, params={}): if not self.has['fetchTradingFees']: raise NotSupported('fetch_trading_fee() not supported yet') return await self.fetch_trading_fees(params) async def load_trading_limits(self, symbols=None, reload=False, params={}): if self.has['fetchTradingLimits']: if reload or not('limitsLoaded' in list(self.options.keys())): response = await self.fetch_trading_limits(symbols) for i in range(0, len(symbols)): symbol = symbols[i] self.markets[symbol] = self.deep_extend(self.markets[symbol], response[symbol]) self.options['limitsLoaded'] = self.milliseconds() return self.markets async def load_accounts(self, reload=False, params={}): if reload: self.accounts = await self.fetch_accounts(params) else: if self.accounts: return self.accounts else: self.accounts = await self.fetch_accounts(params) self.accountsById = self.index_by(self.accounts, 'id') return self.accounts async def fetch_ticker(self, symbol, params={}): raise NotSupported('fetch_ticker() not supported yet')
true
true
1c341f0ecec81fd94df513cec1e8797119db1d81
195
py
Python
setup.py
AdamBlomfield/mod_4_project
dad5775535d50ad4d3d9a8cafdc638572d978ca3
[ "RSA-MD" ]
2
2019-06-18T12:57:42.000Z
2019-07-10T15:28:48.000Z
setup.py
AdamBlomfield/mod_4_project
dad5775535d50ad4d3d9a8cafdc638572d978ca3
[ "RSA-MD" ]
null
null
null
setup.py
AdamBlomfield/mod_4_project
dad5775535d50ad4d3d9a8cafdc638572d978ca3
[ "RSA-MD" ]
null
null
null
from setuptools import find_packages, setup setup( name='src', packages=find_packages(), version='0.1.0', description='mod_4_final_project', author='far', #license='', )
17.727273
43
0.651282
from setuptools import find_packages, setup setup( name='src', packages=find_packages(), version='0.1.0', description='mod_4_final_project', author='far', )
true
true
1c341fc8a17cbd253c660ba3cf5f1ac0c9f71bb8
16,537
py
Python
sans_tools/NotesAppFe.py
Developernation/PythonProjects
d682960d060cb1daede3f2f8e814a5aea05c0ec6
[ "BSD-3-Clause" ]
11
2022-02-12T23:50:27.000Z
2022-03-04T01:24:14.000Z
sans_tools/NotesAppFe.py
Developernation/PythonProjects
d682960d060cb1daede3f2f8e814a5aea05c0ec6
[ "BSD-3-Clause" ]
null
null
null
sans_tools/NotesAppFe.py
Developernation/PythonProjects
d682960d060cb1daede3f2f8e814a5aea05c0ec6
[ "BSD-3-Clause" ]
1
2022-03-27T22:28:37.000Z
2022-03-27T22:28:37.000Z
from tkinter.filedialog import askopenfilename from tkinter.messagebox import showinfo from NotesApp import SansNotesApp as snp from datetime import datetime from tkinter import ttk import tkinter as tk import pandas as pd import os pd.set_option('display.max_rows', None) #database connection notes_db = snp() notes_db.database_name = 'sans' notes_db.db_connect_and_cursor() db_list = notes_db.show_databases() notes_db.create_table('default_sans_table') db_tables = notes_db.show_tables() #first frame def build_frame(label_text_info,box_width,master_frame,label_width=10): frame1 = tk.Frame(master=master_frame,relief=border_effects['flat'],width=100, height=10) text_box1 = tk.Entry(master=frame1, width=box_width, borderwidth=4) label1 = tk.Label(master=frame1, text=label_text_info,width=label_width) label1.pack(side='left') text_box1.pack(side='left') frame1.pack(fill=tk.X) return text_box1 #------------------------------------------------------------------------- border_effects = { "flat": tk.FLAT, "sunken": tk.SUNKEN, "raised": tk.RAISED, "groove": tk.GROOVE, "ridge": tk.RIDGE, } min_width, min_height = 300,400 label_text = ['Subject:','Topic:','Book:','Page:','Notes:'] window = tk.Tk() tabControl = ttk.Notebook(window) window.minsize(min_width, min_height) window.title('SANS NOTES APP') #setting defaults for table list clickedA = tk.StringVar() clickedA.set(db_tables[0]) clickedB = tk.StringVar() clickedB.set(db_tables[0]) clickedC = tk.StringVar() clickedC.set(db_tables[0]) ######################################################## #################### Add Data ########################## ######################################################## super_frame_tab1 = ttk.Frame(master=window,relief=border_effects['flat']) drop_down_frameA = tk.Frame(master=super_frame_tab1,relief=border_effects['flat'],width=50, height=10) drop_down_labelA = tk.Label( drop_down_frameA , text = "Select Table:" ) drop_down_labelA.pack(side='left') # Create Dropdown menu dropA = tk.OptionMenu(drop_down_frameA , clickedA, *db_tables) dropA.pack(side='left') drop_down_frameA.pack(fill=tk.X) frm0 = build_frame(label_text[0],10,super_frame_tab1) frm1 = build_frame(label_text[1],40,super_frame_tab1) frm2 = build_frame(label_text[2],5,super_frame_tab1) frm3 = build_frame(label_text[3],5,super_frame_tab1) frame3 = tk.Frame(master=super_frame_tab1,relief=border_effects['flat'],width=50, height=10) inputtxt = tk.Text(master= frame3, height = 5, width = 52,borderwidth=4,relief=border_effects['sunken']) label2 = tk.Label(master=frame3, text=label_text[4],width=10) label2.pack(side='left') inputtxt.pack(side='left') frame3.pack(fill=tk.X) def write_dataA(): input_vals = { 'table': clickedA.get().strip(), 'subject':frm0.get().strip(), 'topic':frm1.get().strip(), 'book':frm2.get().strip(), 'page':frm3.get().strip(), 'notes':inputtxt.get("1.0","end-1c").strip(), } notes_db.insert_values( input_vals['table'], input_vals['subject'], input_vals['topic'], input_vals['book'], input_vals['page'], input_vals['notes'] ) return input_vals def add_opt(): dropA['menu'].add_command(label=frm0_tb3.get(), command=tk._setit(clickedA, frm0_tb3.get())) dropB['menu'].add_command(label=frm0_tb3.get(), command=tk._setit(clickedB, frm0_tb3.get())) dropC['menu'].add_command(label=frm0_tb3.get(), command=tk._setit(clickedC, frm0_tb3.get())) global db_tables db_tables.append(frm0_tb3.get()) def create_table(): notes_db.create_table(frm0_tb3.get().strip()) add_opt() return True def remove_item(): r_index1=dropB['menu'].index(frm0_tb3.get()) dropB['menu'].delete(r_index1) clickedB.set(dropB['menu'].entrycget(0,"label")) # select the first one r_index2=dropA['menu'].index(frm0_tb3.get()) dropA['menu'].delete(r_index2) clickedA.set(dropB['menu'].entrycget(0,"label")) # select the first one r_index3=dropC['menu'].index(frm0_tb3.get()) dropC['menu'].delete(r_index3) clickedC.set(dropC['menu'].entrycget(0,"label")) # select the first one return True def delete_table(): notes_db.drop_table(frm0_tb3.get().strip()) remove_item() return True frame5 = tk.Frame(master=super_frame_tab1,relief=border_effects['flat'],width=100, height=10) label_opt = tk.Label(master=frame5, text='Options',width=10) Add_Button = tk.Button(master=frame5, height = 1, width = 10, text ="Add Data", relief=tk.RAISED, fg = "blue", command = lambda:write_dataA() ) frame5.pack(fill=tk.X) label_opt.pack(side='left') Add_Button.pack(side='left') tabControl.add(super_frame_tab1,text='Add Data') ############################################################# ######################## SEARCH DATA TAB #################### ############################################################# def show_search_data(): Output.delete('1.0', tk.END) global show_vals show_vals = { 'table': clickedB.get(), 'subject':frm0_tb2.get(), 'topic':frm1_tb2.get(), 'book':frm2_tb2.get(), 'page':frm3_tb2.get(), } global search_data search_data = notes_db.search_data( show_vals['table'], show_vals['subject'], show_vals['topic'], show_vals['book'], show_vals['page'], strict_search = False ) Output.insert(tk.END,search_data) def show_all_table_data(): Output.delete('1.0', tk.END) global search_data search_data = notes_db.show_table_data(clickedB.get()) Output.insert(tk.END,search_data) def show_all_ingest_columns(): Output_tb4.delete('1.0', tk.END) col_data = None if filename.endswith('xlsx'): col_data = list(pd.read_excel(filename).columns) else: col_data = list(pd.read_csv(filename).columns) Output_tb4.insert(tk.END,""" *********Directions****** 1) Map the columns in your file to their respective column in the table schema by entering them in the spaces above. 2) If you do not want to map a specific column from you file you can leave the entry blank. Below are the columns in your file:\n ******************** Ingest Data Column Names ******************* \n\t{} ***************************************************************** """.format('\n\t'.join(col_data))) def delete_data(): notes_db.delete_data( table_name=clickedB.get().strip(), subject=frm0_tb2.get().strip(), topic=frm1_tb2.get().strip(), book=frm2_tb2.get().strip(), page=frm3_tb2.get().strip(), ) show_search_data() def save_to_excel(): save_location = f"{os.path.join(os.path.expanduser('~'),'Downloads','search_data' + datetime.today().strftime('%y%m%d_%H%M%S'))}.xlsx" search_data.sort_values(by='topic').reset_index(drop=True).to_excel( save_location ) showinfo( title='File Saved', message="File has been saved to:\n{}".format(save_location) ) super_frame_tab2 = ttk.Frame(master=window,relief=border_effects['flat']) drop_down_frameB = tk.Frame(master=super_frame_tab2,relief=border_effects['flat'],width=50, height=10) drop_down_labelB = tk.Label( drop_down_frameB , text = "Select Table:" ) drop_down_labelB.pack(side='left') # Create Dropdown menu dropB = tk.OptionMenu(drop_down_frameB , clickedB, *db_tables) dropB.pack(side='left') drop_down_frameB.pack(fill=tk.X) frm0_tb2 = build_frame(label_text[0],10,super_frame_tab2) frm1_tb2 = build_frame(label_text[1],40,super_frame_tab2) frm2_tb2 = build_frame(label_text[2],5,super_frame_tab2) frm3_tb2 = build_frame(label_text[3],5,super_frame_tab2) frame0a_tb2 = tk.Frame(master=super_frame_tab2,relief=border_effects['flat'],width=100, height=10) label_opt2 = tk.Label(master=frame0a_tb2, text='Options:',width=10) Show_Search_Button = tk.Button(master=frame0a_tb2, height = 1, width = 15, text ="Show Search Data", relief=tk.RIDGE, fg = "blue", command = lambda : show_search_data() ) Search_All_Data = tk.Button(master=frame0a_tb2, height = 1, width = 15, text ="Show All Data", relief=tk.RIDGE, fg = "blue", command = lambda : show_all_table_data()) To_Excel_Button = tk.Button(master=frame0a_tb2, height = 1, width = 15, text ="Save Display To Excel", relief=tk.RIDGE, fg = "blue", command = lambda : save_to_excel()) Delete_Data_Button = tk.Button(master=frame0a_tb2, height = 1, width = 15, text ="Delete Displayed Data", relief=tk.RIDGE, fg = "red", command = lambda : delete_data()) label_opt2.pack(side='left') Show_Search_Button.pack(side='left') Search_All_Data.pack(side='left') To_Excel_Button.pack(side='left') Delete_Data_Button.pack(side='left') frame0a_tb2.pack(fill=tk.X) #------ frame0b_tb2 = tk.Frame(master=super_frame_tab2,relief=border_effects['flat'],width=100, height=10) ### Output = tk.Text(frame0b_tb2, height = 50, width = 150, bg = "light cyan") ### Output.pack(side='left') frame0b_tb2.pack(fill=tk.X) super_frame_tab2.pack(fill=tk.X) tabControl.add(super_frame_tab2,text='Search Data') tabControl.pack(expand=1, fill="both",side='right') ############################################################################ #################### Create / Delete Table ################################# ############################################################################ super_frame_tab3 = ttk.Frame(master=window,relief=border_effects['flat']) frm0_tb3 = build_frame('Table Nane:\n *Only letters \n & underscores*',20,super_frame_tab3) #------ frame0_tb3 = tk.Frame(master=super_frame_tab3,relief=border_effects['flat'],width=100, height=10) label_opt3 = tk.Label(master=frame0_tb3, text='Options:',width=10) Create_Button = tk.Button(master=frame0_tb3, height = 1, width = 15, text ="Create Table", relief=tk.RIDGE, padx=5, fg = "blue", command = create_table ) Delete_Table = tk.Button(master=frame0_tb3, height = 1, width = 10, text ="Delete Table", relief=tk.RIDGE, fg = "red", command = delete_table ) label_opt3.pack(side='left') Create_Button.pack(side='left') Delete_Table.pack(side='left') frame0_tb3.pack(fill=tk.X) tabControl.add(super_frame_tab3,text='Create Table') tabControl.pack(expand=1, fill="both",side='right') ############################################################################# ####################### Upload Excel File ################################### ############################################################################# super_frame_tab4 = ttk.Frame(master=window,relief=border_effects['flat']) directions_frame = tk.Frame(master=super_frame_tab4,relief=border_effects['flat'],width=70, height=50) directions_text = """" ********** File Upload Directions ********** 1) Select a table to upload data or create one in the Create Table tab. 2) Select your file by using the Ingest Data button below 3) Click Show Columns to display the availble columns for mapping to the table schema columns 4) Enter the columns from your file that you would like to map to table schema columns in section below 5) Click the Upload Data button """ directions_label = tk.Label(master=directions_frame, text=directions_text ,width=70) directions_label.pack(side='left') directions_frame.pack(fill=tk.X) drop_down_frameC = tk.Frame(master=super_frame_tab4,relief=border_effects['flat'],width=50, height=10) drop_down_labelC = tk.Label( drop_down_frameC , text = "Select Table:" ) drop_down_labelC.pack(side='left') # Create Dropdown menu dropC = tk.OptionMenu(drop_down_frameC , clickedC, *db_tables) dropC.pack(side='left') drop_down_frameC.pack(fill=tk.X) frm0_tb4 = build_frame(f'{label_text[0][:-1]} Column Mapping',10,super_frame_tab4,label_width=20) frm1_tb4 = build_frame(f'{label_text[1][:-1]} Column Mapping',10,super_frame_tab4,label_width=20) frm2_tb4 = build_frame(f'{label_text[2][:-1]} Column Mapping',10,super_frame_tab4,label_width=20) frm3_tb4 = build_frame(f'{label_text[3][:-1]} Column Mapping',10,super_frame_tab4,label_width=20) frm6_tb4 = build_frame('Notes Column Mapping',10,super_frame_tab4,label_width=20) def ingest_file_data(): #select file filetypes = ( ('CSV files', '*.csv'), ('Excel files', '*.xlsx') ) global filename filename = askopenfilename( title='Open files', initialdir='/', filetypes=filetypes) showinfo( title='Selected Files', message=f'You selected:\n {filename}' ) def check_len(str_): return str_ if len(str_) > 0 else None def upload_data(): Output_tb4.delete('1.0', tk.END) table = clickedC.get() subject = frm0_tb4.get() topic = frm1_tb4.get() book = frm2_tb4.get() page = frm3_tb4.get() notes = frm6_tb4.get() mapping_vals = { 'subject': check_len(subject), 'topic': check_len(topic), 'book': check_len(book), 'page': check_len(page), 'notes': check_len(notes), } notes_db.set_ingest_file( filename ) notes_db.rename_df_columns( topic_column=mapping_vals['topic'], subject_column=mapping_vals['subject'], page_column=mapping_vals['page'], notes_column=mapping_vals['notes'], book_column=mapping_vals['book'] ) cursor = notes_db.get_cursor() res = notes_db.build_insert_query( table, cursor, topic_column=mapping_vals['topic'], subject_column=mapping_vals['subject'], page_column=mapping_vals['page'], notes_column=mapping_vals['notes'], book_column=mapping_vals['book'] ) if res: showinfo( title='File Uploaded', message=f'{filename} was uploaded to {table}' ) else: showinfo( title='File Upload Failure', message="Please review input colums:\n{}".format(',\n'.join(icols)) ) frm4_tb4 = tk.Frame(master=super_frame_tab4,relief=border_effects['flat'],width=100, height=10) label_opt4a = tk.Label(master=frm4_tb4, text='Options:',width=10) Ingest_Button = tk.Button(master=frm4_tb4, height = 1, width = 15, text ="Ingest Data", relief=tk.RIDGE, padx=5, fg = "blue", command = ingest_file_data ) Show_Columns_Button = tk.Button(master=frm4_tb4, height = 1, width = 15, text ="Show Columns", relief=tk.RIDGE, padx=5, fg = "green", command = show_all_ingest_columns ) Upload_Data_Button = tk.Button(master=frm4_tb4, height = 1, width = 15, text ="Upload Data", relief=tk.RIDGE, padx=5, fg = "orange", command = upload_data ) frm5_tb4 = tk.Frame(master=super_frame_tab4,relief=border_effects['flat'],width=100, height=10) ### Output_tb4 = tk.Text(frm5_tb4, height = 40, width = 99, bg = "light green") label_opt4a.pack(side='left') Ingest_Button.pack(side='left') Show_Columns_Button.pack(side='left') Upload_Data_Button.pack(side='left') Output_tb4.pack(side='bottom') frm4_tb4.pack(fill=tk.X) frm5_tb4.pack(fill=tk.X) tabControl.add(super_frame_tab4,text='Upload CSV / Excel') tabControl.pack(expand=1, fill="both",side='right') ############################################################################## window.mainloop() notes_db.committ_and_close()
32.173152
138
0.600774
from tkinter.filedialog import askopenfilename from tkinter.messagebox import showinfo from NotesApp import SansNotesApp as snp from datetime import datetime from tkinter import ttk import tkinter as tk import pandas as pd import os pd.set_option('display.max_rows', None) notes_db = snp() notes_db.database_name = 'sans' notes_db.db_connect_and_cursor() db_list = notes_db.show_databases() notes_db.create_table('default_sans_table') db_tables = notes_db.show_tables() def build_frame(label_text_info,box_width,master_frame,label_width=10): frame1 = tk.Frame(master=master_frame,relief=border_effects['flat'],width=100, height=10) text_box1 = tk.Entry(master=frame1, width=box_width, borderwidth=4) label1 = tk.Label(master=frame1, text=label_text_info,width=label_width) label1.pack(side='left') text_box1.pack(side='left') frame1.pack(fill=tk.X) return text_box1 border_effects = { "flat": tk.FLAT, "sunken": tk.SUNKEN, "raised": tk.RAISED, "groove": tk.GROOVE, "ridge": tk.RIDGE, } min_width, min_height = 300,400 label_text = ['Subject:','Topic:','Book:','Page:','Notes:'] window = tk.Tk() tabControl = ttk.Notebook(window) window.minsize(min_width, min_height) window.title('SANS NOTES APP') clickedA = tk.StringVar() clickedA.set(db_tables[0]) clickedB = tk.StringVar() clickedB.set(db_tables[0]) clickedC = tk.StringVar() clickedC.set(db_tables[0])
true
true
1c3421c57b17d9a16190870d5ee5157487dc1ffc
5,474
py
Python
gluon/_compat.py
zhiyongwang/web2py
759616e537deb6148b8f32430e214142b4a65261
[ "BSD-3-Clause" ]
null
null
null
gluon/_compat.py
zhiyongwang/web2py
759616e537deb6148b8f32430e214142b4a65261
[ "BSD-3-Clause" ]
null
null
null
gluon/_compat.py
zhiyongwang/web2py
759616e537deb6148b8f32430e214142b4a65261
[ "BSD-3-Clause" ]
null
null
null
import sys import hashlib import os PY2 = sys.version_info[0] == 2 _identity = lambda x: x if PY2: import cPickle as pickle from cStringIO import StringIO import copy_reg as copyreg from HTMLParser import HTMLParser import urlparse from htmlentitydefs import entitydefs, name2codepoint import __builtin__ as builtin import thread import Cookie import urllib2 import Queue import ConfigParser as configparser from email.MIMEBase import MIMEBase from email.Header import Header from email import Encoders, Charset from email.MIMEMultipart import MIMEMultipart from email.MIMEText import MIMEText from email.Charset import add_charset, QP as charset_QP from urllib import FancyURLopener, urlencode, urlopen from urllib import quote as urllib_quote, unquote as urllib_unquote from string import maketrans from types import ClassType import cgi import cookielib reduce = reduce hashlib_md5 = hashlib.md5 iterkeys = lambda d: d.iterkeys() itervalues = lambda d: d.itervalues() iteritems = lambda d: d.iteritems() integer_types = (int, long) string_types = (str, unicode) text_type = unicode basestring = basestring xrange = xrange long = long unichr = unichr unicodeT = unicode def implements_bool(cls): cls.__nonzero__ = cls.__bool__ del cls.__bool__ return cls def to_bytes(obj, charset='utf-8', errors='strict'): if obj is None: return None if isinstance(obj, (bytes, bytearray, buffer)): return bytes(obj) if isinstance(obj, unicode): return obj.encode(charset, errors) raise TypeError('Expected bytes') def to_native(obj, charset='utf8', errors='strict'): if obj is None or isinstance(obj, str): return obj return obj.encode(charset, errors) def _local_html_escape(data, quote=False): s = cgi.escape(data, quote) return s.replace("'", "&#x27;") if quote else s else: import pickle from io import StringIO import copyreg from functools import reduce from html.parser import HTMLParser from http import cookies as Cookie from urllib import parse as urlparse from urllib import request as urllib2 from html.entities import entitydefs, name2codepoint import builtins as builtin import _thread as thread import configparser import queue as Queue from email.mime.base import MIMEBase from email.mime.multipart import MIMEMultipart from email.mime.text import MIMEText from email import encoders as Encoders from email.header import Header from email.charset import Charset, add_charset, QP as charset_QP from urllib.request import FancyURLopener, urlopen from urllib.parse import quote as urllib_quote, unquote as urllib_unquote, urlencode from http import cookiejar as cookielib import html hashlib_md5 = lambda s: hashlib.md5(bytes(s, 'utf8')) iterkeys = lambda d: iter(d.keys()) itervalues = lambda d: iter(d.values()) iteritems = lambda d: iter(d.items()) integer_types = (int,) string_types = (str,) text_type = str basestring = str xrange = range long = int unichr = chr unicodeT = str maketrans = str.maketrans ClassType = type implements_iterator = _identity implements_bool = _identity def to_bytes(obj, charset='utf-8', errors='strict'): if obj is None: return None if isinstance(obj, (bytes, bytearray, memoryview)): return bytes(obj) if isinstance(obj, str): return obj.encode(charset, errors) raise TypeError('Expected bytes') def to_native(obj, charset='utf8', errors='strict'): if obj is None or isinstance(obj, str): return obj return obj.decode(charset, errors) def _local_html_escape(s, quote=True): """ Works with bytes. Replace special characters "&", "<" and ">" to HTML-safe sequences. If the optional flag quote is true (the default), the quotation mark characters, both double quote (") and single quote (') characters are also translated. """ if isinstance(s, str): return html.escape(s, quote=quote) s = s.replace(b"&", b"&amp;") # Must be done first! s = s.replace(b"<", b"&lt;") s = s.replace(b">", b"&gt;") if quote: s = s.replace(b'"', b"&quot;") s = s.replace(b'\'', b"&#x27;") return s def with_metaclass(meta, *bases): """Create a base class with a metaclass.""" # This requires a bit of explanation: the basic idea is to make a dummy # metaclass for one level of class instantiation that replaces itself with # the actual metaclass. class metaclass(meta): __call__ = type.__call__ __init__ = type.__init__ def __new__(cls, name, this_bases, d): if this_bases is None: return type.__new__(cls, name, (), d) return meta(name, bases, d) return metaclass('temporary_class', None, {}) def to_unicode(obj, charset='utf-8', errors='strict'): if obj is None: return None if not isinstance(obj, bytes): return text_type(obj) return obj.decode(charset, errors) # shortcuts pjoin = os.path.join exists = os.path.exists
31.641618
88
0.654183
import sys import hashlib import os PY2 = sys.version_info[0] == 2 _identity = lambda x: x if PY2: import cPickle as pickle from cStringIO import StringIO import copy_reg as copyreg from HTMLParser import HTMLParser import urlparse from htmlentitydefs import entitydefs, name2codepoint import __builtin__ as builtin import thread import Cookie import urllib2 import Queue import ConfigParser as configparser from email.MIMEBase import MIMEBase from email.Header import Header from email import Encoders, Charset from email.MIMEMultipart import MIMEMultipart from email.MIMEText import MIMEText from email.Charset import add_charset, QP as charset_QP from urllib import FancyURLopener, urlencode, urlopen from urllib import quote as urllib_quote, unquote as urllib_unquote from string import maketrans from types import ClassType import cgi import cookielib reduce = reduce hashlib_md5 = hashlib.md5 iterkeys = lambda d: d.iterkeys() itervalues = lambda d: d.itervalues() iteritems = lambda d: d.iteritems() integer_types = (int, long) string_types = (str, unicode) text_type = unicode basestring = basestring xrange = xrange long = long unichr = unichr unicodeT = unicode def implements_bool(cls): cls.__nonzero__ = cls.__bool__ del cls.__bool__ return cls def to_bytes(obj, charset='utf-8', errors='strict'): if obj is None: return None if isinstance(obj, (bytes, bytearray, buffer)): return bytes(obj) if isinstance(obj, unicode): return obj.encode(charset, errors) raise TypeError('Expected bytes') def to_native(obj, charset='utf8', errors='strict'): if obj is None or isinstance(obj, str): return obj return obj.encode(charset, errors) def _local_html_escape(data, quote=False): s = cgi.escape(data, quote) return s.replace("'", "&#x27;") if quote else s else: import pickle from io import StringIO import copyreg from functools import reduce from html.parser import HTMLParser from http import cookies as Cookie from urllib import parse as urlparse from urllib import request as urllib2 from html.entities import entitydefs, name2codepoint import builtins as builtin import _thread as thread import configparser import queue as Queue from email.mime.base import MIMEBase from email.mime.multipart import MIMEMultipart from email.mime.text import MIMEText from email import encoders as Encoders from email.header import Header from email.charset import Charset, add_charset, QP as charset_QP from urllib.request import FancyURLopener, urlopen from urllib.parse import quote as urllib_quote, unquote as urllib_unquote, urlencode from http import cookiejar as cookielib import html hashlib_md5 = lambda s: hashlib.md5(bytes(s, 'utf8')) iterkeys = lambda d: iter(d.keys()) itervalues = lambda d: iter(d.values()) iteritems = lambda d: iter(d.items()) integer_types = (int,) string_types = (str,) text_type = str basestring = str xrange = range long = int unichr = chr unicodeT = str maketrans = str.maketrans ClassType = type implements_iterator = _identity implements_bool = _identity def to_bytes(obj, charset='utf-8', errors='strict'): if obj is None: return None if isinstance(obj, (bytes, bytearray, memoryview)): return bytes(obj) if isinstance(obj, str): return obj.encode(charset, errors) raise TypeError('Expected bytes') def to_native(obj, charset='utf8', errors='strict'): if obj is None or isinstance(obj, str): return obj return obj.decode(charset, errors) def _local_html_escape(s, quote=True): """ Works with bytes. Replace special characters "&", "<" and ">" to HTML-safe sequences. If the optional flag quote is true (the default), the quotation mark characters, both double quote (") and single quote (') characters are also translated. """ if isinstance(s, str): return html.escape(s, quote=quote) s = s.replace(b"&", b"&amp;") # Must be done first! s = s.replace(b"<", b"&lt;") s = s.replace(b">", b"&gt;") if quote: s = s.replace(b'"', b"&quot;") s = s.replace(b'\'', b"&#x27;") return s def with_metaclass(meta, *bases): # This requires a bit of explanation: the basic idea is to make a dummy # metaclass for one level of class instantiation that replaces itself with # the actual metaclass. class metaclass(meta): __call__ = type.__call__ __init__ = type.__init__ def __new__(cls, name, this_bases, d): if this_bases is None: return type.__new__(cls, name, (), d) return meta(name, bases, d) return metaclass('temporary_class', None, {}) def to_unicode(obj, charset='utf-8', errors='strict'): if obj is None: return None if not isinstance(obj, bytes): return text_type(obj) return obj.decode(charset, errors) # shortcuts pjoin = os.path.join exists = os.path.exists
true
true
1c3421ddc32d9035bd1863f644152cdb8cfd4a61
6,610
py
Python
django_sass_finder/finders.py
Tru-Dev/django_sass_finder
2541e30b1167abd4154ed946aaae7531d3f2a94a
[ "MIT" ]
1
2020-10-24T23:17:18.000Z
2020-10-24T23:17:18.000Z
django_sass_finder/finders.py
Tru-Dev/django_sass_finder
2541e30b1167abd4154ed946aaae7531d3f2a94a
[ "MIT" ]
2
2021-09-13T09:41:16.000Z
2021-09-17T15:56:24.000Z
django_sass_finder/finders.py
Tru-Dev/django_sass_finder
2541e30b1167abd4154ed946aaae7531d3f2a94a
[ "MIT" ]
3
2021-04-13T18:16:45.000Z
2021-09-12T12:05:34.000Z
# -*- coding: utf-8 -*- import stat from pathlib import Path import sass from django.apps import apps from django.conf import settings from django.contrib.staticfiles.finders import FileSystemFinder, AppDirectoriesFinder, BaseFinder from django.core.checks import Error from django.core.files.storage import FileSystemStorage __all__ = ( 'ScssFinder', ) class ScssFinder(BaseFinder): """ Finds .scss files specified in SCSS_ROOT and SCSS_COMPILE settings with globs. """ def _path_is_parent(self, path: Path) -> bool: try: self.css_compile_dir.relative_to(path) return True except ValueError: return False def _path_in_staticfiles(self): for static_dir in getattr(settings, 'STATICFILES_DIRS', []): if self._path_is_parent(Path(static_dir).resolve()): self._serve_static = getattr(settings, 'CSS_SERVE_STATIC', False) return def _path_in_appdirectories(self): if not self.apps_static_checked and apps.apps_ready and self._serve_static: try: app_configs = apps.get_app_configs() for app_config in app_configs: if self._path_is_parent(Path(app_config.path) / AppDirectoriesFinder.source_dir): self._serve_static = getattr(settings, 'CSS_SERVE_STATIC', False) return finally: self.apps_static_checked = True def __init__(self, app_names=None, *args, **kwargs): self.scss_compile = getattr(settings, 'SCSS_COMPILE', ['**/*.scss']) self.root = Path(settings.SCSS_ROOT) self.css_compile_dir = Path(settings.CSS_COMPILE_DIR).resolve() self.output_style = getattr(settings, 'CSS_STYLE', '') self.css_map = getattr(settings, 'CSS_MAP', False) self.include_paths = getattr(settings, 'SCSS_INCLUDE_PATHS', []) self.storage = FileSystemStorage(location=self.css_compile_dir) # by default, we serve our own files self._serve_static = True # we can check staticfiles immediately self._path_in_staticfiles() # apps probably aren't ready yet self.apps_static_checked = False self._path_in_appdirectories() self.source_cache = {} self.files_cache = {} @property def serve_static(self): self._path_in_appdirectories() return self._serve_static def check(self, **kwargs): """ Checks if ScssFinder is configured correctly. SCSS_COMPILE should contain valid files. """ errors = [] for scss_item in self.scss_compile: for _ in self.root.glob(scss_item): break else: errors.append(Error( f'{scss_item} returned no files in {self.scss_compile}.', id='sass.E001' )) return errors def output_path(self, scss_file, makedirs=False): # determine where the file will be generated, and ensure path exists if possible outpath = self.css_compile_dir / scss_file.relative_to(self.root).parent if makedirs: outpath.mkdir(parents=True, exist_ok=True) # add the filename to the output path return outpath / (scss_file.stem + '.css') def compile_scss(self): # search for and compile all scss files checked = [] self.files_cache.clear() for scss_item in self.scss_compile: for scss_file in self.root.glob(scss_item): try: scss_stat = scss_file.stat() except OSError: continue # usually FileNotFoundError if not stat.S_ISREG(scss_stat.st_mode): continue # not is_file() # mark this as checked checked.append(scss_file) # add it to the files cache outpath = self.output_path(scss_file, makedirs=True) relpath = outpath.relative_to(self.css_compile_dir) self.files_cache[relpath.as_posix()] = outpath try: cached = self.source_cache[scss_file] if scss_stat.st_mtime == cached: continue # unchanged, skip except KeyError: pass mappath = outpath.parent / (outpath.stem + '.map') # generate the css with outpath.open('w+') as outfile: sass_args = {'filename': str(scss_file)} if self.css_map: sass_args['source_map_filename'] = str(mappath) if self.include_paths: sass_args['include_paths'] = [str(path) for path in self.include_paths] if self.output_style: sass_args['output_style'] = self.output_style result = sass.compile(**sass_args) if isinstance(result, tuple): # if source map was requested, sass.compile returns a tuple: result, source map # we're not really interested in the source map other than generating it result, _ = result outfile.write(result) # add to or update the cache self.source_cache[scss_file] = scss_stat.st_mtime # walk the cache and check for any previously present files removed = [scss_file for scss_file, _ in self.source_cache.items() if scss_file not in checked] # and remove them from cache and unlink the target files for scss_file in removed: del self.source_cache[scss_file] outpath = self.output_path(scss_file) try: outpath.unlink(missing_ok=True) except OSError: pass def find(self, path, all=False): """ Run the compiler and see if was collected """ self.compile_scss() if self.serve_static and path in self.files_cache: path = self.files_cache[path].as_posix() return [path] if all else path return [] def list(self, ignore_patterns): """ Compile then list the .css files. """ self.compile_scss() if self.serve_static and self.files_cache: for path, _ in self.files_cache.items(): yield str(path), self.storage
38.208092
103
0.581997
import stat from pathlib import Path import sass from django.apps import apps from django.conf import settings from django.contrib.staticfiles.finders import FileSystemFinder, AppDirectoriesFinder, BaseFinder from django.core.checks import Error from django.core.files.storage import FileSystemStorage __all__ = ( 'ScssFinder', ) class ScssFinder(BaseFinder): def _path_is_parent(self, path: Path) -> bool: try: self.css_compile_dir.relative_to(path) return True except ValueError: return False def _path_in_staticfiles(self): for static_dir in getattr(settings, 'STATICFILES_DIRS', []): if self._path_is_parent(Path(static_dir).resolve()): self._serve_static = getattr(settings, 'CSS_SERVE_STATIC', False) return def _path_in_appdirectories(self): if not self.apps_static_checked and apps.apps_ready and self._serve_static: try: app_configs = apps.get_app_configs() for app_config in app_configs: if self._path_is_parent(Path(app_config.path) / AppDirectoriesFinder.source_dir): self._serve_static = getattr(settings, 'CSS_SERVE_STATIC', False) return finally: self.apps_static_checked = True def __init__(self, app_names=None, *args, **kwargs): self.scss_compile = getattr(settings, 'SCSS_COMPILE', ['**/*.scss']) self.root = Path(settings.SCSS_ROOT) self.css_compile_dir = Path(settings.CSS_COMPILE_DIR).resolve() self.output_style = getattr(settings, 'CSS_STYLE', '') self.css_map = getattr(settings, 'CSS_MAP', False) self.include_paths = getattr(settings, 'SCSS_INCLUDE_PATHS', []) self.storage = FileSystemStorage(location=self.css_compile_dir) self._serve_static = True self._path_in_staticfiles() self.apps_static_checked = False self._path_in_appdirectories() self.source_cache = {} self.files_cache = {} @property def serve_static(self): self._path_in_appdirectories() return self._serve_static def check(self, **kwargs): errors = [] for scss_item in self.scss_compile: for _ in self.root.glob(scss_item): break else: errors.append(Error( f'{scss_item} returned no files in {self.scss_compile}.', id='sass.E001' )) return errors def output_path(self, scss_file, makedirs=False): # determine where the file will be generated, and ensure path exists if possible outpath = self.css_compile_dir / scss_file.relative_to(self.root).parent if makedirs: outpath.mkdir(parents=True, exist_ok=True) # add the filename to the output path return outpath / (scss_file.stem + '.css') def compile_scss(self): # search for and compile all scss files checked = [] self.files_cache.clear() for scss_item in self.scss_compile: for scss_file in self.root.glob(scss_item): try: scss_stat = scss_file.stat() except OSError: continue # usually FileNotFoundError if not stat.S_ISREG(scss_stat.st_mode): continue # not is_file() # mark this as checked checked.append(scss_file) # add it to the files cache outpath = self.output_path(scss_file, makedirs=True) relpath = outpath.relative_to(self.css_compile_dir) self.files_cache[relpath.as_posix()] = outpath try: cached = self.source_cache[scss_file] if scss_stat.st_mtime == cached: continue # unchanged, skip except KeyError: pass mappath = outpath.parent / (outpath.stem + '.map') # generate the css with outpath.open('w+') as outfile: sass_args = {'filename': str(scss_file)} if self.css_map: sass_args['source_map_filename'] = str(mappath) if self.include_paths: sass_args['include_paths'] = [str(path) for path in self.include_paths] if self.output_style: sass_args['output_style'] = self.output_style result = sass.compile(**sass_args) if isinstance(result, tuple): # if source map was requested, sass.compile returns a tuple: result, source map # we're not really interested in the source map other than generating it result, _ = result outfile.write(result) self.source_cache[scss_file] = scss_stat.st_mtime removed = [scss_file for scss_file, _ in self.source_cache.items() if scss_file not in checked] for scss_file in removed: del self.source_cache[scss_file] outpath = self.output_path(scss_file) try: outpath.unlink(missing_ok=True) except OSError: pass def find(self, path, all=False): self.compile_scss() if self.serve_static and path in self.files_cache: path = self.files_cache[path].as_posix() return [path] if all else path return [] def list(self, ignore_patterns): self.compile_scss() if self.serve_static and self.files_cache: for path, _ in self.files_cache.items(): yield str(path), self.storage
true
true
1c34231126a265909f39756cbb8e3e90cd5157cc
652
py
Python
pywikibot/compat/userlib.py
notconfusing/pywikibot-fr-welcome-bot
6e07b7e74166a47c9425816e79786308df369ac2
[ "MIT" ]
1
2020-01-03T11:52:01.000Z
2020-01-03T11:52:01.000Z
pywikibot/compat/userlib.py
notconfusing/pywikibot-fr-welcome-bot
6e07b7e74166a47c9425816e79786308df369ac2
[ "MIT" ]
2
2019-11-07T13:46:32.000Z
2019-11-07T14:20:53.000Z
pywikibot/compat/userlib.py
notconfusing/pywikibot-fr-welcome-bot
6e07b7e74166a47c9425816e79786308df369ac2
[ "MIT" ]
null
null
null
# -*- coding: utf-8 -*- """ WARNING: THIS MODULE EXISTS SOLELY TO PROVIDE BACKWARDS-COMPATIBILITY. Do not use in new scripts; use the source to find the appropriate function/method instead. """ # # (C) Pywikibot team, 2008-2018 # # Distributed under the terms of the MIT license. # from __future__ import absolute_import, division, unicode_literals from pywikibot.page import User from pywikibot.tools import ModuleDeprecationWrapper __all__ = ('User',) wrapper = ModuleDeprecationWrapper(__name__) wrapper._add_deprecated_attr('User', replacement_name='pywikibot.User', since='20141209')
26.08
70
0.707055
from __future__ import absolute_import, division, unicode_literals from pywikibot.page import User from pywikibot.tools import ModuleDeprecationWrapper __all__ = ('User',) wrapper = ModuleDeprecationWrapper(__name__) wrapper._add_deprecated_attr('User', replacement_name='pywikibot.User', since='20141209')
true
true
1c34234f58c4cfb7a22a62835900d0f0b2695b61
13,645
py
Python
thrift/compiler/test/fixtures/complex-union/gen-py3lite/module/lite_metadata.py
dgrnbrg-meta/fbthrift
1d5f0799ef53feeb83425b6c9c79f86aeac7d9ed
[ "Apache-2.0" ]
null
null
null
thrift/compiler/test/fixtures/complex-union/gen-py3lite/module/lite_metadata.py
dgrnbrg-meta/fbthrift
1d5f0799ef53feeb83425b6c9c79f86aeac7d9ed
[ "Apache-2.0" ]
1
2022-03-03T09:40:25.000Z
2022-03-03T09:40:25.000Z
thrift/compiler/test/fixtures/complex-union/gen-py3lite/module/lite_metadata.py
dgrnbrg-meta/fbthrift
1d5f0799ef53feeb83425b6c9c79f86aeac7d9ed
[ "Apache-2.0" ]
null
null
null
# # Autogenerated by Thrift # # DO NOT EDIT # @generated # import apache.thrift.metadata.lite_types as _fbthrift_metadata # TODO (ffrancet): This general pattern can be optimized by using tuples and dicts # instead of re-generating thrift structs def _fbthrift_gen_metadata_struct_ComplexUnion(metadata_struct: _fbthrift_metadata.ThriftMetadata) -> _fbthrift_metadata.ThriftMetadata: qualified_name = "module.ComplexUnion" if qualified_name in metadata_struct.structs: return metadata_struct fields = [ _fbthrift_metadata.ThriftField(id=1, type=_fbthrift_metadata.ThriftType(t_primitive=_fbthrift_metadata.ThriftPrimitiveType.THRIFT_I64_TYPE), name="intValue", is_optional=False, structured_annotations=[ ]), _fbthrift_metadata.ThriftField(id=5, type=_fbthrift_metadata.ThriftType(t_primitive=_fbthrift_metadata.ThriftPrimitiveType.THRIFT_STRING_TYPE), name="stringValue", is_optional=False, structured_annotations=[ ]), _fbthrift_metadata.ThriftField(id=2, type=_fbthrift_metadata.ThriftType(t_list=_fbthrift_metadata.ThriftListType(valueType=_fbthrift_metadata.ThriftType(t_primitive=_fbthrift_metadata.ThriftPrimitiveType.THRIFT_I64_TYPE))), name="intListValue", is_optional=False, structured_annotations=[ ]), _fbthrift_metadata.ThriftField(id=3, type=_fbthrift_metadata.ThriftType(t_list=_fbthrift_metadata.ThriftListType(valueType=_fbthrift_metadata.ThriftType(t_primitive=_fbthrift_metadata.ThriftPrimitiveType.THRIFT_STRING_TYPE))), name="stringListValue", is_optional=False, structured_annotations=[ ]), _fbthrift_metadata.ThriftField(id=9, type=_fbthrift_metadata.ThriftType(t_map=_fbthrift_metadata.ThriftMapType(keyType=_fbthrift_metadata.ThriftType(t_primitive=_fbthrift_metadata.ThriftPrimitiveType.THRIFT_I16_TYPE),valueType=_fbthrift_metadata.ThriftType(t_primitive=_fbthrift_metadata.ThriftPrimitiveType.THRIFT_STRING_TYPE))), name="typedefValue", is_optional=False, structured_annotations=[ ]), _fbthrift_metadata.ThriftField(id=14, type=_fbthrift_metadata.ThriftType(t_primitive=_fbthrift_metadata.ThriftPrimitiveType.THRIFT_STRING_TYPE), name="stringRef", is_optional=False, structured_annotations=[ ]), ] struct_dict = dict(metadata_struct.structs) struct_dict[qualified_name] = _fbthrift_metadata.ThriftStruct(name=qualified_name, fields=fields, is_union=True, structured_annotations=[ ]) new_struct = metadata_struct(structs=struct_dict) # intValue # stringValue # intListValue # stringListValue # key # val # typedefValue # stringRef return new_struct def gen_metadata_struct_ComplexUnion() -> _fbthrift_metadata.ThriftMetadata: return _fbthrift_gen_metadata_struct_ComplexUnion(_fbthrift_metadata.ThriftMetadata(structs={}, enums={}, exceptions={}, services={})) # TODO (ffrancet): This general pattern can be optimized by using tuples and dicts # instead of re-generating thrift structs def _fbthrift_gen_metadata_struct_ListUnion(metadata_struct: _fbthrift_metadata.ThriftMetadata) -> _fbthrift_metadata.ThriftMetadata: qualified_name = "module.ListUnion" if qualified_name in metadata_struct.structs: return metadata_struct fields = [ _fbthrift_metadata.ThriftField(id=2, type=_fbthrift_metadata.ThriftType(t_list=_fbthrift_metadata.ThriftListType(valueType=_fbthrift_metadata.ThriftType(t_primitive=_fbthrift_metadata.ThriftPrimitiveType.THRIFT_I64_TYPE))), name="intListValue", is_optional=False, structured_annotations=[ ]), _fbthrift_metadata.ThriftField(id=3, type=_fbthrift_metadata.ThriftType(t_list=_fbthrift_metadata.ThriftListType(valueType=_fbthrift_metadata.ThriftType(t_primitive=_fbthrift_metadata.ThriftPrimitiveType.THRIFT_STRING_TYPE))), name="stringListValue", is_optional=False, structured_annotations=[ ]), ] struct_dict = dict(metadata_struct.structs) struct_dict[qualified_name] = _fbthrift_metadata.ThriftStruct(name=qualified_name, fields=fields, is_union=True, structured_annotations=[ ]) new_struct = metadata_struct(structs=struct_dict) # intListValue # stringListValue return new_struct def gen_metadata_struct_ListUnion() -> _fbthrift_metadata.ThriftMetadata: return _fbthrift_gen_metadata_struct_ListUnion(_fbthrift_metadata.ThriftMetadata(structs={}, enums={}, exceptions={}, services={})) # TODO (ffrancet): This general pattern can be optimized by using tuples and dicts # instead of re-generating thrift structs def _fbthrift_gen_metadata_struct_DataUnion(metadata_struct: _fbthrift_metadata.ThriftMetadata) -> _fbthrift_metadata.ThriftMetadata: qualified_name = "module.DataUnion" if qualified_name in metadata_struct.structs: return metadata_struct fields = [ _fbthrift_metadata.ThriftField(id=1, type=_fbthrift_metadata.ThriftType(t_primitive=_fbthrift_metadata.ThriftPrimitiveType.THRIFT_BINARY_TYPE), name="binaryData", is_optional=False, structured_annotations=[ ]), _fbthrift_metadata.ThriftField(id=2, type=_fbthrift_metadata.ThriftType(t_primitive=_fbthrift_metadata.ThriftPrimitiveType.THRIFT_STRING_TYPE), name="stringData", is_optional=False, structured_annotations=[ ]), ] struct_dict = dict(metadata_struct.structs) struct_dict[qualified_name] = _fbthrift_metadata.ThriftStruct(name=qualified_name, fields=fields, is_union=True, structured_annotations=[ ]) new_struct = metadata_struct(structs=struct_dict) # binaryData # stringData return new_struct def gen_metadata_struct_DataUnion() -> _fbthrift_metadata.ThriftMetadata: return _fbthrift_gen_metadata_struct_DataUnion(_fbthrift_metadata.ThriftMetadata(structs={}, enums={}, exceptions={}, services={})) # TODO (ffrancet): This general pattern can be optimized by using tuples and dicts # instead of re-generating thrift structs def _fbthrift_gen_metadata_struct_Val(metadata_struct: _fbthrift_metadata.ThriftMetadata) -> _fbthrift_metadata.ThriftMetadata: qualified_name = "module.Val" if qualified_name in metadata_struct.structs: return metadata_struct fields = [ _fbthrift_metadata.ThriftField(id=1, type=_fbthrift_metadata.ThriftType(t_primitive=_fbthrift_metadata.ThriftPrimitiveType.THRIFT_STRING_TYPE), name="strVal", is_optional=False, structured_annotations=[ ]), _fbthrift_metadata.ThriftField(id=2, type=_fbthrift_metadata.ThriftType(t_primitive=_fbthrift_metadata.ThriftPrimitiveType.THRIFT_I32_TYPE), name="intVal", is_optional=False, structured_annotations=[ ]), _fbthrift_metadata.ThriftField(id=9, type=_fbthrift_metadata.ThriftType(t_map=_fbthrift_metadata.ThriftMapType(keyType=_fbthrift_metadata.ThriftType(t_primitive=_fbthrift_metadata.ThriftPrimitiveType.THRIFT_I16_TYPE),valueType=_fbthrift_metadata.ThriftType(t_primitive=_fbthrift_metadata.ThriftPrimitiveType.THRIFT_STRING_TYPE))), name="typedefValue", is_optional=False, structured_annotations=[ ]), ] struct_dict = dict(metadata_struct.structs) struct_dict[qualified_name] = _fbthrift_metadata.ThriftStruct(name=qualified_name, fields=fields, is_union=False, structured_annotations=[ ]) new_struct = metadata_struct(structs=struct_dict) # strVal # intVal # key # val # typedefValue return new_struct def gen_metadata_struct_Val() -> _fbthrift_metadata.ThriftMetadata: return _fbthrift_gen_metadata_struct_Val(_fbthrift_metadata.ThriftMetadata(structs={}, enums={}, exceptions={}, services={})) # TODO (ffrancet): This general pattern can be optimized by using tuples and dicts # instead of re-generating thrift structs def _fbthrift_gen_metadata_struct_ValUnion(metadata_struct: _fbthrift_metadata.ThriftMetadata) -> _fbthrift_metadata.ThriftMetadata: qualified_name = "module.ValUnion" if qualified_name in metadata_struct.structs: return metadata_struct fields = [ _fbthrift_metadata.ThriftField(id=1, type=_fbthrift_metadata.ThriftType(t_struct=_fbthrift_metadata.ThriftStructType(name="module.Val")), name="v1", is_optional=False, structured_annotations=[ ]), _fbthrift_metadata.ThriftField(id=2, type=_fbthrift_metadata.ThriftType(t_struct=_fbthrift_metadata.ThriftStructType(name="module.Val")), name="v2", is_optional=False, structured_annotations=[ ]), ] struct_dict = dict(metadata_struct.structs) struct_dict[qualified_name] = _fbthrift_metadata.ThriftStruct(name=qualified_name, fields=fields, is_union=True, structured_annotations=[ ]) new_struct = metadata_struct(structs=struct_dict) new_struct = _fbthrift_gen_metadata_struct_Val(new_struct) # v1 new_struct = _fbthrift_gen_metadata_struct_Val(new_struct) # v2 return new_struct def gen_metadata_struct_ValUnion() -> _fbthrift_metadata.ThriftMetadata: return _fbthrift_gen_metadata_struct_ValUnion(_fbthrift_metadata.ThriftMetadata(structs={}, enums={}, exceptions={}, services={})) # TODO (ffrancet): This general pattern can be optimized by using tuples and dicts # instead of re-generating thrift structs def _fbthrift_gen_metadata_struct_VirtualComplexUnion(metadata_struct: _fbthrift_metadata.ThriftMetadata) -> _fbthrift_metadata.ThriftMetadata: qualified_name = "module.VirtualComplexUnion" if qualified_name in metadata_struct.structs: return metadata_struct fields = [ _fbthrift_metadata.ThriftField(id=1, type=_fbthrift_metadata.ThriftType(t_primitive=_fbthrift_metadata.ThriftPrimitiveType.THRIFT_STRING_TYPE), name="thingOne", is_optional=False, structured_annotations=[ ]), _fbthrift_metadata.ThriftField(id=2, type=_fbthrift_metadata.ThriftType(t_primitive=_fbthrift_metadata.ThriftPrimitiveType.THRIFT_STRING_TYPE), name="thingTwo", is_optional=False, structured_annotations=[ ]), ] struct_dict = dict(metadata_struct.structs) struct_dict[qualified_name] = _fbthrift_metadata.ThriftStruct(name=qualified_name, fields=fields, is_union=True, structured_annotations=[ ]) new_struct = metadata_struct(structs=struct_dict) # thingOne # thingTwo return new_struct def gen_metadata_struct_VirtualComplexUnion() -> _fbthrift_metadata.ThriftMetadata: return _fbthrift_gen_metadata_struct_VirtualComplexUnion(_fbthrift_metadata.ThriftMetadata(structs={}, enums={}, exceptions={}, services={})) # TODO (ffrancet): This general pattern can be optimized by using tuples and dicts # instead of re-generating thrift structs def _fbthrift_gen_metadata_struct_NonCopyableStruct(metadata_struct: _fbthrift_metadata.ThriftMetadata) -> _fbthrift_metadata.ThriftMetadata: qualified_name = "module.NonCopyableStruct" if qualified_name in metadata_struct.structs: return metadata_struct fields = [ _fbthrift_metadata.ThriftField(id=1, type=_fbthrift_metadata.ThriftType(t_primitive=_fbthrift_metadata.ThriftPrimitiveType.THRIFT_I64_TYPE), name="num", is_optional=False, structured_annotations=[ ]), ] struct_dict = dict(metadata_struct.structs) struct_dict[qualified_name] = _fbthrift_metadata.ThriftStruct(name=qualified_name, fields=fields, is_union=False, structured_annotations=[ ]) new_struct = metadata_struct(structs=struct_dict) # num return new_struct def gen_metadata_struct_NonCopyableStruct() -> _fbthrift_metadata.ThriftMetadata: return _fbthrift_gen_metadata_struct_NonCopyableStruct(_fbthrift_metadata.ThriftMetadata(structs={}, enums={}, exceptions={}, services={})) # TODO (ffrancet): This general pattern can be optimized by using tuples and dicts # instead of re-generating thrift structs def _fbthrift_gen_metadata_struct_NonCopyableUnion(metadata_struct: _fbthrift_metadata.ThriftMetadata) -> _fbthrift_metadata.ThriftMetadata: qualified_name = "module.NonCopyableUnion" if qualified_name in metadata_struct.structs: return metadata_struct fields = [ _fbthrift_metadata.ThriftField(id=1, type=_fbthrift_metadata.ThriftType(t_struct=_fbthrift_metadata.ThriftStructType(name="module.NonCopyableStruct")), name="s", is_optional=False, structured_annotations=[ ]), ] struct_dict = dict(metadata_struct.structs) struct_dict[qualified_name] = _fbthrift_metadata.ThriftStruct(name=qualified_name, fields=fields, is_union=True, structured_annotations=[ ]) new_struct = metadata_struct(structs=struct_dict) new_struct = _fbthrift_gen_metadata_struct_NonCopyableStruct(new_struct) # s return new_struct def gen_metadata_struct_NonCopyableUnion() -> _fbthrift_metadata.ThriftMetadata: return _fbthrift_gen_metadata_struct_NonCopyableUnion(_fbthrift_metadata.ThriftMetadata(structs={}, enums={}, exceptions={}, services={})) def getThriftModuleMetadata() -> _fbthrift_metadata.ThriftMetadata: meta = _fbthrift_metadata.ThriftMetadata(structs={}, enums={}, exceptions={}, services={}) meta = _fbthrift_gen_metadata_struct_ComplexUnion(meta) meta = _fbthrift_gen_metadata_struct_ListUnion(meta) meta = _fbthrift_gen_metadata_struct_DataUnion(meta) meta = _fbthrift_gen_metadata_struct_Val(meta) meta = _fbthrift_gen_metadata_struct_ValUnion(meta) meta = _fbthrift_gen_metadata_struct_VirtualComplexUnion(meta) meta = _fbthrift_gen_metadata_struct_NonCopyableStruct(meta) meta = _fbthrift_gen_metadata_struct_NonCopyableUnion(meta) return meta
54.36255
403
0.785196
import apache.thrift.metadata.lite_types as _fbthrift_metadata def _fbthrift_gen_metadata_struct_ComplexUnion(metadata_struct: _fbthrift_metadata.ThriftMetadata) -> _fbthrift_metadata.ThriftMetadata: qualified_name = "module.ComplexUnion" if qualified_name in metadata_struct.structs: return metadata_struct fields = [ _fbthrift_metadata.ThriftField(id=1, type=_fbthrift_metadata.ThriftType(t_primitive=_fbthrift_metadata.ThriftPrimitiveType.THRIFT_I64_TYPE), name="intValue", is_optional=False, structured_annotations=[ ]), _fbthrift_metadata.ThriftField(id=5, type=_fbthrift_metadata.ThriftType(t_primitive=_fbthrift_metadata.ThriftPrimitiveType.THRIFT_STRING_TYPE), name="stringValue", is_optional=False, structured_annotations=[ ]), _fbthrift_metadata.ThriftField(id=2, type=_fbthrift_metadata.ThriftType(t_list=_fbthrift_metadata.ThriftListType(valueType=_fbthrift_metadata.ThriftType(t_primitive=_fbthrift_metadata.ThriftPrimitiveType.THRIFT_I64_TYPE))), name="intListValue", is_optional=False, structured_annotations=[ ]), _fbthrift_metadata.ThriftField(id=3, type=_fbthrift_metadata.ThriftType(t_list=_fbthrift_metadata.ThriftListType(valueType=_fbthrift_metadata.ThriftType(t_primitive=_fbthrift_metadata.ThriftPrimitiveType.THRIFT_STRING_TYPE))), name="stringListValue", is_optional=False, structured_annotations=[ ]), _fbthrift_metadata.ThriftField(id=9, type=_fbthrift_metadata.ThriftType(t_map=_fbthrift_metadata.ThriftMapType(keyType=_fbthrift_metadata.ThriftType(t_primitive=_fbthrift_metadata.ThriftPrimitiveType.THRIFT_I16_TYPE),valueType=_fbthrift_metadata.ThriftType(t_primitive=_fbthrift_metadata.ThriftPrimitiveType.THRIFT_STRING_TYPE))), name="typedefValue", is_optional=False, structured_annotations=[ ]), _fbthrift_metadata.ThriftField(id=14, type=_fbthrift_metadata.ThriftType(t_primitive=_fbthrift_metadata.ThriftPrimitiveType.THRIFT_STRING_TYPE), name="stringRef", is_optional=False, structured_annotations=[ ]), ] struct_dict = dict(metadata_struct.structs) struct_dict[qualified_name] = _fbthrift_metadata.ThriftStruct(name=qualified_name, fields=fields, is_union=True, structured_annotations=[ ]) new_struct = metadata_struct(structs=struct_dict) turn new_struct def gen_metadata_struct_ComplexUnion() -> _fbthrift_metadata.ThriftMetadata: return _fbthrift_gen_metadata_struct_ComplexUnion(_fbthrift_metadata.ThriftMetadata(structs={}, enums={}, exceptions={}, services={})) def _fbthrift_gen_metadata_struct_ListUnion(metadata_struct: _fbthrift_metadata.ThriftMetadata) -> _fbthrift_metadata.ThriftMetadata: qualified_name = "module.ListUnion" if qualified_name in metadata_struct.structs: return metadata_struct fields = [ _fbthrift_metadata.ThriftField(id=2, type=_fbthrift_metadata.ThriftType(t_list=_fbthrift_metadata.ThriftListType(valueType=_fbthrift_metadata.ThriftType(t_primitive=_fbthrift_metadata.ThriftPrimitiveType.THRIFT_I64_TYPE))), name="intListValue", is_optional=False, structured_annotations=[ ]), _fbthrift_metadata.ThriftField(id=3, type=_fbthrift_metadata.ThriftType(t_list=_fbthrift_metadata.ThriftListType(valueType=_fbthrift_metadata.ThriftType(t_primitive=_fbthrift_metadata.ThriftPrimitiveType.THRIFT_STRING_TYPE))), name="stringListValue", is_optional=False, structured_annotations=[ ]), ] struct_dict = dict(metadata_struct.structs) struct_dict[qualified_name] = _fbthrift_metadata.ThriftStruct(name=qualified_name, fields=fields, is_union=True, structured_annotations=[ ]) new_struct = metadata_struct(structs=struct_dict) return new_struct def gen_metadata_struct_ListUnion() -> _fbthrift_metadata.ThriftMetadata: return _fbthrift_gen_metadata_struct_ListUnion(_fbthrift_metadata.ThriftMetadata(structs={}, enums={}, exceptions={}, services={})) def _fbthrift_gen_metadata_struct_DataUnion(metadata_struct: _fbthrift_metadata.ThriftMetadata) -> _fbthrift_metadata.ThriftMetadata: qualified_name = "module.DataUnion" if qualified_name in metadata_struct.structs: return metadata_struct fields = [ _fbthrift_metadata.ThriftField(id=1, type=_fbthrift_metadata.ThriftType(t_primitive=_fbthrift_metadata.ThriftPrimitiveType.THRIFT_BINARY_TYPE), name="binaryData", is_optional=False, structured_annotations=[ ]), _fbthrift_metadata.ThriftField(id=2, type=_fbthrift_metadata.ThriftType(t_primitive=_fbthrift_metadata.ThriftPrimitiveType.THRIFT_STRING_TYPE), name="stringData", is_optional=False, structured_annotations=[ ]), ] struct_dict = dict(metadata_struct.structs) struct_dict[qualified_name] = _fbthrift_metadata.ThriftStruct(name=qualified_name, fields=fields, is_union=True, structured_annotations=[ ]) new_struct = metadata_struct(structs=struct_dict) return new_struct def gen_metadata_struct_DataUnion() -> _fbthrift_metadata.ThriftMetadata: return _fbthrift_gen_metadata_struct_DataUnion(_fbthrift_metadata.ThriftMetadata(structs={}, enums={}, exceptions={}, services={})) def _fbthrift_gen_metadata_struct_Val(metadata_struct: _fbthrift_metadata.ThriftMetadata) -> _fbthrift_metadata.ThriftMetadata: qualified_name = "module.Val" if qualified_name in metadata_struct.structs: return metadata_struct fields = [ _fbthrift_metadata.ThriftField(id=1, type=_fbthrift_metadata.ThriftType(t_primitive=_fbthrift_metadata.ThriftPrimitiveType.THRIFT_STRING_TYPE), name="strVal", is_optional=False, structured_annotations=[ ]), _fbthrift_metadata.ThriftField(id=2, type=_fbthrift_metadata.ThriftType(t_primitive=_fbthrift_metadata.ThriftPrimitiveType.THRIFT_I32_TYPE), name="intVal", is_optional=False, structured_annotations=[ ]), _fbthrift_metadata.ThriftField(id=9, type=_fbthrift_metadata.ThriftType(t_map=_fbthrift_metadata.ThriftMapType(keyType=_fbthrift_metadata.ThriftType(t_primitive=_fbthrift_metadata.ThriftPrimitiveType.THRIFT_I16_TYPE),valueType=_fbthrift_metadata.ThriftType(t_primitive=_fbthrift_metadata.ThriftPrimitiveType.THRIFT_STRING_TYPE))), name="typedefValue", is_optional=False, structured_annotations=[ ]), ] struct_dict = dict(metadata_struct.structs) struct_dict[qualified_name] = _fbthrift_metadata.ThriftStruct(name=qualified_name, fields=fields, is_union=False, structured_annotations=[ ]) new_struct = metadata_struct(structs=struct_dict) ew_struct def gen_metadata_struct_Val() -> _fbthrift_metadata.ThriftMetadata: return _fbthrift_gen_metadata_struct_Val(_fbthrift_metadata.ThriftMetadata(structs={}, enums={}, exceptions={}, services={})) def _fbthrift_gen_metadata_struct_ValUnion(metadata_struct: _fbthrift_metadata.ThriftMetadata) -> _fbthrift_metadata.ThriftMetadata: qualified_name = "module.ValUnion" if qualified_name in metadata_struct.structs: return metadata_struct fields = [ _fbthrift_metadata.ThriftField(id=1, type=_fbthrift_metadata.ThriftType(t_struct=_fbthrift_metadata.ThriftStructType(name="module.Val")), name="v1", is_optional=False, structured_annotations=[ ]), _fbthrift_metadata.ThriftField(id=2, type=_fbthrift_metadata.ThriftType(t_struct=_fbthrift_metadata.ThriftStructType(name="module.Val")), name="v2", is_optional=False, structured_annotations=[ ]), ] struct_dict = dict(metadata_struct.structs) struct_dict[qualified_name] = _fbthrift_metadata.ThriftStruct(name=qualified_name, fields=fields, is_union=True, structured_annotations=[ ]) new_struct = metadata_struct(structs=struct_dict) new_struct = _fbthrift_gen_metadata_struct_Val(new_struct) new_struct = _fbthrift_gen_metadata_struct_Val(new_struct) return new_struct def gen_metadata_struct_ValUnion() -> _fbthrift_metadata.ThriftMetadata: return _fbthrift_gen_metadata_struct_ValUnion(_fbthrift_metadata.ThriftMetadata(structs={}, enums={}, exceptions={}, services={})) def _fbthrift_gen_metadata_struct_VirtualComplexUnion(metadata_struct: _fbthrift_metadata.ThriftMetadata) -> _fbthrift_metadata.ThriftMetadata: qualified_name = "module.VirtualComplexUnion" if qualified_name in metadata_struct.structs: return metadata_struct fields = [ _fbthrift_metadata.ThriftField(id=1, type=_fbthrift_metadata.ThriftType(t_primitive=_fbthrift_metadata.ThriftPrimitiveType.THRIFT_STRING_TYPE), name="thingOne", is_optional=False, structured_annotations=[ ]), _fbthrift_metadata.ThriftField(id=2, type=_fbthrift_metadata.ThriftType(t_primitive=_fbthrift_metadata.ThriftPrimitiveType.THRIFT_STRING_TYPE), name="thingTwo", is_optional=False, structured_annotations=[ ]), ] struct_dict = dict(metadata_struct.structs) struct_dict[qualified_name] = _fbthrift_metadata.ThriftStruct(name=qualified_name, fields=fields, is_union=True, structured_annotations=[ ]) new_struct = metadata_struct(structs=struct_dict) return new_struct def gen_metadata_struct_VirtualComplexUnion() -> _fbthrift_metadata.ThriftMetadata: return _fbthrift_gen_metadata_struct_VirtualComplexUnion(_fbthrift_metadata.ThriftMetadata(structs={}, enums={}, exceptions={}, services={})) def _fbthrift_gen_metadata_struct_NonCopyableStruct(metadata_struct: _fbthrift_metadata.ThriftMetadata) -> _fbthrift_metadata.ThriftMetadata: qualified_name = "module.NonCopyableStruct" if qualified_name in metadata_struct.structs: return metadata_struct fields = [ _fbthrift_metadata.ThriftField(id=1, type=_fbthrift_metadata.ThriftType(t_primitive=_fbthrift_metadata.ThriftPrimitiveType.THRIFT_I64_TYPE), name="num", is_optional=False, structured_annotations=[ ]), ] struct_dict = dict(metadata_struct.structs) struct_dict[qualified_name] = _fbthrift_metadata.ThriftStruct(name=qualified_name, fields=fields, is_union=False, structured_annotations=[ ]) new_struct = metadata_struct(structs=struct_dict) return new_struct def gen_metadata_struct_NonCopyableStruct() -> _fbthrift_metadata.ThriftMetadata: return _fbthrift_gen_metadata_struct_NonCopyableStruct(_fbthrift_metadata.ThriftMetadata(structs={}, enums={}, exceptions={}, services={})) def _fbthrift_gen_metadata_struct_NonCopyableUnion(metadata_struct: _fbthrift_metadata.ThriftMetadata) -> _fbthrift_metadata.ThriftMetadata: qualified_name = "module.NonCopyableUnion" if qualified_name in metadata_struct.structs: return metadata_struct fields = [ _fbthrift_metadata.ThriftField(id=1, type=_fbthrift_metadata.ThriftType(t_struct=_fbthrift_metadata.ThriftStructType(name="module.NonCopyableStruct")), name="s", is_optional=False, structured_annotations=[ ]), ] struct_dict = dict(metadata_struct.structs) struct_dict[qualified_name] = _fbthrift_metadata.ThriftStruct(name=qualified_name, fields=fields, is_union=True, structured_annotations=[ ]) new_struct = metadata_struct(structs=struct_dict) new_struct = _fbthrift_gen_metadata_struct_NonCopyableStruct(new_struct) return new_struct def gen_metadata_struct_NonCopyableUnion() -> _fbthrift_metadata.ThriftMetadata: return _fbthrift_gen_metadata_struct_NonCopyableUnion(_fbthrift_metadata.ThriftMetadata(structs={}, enums={}, exceptions={}, services={})) def getThriftModuleMetadata() -> _fbthrift_metadata.ThriftMetadata: meta = _fbthrift_metadata.ThriftMetadata(structs={}, enums={}, exceptions={}, services={}) meta = _fbthrift_gen_metadata_struct_ComplexUnion(meta) meta = _fbthrift_gen_metadata_struct_ListUnion(meta) meta = _fbthrift_gen_metadata_struct_DataUnion(meta) meta = _fbthrift_gen_metadata_struct_Val(meta) meta = _fbthrift_gen_metadata_struct_ValUnion(meta) meta = _fbthrift_gen_metadata_struct_VirtualComplexUnion(meta) meta = _fbthrift_gen_metadata_struct_NonCopyableStruct(meta) meta = _fbthrift_gen_metadata_struct_NonCopyableUnion(meta) return meta
true
true
1c3423996610ed84883be5d37c04c4b1a7904461
10,743
py
Python
src/pystockwatch/pystockwatch.py
UBC-MDS/Pystockwatch
4c72dae96d392cf2681b043db6e2fd440c936e49
[ "MIT" ]
null
null
null
src/pystockwatch/pystockwatch.py
UBC-MDS/Pystockwatch
4c72dae96d392cf2681b043db6e2fd440c936e49
[ "MIT" ]
55
2022-01-13T08:26:19.000Z
2022-02-05T11:24:07.000Z
src/pystockwatch/pystockwatch.py
UBC-MDS/Pystockwatch
4c72dae96d392cf2681b043db6e2fd440c936e49
[ "MIT" ]
1
2022-01-29T19:33:30.000Z
2022-01-29T19:33:30.000Z
# authors: Affrin Sultana, Helin Wang, Shi Yan Wang and Pavel Levchenko # January,2022 # import plotly.express as px import plotly.graph_objects as go import altair as alt import pandas as pd import numpy as np import yfinance as yf import pandas_datareader as pdr import datetime import warnings alt.renderers.enable('altair_viewer') def percent_change(stock_ticker, start_date, end_date): """ Calculates daily percentage change of a stock price within a given period of time Parameters ---------- stock_ticker : string Ticker of the stock such as 'AAPL' start_date : string Initial date for data extraction end_date : string Final date for stock analysis Returns -------- DataFrame A data frame with dates and their corresponding stock price percentage changes. Examples -------- >>> percent_change('AAPL', '2017-01-01', '2017-01-10') Price Change Percentage(%) Date 2017-01-03 0.000 2017-01-04 -0.112 2017-01-05 0.396 2017-01-06 1.515 2017-01-09 2.445 """ # Assert ticker input value ticker = yf.Ticker(stock_ticker) if(ticker.info["regularMarketPrice"] == None): raise NameError("You have entered an invalid stock ticker! Try again.") # Assert start date input value format = "%Y-%m-%d" try: datetime.datetime.strptime(start_date, format) except ValueError: raise ValueError("You have entered an invalid start date! Try date formatted in YYYY-MM-DD.") # Assert end date input value try: datetime.datetime.strptime(end_date, format) except ValueError: raise ValueError("You have entered an invalid end date! Try date formatted in YYYY-MM-DD.") # Assert end date is later than start date format = "%Y-%m-%d" if(datetime.datetime.strptime(end_date, format) < datetime.datetime.strptime(start_date, format)): raise ValueError("You have entered an end date which is earlier than the start date! Try again.") # Import original dataframe by giving stock ticker, start data and end date data = yf.download(stock_ticker, start=start_date, end=end_date) # Only Keep "Adj Close" Price for data = data.drop(columns={'Open', 'High', 'Low', 'Adj Close', 'Volume'}) # Carry out calculation for i in range(1,len(data)): data.iloc[i,:] = round((data.iloc[i,:] - data.iloc[0,:])/data.iloc[0,:]*100, 3) data.iloc[0,:] = round((data.iloc[0,:] - data.iloc[0,:])/data.iloc[0,:]*100, 3) # Manipulate column name data = data.rename(columns={"Close": "Price Change Percentage(%)"}) # Return result return pd.DataFrame(data) def profit_viz(stock_ticker, start_date , end_date, benchmark_ticker): """ Visualizes trend of a stock price change against the market benchmark within a given period of time Parameters ---------- stock_ticker : string Ticker of the stock such as 'AAPL' start_date : string Initial date for data extraction end_date : string Final date for stock analysis benchmark_ticker : string Ticker for benchmark comparison such as 'SP500' Returns -------- Altair Chart A line chart which shows percentage change in stock price and market performance over time Examples -------- >>> profit_viz('AAPL', '2015-01-01', '2021-12-31', 'SP500') """ ticker = yf.Ticker(stock_ticker) bench_ticker = yf.Ticker(benchmark_ticker) try: # Assert ticker input value if(ticker.info["regularMarketPrice"] == None): raise NameError("You have entered an invalid stock ticker! Try again.") # check data type of input if type(stock_ticker) != str: raise TypeError("stock_ticker should be of type string.") # Assert benchmark ticker input value if(bench_ticker.info["regularMarketPrice"] == None): raise NameError("You have entered an invalid benchmark ticker! Try again.") # check data type of input if type(benchmark_ticker) != str: raise TypeError("Bench Mark ticker should be of type string.") # #check stock ticker and bench mark ticker are not same # if stock_ticker is bench_ticker: # raise NameError("Stock Mark ticker should not be same as Bench Ticker.") # #check stock ticker is not empty # if not stock_ticker or not bench_ticker: # raise ValueError("'Tickers' cannot be empty") # Assert start date input value format = "%Y-%m-%d" try: datetime.datetime.strptime(start_date, format) except ValueError: raise ValueError("You have entered an invalid start date! Try date formatted in YYYY-MM-DD.") # Assert end date input value try: datetime.datetime.strptime(end_date, format) except ValueError: raise ValueError("You have entered an invalid end date! Try date formatted in YYYY-MM-DD.") # Assert end date is later than start date format = "%Y-%m-%d" if(datetime.datetime.strptime(end_date, format) < datetime.datetime.strptime(start_date, format)): raise ValueError("You have entered an end date which is earlier than the start date! Try again.") except (TypeError, ValueError, NameError) as err: print(err) raise # Code to generate the visualization of profit try: stock_profit = percent_change(stock_ticker, start_date, end_date).reset_index() benchmark_profit = percent_change(benchmark_ticker, start_date, end_date).reset_index() profit_df = pd.merge(stock_profit, benchmark_profit, on="Date") profit_df.rename({'Price Change Percentage(%)_x': 'Profit Percent Stock', 'Price Change Percentage(%)_y': 'Profit Percent Benchmark'}, axis=1, inplace=True) # catch when dataframe is None except AttributeError: pass #Checks if the datatype of data frame is correct try: isinstance(profit_df, pd.DataFrame) except ValueError: raise ValueError("profit_df is not a pandas dataframe.") try: isinstance(stock_profit, pd.DataFrame) except ValueError: raise ValueError("stock_profit couldnot be converted to a pandas dataframe.") try: isinstance(benchmark_profit, pd.DataFrame) except ValueError: raise ValueError("Benchmark_profit couldnot be converted to a pandas dataframe.") # Code to plot the profit visualization chart = alt.Chart(profit_df, title='Profit Percent trend of Stock vs Benchmark ticker').mark_line().transform_fold( fold=['Profit Percent Stock', 'Profit Percent Benchmark'], as_=['company', 'Profit Percent'] ).encode( x='Date:T', y = alt.Y('Profit Percent:Q', axis=alt.Axis(format='$.2f')), color=alt.Color('company:N', scale= alt.Scale(domain=['Profit Percent Stock','Profit Percent Benchmark'], range=['red', 'blue'])), tooltip=[alt.Tooltip('Profit Percent Stock'),alt.Tooltip('Profit Percent Benchmark')] ) return chart def volume_change(stock_ticker, start_date, end_date): """ Calculates the daily trading volume change status of a stock within a given period of time Parameters ---------- stock_ticker : string Ticker of the stock such as 'AAPL' start_date : string Initial date for data extraction end_date : string Final date for stock analysis Returns -------- DataFrame A data frame with dates and their corresponding trading volume and changes Examples -------- >>> volume_change('AAPL', '2021-01-01', '2022-01-01') Date Volume Volume_Change 01-01-2021 1000 Nan 01-02-2021 2000 Increase 01-03-2021 3000 Increase 01-04-2021 2500 Decrease ... 12-31-2021 4000 Increase 01-01-2022 5000 Increase """ # Assert ticker value ticker = yf.Ticker(stock_ticker) if(ticker.info["regularMarketPrice"] == None): raise NameError("You have entered an invalid stock ticker! Try again.") # Assert date value format = "%Y-%m-%d" try: datetime.datetime.strptime(start_date, format) except ValueError: raise ValueError("You have entered an invalid start date! Try again.") try: datetime.datetime.strptime(end_date, format) except ValueError: raise ValueError("You have entered an invalid end date! Try again.") df = pdr.get_data_yahoo(stock_ticker, start=start_date, end=end_date).reset_index() # Assert correct data fetched try: isinstance(df, pd.DataFrame) except ValueError: raise ValueError("Your input can't be converted to a pandas dataframe.") df["Price_diff"] = df["Close"].diff().to_frame() df['Price_change'] = np.select([df["Price_diff"] > 0, df["Price_diff"] < 0], ["Increase", "Decrease"], default = np.nan) return df[["Date", "Volume", "Price_change"]] def volume_viz(stock_ticker, start_date, end_date): """ Visualize the daily trading volume of a stock using bar plot within a given period of time Parameters ---------- stock_ticker : string Ticker of the stock such as 'AAPL' start_date : string Initial date for data extraction end_date : string Final date for stock analysis Returns -------- Chart Create interactive bar plot to view the volume change Examples -------- >>> volume_viz('AAPL', '2021-01-01', '2022-01-01') """ try: vdf = volume_change(stock_ticker, start_date, end_date) # catch when dataframe is None except AttributeError: raise AttributeError("Invalid volume change input!") vdf_increase = vdf.loc[vdf['Price_change']=='Increase'] vdf_decrease = vdf.loc[vdf['Price_change']=='Decrease'] fig = go.Figure() fig.add_trace(go.Bar(x=vdf_increase['Date'], y=vdf_increase['Volume'], base=0, marker_color='green', name='Price Increase')) fig.add_trace(go.Bar(x=vdf_decrease['Date'], y=vdf_decrease['Volume'], base=0, marker_color='red', name='Price Decrease' )) return fig
35.572848
164
0.626361
import plotly.graph_objects as go import altair as alt import pandas as pd import numpy as np import yfinance as yf import pandas_datareader as pdr import datetime import warnings alt.renderers.enable('altair_viewer') def percent_change(stock_ticker, start_date, end_date): ticker = yf.Ticker(stock_ticker) if(ticker.info["regularMarketPrice"] == None): raise NameError("You have entered an invalid stock ticker! Try again.") format = "%Y-%m-%d" try: datetime.datetime.strptime(start_date, format) except ValueError: raise ValueError("You have entered an invalid start date! Try date formatted in YYYY-MM-DD.") try: datetime.datetime.strptime(end_date, format) except ValueError: raise ValueError("You have entered an invalid end date! Try date formatted in YYYY-MM-DD.") format = "%Y-%m-%d" if(datetime.datetime.strptime(end_date, format) < datetime.datetime.strptime(start_date, format)): raise ValueError("You have entered an end date which is earlier than the start date! Try again.") data = yf.download(stock_ticker, start=start_date, end=end_date) data = data.drop(columns={'Open', 'High', 'Low', 'Adj Close', 'Volume'}) for i in range(1,len(data)): data.iloc[i,:] = round((data.iloc[i,:] - data.iloc[0,:])/data.iloc[0,:]*100, 3) data.iloc[0,:] = round((data.iloc[0,:] - data.iloc[0,:])/data.iloc[0,:]*100, 3) data = data.rename(columns={"Close": "Price Change Percentage(%)"}) return pd.DataFrame(data) def profit_viz(stock_ticker, start_date , end_date, benchmark_ticker): ticker = yf.Ticker(stock_ticker) bench_ticker = yf.Ticker(benchmark_ticker) try: if(ticker.info["regularMarketPrice"] == None): raise NameError("You have entered an invalid stock ticker! Try again.") if type(stock_ticker) != str: raise TypeError("stock_ticker should be of type string.") if(bench_ticker.info["regularMarketPrice"] == None): raise NameError("You have entered an invalid benchmark ticker! Try again.") if type(benchmark_ticker) != str: raise TypeError("Bench Mark ticker should be of type string.") etime.strptime(start_date, format) except ValueError: raise ValueError("You have entered an invalid start date! Try date formatted in YYYY-MM-DD.") try: datetime.datetime.strptime(end_date, format) except ValueError: raise ValueError("You have entered an invalid end date! Try date formatted in YYYY-MM-DD.") format = "%Y-%m-%d" if(datetime.datetime.strptime(end_date, format) < datetime.datetime.strptime(start_date, format)): raise ValueError("You have entered an end date which is earlier than the start date! Try again.") except (TypeError, ValueError, NameError) as err: print(err) raise try: stock_profit = percent_change(stock_ticker, start_date, end_date).reset_index() benchmark_profit = percent_change(benchmark_ticker, start_date, end_date).reset_index() profit_df = pd.merge(stock_profit, benchmark_profit, on="Date") profit_df.rename({'Price Change Percentage(%)_x': 'Profit Percent Stock', 'Price Change Percentage(%)_y': 'Profit Percent Benchmark'}, axis=1, inplace=True) except AttributeError: pass try: isinstance(profit_df, pd.DataFrame) except ValueError: raise ValueError("profit_df is not a pandas dataframe.") try: isinstance(stock_profit, pd.DataFrame) except ValueError: raise ValueError("stock_profit couldnot be converted to a pandas dataframe.") try: isinstance(benchmark_profit, pd.DataFrame) except ValueError: raise ValueError("Benchmark_profit couldnot be converted to a pandas dataframe.") chart = alt.Chart(profit_df, title='Profit Percent trend of Stock vs Benchmark ticker').mark_line().transform_fold( fold=['Profit Percent Stock', 'Profit Percent Benchmark'], as_=['company', 'Profit Percent'] ).encode( x='Date:T', y = alt.Y('Profit Percent:Q', axis=alt.Axis(format='$.2f')), color=alt.Color('company:N', scale= alt.Scale(domain=['Profit Percent Stock','Profit Percent Benchmark'], range=['red', 'blue'])), tooltip=[alt.Tooltip('Profit Percent Stock'),alt.Tooltip('Profit Percent Benchmark')] ) return chart def volume_change(stock_ticker, start_date, end_date): ticker = yf.Ticker(stock_ticker) if(ticker.info["regularMarketPrice"] == None): raise NameError("You have entered an invalid stock ticker! Try again.") format = "%Y-%m-%d" try: datetime.datetime.strptime(start_date, format) except ValueError: raise ValueError("You have entered an invalid start date! Try again.") try: datetime.datetime.strptime(end_date, format) except ValueError: raise ValueError("You have entered an invalid end date! Try again.") df = pdr.get_data_yahoo(stock_ticker, start=start_date, end=end_date).reset_index() try: isinstance(df, pd.DataFrame) except ValueError: raise ValueError("Your input can't be converted to a pandas dataframe.") df["Price_diff"] = df["Close"].diff().to_frame() df['Price_change'] = np.select([df["Price_diff"] > 0, df["Price_diff"] < 0], ["Increase", "Decrease"], default = np.nan) return df[["Date", "Volume", "Price_change"]] def volume_viz(stock_ticker, start_date, end_date): try: vdf = volume_change(stock_ticker, start_date, end_date) # catch when dataframe is None except AttributeError: raise AttributeError("Invalid volume change input!") vdf_increase = vdf.loc[vdf['Price_change']=='Increase'] vdf_decrease = vdf.loc[vdf['Price_change']=='Decrease'] fig = go.Figure() fig.add_trace(go.Bar(x=vdf_increase['Date'], y=vdf_increase['Volume'], base=0, marker_color='green', name='Price Increase')) fig.add_trace(go.Bar(x=vdf_decrease['Date'], y=vdf_decrease['Volume'], base=0, marker_color='red', name='Price Decrease' )) return fig
true
true
1c3423a4b26e69f635ef04ef776574436569154e
2,900
py
Python
npxconv.py
LeeTehi/nnvolterra
d6a084d2f5b4b716423cb4b952cf58a09ea84c23
[ "MIT" ]
1
2021-11-28T17:16:57.000Z
2021-11-28T17:16:57.000Z
npxconv.py
LeeTehi/nnvolterra
d6a084d2f5b4b716423cb4b952cf58a09ea84c23
[ "MIT" ]
null
null
null
npxconv.py
LeeTehi/nnvolterra
d6a084d2f5b4b716423cb4b952cf58a09ea84c23
[ "MIT" ]
null
null
null
import libnpxconv as libx import numpy as np # params for libx (sedt, kernel, srcx, /, padleft, stride) def conv_ordern(ker, *src, oshape=None, padleft=0, stride=1): if len(src) == 1: src = src[0] if oshape is None: if isinstance(src, (list, tuple)): assert np.ndim(ker) == len(src) oshape = np.min([np.min(s.shape) for s in src]) else: oshape = np.min(src.shape) ks = np.max(ker.shape) if oshape > ks: oshape = (oshape - ks) // stride + 1 out = np.zeros(oshape, dtype=ker.dtype) if isinstance(src, list): src = [np.ascontiguousarray(x) for x in src] else: src = np.ascontiguousarray(src) ker = np.ascontiguousarray(ker) libx.conv1d_order_n(out, ker, src, padleft, stride) return out def outerconv(g, *hx, oshape=None, padleft=0, stride=1): if isinstance(hx[0], (list, tuple)) and len(hx) == 1: hx = hx[0] assert np.ndim(g) == len(hx), \ f"mismatch ndim(g) = {np.ndim(g)}, len(hx) = {len(hx)}" if oshape is None: oshape = [] for i, h in enumerate(hx): gsi = g.shape[i] for hsi in h.shape: oshape.append(hsi + stride*gsi-stride) out = np.zeros(oshape, dtype=g.dtype) g = np.ascontiguousarray(g) hx = [np.ascontiguousarray(h) for h in hx] libx.outerconv_nm(out, g, hx, padleft, stride) return out def outerconv_diag(g, *hx, oshape=None, padleft=0, stride=1): # in the case of passing [x, y, z, ...] if isinstance(hx[0], (list, tuple)) and len(hx) == 1: hx = hx[0] assert np.ndim(g) == 1, "only 1D signal supported" assert len(hx) >= 1, "length of hx must grater than or equals to 1" if oshape is None: oshape = [] for h in hx: for hsi in h.shape: oshape.append(hsi+g.shape[0]-1) out = np.zeros(oshape, dtype=g.dtype) g = np.ascontiguousarray(g) hx = [np.ascontiguousarray(h) for h in hx] libx.outerconv_diagonal_nm(out, g, hx, padleft, stride) return out def outerconv_2d(g, h, stride=1): """g @ h Only support Order-1 2-dimensional outer convolution <-> this equals to convTranspose2D """ assert np.ndim(g) == 2 and np.ndim(h) == 2 if stride > 1: _hs = h.shape _hp = _hs[0] * (stride - 1), _hs[1] * (stride - 1) h = np.pad(h, [(0, _hp[0]), (0, _hp[1])])\ .reshape(stride, _hs[0], stride, _hs[1])\ .transpose(1, 0, 3, 2).reshape(stride*_hs[0], stride*_hs[1]) psg = h.shape[1] - 1 psh = g.shape[1] - 1 pg = np.pad(g, [(0, 0), (0, psg)]).reshape(-1) ph = np.pad(h, [(0, 0), (0, psh)]).reshape(-1) goh = outerconv(pg, ph, stride=1) glen = g.shape[0] + h.shape[0]- 1 R = glen * (g.shape[1] + h.shape[1] - 1) return goh[0:R].reshape(glen, -1)
29
72
0.553103
import libnpxconv as libx import numpy as np def conv_ordern(ker, *src, oshape=None, padleft=0, stride=1): if len(src) == 1: src = src[0] if oshape is None: if isinstance(src, (list, tuple)): assert np.ndim(ker) == len(src) oshape = np.min([np.min(s.shape) for s in src]) else: oshape = np.min(src.shape) ks = np.max(ker.shape) if oshape > ks: oshape = (oshape - ks) // stride + 1 out = np.zeros(oshape, dtype=ker.dtype) if isinstance(src, list): src = [np.ascontiguousarray(x) for x in src] else: src = np.ascontiguousarray(src) ker = np.ascontiguousarray(ker) libx.conv1d_order_n(out, ker, src, padleft, stride) return out def outerconv(g, *hx, oshape=None, padleft=0, stride=1): if isinstance(hx[0], (list, tuple)) and len(hx) == 1: hx = hx[0] assert np.ndim(g) == len(hx), \ f"mismatch ndim(g) = {np.ndim(g)}, len(hx) = {len(hx)}" if oshape is None: oshape = [] for i, h in enumerate(hx): gsi = g.shape[i] for hsi in h.shape: oshape.append(hsi + stride*gsi-stride) out = np.zeros(oshape, dtype=g.dtype) g = np.ascontiguousarray(g) hx = [np.ascontiguousarray(h) for h in hx] libx.outerconv_nm(out, g, hx, padleft, stride) return out def outerconv_diag(g, *hx, oshape=None, padleft=0, stride=1): if isinstance(hx[0], (list, tuple)) and len(hx) == 1: hx = hx[0] assert np.ndim(g) == 1, "only 1D signal supported" assert len(hx) >= 1, "length of hx must grater than or equals to 1" if oshape is None: oshape = [] for h in hx: for hsi in h.shape: oshape.append(hsi+g.shape[0]-1) out = np.zeros(oshape, dtype=g.dtype) g = np.ascontiguousarray(g) hx = [np.ascontiguousarray(h) for h in hx] libx.outerconv_diagonal_nm(out, g, hx, padleft, stride) return out def outerconv_2d(g, h, stride=1): assert np.ndim(g) == 2 and np.ndim(h) == 2 if stride > 1: _hs = h.shape _hp = _hs[0] * (stride - 1), _hs[1] * (stride - 1) h = np.pad(h, [(0, _hp[0]), (0, _hp[1])])\ .reshape(stride, _hs[0], stride, _hs[1])\ .transpose(1, 0, 3, 2).reshape(stride*_hs[0], stride*_hs[1]) psg = h.shape[1] - 1 psh = g.shape[1] - 1 pg = np.pad(g, [(0, 0), (0, psg)]).reshape(-1) ph = np.pad(h, [(0, 0), (0, psh)]).reshape(-1) goh = outerconv(pg, ph, stride=1) glen = g.shape[0] + h.shape[0]- 1 R = glen * (g.shape[1] + h.shape[1] - 1) return goh[0:R].reshape(glen, -1)
true
true