hexsha
stringlengths
40
40
size
int64
7
1.04M
ext
stringclasses
10 values
lang
stringclasses
1 value
max_stars_repo_path
stringlengths
4
247
max_stars_repo_name
stringlengths
4
125
max_stars_repo_head_hexsha
stringlengths
40
78
max_stars_repo_licenses
listlengths
1
10
max_stars_count
int64
1
368k
max_stars_repo_stars_event_min_datetime
stringlengths
24
24
max_stars_repo_stars_event_max_datetime
stringlengths
24
24
max_issues_repo_path
stringlengths
4
247
max_issues_repo_name
stringlengths
4
125
max_issues_repo_head_hexsha
stringlengths
40
78
max_issues_repo_licenses
listlengths
1
10
max_issues_count
int64
1
116k
max_issues_repo_issues_event_min_datetime
stringlengths
24
24
max_issues_repo_issues_event_max_datetime
stringlengths
24
24
max_forks_repo_path
stringlengths
4
247
max_forks_repo_name
stringlengths
4
125
max_forks_repo_head_hexsha
stringlengths
40
78
max_forks_repo_licenses
listlengths
1
10
max_forks_count
int64
1
105k
max_forks_repo_forks_event_min_datetime
stringlengths
24
24
max_forks_repo_forks_event_max_datetime
stringlengths
24
24
content
stringlengths
1
1.04M
avg_line_length
float64
1.77
618k
max_line_length
int64
1
1.02M
alphanum_fraction
float64
0
1
original_content
stringlengths
7
1.04M
filtered:remove_function_no_docstring
int64
-102
942k
filtered:remove_class_no_docstring
int64
-354
977k
filtered:remove_delete_markers
int64
0
60.1k
3e9e7b05c50154f1786818941676949cdcb37843
10,027
py
Python
snp_pipeline/scripts/snp_subsample.py
kelly-sovacool/tiger_salamander_project
fa795f4488aab73564d563c268f1c88969bd2abc
[ "MIT" ]
1
2022-01-31T08:01:12.000Z
2022-01-31T08:01:12.000Z
snp_pipeline/scripts/snp_subsample.py
kelly-sovacool/tiger_salamander_project
fa795f4488aab73564d563c268f1c88969bd2abc
[ "MIT" ]
null
null
null
snp_pipeline/scripts/snp_subsample.py
kelly-sovacool/tiger_salamander_project
fa795f4488aab73564d563c268f1c88969bd2abc
[ "MIT" ]
null
null
null
#!/usr/local/bin/python3 """ Author: Kelly Sovacool Email: kellysovacool@uky.edu 28 Sep 2017 Usage: snp_subsample.py <snp-sites-dir> <output-filename-base> [--abundance-filter=<percent-cutoff> --output-filtered-fasta-dir=<filtered_dir> --skip-filter --num_subsamples=<num> --all-snps-all-loci --missing-cutoff=<percent-cutoff> --output-format=<fasta-or-strx>] snp_subsample.py --help Options: -h --help display this incredibly helpful message. --abundance-filter=<percent-cutoff> filter out SNPs below a percent abundance cutoff [default: 0.05]. --missing-cutoff=<percent-cutoff> filter out SNP sites with more than <percent-cutoff> of individuals missing data [default: 0.5]. --skip-filter skip the filtering step (e.g. if using already-filtered data). --num_subsamples=<num> number of subsamples [default: 1]. --all-snps-all-loci output a file containing all snps from all loci. --output-filtered-fasta-dir=<filtered_dir> output filtered snp-sites fastas to a directory. --output-format=<fasta-or-strx> output format for subsamples [default: strx]. """ import Bio.Seq import Bio.SeqIO import docopt import os import random # TODO: Redesign: clean up main fcn, better OOP design strx_extension = "_strx.txt" fasta_extension = ".fna" if __name__ == "__main__": arguments = docopt.docopt(__doc__) for arg in ("<snp-sites-dir>", "--output-filtered-fasta-dir"): if arguments[arg]: arguments[arg] = check_directory(arguments[arg]) main(arguments)
43.406926
263
0.61863
#!/usr/local/bin/python3 """ Author: Kelly Sovacool Email: kellysovacool@uky.edu 28 Sep 2017 Usage: snp_subsample.py <snp-sites-dir> <output-filename-base> [--abundance-filter=<percent-cutoff> --output-filtered-fasta-dir=<filtered_dir> --skip-filter --num_subsamples=<num> --all-snps-all-loci --missing-cutoff=<percent-cutoff> --output-format=<fasta-or-strx>] snp_subsample.py --help Options: -h --help display this incredibly helpful message. --abundance-filter=<percent-cutoff> filter out SNPs below a percent abundance cutoff [default: 0.05]. --missing-cutoff=<percent-cutoff> filter out SNP sites with more than <percent-cutoff> of individuals missing data [default: 0.5]. --skip-filter skip the filtering step (e.g. if using already-filtered data). --num_subsamples=<num> number of subsamples [default: 1]. --all-snps-all-loci output a file containing all snps from all loci. --output-filtered-fasta-dir=<filtered_dir> output filtered snp-sites fastas to a directory. --output-format=<fasta-or-strx> output format for subsamples [default: strx]. """ import Bio.Seq import Bio.SeqIO import docopt import os import random # TODO: Redesign: clean up main fcn, better OOP design strx_extension = "_strx.txt" fasta_extension = ".fna" def main(args): base, fn = os.path.split(args['<output-filename-base>']) if not os.path.isdir(base): os.mkdir(base) all_individual_ids = set() for fasta_filename in os.listdir(args['<snp-sites-dir>']): # build set of individual ids if fasta_filename.endswith('.fna'): with open(args['<snp-sites-dir>'] + fasta_filename, 'r') as infile: all_individual_ids.update(record.id for record in Bio.SeqIO.parse(infile, 'fasta')) bad_individual_ids = set() for id in all_individual_ids: # throw out individuals that aren't haplotyped (usually they're not real individuals) id_no_number = id.split('_')[0] if id_no_number + '_1' not in all_individual_ids or id_no_number + '_2' not in all_individual_ids: bad_individual_ids.add(id) all_individual_ids.difference_update(bad_individual_ids) # TODO: save loci as jsonpickles to allow quick reloading loci = Loci() # build loci for fasta_filename in sorted(os.listdir(args['<snp-sites-dir>'])): with open(args['<snp-sites-dir>'] + fasta_filename, 'r') as infile: locus_id = fasta_filename.split('.')[0] locus = Locus(locus_id, Bio.SeqIO.parse(infile, 'fasta'), all_individual_ids, bad_individual_ids) if not args['--skip-filter']: locus.filter(float(args['--abundance-filter']), float(args['--missing-cutoff'])) if args['--output-filtered-fasta-dir']: with open(args['--output-filtered-fasta-dir'] + fasta_filename, 'w') as filtered_fasta: for seq_id, sequence in locus.individuals.items(): filtered_fasta.write('>' + seq_id + '\n') filtered_fasta.write(sequence + '\n') loci.append(locus) output_file_extension = output_format_extension(args['--output-format']) if args['--num_subsamples']: # take subsample(s) for number in range(1, int(args['--num_subsamples']) + 1): loci.new_random_poly_sites() with open(args['<output-filename-base>'] + str(number) + output_file_extension, 'w') as outfile: for id in sorted(all_individual_ids): line = id + '\t' if output_file_extension != strx_extension else id.split('_')[0] + '\t' for locus in loci: nuc = locus.individuals[id][locus.random_poly_site] if id in locus.individuals else '-' if output_file_extension == strx_extension: nuc = nucleotide_to_structure(nuc) line += nuc + '\t' line += '\n' outfile.write(line) if args['--all-snps-all-loci']: with open(os.path.join(os.path.split(args['<output-filename-base>'])[0], 'all-snps-all-loci' + output_file_extension), 'w') as outfile: for id in sorted(all_individual_ids): line = id + '\t' if output_file_extension != strx_extension else id.split('_')[0] + '\t' for locus in loci: seq = locus.individuals[id] if id in locus.individuals else '-'*len(locus.polymorphic_sites) if output_file_extension == strx_extension: strx_seq = '' for nuc in seq: strx_seq += nucleotide_to_structure(nuc) + '\t' line += strx_seq else: line += seq line += '\n' outfile.write(line) class Loci(list): def __init__(self, iterable=None): if iterable: super().__init__(iterable) else: super().__init__() def filter(self, abundance_cutoff=0.05, missing_cutoff=0.5): for locus in self: locus.filter(abundance_cutoff, missing_cutoff) def new_random_poly_sites(self): for locus in self: locus.new_random_poly_site() class Locus: def __init__(self, id, seq_records, all_individual_ids, bad_individual_ids): self.id = id self.individuals = {seq_rec.id: str(seq_rec.seq) for seq_rec in seq_records} # id: sequence length = max(len(seq) for seq in self.individuals.values()) for missing_id in all_individual_ids - set(self.individuals.keys()): #print('individual', missing_id, 'not in locus', self.id, '-- filling in nucleotides as dashes') self.individuals[missing_id] = '-' * length for bad_id in bad_individual_ids: self.individuals.pop(bad_id, False) self.polymorphic_sites = [] first_individual = True for indiv_id, sequence in self.individuals.items(): i = 0 for nucleotide in sequence: if first_individual: self.polymorphic_sites.append(PolymorphicSite()) if nucleotide not in self.polymorphic_sites[i].snps and nucleotide in SNP.nucleotides: self.polymorphic_sites[i].snps[nucleotide] = SNP(nucleotide) self.polymorphic_sites[i].snps[nucleotide].individual_ids.add(indiv_id) i += 1 first_individual = False self.random_poly_site = None self.new_random_poly_site() # use same poly site for all subsamples in this run def __str__(self): return self.id def filter(self, abundance_cutoff, missing_cutoff): original_count_sites = len(self.polymorphic_sites) removed_sites = 0 i = 0 while i < (original_count_sites - removed_sites): pmsite = self.polymorphic_sites[i] if pmsite.has_low_abundance(len(self.individuals), abundance_cutoff) or pmsite.number_individuals_missing_data >= missing_cutoff: self.polymorphic_sites.pop(i) for id, sequence in self.individuals.items(): self.individuals[id] = sequence[:i] + sequence[i+1:] # update sequence for individuals removed_sites += 1 i += 1 print(removed_sites, ' SNP sites thrown out for contig ', self.id, '. ', len(self.polymorphic_sites), ' SNP sites remain.', sep='') def new_random_poly_site(self): self.random_poly_site = random.randrange(len(self.polymorphic_sites)) class PolymorphicSite: def __init__(self): self.snps = {} # nucleotide: SNP object def __len__(self): return len(self.snps) def has_low_abundance(self, total_individuals, abundance_cutoff): most_popular_snp = max(self.snps.values(), key=lambda snp: len(snp.individual_ids)) others = set(self.snps.values()) others.remove(most_popular_snp) num_individuals = len({indiv for snp in others for indiv in snp.individual_ids}) return num_individuals / total_individuals <= abundance_cutoff @property def number_individuals_missing_data(self): individuals = set() for nuc, snp in self.snps.items(): if nuc not in SNP.nucleotides: individuals.update(snp.individual_ids) return len(individuals) @property def indel_or_missing_exists(self): return bool(len({nuc for nuc in self.snps if nuc == '-'})) class SNP: nucleotides = {'A': 1, 'C': 2, 'G': 3, 'T': 4} def __init__(self, nucleotide, individual_ids=None): super().__init__() self.nucleotide = nucleotide self.individual_ids = {id for id in individual_ids} if individual_ids else set() def __hash__(self): return hash((self.nucleotide, tuple(sorted(self.individual_ids)))) def output_format_extension(format): if format == 'strx': extension = strx_extension elif format == 'fasta': extension = fasta_extension else: raise ValueError('unrecognized output format {}'.format(format)) return extension def nucleotide_to_structure(nucleotide): if nucleotide in SNP.nucleotides: structure_int = SNP.nucleotides[nucleotide] else: structure_int = -9 return str(structure_int) def check_directory(dir_name): if not os.path.exists(dir_name): os.mkdir(dir_name) if not dir_name.endswith('/'): dir_name = dir_name + '/' return dir_name if __name__ == "__main__": arguments = docopt.docopt(__doc__) for arg in ("<snp-sites-dir>", "--output-filtered-fasta-dir"): if arguments[arg]: arguments[arg] = check_directory(arguments[arg]) main(arguments)
7,744
245
371
d17a5c18fe9d56b7bb799e31cc9d3d646de88110
2,312
py
Python
tests/test_models.py
rekt-hard/invenio-userprofiles
69cbe381a35aca98d398a9673af351b672d41b70
[ "MIT" ]
null
null
null
tests/test_models.py
rekt-hard/invenio-userprofiles
69cbe381a35aca98d398a9673af351b672d41b70
[ "MIT" ]
null
null
null
tests/test_models.py
rekt-hard/invenio-userprofiles
69cbe381a35aca98d398a9673af351b672d41b70
[ "MIT" ]
null
null
null
# -*- coding: utf-8 -*- # # This file is part of Invenio. # Copyright (C) 2015-2018 CERN. # # Invenio is free software; you can redistribute it and/or modify it # under the terms of the MIT License; see LICENSE file for more details. """Tests for user profile models.""" import pytest from invenio_accounts.models import User from invenio_db import db from sqlalchemy.exc import IntegrityError from test_validators import test_usernames from invenio_userprofiles import InvenioUserProfiles, UserProfile def test_userprofiles(app): """Test UserProfile model.""" profile = UserProfile(User()) # Check the username validator works on the model profile.username = test_usernames['valid'] with pytest.raises(ValueError): profile.username = test_usernames['invalid_characters'] with pytest.raises(ValueError): profile.username = test_usernames['invalid_begins_with_number'] # Test non-validated attributes profile.first_name = 'Test' profile.last_name = 'User' assert profile.first_name == 'Test' assert profile.last_name == 'User' def test_case_insensitive_username(app): """Test case-insensitive uniqueness.""" with app.app_context(): with db.session.begin_nested(): u1 = User(email='test@test.org', username="INFO") db.session.add(u1) u2 = User(email='test2@test.org', username="info") db.session.add(u2) pytest.raises(IntegrityError, db.session.commit) def test_case_preserving_username(app): """Test that username preserves the case.""" with app.app_context(): with db.session.begin_nested(): u1 = User(email='test@test.org', username="InFo") db.session.add(u1) db.session.commit() profile = UserProfile.get_by_username('info') assert profile.username == 'InFo' def test_delete_cascade(app): """Test that deletion of user, also removes profile.""" with app.app_context(): with db.session.begin_nested(): u = User(email='test@test.org', username="InFo") db.session.add(u) db.session.commit() assert UserProfile.get_by_userid(u.id) is not None db.session.delete(u) db.session.commit() assert UserProfile.get_by_userid(u.id) is None
31.671233
72
0.679498
# -*- coding: utf-8 -*- # # This file is part of Invenio. # Copyright (C) 2015-2018 CERN. # # Invenio is free software; you can redistribute it and/or modify it # under the terms of the MIT License; see LICENSE file for more details. """Tests for user profile models.""" import pytest from invenio_accounts.models import User from invenio_db import db from sqlalchemy.exc import IntegrityError from test_validators import test_usernames from invenio_userprofiles import InvenioUserProfiles, UserProfile def test_userprofiles(app): """Test UserProfile model.""" profile = UserProfile(User()) # Check the username validator works on the model profile.username = test_usernames['valid'] with pytest.raises(ValueError): profile.username = test_usernames['invalid_characters'] with pytest.raises(ValueError): profile.username = test_usernames['invalid_begins_with_number'] # Test non-validated attributes profile.first_name = 'Test' profile.last_name = 'User' assert profile.first_name == 'Test' assert profile.last_name == 'User' def test_case_insensitive_username(app): """Test case-insensitive uniqueness.""" with app.app_context(): with db.session.begin_nested(): u1 = User(email='test@test.org', username="INFO") db.session.add(u1) u2 = User(email='test2@test.org', username="info") db.session.add(u2) pytest.raises(IntegrityError, db.session.commit) def test_case_preserving_username(app): """Test that username preserves the case.""" with app.app_context(): with db.session.begin_nested(): u1 = User(email='test@test.org', username="InFo") db.session.add(u1) db.session.commit() profile = UserProfile.get_by_username('info') assert profile.username == 'InFo' def test_delete_cascade(app): """Test that deletion of user, also removes profile.""" with app.app_context(): with db.session.begin_nested(): u = User(email='test@test.org', username="InFo") db.session.add(u) db.session.commit() assert UserProfile.get_by_userid(u.id) is not None db.session.delete(u) db.session.commit() assert UserProfile.get_by_userid(u.id) is None
0
0
0
881d4e01c75cf326258781678b4a1ae10cc19b02
3,236
py
Python
libraries/logger.py
tede12/DCNFT
21871b5abec0498ab4402eae0939a4c212025f53
[ "MIT" ]
3
2021-11-06T13:17:07.000Z
2022-03-14T00:01:03.000Z
libraries/logger.py
tede12/DCNFT
21871b5abec0498ab4402eae0939a4c212025f53
[ "MIT" ]
null
null
null
libraries/logger.py
tede12/DCNFT
21871b5abec0498ab4402eae0939a4c212025f53
[ "MIT" ]
null
null
null
import datetime import logging import time from colorama import Fore logging.getLogger('filelock').propagate = False logging.basicConfig( # filename='logger.log', level=logging.INFO, format='%(message)s' ) logger = Logger(classic=True, logger_name='Default-Logger')
29.962963
93
0.545426
import datetime import logging import time from colorama import Fore logging.getLogger('filelock').propagate = False logging.basicConfig( # filename='logger.log', level=logging.INFO, format='%(message)s' ) class Logger: def __init__( self, logger_name='Unknown', classic=False, normal=False ): self.logger_name = logger_name self.classic = classic self.normal = normal self.last_log = None self.logger = logging.getLogger('Logger') @staticmethod def sleep(timeout): time.sleep(timeout) def log(self, message, status, *args, **kwargs): # Printing Exceptions Error if not str(message) and isinstance(message, object) and not isinstance(message, str): attr = str(type(message).__name__) else: attr = '' message = str(message) + attr if status == 'info': status_color = Fore.WHITE elif status == 'status': status_color = Fore.LIGHTYELLOW_EX elif status == 'warning': status_color = Fore.YELLOW elif status == 'success': status_color = Fore.BLUE elif status == 'error': status_color = Fore.RED elif status == 'debug': status_color = Fore.GREEN elif status == 'checkout': status_color = Fore.LIGHTBLUE_EX else: status_color = Fore.CYAN # MODE 1 if self.classic: if status in ['error', 'warning', 'debug']: mess = f'[{status.upper()}]:{status_color} {message}{Fore.RESET}' else: mess = f'{status_color} {message}{Fore.RESET}' # MODE 2 elif self.normal: mess = f'[{datetime.datetime.now().strftime("%H:%M:%S")}][{status.upper()}]:' \ f'{status_color} {message}{Fore.RESET}' else: if kwargs.get('retry'): if isinstance(kwargs['retry'], float) or isinstance(kwargs['retry'], int): retry = kwargs['retry'] message = message + f' Retry in {retry} sec...' # Sleeping self.sleep(timeout=retry) else: message = message + f' Retry...' logger_ = f'{self.logger_name}' mess = f'[{datetime.datetime.now().strftime("%H:%M:%S.%f")}]' \ f'[{status.upper()}]{status_color}[{logger_}] => {message}{Fore.RESET}' self.logger.info(mess) def error(self, message, *args, **kwargs): self.log(message, 'error', *args, **kwargs) def info(self, message, *args, **kwargs): self.log(message, 'info', *args, **kwargs) def status(self, message, **kwargs): self.log(message, 'status', **kwargs) def success(self, message, *args, **kwargs): self.log(message, 'success', *args, **kwargs) def warning(self, message, *args, **kwargs): self.log(message, 'warning', *args, **kwargs) def debug(self, message, *args, **kwargs): self.log(message, 'debug', *args, **kwargs) logger = Logger(classic=True, logger_name='Default-Logger')
2,678
252
23
96fa01033fa1760e78f5335d4f5adf4376fecb7e
1,557
py
Python
test/train/test_train_pairwise_similarity_model.py
mski-iksm/redshells
1e956fed9b000ea3f6ba1c96e25d5dd953025155
[ "MIT" ]
null
null
null
test/train/test_train_pairwise_similarity_model.py
mski-iksm/redshells
1e956fed9b000ea3f6ba1c96e25d5dd953025155
[ "MIT" ]
null
null
null
test/train/test_train_pairwise_similarity_model.py
mski-iksm/redshells
1e956fed9b000ea3f6ba1c96e25d5dd953025155
[ "MIT" ]
null
null
null
import unittest from unittest.mock import MagicMock import luigi import pandas as pd from sklearn.ensemble import RandomForestClassifier from redshells.train import TrainPairwiseSimilarityModel if __name__ == '__main__': unittest.main()
29.942308
91
0.654464
import unittest from unittest.mock import MagicMock import luigi import pandas as pd from sklearn.ensemble import RandomForestClassifier from redshells.train import TrainPairwiseSimilarityModel class _DummyTask(luigi.Task): pass class TrainPairwiseSimilarityModelTest(unittest.TestCase): def setUp(self): self.input_data = dict() self.dump_data = None TrainPairwiseSimilarityModel.clear_instance_cache() def test_run(self): self.input_data['item2embedding'] = dict(i0=[1, 2], i1=[3, 4]) self.input_data['similarity_data'] = pd.DataFrame( dict(item1=['i0', 'i0', 'i1'], item2=['i0', 'i1', 'i1'], similarity=[1, 0, 1])) task = TrainPairwiseSimilarityModel( item2embedding_task=_DummyTask(), similarity_data_task=_DummyTask(), model_name='RandomForestClassifier', item0_column_name='item1', item1_column_name='item2', similarity_column_name='similarity') task.load = MagicMock(side_effect=self._load) task.dump = MagicMock(side_effect=self._dump) task.run() self.assertIsInstance(self.dump_data, RandomForestClassifier) def _load(self, *args, **kwargs): if 'target' in kwargs: return self.input_data.get(kwargs['target'], None) if len(args) > 0: return self.input_data.get(args[0], None) return self.input_data def _dump(self, *args): self.dump_data = args[0] if __name__ == '__main__': unittest.main()
1,103
54
153
43eaa90c3a6818bcb51d39cbf7858f129021fbc3
641
py
Python
tests/queued_scheduler_cancel.py
Gelbpunkt/aiosched
8bb46be71894c022ce4862212c39636c5789a181
[ "MIT" ]
18
2020-05-16T18:46:14.000Z
2022-03-19T18:12:16.000Z
tests/queued_scheduler_cancel.py
Gelbpunkt/aiosched
8bb46be71894c022ce4862212c39636c5789a181
[ "MIT" ]
2
2020-10-02T14:35:04.000Z
2021-12-27T20:47:16.000Z
tests/queued_scheduler_cancel.py
Gelbpunkt/aiosched
8bb46be71894c022ce4862212c39636c5789a181
[ "MIT" ]
4
2020-05-29T19:12:07.000Z
2021-04-13T13:12:10.000Z
import asyncio import sys sys.path.insert(0, ".") from aioscheduler import QueuedScheduler asyncio.run(main())
19.424242
49
0.659906
import asyncio import sys sys.path.insert(0, ".") from aioscheduler import QueuedScheduler async def work(n: int) -> None: await asyncio.sleep(60) print(f"I am doing heavy work: {n}") async def main() -> None: scheduler = QueuedScheduler() scheduler.start() tasks = [] for i in range(50): tasks.append(scheduler.schedule(work(i))) await asyncio.sleep(10) print(scheduler._tasks.qsize()) # Task is running print(scheduler.cancel(tasks[0])) # Task is scheduled print(scheduler.cancel(tasks[-1])) print(scheduler._cancelled) await asyncio.sleep(120) asyncio.run(main())
478
0
46
ed3567225d39db8ffdd0344dc4b4954ff74e2d7f
841
py
Python
FaceDetector.py
rcorvus/R2PY
bb06fba4e73f09095393813ec06dec0a9a49362f
[ "MIT" ]
4
2019-04-21T14:04:56.000Z
2019-04-22T16:32:17.000Z
FaceDetector.py
rcorvus/R2PY
bb06fba4e73f09095393813ec06dec0a9a49362f
[ "MIT" ]
null
null
null
FaceDetector.py
rcorvus/R2PY
bb06fba4e73f09095393813ec06dec0a9a49362f
[ "MIT" ]
null
null
null
import cv2
36.565217
101
0.585018
import cv2 class FaceDetector: def __init__(self, faceCascadePath): # load the face detector try: self.faceCascade = cv2.CascadeClassifier(faceCascadePath) except: print("CascadeClassifier failed to load") def detect(self, image, scaleFactor=1.1, minNeighbors=5, minSize=(30, 30)): # detect faces in the image try: rects = self.faceCascade.detectMultiScale(image, scaleFactor=scaleFactor, minNeighbors=minNeighbors, minSize=minSize, flags=cv2.CASCADE_SCALE_IMAGE) except: print("failure while trying to detect face in image") # return the rectangles representing boundinb # boxes around the faces return rects
756
-2
76
969efcfd98765aae0d9f785d6b09b86bc9087f0a
6,120
py
Python
Subreddit.py
LeBruitDesBots/airAnnuaire
fc03a8b38a9e5401bf09b9a3456bccdef158b03a
[ "0BSD" ]
null
null
null
Subreddit.py
LeBruitDesBots/airAnnuaire
fc03a8b38a9e5401bf09b9a3456bccdef158b03a
[ "0BSD" ]
null
null
null
Subreddit.py
LeBruitDesBots/airAnnuaire
fc03a8b38a9e5401bf09b9a3456bccdef158b03a
[ "0BSD" ]
1
2020-05-29T09:16:51.000Z
2020-05-29T09:16:51.000Z
# encoding: utf-8 from enum import Enum from datetime import datetime, timedelta import math import pprint from prawcore import exceptions import langdetect DAYS_IN_WEEK = 7 DAYS_IN_MONTH = 28 class Subreddit: """A class to retrieve and store information about subreddits""" def auto_update(self, reddit, post_limit=100, comment_limit=1000): """Automatically crawl the subreddit to update all possible info parameters: reddit: a praw instance post_limit: upper limit of posts parsed for activity metrics comment_limit: upper limit of comments parsed for activity metrics""" # FIXME: parse latest posts and comments for activity metrics try: sub = reddit.subreddit(self.name) except (exceptions.NotFound, exceptions.Redirect): self.status = SubredditStatus.DOESNT_EXIST return self._set_status(sub) if self.status not in [SubredditStatus.PUBLIC, SubredditStatus.RESTRICTED]: return self.is_nsfw = sub.over18 self.subscriber_count = sub.subscribers self.created_utc = sub.created_utc self.description = sub.public_description self.official_lang = sub.lang self.moderators = [mod.name for mod in sub.moderator()] self._analyse_submissions(sub, post_limit) self._analyse_comments(sub, comment_limit) return
31.06599
101
0.605065
# encoding: utf-8 from enum import Enum from datetime import datetime, timedelta import math import pprint from prawcore import exceptions import langdetect DAYS_IN_WEEK = 7 DAYS_IN_MONTH = 28 class SubredditStatus(Enum): UNKNOWN = 0 PUBLIC = 1 RESTRICTED = 2 QUARANTINED = 3 PRIVATE = 4 BANNED = 5 DOESNT_EXIST = 6 def __str__(self): return ['Statut inconnu', 'Public', 'Restreint', 'En quarantaine', 'Privé', 'Banni', '404'][self.value] class Subreddit: """A class to retrieve and store information about subreddits""" def __init__(self, name): self.name = name # Auto-retrieved properties self.status = SubredditStatus.UNKNOWN self.is_nsfw = False self.subscriber_count = 0 self.created_utc = 0 self.description = '' self.moderators = list() self.official_lang = '' self.post_in_month = None self.comments_in_week = None self.languages = dict() # Manual properties self.tags = list() self.display_name = '' self.auto_updated = None self.manu_updated = None def auto_update(self, reddit, post_limit=100, comment_limit=1000): """Automatically crawl the subreddit to update all possible info parameters: reddit: a praw instance post_limit: upper limit of posts parsed for activity metrics comment_limit: upper limit of comments parsed for activity metrics""" # FIXME: parse latest posts and comments for activity metrics try: sub = reddit.subreddit(self.name) except (exceptions.NotFound, exceptions.Redirect): self.status = SubredditStatus.DOESNT_EXIST return self._set_status(sub) if self.status not in [SubredditStatus.PUBLIC, SubredditStatus.RESTRICTED]: return self.is_nsfw = sub.over18 self.subscriber_count = sub.subscribers self.created_utc = sub.created_utc self.description = sub.public_description self.official_lang = sub.lang self.moderators = [mod.name for mod in sub.moderator()] self._analyse_submissions(sub, post_limit) self._analyse_comments(sub, comment_limit) return def _set_status(self, praw_sub): try: subreddit_type = praw_sub.subreddit_type except exceptions.NotFound: self.status = SubredditStatus.BANNED return except exceptions.Forbidden: # FIXME: Also catches quarantined subs - find a way to differentiate # quarantined and private subs. self.status = SubredditStatus.PRIVATE return except exceptions.Redirect: self.status = SubredditStatus.DOESNT_EXIST return else: if subreddit_type == 'public': self.status = SubredditStatus.PUBLIC elif subreddit_type == 'restricted': self.status = SubredditStatus.RESTRICTED else: self.status = SubredditStatus.UNKNOWN return def _analyse_submissions(self, praw_sub, post_limit): post_count = 0 limit_reached = False elapsed = None for submission in praw_sub.new(limit=post_limit): limit_reached = True elapsed = datetime.now() - datetime.fromtimestamp(submission.created_utc) if elapsed.days > DAYS_IN_MONTH: limit_reached = False break post_count += 1 self._analyse_lang(submission.title) if limit_reached: # extrapolate post count over DAYS_IN_MONTH period reference_delta = timedelta(days=DAYS_IN_MONTH) post_count = post_count * reference_delta.total_seconds() / elapsed.total_seconds() self.post_in_month = post_count return def _analyse_comments(self, praw_sub, comment_limit): comment_count = 0 limit_reached = False elapsed = None for comment in praw_sub.comments(limit=comment_limit): limit_reached = True elapsed = datetime.now() - datetime.fromtimestamp(comment.created_utc) if elapsed.days > DAYS_IN_WEEK: limit_reached = False break comment_count += 1 self._analyse_lang(comment.body) if limit_reached: # extrapolate post count over DAYS_IN_MONTH period reference_delta = timedelta(days=DAYS_IN_WEEK) comment_count = comment_count * reference_delta.total_seconds() / elapsed.total_seconds() self.comments_in_week = comment_count return def _analyse_lang(self, text): try: lang = langdetect.detect(text) except langdetect.lang_detect_exception.LangDetectException: return if lang in self.languages: self.languages[lang] += 1 else: self.languages[lang] = 1 def get_post_activity_score(self): if self.post_in_month is None: return None return math.log10(1+self.post_in_month * 9) def get_comment_activity_score(self): if self.comments_in_week is None: return None return math.log10(1+self.comments_in_week * 9) def get_activity_score(self): post_score = self.get_post_activity_score() comment_score = self.get_comment_activity_score() if post_score is None or comment_score is None: return return post_score + comment_score def get_langs(self, threshold): val = [] total = sum(self.languages.values()) for lang, count in self.languages.items(): if (count / total) > threshold: val.append(lang) return val def manu_update(self): pass
4,208
156
293
9012b66c9db87f7ba18fc946415ee83d451d1d15
7,247
py
Python
WORC/featureprocessing/Decomposition.py
MStarmans91/WORC
b6b8fc2ccb7d443a69b5ca20b1d6efb65b3f0fc7
[ "ECL-2.0", "Apache-2.0" ]
47
2018-01-28T14:08:15.000Z
2022-03-24T16:10:07.000Z
WORC/featureprocessing/Decomposition.py
JZK00/WORC
14e8099835eccb35d49b52b97c0be64ecca3809c
[ "ECL-2.0", "Apache-2.0" ]
13
2018-08-28T13:32:57.000Z
2020-10-26T16:35:59.000Z
WORC/featureprocessing/Decomposition.py
JZK00/WORC
14e8099835eccb35d49b52b97c0be64ecca3809c
[ "ECL-2.0", "Apache-2.0" ]
16
2017-11-13T10:53:36.000Z
2022-03-18T17:02:04.000Z
#!/usr/bin/env python # Copyright 2016-2021 Biomedical Imaging Group Rotterdam, Departments of # Medical Informatics and Radiology, Erasmus MC, Rotterdam, The Netherlands # # 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 matplotlib matplotlib.use('agg') import matplotlib.pyplot as plt import os import numpy as np from sklearn.decomposition import PCA, SparsePCA, KernelPCA from sklearn.manifold import TSNE from WORC.IOparser.file_io import load_features import WORC.IOparser.config_io_classifier as config_io from WORC.featureprocessing.Imputer import Imputer def Decomposition(features, patientinfo, config, output, label_type=None, verbose=True): """ Perform decompositions to two components of the feature space. Useage is similar to StatisticalTestFeatures. Parameters ---------- features: string, mandatory contains the paths to all .hdf5 feature files used. modalityname1=file1,file2,file3,... modalityname2=file1,... Thus, modalities names are always between a space and a equal sign, files are split by commas. We assume that the lists of files for each modality has the same length. Files on the same position on each list should belong to the same patient. patientinfo: string, mandatory Contains the path referring to a .txt file containing the patient label(s) and value(s) to be used for learning. See the Github Wiki for the format. config: string, mandatory path referring to a .ini file containing the parameters used for feature extraction. See the Github Wiki for the possible fields and their description. # TODO: outputs verbose: boolean, default True print final feature values and labels to command line or not. """ # Load variables from the config file config = config_io.load_config(config) # Create output folder if required if not os.path.exists(os.path.dirname(output)): os.makedirs(os.path.dirname(output)) if label_type is None: label_type = config['Labels']['label_names'] # Read the features and classification data print("Reading features and label data.") label_data, image_features =\ load_features(features, patientinfo, label_type) # Extract feature labels and put values in an array feature_labels = image_features[0][1] feature_values = np.zeros([len(image_features), len(feature_labels)]) for num, x in enumerate(image_features): feature_values[num, :] = x[0] # Detect NaNs, otherwise first feature imputation is required if any(np.isnan(a) for a in np.asarray(feature_values).flatten()): print('\t [WARNING] NaNs detected, applying median imputation') imputer = Imputer(missing_values=np.nan, strategy='median') imputer.fit(feature_values) feature_values = imputer.transform(feature_values) # ----------------------------------------------------------------------- # Perform decomposition print("Performing decompositions.") label_value = label_data['label'] label_name = label_data['label_name'] # Reduce to two components for plotting n_components = 2 for i_class, i_name in zip(label_value, label_name): classlabels = i_class.ravel() class1 = [i for j, i in enumerate(feature_values) if classlabels[j] == 1] class2 = [i for j, i in enumerate(feature_values) if classlabels[j] == 0] f = plt.figure(figsize=(20, 15)) # ------------------------------------------------------- # Fit PCA pca = PCA(n_components=n_components) pca.fit(feature_values) explained_variance_ratio = np.sum(pca.explained_variance_ratio_) class1_pca = pca.transform(class1) class2_pca = pca.transform(class2) # Plot PCA ax = plt.subplot(2, 3, 1) plt.subplots_adjust(hspace=0.3, wspace=0.2) ax.scatter(class1_pca[:, 0], class1_pca[:, 1], color='blue') ax.scatter(class2_pca[:, 0], class2_pca[:, 1], color='green') ax.set_title(f'PCA: {round(explained_variance_ratio, 3)} variance.') # ------------------------------------------------------- # Fit Sparse PCA pca = SparsePCA(n_components=n_components) pca.fit(feature_values) class1_pca = pca.transform(class1) class2_pca = pca.transform(class2) # Plot Sparse PCA ax = plt.subplot(2, 3, 2) plt.subplots_adjust(hspace=0.3, wspace=0.2) ax.scatter(class1_pca[:, 0], class1_pca[:, 1], color='blue') ax.scatter(class2_pca[:, 0], class2_pca[:, 1], color='green') ax.set_title('Sparse PCA.') # ------------------------------------------------------- # Fit Kernel PCA fnum = 3 for kernel in ['linear', 'poly', 'rbf']: try: pca = KernelPCA(n_components=n_components, kernel=kernel) pca.fit(feature_values) class1_pca = pca.transform(class1) class2_pca = pca.transform(class2) # Plot Sparse PCA ax = plt.subplot(2, 3, fnum) plt.subplots_adjust(hspace=0.3, wspace=0.2) ax.scatter(class1_pca[:, 0], class1_pca[:, 1], color='blue') ax.scatter(class2_pca[:, 0], class2_pca[:, 1], color='green') ax.set_title(('Kernel PCA: {} .').format(kernel)) fnum += 1 except ValueError as e: # Sometimes, a specific kernel does not work, just continue print(f'[Error] {e}: skipping kernel {kernel}.') continue # ------------------------------------------------------- # Fit t-SNE tSNE = TSNE(n_components=n_components) class_all = class1 + class2 class_all_tsne = tSNE.fit_transform(class_all) class1_tSNE = class_all_tsne[0:len(class1)] class2_tSNE = class_all_tsne[len(class1):] # Plot Sparse tSNE ax = plt.subplot(2, 3, 6) plt.subplots_adjust(hspace=0.3, wspace=0.2) ax.scatter(class1_tSNE[:, 0], class1_tSNE[:, 1], color='blue') ax.scatter(class2_tSNE[:, 0], class2_tSNE[:, 1], color='green') ax.set_title('t-SNE.') # ------------------------------------------------------- # Maximize figure to get correct spacings # mng = plt.get_current_fig_manager() # mng.resize(*mng.window.maxsize()) # High DTI to make sure we save the maximized image f.savefig(output, dpi=600) print(("Decomposition saved as {} !").format(output))
38.547872
81
0.613357
#!/usr/bin/env python # Copyright 2016-2021 Biomedical Imaging Group Rotterdam, Departments of # Medical Informatics and Radiology, Erasmus MC, Rotterdam, The Netherlands # # 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 matplotlib matplotlib.use('agg') import matplotlib.pyplot as plt import os import numpy as np from sklearn.decomposition import PCA, SparsePCA, KernelPCA from sklearn.manifold import TSNE from WORC.IOparser.file_io import load_features import WORC.IOparser.config_io_classifier as config_io from WORC.featureprocessing.Imputer import Imputer def Decomposition(features, patientinfo, config, output, label_type=None, verbose=True): """ Perform decompositions to two components of the feature space. Useage is similar to StatisticalTestFeatures. Parameters ---------- features: string, mandatory contains the paths to all .hdf5 feature files used. modalityname1=file1,file2,file3,... modalityname2=file1,... Thus, modalities names are always between a space and a equal sign, files are split by commas. We assume that the lists of files for each modality has the same length. Files on the same position on each list should belong to the same patient. patientinfo: string, mandatory Contains the path referring to a .txt file containing the patient label(s) and value(s) to be used for learning. See the Github Wiki for the format. config: string, mandatory path referring to a .ini file containing the parameters used for feature extraction. See the Github Wiki for the possible fields and their description. # TODO: outputs verbose: boolean, default True print final feature values and labels to command line or not. """ # Load variables from the config file config = config_io.load_config(config) # Create output folder if required if not os.path.exists(os.path.dirname(output)): os.makedirs(os.path.dirname(output)) if label_type is None: label_type = config['Labels']['label_names'] # Read the features and classification data print("Reading features and label data.") label_data, image_features =\ load_features(features, patientinfo, label_type) # Extract feature labels and put values in an array feature_labels = image_features[0][1] feature_values = np.zeros([len(image_features), len(feature_labels)]) for num, x in enumerate(image_features): feature_values[num, :] = x[0] # Detect NaNs, otherwise first feature imputation is required if any(np.isnan(a) for a in np.asarray(feature_values).flatten()): print('\t [WARNING] NaNs detected, applying median imputation') imputer = Imputer(missing_values=np.nan, strategy='median') imputer.fit(feature_values) feature_values = imputer.transform(feature_values) # ----------------------------------------------------------------------- # Perform decomposition print("Performing decompositions.") label_value = label_data['label'] label_name = label_data['label_name'] # Reduce to two components for plotting n_components = 2 for i_class, i_name in zip(label_value, label_name): classlabels = i_class.ravel() class1 = [i for j, i in enumerate(feature_values) if classlabels[j] == 1] class2 = [i for j, i in enumerate(feature_values) if classlabels[j] == 0] f = plt.figure(figsize=(20, 15)) # ------------------------------------------------------- # Fit PCA pca = PCA(n_components=n_components) pca.fit(feature_values) explained_variance_ratio = np.sum(pca.explained_variance_ratio_) class1_pca = pca.transform(class1) class2_pca = pca.transform(class2) # Plot PCA ax = plt.subplot(2, 3, 1) plt.subplots_adjust(hspace=0.3, wspace=0.2) ax.scatter(class1_pca[:, 0], class1_pca[:, 1], color='blue') ax.scatter(class2_pca[:, 0], class2_pca[:, 1], color='green') ax.set_title(f'PCA: {round(explained_variance_ratio, 3)} variance.') # ------------------------------------------------------- # Fit Sparse PCA pca = SparsePCA(n_components=n_components) pca.fit(feature_values) class1_pca = pca.transform(class1) class2_pca = pca.transform(class2) # Plot Sparse PCA ax = plt.subplot(2, 3, 2) plt.subplots_adjust(hspace=0.3, wspace=0.2) ax.scatter(class1_pca[:, 0], class1_pca[:, 1], color='blue') ax.scatter(class2_pca[:, 0], class2_pca[:, 1], color='green') ax.set_title('Sparse PCA.') # ------------------------------------------------------- # Fit Kernel PCA fnum = 3 for kernel in ['linear', 'poly', 'rbf']: try: pca = KernelPCA(n_components=n_components, kernel=kernel) pca.fit(feature_values) class1_pca = pca.transform(class1) class2_pca = pca.transform(class2) # Plot Sparse PCA ax = plt.subplot(2, 3, fnum) plt.subplots_adjust(hspace=0.3, wspace=0.2) ax.scatter(class1_pca[:, 0], class1_pca[:, 1], color='blue') ax.scatter(class2_pca[:, 0], class2_pca[:, 1], color='green') ax.set_title(('Kernel PCA: {} .').format(kernel)) fnum += 1 except ValueError as e: # Sometimes, a specific kernel does not work, just continue print(f'[Error] {e}: skipping kernel {kernel}.') continue # ------------------------------------------------------- # Fit t-SNE tSNE = TSNE(n_components=n_components) class_all = class1 + class2 class_all_tsne = tSNE.fit_transform(class_all) class1_tSNE = class_all_tsne[0:len(class1)] class2_tSNE = class_all_tsne[len(class1):] # Plot Sparse tSNE ax = plt.subplot(2, 3, 6) plt.subplots_adjust(hspace=0.3, wspace=0.2) ax.scatter(class1_tSNE[:, 0], class1_tSNE[:, 1], color='blue') ax.scatter(class2_tSNE[:, 0], class2_tSNE[:, 1], color='green') ax.set_title('t-SNE.') # ------------------------------------------------------- # Maximize figure to get correct spacings # mng = plt.get_current_fig_manager() # mng.resize(*mng.window.maxsize()) # High DTI to make sure we save the maximized image f.savefig(output, dpi=600) print(("Decomposition saved as {} !").format(output))
0
0
0
703b2e178dfc582d43a9a15235386cc883ec6042
1,766
py
Python
common/actor_critic.py
IanYHWu/msc_2021
0ae09ed392cce5fdf0e85d1f96b7af82900835f8
[ "MIT" ]
null
null
null
common/actor_critic.py
IanYHWu/msc_2021
0ae09ed392cce5fdf0e85d1f96b7af82900835f8
[ "MIT" ]
null
null
null
common/actor_critic.py
IanYHWu/msc_2021
0ae09ed392cce5fdf0e85d1f96b7af82900835f8
[ "MIT" ]
null
null
null
import torch.nn as nn import torch.nn.functional as F from torch.distributions import Categorical from common.utils import init class FixedCategorical(Categorical): """ Categorical distribution object """ class Categorical(nn.Module): """ Categorical distribution (NN module) """
26.358209
100
0.606455
import torch.nn as nn import torch.nn.functional as F from torch.distributions import Categorical from common.utils import init class CategoricalAC(nn.Module): def __init__(self, base, recurrent, num_actions): """ embedder: (torch.Tensor) model to extract the embedding for observation - probably a ConvNet action_size: number of the categorical actions """ super().__init__() self.base = base self.recurrent = recurrent self.dist = Categorical(self.base.output_size, num_actions) def is_recurrent(self): return self.recurrent def forward(self, x, hx, masks): value, actor_features, rnn_hxs = self.base(x, hx, masks) dist = self.dist(actor_features) value = value.reshape(-1) return dist, value, rnn_hxs class FixedCategorical(Categorical): """ Categorical distribution object """ def sample(self): return super().sample().unsqueeze(-1) def log_probs(self, actions): return ( super() .log_prob(actions.squeeze(-1)) .view(actions.size(0), -1) .sum(-1) .unsqueeze(-1) ) def mode(self): return self.probs.argmax(dim=-1, keepdim=True) class Categorical(nn.Module): """ Categorical distribution (NN module) """ def __init__(self, num_inputs, num_outputs): super(Categorical, self).__init__() init_ = lambda m: init( m, nn.init.orthogonal_, lambda x: nn.init.constant_(x, 0), gain=0.01) self.linear = init_(nn.Linear(num_inputs, num_outputs)) def forward(self, x): x = self.linear(x) return FixedCategorical(logits=x)
848
453
156
7073f16f06db3de1ab53d454e076544e515ab1d3
1,220
py
Python
XML/XML_to_dict__xmltodict__examples/dict_to_xml__unparse.py
DazEB2/SimplePyScripts
1dde0a42ba93fe89609855d6db8af1c63b1ab7cc
[ "CC-BY-4.0" ]
117
2015-12-18T07:18:27.000Z
2022-03-28T00:25:54.000Z
XML/XML_to_dict__xmltodict__examples/dict_to_xml__unparse.py
DazEB2/SimplePyScripts
1dde0a42ba93fe89609855d6db8af1c63b1ab7cc
[ "CC-BY-4.0" ]
8
2018-10-03T09:38:46.000Z
2021-12-13T19:51:09.000Z
XML/XML_to_dict__xmltodict__examples/dict_to_xml__unparse.py
DazEB2/SimplePyScripts
1dde0a42ba93fe89609855d6db8af1c63b1ab7cc
[ "CC-BY-4.0" ]
28
2016-08-02T17:43:47.000Z
2022-03-21T08:31:12.000Z
#!/usr/bin/env python3 # -*- coding: utf-8 -*- __author__ = 'ipetrash' # SOURCE: https://github.com/martinblech/xmltodict#roundtripping # pip install xmltodict import xmltodict my_dict = { 'response': { 'status': 'good', 'last_updated': '2014-02-16T23:10:12Z', } } print(xmltodict.unparse(my_dict)) # <?xml version="1.0" encoding="utf-8"?> # <response><status>good</status><last_updated>2014-02-16T23:10:12Z</last_updated></response> print() print(xmltodict.unparse(my_dict, pretty=True)) # <?xml version="1.0" encoding="utf-8"?> # <response> # <status>good</status> # <last_updated>2014-02-16T23:10:12Z</last_updated> # </response> print('\n') # Text values for nodes can be specified with the cdata_key key in the python dict, while node properties can # be specified with the attr_prefix prefixed to the key name in the python dict. The default value for attr_ # prefix is @ and the default value for cdata_key is #text. my_dict = { 'text': { '@color': 'red', '@stroke': '2', '#text': 'This is a test', } } print(xmltodict.unparse(my_dict, pretty=True)) # <?xml version="1.0" encoding="utf-8"?> # <text stroke="2" color="red">This is a test</text>
25.416667
109
0.663115
#!/usr/bin/env python3 # -*- coding: utf-8 -*- __author__ = 'ipetrash' # SOURCE: https://github.com/martinblech/xmltodict#roundtripping # pip install xmltodict import xmltodict my_dict = { 'response': { 'status': 'good', 'last_updated': '2014-02-16T23:10:12Z', } } print(xmltodict.unparse(my_dict)) # <?xml version="1.0" encoding="utf-8"?> # <response><status>good</status><last_updated>2014-02-16T23:10:12Z</last_updated></response> print() print(xmltodict.unparse(my_dict, pretty=True)) # <?xml version="1.0" encoding="utf-8"?> # <response> # <status>good</status> # <last_updated>2014-02-16T23:10:12Z</last_updated> # </response> print('\n') # Text values for nodes can be specified with the cdata_key key in the python dict, while node properties can # be specified with the attr_prefix prefixed to the key name in the python dict. The default value for attr_ # prefix is @ and the default value for cdata_key is #text. my_dict = { 'text': { '@color': 'red', '@stroke': '2', '#text': 'This is a test', } } print(xmltodict.unparse(my_dict, pretty=True)) # <?xml version="1.0" encoding="utf-8"?> # <text stroke="2" color="red">This is a test</text>
0
0
0
547250e28386f9801f70b2f1c41a9589aa802d7d
15,648
py
Python
resources/libraries/python/QemuManager.py
nidhyanandhan/csit
2156583b4e66f2c3c35903c854b1823b76a4e9a6
[ "Apache-2.0" ]
null
null
null
resources/libraries/python/QemuManager.py
nidhyanandhan/csit
2156583b4e66f2c3c35903c854b1823b76a4e9a6
[ "Apache-2.0" ]
null
null
null
resources/libraries/python/QemuManager.py
nidhyanandhan/csit
2156583b4e66f2c3c35903c854b1823b76a4e9a6
[ "Apache-2.0" ]
null
null
null
# Copyright (c) 2020 Cisco and/or its affiliates. # 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. """QEMU Manager library.""" from collections import OrderedDict from resources.libraries.python.Constants import Constants from resources.libraries.python.CpuUtils import CpuUtils from resources.libraries.python.QemuUtils import QemuUtils from resources.libraries.python.topology import NodeType, Topology __all__ = [u"QemuManager"] class QemuManager: """QEMU lifecycle management class""" # Use one instance of class per tests. ROBOT_LIBRARY_SCOPE = u"TEST CASE" def __init__(self, nodes): """Init QemuManager object.""" self.machines = None self.machines_affinity = None self.nodes = nodes def initialize(self): """Initialize QemuManager object.""" self.machines = OrderedDict() self.machines_affinity = OrderedDict() def construct_vms_on_node(self, **kwargs): """Construct 1..Mx1..N VMs(s) on node with specified name. :param kwargs: Named parameters. :type kwargs: dict """ node = kwargs[u"node"] nf_chains = int(kwargs[u"nf_chains"]) nf_nodes = int(kwargs[u"nf_nodes"]) queues = kwargs[u"rxq_count_int"] if kwargs[u"auto_scale"] else 1 vs_dtc = kwargs[u"vs_dtc"] nf_dtc = kwargs[u"vs_dtc"] if kwargs[u"auto_scale"] \ else kwargs[u"nf_dtc"] nf_dtcr = kwargs[u"nf_dtcr"] \ if isinstance(kwargs[u"nf_dtcr"], int) else 2 for nf_chain in range(1, nf_chains + 1): for nf_node in range(1, nf_nodes + 1): qemu_id = (nf_chain - 1) * nf_nodes + nf_node name = f"{node}_{qemu_id}" idx1 = (nf_chain - 1) * nf_nodes * 2 + nf_node * 2 - 1 vif1_mac = Topology.get_interface_mac( self.nodes[node], f"vhost{idx1}" ) if kwargs[u"vnf"] == u"testpmd_mac" \ else kwargs[u"tg_pf1_mac"] if nf_node == 1 \ else f"52:54:00:00:{(qemu_id - 1):02x}:02" idx2 = (nf_chain - 1) * nf_nodes * 2 + nf_node * 2 vif2_mac = Topology.get_interface_mac( self.nodes[node], f"vhost{idx2}" ) if kwargs[u"vnf"] == u"testpmd_mac" \ else kwargs[u"tg_pf2_mac"] if nf_node == nf_nodes \ else f"52:54:00:00:{(qemu_id + 1):02x}:01" self.machines_affinity[name] = CpuUtils.get_affinity_nf( nodes=self.nodes, node=node, nf_chains=nf_chains, nf_nodes=nf_nodes, nf_chain=nf_chain, nf_node=nf_node, vs_dtc=vs_dtc, nf_dtc=nf_dtc, nf_dtcr=nf_dtcr ) try: getattr(self, f'_c_{kwargs["vnf"]}')( qemu_id=qemu_id, name=name, queues=queues, **kwargs ) except AttributeError: self._c_default( qemu_id=qemu_id, name=name, queues=queues, vif1_mac=vif1_mac, vif2_mac=vif2_mac, **kwargs ) def construct_vms_on_all_nodes(self, **kwargs): """Construct 1..Mx1..N VMs(s) with specified name on all nodes. :param kwargs: Named parameters. :type kwargs: dict """ self.initialize() for node in self.nodes: if self.nodes[node][u"type"] == NodeType.DUT: self.construct_vms_on_node(node=node, **kwargs) def start_all_vms(self, pinning=False): """Start all added VMs in manager. :param pinning: If True, then do also QEMU process pinning. :type pinning: bool """ cpus = [] for machine, machine_affinity in \ zip(self.machines.values(), self.machines_affinity.values()): index = list(self.machines.values()).index(machine) name = list(self.machines.keys())[index] self.nodes[name] = machine.qemu_start() if pinning: machine.qemu_set_affinity(*machine_affinity) cpus.extend(machine_affinity) return ",".join(str(cpu) for cpu in cpus) def kill_all_vms(self, force=False): """Kill all added VMs in manager. :param force: Force kill all Qemu instances by pkill qemu if True. :type force: bool """ for node in list(self.nodes.values()): if node["type"] == NodeType.VM: try: self.nodes.popitem(node) except TypeError: pass for machine in self.machines.values(): if force: machine.qemu_kill_all() else: machine.qemu_kill() def _c_default(self, **kwargs): """Instantiate one VM with default configuration. :param kwargs: Named parameters. :type kwargs: dict """ qemu_id = kwargs[u"qemu_id"] name = kwargs[u"name"] self.machines[name] = QemuUtils( node=self.nodes[kwargs[u"node"]], qemu_id=qemu_id, smp=len(self.machines_affinity[name]), mem=4096, vnf=kwargs[u"vnf"], img=Constants.QEMU_VM_KERNEL ) self.machines[name].add_default_params() self.machines[name].add_kernelvm_params() self.machines[name].configure_kernelvm_vnf( mac1=f"52:54:00:00:{qemu_id:02x}:01", mac2=f"52:54:00:00:{qemu_id:02x}:02", vif1_mac=kwargs[u"vif1_mac"], vif2_mac=kwargs[u"vif2_mac"], queues=kwargs[u"queues"], jumbo_frames=kwargs[u"jumbo"] ) self.machines[name].add_vhost_user_if( f"/run/vpp/sock-{qemu_id}-1", jumbo_frames=kwargs[u"jumbo"], queues=kwargs[u"queues"], queue_size=kwargs[u"perf_qemu_qsz"], csum=kwargs[u"enable_csum"], gso=kwargs[u"enable_gso"] ) self.machines[name].add_vhost_user_if( f"/run/vpp/sock-{qemu_id}-2", jumbo_frames=kwargs[u"jumbo"], queues=kwargs[u"queues"], queue_size=kwargs[u"perf_qemu_qsz"], csum=kwargs[u"enable_csum"], gso=kwargs[u"enable_gso"] ) def _c_vpp_2vfpt_ip4base_plen24(self, **kwargs): """Instantiate one VM with vpp_2vfpt_ip4base_plen24 configuration. :param kwargs: Named parameters. :type kwargs: dict """ qemu_id = kwargs[u"qemu_id"] name = kwargs[u"name"] self.machines[name] = QemuUtils( node=self.nodes[kwargs[u"node"]], qemu_id=qemu_id, smp=len(self.machines_affinity[name]), mem=4096, vnf=kwargs[u"vnf"], img=Constants.QEMU_VM_KERNEL ) self.machines[name].add_default_params() self.machines[name].add_kernelvm_params() if u"DUT1" in name: self.machines[name].configure_kernelvm_vnf( ip1=u"2.2.2.1/30", ip2=u"1.1.1.2/30", route1=u"20.0.0.0/24", routeif1=u"avf-0/0/6/0", nexthop1=u"2.2.2.2", route2=u"10.0.0.0/24", routeif2=u"avf-0/0/7/0", nexthop2=u"1.1.1.1", arpmac1=u"3c:fd:fe:d1:5c:d8", arpip1=u"1.1.1.1", arpif1=u"avf-0/0/7/0", queues=kwargs[u"queues"], jumbo_frames=kwargs[u"jumbo"] ) else: self.machines[name].configure_kernelvm_vnf( ip1=u"3.3.3.2/30", ip2=u"2.2.2.2/30", route1=u"10.0.0.0/24", routeif1=u"avf-0/0/7/0", nexthop1=u"2.2.2.1", route2=u"20.0.0.0/24", routeif2=u"avf-0/0/6/0", nexthop2=u"3.3.3.1", arpmac1=u"3c:fd:fe:d1:5c:d9", arpip1=u"3.3.3.1", arpif1=u"avf-0/0/6/0", queues=kwargs[u"queues"], jumbo_frames=kwargs[u"jumbo"] ) self.machines[name].add_vfio_pci_if( pci=Topology.get_interface_pci_addr( self.nodes[kwargs[u"node"]], kwargs[u"if2"]) ) self.machines[name].add_vfio_pci_if( pci=Topology.get_interface_pci_addr( self.nodes[kwargs[u"node"]], kwargs[u"if1"]) ) def _c_vpp_2vfpt_ip4scale2k_plen30(self, **kwargs): """Instantiate one VM with vpp_2vfpt_ip4scale2k_plen30 configuration. :param kwargs: Named parameters. :type kwargs: dict """ qemu_id = kwargs[u"qemu_id"] name = kwargs[u"name"] self.machines[name] = QemuUtils( node=self.nodes[kwargs[u"node"]], qemu_id=qemu_id, smp=len(self.machines_affinity[name]), mem=4096, vnf=kwargs[u"vnf"], img=Constants.QEMU_VM_KERNEL ) self.machines[name].add_default_params() self.machines[name].add_kernelvm_params() if u"DUT1" in name: self.machines[name].configure_kernelvm_vnf( ip1=u"2.2.2.1/30", ip2=u"1.1.1.2/30", route1=u"20.0.0.0/30", routeif1=u"avf-0/0/6/0", nexthop1=u"2.2.2.2", route2=u"10.0.0.0/30", routeif2=u"avf-0/0/7/0", nexthop2=u"1.1.1.1", arpmac1=u"3c:fd:fe:d1:5c:d8", arpip1=u"1.1.1.1", arpif1=u"avf-0/0/7/0", queues=kwargs[u"queues"], jumbo_frames=kwargs[u"jumbo"] ) else: self.machines[name].configure_kernelvm_vnf( ip1=u"3.3.3.2/30", ip2=u"2.2.2.2/30", route1=u"10.0.0.0/30", routeif1=u"avf-0/0/7/0", nexthop1=u"2.2.2.1", route2=u"20.0.0.0/30", routeif2=u"avf-0/0/6/0", nexthop2=u"3.3.3.1", arpmac1=u"3c:fd:fe:d1:5c:d9", arpip1=u"3.3.3.1", arpif1=u"avf-0/0/6/0", queues=kwargs[u"queues"], jumbo_frames=kwargs[u"jumbo"] ) self.machines[name].add_vfio_pci_if( pci=Topology.get_interface_pci_addr( self.nodes[kwargs[u"node"]], kwargs[u"if2"]) ) self.machines[name].add_vfio_pci_if( pci=Topology.get_interface_pci_addr( self.nodes[kwargs[u"node"]], kwargs[u"if1"]) ) def _c_vpp_2vfpt_ip4scale20k_plen30(self, **kwargs): """Instantiate one VM with vpp_2vfpt_ip4scale20k_plen30 configuration. :param kwargs: Named parameters. :type kwargs: dict """ qemu_id = kwargs[u"qemu_id"] name = kwargs[u"name"] self.machines[name] = QemuUtils( node=self.nodes[kwargs[u"node"]], qemu_id=qemu_id, smp=len(self.machines_affinity[name]), mem=4096, vnf=kwargs[u"vnf"], img=Constants.QEMU_VM_KERNEL ) self.machines[name].add_default_params() self.machines[name].add_kernelvm_params() if u"DUT1" in name: self.machines[name].configure_kernelvm_vnf( ip1=u"2.2.2.1/30", ip2=u"1.1.1.2/30", route1=u"20.0.0.0/30", routeif1=u"avf-0/0/6/0", nexthop1=u"2.2.2.2", route2=u"10.0.0.0/30", routeif2=u"avf-0/0/7/0", nexthop2=u"1.1.1.1", arpmac1=u"3c:fd:fe:d1:5c:d8", arpip1=u"1.1.1.1", arpif1=u"avf-0/0/7/0", queues=kwargs[u"queues"], jumbo_frames=kwargs[u"jumbo"] ) else: self.machines[name].configure_kernelvm_vnf( ip1=u"3.3.3.2/30", ip2=u"2.2.2.2/30", route1=u"10.0.0.0/30", routeif1=u"avf-0/0/7/0", nexthop1=u"2.2.2.1", route2=u"20.0.0.0/30", routeif2=u"avf-0/0/6/0", nexthop2=u"3.3.3.1", arpmac1=u"3c:fd:fe:d1:5c:d9", arpip1=u"3.3.3.1", arpif1=u"avf-0/0/6/0", queues=kwargs[u"queues"], jumbo_frames=kwargs[u"jumbo"] ) self.machines[name].add_vfio_pci_if( pci=Topology.get_interface_pci_addr( self.nodes[kwargs[u"node"]], kwargs[u"if2"]) ) self.machines[name].add_vfio_pci_if( pci=Topology.get_interface_pci_addr( self.nodes[kwargs[u"node"]], kwargs[u"if1"]) ) def _c_vpp_2vfpt_ip4scale200k_plen30(self, **kwargs): """Instantiate one VM with vpp_2vfpt_ip4scale200k_plen30 configuration. :param kwargs: Named parameters. :type kwargs: dict """ qemu_id = kwargs[u"qemu_id"] name = kwargs[u"name"] self.machines[name] = QemuUtils( node=self.nodes[kwargs[u"node"]], qemu_id=qemu_id, smp=len(self.machines_affinity[name]), mem=4096, vnf=kwargs[u"vnf"], img=Constants.QEMU_VM_KERNEL ) self.machines[name].add_default_params() self.machines[name].add_kernelvm_params() if u"DUT1" in name: self.machines[name].configure_kernelvm_vnf( ip1=u"2.2.2.1/30", ip2=u"1.1.1.2/30", route1=u"20.0.0.0/30", routeif1=u"avf-0/0/6/0", nexthop1=u"2.2.2.2", route2=u"10.0.0.0/30", routeif2=u"avf-0/0/7/0", nexthop2=u"1.1.1.1", arpmac1=u"3c:fd:fe:d1:5c:d8", arpip1=u"1.1.1.1", arpif1=u"avf-0/0/7/0", queues=kwargs[u"queues"], jumbo_frames=kwargs[u"jumbo"] ) else: self.machines[name].configure_kernelvm_vnf( ip1=u"3.3.3.2/30", ip2=u"2.2.2.2/30", route1=u"10.0.0.0/30", routeif1=u"avf-0/0/7/0", nexthop1=u"2.2.2.1", route2=u"20.0.0.0/30", routeif2=u"avf-0/0/6/0", nexthop2=u"3.3.3.1", arpmac1=u"3c:fd:fe:d1:5c:d9", arpip1=u"3.3.3.1", arpif1=u"avf-0/0/6/0", queues=kwargs[u"queues"], jumbo_frames=kwargs[u"jumbo"] ) self.machines[name].add_vfio_pci_if( pci=Topology.get_interface_pci_addr( self.nodes[kwargs[u"node"]], kwargs[u"if2"]) ) self.machines[name].add_vfio_pci_if( pci=Topology.get_interface_pci_addr( self.nodes[kwargs[u"node"]], kwargs[u"if1"]) )
37.080569
79
0.522814
# Copyright (c) 2020 Cisco and/or its affiliates. # 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. """QEMU Manager library.""" from collections import OrderedDict from resources.libraries.python.Constants import Constants from resources.libraries.python.CpuUtils import CpuUtils from resources.libraries.python.QemuUtils import QemuUtils from resources.libraries.python.topology import NodeType, Topology __all__ = [u"QemuManager"] class QemuManager: """QEMU lifecycle management class""" # Use one instance of class per tests. ROBOT_LIBRARY_SCOPE = u"TEST CASE" def __init__(self, nodes): """Init QemuManager object.""" self.machines = None self.machines_affinity = None self.nodes = nodes def initialize(self): """Initialize QemuManager object.""" self.machines = OrderedDict() self.machines_affinity = OrderedDict() def construct_vms_on_node(self, **kwargs): """Construct 1..Mx1..N VMs(s) on node with specified name. :param kwargs: Named parameters. :type kwargs: dict """ node = kwargs[u"node"] nf_chains = int(kwargs[u"nf_chains"]) nf_nodes = int(kwargs[u"nf_nodes"]) queues = kwargs[u"rxq_count_int"] if kwargs[u"auto_scale"] else 1 vs_dtc = kwargs[u"vs_dtc"] nf_dtc = kwargs[u"vs_dtc"] if kwargs[u"auto_scale"] \ else kwargs[u"nf_dtc"] nf_dtcr = kwargs[u"nf_dtcr"] \ if isinstance(kwargs[u"nf_dtcr"], int) else 2 for nf_chain in range(1, nf_chains + 1): for nf_node in range(1, nf_nodes + 1): qemu_id = (nf_chain - 1) * nf_nodes + nf_node name = f"{node}_{qemu_id}" idx1 = (nf_chain - 1) * nf_nodes * 2 + nf_node * 2 - 1 vif1_mac = Topology.get_interface_mac( self.nodes[node], f"vhost{idx1}" ) if kwargs[u"vnf"] == u"testpmd_mac" \ else kwargs[u"tg_pf1_mac"] if nf_node == 1 \ else f"52:54:00:00:{(qemu_id - 1):02x}:02" idx2 = (nf_chain - 1) * nf_nodes * 2 + nf_node * 2 vif2_mac = Topology.get_interface_mac( self.nodes[node], f"vhost{idx2}" ) if kwargs[u"vnf"] == u"testpmd_mac" \ else kwargs[u"tg_pf2_mac"] if nf_node == nf_nodes \ else f"52:54:00:00:{(qemu_id + 1):02x}:01" self.machines_affinity[name] = CpuUtils.get_affinity_nf( nodes=self.nodes, node=node, nf_chains=nf_chains, nf_nodes=nf_nodes, nf_chain=nf_chain, nf_node=nf_node, vs_dtc=vs_dtc, nf_dtc=nf_dtc, nf_dtcr=nf_dtcr ) try: getattr(self, f'_c_{kwargs["vnf"]}')( qemu_id=qemu_id, name=name, queues=queues, **kwargs ) except AttributeError: self._c_default( qemu_id=qemu_id, name=name, queues=queues, vif1_mac=vif1_mac, vif2_mac=vif2_mac, **kwargs ) def construct_vms_on_all_nodes(self, **kwargs): """Construct 1..Mx1..N VMs(s) with specified name on all nodes. :param kwargs: Named parameters. :type kwargs: dict """ self.initialize() for node in self.nodes: if self.nodes[node][u"type"] == NodeType.DUT: self.construct_vms_on_node(node=node, **kwargs) def start_all_vms(self, pinning=False): """Start all added VMs in manager. :param pinning: If True, then do also QEMU process pinning. :type pinning: bool """ cpus = [] for machine, machine_affinity in \ zip(self.machines.values(), self.machines_affinity.values()): index = list(self.machines.values()).index(machine) name = list(self.machines.keys())[index] self.nodes[name] = machine.qemu_start() if pinning: machine.qemu_set_affinity(*machine_affinity) cpus.extend(machine_affinity) return ",".join(str(cpu) for cpu in cpus) def kill_all_vms(self, force=False): """Kill all added VMs in manager. :param force: Force kill all Qemu instances by pkill qemu if True. :type force: bool """ for node in list(self.nodes.values()): if node["type"] == NodeType.VM: try: self.nodes.popitem(node) except TypeError: pass for machine in self.machines.values(): if force: machine.qemu_kill_all() else: machine.qemu_kill() def _c_default(self, **kwargs): """Instantiate one VM with default configuration. :param kwargs: Named parameters. :type kwargs: dict """ qemu_id = kwargs[u"qemu_id"] name = kwargs[u"name"] self.machines[name] = QemuUtils( node=self.nodes[kwargs[u"node"]], qemu_id=qemu_id, smp=len(self.machines_affinity[name]), mem=4096, vnf=kwargs[u"vnf"], img=Constants.QEMU_VM_KERNEL ) self.machines[name].add_default_params() self.machines[name].add_kernelvm_params() self.machines[name].configure_kernelvm_vnf( mac1=f"52:54:00:00:{qemu_id:02x}:01", mac2=f"52:54:00:00:{qemu_id:02x}:02", vif1_mac=kwargs[u"vif1_mac"], vif2_mac=kwargs[u"vif2_mac"], queues=kwargs[u"queues"], jumbo_frames=kwargs[u"jumbo"] ) self.machines[name].add_vhost_user_if( f"/run/vpp/sock-{qemu_id}-1", jumbo_frames=kwargs[u"jumbo"], queues=kwargs[u"queues"], queue_size=kwargs[u"perf_qemu_qsz"], csum=kwargs[u"enable_csum"], gso=kwargs[u"enable_gso"] ) self.machines[name].add_vhost_user_if( f"/run/vpp/sock-{qemu_id}-2", jumbo_frames=kwargs[u"jumbo"], queues=kwargs[u"queues"], queue_size=kwargs[u"perf_qemu_qsz"], csum=kwargs[u"enable_csum"], gso=kwargs[u"enable_gso"] ) def _c_vpp_2vfpt_ip4base_plen24(self, **kwargs): """Instantiate one VM with vpp_2vfpt_ip4base_plen24 configuration. :param kwargs: Named parameters. :type kwargs: dict """ qemu_id = kwargs[u"qemu_id"] name = kwargs[u"name"] self.machines[name] = QemuUtils( node=self.nodes[kwargs[u"node"]], qemu_id=qemu_id, smp=len(self.machines_affinity[name]), mem=4096, vnf=kwargs[u"vnf"], img=Constants.QEMU_VM_KERNEL ) self.machines[name].add_default_params() self.machines[name].add_kernelvm_params() if u"DUT1" in name: self.machines[name].configure_kernelvm_vnf( ip1=u"2.2.2.1/30", ip2=u"1.1.1.2/30", route1=u"20.0.0.0/24", routeif1=u"avf-0/0/6/0", nexthop1=u"2.2.2.2", route2=u"10.0.0.0/24", routeif2=u"avf-0/0/7/0", nexthop2=u"1.1.1.1", arpmac1=u"3c:fd:fe:d1:5c:d8", arpip1=u"1.1.1.1", arpif1=u"avf-0/0/7/0", queues=kwargs[u"queues"], jumbo_frames=kwargs[u"jumbo"] ) else: self.machines[name].configure_kernelvm_vnf( ip1=u"3.3.3.2/30", ip2=u"2.2.2.2/30", route1=u"10.0.0.0/24", routeif1=u"avf-0/0/7/0", nexthop1=u"2.2.2.1", route2=u"20.0.0.0/24", routeif2=u"avf-0/0/6/0", nexthop2=u"3.3.3.1", arpmac1=u"3c:fd:fe:d1:5c:d9", arpip1=u"3.3.3.1", arpif1=u"avf-0/0/6/0", queues=kwargs[u"queues"], jumbo_frames=kwargs[u"jumbo"] ) self.machines[name].add_vfio_pci_if( pci=Topology.get_interface_pci_addr( self.nodes[kwargs[u"node"]], kwargs[u"if2"]) ) self.machines[name].add_vfio_pci_if( pci=Topology.get_interface_pci_addr( self.nodes[kwargs[u"node"]], kwargs[u"if1"]) ) def _c_vpp_2vfpt_ip4scale2k_plen30(self, **kwargs): """Instantiate one VM with vpp_2vfpt_ip4scale2k_plen30 configuration. :param kwargs: Named parameters. :type kwargs: dict """ qemu_id = kwargs[u"qemu_id"] name = kwargs[u"name"] self.machines[name] = QemuUtils( node=self.nodes[kwargs[u"node"]], qemu_id=qemu_id, smp=len(self.machines_affinity[name]), mem=4096, vnf=kwargs[u"vnf"], img=Constants.QEMU_VM_KERNEL ) self.machines[name].add_default_params() self.machines[name].add_kernelvm_params() if u"DUT1" in name: self.machines[name].configure_kernelvm_vnf( ip1=u"2.2.2.1/30", ip2=u"1.1.1.2/30", route1=u"20.0.0.0/30", routeif1=u"avf-0/0/6/0", nexthop1=u"2.2.2.2", route2=u"10.0.0.0/30", routeif2=u"avf-0/0/7/0", nexthop2=u"1.1.1.1", arpmac1=u"3c:fd:fe:d1:5c:d8", arpip1=u"1.1.1.1", arpif1=u"avf-0/0/7/0", queues=kwargs[u"queues"], jumbo_frames=kwargs[u"jumbo"] ) else: self.machines[name].configure_kernelvm_vnf( ip1=u"3.3.3.2/30", ip2=u"2.2.2.2/30", route1=u"10.0.0.0/30", routeif1=u"avf-0/0/7/0", nexthop1=u"2.2.2.1", route2=u"20.0.0.0/30", routeif2=u"avf-0/0/6/0", nexthop2=u"3.3.3.1", arpmac1=u"3c:fd:fe:d1:5c:d9", arpip1=u"3.3.3.1", arpif1=u"avf-0/0/6/0", queues=kwargs[u"queues"], jumbo_frames=kwargs[u"jumbo"] ) self.machines[name].add_vfio_pci_if( pci=Topology.get_interface_pci_addr( self.nodes[kwargs[u"node"]], kwargs[u"if2"]) ) self.machines[name].add_vfio_pci_if( pci=Topology.get_interface_pci_addr( self.nodes[kwargs[u"node"]], kwargs[u"if1"]) ) def _c_vpp_2vfpt_ip4scale20k_plen30(self, **kwargs): """Instantiate one VM with vpp_2vfpt_ip4scale20k_plen30 configuration. :param kwargs: Named parameters. :type kwargs: dict """ qemu_id = kwargs[u"qemu_id"] name = kwargs[u"name"] self.machines[name] = QemuUtils( node=self.nodes[kwargs[u"node"]], qemu_id=qemu_id, smp=len(self.machines_affinity[name]), mem=4096, vnf=kwargs[u"vnf"], img=Constants.QEMU_VM_KERNEL ) self.machines[name].add_default_params() self.machines[name].add_kernelvm_params() if u"DUT1" in name: self.machines[name].configure_kernelvm_vnf( ip1=u"2.2.2.1/30", ip2=u"1.1.1.2/30", route1=u"20.0.0.0/30", routeif1=u"avf-0/0/6/0", nexthop1=u"2.2.2.2", route2=u"10.0.0.0/30", routeif2=u"avf-0/0/7/0", nexthop2=u"1.1.1.1", arpmac1=u"3c:fd:fe:d1:5c:d8", arpip1=u"1.1.1.1", arpif1=u"avf-0/0/7/0", queues=kwargs[u"queues"], jumbo_frames=kwargs[u"jumbo"] ) else: self.machines[name].configure_kernelvm_vnf( ip1=u"3.3.3.2/30", ip2=u"2.2.2.2/30", route1=u"10.0.0.0/30", routeif1=u"avf-0/0/7/0", nexthop1=u"2.2.2.1", route2=u"20.0.0.0/30", routeif2=u"avf-0/0/6/0", nexthop2=u"3.3.3.1", arpmac1=u"3c:fd:fe:d1:5c:d9", arpip1=u"3.3.3.1", arpif1=u"avf-0/0/6/0", queues=kwargs[u"queues"], jumbo_frames=kwargs[u"jumbo"] ) self.machines[name].add_vfio_pci_if( pci=Topology.get_interface_pci_addr( self.nodes[kwargs[u"node"]], kwargs[u"if2"]) ) self.machines[name].add_vfio_pci_if( pci=Topology.get_interface_pci_addr( self.nodes[kwargs[u"node"]], kwargs[u"if1"]) ) def _c_vpp_2vfpt_ip4scale200k_plen30(self, **kwargs): """Instantiate one VM with vpp_2vfpt_ip4scale200k_plen30 configuration. :param kwargs: Named parameters. :type kwargs: dict """ qemu_id = kwargs[u"qemu_id"] name = kwargs[u"name"] self.machines[name] = QemuUtils( node=self.nodes[kwargs[u"node"]], qemu_id=qemu_id, smp=len(self.machines_affinity[name]), mem=4096, vnf=kwargs[u"vnf"], img=Constants.QEMU_VM_KERNEL ) self.machines[name].add_default_params() self.machines[name].add_kernelvm_params() if u"DUT1" in name: self.machines[name].configure_kernelvm_vnf( ip1=u"2.2.2.1/30", ip2=u"1.1.1.2/30", route1=u"20.0.0.0/30", routeif1=u"avf-0/0/6/0", nexthop1=u"2.2.2.2", route2=u"10.0.0.0/30", routeif2=u"avf-0/0/7/0", nexthop2=u"1.1.1.1", arpmac1=u"3c:fd:fe:d1:5c:d8", arpip1=u"1.1.1.1", arpif1=u"avf-0/0/7/0", queues=kwargs[u"queues"], jumbo_frames=kwargs[u"jumbo"] ) else: self.machines[name].configure_kernelvm_vnf( ip1=u"3.3.3.2/30", ip2=u"2.2.2.2/30", route1=u"10.0.0.0/30", routeif1=u"avf-0/0/7/0", nexthop1=u"2.2.2.1", route2=u"20.0.0.0/30", routeif2=u"avf-0/0/6/0", nexthop2=u"3.3.3.1", arpmac1=u"3c:fd:fe:d1:5c:d9", arpip1=u"3.3.3.1", arpif1=u"avf-0/0/6/0", queues=kwargs[u"queues"], jumbo_frames=kwargs[u"jumbo"] ) self.machines[name].add_vfio_pci_if( pci=Topology.get_interface_pci_addr( self.nodes[kwargs[u"node"]], kwargs[u"if2"]) ) self.machines[name].add_vfio_pci_if( pci=Topology.get_interface_pci_addr( self.nodes[kwargs[u"node"]], kwargs[u"if1"]) )
0
0
0
ae12c915e418b34a08c739c078807fd4542718ed
973
py
Python
utvsapi/main.py
hroncok/utvsapi-eve
83fcf9e1d14be2740cfec810c97f662a56a1a0ed
[ "MIT" ]
null
null
null
utvsapi/main.py
hroncok/utvsapi-eve
83fcf9e1d14be2740cfec810c97f662a56a1a0ed
[ "MIT" ]
null
null
null
utvsapi/main.py
hroncok/utvsapi-eve
83fcf9e1d14be2740cfec810c97f662a56a1a0ed
[ "MIT" ]
null
null
null
from eve import Eve from eve_sqlalchemy import SQL from eve_sqlalchemy.validation import ValidatorSQL from sqlalchemy.engine.url import URL try: from eve_docs import eve_docs from flask.ext.bootstrap import Bootstrap except ImportError: Bootstrap = None from utvsapi.tables import domain, Base, on_fetched_item, on_fetched_resource from utvsapi.auth import BearerAuth url = URL('mysql', query={'read_default_file': './mysql.cnf'}) SETTINGS = { 'SQLALCHEMY_DATABASE_URI': url, 'SQLALCHEMY_TRACK_MODIFICATIONS': False, 'DOMAIN': domain, 'API_NAME': 'UTVS API', } app = Eve(auth=BearerAuth, settings=SETTINGS, validator=ValidatorSQL, data=SQL) app.on_fetched_item += on_fetched_item app.on_fetched_resource += on_fetched_resource if Bootstrap: Bootstrap(app) app.register_blueprint(eve_docs, url_prefix='/docs') db = app.data.driver Base.metadata.bind = db.engine db.Model = Base if __name__ == '__main__': app.run(debug=True)
24.948718
79
0.758479
from eve import Eve from eve_sqlalchemy import SQL from eve_sqlalchemy.validation import ValidatorSQL from sqlalchemy.engine.url import URL try: from eve_docs import eve_docs from flask.ext.bootstrap import Bootstrap except ImportError: Bootstrap = None from utvsapi.tables import domain, Base, on_fetched_item, on_fetched_resource from utvsapi.auth import BearerAuth url = URL('mysql', query={'read_default_file': './mysql.cnf'}) SETTINGS = { 'SQLALCHEMY_DATABASE_URI': url, 'SQLALCHEMY_TRACK_MODIFICATIONS': False, 'DOMAIN': domain, 'API_NAME': 'UTVS API', } app = Eve(auth=BearerAuth, settings=SETTINGS, validator=ValidatorSQL, data=SQL) app.on_fetched_item += on_fetched_item app.on_fetched_resource += on_fetched_resource if Bootstrap: Bootstrap(app) app.register_blueprint(eve_docs, url_prefix='/docs') db = app.data.driver Base.metadata.bind = db.engine db.Model = Base if __name__ == '__main__': app.run(debug=True)
0
0
0
bcbe3aaf1f6e1214c4258ecc1fbd37b90e14f66f
600
py
Python
class1/create_yaml_json.py
hyoung-dpl/pynet
3171268fd44bffef4a42e5381f11f2aae7b338d6
[ "Apache-2.0" ]
null
null
null
class1/create_yaml_json.py
hyoung-dpl/pynet
3171268fd44bffef4a42e5381f11f2aae7b338d6
[ "Apache-2.0" ]
null
null
null
class1/create_yaml_json.py
hyoung-dpl/pynet
3171268fd44bffef4a42e5381f11f2aae7b338d6
[ "Apache-2.0" ]
null
null
null
#!/usr/bin/env python ''' Write to a yaml and json file for a list and dictionary variable ''' import yaml import json if __name__ == "__main__": main()
17.647059
66
0.64
#!/usr/bin/env python ''' Write to a yaml and json file for a list and dictionary variable ''' import yaml import json def main(): yaml_file = 'yaml_write.yml' json_file = 'json_write.json' yaml_json_dictionary = { 'code_version': '11.5', 'vlan': '404', } yaml_json_list = [ 'Location', 'Manager', yaml_json_dictionary, 'Closet 55' ] with open(yaml_file, "w") as out: out.write(yaml.dump(yaml_json_list, default_flow_style=False)) with open(json_file, "w") as out: json.dump(yaml_json_list, out) if __name__ == "__main__": main()
418
0
23
639bf8a31fde3adf852d62aede94eb4377ccd087
1,211
py
Python
src/train_emb.py
RowitZou/topic_dialog_summ
0de31d97b07be4004e08f9755ee66bea47aa7b10
[ "MIT" ]
42
2020-12-16T07:53:44.000Z
2022-03-31T06:48:18.000Z
src/train_emb.py
RowitZou/topic_dialog_summ
0de31d97b07be4004e08f9755ee66bea47aa7b10
[ "MIT" ]
25
2021-03-26T02:07:36.000Z
2022-03-29T09:55:55.000Z
src/train_emb.py
RowitZou/topic_dialog_summ
0de31d97b07be4004e08f9755ee66bea47aa7b10
[ "MIT" ]
7
2020-12-23T20:07:22.000Z
2022-03-07T12:47:37.000Z
import argparse import os import json import glob from os.path import join as pjoin from others.vocab_wrapper import VocabWrapper if __name__ == "__main__": parser = argparse.ArgumentParser() parser.add_argument("-mode", default='word2vec', type=str, choices=['glove', 'word2vec']) parser.add_argument("-data_path", default="", type=str) parser.add_argument("-emb_size", default=100, type=int) parser.add_argument("-emb_path", default="", type=str) args = parser.parse_args() train_emb(args)
28.833333
93
0.659785
import argparse import os import json import glob from os.path import join as pjoin from others.vocab_wrapper import VocabWrapper def train_emb(args): data_dir = os.path.abspath(args.data_path) print("Preparing to process %s ..." % data_dir) raw_files = glob.glob(pjoin(data_dir, '*.json')) ex_num = 0 vocab_wrapper = VocabWrapper(args.mode, args.emb_size) vocab_wrapper.init_model() file_ex = [] for s in raw_files: exs = json.load(open(s)) print("Processing File " + s) for ex in exs: example = list(map(lambda x: x['word'], ex['session'])) file_ex.extend(example) ex_num += 1 vocab_wrapper.train(file_ex) vocab_wrapper.report() print("Datasets size: %d" % ex_num) vocab_wrapper.save_emb(args.emb_path) if __name__ == "__main__": parser = argparse.ArgumentParser() parser.add_argument("-mode", default='word2vec', type=str, choices=['glove', 'word2vec']) parser.add_argument("-data_path", default="", type=str) parser.add_argument("-emb_size", default=100, type=int) parser.add_argument("-emb_path", default="", type=str) args = parser.parse_args() train_emb(args)
663
0
23
f8f0611c9323dcea116a76a266b78b5412d312ca
1,376
py
Python
vectorbt/returns/__init__.py
RileyMShea/vectorbt
92ce571ce9fd0667f2994a2c922fb4cfcde10c88
[ "Apache-2.0" ]
1
2021-01-15T00:02:11.000Z
2021-01-15T00:02:11.000Z
vectorbt/returns/__init__.py
RileyMShea/vectorbt
92ce571ce9fd0667f2994a2c922fb4cfcde10c88
[ "Apache-2.0" ]
null
null
null
vectorbt/returns/__init__.py
RileyMShea/vectorbt
92ce571ce9fd0667f2994a2c922fb4cfcde10c88
[ "Apache-2.0" ]
null
null
null
"""Modules for working with returns. Offers common financial risk and performance metrics as found in [empyrical](https://github.com/quantopian/empyrical), but Numba-compiled and optimized for 2-dim arrays. ## Accessors You can access methods listed in `vectorbt.returns.accessors` as follows: * `vectorbt.returns.accessors.ReturnsSRAccessor` -> `pd.Series.vbt.returns.*` * `vectorbt.returns.accessors.ReturnsDFAccessor` -> `pd.DataFrame.vbt.returns.*` ```python-repl >>> import numpy as np >>> import pandas as pd >>> import vectorbt as vbt >>> # vectorbt.returns.accessors.ReturnsAccessor.total >>> price = pd.Series([1.1, 1.2, 1.3, 1.2, 1.1]) >>> returns = price.pct_change() >>> returns.vbt.returns.total() 0.0 ``` The accessors extend `vectorbt.generic.accessors`. ```python-repl >>> # inherited from GenericAccessor >>> returns.vbt.returns.max() 0.09090909090909083 ``` !!! note The underlying Series/DataFrame must already be a return series. ## Numba-compiled functions Module `vectorbt.returns.nb` provides an arsenal of Numba-compiled functions that are used by accessors and for measuring portfolio performance. These only accept NumPy arrays and other Numba-compatible types. ```python-repl >>> # vectorbt.returns.nb.cum_returns_1d_nb >>> vbt.returns.nb.cum_returns_1d_nb(returns.values) array([0., 0.09090909, 0.18181818, 0.09090909, 0.]) ```"""
29.276596
118
0.742733
"""Modules for working with returns. Offers common financial risk and performance metrics as found in [empyrical](https://github.com/quantopian/empyrical), but Numba-compiled and optimized for 2-dim arrays. ## Accessors You can access methods listed in `vectorbt.returns.accessors` as follows: * `vectorbt.returns.accessors.ReturnsSRAccessor` -> `pd.Series.vbt.returns.*` * `vectorbt.returns.accessors.ReturnsDFAccessor` -> `pd.DataFrame.vbt.returns.*` ```python-repl >>> import numpy as np >>> import pandas as pd >>> import vectorbt as vbt >>> # vectorbt.returns.accessors.ReturnsAccessor.total >>> price = pd.Series([1.1, 1.2, 1.3, 1.2, 1.1]) >>> returns = price.pct_change() >>> returns.vbt.returns.total() 0.0 ``` The accessors extend `vectorbt.generic.accessors`. ```python-repl >>> # inherited from GenericAccessor >>> returns.vbt.returns.max() 0.09090909090909083 ``` !!! note The underlying Series/DataFrame must already be a return series. ## Numba-compiled functions Module `vectorbt.returns.nb` provides an arsenal of Numba-compiled functions that are used by accessors and for measuring portfolio performance. These only accept NumPy arrays and other Numba-compatible types. ```python-repl >>> # vectorbt.returns.nb.cum_returns_1d_nb >>> vbt.returns.nb.cum_returns_1d_nb(returns.values) array([0., 0.09090909, 0.18181818, 0.09090909, 0.]) ```"""
0
0
0
ac967be092eb4b64ff1b298ff06388e5136ace2c
2,819
py
Python
Fundamentos/Strings.py
VictorMello1993/CursoPythonUdemy
d3e2e542a7c3d3f9635f2b88d0e75ab4fa84236d
[ "MIT" ]
null
null
null
Fundamentos/Strings.py
VictorMello1993/CursoPythonUdemy
d3e2e542a7c3d3f9635f2b88d0e75ab4fa84236d
[ "MIT" ]
4
2021-04-08T21:54:09.000Z
2022-02-10T14:35:13.000Z
Fundamentos/Strings.py
VictorMello1993/CursoPythonUdemy
d3e2e542a7c3d3f9635f2b88d0e75ab4fa84236d
[ "MIT" ]
null
null
null
#%% [markdown] ## Strings (parte 1) dir(str) nome = 'Victor Mello' nome #Acessando um caracter de uma string nome[0] # nome[0] = 'P' #Erro! Strings são imutáveis """OBS: quando se tem uma string cujo conteúdo já possui aspas simples, para evitar erro de sintaxe, tem-se 2 opções: 1) Delimitar a string com aspas duplas e dentro dela colocar entre aspas simples; 2) Delimitar a string com aspas simples, mas utilizando o caracter de escape \ antes de colocar mais aspas simples no conteúdo """ #Exemplo "Marca d'água" == 'Marca d\'água' texto = "Teste \"funciona!" """Texto com múltiplas linhas com \, mas é executado um texto de uma única linha""" #Exemplo texto2 = 'Texto entre \ apóstrofos pode ter "aspas"' texto3 = """Texto com múltiplas linhas com aspas triplas, assim como comentário""" #Neste caso, será impresso um texto de uma única linha com \n indicando quebra de linha texto3 #No entanto, com print(), o resultado é de fato um texto com quebra de linhas print(texto3) #Da mesma forma se imprimir um texto da mesma linha com \n print('Texto com múltiplas linhas com aspas triplas,\nassim como comentário') # %% [markdown] ## Strings (Parte 2) #Acessando o caracter da string da direita para esquerda nome[-4] #Acessando uma substring a partir de um conjunto de caracteres nome[4:] #Começando com índice 4 nome[-5:] #Começando com índice -5, da direita para esqueda #Acessando do início da string até o índice 6 (exclusive) nome[:6] #Acessando do índice 1 até o índice 4 (exclusive) nome[1:4] numeros = '123456789' numeros # numeros[::] #Equivalente ao resultado anterior numeros[::2] #Acessando os caracteres de 2 em 2 caracteres numeros[1::2] #Acessando os caracteres a partir de íncide 1, de 2 em 2 caracteres #Invertendo uma string numeros[::-1] #Invertendo uma string de 2 em 2 caracteres numeros[::-2] # %% [markdown] ## Strings (parte 3) frase = 'Olá, meu nome é Victor e sou legal' #Usando operador membro no contexto de string #Exemplo 1 'Vic' in frase 'vic' not in frase #Exibindo o tamanho da string len(frase) #Gerando uma nova string em caixa baixa frase.lower() 'vic' in frase.lower() #Gerando uma nova string em caixa alta frase.upper() 'VIC' in frase.upper() #Modificando o conteúdo da string frase = frase.upper() frase #Dividindo a string em um array de strings (substrings, melhor dizendo) frase.split() #Dividindo a string quebrando o caracter 'E' frase.split('E') # %% [markdown] ## Strings (parte 4) #Métodos mágicos de strings # dir(str) a = '123 ' b = 'Santos de Mello' a + b #Equivalentes ao operador de concatenação '+' a.__add__(b) str.__add__(a, b) len(a) #Equivalentes ao método len() normal a.__len__() str.__len__(a) '1' in a #Equivalentes ao operador membro 'in' a.__contains__('1') str.__contains__(a, '1')
21.356061
99
0.719759
#%% [markdown] ## Strings (parte 1) dir(str) nome = 'Victor Mello' nome #Acessando um caracter de uma string nome[0] # nome[0] = 'P' #Erro! Strings são imutáveis """OBS: quando se tem uma string cujo conteúdo já possui aspas simples, para evitar erro de sintaxe, tem-se 2 opções: 1) Delimitar a string com aspas duplas e dentro dela colocar entre aspas simples; 2) Delimitar a string com aspas simples, mas utilizando o caracter de escape \ antes de colocar mais aspas simples no conteúdo """ #Exemplo "Marca d'água" == 'Marca d\'água' texto = "Teste \"funciona!" """Texto com múltiplas linhas com \, mas é executado um texto de uma única linha""" #Exemplo texto2 = 'Texto entre \ apóstrofos pode ter "aspas"' texto3 = """Texto com múltiplas linhas com aspas triplas, assim como comentário""" #Neste caso, será impresso um texto de uma única linha com \n indicando quebra de linha texto3 #No entanto, com print(), o resultado é de fato um texto com quebra de linhas print(texto3) #Da mesma forma se imprimir um texto da mesma linha com \n print('Texto com múltiplas linhas com aspas triplas,\nassim como comentário') # %% [markdown] ## Strings (Parte 2) #Acessando o caracter da string da direita para esquerda nome[-4] #Acessando uma substring a partir de um conjunto de caracteres nome[4:] #Começando com índice 4 nome[-5:] #Começando com índice -5, da direita para esqueda #Acessando do início da string até o índice 6 (exclusive) nome[:6] #Acessando do índice 1 até o índice 4 (exclusive) nome[1:4] numeros = '123456789' numeros # numeros[::] #Equivalente ao resultado anterior numeros[::2] #Acessando os caracteres de 2 em 2 caracteres numeros[1::2] #Acessando os caracteres a partir de íncide 1, de 2 em 2 caracteres #Invertendo uma string numeros[::-1] #Invertendo uma string de 2 em 2 caracteres numeros[::-2] # %% [markdown] ## Strings (parte 3) frase = 'Olá, meu nome é Victor e sou legal' #Usando operador membro no contexto de string #Exemplo 1 'Vic' in frase 'vic' not in frase #Exibindo o tamanho da string len(frase) #Gerando uma nova string em caixa baixa frase.lower() 'vic' in frase.lower() #Gerando uma nova string em caixa alta frase.upper() 'VIC' in frase.upper() #Modificando o conteúdo da string frase = frase.upper() frase #Dividindo a string em um array de strings (substrings, melhor dizendo) frase.split() #Dividindo a string quebrando o caracter 'E' frase.split('E') # %% [markdown] ## Strings (parte 4) #Métodos mágicos de strings # dir(str) a = '123 ' b = 'Santos de Mello' a + b #Equivalentes ao operador de concatenação '+' a.__add__(b) str.__add__(a, b) len(a) #Equivalentes ao método len() normal a.__len__() str.__len__(a) '1' in a #Equivalentes ao operador membro 'in' a.__contains__('1') str.__contains__(a, '1')
0
0
0
02a06d266080beb3092c464049b0b79657ebae9b
6,665
py
Python
tests/test_kinematics.py
tp5uiuc/kinematic_snake
70a59a431d185a5fbe304b18db17eb3819ddbee1
[ "MIT" ]
2
2022-01-01T21:12:53.000Z
2022-01-02T16:23:09.000Z
tests/test_kinematics.py
tp5uiuc/kinematic_snake
70a59a431d185a5fbe304b18db17eb3819ddbee1
[ "MIT" ]
null
null
null
tests/test_kinematics.py
tp5uiuc/kinematic_snake
70a59a431d185a5fbe304b18db17eb3819ddbee1
[ "MIT" ]
null
null
null
import numpy as np from numpy.testing import assert_allclose from scipy.integrate import trapz import pytest from kinematic_snake.kinematic_snake import zero_mean_integral, project, KinematicSnake # TODO Add more tests
32.832512
87
0.628807
import numpy as np from numpy.testing import assert_allclose from scipy.integrate import trapz import pytest from kinematic_snake.kinematic_snake import zero_mean_integral, project, KinematicSnake class TestZeroMeanIntegral: @pytest.fixture(scope="class", params=[101, np.random.randint(100, 200)]) def load_sample_points(self, request): bs = request.param sample_points = np.linspace(0.0, 1.0, bs) sample_points = sample_points.reshape(1, -1) return sample_points @pytest.mark.parametrize("dim", [1, 2]) def test_integrity(self, load_sample_points, dim): sample_points = load_sample_points sampled_func = 1.0 + sample_points ** 2 if dim == 2: sampled_func = np.vstack((sampled_func, sampled_func)) zmi = zero_mean_integral(sampled_func, sample_points) assert zmi.shape == (dim, sample_points.shape[1]) assert_allclose(trapz(zmi, sample_points), np.zeros((dim)), atol=1e-12) @pytest.mark.parametrize( "func_pairs", [ (lambda x: np.sin(np.pi * x), lambda z: -np.cos(np.pi * z) / np.pi), (lambda x: 1.0 + x ** 3, lambda z: z + z ** 4 / 4.0 - 11.0 / 20.0), ], ) def test_accuracy(self, load_sample_points, func_pairs): test_func = func_pairs[0] correct_func = func_pairs[1] sample_points = load_sample_points sampled_test_func = test_func(sample_points) zmi_of_test_func = zero_mean_integral(sampled_test_func, sample_points) sampled_correct_func = correct_func(sample_points) assert_allclose(zmi_of_test_func, sampled_correct_func, rtol=1e-4, atol=1e-4) # TODO Add more tests class TestProjection: @pytest.mark.parametrize("proj_axis", ["x", "y"]) def test_accuracy_on_canonical_axes(self, proj_axis): vec = np.random.randn(2, 100) dir = [0.0, 0.0] if proj_axis == "x": ax_idx = 0 elif proj_axis == "y": ax_idx = 1 # Set unit vector on ax_idx dir[ax_idx] = 1.0 ax = np.array(dir).reshape(-1, 1) + 0.0 * vec mag, p = project(vec, ax) assert_allclose(mag, vec[ax_idx, :]) assert_allclose(np.flipud(p)[ax_idx, :], 0.0) def test_integrity_on_perpendicular_axes(self): vec = np.random.randn(2, 100) theta = np.random.uniform(0.0, 2.0 * np.pi) ax = [np.cos(theta), np.sin(theta)] perp_ax = [-np.sin(theta), np.cos(theta)] axis = np.array(ax).reshape(-1, 1) + 0.0 * vec perp_axis = np.array(perp_ax).reshape(-1, 1) + 0.0 * vec mag_par, p_par = project(vec, axis) mag_perp, p_perp = project(vec, perp_axis) # magnitues mag_vec_sq = np.einsum("ij,ij->j", vec, vec) assert_allclose(mag_par ** 2 + mag_perp ** 2, mag_vec_sq) # directions mag_pr, _ = project(p_par, p_perp) assert_allclose(mag_pr, 0.0 * mag_pr, rtol=1e-8, atol=1e-12) class TestKinematicSnake: @pytest.fixture(scope="class") def load_snake(self): froude_number = 0.1 friction_coefficients = {"mu_f": 0.1, "mu_b": 0.2, "mu_lat": 0.3} def activation(s, time): """Flat snake""" return 0.0 * (s + time) snake = KinematicSnake( froude_number=froude_number, friction_coefficients=friction_coefficients, samples=50, ) snake.set_activation(activation) snake._construct(0.0) return snake, friction_coefficients def test_forward_friction(self, load_snake): snake, fc = load_snake # Moves forward while snake faces forward # Activates only forward friction forces snake.dx_dt[0, ...] = 1.0 snake.dx_dt[1, ...] = 0.0 friction_force = snake.external_force_distribution(time=0.0) expected_force = 0.0 * snake.dx_dt expected_force[0, :] = -fc["mu_f"] assert_allclose(friction_force, expected_force) friction_torque = snake.external_torque_distribution(friction_force) expected_torque = 0.0 * friction_torque assert_allclose(friction_torque, expected_torque) def test_backward_friction(self, load_snake): snake, fc = load_snake # Moves backward while snake faces forward # Activates only forward friction forces snake.dx_dt[0, ...] = -1.0 snake.dx_dt[1, ...] = 0.0 friction_force = snake.external_force_distribution(time=0.0) expected_force = 0.0 * snake.dx_dt expected_force[0, :] = fc["mu_b"] assert_allclose(friction_force, expected_force) friction_torque = snake.external_torque_distribution(friction_force) expected_torque = 0.0 * friction_torque assert_allclose(friction_torque, expected_torque) def test_lateral_friction(self, load_snake): snake, fc = load_snake # Faces y axes, rolling frinction only! snake.dx_dt[0, ...] = 0.0 snake.dx_dt[1, ...] = 1.0 friction_force = snake.external_force_distribution(time=0.0) expected_force = 0.0 * snake.dx_dt expected_force[1, :] = -fc["mu_lat"] assert_allclose(friction_force, expected_force) friction_torque = snake.external_torque_distribution(friction_force) expected_torque = 0.0 assert_allclose(np.sum(friction_torque), expected_torque, atol=1e-6) def test_moment_of_inertia_accuracy(self, load_snake): """For a straight rod, compare against analytical solution Parameters ---------- load_snake Returns ------- """ snake, fc = load_snake moment_of_inertia = snake.calculate_moment_of_inertia() # 2 * (l/2)^3 / 3.0 expected_moment_of_inertia = 2.0 * (1.0 / 2.0) ** 3 / 3.0 assert_allclose( moment_of_inertia, expected_moment_of_inertia, rtol=1e-4, atol=1e-4 ) def test_internal_torque(self, load_snake): snake, fc = load_snake internal_torque = snake.internal_torque_distribution(time=0.0) expected_torque = 0.0 * internal_torque assert_allclose(internal_torque, expected_torque, atol=1e-6) def generate_unevenly_spaced_time_series(start=0.0, stop=2.0 * np.pi, size=(35,)): assert start < stop local_start = start local_stop = 0.5 * (start + stop) t = np.random.uniform(low=local_start, high=local_stop, size=size) def mirror(x): return 2.0 * local_stop - x t = np.hstack((np.array(start), t, mirror(t[::-1]), np.array(stop))) t = np.sort(t) return t
5,083
1,266
91
f0bd97a83ef68c7c33ba4c4c35408149131700ab
1,172
py
Python
open-ai-gym-lab/1. gym/ex01/gym1.py
hojeong3709/RL
a1c6eab8c3e7f2487e527fe68658d13eea5334af
[ "MIT" ]
null
null
null
open-ai-gym-lab/1. gym/ex01/gym1.py
hojeong3709/RL
a1c6eab8c3e7f2487e527fe68658d13eea5334af
[ "MIT" ]
null
null
null
open-ai-gym-lab/1. gym/ex01/gym1.py
hojeong3709/RL
a1c6eab8c3e7f2487e527fe68658d13eea5334af
[ "MIT" ]
null
null
null
import gym import numpy as np print(gym.__file__) print(dir(gym)) env = gym.make('FrozenLake-v0') q_table = np.zeros([env.observation_space.n, env.action_space.n]) print(env.render()) if __name__ == "__main__": lr = 0.8 discount_factor = 0.95 num_episodes = 2000 reward_list = [] for i in range(num_episodes): reward_total_sum = 0 done = False j = 0 current_state = env.reset() while j < 99: j += 1 action = np.argmax(q_table[current_state, :] + np.random.randn(1, env.action_space.n) * (1./(i + 1))) next_state, reward, done, _ = env.step(action) q_table[current_state, action] = q_table[current_state, action] + \ lr * (reward + discount_factor * np.max(q_table[next_state, :]) - q_table[current_state, action]) reward_total_sum += reward current_state = next_state if done: break reward_list.append(reward_total_sum) print('score over time:' + str(sum(reward_list)/num_episodes)) print(q_table)
29.3
113
0.562287
import gym import numpy as np print(gym.__file__) print(dir(gym)) env = gym.make('FrozenLake-v0') q_table = np.zeros([env.observation_space.n, env.action_space.n]) print(env.render()) if __name__ == "__main__": lr = 0.8 discount_factor = 0.95 num_episodes = 2000 reward_list = [] for i in range(num_episodes): reward_total_sum = 0 done = False j = 0 current_state = env.reset() while j < 99: j += 1 action = np.argmax(q_table[current_state, :] + np.random.randn(1, env.action_space.n) * (1./(i + 1))) next_state, reward, done, _ = env.step(action) q_table[current_state, action] = q_table[current_state, action] + \ lr * (reward + discount_factor * np.max(q_table[next_state, :]) - q_table[current_state, action]) reward_total_sum += reward current_state = next_state if done: break reward_list.append(reward_total_sum) print('score over time:' + str(sum(reward_list)/num_episodes)) print(q_table)
0
0
0
0a8a0a0e92b9c19993841104fa8221ea7e366c1f
46,575
py
Python
peripheral/tcc_u2213/config/tcc.py
Techdisc/Microchip
ea8391c689c4badbe2f9ac5181e21bbd5d9d1e54
[ "0BSD" ]
null
null
null
peripheral/tcc_u2213/config/tcc.py
Techdisc/Microchip
ea8391c689c4badbe2f9ac5181e21bbd5d9d1e54
[ "0BSD" ]
null
null
null
peripheral/tcc_u2213/config/tcc.py
Techdisc/Microchip
ea8391c689c4badbe2f9ac5181e21bbd5d9d1e54
[ "0BSD" ]
null
null
null
# coding: utf-8 """***************************************************************************** * Copyright (C) 2018 Microchip Technology Inc. and its subsidiaries. * * Subject to your compliance with these terms, you may use Microchip software * and any derivatives exclusively with Microchip products. It is your * responsibility to comply with third party license terms applicable to your * use of third party software (including open source software) that may * accompany Microchip software. * * THIS SOFTWARE IS SUPPLIED BY MICROCHIP "AS IS". NO WARRANTIES, WHETHER * EXPRESS, IMPLIED OR STATUTORY, APPLY TO THIS SOFTWARE, INCLUDING ANY IMPLIED * WARRANTIES OF NON-INFRINGEMENT, MERCHANTABILITY, AND FITNESS FOR A * PARTICULAR PURPOSE. * * IN NO EVENT WILL MICROCHIP BE LIABLE FOR ANY INDIRECT, SPECIAL, PUNITIVE, * INCIDENTAL OR CONSEQUENTIAL LOSS, DAMAGE, COST OR EXPENSE OF ANY KIND * WHATSOEVER RELATED TO THE SOFTWARE, HOWEVER CAUSED, EVEN IF MICROCHIP HAS * BEEN ADVISED OF THE POSSIBILITY OR THE DAMAGES ARE FORESEEABLE. TO THE * FULLEST EXTENT ALLOWED BY LAW, MICROCHIP'S TOTAL LIABILITY ON ALL CLAIMS IN * ANY WAY RELATED TO THIS SOFTWARE WILL NOT EXCEED THE AMOUNT OF FEES, IF ANY, * THAT YOU HAVE PAID DIRECTLY TO MICROCHIP FOR THIS SOFTWARE. *****************************************************************************""" global InterruptVector InterruptVector = [] global InterruptHandler InterruptHandler = [] global InterruptHandlerLock InterruptHandlerLock = [] global InterruptVectorUpdate InterruptVectorUpdate = [] global tccInstanceName global intPrev intPrev = 0 global numOfChannels tccSym_Channel_Menu = [] tccSym_Channel_CC = [] tccSym_Channel_Polarity = [] tccSym_Channel_Polarity_NPWM = [] tccSym_Channel_WAVE_SWAP = [] tccSym_Channel_WEXCTRL_DTIEN = [] tccSym_Channel_INTENSET_MC = [] tccSym_Channel_EVCTRL_MCEO = [] tccSym_Channel_EVCTRL_MCEI = [] tccSym_DRVCTRL_NRE_NRV = [] tccSym_PATT_PGE = [] tccSym_PATT_PGV = [] ################################################################################################### ########################################## Callbacks ############################################# ################################################################################################### ################################################################################ #### Dependency #### ################################################################################ global lastPwmChU lastPwmChU = 0 global lastPwmChV lastPwmChV = 1 global lastPwmChW lastPwmChW = 2 ################################################################################################### ########################################## Component ############################################# ###################################################################################################
50.735294
212
0.704369
# coding: utf-8 """***************************************************************************** * Copyright (C) 2018 Microchip Technology Inc. and its subsidiaries. * * Subject to your compliance with these terms, you may use Microchip software * and any derivatives exclusively with Microchip products. It is your * responsibility to comply with third party license terms applicable to your * use of third party software (including open source software) that may * accompany Microchip software. * * THIS SOFTWARE IS SUPPLIED BY MICROCHIP "AS IS". NO WARRANTIES, WHETHER * EXPRESS, IMPLIED OR STATUTORY, APPLY TO THIS SOFTWARE, INCLUDING ANY IMPLIED * WARRANTIES OF NON-INFRINGEMENT, MERCHANTABILITY, AND FITNESS FOR A * PARTICULAR PURPOSE. * * IN NO EVENT WILL MICROCHIP BE LIABLE FOR ANY INDIRECT, SPECIAL, PUNITIVE, * INCIDENTAL OR CONSEQUENTIAL LOSS, DAMAGE, COST OR EXPENSE OF ANY KIND * WHATSOEVER RELATED TO THE SOFTWARE, HOWEVER CAUSED, EVEN IF MICROCHIP HAS * BEEN ADVISED OF THE POSSIBILITY OR THE DAMAGES ARE FORESEEABLE. TO THE * FULLEST EXTENT ALLOWED BY LAW, MICROCHIP'S TOTAL LIABILITY ON ALL CLAIMS IN * ANY WAY RELATED TO THIS SOFTWARE WILL NOT EXCEED THE AMOUNT OF FEES, IF ANY, * THAT YOU HAVE PAID DIRECTLY TO MICROCHIP FOR THIS SOFTWARE. *****************************************************************************""" global InterruptVector InterruptVector = [] global InterruptHandler InterruptHandler = [] global InterruptHandlerLock InterruptHandlerLock = [] global InterruptVectorUpdate InterruptVectorUpdate = [] global tccInstanceName global intPrev intPrev = 0 global numOfChannels tccSym_Channel_Menu = [] tccSym_Channel_CC = [] tccSym_Channel_Polarity = [] tccSym_Channel_Polarity_NPWM = [] tccSym_Channel_WAVE_SWAP = [] tccSym_Channel_WEXCTRL_DTIEN = [] tccSym_Channel_INTENSET_MC = [] tccSym_Channel_EVCTRL_MCEO = [] tccSym_Channel_EVCTRL_MCEI = [] tccSym_DRVCTRL_NRE_NRV = [] tccSym_PATT_PGE = [] tccSym_PATT_PGV = [] ################################################################################################### ########################################## Callbacks ############################################# ################################################################################################### def tccEvsys(symbol, event): if(event["id"] == "TCC_EVCTRL_OVFEO"): Database.setSymbolValue("evsys", "GENERATOR_"+str(tccInstanceName.getValue())+"_OVF_ACTIVE", event["value"], 2) if(event["id"] == "TCC_EVCTRL_EVACT0"): if (event["value"] != 0): Database.setSymbolValue("evsys", "USER_"+str(tccInstanceName.getValue())+"_EV_0_READY", True, 2) else: Database.setSymbolValue("evsys", "USER_"+str(tccInstanceName.getValue())+"_EV_0_READY", False, 2) if(event["id"] == "TCC_EVCTRL_EVACT1"): if (event["value"] != 0): Database.setSymbolValue("evsys", "USER_"+str(tccInstanceName.getValue())+"_EV_1_READY", True, 2) else: Database.setSymbolValue("evsys", "USER_"+str(tccInstanceName.getValue())+"_EV_1_READY", False, 2) if("EVCTRL_MCEO" in event["id"]): mcInstance = event["id"].split("_")[2][:2] event_name = "_" + (mcInstance) + "_" + event["id"].split("_")[3] Database.setSymbolValue("evsys", "GENERATOR_"+str(tccInstanceName.getValue())+ str(event_name)+"_ACTIVE", event["value"], 2) if("EVCTRL_MCEI" in event["id"]): mcInstance = event["id"].split("_")[2][:2] event_name = "_" + (mcInstance) + "_" + event["id"].split("_")[3] Database.setSymbolValue("evsys", "USER_"+str(tccInstanceName.getValue())+ str(event_name)+"_READY", event["value"], 2) def updateTCCInterruptStatus(symbol, event): component = symbol.getComponent() # For single interrupt line for peripheral if len(InterruptVector) == 1: if (event["value"] == True): Database.setSymbolValue("core", InterruptVector[0], True, 2) Database.setSymbolValue("core", InterruptHandlerLock[0], True, 2) Database.setSymbolValue("core", InterruptHandler[0], tccInstanceName.getValue() + "_PWMInterruptHandler", 2) else: Database.setSymbolValue("core", InterruptVector[0], False, 2) Database.setSymbolValue("core", InterruptHandlerLock[0], False, 2) Database.setSymbolValue("core", InterruptHandler[0], tccInstanceName.getValue() + "_Handler", 2) # For multiple interrupt lines for peripheral else: if (event["id"] == "TCC_INTENSET_OVF") or (event["id"] == "TCC_INTENSET_FAULT0") or (event["id"] == "TCC_INTENSET_FAULT1"): if (component.getSymbolValue("TCC_INTENSET_OVF") or component.getSymbolValue("TCC_INTENSET_FAULT0") or component.getSymbolValue("TCC_INTENSET_FAULT1")): Database.setSymbolValue("core", InterruptVector[0], True, 2) Database.setSymbolValue("core", InterruptHandlerLock[0], True, 2) Database.setSymbolValue("core", InterruptHandler[0], tccInstanceName.getValue() + "_PWMInterruptHandler", 2) else: Database.setSymbolValue("core", InterruptVector[0], False, 2) Database.setSymbolValue("core", InterruptHandlerLock[0], False, 2) Database.setSymbolValue("core", InterruptHandler[0], tccInstanceName.getValue() + "_Handler", 2) else: mcInstance = int(event["id"].split("_")[-1]) Database.setSymbolValue("core", InterruptVector[mcInstance+1], event["value"], 2) Database.setSymbolValue("core", InterruptHandlerLock[mcInstance+1], event["value"], 2) if event["value"] == True: Database.setSymbolValue("core", InterruptHandler[mcInstance+1], InterruptHandler[mcInstance+1].split("_INTERRUPT_HANDLER")[0] + "_InterruptHandler", 2) else: Database.setSymbolValue("core", InterruptHandler[mcInstance+1], InterruptHandler[mcInstance+1].split("_INTERRUPT_HANDLER")[0] + "_Handler", 2) def updateTCCInterruptWarningStatus(symbol, event): global InterruptVectorUpdate global numOfChannels isVisible = False component = symbol.getComponent() if (component.getSymbolValue("TCC_INTENSET_OVF") or component.getSymbolValue("TCC_INTENSET_FAULT0") or component.getSymbolValue("TCC_INTENSET_FAULT1")): if (Database.getSymbolValue("core", InterruptVectorUpdate[0].split(".")[-1]) == True): isVisible = True else: for i in range(0, numOfChannels): if (component.getSymbolValue("TCC_INTENSET_MC_"+str(i)) == True): if (Database.getSymbolValue("core", InterruptVectorUpdate[1].split(".")[-1]) == True): isVisible = True if (isVisible == True): symbol.setVisible(True) else: symbol.setVisible(False) def updateTCCClockWarningStatus(symbol, event): if event["value"] == False: symbol.setVisible(True) else: symbol.setVisible(False) def tccDirVisible(symbol, event): if (event["id"] == "TCC_WAVE_WAVEGEN" and tccSym_Slave_Mode.getValue() == False): symObj = event["symbol"] if (symObj.getSelectedKey() == "NPWM"): symbol.setVisible(True) else: symbol.setVisible(False) elif (event["id"] == "TCC_SLAVE_MODE"): symbol.setVisible(not event["value"]) def tccFaultVisible(symbol, event): global tccSym_EVCTRL_EVACT0 global tccSym_EVCTRL_EVACT1 fault0 = tccSym_EVCTRL_EVACT0.getSelectedKey() fault1 = tccSym_EVCTRL_EVACT1.getSelectedKey() if "TCC_FAULT_COMMENT" in symbol.getID(): if (fault0 == "FAULT" or fault1 == "FAULT"): symbol.setVisible(False) else: symbol.setVisible(True) else: if (fault0 == "FAULT" or fault1 == "FAULT"): symbol.setVisible(True) else: symbol.setVisible(False) def tccDeadTimeVisible(symbol, event): if (tccSym_Channel_WEXCTRL_DTIEN[0].getValue() == True or tccSym_Channel_WEXCTRL_DTIEN[1].getValue() == True or tccSym_Channel_WEXCTRL_DTIEN[2].getValue() == True or tccSym_Channel_WEXCTRL_DTIEN[3].getValue() == True): symbol.setVisible(True) else: symbol.setVisible(False) def tccPattgenVisible(symbol, event): if(event["value"] == True): symbol.setVisible(True) else: symbol.setVisible(False) def tccPWMFreqCalc(symbol, event): if (tccSym_Slave_Mode.getValue() == False): clock_freq = Database.getSymbolValue("core", tccInstanceName.getValue()+"_CLOCK_FREQUENCY") if clock_freq == 0: clock_freq = 1 prescaler = int(tccSym_CTRLA_PRESCALER.getSelectedKey()[3:]) if (tccSym_WAVE_WAVEGEN.getValue() == 0): #single slope PWM slope = 1 period = tccSym_PER_PER.getValue() + 1 else: slope = 2 period = tccSym_PER_PER.getValue() frequency = ((clock_freq / prescaler) / period) / slope symbol.setLabel("**** PWM Frequency is " +str(frequency)+ " Hz ****") symbol.setVisible(True) elif (event["id"] == "TCC_SLAVE_MODE"): symbol.setVisible(not event["value"]) def tccDeadTimeCalc(symbol, event): clock_freq = Database.getSymbolValue("core", tccInstanceName.getValue()+"_CLOCK_FREQUENCY") if clock_freq == 0: clock_freq = 1 if (symbol.getID() == "TCC_DTLS_COMMENT"): dead_time = (tccSym_WEXCTRL_DTLS.getValue() * 1000000.0 / (clock_freq)) symbol.setLabel("**** Low side dead time is "+str(dead_time)+ " uS ****") if (symbol.getID() == "TCC_DTHS_COMMENT"): dead_time = (tccSym_WEXCTRL_DTHS.getValue() * 1000000.0 / (clock_freq)) symbol.setLabel("**** High side dead time is "+str(dead_time)+ " uS ****") def tccSlaveCommentVisible(symbol, event): symbol.setVisible(event["value"]) def tccSlaveModeVisibility(symbol, event): symbol.setVisible(not event["value"]) def tccIpEventVisible(symbol, event): symbol.setVisible(event["value"]) def tccEvent0Visible(symbol, event): if event["value"] == 1 or event["value"] == 2: symbol.setVisible(False) else: symbol.setVisible(True) def tccSingleSlopeVisible(symbol, event): if (event["value"] == 0): symbol.setVisible(True) else: symbol.setVisible(False) def tccDualSlopeVisible(symbol, event): if (event["value"] != 0): symbol.setVisible(True) else: symbol.setVisible(False) ################################################################################ #### Dependency #### ################################################################################ def onAttachmentConnected(source, target): localComponent = source["component"] remoteComponent = target["component"] remoteID = remoteComponent.getID() connectID = source["id"] targetID = target["id"] def onAttachmentDisconnected(source, target): localComponent = source["component"] remoteComponent = target["component"] remoteID = remoteComponent.getID() connectID = source["id"] targetID = target["id"] resetChannels() global lastPwmChU lastPwmChU = 0 global lastPwmChV lastPwmChV = 1 global lastPwmChW lastPwmChW = 2 def resetChannels(): global lastPwmChU global lastPwmChV global lastPwmChW component = str(tccInstanceName.getValue()).lower() #disbale interrupt Database.setSymbolValue(component, "TCC_EVCTRL_EVACT1", 0) Database.setSymbolValue(component, "TCC_INTENSET_FAULT1", False) def handleMessage(messageID, args): global lastPwmChU global lastPwmChV global lastPwmChW component = str(tccInstanceName.getValue()).lower() dict = {} if (messageID == "PMSM_FOC_PWM_CONF"): resetChannels() dict['PWM_MAX_CH'] = 4 lastPwmChU = pwmChU = args['PWM_PH_U'] lastPwmChV = pwmChV = args['PWM_PH_V'] lastPwmChW = pwmChW = args['PWM_PH_W'] freq = args['PWM_FREQ'] clock = int(Database.getSymbolValue("core", tccInstanceName.getValue() + "_CLOCK_FREQUENCY")) period = int(clock)/int(freq)/2 Database.setSymbolValue(component, "TCC_PER_PER", period) Database.setSymbolValue(component, "TCC_WAVE_WAVEGEN", 1) Database.setSymbolValue(component, "TCC_EVCTRL_OVFEO", True) Database.setSymbolValue(component, "TCC_"+str(pwmChU)+"_CC", 0) Database.setSymbolValue(component, "TCC_"+str(pwmChV)+"_CC", 0) Database.setSymbolValue(component, "TCC_"+str(pwmChW)+"_CC", 0) #macros for channel numbers Database.setSymbolValue(component, "PWM_PH_U", tccInstanceName.getValue()+"_CHANNEL"+str(pwmChU)) Database.setSymbolValue(component, "PWM_PH_V", tccInstanceName.getValue()+"_CHANNEL"+str(pwmChV)) Database.setSymbolValue(component, "PWM_PH_W", tccInstanceName.getValue()+"_CHANNEL"+str(pwmChW)) Database.setSymbolValue(component, "INTR_PWM_FAULT", tccInstanceName.getValue()+"_OTHER_IRQn") mask = (1 << pwmChU) + (1 << pwmChV) + (1 << pwmChW) tccPhMask.setValue(mask) tccPatternMask.setValue((mask << 4) + mask) #dead-Time dt = args['PWM_DEAD_TIME'] deadtime = int((clock) * float(dt)) / 1000000 Database.setSymbolValue(component, "TCC_"+str(pwmChU)+"_WEXCTRL_DTIEN", True) Database.setSymbolValue(component, "TCC_"+str(pwmChV)+"_WEXCTRL_DTIEN", True) Database.setSymbolValue(component, "TCC_"+str(pwmChW)+"_WEXCTRL_DTIEN", True) Database.setSymbolValue(component, "TCC_WEXCTRL_DTHS", deadtime) Database.setSymbolValue(component, "TCC_WEXCTRL_DTLS", deadtime) #Fault Database.setSymbolValue(component, "TCC_EVCTRL_EVACT1", 5) Database.setSymbolValue(component, "TCC_INTENSET_FAULT1", True) fault = args['PWM_FAULT'] Database.setSymbolValue(component, "TCC_0_DRVCTRL_NRE_NRV", 1) Database.setSymbolValue(component, "TCC_1_DRVCTRL_NRE_NRV", 1) Database.setSymbolValue(component, "TCC_2_DRVCTRL_NRE_NRV", 1) Database.setSymbolValue(component, "TCC_3_DRVCTRL_NRE_NRV", 1) Database.setSymbolValue(component, "TCC_4_DRVCTRL_NRE_NRV", 1) Database.setSymbolValue(component, "TCC_5_DRVCTRL_NRE_NRV", 1) Database.setSymbolValue(component, "TCC_6_DRVCTRL_NRE_NRV", 1) Database.setSymbolValue(component, "TCC_7_DRVCTRL_NRE_NRV", 1) return dict ################################################################################################### ########################################## Component ############################################# ################################################################################################### def instantiateComponent(tccComponent): global InterruptVector global InterruptHandler global InterruptHandlerLock global tccInstanceName global tccSym_INTENSET_OVF global InterruptVectorUpdate eventDepList = [] interruptDepList = [] tccInstanceName = tccComponent.createStringSymbol("TCC_INSTANCE_NAME", None) tccInstanceName.setVisible(False) tccInstanceName.setDefaultValue(tccComponent.getID().upper()) #clock enable Database.setSymbolValue("core", tccInstanceName.getValue() + "_CLOCK_ENABLE", True, 2) ################################ ATDF #################################################### node = ATDF.getNode("/avr-tools-device-file/devices/device/peripherals/module@[name=\"TCC\"]/instance@[name=\""+tccInstanceName.getValue()+"\"]/parameters") global numOfChannels numOfChannels = 4 deadTimeImplemented = 1 swapImplemented = 1 outputMatrixImplemented = 1 patternGenImplemented = 1 numOfOutputs = 8 size = 24 parameters = [] parameters = node.getChildren() for param in range (0, len(parameters)): if(parameters[param].getAttribute("name") == "CC_NUM"): numOfChannels = int(parameters[param].getAttribute("value")) if(parameters[param].getAttribute("name") == "DTI"): deadTimeImplemented = int(parameters[param].getAttribute("value")) if(parameters[param].getAttribute("name") == "SWAP"): swapImplemented = int(parameters[param].getAttribute("value")) if(parameters[param].getAttribute("name") == "OTMX"): outputMatrixImplemented = int(parameters[param].getAttribute("value")) if(parameters[param].getAttribute("name") == "OW_NUM"): numOfOutputs = int(parameters[param].getAttribute("value")) if(parameters[param].getAttribute("name") == "PG"): patternGenImplemented = int(parameters[param].getAttribute("value")) if(parameters[param].getAttribute("name") == "SIZE"): size = int(parameters[param].getAttribute("value")) tccSym_NUM_CHANNELS = tccComponent.createIntegerSymbol("TCC_NUM_CHANNELS", None) tccSym_NUM_CHANNELS.setDefaultValue(int(numOfChannels)) tccSym_NUM_CHANNELS.setVisible(False) tccSym_NUM_OUTPUTS = tccComponent.createIntegerSymbol("TCC_NUM_OUTPUTS", None) tccSym_NUM_OUTPUTS.setDefaultValue(int(numOfOutputs)) tccSym_NUM_OUTPUTS.setVisible(False) tccSym_Is_DeadTime = tccComponent.createIntegerSymbol("TCC_IS_DEAD_TIME", None) tccSym_Is_DeadTime.setDefaultValue(int(deadTimeImplemented)) tccSym_Is_DeadTime.setVisible(False) tccSym_Is_Swap = tccComponent.createIntegerSymbol("TCC_IS_SWAP", None) tccSym_Is_Swap.setDefaultValue(int(swapImplemented)) tccSym_Is_Swap.setVisible(False) tccSym_Is_OTM = tccComponent.createIntegerSymbol("TCC_IS_OTM", None) tccSym_Is_OTM.setDefaultValue(int(outputMatrixImplemented)) tccSym_Is_OTM.setVisible(False) tccSym_Is_PG = tccComponent.createIntegerSymbol("TCC_IS_PG", None) tccSym_Is_PG.setDefaultValue(int(patternGenImplemented)) tccSym_Is_PG.setVisible(False) tccSym_SIZE = tccComponent.createIntegerSymbol("TCC_SIZE", None) tccSym_SIZE.setDefaultValue(int(size)) tccSym_SIZE.setVisible(False) tccSym_MCU_FAMILY = tccComponent.createStringSymbol("TCC_MCU_FAMILY", None) tccSym_MCU_FAMILY.setVisible(False) node = ATDF.getNode("/avr-tools-device-file/devices") series = node.getChildren()[0].getAttribute("family") tccSym_MCU_FAMILY.setDefaultValue(node.getChildren()[0].getAttribute("family")) node = ATDF.getNode("/avr-tools-device-file/modules/module@[name=\"TCC\"]/register-group@[name=\"TCC\"]") register_names = [] register_names = node.getChildren() tccSym_CBUF_REG_NAME = tccComponent.createStringSymbol("TCC_CBUF_REG_NAME", None) tccSym_CBUF_REG_NAME.setVisible(False) for index in range(0, len(register_names)): if "CCBUF" in register_names[index].getAttribute("name"): tccSym_CBUF_REG_NAME.setDefaultValue("CCBUF") break else: tccSym_CBUF_REG_NAME.setDefaultValue("CCB") tccSym_PBUF_REG_NAME = tccComponent.createStringSymbol("TCC_PBUF_REG_NAME", None) tccSym_PBUF_REG_NAME.setVisible(False) for index in range(0, len(register_names)): if "PERBUF" in register_names[index].getAttribute("name"): tccSym_PBUF_REG_NAME.setDefaultValue("PERBUF") break else: tccSym_PBUF_REG_NAME.setDefaultValue("PERB") tccSym_PATBUF_REG_NAME = tccComponent.createStringSymbol("TCC_PATBUF_REG_NAME", None) tccSym_PATBUF_REG_NAME.setVisible(False) for index in range(0, len(register_names)): if "PATTBUF" in register_names[index].getAttribute("name"): tccSym_PATBUF_REG_NAME.setDefaultValue("PATTBUF") break else: tccSym_PATBUF_REG_NAME.setDefaultValue("PATTB") # master slave mode tccInstanceMasterValue = 0 tccInstanceMasterNode = ATDF.getNode("/avr-tools-device-file/devices/device/peripherals/module@[name=\"TCC\"]/instance@[name=\""+tccInstanceName.getValue()+"\"]/parameters/param@[name=\"MASTER_SLAVE_MODE\"]") if (tccInstanceMasterNode != None): tccInstanceMasterValue = int(tccInstanceMasterNode.getAttribute("value")) if (tccInstanceMasterValue == 2): #slave activeComponentList = Database.getActiveComponentIDs() temp = int(tccInstanceName.getValue().split("TCC")[1]) masterComponentID = "TCC" + str(temp - 1) global tccSym_Slave_Mode tccSym_Slave_Mode = tccComponent.createBooleanSymbol("TCC_SLAVE_MODE", None) tccSym_Slave_Mode.setLabel("Enable Slave") tccSym_Slave_Mode.setDefaultValue(False) if ((tccInstanceMasterValue == 2)): tccSym_Slave_Mode.setVisible(True) else: tccSym_Slave_Mode.setVisible(False) if (tccInstanceMasterValue == 2): #slave tccSym_Slave_Mode_Comment = tccComponent.createCommentSymbol("TCC_SLAVE_MODE_COMMENT", None) tccSym_Slave_Mode_Comment.setLabel("**** Ensure Master - " + str(masterComponentID) + " is in active components ****") tccSym_Slave_Mode_Comment.setVisible(False) tccSym_Slave_Mode_Comment.setDependencies(tccSlaveCommentVisible, ["TCC_SLAVE_MODE"]) ########################################################################################### #------------------------Motor Control APIs---------------------------------------------------- tccStartApi = tccComponent.createStringSymbol("PWM_START_API", None) tccStartApi.setVisible(False) tccStartApi.setValue(tccInstanceName.getValue()+"_PWMStart") tccStopApi = tccComponent.createStringSymbol("PWM_STOP_API", None) tccStopApi.setVisible(False) tccStopApi.setValue(tccInstanceName.getValue()+"_PWMStop") tccPeriodApi = tccComponent.createStringSymbol("PWM_GET_PERIOD_API", None) tccPeriodApi.setVisible(False) tccPeriodApi.setValue(tccInstanceName.getValue()+"_PWM"+str(size)+"bitPeriodGet") tccDutyApi = tccComponent.createStringSymbol("PWM_SET_DUTY_API", None) tccDutyApi.setVisible(False) tccDutyApi.setValue(tccInstanceName.getValue() + "_PWM"+str(size)+"bitDutySet") tccOpDisableApi = tccComponent.createStringSymbol("PWM_OUTPUT_DISABLE_API", None) tccOpDisableApi.setVisible(False) tccOpDisableApi.setValue(tccInstanceName.getValue() + "_PWMPatternSet") tccOpEnableApi = tccComponent.createStringSymbol("PWM_OUTPUT_ENABLE_API", None) tccOpEnableApi.setVisible(False) tccOpEnableApi.setValue(tccInstanceName.getValue() + "_PWMPatternSet") tccCallbackApi = tccComponent.createStringSymbol("PWM_CALLBACK_API", None) tccCallbackApi.setVisible(False) tccCallbackApi.setValue(tccInstanceName.getValue() + "_PWMCallbackRegister") tccPhU = tccComponent.createStringSymbol("PWM_PH_U", None) tccPhU.setVisible(False) tccPhU.setValue(tccInstanceName.getValue() + "CHANNEL0") tccPhV = tccComponent.createStringSymbol("PWM_PH_V", None) tccPhV.setVisible(False) tccPhV.setValue(tccInstanceName.getValue() + "CHANNEL1") tccPhW = tccComponent.createStringSymbol("PWM_PH_W", None) tccPhW.setVisible(False) tccPhW.setValue(tccInstanceName.getValue() + "CHANNEL2") global tccPhMask tccPhMask = tccComponent.createHexSymbol("PWM_PH_MASK", None) tccPhMask.setVisible(False) tccPhMask.setValue(0x7) global tccPatternMask tccPatternMask = tccComponent.createHexSymbol("PWM_PATTERN_MASK", None) tccPatternMask.setVisible(False) tccPatternMask.setValue(0x77) tccFaultInt = tccComponent.createStringSymbol("INTR_PWM_FAULT", None) tccFaultInt.setVisible(False) tccFaultInt.setValue(tccInstanceName.getValue()+"_OTHER_IRQn") #----------------------------------------------------------------------------------------------------------- #prescaler configuration global tccSym_CTRLA_PRESCALER tccSym_CTRLA_PRESCALER = tccComponent.createKeyValueSetSymbol("TCC_CTRLA_PRESCALER", None) tccSym_CTRLA_PRESCALER.setLabel("Select Prescaler") tccSym_CTRLA_PRESCALER.setDefaultValue(0) tccSym_CTRLA_PRESCALER.setOutputMode("Key") tccSym_CTRLA_PRESCALER.setDisplayMode("Description") node = ATDF.getNode("/avr-tools-device-file/modules/module@[name=\"TCC\"]/value-group@[name=\"TCC_CTRLA__PRESCALER\"]") values = [] values = node.getChildren() for index in range(0, len(values)): tccSym_CTRLA_PRESCALER.addKey(values[index].getAttribute("name"), values[index].getAttribute("value"), values[index].getAttribute("caption")) tccSym_CTRLA_PRESCALER.setDependencies(tccSlaveModeVisibility, ["TCC_SLAVE_MODE"]) #waveform option global tccSym_WAVE_WAVEGEN tccSym_WAVE_WAVEGEN = tccComponent.createKeyValueSetSymbol("TCC_WAVE_WAVEGEN", None) tccSym_WAVE_WAVEGEN.setLabel("Select PWM Type") tccSym_WAVE_WAVEGEN.setDefaultValue(0) tccSym_WAVE_WAVEGEN.setOutputMode("Key") tccSym_WAVE_WAVEGEN.setDisplayMode("Description") tccSym_WAVE_WAVEGEN.addKey("NPWM", "2", "Single slope PWM") tccSym_WAVE_WAVEGEN.addKey("DSBOTTOM", "5", "Dual slope PWM with interrupt/event when counter = ZERO") tccSym_WAVE_WAVEGEN.addKey("DSBOTH", "6", "Dual slope PWM with interrupt/event when counter = ZERO or counter = TOP") tccSym_WAVE_WAVEGEN.addKey("DSTOP", "7", "Dual slope PWM with interrupt/event when counter = TOP") tccSym_WAVE_WAVEGEN.setDependencies(tccSlaveModeVisibility, ["TCC_SLAVE_MODE"]) tccSym_CTRLBSET_DIR = tccComponent.createBooleanSymbol("TCC_CTRLBSET_DIR", None) tccSym_CTRLBSET_DIR.setLabel("PWM Direction - Count Down") tccSym_CTRLBSET_DIR.setDefaultValue(False) tccSym_CTRLBSET_DIR.setDependencies(tccDirVisible, ["TCC_WAVE_WAVEGEN", "TCC_SLAVE_MODE"]) if (outputMatrixImplemented == 1): tccSym_WEXCTRL_OTMX = tccComponent.createKeyValueSetSymbol("TCC_WEXCTRL_OTMX", None) tccSym_WEXCTRL_OTMX.setLabel("Select Output Matrix") tccSym_WEXCTRL_OTMX.setDefaultValue(0) tccSym_WEXCTRL_OTMX.setOutputMode("Value") tccSym_WEXCTRL_OTMX.setDisplayMode("Description") tccSym_WEXCTRL_OTMX.addKey("OTMX_0", "0", "Default Channel Outputs") tccSym_WEXCTRL_OTMX.addKey("OTMX_1", "1", "Modulo Half Number of Channel Outputs") tccSym_WEXCTRL_OTMX.addKey("OTMX_2", "2", "Only Channel 0 Outputs") tccSym_WEXCTRL_OTMX.addKey("OTMX_3", "3", "Channel 0 + Remaining Channel 1 Outputs") #Period Value global tccSym_PER_PER tccSym_PER_PER = tccComponent.createIntegerSymbol("TCC_PER_PER", None) tccSym_PER_PER.setLabel("Period Value") tccSym_PER_PER.setDefaultValue(2399) tccSym_PER_PER.setMin(0) tccSym_PER_PER.setMax(pow(2, size) - 1) tccSym_PER_PER.setDependencies(tccSlaveModeVisibility, ["TCC_SLAVE_MODE"]) clock_freq = Database.getSymbolValue("core", tccInstanceName.getValue()+"_CLOCK_FREQUENCY") if clock_freq == 0: clock_freq = 1 prescaler = int(tccSym_CTRLA_PRESCALER.getSelectedKey()[3:]) if (tccSym_WAVE_WAVEGEN.getValue() == 0): slope = 1 period = tccSym_PER_PER.getValue() + 1 else: slope = 2 period = tccSym_PER_PER.getValue() frequency = ((clock_freq / prescaler) / period) / slope #Calculated frequency tccSym_Frequency = tccComponent.createCommentSymbol("TCC_FREQUENCY", None) tccSym_Frequency.setLabel("**** PWM Frequency is "+str(frequency)+" Hz ****") tccSym_Frequency.setDependencies(tccPWMFreqCalc, ["core."+tccInstanceName.getValue()+"_CLOCK_FREQUENCY", "TCC_PER_PER", "TCC_WAVE_WAVEGEN", "TCC_CTRLA_PRESCALER", "TCC_SLAVE_MODE"]) #Period interrupt tccSym_INTENSET_OVF = tccComponent.createBooleanSymbol("TCC_INTENSET_OVF", None) tccSym_INTENSET_OVF.setLabel("Enable Period Interrupt") tccSym_INTENSET_OVF.setDefaultValue(False) interruptDepList.append("TCC_INTENSET_OVF") #Period out event tccSym_EVCTRL_OVFEO = tccComponent.createBooleanSymbol("TCC_EVCTRL_OVFEO", None) tccSym_EVCTRL_OVFEO.setLabel("Enable Period Event Out") tccSym_EVCTRL_OVFEO.setDefaultValue(False) eventDepList.append("TCC_EVCTRL_OVFEO") tccSym_MainChannel_Menu = tccComponent.createMenuSymbol("TCC_CHANNEL", None) tccSym_MainChannel_Menu.setLabel("Channel Configurations") for channelID in range(0, int(numOfChannels)): #channel menu tccSym_Channel_Menu.append(channelID) tccSym_Channel_Menu[channelID] = tccComponent.createMenuSymbol("TCC_CHANNEL"+str(channelID), tccSym_MainChannel_Menu) tccSym_Channel_Menu[channelID].setLabel("Channel "+str(channelID)) #Duty tccSym_Channel_CC.append(channelID) tccSym_Channel_CC[channelID] = tccComponent.createIntegerSymbol("TCC_"+str(channelID)+"_CC", tccSym_Channel_Menu[channelID]) tccSym_Channel_CC[channelID].setLabel("Duty Value") tccSym_Channel_CC[channelID].setMin(0) tccSym_Channel_CC[channelID].setMax(pow(2, size) - 1) #output polarity for dual slope tccSym_Channel_Polarity.append(channelID) tccSym_Channel_Polarity[channelID] = tccComponent.createKeyValueSetSymbol("TCC_"+str(channelID)+"_WAVE_POL", tccSym_Channel_Menu[channelID]) tccSym_Channel_Polarity[channelID].setLabel("Output Polarity") tccSym_Channel_Polarity[channelID].addKey("LOW","0","Output is ~DIR when counter matches CCx value") tccSym_Channel_Polarity[channelID].addKey("HIGH","1","Output is DIR when counter matches CCx value") tccSym_Channel_Polarity[channelID].setOutputMode("Value") tccSym_Channel_Polarity[channelID].setDisplayMode("Description") tccSym_Channel_Polarity[channelID].setVisible(False) tccSym_Channel_Polarity[channelID].setDependencies(tccDualSlopeVisible, ["TCC_WAVE_WAVEGEN"]) #output polarity for single slope tccSym_Channel_Polarity_NPWM.append(channelID) tccSym_Channel_Polarity_NPWM[channelID] = tccComponent.createKeyValueSetSymbol("TCC_"+str(channelID)+"_WAVE_POL_NPWM", tccSym_Channel_Menu[channelID]) tccSym_Channel_Polarity_NPWM[channelID].setLabel("Output Polarity") tccSym_Channel_Polarity_NPWM[channelID].addKey("LOW","0","Output is ~DIR and set to DIR when counter matches CCx value") tccSym_Channel_Polarity_NPWM[channelID].addKey("HIGH","1","Output is DIR and set to ~DIR when counter matches CCx value") tccSym_Channel_Polarity_NPWM[channelID].setOutputMode("Value") tccSym_Channel_Polarity_NPWM[channelID].setDisplayMode("Description") tccSym_Channel_Polarity_NPWM[channelID].setVisible(True) tccSym_Channel_Polarity_NPWM[channelID].setDependencies(tccSingleSlopeVisible, ["TCC_WAVE_WAVEGEN"]) if (deadTimeImplemented == 1 and (channelID < (numOfOutputs/2))): #dead time tccSym_Channel_WEXCTRL_DTIEN.append(channelID) tccSym_Channel_WEXCTRL_DTIEN[channelID] = tccComponent.createBooleanSymbol("TCC_"+str(channelID)+"_WEXCTRL_DTIEN", tccSym_Channel_Menu[channelID]) tccSym_Channel_WEXCTRL_DTIEN[channelID].setLabel("Enable Dead Time") tccSym_Channel_WEXCTRL_DTIEN[channelID].setDefaultValue(True) if (swapImplemented == 1 and (channelID < (numOfOutputs/2))): #swap dead time outputs tccSym_Channel_WAVE_SWAP.append(channelID) tccSym_Channel_WAVE_SWAP[channelID] = tccComponent.createBooleanSymbol("TCC_"+str(channelID)+"_WAVE_SWAP", tccSym_Channel_Menu[channelID]) tccSym_Channel_WAVE_SWAP[channelID].setLabel("Swap Outputs") tccSym_Channel_WAVE_SWAP[channelID].setDefaultValue(False) #compare match event out tccSym_Channel_INTENSET_MC.append(channelID) tccSym_Channel_INTENSET_MC[channelID] = tccComponent.createBooleanSymbol("TCC_INTENSET_MC_"+str(channelID), tccSym_Channel_Menu[channelID]) tccSym_Channel_INTENSET_MC[channelID].setLabel("Enable Compare Match Interrupt") tccSym_Channel_INTENSET_MC[channelID].setDefaultValue(False) interruptDepList.append("TCC_INTENSET_MC_"+str(channelID)) #compare match event out tccSym_Channel_EVCTRL_MCEO.append(channelID) tccSym_Channel_EVCTRL_MCEO[channelID] = tccComponent.createBooleanSymbol("TCC_EVCTRL_MCEO_"+str(channelID), tccSym_Channel_Menu[channelID]) tccSym_Channel_EVCTRL_MCEO[channelID].setLabel("Enable Compare Match Event OUT") tccSym_Channel_EVCTRL_MCEO[channelID].setDefaultValue(False) eventDepList.append("TCC_EVCTRL_MCEO_"+str(channelID)) #compare match event in tccSym_Channel_EVCTRL_MCEI.append(channelID) tccSym_Channel_EVCTRL_MCEI[channelID] = tccComponent.createBooleanSymbol("TCC_EVCTRL_MCEI_"+str(channelID), tccSym_Channel_Menu[channelID]) tccSym_Channel_EVCTRL_MCEI[channelID].setLabel("Enable Compare Match Event IN") tccSym_Channel_EVCTRL_MCEI[channelID].setDefaultValue(False) eventDepList.append("TCC_EVCTRL_MCEI_"+str(channelID)) #dead time menu tccSym_DeadTime_Menu = tccComponent.createMenuSymbol("TCC_DEAD_TIME_MENU", None) tccSym_DeadTime_Menu.setLabel("Dead Time") if (deadTimeImplemented == 1): tccSym_DeadTime_Menu.setVisible(True) else: tccSym_DeadTime_Menu.setVisible(False) tccSym_DeadTime_Menu.setDependencies(tccDeadTimeVisible, ["TCC_0_WEXCTRL_DTIEN","TCC_1_WEXCTRL_DTIEN", "TCC_2_WEXCTRL_DTIEN", "TCC_3_WEXCTRL_DTIEN"]) #Low dead time global tccSym_WEXCTRL_DTLS tccSym_WEXCTRL_DTLS = tccComponent.createIntegerSymbol("TCC_WEXCTRL_DTLS", tccSym_DeadTime_Menu) tccSym_WEXCTRL_DTLS.setLabel("Dead Time for Low Side Output") tccSym_WEXCTRL_DTLS.setDefaultValue(64) tccSym_WEXCTRL_DTLS.setMin(0) tccSym_WEXCTRL_DTLS.setMax(255) low_deadtime = (tccSym_WEXCTRL_DTLS.getValue() * 1000000.0 / (clock_freq)) tccSym_DTLS_COMMENT = tccComponent. createCommentSymbol("TCC_DTLS_COMMENT", tccSym_DeadTime_Menu) tccSym_DTLS_COMMENT.setLabel("**** Low side dead time is "+str(low_deadtime)+ " uS ****") tccSym_DTLS_COMMENT.setDependencies(tccDeadTimeCalc, ["TCC_WEXCTRL_DTLS", "core."+tccInstanceName.getValue()+"_CLOCK_FREQUENCY", "TCC_CTRLA_PRESCALER"]) #High dead time global tccSym_WEXCTRL_DTHS tccSym_WEXCTRL_DTHS = tccComponent.createIntegerSymbol("TCC_WEXCTRL_DTHS", tccSym_DeadTime_Menu) tccSym_WEXCTRL_DTHS.setLabel("Dead Time for High Side Output") tccSym_WEXCTRL_DTHS.setDefaultValue(64) tccSym_WEXCTRL_DTHS.setMin(0) tccSym_WEXCTRL_DTHS.setMax(255) high_deadtime = (tccSym_WEXCTRL_DTHS.getValue() * 1000000.0 / (clock_freq)) tccSym_DTHS_COMMENT = tccComponent. createCommentSymbol("TCC_DTHS_COMMENT", tccSym_DeadTime_Menu) tccSym_DTHS_COMMENT.setLabel("**** High side dead time is "+str(high_deadtime)+ " uS ****") tccSym_DTHS_COMMENT.setDependencies(tccDeadTimeCalc, ["TCC_WEXCTRL_DTHS", "core."+tccInstanceName.getValue()+"_CLOCK_FREQUENCY", "TCC_CTRLA_PRESCALER"]) if (patternGenImplemented == 1): #Pattern Generation menu tccSym_PatGen_Menu = tccComponent.createMenuSymbol("TCC_PATGEN_MENU", None) tccSym_PatGen_Menu.setLabel("Pattern Generation") for output in range(0, numOfOutputs): tccSym_PATT_PGE.append(output) tccSym_PATT_PGE[output] = tccComponent.createBooleanSymbol("TCC_"+str(output)+"PATT_PGE", tccSym_PatGen_Menu) tccSym_PATT_PGE[output].setLabel("Enable for Output " +str(output)) tccSym_PATT_PGE[output].setDefaultValue(False) tccSym_PATT_PGV.append(output) tccSym_PATT_PGV[output] = tccComponent.createKeyValueSetSymbol("TCC_"+str(output)+"PATT_PGV", tccSym_PATT_PGE[output]) tccSym_PATT_PGV[output].setLabel("Select Pattern Level for Output " +str(output)) tccSym_PATT_PGV[output].setVisible(False) tccSym_PATT_PGV[output].addKey("Low", "0", "Low") tccSym_PATT_PGV[output].addKey("High", "1", "High") tccSym_PATT_PGV[output].setOutputMode("Value") tccSym_PATT_PGV[output].setDisplayMode("Description") tccSym_PATT_PGV[output].setDependencies(tccPattgenVisible, ["TCC_"+str(output)+"PATT_PGE"]) tccSym_InputEvents_Menu = tccComponent.createMenuSymbol("TCC_INPUT_EVENTS", None) tccSym_InputEvents_Menu.setLabel("Input Events Configuration") global tccSym_EVCTRL_EVACT0 tccSym_EVCTRL_EVACT0 = tccComponent.createKeyValueSetSymbol("TCC_EVCTRL_EVACT0", tccSym_InputEvents_Menu) tccSym_EVCTRL_EVACT0.setLabel("Select Input Event 0 Action") tccSym_EVCTRL_EVACT0.addKey("OFF", "0", "Disabled") tccSym_EVCTRL_EVACT0.addKey("RETRIGGER", "1", "Start, restart or retrigger counter") tccSym_EVCTRL_EVACT0.addKey("COUNTEV", "2", "Count on event") tccSym_EVCTRL_EVACT0.addKey("START", "3", "Start counter") tccSym_EVCTRL_EVACT0.addKey("INC", "4", "Increment counter") tccSym_EVCTRL_EVACT0.addKey("COUNT", "5", "Count on active state of asynchronous event") tccSym_EVCTRL_EVACT0.addKey("FAULT", "7", "Non-recoverable fault") tccSym_EVCTRL_EVACT0.setDisplayMode("Description") tccSym_EVCTRL_EVACT0.setOutputMode("Key") eventDepList.append("TCC_EVCTRL_EVACT0") tccSym_EVCTRL_TCINV0 = tccComponent.createBooleanSymbol("TCC_EVCTRL_TCINV0", tccSym_EVCTRL_EVACT0) tccSym_EVCTRL_TCINV0.setLabel("Invert Input Event 0") tccSym_EVCTRL_TCINV0.setVisible(False) tccSym_EVCTRL_TCINV0.setDependencies(tccIpEventVisible, ["TCC_EVCTRL_EVACT0"]) global tccSym_EVCTRL_EVACT1 tccSym_EVCTRL_EVACT1 = tccComponent.createKeyValueSetSymbol("TCC_EVCTRL_EVACT1", tccSym_InputEvents_Menu) tccSym_EVCTRL_EVACT1.setLabel("Select Input Event 1 Action") tccSym_EVCTRL_EVACT1.addKey("OFF", "0", "Disabled") tccSym_EVCTRL_EVACT1.addKey("RETRIGGER", "1", "Start, restart or retrigger counter") tccSym_EVCTRL_EVACT1.addKey("DIR", "2", "Direction control") tccSym_EVCTRL_EVACT1.addKey("STOP", "3", "Stop counter") tccSym_EVCTRL_EVACT1.addKey("DEC", "4", "Increment counter") tccSym_EVCTRL_EVACT1.addKey("FAULT", "7", "Non-recoverable fault") tccSym_EVCTRL_EVACT1.setDisplayMode("Description") tccSym_EVCTRL_EVACT1.setOutputMode("Key") eventDepList.append("TCC_EVCTRL_EVACT1") tccSym_EVCTRL_TCINV1 = tccComponent.createBooleanSymbol("TCC_EVCTRL_TCINV1", tccSym_EVCTRL_EVACT1) tccSym_EVCTRL_TCINV1.setLabel("Invert Input Event 1") tccSym_EVCTRL_TCINV1.setVisible(False) tccSym_EVCTRL_TCINV1.setDependencies(tccIpEventVisible, ["TCC_EVCTRL_EVACT1"]) #Fault menu tccSym_Fault_Menu = tccComponent.createMenuSymbol("TCC_FAULT_MENU", None) tccSym_Fault_Menu.setLabel("Fault Configurations") tccSym_Fault_Comment = tccComponent.createCommentSymbol("TCC_FAULT_COMMENT", tccSym_Fault_Menu) tccSym_Fault_Comment.setLabel("**** Select input event action as non-recoverable fault ****") tccSym_Fault_Comment.setDependencies(tccFaultVisible, ["TCC_EVCTRL_EVACT0", "TCC_EVCTRL_EVACT1"]) #fault filter value tccSym_DRVCTRL_FILTERVAL = tccComponent.createIntegerSymbol("TCC_DRVCTRL_FILTERVAL", tccSym_Fault_Menu) tccSym_DRVCTRL_FILTERVAL.setLabel(" Fault 0 Filter Value") tccSym_DRVCTRL_FILTERVAL.setMin(0) tccSym_DRVCTRL_FILTERVAL.setMax(15) tccSym_DRVCTRL_FILTERVAL.setDefaultValue(0) tccSym_DRVCTRL_FILTERVAL.setVisible(False) tccSym_DRVCTRL_FILTERVAL.setDependencies(tccFaultVisible, ["TCC_EVCTRL_EVACT0", "TCC_EVCTRL_EVACT1"]) tccSym_DRVCTRL_FILTERVAL1 = tccComponent.createIntegerSymbol("TCC_DRVCTRL_FILTERVAL1", tccSym_Fault_Menu) tccSym_DRVCTRL_FILTERVAL1.setLabel(" Fault 1 Filter Value") tccSym_DRVCTRL_FILTERVAL1.setMin(0) tccSym_DRVCTRL_FILTERVAL1.setMax(15) tccSym_DRVCTRL_FILTERVAL1.setDefaultValue(0) tccSym_DRVCTRL_FILTERVAL1.setVisible(False) tccSym_DRVCTRL_FILTERVAL1.setDependencies(tccFaultVisible, ["TCC_EVCTRL_EVACT0", "TCC_EVCTRL_EVACT1"]) #output polarity after fault for output in range(0, numOfOutputs): tccSym_DRVCTRL_NRE_NRV.append(output) tccSym_DRVCTRL_NRE_NRV[output] = tccComponent.createKeyValueSetSymbol("TCC_"+str(output)+"_DRVCTRL_NRE_NRV", tccSym_Fault_Menu) tccSym_DRVCTRL_NRE_NRV[output].setLabel("Select Level for Output " +str(output)) tccSym_DRVCTRL_NRE_NRV[output].setVisible(False) tccSym_DRVCTRL_NRE_NRV[output].addKey("Tri-state", "-1", "Tri-state") tccSym_DRVCTRL_NRE_NRV[output].addKey("Low", "0", "Low") tccSym_DRVCTRL_NRE_NRV[output].addKey("High", "1", "High") tccSym_DRVCTRL_NRE_NRV[output].setOutputMode("Value") tccSym_DRVCTRL_NRE_NRV[output].setDisplayMode("Description") tccSym_DRVCTRL_NRE_NRV[output].setDependencies(tccFaultVisible, ["TCC_EVCTRL_EVACT0", "TCC_EVCTRL_EVACT1"]) tccSym_INTENSET_FAULT0 = tccComponent.createBooleanSymbol("TCC_INTENSET_FAULT0", tccSym_Fault_Menu) tccSym_INTENSET_FAULT0.setLabel("Enable Fault 0 Interrupt") tccSym_INTENSET_FAULT0.setDefaultValue(False) tccSym_INTENSET_FAULT0.setVisible(False) tccSym_INTENSET_FAULT0.setDependencies(tccFaultVisible, ["TCC_EVCTRL_EVACT0", "TCC_EVCTRL_EVACT1"]) interruptDepList.append("TCC_INTENSET_FAULT0") tccSym_INTENSET_FAULT1 = tccComponent.createBooleanSymbol("TCC_INTENSET_FAULT1", tccSym_Fault_Menu) tccSym_INTENSET_FAULT1.setLabel("Enable Fault 1 Interrupt") tccSym_INTENSET_FAULT1.setDefaultValue(False) tccSym_INTENSET_FAULT1.setVisible(False) tccSym_INTENSET_FAULT1.setDependencies(tccFaultVisible, ["TCC_EVCTRL_EVACT0", "TCC_EVCTRL_EVACT1"]) interruptDepList.append("TCC_INTENSET_FAULT1") tccSym_CTRLA_RUNSTDBY = tccComponent.createBooleanSymbol("TCC_CTRLA_RUNSTDBY", None) tccSym_CTRLA_RUNSTDBY.setLabel("Run during Standby") ############################################################################ #### Dependency #### ############################################################################ vectorNode=ATDF.getNode( "/avr-tools-device-file/devices/device/interrupts") vectorValues = vectorNode.getChildren() for id in range(0, len(vectorNode.getChildren())): if vectorValues[id].getAttribute("module-instance") == tccInstanceName.getValue(): name = vectorValues[id].getAttribute("name") InterruptVector.append(name + "_INTERRUPT_ENABLE") InterruptHandler.append(name + "_INTERRUPT_HANDLER") InterruptHandlerLock.append(name + "_INTERRUPT_HANDLER_LOCK") InterruptVectorUpdate.append( "core." + name + "_INTERRUPT_ENABLE_UPDATE") tccSym_IntLines = tccComponent.createIntegerSymbol("TCC_NUM_INT_LINES", None) tccSym_IntLines.setVisible(False) tccSym_IntLines.setDefaultValue((len(InterruptVector) - 1)) # Interrupt Dynamic settings tccSym_UpdateInterruptStatus = tccComponent.createBooleanSymbol("TCC_INTERRUPT_STATUS", None) tccSym_UpdateInterruptStatus.setDependencies(updateTCCInterruptStatus, interruptDepList) tccSym_UpdateInterruptStatus.setVisible(False) # Interrupt Warning status tccSym_IntEnComment = tccComponent.createCommentSymbol("TCC_INTERRUPT_ENABLE_COMMENT", None) tccSym_IntEnComment.setVisible(False) tccSym_IntEnComment.setLabel("Warning!!! " + tccInstanceName.getValue() + " Interrupt is Disabled in Interrupt Manager") tccSym_IntEnComment.setDependencies(updateTCCInterruptWarningStatus, interruptDepList + InterruptVectorUpdate) # Clock Warning status tccSym_ClkEnComment = tccComponent.createCommentSymbol("TCC_CLOCK_ENABLE_COMMENT", None) tccSym_ClkEnComment.setLabel("Warning!!! TCC Peripheral Clock is Disabled in Clock Manager") tccSym_ClkEnComment.setVisible(False) tccSym_ClkEnComment.setDependencies(updateTCCClockWarningStatus, ["core." + tccInstanceName.getValue() + "_CLOCK_ENABLE"]) tccSym_EVSYS_CONFIGURE = tccComponent.createIntegerSymbol("TCC_TIMER_EVSYS_CONFIGURE", None) tccSym_EVSYS_CONFIGURE.setVisible(False) tccSym_EVSYS_CONFIGURE.setDependencies(tccEvsys, eventDepList) ################################################################################################### ####################################### Code Generation ########################################## ################################################################################################### configName = Variables.get("__CONFIGURATION_NAME") tccSym_PWMHeaderFile = tccComponent.createFileSymbol("TCC_HEADER", None) tccSym_PWMHeaderFile.setSourcePath("../peripheral/tcc_u2213/templates/plib_tcc.h.ftl") tccSym_PWMHeaderFile.setOutputName("plib_"+tccInstanceName.getValue().lower()+".h") tccSym_PWMHeaderFile.setDestPath("/peripheral/tcc/") tccSym_PWMHeaderFile.setProjectPath("config/" + configName + "/peripheral/tcc/") tccSym_PWMHeaderFile.setType("HEADER") tccSym_PWMHeaderFile.setMarkup(True) tccSym_PWMSourceFile = tccComponent.createFileSymbol("TCC_SOURCE", None) tccSym_PWMSourceFile.setSourcePath("../peripheral/tcc_u2213/templates/plib_tcc.c.ftl") tccSym_PWMSourceFile.setOutputName("plib_"+tccInstanceName.getValue().lower()+".c") tccSym_PWMSourceFile.setDestPath("/peripheral/tcc/") tccSym_PWMSourceFile.setProjectPath("config/" + configName + "/peripheral/tcc/") tccSym_PWMSourceFile.setType("SOURCE") tccSym_PWMSourceFile.setMarkup(True) tccSym_PWMGlobalHeaderFile = tccComponent.createFileSymbol("TCC_GLOBAL_HEADER", None) tccSym_PWMGlobalHeaderFile.setSourcePath("../peripheral/tcc_u2213/templates/plib_tcc_common.h") tccSym_PWMGlobalHeaderFile.setOutputName("plib_tcc_common.h") tccSym_PWMGlobalHeaderFile.setDestPath("/peripheral/tcc/") tccSym_PWMGlobalHeaderFile.setProjectPath("config/" + configName +"/peripheral/tcc/") tccSym_PWMGlobalHeaderFile.setType("HEADER") tccSym_PWMGlobalHeaderFile.setMarkup(False) tccSym_SystemInitFile = tccComponent.createFileSymbol("TC_SYS_INT", None) tccSym_SystemInitFile.setType("STRING") tccSym_SystemInitFile.setOutputName("core.LIST_SYSTEM_INIT_C_SYS_INITIALIZE_PERIPHERALS") tccSym_SystemInitFile.setSourcePath("../peripheral/tcc_u2213/templates/system/initialization.c.ftl") tccSym_SystemInitFile.setMarkup(True) tccSym_SystemDefFile = tccComponent.createFileSymbol("TC_SYS_DEF", None) tccSym_SystemDefFile.setType("STRING") tccSym_SystemDefFile.setOutputName("core.LIST_SYSTEM_DEFINITIONS_H_INCLUDES") tccSym_SystemDefFile.setSourcePath("../peripheral/tcc_u2213/templates/system/definitions.h.ftl") tccSym_SystemDefFile.setMarkup(True)
43,253
0
481
7c16237489a32a6947682f9416ee999e331bf508
1,151
py
Python
Task2F.py
amyponter/amy_reve
89c6464d56a96d3430a2b3106fc386a86a8b4512
[ "MIT" ]
null
null
null
Task2F.py
amyponter/amy_reve
89c6464d56a96d3430a2b3106fc386a86a8b4512
[ "MIT" ]
null
null
null
Task2F.py
amyponter/amy_reve
89c6464d56a96d3430a2b3106fc386a86a8b4512
[ "MIT" ]
null
null
null
import datetime from floodsystem.analysis import polyfit from floodsystem.datafetcher import fetch_measure_levels from floodsystem.stationdata import build_station_list, update_water_levels from floodsystem.plot import plot_water_level_with_fit from floodsystem.utils import sorted_by_key if __name__ == "__main__": print("*** Task 2F: CUED Part IA Flood Warning System ***") run()
29.512821
93
0.691573
import datetime from floodsystem.analysis import polyfit from floodsystem.datafetcher import fetch_measure_levels from floodsystem.stationdata import build_station_list, update_water_levels from floodsystem.plot import plot_water_level_with_fit from floodsystem.utils import sorted_by_key def highest_levels(stations): update_water_levels(stations) highest = [] for station in stations: if station.latest_level == None: pass elif station.latest_level >= 90: pass else: highest.append((station, station.latest_level)) sortedlist = sorted_by_key(highest, 1) x = sortedlist[-5:] return x def run(): stations = build_station_list() # Sort top 5 highest levels top_water_levels = highest_levels(stations) # Fetch data over past 10 days dt = 2 for i in top_water_levels: dates, levels = fetch_measure_levels(i[0].measure_id, dt=datetime.timedelta(days=dt)) plot_water_level_with_fit(i[0], dates, levels, 4) if __name__ == "__main__": print("*** Task 2F: CUED Part IA Flood Warning System ***") run()
715
0
46
97ddfff6de8858ea4f079e934f202617622729a8
26,309
py
Python
putil/plot/series.py
pmacosta/putil
416cea52df8221981727e25d133e9b4e3f464798
[ "MIT" ]
6
2015-12-15T04:09:08.000Z
2020-02-21T01:40:57.000Z
putil/plot/series.py
pmacosta/putil
416cea52df8221981727e25d133e9b4e3f464798
[ "MIT" ]
null
null
null
putil/plot/series.py
pmacosta/putil
416cea52df8221981727e25d133e9b4e3f464798
[ "MIT" ]
2
2016-01-21T23:29:17.000Z
2020-02-21T01:41:05.000Z
# series.py # Copyright (c) 2013-2016 Pablo Acosta-Serafini # See LICENSE for details # pylint: disable=C0111,C0302,E0102,E0611,W0105 # PyPI imports import numpy import matplotlib.path import matplotlib.pyplot as plt from scipy.stats import linregress from scipy.interpolate import InterpolatedUnivariateSpline # Putil imports import putil.misc import putil.pcontracts from .functions import _C from .constants import LEGEND_SCALE, LINE_WIDTH, MARKER_SIZE ### # Exception tracing initialization code ### """ [[[cog import os, sys if sys.hexversion < 0x03000000: import __builtin__ else: import builtins as __builtin__ sys.path.append(os.environ['TRACER_DIR']) import trace_ex_plot_series exobj_plot = trace_ex_plot_series.trace_module(no_print=True) ]]] [[[end]]] """ ### # Class ### class Series(object): r""" Specifies a series within a panel :param data_source: Data source object :type data_source: :py:class:`putil.plot.BasicSource`, :py:class:`putil.plot.CsvSource` *or others conforming to the data source specification* :param label: Series label, to be used in the panel legend :type label: string :param color: Series color. All `Matplotlib colors <http://matplotlib.org/api/colors_api.html>`_ are supported :type color: polymorphic :param marker: Marker type. All `Matplotlib marker types <http://matplotlib.org/api/markers_api.html>`_ are supported. None indicates no marker :type marker: string or None :param interp: Interpolation option (case insensitive), one of None (no interpolation) 'STRAIGHT' (straight line connects data points), 'STEP' (horizontal segments between data points), 'CUBIC' (cubic interpolation between data points) or 'LINREG' (linear regression based on data points). The interpolation option is case insensitive :type interp: :ref:`InterpolationOption` *or None* :param line_style: Line style. All `Matplotlib line styles <http://matplotlib.org/api/artist_api.html# matplotlib.lines.Line2D.set_linestyle>`_ are supported. None indicates no line :type line_style: :ref:`LineStyleOption` *or None* :param secondary_axis: Flag that indicates whether the series belongs to the panel primary axis (False) or secondary axis (True) :type secondary_axis: boolean .. [[[cog cog.out(exobj_plot.get_sphinx_autodoc()) ]]] .. Auto-generated exceptions documentation for .. putil.plot.series.Series.__init__ :raises: * RuntimeError (Argument \`color\` is not valid) * RuntimeError (Argument \`data_source\` does not have an \`dep_var\` attribute) * RuntimeError (Argument \`data_source\` does not have an \`indep_var\` attribute) * RuntimeError (Argument \`data_source\` is not fully specified) * RuntimeError (Argument \`interp\` is not valid) * RuntimeError (Argument \`label\` is not valid) * RuntimeError (Argument \`line_style\` is not valid) * RuntimeError (Argument \`marker\` is not valid) * RuntimeError (Argument \`secondary_axis\` is not valid) * TypeError (Invalid color specification) * ValueError (Argument \`interp\` is not one of ['STRAIGHT', 'STEP', 'CUBIC', 'LINREG'] (case insensitive)) * ValueError (Argument \`line_style\` is not one of ['-', '--', '-.', ':']) * ValueError (Arguments \`indep_var\` and \`dep_var\` must have the same number of elements) * ValueError (At least 4 data points are needed for CUBIC interpolation) .. [[[end]]] """ # pylint: disable=R0902,R0903,R0913 @putil.pcontracts.contract(label='None|str') @putil.pcontracts.contract(color='real_num|str|list|tuple') @putil.pcontracts.contract(interp='interpolation_option') @putil.pcontracts.contract(line_style='line_style_option') @putil.pcontracts.contract(secondary_axis='None|bool') def __str__(self): """ Print series object information """ ret = '' ret += 'Independent variable: {0}\n'.format( putil.eng.pprint_vector(self.indep_var, width=50) ) ret += 'Dependent variable: {0}\n'.format( putil.eng.pprint_vector(self.dep_var, width=50) ) ret += 'Label: {0}\n'.format(self.label) ret += 'Color: {0}\n'.format(self.color) ret += 'Marker: {0}\n'.format(self._print_marker()) ret += 'Interpolation: {0}\n'.format(self.interp) ret += 'Line style: {0}\n'.format(self.line_style) ret += 'Secondary axis: {0}'.format(self.secondary_axis) return ret def _check_series_is_plottable(self): """ Check that the combination of marker, line style and line width width will produce a printable series """ return ( not (((self._marker_spec == '') and ((not self.interp) or (not self.line_style))) or (self.color in [None, ''])) ) def _validate_source_length_cubic_interp(self): """ Test if data source has minimum length to calculate cubic interpolation """ # pylint: disable=C0103 putil.exh.addex( ValueError, 'At least 4 data points are needed for CUBIC interpolation', (self.interp == 'CUBIC') and (self.indep_var is not None) and (self.dep_var is not None) and (self.indep_var.shape[0] < 4) ) def _validate_marker(self, marker): """ Validate if marker specification is valid """ # pylint: disable=R0201 try: plt.plot(range(10), marker=marker) except ValueError: return False except: # pragma: no cover raise return True def _print_marker(self): """ Returns marker description """ marker_consts = [ { 'value':matplotlib.markers.TICKLEFT, 'repr':'matplotlib.markers.TICKLEFT' }, { 'value':matplotlib.markers.TICKRIGHT, 'repr':'matplotlib.markers.TICKRIGHT' }, { 'value':matplotlib.markers.TICKUP, 'repr':'matplotlib.markers.TICKUP' }, { 'value':matplotlib.markers.TICKDOWN, 'repr':'matplotlib.markers.TICKDOWN' }, { 'value':matplotlib.markers.CARETLEFT, 'repr':'matplotlib.markers.CARETLEFT' }, { 'value':matplotlib.markers.CARETRIGHT, 'repr':'matplotlib.markers.CARETRIGHT' }, { 'value':matplotlib.markers.CARETUP, 'repr':'matplotlib.markers.CARETUP' }, { 'value':matplotlib.markers.CARETDOWN, 'repr':'matplotlib.markers.CARETDOWN' } ] marker_none = ["None", None, ' ', ''] if self.marker in marker_none: return 'None' for const_dict in marker_consts: if self.marker == const_dict['value']: return const_dict['repr'] if isinstance(self.marker, str): return self.marker if isinstance(self.marker, matplotlib.path.Path): return 'matplotlib.path.Path object' return str(self.marker) def _get_complete(self): """ Returns True if series is fully specified, otherwise returns False """ return self.data_source is not None def _calculate_curve(self): """ Compute curve to interpolate between data points """ # pylint: disable=E1101,W0612 if _C(self.interp, self.indep_var, self.dep_var): if self.interp == 'CUBIC': # Add 20 points between existing points self.interp_indep_var = numpy.array([]) iobj = zip(self.indep_var[:-1], self.indep_var[1:]) for start, stop in iobj: self.interp_indep_var = numpy.concatenate( ( self.interp_indep_var, numpy.linspace(start, stop, 20, endpoint=False) ) ) self.interp_indep_var = numpy.concatenate( (self.interp_indep_var, [self.indep_var[-1]]) ) spl = InterpolatedUnivariateSpline( self.indep_var, self.dep_var ) self.interp_dep_var = spl(self.interp_indep_var) elif self.interp == 'LINREG': slope, intercept, _, _, _ = linregress( self.indep_var, self.dep_var ) self.interp_indep_var = self.indep_var self.interp_dep_var = intercept+(slope*self.indep_var) self._scale_indep_var(self._scaling_factor_indep_var) self._scale_dep_var(self._scaling_factor_dep_var) def _scale_indep_var(self, scaling_factor): """ Scale independent variable """ self._scaling_factor_indep_var = float(scaling_factor) self.scaled_indep_var = ( self.indep_var/self._scaling_factor_indep_var if self.indep_var is not None else self.scaled_indep_var ) self.scaled_interp_indep_var = ( self.interp_indep_var/self._scaling_factor_indep_var if self.interp_indep_var is not None else self.scaled_interp_indep_var ) def _scale_dep_var(self, scaling_factor): """ Scale dependent variable """ self._scaling_factor_dep_var = float(scaling_factor) self.scaled_dep_var = ( self.dep_var/self._scaling_factor_dep_var if self.dep_var is not None else self.scaled_dep_var ) self.scaled_interp_dep_var = ( self.interp_dep_var/self._scaling_factor_dep_var if self.interp_dep_var is not None else self.scaled_interp_dep_var ) def _update_linestyle_spec(self): """ Update line style specification to be used in series drawing """ self._linestyle_spec = ( self.line_style if _C(self.line_style, self.interp) else '' ) def _update_linewidth_spec(self): """ Update line width specification to be used in series drawing """ self._linewidth_spec = ( self._ref_linewidth if _C(self.line_style, self.interp) else 0.0 ) def _legend_artist(self, legend_scale=None): """ Creates artist (marker -if used- and line style -if used-) """ legend_scale = LEGEND_SCALE if legend_scale is None else legend_scale return plt.Line2D( (0, 1), (0, 0), color=self.color, marker=self._marker_spec, linestyle=self._linestyle_spec, linewidth=self._linewidth_spec/legend_scale, markeredgecolor=self.color, markersize=self._ref_markersize/legend_scale, markeredgewidth=self._ref_markeredgewidth/legend_scale, markerfacecolor=self._ref_markerfacecolor ) def _draw_series(self, axarr, log_indep, log_dep): """ Draw series """ if self._check_series_is_plottable(): flist = [axarr.plot, axarr.semilogx, axarr.semilogy, axarr.loglog] fplot = flist[2*log_dep+log_indep] # Plot line if self._linestyle_spec != '': fplot( self.scaled_indep_var if self.interp in ['STRAIGHT', 'STEP'] else self.scaled_interp_indep_var, self.scaled_dep_var if self.interp in ['STRAIGHT', 'STEP'] else self.scaled_interp_dep_var, color=self.color, linestyle=self.line_style, linewidth=self._ref_linewidth, drawstyle=( 'steps-post' if self.interp == 'STEP' else 'default' ), label=self.label ) # Plot markers if self._marker_spec != '': fplot( self.scaled_indep_var, self.scaled_dep_var, color=self.color, linestyle='', linewidth=0, drawstyle=( 'steps-post' if self.interp == 'STEP' else 'default' ), marker=self._marker_spec, markeredgecolor=self.color, markersize=self._ref_markersize, markeredgewidth=self._ref_markeredgewidth, markerfacecolor=self._ref_markerfacecolor, label=self.label if self.line_style is None else None ) # Managed attributes _complete = property(_get_complete) color = property( _get_color, _set_color, doc='Series line and marker color' ) r""" Gets or sets the series line and marker color. All `Matplotlib colors <http://matplotlib.org/api/colors_api.html>`_ are supported :type: polymorphic .. [[[cog cog.out(exobj_plot.get_sphinx_autodoc()) ]]] .. Auto-generated exceptions documentation for .. putil.plot.series.Series.color :raises: (when assigned) * RuntimeError (Argument \`color\` is not valid) * TypeError (Invalid color specification) .. [[[end]]] """ data_source = property( _get_data_source, _set_data_source, doc='Data source' ) r""" Gets or sets the data source object. The independent and dependent data sets are obtained once this attribute is set. To be valid, a data source object must have an ``indep_var`` attribute that contains a Numpy vector of increasing real numbers and a ``dep_var`` attribute that contains a Numpy vector of real numbers :type: :py:class:`putil.plot.BasicSource`, :py:class:`putil.plot.CsvSource` or others conforming to the data source specification .. [[[cog cog.out(exobj_plot.get_sphinx_autodoc()) ]]] .. Auto-generated exceptions documentation for .. putil.plot.series.Series.data_source :raises: (when assigned) * RuntimeError (Argument \`data_source\` does not have an \`dep_var\` attribute) * RuntimeError (Argument \`data_source\` does not have an \`indep_var\` attribute) * RuntimeError (Argument \`data_source\` is not fully specified) * ValueError (Arguments \`indep_var\` and \`dep_var\` must have the same number of elements) * ValueError (At least 4 data points are needed for CUBIC interpolation) .. [[[end]]] """ interp = property( _get_interp, _set_interp, doc='Series interpolation option, one of `STRAIGHT`, ' '`CUBIC` or `LINREG` (case insensitive)' ) r""" Gets or sets the interpolation option, one of :code:`None` (no interpolation) :code:`'STRAIGHT'` (straight line connects data points), :code:`'STEP'` (horizontal segments between data points), :code:`'CUBIC'` (cubic interpolation between data points) or :code:`'LINREG'` (linear regression based on data points). The interpolation option is case insensitive :type: :ref:`InterpolationOption` or None .. [[[cog cog.out(exobj_plot.get_sphinx_autodoc()) ]]] .. Auto-generated exceptions documentation for .. putil.plot.series.Series.interp :raises: (when assigned) * RuntimeError (Argument \`interp\` is not valid) * ValueError (Argument \`interp\` is not one of ['STRAIGHT', 'STEP', 'CUBIC', 'LINREG'] (case insensitive)) * ValueError (At least 4 data points are needed for CUBIC interpolation) .. [[[end]]] """ label = property(_get_label, _set_label, doc='Series label') r""" Gets or sets the series label, to be used in the panel legend if the panel has more than one series :type: string .. [[[cog cog.out(exobj_plot.get_sphinx_autodoc()) ]]] .. Auto-generated exceptions documentation for .. putil.plot.series.Series.label :raises: (when assigned) RuntimeError (Argument \`label\` is not valid) .. [[[end]]] """ line_style = property( _get_line_style, _set_line_style, doc='Series line style, one of `-`, `--`, `-.` or `:`' ) r""" Sets or gets the line style. All `Matplotlib line styles <http://matplotlib.org/api/artist_api.html#matplotlib.lines. Line2D.set_linestyle>`_ are supported. :code:`None` indicates no line :type: :ref:`LineStyleOption` .. [[[cog cog.out(exobj_plot.get_sphinx_autodoc()) ]]] .. Auto-generated exceptions documentation for .. putil.plot.series.Series.line_style :raises: (when assigned) * RuntimeError (Argument \`line_style\` is not valid) * ValueError (Argument \`line_style\` is not one of ['-', '--', '-.', ':']) .. [[[end]]] """ marker = property( _get_marker, _set_marker, doc='Plot data point markers flag' ) r""" Gets or sets the series marker type. All `Matplotlib marker types <http://matplotlib.org/api/markers_api.html>`_ are supported. :code:`None` indicates no marker :type: string or None .. [[[cog cog.out(exobj_plot.get_sphinx_autodoc()) ]]] .. Auto-generated exceptions documentation for .. putil.plot.series.Series.marker :raises: (when assigned) RuntimeError (Argument \`marker\` is not valid) .. [[[end]]] """ secondary_axis = property( _get_secondary_axis, _set_secondary_axis, doc='Series secondary axis flag' ) r""" Sets or gets the secondary axis flag; indicates whether the series belongs to the panel primary axis (False) or secondary axis (True) :type: boolean .. [[[cog cog.out(exobj_plot.get_sphinx_autodoc()) ]]] .. Auto-generated exceptions documentation for .. putil.plot.series.Series.secondary_axis :raises: (when assigned) RuntimeError (Argument \`secondary_axis\` is not valid) .. [[[end]]] """
36.138736
79
0.594511
# series.py # Copyright (c) 2013-2016 Pablo Acosta-Serafini # See LICENSE for details # pylint: disable=C0111,C0302,E0102,E0611,W0105 # PyPI imports import numpy import matplotlib.path import matplotlib.pyplot as plt from scipy.stats import linregress from scipy.interpolate import InterpolatedUnivariateSpline # Putil imports import putil.misc import putil.pcontracts from .functions import _C from .constants import LEGEND_SCALE, LINE_WIDTH, MARKER_SIZE ### # Exception tracing initialization code ### """ [[[cog import os, sys if sys.hexversion < 0x03000000: import __builtin__ else: import builtins as __builtin__ sys.path.append(os.environ['TRACER_DIR']) import trace_ex_plot_series exobj_plot = trace_ex_plot_series.trace_module(no_print=True) ]]] [[[end]]] """ ### # Class ### class Series(object): r""" Specifies a series within a panel :param data_source: Data source object :type data_source: :py:class:`putil.plot.BasicSource`, :py:class:`putil.plot.CsvSource` *or others conforming to the data source specification* :param label: Series label, to be used in the panel legend :type label: string :param color: Series color. All `Matplotlib colors <http://matplotlib.org/api/colors_api.html>`_ are supported :type color: polymorphic :param marker: Marker type. All `Matplotlib marker types <http://matplotlib.org/api/markers_api.html>`_ are supported. None indicates no marker :type marker: string or None :param interp: Interpolation option (case insensitive), one of None (no interpolation) 'STRAIGHT' (straight line connects data points), 'STEP' (horizontal segments between data points), 'CUBIC' (cubic interpolation between data points) or 'LINREG' (linear regression based on data points). The interpolation option is case insensitive :type interp: :ref:`InterpolationOption` *or None* :param line_style: Line style. All `Matplotlib line styles <http://matplotlib.org/api/artist_api.html# matplotlib.lines.Line2D.set_linestyle>`_ are supported. None indicates no line :type line_style: :ref:`LineStyleOption` *or None* :param secondary_axis: Flag that indicates whether the series belongs to the panel primary axis (False) or secondary axis (True) :type secondary_axis: boolean .. [[[cog cog.out(exobj_plot.get_sphinx_autodoc()) ]]] .. Auto-generated exceptions documentation for .. putil.plot.series.Series.__init__ :raises: * RuntimeError (Argument \`color\` is not valid) * RuntimeError (Argument \`data_source\` does not have an \`dep_var\` attribute) * RuntimeError (Argument \`data_source\` does not have an \`indep_var\` attribute) * RuntimeError (Argument \`data_source\` is not fully specified) * RuntimeError (Argument \`interp\` is not valid) * RuntimeError (Argument \`label\` is not valid) * RuntimeError (Argument \`line_style\` is not valid) * RuntimeError (Argument \`marker\` is not valid) * RuntimeError (Argument \`secondary_axis\` is not valid) * TypeError (Invalid color specification) * ValueError (Argument \`interp\` is not one of ['STRAIGHT', 'STEP', 'CUBIC', 'LINREG'] (case insensitive)) * ValueError (Argument \`line_style\` is not one of ['-', '--', '-.', ':']) * ValueError (Arguments \`indep_var\` and \`dep_var\` must have the same number of elements) * ValueError (At least 4 data points are needed for CUBIC interpolation) .. [[[end]]] """ # pylint: disable=R0902,R0903,R0913 def __init__(self, data_source, label, color='k', marker='o', interp='CUBIC', line_style='-', secondary_axis=False): # Series plotting attributes self._ref_linewidth = LINE_WIDTH self._ref_markersize = MARKER_SIZE self._ref_markeredgewidth = self._ref_markersize*(5.0/14.0) self._ref_markerfacecolor = 'w' # Private attributes self._scaling_factor_indep_var = 1 self._scaling_factor_dep_var = 1 self._marker_spec = None self._linestyle_spec = None self._linewidth_spec = None # Public attributes self.scaled_indep_var = None self.scaled_dep_var = None self.interp_indep_var = None self.interp_dep_var = None self.indep_var = None self.dep_var = None self.scaled_interp_indep_var = None self.scaled_interp_dep_var = None self._data_source = None self._label = None self._color = 'k' self._marker = 'o' self._interp = 'CUBIC' self._line_style = '-' self._secondary_axis = False # Assignment of arguments to attributes self._set_label(label) self._set_color(color) self._set_marker(marker) self._set_interp(interp) self._set_line_style(line_style) self._set_secondary_axis(secondary_axis) self._set_data_source(data_source) def _get_data_source(self): return self._data_source def _set_data_source(self, data_source): # pylint: disable=W0212 indep_ex = putil.exh.addex( RuntimeError, 'Argument `data_source` does not have an `indep_var` attribute' ) dep_ex = putil.exh.addex( RuntimeError, 'Argument `data_source` does not have an `dep_var` attribute' ) specified_ex = putil.exh.addex( RuntimeError, 'Argument `data_source` is not fully specified' ) if data_source is not None: indep_ex('indep_var' not in dir(data_source)) dep_ex('dep_var' not in dir(data_source)) specified_ex( ('_complete' in dir(data_source)) and (not data_source._complete) ) self._data_source = data_source self.indep_var = self.data_source.indep_var self.dep_var = self.data_source.dep_var self._validate_source_length_cubic_interp() self._calculate_curve() def _get_label(self): return self._label @putil.pcontracts.contract(label='None|str') def _set_label(self, label): self._label = label def _get_color(self): return self._color @putil.pcontracts.contract(color='real_num|str|list|tuple') def _set_color(self, color): invalid_ex = putil.exh.addex( TypeError, 'Invalid color specification' ) valid_html_colors = [ 'aliceblue', 'antiquewhite', 'aqua', 'aquamarine', 'azure', 'beige', 'bisque', 'black', 'blanchedalmond', 'blue', 'blueviolet', 'brown', 'burlywood', 'cadetblue', 'chartreuse', 'chocolate', 'coral', 'cornflowerblue', 'cornsilk', 'crimson', 'cyan', 'darkblue', 'darkcyan', 'darkgoldenrod', 'darkgray', 'darkgreen', 'darkkhaki', 'darkmagenta', 'darkolivegreen', 'darkorange', 'darkorchid', 'darkred', 'darksalmon', 'darkseagreen', 'darkslateblue', 'darkslategray', 'darkturquoise', 'darkviolet', 'deeppink', 'deepskyblue', 'dimgray', 'dodgerblue', 'firebrick', 'floralwhite', 'forestgreen', 'fuchsia', 'gainsboro', 'ghostwhite', 'gold', 'goldenrod', 'gray', 'green', 'greenyellow', 'honeydew', 'hotpink', 'indianred', 'indigo', 'ivory', 'khaki', 'lavender', 'lavenderblush', 'lawngreen', 'lemonchiffon', 'lightblue', 'lightcoral', 'lightcyan', 'lightgoldenrodyellow', 'lightgreen', 'lightgrey', 'lightpink', 'lightsalmon', 'lightseagreen', 'lightskyblue', 'lightslategray', 'lightsteelblue', 'lightyellow', 'lime', 'limegreen', 'linen', 'magenta', 'maroon', 'mediumaquamarine', 'mediumblue', 'mediumorchid', 'mediumpurple', 'mediumseagreen', 'mediumslateblue', 'mediumspringgreen', 'mediumturquoise', 'mediumvioletred', 'midnightblue', 'mintcream', 'mistyrose', 'moccasin', 'navajowhite', 'navy', 'oldlace', 'olive', 'olivedrab', 'orange', 'orangered', 'orchid', 'palegoldenrod', 'palegreen', 'paleturquoise', 'palevioletred', 'papayawhip', 'peachpuff', 'peru', 'pink', 'plum', 'powderblue', 'purple', 'red', 'rosybrown', 'royalblue', 'saddlebrown', 'salmon', 'sandybrown', 'seagreen', 'seashell', 'sienna', 'silver', 'skyblue', 'slateblue', 'slategray', 'snow', 'springgreen', 'steelblue', 'tan', 'teal', 'thistle', 'tomato', 'turquois', 'violet', 'wheat', 'white', 'whitesmoke', 'yellow', 'yellowgreen' ] self._color = ( color.lower().strip() if isinstance(color, str) else (float(color) if putil.misc.isreal(color) else color) ) check_list = list() # No color specification check_list.append(self.color is None) # Gray scale color specification, checked by decorator check_list.append( putil.misc.isreal(self.color) and (0.0 <= color <= 1.0) ) # Basic built-in Matplotlib specification check_list.append( isinstance(self.color, str) and (len(self.color) == 1) and (self.color in 'bgrcmykw') ) # HTML color name specification check_list.append( isinstance(self.color, str) and (self.color in valid_html_colors) ) # HTML hex color specification check_list.append( isinstance(self.color, str) and (self.color[0] == '#') and (len(self.color) == 7) and ((numpy.array([putil.misc.ishex(char) for char in self.color[1:]] ) == numpy.array([True]*6)).all()) ) # RGB or RGBA tuple check_list.append( (isinstance(self.color, list) or isinstance(self.color, tuple)) and (len(self.color) in [3, 4]) and ((numpy.array([ putil.misc.isreal(comp) and (0.0 <= comp <= 1.0) for comp in self.color ]) == numpy.array([True]*len(self.color))).all()) ) invalid_ex(True not in check_list) def _get_marker(self): return self._marker def _set_marker(self, marker): putil.exh.addai('marker', not self._validate_marker(marker)) self._marker = marker self._marker_spec = ( self.marker if self.marker not in ["None", None, ' ', ''] else '' ) def _get_interp(self): return self._interp @putil.pcontracts.contract(interp='interpolation_option') def _set_interp(self, interp): self._interp = ( interp.upper().strip() if isinstance(interp, str) else interp ) self._validate_source_length_cubic_interp() self._update_linestyle_spec() self._update_linewidth_spec() self._calculate_curve() def _get_line_style(self): return self._line_style @putil.pcontracts.contract(line_style='line_style_option') def _set_line_style(self, line_style): self._line_style = line_style self._update_linestyle_spec() self._update_linewidth_spec() def _get_secondary_axis(self): return self._secondary_axis @putil.pcontracts.contract(secondary_axis='None|bool') def _set_secondary_axis(self, secondary_axis): self._secondary_axis = secondary_axis def __str__(self): """ Print series object information """ ret = '' ret += 'Independent variable: {0}\n'.format( putil.eng.pprint_vector(self.indep_var, width=50) ) ret += 'Dependent variable: {0}\n'.format( putil.eng.pprint_vector(self.dep_var, width=50) ) ret += 'Label: {0}\n'.format(self.label) ret += 'Color: {0}\n'.format(self.color) ret += 'Marker: {0}\n'.format(self._print_marker()) ret += 'Interpolation: {0}\n'.format(self.interp) ret += 'Line style: {0}\n'.format(self.line_style) ret += 'Secondary axis: {0}'.format(self.secondary_axis) return ret def _check_series_is_plottable(self): """ Check that the combination of marker, line style and line width width will produce a printable series """ return ( not (((self._marker_spec == '') and ((not self.interp) or (not self.line_style))) or (self.color in [None, ''])) ) def _validate_source_length_cubic_interp(self): """ Test if data source has minimum length to calculate cubic interpolation """ # pylint: disable=C0103 putil.exh.addex( ValueError, 'At least 4 data points are needed for CUBIC interpolation', (self.interp == 'CUBIC') and (self.indep_var is not None) and (self.dep_var is not None) and (self.indep_var.shape[0] < 4) ) def _validate_marker(self, marker): """ Validate if marker specification is valid """ # pylint: disable=R0201 try: plt.plot(range(10), marker=marker) except ValueError: return False except: # pragma: no cover raise return True def _print_marker(self): """ Returns marker description """ marker_consts = [ { 'value':matplotlib.markers.TICKLEFT, 'repr':'matplotlib.markers.TICKLEFT' }, { 'value':matplotlib.markers.TICKRIGHT, 'repr':'matplotlib.markers.TICKRIGHT' }, { 'value':matplotlib.markers.TICKUP, 'repr':'matplotlib.markers.TICKUP' }, { 'value':matplotlib.markers.TICKDOWN, 'repr':'matplotlib.markers.TICKDOWN' }, { 'value':matplotlib.markers.CARETLEFT, 'repr':'matplotlib.markers.CARETLEFT' }, { 'value':matplotlib.markers.CARETRIGHT, 'repr':'matplotlib.markers.CARETRIGHT' }, { 'value':matplotlib.markers.CARETUP, 'repr':'matplotlib.markers.CARETUP' }, { 'value':matplotlib.markers.CARETDOWN, 'repr':'matplotlib.markers.CARETDOWN' } ] marker_none = ["None", None, ' ', ''] if self.marker in marker_none: return 'None' for const_dict in marker_consts: if self.marker == const_dict['value']: return const_dict['repr'] if isinstance(self.marker, str): return self.marker if isinstance(self.marker, matplotlib.path.Path): return 'matplotlib.path.Path object' return str(self.marker) def _get_complete(self): """ Returns True if series is fully specified, otherwise returns False """ return self.data_source is not None def _calculate_curve(self): """ Compute curve to interpolate between data points """ # pylint: disable=E1101,W0612 if _C(self.interp, self.indep_var, self.dep_var): if self.interp == 'CUBIC': # Add 20 points between existing points self.interp_indep_var = numpy.array([]) iobj = zip(self.indep_var[:-1], self.indep_var[1:]) for start, stop in iobj: self.interp_indep_var = numpy.concatenate( ( self.interp_indep_var, numpy.linspace(start, stop, 20, endpoint=False) ) ) self.interp_indep_var = numpy.concatenate( (self.interp_indep_var, [self.indep_var[-1]]) ) spl = InterpolatedUnivariateSpline( self.indep_var, self.dep_var ) self.interp_dep_var = spl(self.interp_indep_var) elif self.interp == 'LINREG': slope, intercept, _, _, _ = linregress( self.indep_var, self.dep_var ) self.interp_indep_var = self.indep_var self.interp_dep_var = intercept+(slope*self.indep_var) self._scale_indep_var(self._scaling_factor_indep_var) self._scale_dep_var(self._scaling_factor_dep_var) def _scale_indep_var(self, scaling_factor): """ Scale independent variable """ self._scaling_factor_indep_var = float(scaling_factor) self.scaled_indep_var = ( self.indep_var/self._scaling_factor_indep_var if self.indep_var is not None else self.scaled_indep_var ) self.scaled_interp_indep_var = ( self.interp_indep_var/self._scaling_factor_indep_var if self.interp_indep_var is not None else self.scaled_interp_indep_var ) def _scale_dep_var(self, scaling_factor): """ Scale dependent variable """ self._scaling_factor_dep_var = float(scaling_factor) self.scaled_dep_var = ( self.dep_var/self._scaling_factor_dep_var if self.dep_var is not None else self.scaled_dep_var ) self.scaled_interp_dep_var = ( self.interp_dep_var/self._scaling_factor_dep_var if self.interp_dep_var is not None else self.scaled_interp_dep_var ) def _update_linestyle_spec(self): """ Update line style specification to be used in series drawing """ self._linestyle_spec = ( self.line_style if _C(self.line_style, self.interp) else '' ) def _update_linewidth_spec(self): """ Update line width specification to be used in series drawing """ self._linewidth_spec = ( self._ref_linewidth if _C(self.line_style, self.interp) else 0.0 ) def _legend_artist(self, legend_scale=None): """ Creates artist (marker -if used- and line style -if used-) """ legend_scale = LEGEND_SCALE if legend_scale is None else legend_scale return plt.Line2D( (0, 1), (0, 0), color=self.color, marker=self._marker_spec, linestyle=self._linestyle_spec, linewidth=self._linewidth_spec/legend_scale, markeredgecolor=self.color, markersize=self._ref_markersize/legend_scale, markeredgewidth=self._ref_markeredgewidth/legend_scale, markerfacecolor=self._ref_markerfacecolor ) def _draw_series(self, axarr, log_indep, log_dep): """ Draw series """ if self._check_series_is_plottable(): flist = [axarr.plot, axarr.semilogx, axarr.semilogy, axarr.loglog] fplot = flist[2*log_dep+log_indep] # Plot line if self._linestyle_spec != '': fplot( self.scaled_indep_var if self.interp in ['STRAIGHT', 'STEP'] else self.scaled_interp_indep_var, self.scaled_dep_var if self.interp in ['STRAIGHT', 'STEP'] else self.scaled_interp_dep_var, color=self.color, linestyle=self.line_style, linewidth=self._ref_linewidth, drawstyle=( 'steps-post' if self.interp == 'STEP' else 'default' ), label=self.label ) # Plot markers if self._marker_spec != '': fplot( self.scaled_indep_var, self.scaled_dep_var, color=self.color, linestyle='', linewidth=0, drawstyle=( 'steps-post' if self.interp == 'STEP' else 'default' ), marker=self._marker_spec, markeredgecolor=self.color, markersize=self._ref_markersize, markeredgewidth=self._ref_markeredgewidth, markerfacecolor=self._ref_markerfacecolor, label=self.label if self.line_style is None else None ) # Managed attributes _complete = property(_get_complete) color = property( _get_color, _set_color, doc='Series line and marker color' ) r""" Gets or sets the series line and marker color. All `Matplotlib colors <http://matplotlib.org/api/colors_api.html>`_ are supported :type: polymorphic .. [[[cog cog.out(exobj_plot.get_sphinx_autodoc()) ]]] .. Auto-generated exceptions documentation for .. putil.plot.series.Series.color :raises: (when assigned) * RuntimeError (Argument \`color\` is not valid) * TypeError (Invalid color specification) .. [[[end]]] """ data_source = property( _get_data_source, _set_data_source, doc='Data source' ) r""" Gets or sets the data source object. The independent and dependent data sets are obtained once this attribute is set. To be valid, a data source object must have an ``indep_var`` attribute that contains a Numpy vector of increasing real numbers and a ``dep_var`` attribute that contains a Numpy vector of real numbers :type: :py:class:`putil.plot.BasicSource`, :py:class:`putil.plot.CsvSource` or others conforming to the data source specification .. [[[cog cog.out(exobj_plot.get_sphinx_autodoc()) ]]] .. Auto-generated exceptions documentation for .. putil.plot.series.Series.data_source :raises: (when assigned) * RuntimeError (Argument \`data_source\` does not have an \`dep_var\` attribute) * RuntimeError (Argument \`data_source\` does not have an \`indep_var\` attribute) * RuntimeError (Argument \`data_source\` is not fully specified) * ValueError (Arguments \`indep_var\` and \`dep_var\` must have the same number of elements) * ValueError (At least 4 data points are needed for CUBIC interpolation) .. [[[end]]] """ interp = property( _get_interp, _set_interp, doc='Series interpolation option, one of `STRAIGHT`, ' '`CUBIC` or `LINREG` (case insensitive)' ) r""" Gets or sets the interpolation option, one of :code:`None` (no interpolation) :code:`'STRAIGHT'` (straight line connects data points), :code:`'STEP'` (horizontal segments between data points), :code:`'CUBIC'` (cubic interpolation between data points) or :code:`'LINREG'` (linear regression based on data points). The interpolation option is case insensitive :type: :ref:`InterpolationOption` or None .. [[[cog cog.out(exobj_plot.get_sphinx_autodoc()) ]]] .. Auto-generated exceptions documentation for .. putil.plot.series.Series.interp :raises: (when assigned) * RuntimeError (Argument \`interp\` is not valid) * ValueError (Argument \`interp\` is not one of ['STRAIGHT', 'STEP', 'CUBIC', 'LINREG'] (case insensitive)) * ValueError (At least 4 data points are needed for CUBIC interpolation) .. [[[end]]] """ label = property(_get_label, _set_label, doc='Series label') r""" Gets or sets the series label, to be used in the panel legend if the panel has more than one series :type: string .. [[[cog cog.out(exobj_plot.get_sphinx_autodoc()) ]]] .. Auto-generated exceptions documentation for .. putil.plot.series.Series.label :raises: (when assigned) RuntimeError (Argument \`label\` is not valid) .. [[[end]]] """ line_style = property( _get_line_style, _set_line_style, doc='Series line style, one of `-`, `--`, `-.` or `:`' ) r""" Sets or gets the line style. All `Matplotlib line styles <http://matplotlib.org/api/artist_api.html#matplotlib.lines. Line2D.set_linestyle>`_ are supported. :code:`None` indicates no line :type: :ref:`LineStyleOption` .. [[[cog cog.out(exobj_plot.get_sphinx_autodoc()) ]]] .. Auto-generated exceptions documentation for .. putil.plot.series.Series.line_style :raises: (when assigned) * RuntimeError (Argument \`line_style\` is not valid) * ValueError (Argument \`line_style\` is not one of ['-', '--', '-.', ':']) .. [[[end]]] """ marker = property( _get_marker, _set_marker, doc='Plot data point markers flag' ) r""" Gets or sets the series marker type. All `Matplotlib marker types <http://matplotlib.org/api/markers_api.html>`_ are supported. :code:`None` indicates no marker :type: string or None .. [[[cog cog.out(exobj_plot.get_sphinx_autodoc()) ]]] .. Auto-generated exceptions documentation for .. putil.plot.series.Series.marker :raises: (when assigned) RuntimeError (Argument \`marker\` is not valid) .. [[[end]]] """ secondary_axis = property( _get_secondary_axis, _set_secondary_axis, doc='Series secondary axis flag' ) r""" Sets or gets the secondary axis flag; indicates whether the series belongs to the panel primary axis (False) or secondary axis (True) :type: boolean .. [[[cog cog.out(exobj_plot.get_sphinx_autodoc()) ]]] .. Auto-generated exceptions documentation for .. putil.plot.series.Series.secondary_axis :raises: (when assigned) RuntimeError (Argument \`secondary_axis\` is not valid) .. [[[end]]] """
7,254
0
399
ba5b2d2a2874a4511323fe0650c36a0e9d8df146
313
py
Python
handlers/FaviconHandler.py
Boss-XP/server_tornado
d25781f8c426ae6ec2af4ecdcfd87c6ba5eaa55f
[ "Apache-2.0" ]
null
null
null
handlers/FaviconHandler.py
Boss-XP/server_tornado
d25781f8c426ae6ec2af4ecdcfd87c6ba5eaa55f
[ "Apache-2.0" ]
null
null
null
handlers/FaviconHandler.py
Boss-XP/server_tornado
d25781f8c426ae6ec2af4ecdcfd87c6ba5eaa55f
[ "Apache-2.0" ]
null
null
null
# coding: utf-8 from handlers.BaseHandler import RequestBaseHandler import os class GetFavicon(RequestBaseHandler): """发布数据接口"""
26.083333
79
0.648562
# coding: utf-8 from handlers.BaseHandler import RequestBaseHandler import os class GetFavicon(RequestBaseHandler): """发布数据接口""" def get(self, *args, **kwargs): print('---fav') pic = open(os.path.join(os.path.dirname(__file__), "favicon.png"), 'r') return self.write(pic.read())
152
0
26
accc11b35ac61e2ea056f246d67b34b4dcbe62b1
1,194
py
Python
datasets/Macaws/split.py
yuhongherald/pytorch-CycleGAN-and-pix2pix
48cb3aa46fde39684db9c24586fcec6781138e2a
[ "BSD-3-Clause" ]
null
null
null
datasets/Macaws/split.py
yuhongherald/pytorch-CycleGAN-and-pix2pix
48cb3aa46fde39684db9c24586fcec6781138e2a
[ "BSD-3-Clause" ]
null
null
null
datasets/Macaws/split.py
yuhongherald/pytorch-CycleGAN-and-pix2pix
48cb3aa46fde39684db9c24586fcec6781138e2a
[ "BSD-3-Clause" ]
1
2019-09-28T02:29:58.000Z
2019-09-28T02:29:58.000Z
import os import random import tqdm import shutil train_p = 0.9 #val_p = 0.05 test_p = 0.05 root_dir = "contoured-cut-outlines" all_dir = "all" train_dir = "train" val_dir = "val" test_dir = "test" if __name__ == "__main__": data = os.listdir(os.path.join(root_dir, all_dir)) random.shuffle(data) total_count = len(data) train_split = int(train_p * total_count) test_split = int((1 - test_p) * total_count) train_data = data[:train_split] val_data = data[train_split:test_split] test_data = data[test_split:] #newPath = shutil.copy("all/20063861.png", "test/20063861.png") for data in tqdm.tqdm(train_data, ascii=True, desc='train_data', unit='|image|'): newPath = shutil.copy(os.path.join(root_dir, all_dir, data), os.path.join(root_dir, train_dir, data)) for data in tqdm.tqdm(val_data, ascii=True, desc='val_data', unit='|image|'): newPath = shutil.copy(os.path.join(root_dir, all_dir, data), os.path.join(root_dir, val_dir, data)) for data in tqdm.tqdm(test_data, ascii=True, desc='test_data', unit='|image|'): newPath = shutil.copy(os.path.join(root_dir, all_dir, data), os.path.join(root_dir, test_dir, data))
34.114286
109
0.688442
import os import random import tqdm import shutil train_p = 0.9 #val_p = 0.05 test_p = 0.05 root_dir = "contoured-cut-outlines" all_dir = "all" train_dir = "train" val_dir = "val" test_dir = "test" if __name__ == "__main__": data = os.listdir(os.path.join(root_dir, all_dir)) random.shuffle(data) total_count = len(data) train_split = int(train_p * total_count) test_split = int((1 - test_p) * total_count) train_data = data[:train_split] val_data = data[train_split:test_split] test_data = data[test_split:] #newPath = shutil.copy("all/20063861.png", "test/20063861.png") for data in tqdm.tqdm(train_data, ascii=True, desc='train_data', unit='|image|'): newPath = shutil.copy(os.path.join(root_dir, all_dir, data), os.path.join(root_dir, train_dir, data)) for data in tqdm.tqdm(val_data, ascii=True, desc='val_data', unit='|image|'): newPath = shutil.copy(os.path.join(root_dir, all_dir, data), os.path.join(root_dir, val_dir, data)) for data in tqdm.tqdm(test_data, ascii=True, desc='test_data', unit='|image|'): newPath = shutil.copy(os.path.join(root_dir, all_dir, data), os.path.join(root_dir, test_dir, data))
0
0
0
c90f69370182cc935ee7b07948d1203a8e243e9e
613
py
Python
src/loggy.py
aarora8/VistaOCR
dd8a41e45d4efe49816054c097d06be41937fae1
[ "Apache-2.0" ]
24
2018-06-05T06:38:24.000Z
2021-12-08T12:20:06.000Z
src/loggy.py
aarora8/VistaOCR
dd8a41e45d4efe49816054c097d06be41937fae1
[ "Apache-2.0" ]
3
2018-08-16T23:47:30.000Z
2020-02-13T09:48:53.000Z
src/loggy.py
aarora8/VistaOCR
dd8a41e45d4efe49816054c097d06be41937fae1
[ "Apache-2.0" ]
10
2018-05-07T17:30:45.000Z
2020-01-29T10:34:02.000Z
import datetime import logging
30.65
107
0.71615
import datetime import logging def setup_custom_logger(name, filename, path="/tmp"): logFormatter = logging.Formatter("%(asctime)s [%(filename)s] %(message)s") fileHandler = logging.FileHandler( "{0}/{1}.log".format(path, filename + '_' + datetime.datetime.now().strftime('%y_%m_%d_%H_%M_%S'))) fileHandler.setFormatter(logFormatter) consoleHandler = logging.StreamHandler() consoleHandler.setFormatter(logFormatter) logger = logging.getLogger(name) logger.setLevel(logging.INFO) logger.addHandler(fileHandler) logger.addHandler(consoleHandler) return logger
558
0
23
6c5fe05941b7380a3079443f25ac97babdcda178
1,169
py
Python
follow/urls.py
CMPUT404W22AMNRY/CMPUT404-project-socialdistribution
61d5c8aa2c7f038c137fc86c8b194d92a33d90e3
[ "W3C-20150513" ]
1
2022-01-14T04:37:54.000Z
2022-01-14T04:37:54.000Z
follow/urls.py
CMPUT404W22AMNRY/CMPUT404-project-socialdistribution
61d5c8aa2c7f038c137fc86c8b194d92a33d90e3
[ "W3C-20150513" ]
88
2022-02-19T00:16:44.000Z
2022-03-29T03:05:08.000Z
follow/urls.py
CMPUT404W22AMNRY/CMPUT404-project-socialdistribution
61d5c8aa2c7f038c137fc86c8b194d92a33d90e3
[ "W3C-20150513" ]
null
null
null
from django.urls import path from .views import ( FriendRequestsView, MyFriendsView, create_follow_request, accept_follow_request, unfollow_request, reject_follow_request, accept_remote_follow_request, reject_remote_follow_request, UsersView ) app_name = 'follow' urlpatterns = [ path('users/<slug:to_username>/request/', view=create_follow_request, name='create_follow_request'), path('users/<slug:from_username>/accept/', view=accept_follow_request, name='accept_follow_request'), path('users/<slug:from_username>/reject/', view=reject_follow_request, name='reject_follow_request'), path('users/<slug:from_username>/unfollow/', view=unfollow_request, name='unfollow_request'), path('remote/accept/<path:from_user_url>', view=accept_remote_follow_request, name='accept_remote_request'), path('remote/reject/<path:from_user_url>', view=reject_remote_follow_request, name='reject_remote_request'), path('friend-requests', view=FriendRequestsView.as_view(), name='friend_requests'), path('friends', view=MyFriendsView.as_view(), name='friends'), path('', view=UsersView.as_view(), name='users'), ]
44.961538
112
0.755346
from django.urls import path from .views import ( FriendRequestsView, MyFriendsView, create_follow_request, accept_follow_request, unfollow_request, reject_follow_request, accept_remote_follow_request, reject_remote_follow_request, UsersView ) app_name = 'follow' urlpatterns = [ path('users/<slug:to_username>/request/', view=create_follow_request, name='create_follow_request'), path('users/<slug:from_username>/accept/', view=accept_follow_request, name='accept_follow_request'), path('users/<slug:from_username>/reject/', view=reject_follow_request, name='reject_follow_request'), path('users/<slug:from_username>/unfollow/', view=unfollow_request, name='unfollow_request'), path('remote/accept/<path:from_user_url>', view=accept_remote_follow_request, name='accept_remote_request'), path('remote/reject/<path:from_user_url>', view=reject_remote_follow_request, name='reject_remote_request'), path('friend-requests', view=FriendRequestsView.as_view(), name='friend_requests'), path('friends', view=MyFriendsView.as_view(), name='friends'), path('', view=UsersView.as_view(), name='users'), ]
0
0
0
1352cd1956b4e01e14016003fe3ea6ede6c23e4f
352
py
Python
challenges/array_shift/array_shift.py
dambergn-codefellows/py401_data-structures-and-algorithms
64ca78a70c9de8bee37459481eb8ce0d359b1bb8
[ "MIT" ]
null
null
null
challenges/array_shift/array_shift.py
dambergn-codefellows/py401_data-structures-and-algorithms
64ca78a70c9de8bee37459481eb8ce0d359b1bb8
[ "MIT" ]
null
null
null
challenges/array_shift/array_shift.py
dambergn-codefellows/py401_data-structures-and-algorithms
64ca78a70c9de8bee37459481eb8ce0d359b1bb8
[ "MIT" ]
null
null
null
def insertShiftArray(array, value): ''' inserts a value in middle of array. ''' if len(array)%2 !=0: oddOrEven = 1 else: oddOrEven = 0 half = len(array)//2 + oddOrEven # print(array[:half] + [value] + array[half:]) return array[:half] + [value] + array[half:] #insertShiftArray([1,2,4,5], 3) #insertShiftArray([1,2,4,5,6], 3)
22
48
0.610795
def insertShiftArray(array, value): ''' inserts a value in middle of array. ''' if len(array)%2 !=0: oddOrEven = 1 else: oddOrEven = 0 half = len(array)//2 + oddOrEven # print(array[:half] + [value] + array[half:]) return array[:half] + [value] + array[half:] #insertShiftArray([1,2,4,5], 3) #insertShiftArray([1,2,4,5,6], 3)
0
0
0
a317b2012cc9cb51be908bfe20411a2c9002cee9
1,333
py
Python
src/others/download_pdb.py
ruiyangsong/mCNN
889f182245f919fb9c7a8d97965b11576b01a96c
[ "MIT" ]
null
null
null
src/others/download_pdb.py
ruiyangsong/mCNN
889f182245f919fb9c7a8d97965b11576b01a96c
[ "MIT" ]
null
null
null
src/others/download_pdb.py
ruiyangsong/mCNN
889f182245f919fb9c7a8d97965b11576b01a96c
[ "MIT" ]
null
null
null
#!/usr/bin/env python3 # -*- coding: utf-8 -*- # file_name : download_pdb.py # time : 3/22/2019 13:54 # author : ruiyang # email : ww_sry@163.com # ------------------------------ import sys import pandas as pd import os def download_pdb(name_list,outpath): """ :function: download pdb archive by pdbid from server: https://files.rcsb.org/download/ :param name_list: 存储了pdbid的python list, set, numpy_array等可迭代对象 :param outpath: 文件存储路径 :return: none """ if not os.path.exists(outpath): os.mkdir(outpath) os.chdir(outpath) print('len of namelist:', len(name_list)) errorlist = [] for pdbid in name_list: print(pdbid) print('download begin') try: os.system('wget https://files.rcsb.org/download/' + pdbid[:4] + '.pdb') except: errorlist.append(pdbid) print('len of errorlist:',len(errorlist)) return(errorlist) if __name__ == '__main__': dataset_name = sys.argv[1] csv_path = r'../datasets/%s/%s_new.csv'%(dataset_name,dataset_name) outpath = r'../datasets/%s/pdb%s'%(dataset_name,dataset_name) f = open(csv_path,'r') mutation_df = pd.read_csv(f) f.close() pdbid_array = mutation_df.loc[:,'PDB'].values pdbid_array = set(pdbid_array) download_pdb(pdbid_array, outpath)
28.978261
90
0.622656
#!/usr/bin/env python3 # -*- coding: utf-8 -*- # file_name : download_pdb.py # time : 3/22/2019 13:54 # author : ruiyang # email : ww_sry@163.com # ------------------------------ import sys import pandas as pd import os def download_pdb(name_list,outpath): """ :function: download pdb archive by pdbid from server: https://files.rcsb.org/download/ :param name_list: 存储了pdbid的python list, set, numpy_array等可迭代对象 :param outpath: 文件存储路径 :return: none """ if not os.path.exists(outpath): os.mkdir(outpath) os.chdir(outpath) print('len of namelist:', len(name_list)) errorlist = [] for pdbid in name_list: print(pdbid) print('download begin') try: os.system('wget https://files.rcsb.org/download/' + pdbid[:4] + '.pdb') except: errorlist.append(pdbid) print('len of errorlist:',len(errorlist)) return(errorlist) if __name__ == '__main__': dataset_name = sys.argv[1] csv_path = r'../datasets/%s/%s_new.csv'%(dataset_name,dataset_name) outpath = r'../datasets/%s/pdb%s'%(dataset_name,dataset_name) f = open(csv_path,'r') mutation_df = pd.read_csv(f) f.close() pdbid_array = mutation_df.loc[:,'PDB'].values pdbid_array = set(pdbid_array) download_pdb(pdbid_array, outpath)
0
0
0
837cb049c36189f05e97e865bab8ef0f9cee3048
350
py
Python
examples/configs/generic_st7735/landscape_128x128.py
russhughes/lv_st7789
aa5134383250abd7d26285c01cb344374449e5b8
[ "MIT" ]
8
2021-08-28T01:41:38.000Z
2022-01-30T15:49:33.000Z
examples/configs/generic_st7735/landscape_128x128.py
russhughes/lv_st7789
aa5134383250abd7d26285c01cb344374449e5b8
[ "MIT" ]
9
2021-08-29T03:01:28.000Z
2022-01-28T11:57:45.000Z
examples/configs/generic_st7735/landscape_128x128.py
russhughes/lv_st7789
aa5134383250abd7d26285c01cb344374449e5b8
[ "MIT" ]
1
2022-01-28T11:58:10.000Z
2022-01-28T11:58:10.000Z
''' Generic st7735 128x128 LCD module on esp32 ''' from ili9XXX import ili9341, MADCTL_MY, MADCTL_MV disp = ili9341( mhz=3, mosi=18, clk=19, cs=13, dc=12, rst=4, power=-1, backlight=15, backlight_on=1, width=128, height=128, start_x=2, start_y=1, invert=False, rot=MADCTL_MY | MADCTL_MV)
15.217391
49
0.602857
''' Generic st7735 128x128 LCD module on esp32 ''' from ili9XXX import ili9341, MADCTL_MY, MADCTL_MV disp = ili9341( mhz=3, mosi=18, clk=19, cs=13, dc=12, rst=4, power=-1, backlight=15, backlight_on=1, width=128, height=128, start_x=2, start_y=1, invert=False, rot=MADCTL_MY | MADCTL_MV)
0
0
0
f7a31e4bb99aff01ed2a23f058553ba02d108c73
945
py
Python
mne/viz/backends/tests/_utils.py
kalenkovich/mne-python
d5752051b37f74713233929382bcc632d404f837
[ "BSD-3-Clause" ]
null
null
null
mne/viz/backends/tests/_utils.py
kalenkovich/mne-python
d5752051b37f74713233929382bcc632d404f837
[ "BSD-3-Clause" ]
null
null
null
mne/viz/backends/tests/_utils.py
kalenkovich/mne-python
d5752051b37f74713233929382bcc632d404f837
[ "BSD-3-Clause" ]
null
null
null
# Authors: Alexandre Gramfort <alexandre.gramfort@telecom-paristech.fr> # Eric Larson <larson.eric.d@gmail.com> # Joan Massich <mailsik@gmail.com> # Guillaume Favelier <guillaume.favelier@gmail.com> # # License: Simplified BSD import pytest import warnings def has_vtki(): """Check that vtki is installed.""" try: import vtki # noqa: F401 return True except ImportError: return False def has_mayavi(): """Check that mayavi is installed.""" try: with warnings.catch_warnings(record=True): # traits from mayavi import mlab # noqa F401 return True except ImportError: return False skips_if_not_mayavi = pytest.mark.skipif(not(has_mayavi()), reason='requires mayavi') skips_if_not_vtki = pytest.mark.skipif(not(has_vtki()), reason='requires vtki')
27
71
0.609524
# Authors: Alexandre Gramfort <alexandre.gramfort@telecom-paristech.fr> # Eric Larson <larson.eric.d@gmail.com> # Joan Massich <mailsik@gmail.com> # Guillaume Favelier <guillaume.favelier@gmail.com> # # License: Simplified BSD import pytest import warnings def has_vtki(): """Check that vtki is installed.""" try: import vtki # noqa: F401 return True except ImportError: return False def has_mayavi(): """Check that mayavi is installed.""" try: with warnings.catch_warnings(record=True): # traits from mayavi import mlab # noqa F401 return True except ImportError: return False skips_if_not_mayavi = pytest.mark.skipif(not(has_mayavi()), reason='requires mayavi') skips_if_not_vtki = pytest.mark.skipif(not(has_vtki()), reason='requires vtki')
0
0
0
faf6328d3f2235855bce224b41bfd52ccae030e4
595
py
Python
setup.py
bonnland/geocat-comp
cb6e0f6a50ff9542d2f003dd0e9ffa1434d4a561
[ "Apache-2.0" ]
null
null
null
setup.py
bonnland/geocat-comp
cb6e0f6a50ff9542d2f003dd0e9ffa1434d4a561
[ "Apache-2.0" ]
null
null
null
setup.py
bonnland/geocat-comp
cb6e0f6a50ff9542d2f003dd0e9ffa1434d4a561
[ "Apache-2.0" ]
null
null
null
try: from setuptools import setup from setuptools import Extension except ImportError: from distutils.core import setup from distutils.extension import Extension #import distutils.sysconfig with open("src/geocat/comp/version.py") as f: exec(f.read()) setup(name="geocat.comp", package_dir={ '': 'src', 'geocat': 'src/geocat', 'geocat.comp': 'src/geocat/comp' }, namespace_packages=['geocat'], packages=["geocat", "geocat.comp"], version=__version__, install_requires=['numpy', 'xarray', 'dask[complete]'])
25.869565
61
0.640336
try: from setuptools import setup from setuptools import Extension except ImportError: from distutils.core import setup from distutils.extension import Extension #import distutils.sysconfig with open("src/geocat/comp/version.py") as f: exec(f.read()) setup(name="geocat.comp", package_dir={ '': 'src', 'geocat': 'src/geocat', 'geocat.comp': 'src/geocat/comp' }, namespace_packages=['geocat'], packages=["geocat", "geocat.comp"], version=__version__, install_requires=['numpy', 'xarray', 'dask[complete]'])
0
0
0
cb7d2a1e81d6afc89d1b23a6bfa078facb0d862d
1,469
py
Python
src/GDNN3_tf.py
gmaggiotti/genetic_deep_learning
3bade857fa7a1564d2c6ef9519bcd37cfcd2d1a4
[ "MIT" ]
13
2019-01-01T20:30:56.000Z
2020-02-13T19:49:21.000Z
src/GDNN3_tf.py
gmaggiotti/genetic_deep_learning
3bade857fa7a1564d2c6ef9519bcd37cfcd2d1a4
[ "MIT" ]
2
2019-01-05T15:33:26.000Z
2019-01-05T15:38:16.000Z
src/GDNN3_tf.py
gmaggiotti/genetic_deep_learning
3bade857fa7a1564d2c6ef9519bcd37cfcd2d1a4
[ "MIT" ]
9
2019-01-06T14:37:15.000Z
2020-12-16T15:34:30.000Z
import numpy as np from NN3_tf import NN3_tf from sklearn.model_selection import train_test_split from nn_utils import crossover, Type, sort_by_fittest, read_dataset X, Y = read_dataset(180, 500) train_x, test_x, train_y, test_y = train_test_split( X, Y, test_size=0.3, random_state=1) X, Y = read_dataset(180, 500) train_x, test_x, train_y, test_y = train_test_split(X, Y, test_size=0.3, random_state=1) epochs = 600 best_n_children = 4 population_size = 20 gen = {} generations = 10 dataset = train_x, train_y, test_x, test_y ## Generate a poblation of neural networks each trained from a random starting weigth ## ordered by the best performers (low error) init_pob = [NN3_tf(dataset, epochs) for i in range(population_size)] init_pob = sort_by_fittest([(nn.get_acc(), nn) for nn in init_pob], Type.accuracy) print("600,{},{}".format(init_pob[0][1].get_error(),init_pob[0][1].get_acc())) gen[0] = init_pob for x in range(1, generations): population = [] for i in range(population_size): parent1 = gen[x - 1][np.random.randint(best_n_children)][1] parent2 = gen[x - 1][np.random.randint(best_n_children)][1] w_child = crossover(parent1, parent2) aux = NN3_tf(dataset, epochs, w_child) population += [tuple((aux.get_acc(), aux))] gen[x] = sort_by_fittest(population, Type.accuracy) net = gen[x][0][1] print("{},{},{}".format((x + 1) * epochs, net.get_error(), net.get_acc())) del population
34.162791
88
0.698434
import numpy as np from NN3_tf import NN3_tf from sklearn.model_selection import train_test_split from nn_utils import crossover, Type, sort_by_fittest, read_dataset X, Y = read_dataset(180, 500) train_x, test_x, train_y, test_y = train_test_split( X, Y, test_size=0.3, random_state=1) X, Y = read_dataset(180, 500) train_x, test_x, train_y, test_y = train_test_split(X, Y, test_size=0.3, random_state=1) epochs = 600 best_n_children = 4 population_size = 20 gen = {} generations = 10 dataset = train_x, train_y, test_x, test_y ## Generate a poblation of neural networks each trained from a random starting weigth ## ordered by the best performers (low error) init_pob = [NN3_tf(dataset, epochs) for i in range(population_size)] init_pob = sort_by_fittest([(nn.get_acc(), nn) for nn in init_pob], Type.accuracy) print("600,{},{}".format(init_pob[0][1].get_error(),init_pob[0][1].get_acc())) gen[0] = init_pob for x in range(1, generations): population = [] for i in range(population_size): parent1 = gen[x - 1][np.random.randint(best_n_children)][1] parent2 = gen[x - 1][np.random.randint(best_n_children)][1] w_child = crossover(parent1, parent2) aux = NN3_tf(dataset, epochs, w_child) population += [tuple((aux.get_acc(), aux))] gen[x] = sort_by_fittest(population, Type.accuracy) net = gen[x][0][1] print("{},{},{}".format((x + 1) * epochs, net.get_error(), net.get_acc())) del population
0
0
0
dba5aab41fe191654d0d37097ad32f42312cd355
701
py
Python
smlb/core/features.py
CitrineInformatics/smlb
28a3689bd36aa8d51031b4faf7e2331bbd8148a9
[ "Apache-2.0" ]
6
2020-07-27T21:08:55.000Z
2021-05-04T07:00:29.000Z
smlb/core/features.py
CitrineInformatics/smlb
28a3689bd36aa8d51031b4faf7e2331bbd8148a9
[ "Apache-2.0" ]
18
2020-09-01T00:47:04.000Z
2021-09-15T22:16:56.000Z
smlb/core/features.py
CitrineInformatics/smlb
28a3689bd36aa8d51031b4faf7e2331bbd8148a9
[ "Apache-2.0" ]
2
2020-08-24T21:50:16.000Z
2020-12-06T05:18:57.000Z
"""Features Scientific Machine Learning Benchmark: A benchmark of regression models in chem- and materials informatics. 2020, Matthias Rupp, Citrine Informatics. Features transform datasets. """ from smlb import DataValuedTransformation, IdentityTransformation, DataPipelineTransformation class Features(DataValuedTransformation): """Abstract base class for features.""" # currently adds no functionality, but serves as common base class pass class IdentityFeatures(Features, IdentityTransformation): """Leaves dataset unchanged.""" pass class DataPipelineFeatures(Features, DataPipelineTransformation): """Applies transformation steps sequentially.""" pass
21.90625
93
0.777461
"""Features Scientific Machine Learning Benchmark: A benchmark of regression models in chem- and materials informatics. 2020, Matthias Rupp, Citrine Informatics. Features transform datasets. """ from smlb import DataValuedTransformation, IdentityTransformation, DataPipelineTransformation class Features(DataValuedTransformation): """Abstract base class for features.""" # currently adds no functionality, but serves as common base class pass class IdentityFeatures(Features, IdentityTransformation): """Leaves dataset unchanged.""" pass class DataPipelineFeatures(Features, DataPipelineTransformation): """Applies transformation steps sequentially.""" pass
0
0
0
50cc1ee5cf17c548e771c7096fa0a585e90d55ad
2,408
py
Python
simpegAIP/SeogiUtils/PetaInv.py
sgkang/simpegAIP
78d24c9170a6a345e0896a932e80ef1a6959cf30
[ "MIT" ]
null
null
null
simpegAIP/SeogiUtils/PetaInv.py
sgkang/simpegAIP
78d24c9170a6a345e0896a932e80ef1a6959cf30
[ "MIT" ]
2
2016-02-04T21:55:03.000Z
2016-02-05T17:40:55.000Z
simpegAIP/SeogiUtils/PetaInv.py
sgkang/simpegAIP
78d24c9170a6a345e0896a932e80ef1a6959cf30
[ "MIT" ]
1
2022-01-11T08:22:10.000Z
2022-01-11T08:22:10.000Z
from SimPEG import Problem, Survey, Utils, Maps import Convolution import numpy as np
32.540541
88
0.584302
from SimPEG import Problem, Survey, Utils, Maps import Convolution import numpy as np class PetaInvProblem(Problem.BaseProblem): surveyPair = Survey.BaseSurvey P = None J = None time = None we = None def __init__(self, mesh, mapping, **kwargs): Problem.BaseProblem.__init__(self, mesh, mapping, **kwargs) def fields(self, m, u=None): mtemp=self.mapping*m self.J = petaJconvfun(m[0],m[1],self.we,self.time,self.P) return petaconvfun(mtemp[0],mtemp[1], self.we, self.time, self.P) def Jvec(self, m, v, u=None): # J = petaJconvfun(m[0],m[1],self.we,self.time,self.P) P = self.mapping.deriv(m) jvec = self.J.dot(P*v) return jvec def Jtvec(self, m, v, u=None): # J = petaJconvfun(m[0],m[1],self.we,self.time,self.P) P = self.mapping.deriv(m) jtvec =P.T*(self.J.T.dot(v)) return jtvec def petaconvfun(a, b, we, time, P,ColeCole="Debye"): if ColeCole == "Debye": kernel = lambda x: a*np.exp(-b*x) elif ColeCole == "Warburg": kernel = lambda t: a*(1./np.sqrt(np.pi*t) - b*np.exp(b**2*t)*erfc(b*np.sqrt(t))) temp = kernel(time) temp = Convolution.CausalConvIntSingle(we, time, kernel) out = P*temp return out def petaJconvfun(a, b, we, time, P): if ColeCole == "Debye": kernela = lambda x: np.exp(-b*x) kernelb = lambda x: -a*x*np.exp(-b*x) elif ColeCole == "Warburg": kernela = lambda x: 1./np.sqrt(np.pi*t) - b*np.exp(b**2*t)*erfc(b*np.sqrt(t)) kernelb = lambda x: a*(2*b*np.sqrt(t)/np.sqrt(np.pi) \ - 2*b**2*t*np.exp(b**2*t)*erfc(b*np.sqrt(t))\ - np.exp(b**2*t)*erfc(b*np.sqrt(t))) tempa = kernela(time) tempb = kernelb(time) tempa = Convolution.CausalConvIntSingle(we, time, kernela) tempb = Convolution.CausalConvIntSingle(we, time, kernelb) J = np.c_[P*tempa, P*tempb] return J class PetaSurvey(Survey.BaseSurvey): def __init__(self, **kwargs): Survey.BaseSurvey.__init__(self, **kwargs) @Utils.requires('prob') def dpred(self, m, u=None): return self.prob.fields(m) def residual(self, m, u=None): if self.dobs.size ==1: return Utils.mkvc(np.r_[self.dpred(m, u=u) - self.dobs]) else: return Utils.mkvc(self.dpred(m, u=u) - self.dobs)
1,885
344
92
eb656459d5c06345b5b9787e8be6a55e5c9cc130
615
py
Python
_1327/information_pages/urls.py
Nef10/1327
71fb83a3c12ba24a7638acebeeffed80825e0101
[ "MIT" ]
null
null
null
_1327/information_pages/urls.py
Nef10/1327
71fb83a3c12ba24a7638acebeeffed80825e0101
[ "MIT" ]
null
null
null
_1327/information_pages/urls.py
Nef10/1327
71fb83a3c12ba24a7638acebeeffed80825e0101
[ "MIT" ]
null
null
null
from django.conf.urls import patterns, url from django.contrib import admin admin.autodiscover() urlpatterns = patterns('_1327.information_pages.views', url(r"create$", 'create', name='create'), url(r"(?P<title>[\w-]+)/edit$", 'edit', name='edit'), url(r"(?P<title>[\w-]+)/autosave$", 'autosave', name='autosave'), url(r"(?P<title>[\w-]+)/versions$", 'versions', name="versions"), url(r"(?P<title>[\w-]+)/permissions$", 'permissions', name="permissions"), url(r"(?P<title>[\w-]+)/attachments$", 'attachments', name="attachments"), url(r"(?P<title>[\w-]+)$", 'view_information', name='view_information'), )
41
75
0.650407
from django.conf.urls import patterns, url from django.contrib import admin admin.autodiscover() urlpatterns = patterns('_1327.information_pages.views', url(r"create$", 'create', name='create'), url(r"(?P<title>[\w-]+)/edit$", 'edit', name='edit'), url(r"(?P<title>[\w-]+)/autosave$", 'autosave', name='autosave'), url(r"(?P<title>[\w-]+)/versions$", 'versions', name="versions"), url(r"(?P<title>[\w-]+)/permissions$", 'permissions', name="permissions"), url(r"(?P<title>[\w-]+)/attachments$", 'attachments', name="attachments"), url(r"(?P<title>[\w-]+)$", 'view_information', name='view_information'), )
0
0
0
48d60e2dc37de4248f1cec08b57bcbb18f01dd84
1,844
py
Python
environmennt.py
cyroilt/game
49dba23c8e361f8d870cb3260f3421ca9f9e16de
[ "BSD-3-Clause" ]
null
null
null
environmennt.py
cyroilt/game
49dba23c8e361f8d870cb3260f3421ca9f9e16de
[ "BSD-3-Clause" ]
null
null
null
environmennt.py
cyroilt/game
49dba23c8e361f8d870cb3260f3421ca9f9e16de
[ "BSD-3-Clause" ]
null
null
null
import random forests=[] forestload=[] forestmaxload=[] stones1=[] stoneload=[] stonemaxload=[] frpl=[] frpl1=[]
24.918919
73
0.703905
import random forests=[] forestload=[] forestmaxload=[] stones1=[] stoneload=[] stonemaxload=[] frpl=[] frpl1=[] class forest(): def genforest(n,maxgen): global forests,forestload,forestmaxload for i in range(n): forests.append([random.randint(0,maxgen),random.randint(0,maxgen)]) forestload.append(random.randint(0,500)) for i in forestload: forestmaxload.append(i) return forests,forestload def load(foresting,forestingl,forestingml): global forests,forestload,forestmaxload forests=foresting forestload=forestingl forestmaxload=forestingml def getlo(): global forests,forestload return forests,forestload def cut(n,i): global forestload,forestmaxload forestload[n]-=i def get(n): return forestload[n] def stnw(f): global frpl frpl=f def ggget(): global frpl return frpl def getmax(n): global forestmaxload return forestmaxload[n] class stones(): def genstone(n,maxgen): global stones1,stoneload,stonemaxload for i in range(n): stones1.append([random.randint(0,maxgen),random.randint(0,maxgen)]) stoneload.append(random.randint(0,300)) for i in stoneload: stonemaxload.append(i) return stones1,stoneload def load(stoneing,stoneingl,stoneingml): global stones1,stoneload,stonemaxload stones1=stoneing stoneload=stoneingl stonemaxload=stoneingml def getlo(): global stones1,stoneload return stones1,stoneload def cut(n,i): global stoneload,stonemaxload stoneload[n]-=i def get(n): return stoneload[n] def stnw(f): global frpl1 frpl1=f def ggget(): global frpl1 return frpl1 def getmax(n): global stonemaxload return stonemaxload[n] def get_all(): return forests,forestload,forestmaxload,stones1,stoneload,stonemaxload
1,293
-12
450
addfbd51a9bfbe32f25a15f5a5b371e22f592d52
8,144
py
Python
yz/rl_agent_sil.py
yizhouzhao/moca
2a4c3cb140f59aef94f9cdfce1169089b3aabddf
[ "MIT" ]
null
null
null
yz/rl_agent_sil.py
yizhouzhao/moca
2a4c3cb140f59aef94f9cdfce1169089b3aabddf
[ "MIT" ]
null
null
null
yz/rl_agent_sil.py
yizhouzhao/moca
2a4c3cb140f59aef94f9cdfce1169089b3aabddf
[ "MIT" ]
null
null
null
from yz.nav_tools import FrameInfo from yz.params import * from yz.rl_policy import PolicyNetwork, ValueNetwork from yz.utils import soft_update_from_to from ai2thor.controller import Controller from collections import deque import random import numpy as np import torch import torch.nn as nn import torch.optim as optim
32.189723
116
0.603635
from yz.nav_tools import FrameInfo from yz.params import * from yz.rl_policy import PolicyNetwork, ValueNetwork from yz.utils import soft_update_from_to from ai2thor.controller import Controller from collections import deque import random import numpy as np import torch import torch.nn as nn import torch.optim as optim class QueryAgentSIL(): def __init__(self, scene, target, room_object_types = G_livingroom_objtype): # ai2thor self.scene = scene self.target = target assert self.target in room_object_types self.room_object_types = room_object_types self.controller = Controller(scene=scene, renderInstanceSegmentation=True, width=1080, height=1080) self.target_type = target # register query FrameInfo.candidates = self.room_object_types self.query_indicates = [True for _ in range(len(FrameInfo.candidates))] # Keep track of qa history self.keep_frame_map = False # weather to keep history to avoid duplicated query self.replay_buffer = deque(maxlen = 1000) # self.frame_map = {} # (position and rotation) -> FrameInfo # RL part self.observation = None self.last_action = None self.episode_done = False self.episode_history = [] # reward self.time_penalty = -0.01 self.action_fail_penalty = -0.01 self.first_seen = False self.first_seen_reward = 1 # reward for finding the object initially self.first_in_range = False self.first_in_range_reward = 5.0 # object in interaction range self.mission_success_reward = 10.0 # object in interaction range and done # init event self.event = None self.step(5) # self.controller.step("Done") self.observation = self.get_observation() # training self.use_gpu = True # learning self.batch_size = 4 self.learning_rate = 0.001 self.alpha = 1 # soc temparature self.gamma = 0.95 # discount factor # record self.n_train_steps_total = 0 self.episode_steps = 0 self.episode_total_reward = 0 # policy network self.state_dim = len(self.observation) self.hidden_dim = 64 self.action_dim = 6 self.policy = PolicyNetwork(self.state_dim, self.hidden_dim, self.action_dim) self.value_net = ValueNetwork(self.state_dim, self.action_dim) if self.use_gpu: self.policy = self.policy.cuda() self.value_net = self.value_net.cuda() # loss self.vf_criterion = nn.MSELoss() self.policy_optimizer = optim.Adam( self.policy.parameters(), lr=self.learning_rate, ) self.value_optimizer = optim.Adam( self.value_net.parameters(), lr=self.learning_rate, ) def step(self, action_code:int): self.last_action = action_code self.event = self.controller.step(G_action_code2action[action_code]) def get_observation(self): ''' Get state for RL ''' state = [] frame_info = FrameInfo(self.event) # target encode target_encode = [0 for _ in range(len(self.room_object_types))] target_index = self.room_object_types.index(self.target_type) target_encode[target_index] = 1 state.extend(target_encode) # agent state: last action success encode last_action_success = 1 if self.event.metadata["lastActionSuccess"] else -1 state.append(last_action_success) last_action_encode = [0] * len(G_action2code) last_action_encode[self.last_action] = 1 state.extend(last_action_encode) # agent head position head_pose = round(self.event.metadata["agent"]['cameraHorizon']) // 30 state.append(head_pose) # object state query # if self.keep_history frame_info = FrameInfo(self.event) obj_query_state = frame_info.get_answer_array_for_all_candidates(self.query_indicates) state.extend(obj_query_state) return state def take_action(self): current_state = self.observation current_state_tensor = torch.FloatTensor(current_state).unsqueeze(0) if self.use_gpu: current_state_tensor = current_state_tensor.to("cuda") action, log_prob = self.policy.sample_action_with_prob(current_state_tensor) action_code = torch.argmax(action, dim = -1)[0].item() #print(action_code) self.step(action_code) next_observation = self.get_observation() # calulate reward reward = self.time_penalty if not self.event.metadata["lastActionSuccess"]: reward += self.action_fail_penalty frame_info = FrameInfo(self.event) if not self.first_seen: for obj in frame_info.object_info: if self.target_type == obj["objectType"]: reward += self.first_seen_reward self.first_seen = True break if not self.first_in_range: for obj in frame_info.object_info: if self.target_type == obj["objectType"] and obj["visible"] == True: reward += self.first_in_range_reward self.first_in_range = True break for obj in frame_info.object_info: if self.target_type == obj["objectType"] and obj["visible"] == True: if action_code == 5: reward += self.mission_success_reward self.episode_done = True break self.episode_history.append([self.observation.copy(), action_code, reward, log_probs[0], self.episode_done]) self.observation = next_observation # for print record self.episode_steps += 1 self.episode_total_reward += reward def learn(self): ''' On episode ends, learn somethings ''' # A2C part policy_loss = 0 value_loss = 0 R = 0 for i in reversed(range(len(self.episode_history))): state = h[0] action = h[1] reward = h[2] log_probs = h[3] h = self.episode_history[i] R = self.gamma * R + reward s0 = torch.FloatTensor(state) if self.use_gpu: s0 = s0.to("cuda") value_i = self.value_net(s0.unsqueeze(-1))[0] advantage = R - values_i value_loss += 0.5 * advantage ** 2 entropy = - torch.sum(torch.exp(log_probs) * log_probs) policy_loss = policy_loss - log_probs[action] * advantage.detach() - self.alpha * entropy #update parameters self.policy_optimizer.zero_grad() policy_loss.backward() self.policy_optimizer.step() self.value_optimizer.zero_grad() value_loss.backward() self.value_optimizer.step() def reset_scene_and_target(self, scene: str, target: str): self.controller.reset(scene=scene) self.target_type = target def reset_episode(self): self.reset_scene_and_target(self.scene, self.target) self.episode_done = False self.episode_steps = 0 self.episode_total_reward = 0 self.episode_policy_loss.clear() self.episode_pf1_loss.clear() self.episode_pf2_loss.clear() def close(self): self.controller.stop() def save_model(self): from datetime import datetime now = datetime.now() time_str = now.strftime("%H:%M:%S") torch.save(self.qf1.state_dict(), "record/qf1_" + time_str + ".pth") torch.save(self.qf2.state_dict(), "record/qf2_" + time_str + ".pth") torch.save(self.qf2.state_dict(), "record/policy_" + time_str + ".pth")
5,382
2,416
23
56741da3d94b0e05476cdd784d626e95cb58ad9b
1,185
py
Python
ucb_cs61A/lab/lab09/tests/accumulate.py
tavaresdong/courses-notes
7fb89103bca679f5ef9b14cbc777152daac1402e
[ "MIT" ]
null
null
null
ucb_cs61A/lab/lab09/tests/accumulate.py
tavaresdong/courses-notes
7fb89103bca679f5ef9b14cbc777152daac1402e
[ "MIT" ]
1
2017-07-31T08:15:26.000Z
2017-07-31T08:15:26.000Z
ucb_cs61A/lab/lab09/tests/accumulate.py
tavaresdong/courses-notes
7fb89103bca679f5ef9b14cbc777152daac1402e
[ "MIT" ]
1
2019-10-06T16:52:31.000Z
2019-10-06T16:52:31.000Z
test = { 'name': 'accumulate', 'points': 0, 'suites': [ { 'cases': [ { 'code': r""" scm> (accumulate + 0 4 square) 30 """, 'hidden': False, 'locked': False } ], 'scored': False, 'setup': r""" scm> (load 'lab09_extra) scm> (define (square x) (* x x)) """, 'teardown': '', 'type': 'scheme' }, { 'cases': [ { 'code': r""" scm> (accumulate * 3 3 identity) 18 """, 'hidden': False, 'locked': False } ], 'scored': False, 'setup': r""" scm> (load 'lab09_extra) scm> (define (identity x) x) """, 'teardown': '', 'type': 'scheme' }, { 'cases': [ { 'code': r""" scm> (accumulate + 1 5 add-one) 21 """, 'hidden': False, 'locked': False } ], 'scored': False, 'setup': r""" scm> (load 'lab09_extra) scm> (define (add-one x) (+ x 1)) """, 'teardown': '', 'type': 'scheme' } ] }
18.809524
42
0.347679
test = { 'name': 'accumulate', 'points': 0, 'suites': [ { 'cases': [ { 'code': r""" scm> (accumulate + 0 4 square) 30 """, 'hidden': False, 'locked': False } ], 'scored': False, 'setup': r""" scm> (load 'lab09_extra) scm> (define (square x) (* x x)) """, 'teardown': '', 'type': 'scheme' }, { 'cases': [ { 'code': r""" scm> (accumulate * 3 3 identity) 18 """, 'hidden': False, 'locked': False } ], 'scored': False, 'setup': r""" scm> (load 'lab09_extra) scm> (define (identity x) x) """, 'teardown': '', 'type': 'scheme' }, { 'cases': [ { 'code': r""" scm> (accumulate + 1 5 add-one) 21 """, 'hidden': False, 'locked': False } ], 'scored': False, 'setup': r""" scm> (load 'lab09_extra) scm> (define (add-one x) (+ x 1)) """, 'teardown': '', 'type': 'scheme' } ] }
0
0
0
c20c0b53ab477291ef3dcfbc603ab811174b4302
3,328
py
Python
coderunner/interact.py
zhao-embassy/learn_language
2719f27dea1877ba1da32f1c1d53ebedd5a81fdf
[ "FSFAP" ]
48
2015-02-05T15:25:47.000Z
2022-01-07T05:52:03.000Z
coderunner/interact.py
zhao-embassy/learn_language
2719f27dea1877ba1da32f1c1d53ebedd5a81fdf
[ "FSFAP" ]
null
null
null
coderunner/interact.py
zhao-embassy/learn_language
2719f27dea1877ba1da32f1c1d53ebedd5a81fdf
[ "FSFAP" ]
21
2015-02-12T23:50:10.000Z
2019-12-12T08:25:35.000Z
r""" communicate with interactive subprocess, such as GHCi, and get its output >>> s = interact('ghci', ':t 1\n' + EOT) >>> get_ghci_body(s) 'Prelude> :t 1\n1 :: (Num t) => t' >>> s = interact('swipl', 'X = 1 - 1.\n' + EOT) >>> get_swipl_body(s) '?- X = 1 - 1.\nX = 1-1.' >>> s = interact('python', 'import this\n' + EOT) >>> get_python_body(s).split('\n')[:2] ['>>> import this', 'The Zen of Python, by Tim Peters'] Scala takes more than 1 second (default timeout) to respond. I set timeout=10.0 to wait it. >>> s = interact('scala-2.10', '1\n' + EOT, timeout=10.0) >>> get_scala_body(s) 'scala> 1\nres0: Int = 1' """ from select import select import os import pty import re TYPESCRIPT = 'tmp.log' EOT = '\x04' # ^D: End of Transmission ESCAPE_SEQUENCE = ( '\x1B\[\d+(;\d+)*m|' # color '\x1B\[\d+;\d+[Hf]|' # move cursor absolute '\x1B\[\d*[ABCD]|' # move cursor relative '\x1B\[[DMELsu]|' # other cursor? '\x1B\[\?1[lh]|' # ? from GHCi '\x1B[=>]|' # ? from GHCi '\x1B\[0?J|' # delete back '\x1B\[1J|' # delete forward? '\x1B\[2J|\x1B\*|' # clear screen '\x1B\[0?K|' # kill right line '\x1B\[1K|' # kill left line '\x1B\[2K|' # kill whole line '\x1B\[6n') # console input? # ported from 'pty' library STDIN_FILENO = 0 CHILD = 0 def spawn(argv, master_read, stdin_read, commands_to_run, timeout): """Create a spawned process.""" if type(argv) == type(''): argv = (argv,) pid, master_fd = pty.fork() if pid == CHILD: os.execlp(argv[0], *argv) pty._writen(master_fd, commands_to_run) fds = [master_fd] while True: rfds, wfds, xfds = select(fds, [], [], timeout) if not rfds: # timeout break data = master_read(master_fd) if not data: # Reached EOF. break os.close(master_fd) # end: ported from 'pty' library if __name__ == '__main__': _test()
24.651852
73
0.555589
r""" communicate with interactive subprocess, such as GHCi, and get its output >>> s = interact('ghci', ':t 1\n' + EOT) >>> get_ghci_body(s) 'Prelude> :t 1\n1 :: (Num t) => t' >>> s = interact('swipl', 'X = 1 - 1.\n' + EOT) >>> get_swipl_body(s) '?- X = 1 - 1.\nX = 1-1.' >>> s = interact('python', 'import this\n' + EOT) >>> get_python_body(s).split('\n')[:2] ['>>> import this', 'The Zen of Python, by Tim Peters'] Scala takes more than 1 second (default timeout) to respond. I set timeout=10.0 to wait it. >>> s = interact('scala-2.10', '1\n' + EOT, timeout=10.0) >>> get_scala_body(s) 'scala> 1\nres0: Int = 1' """ from select import select import os import pty import re TYPESCRIPT = 'tmp.log' EOT = '\x04' # ^D: End of Transmission ESCAPE_SEQUENCE = ( '\x1B\[\d+(;\d+)*m|' # color '\x1B\[\d+;\d+[Hf]|' # move cursor absolute '\x1B\[\d*[ABCD]|' # move cursor relative '\x1B\[[DMELsu]|' # other cursor? '\x1B\[\?1[lh]|' # ? from GHCi '\x1B[=>]|' # ? from GHCi '\x1B\[0?J|' # delete back '\x1B\[1J|' # delete forward? '\x1B\[2J|\x1B\*|' # clear screen '\x1B\[0?K|' # kill right line '\x1B\[1K|' # kill left line '\x1B\[2K|' # kill whole line '\x1B\[6n') # console input? # ported from 'pty' library STDIN_FILENO = 0 CHILD = 0 def spawn(argv, master_read, stdin_read, commands_to_run, timeout): """Create a spawned process.""" if type(argv) == type(''): argv = (argv,) pid, master_fd = pty.fork() if pid == CHILD: os.execlp(argv[0], *argv) pty._writen(master_fd, commands_to_run) fds = [master_fd] while True: rfds, wfds, xfds = select(fds, [], [], timeout) if not rfds: # timeout break data = master_read(master_fd) if not data: # Reached EOF. break os.close(master_fd) # end: ported from 'pty' library def interact(shell, commands_to_run, timeout=1.0): typescript = open(TYPESCRIPT, 'w') def read(fd): data = os.read(fd, 1024) typescript.write(data) typescript.flush() return data def read2(fd): data = os.read(fd, 1024) return data spawn(shell, read, read2, commands_to_run, timeout) typescript.close() data = open(TYPESCRIPT).read() return remove_escape_sequence(data) def remove_escape_sequence(s): return re.sub(ESCAPE_SEQUENCE, '', s) def get_ghci_body(s): m = re.search(r'Prelude>.*(?=\r\n\w+>)', s, re.DOTALL) ret = m.group() # nomarlize newline ret = ret.replace('\r\n', '\n') ret = ret.replace('\r', '') return ret def get_swipl_body(s): m = re.search(r'\r\n\r\n(\?- .*)(?=\r\n\r\n\?- )', s, re.DOTALL) ret = m.groups()[0] # nomarlize newline ret = ret.replace('\r\n', '\n') ret = ret.replace('\r', '') return ret def get_python_body(s): m = re.search(r'>>>.*(?=\r\n>>>)', s, re.DOTALL) ret = m.group() ret = ret.replace('\r\n', '\n') return ret def get_scala_body(s): m = re.search(r'scala>.*(?=\r\n\r\nscala>)', s, re.DOTALL) ret = m.group() ret = ret.replace('\r\n', '\n') return ret def _test(): import doctest doctest.testmod() if __name__ == '__main__': _test()
1,158
0
161
4c27a7ebbbdaa0bf7cc6bd83f0a8e845805c3b62
7,168
py
Python
docx2python/iterators.py
FabianGroeger96/docx2python
7a43fc4ef15033881203713224e894ae33ef79d7
[ "MIT" ]
null
null
null
docx2python/iterators.py
FabianGroeger96/docx2python
7a43fc4ef15033881203713224e894ae33ef79d7
[ "MIT" ]
null
null
null
docx2python/iterators.py
FabianGroeger96/docx2python
7a43fc4ef15033881203713224e894ae33ef79d7
[ "MIT" ]
null
null
null
#!/usr/bin/env python3 # _*_ coding: utf-8 _*_ """Iterate over extracted docx content. :author: Shay Hill :created: 6/28/2019 This package extracts docx text as:: [ # tables [ # table [ # row [ # cell "" # paragraph ] ] ] ] These functions help manipulate that deep nest without deep indentation. """ from typing import Any, Iterable, Iterator, List, NamedTuple, Sequence, Tuple TablesList = Sequence[Sequence[Sequence[Sequence[Any]]]] IndexedItem = NamedTuple("IndexedItem", [("index", Tuple[int, ...]), ("value", Any)]) def enum_at_depth(nested: Sequence[Any], depth: int) -> Iterator[IndexedItem]: """ Enumerate over a nested sequence at depth. :param nested: a (nested) sequence :param depth: depth of iteration * ``1`` => ``((i,), nested[i])`` * ``2`` => ``((i, j), nested[:][j])`` * ``3`` => ``((i, j, k), nested[:][:][k])`` * ... :returns: tuples (tuple "address", item) >>> sequence = [ ... [[["a", "b"], ["c"]], [["d", "e"]]], ... [[["f"], ["g", "h"]]] ... ] >>> for x in enum_at_depth(sequence, 1): print(x) IndexedItem(index=(0,), value=[[['a', 'b'], ['c']], [['d', 'e']]]) IndexedItem(index=(1,), value=[[['f'], ['g', 'h']]]) >>> for x in enum_at_depth(sequence, 2): print(x) IndexedItem(index=(0, 0), value=[['a', 'b'], ['c']]) IndexedItem(index=(0, 1), value=[['d', 'e']]) IndexedItem(index=(1, 0), value=[['f'], ['g', 'h']]) >>> for x in enum_at_depth(sequence, 3): print(x) IndexedItem(index=(0, 0, 0), value=['a', 'b']) IndexedItem(index=(0, 0, 1), value=['c']) IndexedItem(index=(0, 1, 0), value=['d', 'e']) IndexedItem(index=(1, 0, 0), value=['f']) IndexedItem(index=(1, 0, 1), value=['g', 'h']) >>> for x in enum_at_depth(sequence, 4): print(x) IndexedItem(index=(0, 0, 0, 0), value='a') IndexedItem(index=(0, 0, 0, 1), value='b') IndexedItem(index=(0, 0, 1, 0), value='c') IndexedItem(index=(0, 1, 0, 0), value='d') IndexedItem(index=(0, 1, 0, 1), value='e') IndexedItem(index=(1, 0, 0, 0), value='f') IndexedItem(index=(1, 0, 1, 0), value='g') IndexedItem(index=(1, 0, 1, 1), value='h') >>> list(enum_at_depth(sequence, 5)) Traceback (most recent call last): ... TypeError: will not iterate over sequence item This error is analogous to the ``TypeError: 'int' object is not iterable`` you would see if attempting to enumerate over a non-iterable. In this case, you've attempted to enumerate over an item that *may* be iterable, but is not of the same type as the ``nested`` sequence argument. This type checking is how we can safely descend into a nested list of strings. """ if depth < 1: raise ValueError("depth argument must be >= 1") argument_type = type(nested) def enumerate_next_depth(enumd: Iterable[IndexedItem]) -> Iterator[IndexedItem]: """ Descend into a nested sequence, enumerating along descent :param enumd: tuples (tuple of indices, sequences) :return: updated index tuples with items from each sequence. """ for index_tuple, sequence in enumd: if type(sequence) != argument_type: raise TypeError("will not iterate over sequence item") for i, item in enumerate(sequence): yield IndexedItem(index_tuple + (i,), item) depth_n = (IndexedItem((i,), x) for i, x in enumerate(nested)) for depth in range(1, depth): depth_n = enumerate_next_depth(depth_n) return depth_n def iter_at_depth(nested: Sequence[Any], depth: int) -> Iterator[Any]: """ Iterate over a nested sequence at depth. :param nested: a (nested) sequence :param depth: depth of iteration * ``1`` => ``nested[i]`` * ``2`` => ``nested[:][j]`` * ``3`` => ``nested[:][:][k]`` * ... :returns: sub-sequences or items in nested >>> sequence = [ ... [[["a", "b"], ["c"]], [["d", "e"]]], ... [[["f"], ["g", "h"]]] ... ] >>> for x in iter_at_depth(sequence, 1): print(x) [[['a', 'b'], ['c']], [['d', 'e']]] [[['f'], ['g', 'h']]] >>> for x in iter_at_depth(sequence, 2): print(x) [['a', 'b'], ['c']] [['d', 'e']] [['f'], ['g', 'h']] >>> for x in iter_at_depth(sequence, 3): print(x) ['a', 'b'] ['c'] ['d', 'e'] ['f'] ['g', 'h'] >>> list(iter_at_depth(sequence, 4)) ['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h'] """ return (value for index, value in enum_at_depth(nested, depth)) def iter_tables(tables: TablesList) -> Iterator[List[List[List[Any]]]]: """ Iterate over ``tables[i]`` Analog of iter_at_depth(tables, 1) :param tables: ``[[[["string"]]]]`` :return: ``tables[0], tables[1], ... tables[i]`` """ return iter_at_depth(tables, 1) def iter_rows(tables: TablesList) -> Iterator[List[List[Any]]]: """ Iterate over ``tables[:][j]`` Analog of iter_at_depth(tables, 2) :param tables: ``[[[["string"]]]]`` :return: ``tables[0][0], tables[0][1], ... tables[i][j]`` """ return iter_at_depth(tables, 2) def iter_cells(tables: TablesList) -> Iterator[List[Any]]: """ Iterate over ``tables[:][:][k]`` Analog of iter_at_depth(tables, 3) :param tables: ``[[[["string"]]]]`` :return: ``tables[0][0][0], tables[0][0][1], ... tables[i][j][k]`` """ return iter_at_depth(tables, 3) def iter_paragraphs(tables: TablesList) -> Iterator[str]: """ Iterate over ``tables[:][:][:][l]`` Analog of iter_at_depth(tables, 4) :param tables: ``[[[["string"]]]]`` :return: ``tables[0][0][0][0], tables[0][0][0][1], ... tables[i][j][k][l]`` """ return iter_at_depth(tables, 4) def enum_tables(tables: TablesList) -> Iterator[IndexedItem]: """ Enumerate over ``tables[i]`` Analog of enum_at_depth(tables, 1) :param tables: ``[[[["string"]]]]`` :return: ``((0, ), tables[0]) ... , ((i, ), tables[i])`` """ return enum_at_depth(tables, 1) def enum_rows(tables: TablesList) -> Iterator[IndexedItem]: """ Enumerate over ``tables[:][j]`` Analog of enum_at_depth(tables, 2) :param tables: ``[[[["string"]]]]`` :return: ``((0, 0), tables[0][0]) ... , ((i, j), tables[i][j])`` """ return enum_at_depth(tables, 2) def enum_cells(tables: TablesList) -> Iterator[IndexedItem]: """ Enumerate over ``tables[:][:][k]`` Analog of enum_at_depth(tables, 3) :param tables: ``[[[["string"]]]]`` :return: ``((0, 0, 0), tables[0][0][0]) ... , ((i, j, k), tables[i][j][k])`` """ return enum_at_depth(tables, 3) def enum_paragraphs(tables: TablesList) -> Iterator[IndexedItem]: """ Enumerate over ``tables[:][:][:][l]`` Analog of enum_at_depth(tables, 4) :param tables: ``[[[["string"]]]]`` :return: ``((0, 0, 0, 0), tables[0][0][0][0]) ... , ((i, j, k, l), tables[i][j][k][l])`` """ return enum_at_depth(tables, 4)
28.787149
87
0.539063
#!/usr/bin/env python3 # _*_ coding: utf-8 _*_ """Iterate over extracted docx content. :author: Shay Hill :created: 6/28/2019 This package extracts docx text as:: [ # tables [ # table [ # row [ # cell "" # paragraph ] ] ] ] These functions help manipulate that deep nest without deep indentation. """ from typing import Any, Iterable, Iterator, List, NamedTuple, Sequence, Tuple TablesList = Sequence[Sequence[Sequence[Sequence[Any]]]] IndexedItem = NamedTuple("IndexedItem", [("index", Tuple[int, ...]), ("value", Any)]) def enum_at_depth(nested: Sequence[Any], depth: int) -> Iterator[IndexedItem]: """ Enumerate over a nested sequence at depth. :param nested: a (nested) sequence :param depth: depth of iteration * ``1`` => ``((i,), nested[i])`` * ``2`` => ``((i, j), nested[:][j])`` * ``3`` => ``((i, j, k), nested[:][:][k])`` * ... :returns: tuples (tuple "address", item) >>> sequence = [ ... [[["a", "b"], ["c"]], [["d", "e"]]], ... [[["f"], ["g", "h"]]] ... ] >>> for x in enum_at_depth(sequence, 1): print(x) IndexedItem(index=(0,), value=[[['a', 'b'], ['c']], [['d', 'e']]]) IndexedItem(index=(1,), value=[[['f'], ['g', 'h']]]) >>> for x in enum_at_depth(sequence, 2): print(x) IndexedItem(index=(0, 0), value=[['a', 'b'], ['c']]) IndexedItem(index=(0, 1), value=[['d', 'e']]) IndexedItem(index=(1, 0), value=[['f'], ['g', 'h']]) >>> for x in enum_at_depth(sequence, 3): print(x) IndexedItem(index=(0, 0, 0), value=['a', 'b']) IndexedItem(index=(0, 0, 1), value=['c']) IndexedItem(index=(0, 1, 0), value=['d', 'e']) IndexedItem(index=(1, 0, 0), value=['f']) IndexedItem(index=(1, 0, 1), value=['g', 'h']) >>> for x in enum_at_depth(sequence, 4): print(x) IndexedItem(index=(0, 0, 0, 0), value='a') IndexedItem(index=(0, 0, 0, 1), value='b') IndexedItem(index=(0, 0, 1, 0), value='c') IndexedItem(index=(0, 1, 0, 0), value='d') IndexedItem(index=(0, 1, 0, 1), value='e') IndexedItem(index=(1, 0, 0, 0), value='f') IndexedItem(index=(1, 0, 1, 0), value='g') IndexedItem(index=(1, 0, 1, 1), value='h') >>> list(enum_at_depth(sequence, 5)) Traceback (most recent call last): ... TypeError: will not iterate over sequence item This error is analogous to the ``TypeError: 'int' object is not iterable`` you would see if attempting to enumerate over a non-iterable. In this case, you've attempted to enumerate over an item that *may* be iterable, but is not of the same type as the ``nested`` sequence argument. This type checking is how we can safely descend into a nested list of strings. """ if depth < 1: raise ValueError("depth argument must be >= 1") argument_type = type(nested) def enumerate_next_depth(enumd: Iterable[IndexedItem]) -> Iterator[IndexedItem]: """ Descend into a nested sequence, enumerating along descent :param enumd: tuples (tuple of indices, sequences) :return: updated index tuples with items from each sequence. """ for index_tuple, sequence in enumd: if type(sequence) != argument_type: raise TypeError("will not iterate over sequence item") for i, item in enumerate(sequence): yield IndexedItem(index_tuple + (i,), item) depth_n = (IndexedItem((i,), x) for i, x in enumerate(nested)) for depth in range(1, depth): depth_n = enumerate_next_depth(depth_n) return depth_n def iter_at_depth(nested: Sequence[Any], depth: int) -> Iterator[Any]: """ Iterate over a nested sequence at depth. :param nested: a (nested) sequence :param depth: depth of iteration * ``1`` => ``nested[i]`` * ``2`` => ``nested[:][j]`` * ``3`` => ``nested[:][:][k]`` * ... :returns: sub-sequences or items in nested >>> sequence = [ ... [[["a", "b"], ["c"]], [["d", "e"]]], ... [[["f"], ["g", "h"]]] ... ] >>> for x in iter_at_depth(sequence, 1): print(x) [[['a', 'b'], ['c']], [['d', 'e']]] [[['f'], ['g', 'h']]] >>> for x in iter_at_depth(sequence, 2): print(x) [['a', 'b'], ['c']] [['d', 'e']] [['f'], ['g', 'h']] >>> for x in iter_at_depth(sequence, 3): print(x) ['a', 'b'] ['c'] ['d', 'e'] ['f'] ['g', 'h'] >>> list(iter_at_depth(sequence, 4)) ['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h'] """ return (value for index, value in enum_at_depth(nested, depth)) def iter_tables(tables: TablesList) -> Iterator[List[List[List[Any]]]]: """ Iterate over ``tables[i]`` Analog of iter_at_depth(tables, 1) :param tables: ``[[[["string"]]]]`` :return: ``tables[0], tables[1], ... tables[i]`` """ return iter_at_depth(tables, 1) def iter_rows(tables: TablesList) -> Iterator[List[List[Any]]]: """ Iterate over ``tables[:][j]`` Analog of iter_at_depth(tables, 2) :param tables: ``[[[["string"]]]]`` :return: ``tables[0][0], tables[0][1], ... tables[i][j]`` """ return iter_at_depth(tables, 2) def iter_cells(tables: TablesList) -> Iterator[List[Any]]: """ Iterate over ``tables[:][:][k]`` Analog of iter_at_depth(tables, 3) :param tables: ``[[[["string"]]]]`` :return: ``tables[0][0][0], tables[0][0][1], ... tables[i][j][k]`` """ return iter_at_depth(tables, 3) def iter_paragraphs(tables: TablesList) -> Iterator[str]: """ Iterate over ``tables[:][:][:][l]`` Analog of iter_at_depth(tables, 4) :param tables: ``[[[["string"]]]]`` :return: ``tables[0][0][0][0], tables[0][0][0][1], ... tables[i][j][k][l]`` """ return iter_at_depth(tables, 4) def enum_tables(tables: TablesList) -> Iterator[IndexedItem]: """ Enumerate over ``tables[i]`` Analog of enum_at_depth(tables, 1) :param tables: ``[[[["string"]]]]`` :return: ``((0, ), tables[0]) ... , ((i, ), tables[i])`` """ return enum_at_depth(tables, 1) def enum_rows(tables: TablesList) -> Iterator[IndexedItem]: """ Enumerate over ``tables[:][j]`` Analog of enum_at_depth(tables, 2) :param tables: ``[[[["string"]]]]`` :return: ``((0, 0), tables[0][0]) ... , ((i, j), tables[i][j])`` """ return enum_at_depth(tables, 2) def enum_cells(tables: TablesList) -> Iterator[IndexedItem]: """ Enumerate over ``tables[:][:][k]`` Analog of enum_at_depth(tables, 3) :param tables: ``[[[["string"]]]]`` :return: ``((0, 0, 0), tables[0][0][0]) ... , ((i, j, k), tables[i][j][k])`` """ return enum_at_depth(tables, 3) def enum_paragraphs(tables: TablesList) -> Iterator[IndexedItem]: """ Enumerate over ``tables[:][:][:][l]`` Analog of enum_at_depth(tables, 4) :param tables: ``[[[["string"]]]]`` :return: ``((0, 0, 0, 0), tables[0][0][0][0]) ... , ((i, j, k, l), tables[i][j][k][l])`` """ return enum_at_depth(tables, 4)
0
0
0
e48df518cad508f16a41114500431b930ec91a46
2,062
py
Python
tests/test_cli_gui/test_fetch.py
ejfitzgerald/agents-aea
6411fcba8af2cdf55a3005939ae8129df92e8c3e
[ "Apache-2.0" ]
null
null
null
tests/test_cli_gui/test_fetch.py
ejfitzgerald/agents-aea
6411fcba8af2cdf55a3005939ae8129df92e8c3e
[ "Apache-2.0" ]
null
null
null
tests/test_cli_gui/test_fetch.py
ejfitzgerald/agents-aea
6411fcba8af2cdf55a3005939ae8129df92e8c3e
[ "Apache-2.0" ]
null
null
null
# -*- coding: utf-8 -*- # ------------------------------------------------------------------------------ # # Copyright 2018-2020 Fetch.AI Limited # # 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. # # ------------------------------------------------------------------------------ """This test module contains the tests for the `aea gui` sub-commands.""" import json from unittest.mock import patch from tests.test_cli.tools_for_testing import raise_click_exception from tests.test_cli_gui.test_base import create_app @patch("aea.cli_gui.cli_fetch_agent") def test_fetch_agent(*mocks): """Test fetch an agent.""" app = create_app() agent_name = "test_agent_name" agent_id = "author/{}:0.1.0".format(agent_name) # Ensure there is now one agent resp = app.post( "api/fetch-agent", content_type="application/json", data=json.dumps(agent_id), ) assert resp.status_code == 201 data = json.loads(resp.get_data(as_text=True)) assert data == agent_name @patch("aea.cli_gui.cli_fetch_agent", raise_click_exception) def test_fetch_agent_fail(*mocks): """Test fetch agent fail.""" app = create_app() agent_name = "test_agent_name" agent_id = "author/{}:0.1.0".format(agent_name) resp = app.post( "api/fetch-agent", content_type="application/json", data=json.dumps(agent_id), ) assert resp.status_code == 400 data = json.loads(resp.get_data(as_text=True)) assert data["detail"] == "Failed to fetch an agent {}. {}".format( agent_id, "Message" )
33.258065
86
0.64452
# -*- coding: utf-8 -*- # ------------------------------------------------------------------------------ # # Copyright 2018-2020 Fetch.AI Limited # # 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. # # ------------------------------------------------------------------------------ """This test module contains the tests for the `aea gui` sub-commands.""" import json from unittest.mock import patch from tests.test_cli.tools_for_testing import raise_click_exception from tests.test_cli_gui.test_base import create_app @patch("aea.cli_gui.cli_fetch_agent") def test_fetch_agent(*mocks): """Test fetch an agent.""" app = create_app() agent_name = "test_agent_name" agent_id = "author/{}:0.1.0".format(agent_name) # Ensure there is now one agent resp = app.post( "api/fetch-agent", content_type="application/json", data=json.dumps(agent_id), ) assert resp.status_code == 201 data = json.loads(resp.get_data(as_text=True)) assert data == agent_name @patch("aea.cli_gui.cli_fetch_agent", raise_click_exception) def test_fetch_agent_fail(*mocks): """Test fetch agent fail.""" app = create_app() agent_name = "test_agent_name" agent_id = "author/{}:0.1.0".format(agent_name) resp = app.post( "api/fetch-agent", content_type="application/json", data=json.dumps(agent_id), ) assert resp.status_code == 400 data = json.loads(resp.get_data(as_text=True)) assert data["detail"] == "Failed to fetch an agent {}. {}".format( agent_id, "Message" )
0
0
0
77cd887735c4c63ff879ffa44e3e4c4e0b7004b1
487
py
Python
scripts/encode.py
univoid/a3x
46f48363f191344747fec5e643efe1b467fb04c3
[ "MIT" ]
null
null
null
scripts/encode.py
univoid/a3x
46f48363f191344747fec5e643efe1b467fb04c3
[ "MIT" ]
null
null
null
scripts/encode.py
univoid/a3x
46f48363f191344747fec5e643efe1b467fb04c3
[ "MIT" ]
null
null
null
import base64 if __name__ == "__main__": print convert("in.jpeg")
22.136364
46
0.64271
import base64 def decode_base64(data): missing_padding = len(data) % 4 if missing_padding != 0: data += b'='* (4 - missing_padding) return base64.decodestring(data) def convert(image): f = open(image) data = f.read() f.close() base64_encode_str = base64.b64encode(data) t = open("out.jpeg", "wb+") t.write(decode_base64(base64_encode_str)) t.close() return base64_encode_str if __name__ == "__main__": print convert("in.jpeg")
370
0
46
a5e6293df4e370dbbceb0976cbcb58cc075c164c
2,568
py
Python
scripts/tests/tests1.py
ronan-keane/hav-sim
0aaf9674e987822ff2dc90c74613d5e68e8ef0ce
[ "Apache-2.0" ]
null
null
null
scripts/tests/tests1.py
ronan-keane/hav-sim
0aaf9674e987822ff2dc90c74613d5e68e8ef0ce
[ "Apache-2.0" ]
null
null
null
scripts/tests/tests1.py
ronan-keane/hav-sim
0aaf9674e987822ff2dc90c74613d5e68e8ef0ce
[ "Apache-2.0" ]
2
2020-09-30T22:44:37.000Z
2021-05-09T07:36:28.000Z
""" @author: rlk268@cornell.edu test helper functions """ from havsim.calibration.helper import makeleadfolinfo, boundaryspeeds, interpolate path_reconngsim = 'C:/Users/rlk268/OneDrive - Cornell University/important misc/pickle files/meng/reconngsim.pkl' # reconstructed ngsim data with open(path_reconngsim, 'rb') as f: data = pickle.load(f)[0] meas, platooninfo, = makeplatoonlist(data,1,False) platoon = [875.0, 903.0, 908.0] # dataset only with these vehicles toymeas = {} for i in platoon: toymeas[i] = meas[i].copy() toymeas[875][:, 4] = 0 toymeas[908][:, 5] = 0 test_interpolate() test_boundaryspeeds() test_leadfolinfo()
40.125
116
0.580997
""" @author: rlk268@cornell.edu test helper functions """ from havsim.calibration.helper import makeleadfolinfo, boundaryspeeds, interpolate path_reconngsim = 'C:/Users/rlk268/OneDrive - Cornell University/important misc/pickle files/meng/reconngsim.pkl' # reconstructed ngsim data with open(path_reconngsim, 'rb') as f: data = pickle.load(f)[0] meas, platooninfo, = makeplatoonlist(data,1,False) platoon = [875.0, 903.0, 908.0] # dataset only with these vehicles toymeas = {} for i in platoon: toymeas[i] = meas[i].copy() toymeas[875][:, 4] = 0 toymeas[908][:, 5] = 0 def test_interpolate(): assert interpolate(np.array([])) == ([], ()) assert interpolate(np.array([[1, 5]])) == ([5], (1, 1)) assert interpolate(np.array([[1, 5], [2, 6], [3, 7]]), 1) == ([5.0, 6.0, 7.0], (1, 3)) assert interpolate(np.array([[1, 5], [2, 6], [3, 7]]), interval=2.5) == ([(5 + 6 + 7 / 2.0) / 2.5], (1, 1.0)) assert interpolate(np.array([[1, 5], [2, 6], [4, 7]]), interval=2.5) == ( [(5 + 6 + 3) / 2.5, (3 + 7 + 7) / 2.5], (1, 3.5)) def test_boundaryspeeds(): result_to_test = boundaryspeeds(meas, [3, 4], [3, 4], .1, .1, car_ids=[875.0, 903.0, 908.0]) # according to the result we compute manually above car875 = toymeas[875] car903 = toymeas[903] car908 = toymeas[908] lane3entry = list(car875[np.isin(car875[:, 1], range(2558, 2574))][:, 3]) + list( car903[np.isin(car903[:, 1], range(2574, 2621))][:, 3]) + list( car908[np.isin(car908[:, 1], range(2621, 3140))][:, 3]) lane3exit = list(car875[np.isin(car875[:, 1], range(2558, 3083))][:, 3]) + list( car903[np.isin(car903[:, 1], range(3083, 3105))][:, 3]) + list( car908[np.isin(car908[:, 1], range(3105, 3140))][:, 3]) lane4entry = list(car875[np.isin(car875[:, 1], range(2555, 2558))][:, 3]) lane4exit = list(lane4entry) expected_result = [lane3entry, lane4entry], [(2558, 3139), (2555, 2557)], [lane3exit, lane4exit], [(2558, 3139), (2555, 2557)] assert result_to_test == expected_result test_interpolate() test_boundaryspeeds() def test_leadfolinfo(): leadinfo, folinfo, rinfo = makeleadfolinfo(platoon,platooninfo,meas) assert leadinfo == [[[886.0, 2555, 2557], [889.0, 2558, 3059]],[[875.0, 2574, 3082]],[[903.0, 2621, 3104]]] assert folinfo == [[[903.0, 2574, 3082]], [[908.0, 2621, 3104]], []] assert rinfo == [[[2558, 6.591962153199944]], [], []] test_leadfolinfo()
1,839
0
69
ce9d97cd2c8d61694d46d2f7ee2e3ee27fbb4bf9
1,185
py
Python
demo/fibonacci.py
camillobruni/pygirl
ddbd442d53061d6ff4af831c1eab153bcc771b5a
[ "MIT" ]
12
2016-01-06T07:10:28.000Z
2021-05-13T23:02:02.000Z
demo/fibonacci.py
woodrow/pyoac
b5dc59e6a38e7912db47f26fb23ffa4764a3c0e7
[ "MIT" ]
null
null
null
demo/fibonacci.py
woodrow/pyoac
b5dc59e6a38e7912db47f26fb23ffa4764a3c0e7
[ "MIT" ]
2
2016-07-29T07:09:50.000Z
2016-10-16T08:50:26.000Z
""" Thunk (a.k.a. lazy objects) in PyPy. To run on top of the thunk object space with the following command-line: py.py -o thunk fibonacci.py This is a typical Functional Programming Languages demo, computing the Fibonacci sequence by using an infinite lazy linked list. """ try: from __pypy__ import thunk # only available in 'py.py -o thunk' except ImportError: print __doc__ raise SystemExit(2) # ____________________________________________________________ def add_lists(list1, list2): """Compute the linked-list equivalent of the Python expression [a+b for (a,b) in zip(list1,list2)] """ return ListNode(list1.head + list2.head, thunk(add_lists, list1.tail, list2.tail)) # 1, 1, 2, 3, 5, 8, 13, 21, 34, ... Fibonacci = ListNode(1, ListNode(1, None)) Fibonacci.tail.tail = thunk(add_lists, Fibonacci, Fibonacci.tail) if __name__ == '__main__': node = Fibonacci while True: print node.head node = node.tail
26.931818
72
0.678481
""" Thunk (a.k.a. lazy objects) in PyPy. To run on top of the thunk object space with the following command-line: py.py -o thunk fibonacci.py This is a typical Functional Programming Languages demo, computing the Fibonacci sequence by using an infinite lazy linked list. """ try: from __pypy__ import thunk # only available in 'py.py -o thunk' except ImportError: print __doc__ raise SystemExit(2) # ____________________________________________________________ class ListNode: def __init__(self, head, tail): self.head = head # the first element of the list self.tail = tail # the sublist of all remaining elements def add_lists(list1, list2): """Compute the linked-list equivalent of the Python expression [a+b for (a,b) in zip(list1,list2)] """ return ListNode(list1.head + list2.head, thunk(add_lists, list1.tail, list2.tail)) # 1, 1, 2, 3, 5, 8, 13, 21, 34, ... Fibonacci = ListNode(1, ListNode(1, None)) Fibonacci.tail.tail = thunk(add_lists, Fibonacci, Fibonacci.tail) if __name__ == '__main__': node = Fibonacci while True: print node.head node = node.tail
136
-6
49
aacfde57a3d4e97b3f22201cd2b8b1e04de71e89
34,754
py
Python
websocket_server/wsfile.py
CylonicRaider/websocket-server
8288edf7f145b6359378c1bf745e92b9aa963791
[ "MIT" ]
1
2019-06-08T21:25:51.000Z
2019-06-08T21:25:51.000Z
websocket_server/wsfile.py
CylonicRaider/websocket-server
8288edf7f145b6359378c1bf745e92b9aa963791
[ "MIT" ]
null
null
null
websocket_server/wsfile.py
CylonicRaider/websocket-server
8288edf7f145b6359378c1bf745e92b9aa963791
[ "MIT" ]
1
2017-03-16T00:40:56.000Z
2017-03-16T00:40:56.000Z
# websocket_server -- WebSocket/HTTP server/client library # https://github.com/CylonicRaider/websocket-server """ WebSocket protocol implementation. client_handshake() and server_handshake() perform the appropriate operations on mappings of HTTP headers; the WebSocketFile class implements the framing protocol. """ import os import socket import struct import base64 import codecs import threading import hashlib from collections import namedtuple from . import constants from .compat import bytearray, bytes, tobytes, unicode, callable from .exceptions import ProtocolError, InvalidDataError from .exceptions import ConnectionClosedError from .tools import mask, new_mask __all__ = ['client_handshake', 'WebSocketFile', 'wrap'] # Allocation unit. BUFFER_SIZE = 16384 # Frame class Frame = namedtuple('Frame', 'opcode payload final msgtype') # Message class Message = namedtuple('Message', 'msgtype content final') # Adapted from RFC 6455: # 0 1 2 3 # 0 1 2 3 4 5 6 7 0 1 2 3 4 5 6 7 0 1 2 3 4 5 6 7 0 1 2 3 4 5 6 7 # +-+-+-+-+-------+-+-------------+-------------------------------+ # |F|R|R|R| opcode|M| Payload len | Extended payload length | # |I|S|S|S| (4) |A| (7) | (16/64) | # |N|V|V|V| |S| | (if payload len==126/127) | # | |1|2|3| |K| | | # +-+-+-+-+-------+-+-------------+ - - - - - - - - - - - - - - - + # | Extended payload length continued, if payload len == 127 | # + - - - - - - - - - - - - - - - +-------------------------------+ # | |Masking-key, if MASK set to 1 | # +-------------------------------+-------------------------------+ # | Masking-key (continued) | Payload Data | # +-------------------------------+ - - - - - - - - - - - - - - - + # : Payload Data continued ... : # + - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - + # | Payload Data continued ... | # +---------------------------------------------------------------+ # The "magic" GUID used for Sec-WebSocket-Accept. MAGIC_GUID = unicode('258EAFA5-E914-47DA-95CA-C5AB0DC85B11') def process_key(key): """ process_key(key) -> unicode Transform the given key as required to form a Sec-WebSocket-Accept field, and return the new key. """ enc_key = (unicode(key) + MAGIC_GUID).encode('ascii') resp_key = base64.b64encode(hashlib.sha1(enc_key).digest()) return resp_key.decode('ascii') def client_handshake(headers, protos=None, makekey=None): """ client_handshake(headers, protos=None, makekey=None) -> function Perform the client-side parts of a WebSocket handshake. headers is a mapping from header names to header values (both Unicode strings) which is modified in-place with WebSocket headers. protos is one of: - None to not advertise subprotocols, - A single string used directly as the Sec-WebSocket-Protocol header, - A list of strings, which are joined by commata into the value of the Sec-WebSocket-Protocol header. NOTE that the value of protos is not validated. makekey, if not None, is a function that returns a byte string of length 16 that is used as the base of the Sec-WebSocket-Key header. If makekey is None, os.urandom() is used. The return value is a function that takes the response headers (in the same format as headers) as the only parameter and raises a ProtocolError if the handshake is not successful. If the handshake *is* successful, the function returns the subprotocol selected by the server (a string that must have been present in protos), or None (for no subprotocol). NOTE that this library does not support extensions. For future compatibility, it would be prudent to specify makekey, if at all, as a keyword argument. """ def check_response(respheaders): "Ensure the given HTTP response headers are a valid WS handshake." # Verify key and other fields. if respheaders.get('Sec-WebSocket-Accept') != process_key(key): raise ProtocolError('Invalid response key') if respheaders.get('Sec-WebSocket-Extensions'): raise ProtocolError('Extensions not supported') p = respheaders.get('Sec-WebSocket-Protocol') # If protos is None, using the "in" operator may fail. if p and (not protos or p not in protos): raise ProtocolError('Invalid subprotocol received') return p if makekey is None: makekey = lambda: os.urandom(16) headers.update({'Connection': 'Upgrade', 'Upgrade': 'websocket', 'Sec-WebSocket-Version': '13'}) if isinstance(protos, str): headers['Sec-WebSocket-Protocol'] = protos elif protos is not None: headers['Sec-WebSocket-Protocol'] = ', '.join(protos) key = base64.b64encode(makekey()).decode('ascii') headers['Sec-WebSocket-Key'] = key return check_response def server_handshake(headers, protos=None): """ server_handshake(headers, protos=None) -> dict Perform the server-side part of a WebSocket handshake. headers is a maping from header names to header values (both Unicode strings), which is validated. protos is one of: - None to indicate no subprotocols, - A sequence or whitespace-delimited string of names of accepted subprotocols (the first subprotocol proposed by the client that is in the list is selected), - A function taking the list of subprotocols proposed by the client as the only argument and returning a subprotocol name or None. The return value is a mapping of headers to be included in the response. """ # The standard requires a Host header... why not... if 'Host' not in headers: error('Missing Host header') # Validate Upgrade header. if 'websocket' not in headers.get('Upgrade', '').lower(): error('Invalid/Missing Upgrade header') # Validate protocol version. if headers.get('Sec-WebSocket-Version') != '13': error('Invalid WebSocket version (!= 13)') # Validate Connection header. connection = [i.lower().strip() for i in headers.get('Connection', '').split(',')] if 'upgrade' not in connection: error('Invalid/Missing Connection header') # Validate the key. key = headers.get('Sec-WebSocket-Key') try: if len(base64.b64decode(tobytes(key))) != 16: error('Invalid WebSocket key length') except (TypeError, ValueError): error('Invalid WebSocket key') # Extensions are not supported. # Be permissive with subprotocol tokens. protstr = headers.get('Sec-WebSocket-Protocol', '') protlist = ([i.strip() for i in protstr.split(',')] if protstr else []) if protos is None: respproto = None elif callable(protos): respproto = protos(protlist) else: if isinstance(protos, str): protos = protos.split() # Intentionally leaking loop variable. for respproto in protlist: if respproto in protos: break else: respproto = None # Prepare response headers. ret = {'Connection': 'upgrade', 'Upgrade': 'websocket', 'Sec-WebSocket-Accept': process_key(key)} if respproto is not None: ret['Sec-WebSocket-Protocol'] = respproto return ret class WebSocketFile(object): """ WebSocket protocol implementation. May base on a pair of file-like objects (for usage in HTTPRequestHandler's); a "raw" socket (if you prefer parsing HTTP headers yourself); or a single file object (if you have got such a read-write one). This class is not concerned with the handshake; see client_handshake() and server_handshake() for that. WebSocketFile(rdfile, wrfile, server_side=False, subprotocol=None) rdfile : File to perform reading operations on. wrfile : File to perform writing operations on. server_side: Whether to engage server-side behavior (if true) or not (otherwise). subprotocol: The subprotocol to be used. Attributes: server_side : Whether this is a server-side WebSocketFile. subprotocol : The subprotocol as passed to the constructor. close_wrapped: Whether calling close() should close the underlying files as well. Defaults to True. _rdlock : threading.RLock instance used for serializing and protecting reading-related operations. _wrlock : threading.RLock instance user for serializing and protecting write-related operations. _rdlock should always be asserted before _wrlock, if at all; generally, do not call reading-related methods (which also include close*()) with _wrlock asserted, and do not use those locks unless necessary. _socket : Underlying socket (set by from_socket()). May not be present at all (i.e. be None). Only use this if you are really sure you need to. Class attributes: MAXFRAME : Maximum frame payload length. May be overridden by subclasses (or instances). Value is either an integer or None (indicating no limit). This is not enforced for outgoing messages. MAXCONTFRAME: Maximum length of a frame reconstructed from fragments. May be overridden as well. The value has the same semantics as the one of MAXFRAME. This is not enforced for outgoing messages as well. NOTE: This class reads exactly the amount of bytes needed, yet buffering of the underlying stream may cause frames to "congest". The underlying stream must be blocking, or unpredictable behavior occurs. """ # Maximum allowed frame length. MAXFRAME = None # Maximum continued frame length. MAXCONTFRAME = None @classmethod def from_files(cls, rdfile, wrfile, **kwds): """ from_files(rdfile, wrfile, **kwds) -> WebSocketFile Equivalent to the constructor; provided for symmetry. """ return cls(rdfile, wrfile, **kwds) @classmethod def from_socket(cls, sock, **kwds): """ from_socket(sock, **kwds) -> WebSocketFile Wrap a socket in a WebSocketFile. Uses the makefile() method to obtain the file objects internally used. Keyword arguments are passed on to the constructor. """ ret = cls.from_file(sock.makefile('rwb'), **kwds) ret._socket = sock return ret @classmethod def from_file(cls, file, **kwds): """ from_file(file, **kwds) -> WebSocketFile Wrap a read-write file object. Keyword arguments are passed on to the constructor. """ return cls(file, file, **kwds) def __init__(self, rdfile, wrfile, server_side=False, subprotocol=None): """ __init__(rdfile, wrfile, server_side=False, subprotocol=None) -> None See the class docstring for details. """ self._rdfile = rdfile self._wrfile = wrfile self._socket = None self.server_side = server_side self.subprotocol = subprotocol self.close_wrapped = True self._rdlock = threading.RLock() self._wrlock = threading.RLock() factory = codecs.getincrementaldecoder('utf-8') self._decoder = factory(errors='strict') self._cur_opcode = None self._read_close = False self._written_close = False self._closed = False def _read_raw(self, length): """ _read_raw(length) -> bytes Read exactly length bytes from the underlying stream, and return them as a bytes object. Should be used for small amounts. Raises EOFError if less than length bytes are read. """ if not length: return b'' rf = self._rdfile buf, buflen = [], 0 while buflen < length: rd = rf.read(length - buflen) if not rd: raise EOFError() buf.append(rd) buflen += len(rd) return b''.join(buf) def _readinto_raw(self, buf, offset=0): """ _readinto_raw(buf, offset=0) -> buf Try to fill buf with exactly as many bytes as buf can hold. If buf is an integer, a bytearray object of that length is allocated and returned. If offset is nonzero, reading starts at that offset. Raises EOFError on failure. """ # Convert integers into byte arrays. if isinstance(buf, int): buf = bytearray(buf) # Don't fail on empty reads. if not buf: return buf # Main... try-except clause. rf, fl = self._rdfile, len(buf) try: # Try "native" readinto method. if not offset: l = rf.readinto(buf) if l == 0: # EOF raise EOFError() else: l = offset if l < len(buf): # Fill the rest. try: # Try still to use buf itself (indirectly). v, o = memoryview(buf), l while o < fl: rd = rf.readinto(v[o:]) if not rd: raise EOFError() o += rd except NameError: # Will have to read individual parts. o = l temp = bytearray(min(fl - o, BUFFER_SIZE)) while o < fl: if len(temp) > fl - o: temp = bytearray(fl - o) rd = rf.readinto(temp) if not rd: raise EOFError() no = o + rd buf[o:no] = temp o = no except AttributeError: # No readinto available, have to read chunks. o, fl = offset, len(buf) while o < fl: chunk = rf.read(min(fl - o, BUFFER_SIZE)) if not chunk: raise EOFError() no = o + len(chunk) buf[o:no] = chunk o = no return buf def _write_raw(self, data): """ _write_raw(data) -> None Write data to the underlying stream. May or may be not buffered. """ self._wrfile.write(data) def _flush_raw(self): """ _flush_raw() -> None Force any buffered output data to be written out. """ self._wrfile.flush() def _shutdown_raw(self, mode): """ _shutdown_raw(mode) -> None Perform a shutdown of the underlying socket, if any. mode is a socket.SHUT_* constant denoting the precise mode of shutdown. """ s = self._socket if s: try: s.shutdown(mode) except socket.error: pass def read_single_frame(self): """ read_single_frame() -> (opcode, payload, final, type) or None Read (and parse) a single WebSocket frame. opcode is the opcode of the frame, as an integer; payload is the payload of the frame, text data is *not* decoded; final is a boolean indicating whether this frame was final, type is the same as opcode for non-continuation frames, and the opcode of the frame continued for continuation frames. The return value is a named tuple, with the fields named as indicated. If EOF is reached (not in the middle of the frame), None is returned. MAXFRAME is applied. May raise ProtocolError (via error()) if the data received is invalid, is truncated, an invalid (non-)continuation frame is read, EOF inside an unfinished fragmented frame is encountered, etc. WARNING: If a control frame is received (i.e. whose opcode bitwise-AND OPMASK_CONTROL is nonzero), it must be passed into the handle_control() method; otherwise. the implementation may misbehave. """ with self._rdlock: # Store for later. was_read_close = self._read_close # No more reading after close. if was_read_close: return None # Read opcode byte. A EOF here is non-fatal. header = bytearray(2) try: header[0] = ord(self._read_raw(1)) except EOFError: if self._cur_opcode is not None: self._error('Unfinished fragmented frame') return None # ...And EOF from here on, on the other hand, is. try: # Read the length byte. header[1] = ord(self._read_raw(1)) # Extract header fields. final = header[0] & constants.FLAG_FIN reserved = header[0] & constants.MASK_RSV opcode = header[0] & constants.MASK_OPCODE masked = header[1] & constants.FLAG_MASK length = header[1] & constants.MASK_LENGTH # Verify them. if reserved: self._error('Frame with reserved flags received') if bool(self.server_side) ^ bool(masked): self._error('Frame with invalid masking received') if opcode & constants.OPMASK_CONTROL and not final: self._error('Fragmented control frame received') # (Fragmented) Message type. msgtype = opcode # Validate fragmentation state. if not opcode & constants.OPMASK_CONTROL: # Control frames may pass freely, non-control ones # interact with the state. if opcode == constants.OP_CONT: # Continuation frame. msgtype = self._cur_opcode if self._cur_opcode is None: # See the error message. self._error('Orphaned continuation frame') elif final: # Finishing fragmented frame. self._cur_opcode = None # "Normal" continuation frame passed. else: # "Header" frame. if self._cur_opcode is not None: # Already inside fragmented frame. self._error('Fragmented frame interrupted') elif not final: # Fragmented frame started. self._cur_opcode = opcode # Self-contained frame passed -- no action. # Extract length and mask value; start reading payload # buffer. masklen = (4 if masked else 0) if length < 126: # Just read the mask if necessary. msk = self._readinto_raw(masklen) elif length == 126: buf = self._readinto_raw(2 + masklen) length = struct.unpack('!H', buf[:2])[0] # Validate length if length < 126: self._error('Invalid frame length encoding') if masked: msk = buf[2:6] elif length == 127: buf = self._readinto_raw(8 + masklen) length = struct.unpack('!Q', buf[:8])[0] # Validate length. if length < 65536: self._error('Invalid frame length encoding') elif length >= 9223372036854775808: # 2 ** 63 # MUST in RFC 6455, section 5.2 # We could handle those frames easily (given we have # enough memory), though. self._error('Frame too long') if masked: msk = buf[8:12] # Validate length. if self.MAXFRAME is not None and length > self.MAXFRAME: self.error('Frame too long', code=constants.CLOSE_MESSAGE_TOO_BIG) # Allocate result buffer. rbuf = bytearray(length) # Read rest of message. self._readinto_raw(rbuf) # Verify this is not a post-close frame. if was_read_close: self._error('Received frame after closing one') # Reverse masking if necessary. if masked: rbuf = mask(msk, rbuf) # Done! return Frame(opcode, bytes(rbuf), bool(final), msgtype) except EOFError: self._error('Truncated frame') def read_frame(self, stream=False): """ read_frame(stream=False) -> (msgtype, content, final) or None Read a WebSocket data frame. The return value is composed from fields of the same meaning as from read_single_frame(). Note that the opcode field is discarded in favor of msgtype. The return value is (as in read_single_frame()), a named tuple, with the field names as indicated. If the stream encounters an EOF, returns None. If stream is false, fragmented frames are re-combined into a single frame (MAXCONTFRAME is applied), otherwise, they are returned individually. If the beginning of a fragmented frame was already consumed, the remainder of it (or one frame of the remainder, depending on stream) is read. May raise ProtocolError (if read_single_frame() does), or InvalidDataError, if decoding a text frame fails. NOTE: The data returned may not correspond entirely to the payload of the underlying frame, if the latter contains incomplete UTF-8 sequences. """ buf, buflen = [], 0 with self._rdlock: while 1: # Read frame. fr = self.read_single_frame() # EOF reached. Assuming state is clean. if not fr: return None # Process control frames as quickly as possible. if fr.opcode & constants.OPMASK_CONTROL: self.handle_control(fr.opcode, fr.payload) continue # Decode text frames. if fr.msgtype == constants.OP_TEXT: try: payload = self._decoder.decode(fr.payload, fr.final) except ValueError: raise InvalidDataError('Invalid message payload') else: payload = fr.payload # Enforce MAXCONTFRAME if (self.MAXCONTFRAME is not None and buflen + len(payload) > self.MAXCONTFRAME): self.error('Fragmented frame too long', code=constants.CLOSE_MESSAGE_TOO_BIG) # Prepare value for returning. datum = Message(fr.msgtype, payload, fr.final) # Regard streaming mode. if stream: return datum # Accumulate non-final frames. buf.append(datum.content) buflen += len(datum.content) # Stop if final message encountered. if datum.final: if datum.msgtype == constants.OP_TEXT: base = unicode() else: base = bytes() return Message(datum.msgtype, base.join(buf), True) def handle_control(self, opcode, cnt): """ handle_control(opcode, cnt) -> bool Handle a control frame. Called by read_frame() if a control frame is read, to evoke a required response "as soon as practical". The return value tells whether it is safe to continue reading (true), or if EOF (i.e. a close frame) was reached (false). """ if opcode == constants.OP_PING: self.write_single_frame(constants.OP_PONG, cnt) elif opcode == constants.OP_CLOSE: self._read_close = True self._shutdown_raw(socket.SHUT_RD) self.close_ex(*self.parse_close(cnt)) return False return True def _error(self, message): "Used internally." self.error(message) # Assure execution does not continue. raise RuntimeError('error() returned') def error(self, message, code=constants.CLOSE_PROTOCOL_FAILURE): """ error(message, code=CLOSE_PROTOCOL_FAILURE) -> [ProtocolError] Initiate an abnormal connection close and raise a ProtocolError. code is the error code to use. This method is called from read_single_frame() if an invalid frame is detected. """ # We will hardly be able to interpret anything the other side emits # at this point. self._read_close = True self.close_ex(code, message) raise ProtocolError(message, code=code) def write_single_frame(self, opcode, data, final=True, maskkey=None): """ write_single_frame(opcode, data, final=True, maskkey=None) -> None Write a frame with the given parameters. final determines whether the frame is final; opcode is one of the OP_* constants; data is the payload of the message. maskkey, if not None, is a length-four byte sequence that determines which mask key to use, otherwise, tools.new_mask() will be invoked to create one if necessary. If opcode is OP_TEXT, data may be a Unicode or a byte string, otherwise, data must be a byte string. If the type of data is inappropriate, TypeError is raised. Raises ConnectionClosedError is the connection is already closed or closing. """ # Validate arguments. if not constants.OP_MIN <= opcode <= constants.OP_MAX: raise ValueError('Opcode out of range') if isinstance(data, unicode): if opcode != constants.OP_TEXT: raise TypeError('Unicode payload specfied for ' 'non-Unicode opcode') data = data.encode('utf-8') elif not isinstance(data, (bytes, bytearray)): raise TypeError('Invalid data type') # Allocate new mask if necessary; validate type. masked = (not self.server_side) if masked: if maskkey is None: maskkey = new_mask() elif isinstance(maskkey, bytes): maskkey = bytearray(maskkey) else: maskkey = None # Construct message header. header = bytearray(2) if final: header[0] |= constants.FLAG_FIN if masked: header[1] |= constants.FLAG_MASK header[0] |= opcode # Insert message length. if len(data) < 126: header[1] |= len(data) elif len(data) < 65536: header[1] |= 126 header.extend(struct.pack('!H', len(data))) elif len(data) < 9223372036854775808: # 2 ** 63 header[1] |= 127 header.extend(struct.pack('!Q', len(data))) else: # WTF? raise ValueError('Frame too long') # Masking. if masked: # Add key to header. header.extend(maskkey) # Actually mask data. data = mask(maskkey, bytearray(data)) # Drain all that onto the wire. with self._wrlock: if self._written_close: raise ConnectionClosedError( 'Trying to write data after close()') self._write_raw(header) self._write_raw(data) self._flush_raw() def write_frame(self, opcode, data): """ write_frame(opcode, data) -> None Write a complete data frame with given opcode and data. Arguments are validated. May raise exceptions as write_single_frame() does. """ if opcode & constants.OPMASK_CONTROL or opcode == constants.OP_CONT: raise ValueError('Trying to write non-data frame') self.write_single_frame(opcode, data) def write_text_frame(self, data): """ write_text_frame(data) -> None Write an OP_TEXT frame with given data, which must be a Unicode string. """ if not isinstance(data, unicode): raise TypeError('Invalid data') return self.write_frame(constants.OP_TEXT, data) def write_binary_frame(self, data): """ write_binary_frame(data) -> None Write an OP_BINARY frame with given data. """ return self.write_frame(constants.OP_BINARY, data) def close_now(self, force=False): """ close_now(force=False) -> None Close the underlying files immediately. If force is true, they are closed unconditionally, otherwise only if the close_wrapped attribute is true. This does not perform a proper closing handshake and should be avoided in favor of close(). """ # Waiting for locks contradicts the "now!" intention, so none of that # here. self._read_close = True self._written_close = True self._closed = True if force or self.close_wrapped: self._shutdown_raw(socket.SHUT_RDWR) try: self._rdfile.close() except IOError: pass try: self._wrfile.close() except IOError: pass if self._socket: try: self._socket.close() except socket.error: pass def close_ex(self, code=None, message=None, wait=True): """ close_ex(code=None, message=None, wait=True) -> None Close the underlying connection, delivering the code and message (if given) to the other point. If code is None, message is ignored. If message is a Unicode string, it is encoded using UTF-8. If wait is true, this will read frames from self and discard them until the other side acknowledges the close; as this may cause data loss, be careful. The default is to ensure the WebSocket is fully closed when the call finishes; when closing a WebSocket that is read from in a different thread, specify wait=False and let the other thread consume any remaining input. If the connection is already closed, the method has no effect (but might raise an exception if encoding code or message fails). """ # Construct payload. payload = bytearray() if code is not None: # Add code. payload.extend(struct.pack('!H', code)) # Add message. if message is None: pass elif isinstance(message, unicode): payload.extend(message.encode('utf-8')) else: payload.extend(message) with self._wrlock: # Already closed? if self._written_close: # Close underlying streams if necessary. if self._read_close: if not self._closed: self.close_now() wait = False else: # Write close frame. self.write_single_frame(constants.OP_CLOSE, payload) # Close frame written. self._written_close = True self._shutdown_raw(socket.SHUT_WR) # Wait for close if desired. if wait: with self._rdlock: while self.read_frame(True): pass self.close_ex(wait=False) def close(self, message=None, wait=True): """ close(message=None, wait=True) -> None Close the underlying connection with a code of CLOSE_NORMAL and the (optional) given message. If wait is true, this will read frames from self until the other side acknowledges the close; as this may cause data loss, be careful. """ self.close_ex(constants.CLOSE_NORMAL, message, wait) def parse_close(self, content): """ parse_close(content) -> (code, message) Parse the given content as the payload of a OP_CLOSE frame, and return the error code (as an unsigned integer) and the error payload (as a bytes object). If content is empty, the tuple (None, None) is returned, to aid round-tripping into close(). Raises InvalidDataError if the content has a length of 1. """ if not content: return (None, None) elif len(content) == 1: raise InvalidDataError('Invalid close frame payload') else: return (struct.unpack('!H', content[:2])[0], content[2:]) def wrap(*args, **kwds): """ wrap(file1[, file2], **kwds) -> WebSocket Try to wrap file1 and (if given) file2 into a WebSocket. Convenience method for static factory methods: If both file1 and file2 are given, they are passed to from_files(); if otherwise file1 has recv and send attributes, it is passed to from_socket(), otherwise, it is passed to from_file(). """ if len(args) == 0: raise TypeError('Cannot wrap nothing') elif len(args) == 1: f = args[0] if hasattr(f, 'recv') and hasattr(f, 'send'): return WebSocketFile.from_socket(f, **kwds) else: return WebSocketFile.from_file(f, **kwds) elif len(args) == 2: return WebSocketFile.from_files(args[0], args[1], **kwds) else: raise TypeError('Too many arguments')
40.935218
78
0.567388
# websocket_server -- WebSocket/HTTP server/client library # https://github.com/CylonicRaider/websocket-server """ WebSocket protocol implementation. client_handshake() and server_handshake() perform the appropriate operations on mappings of HTTP headers; the WebSocketFile class implements the framing protocol. """ import os import socket import struct import base64 import codecs import threading import hashlib from collections import namedtuple from . import constants from .compat import bytearray, bytes, tobytes, unicode, callable from .exceptions import ProtocolError, InvalidDataError from .exceptions import ConnectionClosedError from .tools import mask, new_mask __all__ = ['client_handshake', 'WebSocketFile', 'wrap'] # Allocation unit. BUFFER_SIZE = 16384 # Frame class Frame = namedtuple('Frame', 'opcode payload final msgtype') # Message class Message = namedtuple('Message', 'msgtype content final') # Adapted from RFC 6455: # 0 1 2 3 # 0 1 2 3 4 5 6 7 0 1 2 3 4 5 6 7 0 1 2 3 4 5 6 7 0 1 2 3 4 5 6 7 # +-+-+-+-+-------+-+-------------+-------------------------------+ # |F|R|R|R| opcode|M| Payload len | Extended payload length | # |I|S|S|S| (4) |A| (7) | (16/64) | # |N|V|V|V| |S| | (if payload len==126/127) | # | |1|2|3| |K| | | # +-+-+-+-+-------+-+-------------+ - - - - - - - - - - - - - - - + # | Extended payload length continued, if payload len == 127 | # + - - - - - - - - - - - - - - - +-------------------------------+ # | |Masking-key, if MASK set to 1 | # +-------------------------------+-------------------------------+ # | Masking-key (continued) | Payload Data | # +-------------------------------+ - - - - - - - - - - - - - - - + # : Payload Data continued ... : # + - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - + # | Payload Data continued ... | # +---------------------------------------------------------------+ # The "magic" GUID used for Sec-WebSocket-Accept. MAGIC_GUID = unicode('258EAFA5-E914-47DA-95CA-C5AB0DC85B11') def process_key(key): """ process_key(key) -> unicode Transform the given key as required to form a Sec-WebSocket-Accept field, and return the new key. """ enc_key = (unicode(key) + MAGIC_GUID).encode('ascii') resp_key = base64.b64encode(hashlib.sha1(enc_key).digest()) return resp_key.decode('ascii') def client_handshake(headers, protos=None, makekey=None): """ client_handshake(headers, protos=None, makekey=None) -> function Perform the client-side parts of a WebSocket handshake. headers is a mapping from header names to header values (both Unicode strings) which is modified in-place with WebSocket headers. protos is one of: - None to not advertise subprotocols, - A single string used directly as the Sec-WebSocket-Protocol header, - A list of strings, which are joined by commata into the value of the Sec-WebSocket-Protocol header. NOTE that the value of protos is not validated. makekey, if not None, is a function that returns a byte string of length 16 that is used as the base of the Sec-WebSocket-Key header. If makekey is None, os.urandom() is used. The return value is a function that takes the response headers (in the same format as headers) as the only parameter and raises a ProtocolError if the handshake is not successful. If the handshake *is* successful, the function returns the subprotocol selected by the server (a string that must have been present in protos), or None (for no subprotocol). NOTE that this library does not support extensions. For future compatibility, it would be prudent to specify makekey, if at all, as a keyword argument. """ def check_response(respheaders): "Ensure the given HTTP response headers are a valid WS handshake." # Verify key and other fields. if respheaders.get('Sec-WebSocket-Accept') != process_key(key): raise ProtocolError('Invalid response key') if respheaders.get('Sec-WebSocket-Extensions'): raise ProtocolError('Extensions not supported') p = respheaders.get('Sec-WebSocket-Protocol') # If protos is None, using the "in" operator may fail. if p and (not protos or p not in protos): raise ProtocolError('Invalid subprotocol received') return p if makekey is None: makekey = lambda: os.urandom(16) headers.update({'Connection': 'Upgrade', 'Upgrade': 'websocket', 'Sec-WebSocket-Version': '13'}) if isinstance(protos, str): headers['Sec-WebSocket-Protocol'] = protos elif protos is not None: headers['Sec-WebSocket-Protocol'] = ', '.join(protos) key = base64.b64encode(makekey()).decode('ascii') headers['Sec-WebSocket-Key'] = key return check_response def server_handshake(headers, protos=None): """ server_handshake(headers, protos=None) -> dict Perform the server-side part of a WebSocket handshake. headers is a maping from header names to header values (both Unicode strings), which is validated. protos is one of: - None to indicate no subprotocols, - A sequence or whitespace-delimited string of names of accepted subprotocols (the first subprotocol proposed by the client that is in the list is selected), - A function taking the list of subprotocols proposed by the client as the only argument and returning a subprotocol name or None. The return value is a mapping of headers to be included in the response. """ def error(msg): raise ProtocolError('Invalid handshake: %s' % msg) # The standard requires a Host header... why not... if 'Host' not in headers: error('Missing Host header') # Validate Upgrade header. if 'websocket' not in headers.get('Upgrade', '').lower(): error('Invalid/Missing Upgrade header') # Validate protocol version. if headers.get('Sec-WebSocket-Version') != '13': error('Invalid WebSocket version (!= 13)') # Validate Connection header. connection = [i.lower().strip() for i in headers.get('Connection', '').split(',')] if 'upgrade' not in connection: error('Invalid/Missing Connection header') # Validate the key. key = headers.get('Sec-WebSocket-Key') try: if len(base64.b64decode(tobytes(key))) != 16: error('Invalid WebSocket key length') except (TypeError, ValueError): error('Invalid WebSocket key') # Extensions are not supported. # Be permissive with subprotocol tokens. protstr = headers.get('Sec-WebSocket-Protocol', '') protlist = ([i.strip() for i in protstr.split(',')] if protstr else []) if protos is None: respproto = None elif callable(protos): respproto = protos(protlist) else: if isinstance(protos, str): protos = protos.split() # Intentionally leaking loop variable. for respproto in protlist: if respproto in protos: break else: respproto = None # Prepare response headers. ret = {'Connection': 'upgrade', 'Upgrade': 'websocket', 'Sec-WebSocket-Accept': process_key(key)} if respproto is not None: ret['Sec-WebSocket-Protocol'] = respproto return ret class WebSocketFile(object): """ WebSocket protocol implementation. May base on a pair of file-like objects (for usage in HTTPRequestHandler's); a "raw" socket (if you prefer parsing HTTP headers yourself); or a single file object (if you have got such a read-write one). This class is not concerned with the handshake; see client_handshake() and server_handshake() for that. WebSocketFile(rdfile, wrfile, server_side=False, subprotocol=None) rdfile : File to perform reading operations on. wrfile : File to perform writing operations on. server_side: Whether to engage server-side behavior (if true) or not (otherwise). subprotocol: The subprotocol to be used. Attributes: server_side : Whether this is a server-side WebSocketFile. subprotocol : The subprotocol as passed to the constructor. close_wrapped: Whether calling close() should close the underlying files as well. Defaults to True. _rdlock : threading.RLock instance used for serializing and protecting reading-related operations. _wrlock : threading.RLock instance user for serializing and protecting write-related operations. _rdlock should always be asserted before _wrlock, if at all; generally, do not call reading-related methods (which also include close*()) with _wrlock asserted, and do not use those locks unless necessary. _socket : Underlying socket (set by from_socket()). May not be present at all (i.e. be None). Only use this if you are really sure you need to. Class attributes: MAXFRAME : Maximum frame payload length. May be overridden by subclasses (or instances). Value is either an integer or None (indicating no limit). This is not enforced for outgoing messages. MAXCONTFRAME: Maximum length of a frame reconstructed from fragments. May be overridden as well. The value has the same semantics as the one of MAXFRAME. This is not enforced for outgoing messages as well. NOTE: This class reads exactly the amount of bytes needed, yet buffering of the underlying stream may cause frames to "congest". The underlying stream must be blocking, or unpredictable behavior occurs. """ # Maximum allowed frame length. MAXFRAME = None # Maximum continued frame length. MAXCONTFRAME = None @classmethod def from_files(cls, rdfile, wrfile, **kwds): """ from_files(rdfile, wrfile, **kwds) -> WebSocketFile Equivalent to the constructor; provided for symmetry. """ return cls(rdfile, wrfile, **kwds) @classmethod def from_socket(cls, sock, **kwds): """ from_socket(sock, **kwds) -> WebSocketFile Wrap a socket in a WebSocketFile. Uses the makefile() method to obtain the file objects internally used. Keyword arguments are passed on to the constructor. """ ret = cls.from_file(sock.makefile('rwb'), **kwds) ret._socket = sock return ret @classmethod def from_file(cls, file, **kwds): """ from_file(file, **kwds) -> WebSocketFile Wrap a read-write file object. Keyword arguments are passed on to the constructor. """ return cls(file, file, **kwds) def __init__(self, rdfile, wrfile, server_side=False, subprotocol=None): """ __init__(rdfile, wrfile, server_side=False, subprotocol=None) -> None See the class docstring for details. """ self._rdfile = rdfile self._wrfile = wrfile self._socket = None self.server_side = server_side self.subprotocol = subprotocol self.close_wrapped = True self._rdlock = threading.RLock() self._wrlock = threading.RLock() factory = codecs.getincrementaldecoder('utf-8') self._decoder = factory(errors='strict') self._cur_opcode = None self._read_close = False self._written_close = False self._closed = False def _read_raw(self, length): """ _read_raw(length) -> bytes Read exactly length bytes from the underlying stream, and return them as a bytes object. Should be used for small amounts. Raises EOFError if less than length bytes are read. """ if not length: return b'' rf = self._rdfile buf, buflen = [], 0 while buflen < length: rd = rf.read(length - buflen) if not rd: raise EOFError() buf.append(rd) buflen += len(rd) return b''.join(buf) def _readinto_raw(self, buf, offset=0): """ _readinto_raw(buf, offset=0) -> buf Try to fill buf with exactly as many bytes as buf can hold. If buf is an integer, a bytearray object of that length is allocated and returned. If offset is nonzero, reading starts at that offset. Raises EOFError on failure. """ # Convert integers into byte arrays. if isinstance(buf, int): buf = bytearray(buf) # Don't fail on empty reads. if not buf: return buf # Main... try-except clause. rf, fl = self._rdfile, len(buf) try: # Try "native" readinto method. if not offset: l = rf.readinto(buf) if l == 0: # EOF raise EOFError() else: l = offset if l < len(buf): # Fill the rest. try: # Try still to use buf itself (indirectly). v, o = memoryview(buf), l while o < fl: rd = rf.readinto(v[o:]) if not rd: raise EOFError() o += rd except NameError: # Will have to read individual parts. o = l temp = bytearray(min(fl - o, BUFFER_SIZE)) while o < fl: if len(temp) > fl - o: temp = bytearray(fl - o) rd = rf.readinto(temp) if not rd: raise EOFError() no = o + rd buf[o:no] = temp o = no except AttributeError: # No readinto available, have to read chunks. o, fl = offset, len(buf) while o < fl: chunk = rf.read(min(fl - o, BUFFER_SIZE)) if not chunk: raise EOFError() no = o + len(chunk) buf[o:no] = chunk o = no return buf def _write_raw(self, data): """ _write_raw(data) -> None Write data to the underlying stream. May or may be not buffered. """ self._wrfile.write(data) def _flush_raw(self): """ _flush_raw() -> None Force any buffered output data to be written out. """ self._wrfile.flush() def _shutdown_raw(self, mode): """ _shutdown_raw(mode) -> None Perform a shutdown of the underlying socket, if any. mode is a socket.SHUT_* constant denoting the precise mode of shutdown. """ s = self._socket if s: try: s.shutdown(mode) except socket.error: pass def read_single_frame(self): """ read_single_frame() -> (opcode, payload, final, type) or None Read (and parse) a single WebSocket frame. opcode is the opcode of the frame, as an integer; payload is the payload of the frame, text data is *not* decoded; final is a boolean indicating whether this frame was final, type is the same as opcode for non-continuation frames, and the opcode of the frame continued for continuation frames. The return value is a named tuple, with the fields named as indicated. If EOF is reached (not in the middle of the frame), None is returned. MAXFRAME is applied. May raise ProtocolError (via error()) if the data received is invalid, is truncated, an invalid (non-)continuation frame is read, EOF inside an unfinished fragmented frame is encountered, etc. WARNING: If a control frame is received (i.e. whose opcode bitwise-AND OPMASK_CONTROL is nonzero), it must be passed into the handle_control() method; otherwise. the implementation may misbehave. """ with self._rdlock: # Store for later. was_read_close = self._read_close # No more reading after close. if was_read_close: return None # Read opcode byte. A EOF here is non-fatal. header = bytearray(2) try: header[0] = ord(self._read_raw(1)) except EOFError: if self._cur_opcode is not None: self._error('Unfinished fragmented frame') return None # ...And EOF from here on, on the other hand, is. try: # Read the length byte. header[1] = ord(self._read_raw(1)) # Extract header fields. final = header[0] & constants.FLAG_FIN reserved = header[0] & constants.MASK_RSV opcode = header[0] & constants.MASK_OPCODE masked = header[1] & constants.FLAG_MASK length = header[1] & constants.MASK_LENGTH # Verify them. if reserved: self._error('Frame with reserved flags received') if bool(self.server_side) ^ bool(masked): self._error('Frame with invalid masking received') if opcode & constants.OPMASK_CONTROL and not final: self._error('Fragmented control frame received') # (Fragmented) Message type. msgtype = opcode # Validate fragmentation state. if not opcode & constants.OPMASK_CONTROL: # Control frames may pass freely, non-control ones # interact with the state. if opcode == constants.OP_CONT: # Continuation frame. msgtype = self._cur_opcode if self._cur_opcode is None: # See the error message. self._error('Orphaned continuation frame') elif final: # Finishing fragmented frame. self._cur_opcode = None # "Normal" continuation frame passed. else: # "Header" frame. if self._cur_opcode is not None: # Already inside fragmented frame. self._error('Fragmented frame interrupted') elif not final: # Fragmented frame started. self._cur_opcode = opcode # Self-contained frame passed -- no action. # Extract length and mask value; start reading payload # buffer. masklen = (4 if masked else 0) if length < 126: # Just read the mask if necessary. msk = self._readinto_raw(masklen) elif length == 126: buf = self._readinto_raw(2 + masklen) length = struct.unpack('!H', buf[:2])[0] # Validate length if length < 126: self._error('Invalid frame length encoding') if masked: msk = buf[2:6] elif length == 127: buf = self._readinto_raw(8 + masklen) length = struct.unpack('!Q', buf[:8])[0] # Validate length. if length < 65536: self._error('Invalid frame length encoding') elif length >= 9223372036854775808: # 2 ** 63 # MUST in RFC 6455, section 5.2 # We could handle those frames easily (given we have # enough memory), though. self._error('Frame too long') if masked: msk = buf[8:12] # Validate length. if self.MAXFRAME is not None and length > self.MAXFRAME: self.error('Frame too long', code=constants.CLOSE_MESSAGE_TOO_BIG) # Allocate result buffer. rbuf = bytearray(length) # Read rest of message. self._readinto_raw(rbuf) # Verify this is not a post-close frame. if was_read_close: self._error('Received frame after closing one') # Reverse masking if necessary. if masked: rbuf = mask(msk, rbuf) # Done! return Frame(opcode, bytes(rbuf), bool(final), msgtype) except EOFError: self._error('Truncated frame') def read_frame(self, stream=False): """ read_frame(stream=False) -> (msgtype, content, final) or None Read a WebSocket data frame. The return value is composed from fields of the same meaning as from read_single_frame(). Note that the opcode field is discarded in favor of msgtype. The return value is (as in read_single_frame()), a named tuple, with the field names as indicated. If the stream encounters an EOF, returns None. If stream is false, fragmented frames are re-combined into a single frame (MAXCONTFRAME is applied), otherwise, they are returned individually. If the beginning of a fragmented frame was already consumed, the remainder of it (or one frame of the remainder, depending on stream) is read. May raise ProtocolError (if read_single_frame() does), or InvalidDataError, if decoding a text frame fails. NOTE: The data returned may not correspond entirely to the payload of the underlying frame, if the latter contains incomplete UTF-8 sequences. """ buf, buflen = [], 0 with self._rdlock: while 1: # Read frame. fr = self.read_single_frame() # EOF reached. Assuming state is clean. if not fr: return None # Process control frames as quickly as possible. if fr.opcode & constants.OPMASK_CONTROL: self.handle_control(fr.opcode, fr.payload) continue # Decode text frames. if fr.msgtype == constants.OP_TEXT: try: payload = self._decoder.decode(fr.payload, fr.final) except ValueError: raise InvalidDataError('Invalid message payload') else: payload = fr.payload # Enforce MAXCONTFRAME if (self.MAXCONTFRAME is not None and buflen + len(payload) > self.MAXCONTFRAME): self.error('Fragmented frame too long', code=constants.CLOSE_MESSAGE_TOO_BIG) # Prepare value for returning. datum = Message(fr.msgtype, payload, fr.final) # Regard streaming mode. if stream: return datum # Accumulate non-final frames. buf.append(datum.content) buflen += len(datum.content) # Stop if final message encountered. if datum.final: if datum.msgtype == constants.OP_TEXT: base = unicode() else: base = bytes() return Message(datum.msgtype, base.join(buf), True) def handle_control(self, opcode, cnt): """ handle_control(opcode, cnt) -> bool Handle a control frame. Called by read_frame() if a control frame is read, to evoke a required response "as soon as practical". The return value tells whether it is safe to continue reading (true), or if EOF (i.e. a close frame) was reached (false). """ if opcode == constants.OP_PING: self.write_single_frame(constants.OP_PONG, cnt) elif opcode == constants.OP_CLOSE: self._read_close = True self._shutdown_raw(socket.SHUT_RD) self.close_ex(*self.parse_close(cnt)) return False return True def _error(self, message): "Used internally." self.error(message) # Assure execution does not continue. raise RuntimeError('error() returned') def error(self, message, code=constants.CLOSE_PROTOCOL_FAILURE): """ error(message, code=CLOSE_PROTOCOL_FAILURE) -> [ProtocolError] Initiate an abnormal connection close and raise a ProtocolError. code is the error code to use. This method is called from read_single_frame() if an invalid frame is detected. """ # We will hardly be able to interpret anything the other side emits # at this point. self._read_close = True self.close_ex(code, message) raise ProtocolError(message, code=code) def write_single_frame(self, opcode, data, final=True, maskkey=None): """ write_single_frame(opcode, data, final=True, maskkey=None) -> None Write a frame with the given parameters. final determines whether the frame is final; opcode is one of the OP_* constants; data is the payload of the message. maskkey, if not None, is a length-four byte sequence that determines which mask key to use, otherwise, tools.new_mask() will be invoked to create one if necessary. If opcode is OP_TEXT, data may be a Unicode or a byte string, otherwise, data must be a byte string. If the type of data is inappropriate, TypeError is raised. Raises ConnectionClosedError is the connection is already closed or closing. """ # Validate arguments. if not constants.OP_MIN <= opcode <= constants.OP_MAX: raise ValueError('Opcode out of range') if isinstance(data, unicode): if opcode != constants.OP_TEXT: raise TypeError('Unicode payload specfied for ' 'non-Unicode opcode') data = data.encode('utf-8') elif not isinstance(data, (bytes, bytearray)): raise TypeError('Invalid data type') # Allocate new mask if necessary; validate type. masked = (not self.server_side) if masked: if maskkey is None: maskkey = new_mask() elif isinstance(maskkey, bytes): maskkey = bytearray(maskkey) else: maskkey = None # Construct message header. header = bytearray(2) if final: header[0] |= constants.FLAG_FIN if masked: header[1] |= constants.FLAG_MASK header[0] |= opcode # Insert message length. if len(data) < 126: header[1] |= len(data) elif len(data) < 65536: header[1] |= 126 header.extend(struct.pack('!H', len(data))) elif len(data) < 9223372036854775808: # 2 ** 63 header[1] |= 127 header.extend(struct.pack('!Q', len(data))) else: # WTF? raise ValueError('Frame too long') # Masking. if masked: # Add key to header. header.extend(maskkey) # Actually mask data. data = mask(maskkey, bytearray(data)) # Drain all that onto the wire. with self._wrlock: if self._written_close: raise ConnectionClosedError( 'Trying to write data after close()') self._write_raw(header) self._write_raw(data) self._flush_raw() def write_frame(self, opcode, data): """ write_frame(opcode, data) -> None Write a complete data frame with given opcode and data. Arguments are validated. May raise exceptions as write_single_frame() does. """ if opcode & constants.OPMASK_CONTROL or opcode == constants.OP_CONT: raise ValueError('Trying to write non-data frame') self.write_single_frame(opcode, data) def write_text_frame(self, data): """ write_text_frame(data) -> None Write an OP_TEXT frame with given data, which must be a Unicode string. """ if not isinstance(data, unicode): raise TypeError('Invalid data') return self.write_frame(constants.OP_TEXT, data) def write_binary_frame(self, data): """ write_binary_frame(data) -> None Write an OP_BINARY frame with given data. """ return self.write_frame(constants.OP_BINARY, data) def close_now(self, force=False): """ close_now(force=False) -> None Close the underlying files immediately. If force is true, they are closed unconditionally, otherwise only if the close_wrapped attribute is true. This does not perform a proper closing handshake and should be avoided in favor of close(). """ # Waiting for locks contradicts the "now!" intention, so none of that # here. self._read_close = True self._written_close = True self._closed = True if force or self.close_wrapped: self._shutdown_raw(socket.SHUT_RDWR) try: self._rdfile.close() except IOError: pass try: self._wrfile.close() except IOError: pass if self._socket: try: self._socket.close() except socket.error: pass def close_ex(self, code=None, message=None, wait=True): """ close_ex(code=None, message=None, wait=True) -> None Close the underlying connection, delivering the code and message (if given) to the other point. If code is None, message is ignored. If message is a Unicode string, it is encoded using UTF-8. If wait is true, this will read frames from self and discard them until the other side acknowledges the close; as this may cause data loss, be careful. The default is to ensure the WebSocket is fully closed when the call finishes; when closing a WebSocket that is read from in a different thread, specify wait=False and let the other thread consume any remaining input. If the connection is already closed, the method has no effect (but might raise an exception if encoding code or message fails). """ # Construct payload. payload = bytearray() if code is not None: # Add code. payload.extend(struct.pack('!H', code)) # Add message. if message is None: pass elif isinstance(message, unicode): payload.extend(message.encode('utf-8')) else: payload.extend(message) with self._wrlock: # Already closed? if self._written_close: # Close underlying streams if necessary. if self._read_close: if not self._closed: self.close_now() wait = False else: # Write close frame. self.write_single_frame(constants.OP_CLOSE, payload) # Close frame written. self._written_close = True self._shutdown_raw(socket.SHUT_WR) # Wait for close if desired. if wait: with self._rdlock: while self.read_frame(True): pass self.close_ex(wait=False) def close(self, message=None, wait=True): """ close(message=None, wait=True) -> None Close the underlying connection with a code of CLOSE_NORMAL and the (optional) given message. If wait is true, this will read frames from self until the other side acknowledges the close; as this may cause data loss, be careful. """ self.close_ex(constants.CLOSE_NORMAL, message, wait) def parse_close(self, content): """ parse_close(content) -> (code, message) Parse the given content as the payload of a OP_CLOSE frame, and return the error code (as an unsigned integer) and the error payload (as a bytes object). If content is empty, the tuple (None, None) is returned, to aid round-tripping into close(). Raises InvalidDataError if the content has a length of 1. """ if not content: return (None, None) elif len(content) == 1: raise InvalidDataError('Invalid close frame payload') else: return (struct.unpack('!H', content[:2])[0], content[2:]) def wrap(*args, **kwds): """ wrap(file1[, file2], **kwds) -> WebSocket Try to wrap file1 and (if given) file2 into a WebSocket. Convenience method for static factory methods: If both file1 and file2 are given, they are passed to from_files(); if otherwise file1 has recv and send attributes, it is passed to from_socket(), otherwise, it is passed to from_file(). """ if len(args) == 0: raise TypeError('Cannot wrap nothing') elif len(args) == 1: f = args[0] if hasattr(f, 'recv') and hasattr(f, 'send'): return WebSocketFile.from_socket(f, **kwds) else: return WebSocketFile.from_file(f, **kwds) elif len(args) == 2: return WebSocketFile.from_files(args[0], args[1], **kwds) else: raise TypeError('Too many arguments')
45
0
26
e32632230e8d861c619ce796ee13f65c84506eb5
1,908
py
Python
__main__.py
vprzybylo/ai2es
cd54222ca377e15dfada6436564e7f4ee942527c
[ "MIT" ]
null
null
null
__main__.py
vprzybylo/ai2es
cd54222ca377e15dfada6436564e7f4ee942527c
[ "MIT" ]
null
null
null
__main__.py
vprzybylo/ai2es
cd54222ca377e15dfada6436564e7f4ee942527c
[ "MIT" ]
null
null
null
import cocpit import cocpit.config as config # isort: split import os import time import pandas as pd import torch def build_model(): """ train ML models """ # loop through batch sizes, models, epochs, and/or folds for batch_size in config.BATCH_SIZE: print("BATCH SIZE: ", batch_size) for model_name in config.MODEL_NAMES: print("MODEL: ", model_name) for epochs in config.MAX_EPOCHS: print("MAX EPOCH: ", epochs) cocpit.setup_training.main( batch_size, model_name, epochs, ) def classification(): """ classify images using the ML model """ print("running ML model to classify ice...") start_time = time.time() # load ML model for predictions model = torch.load(config.MODEL_PATH) # load df of quality ice particles to make predictions on df = pd.read_csv(df_path) df = cocpit.run_model.main(df, model) # remove open_dir from run_model # df.to_csv(df_path, index=False) print("done classifying all images!") print("time to classify ice = %.2f seconds" % (time.time() - start_time)) if __name__ == "__main__": print( "num workers in loader = {}".format(config.NUM_WORKERS) ) if config.CLASSIFICATION or config.BUILD_MODEL else print( "num cpus for parallelization = {}".format(config.NUM_WORKERS) ) # only run one arbitrary year in loop if building model years = [2018] if config.BUILD_MODEL else [2018, 2019, 2020, 2021] for year in years: print("years: ", year) # create dir for final databases outname = f"{year}.parquet" df_path = os.path.join(config.FINAL_DIR, outname) if config.BUILD_MODEL: build_model() if config.CLASSIFICATION: classification()
26.136986
77
0.614256
import cocpit import cocpit.config as config # isort: split import os import time import pandas as pd import torch def build_model(): """ train ML models """ # loop through batch sizes, models, epochs, and/or folds for batch_size in config.BATCH_SIZE: print("BATCH SIZE: ", batch_size) for model_name in config.MODEL_NAMES: print("MODEL: ", model_name) for epochs in config.MAX_EPOCHS: print("MAX EPOCH: ", epochs) cocpit.setup_training.main( batch_size, model_name, epochs, ) def classification(): """ classify images using the ML model """ print("running ML model to classify ice...") start_time = time.time() # load ML model for predictions model = torch.load(config.MODEL_PATH) # load df of quality ice particles to make predictions on df = pd.read_csv(df_path) df = cocpit.run_model.main(df, model) # remove open_dir from run_model # df.to_csv(df_path, index=False) print("done classifying all images!") print("time to classify ice = %.2f seconds" % (time.time() - start_time)) if __name__ == "__main__": print( "num workers in loader = {}".format(config.NUM_WORKERS) ) if config.CLASSIFICATION or config.BUILD_MODEL else print( "num cpus for parallelization = {}".format(config.NUM_WORKERS) ) # only run one arbitrary year in loop if building model years = [2018] if config.BUILD_MODEL else [2018, 2019, 2020, 2021] for year in years: print("years: ", year) # create dir for final databases outname = f"{year}.parquet" df_path = os.path.join(config.FINAL_DIR, outname) if config.BUILD_MODEL: build_model() if config.CLASSIFICATION: classification()
0
0
0
cfa59b7e03a621229d3a7654d9a1137ae714d261
2,256
py
Python
20-fs-ias-lec/groups/Demo B/src/longFi/src/receiveEther.py
Kyrus1999/BACnet
5be8e1377252166041bcd0b066cce5b92b077d06
[ "MIT" ]
8
2020-03-17T21:12:18.000Z
2021-12-12T15:55:54.000Z
20-fs-ias-lec/groups/Demo B/src/longFi/src/receiveEther.py
Kyrus1999/BACnet
5be8e1377252166041bcd0b066cce5b92b077d06
[ "MIT" ]
2
2021-07-19T06:18:43.000Z
2022-02-10T12:17:58.000Z
20-fs-ias-lec/groups/Demo B/src/longFi/src/receiveEther.py
Kyrus1999/BACnet
5be8e1377252166041bcd0b066cce5b92b077d06
[ "MIT" ]
25
2020-03-20T09:32:45.000Z
2021-07-18T18:12:59.000Z
""" receiveEther.py Faris Ahmetasevic, Marco Banholzer, Nderim Shatri This code receives raw ethernet packets, which were sent to a network using the scapy library. """ from scapy.all import conf import struct """ This function returns the converted information of the packets. :param data: the bytes data which gets split up to get the mac-addresses and the protocol :type: bytes """ """ This function returns the converted MAC-addresses. :param bytes_addr: bytes which represent the mac-address :type: bytes """ """ This function returns the converted protocol. :param bytes_proto: bytes which represent the protocol :type: bytes """ """ The function filters the new sent packet with the protocol "0x7000" and prints the information. :param interface: name of the network interface, for instance 'en0', 'en1', ... :type: str :return: the payload of the ethernet packet :rtype: bytes """
27.512195
128
0.699911
""" receiveEther.py Faris Ahmetasevic, Marco Banholzer, Nderim Shatri This code receives raw ethernet packets, which were sent to a network using the scapy library. """ from scapy.all import conf import struct """ This function returns the converted information of the packets. :param data: the bytes data which gets split up to get the mac-addresses and the protocol :type: bytes """ def ethernet_frame(data): dest_mac, src_mac, proto = struct.unpack('!6s6s2s', data[:14]) return get_mac_addr(dest_mac), get_mac_addr(src_mac), get_protocol(proto), data[14:] """ This function returns the converted MAC-addresses. :param bytes_addr: bytes which represent the mac-address :type: bytes """ def get_mac_addr(bytes_addr): bytes_str = map('{:02x}'.format, bytes_addr) mac_address = ':'.join(bytes_str).upper() return mac_address """ This function returns the converted protocol. :param bytes_proto: bytes which represent the protocol :type: bytes """ def get_protocol(bytes_proto): bytes_str = map('{:02x}'.format, bytes_proto) protocol = ''.join(bytes_str).upper() return protocol """ The function filters the new sent packet with the protocol "0x7000" and prints the information. :param interface: name of the network interface, for instance 'en0', 'en1', ... :type: str :return: the payload of the ethernet packet :rtype: bytes """ def receive(interface): while True: sock = conf.L2socket(iface=interface) # scapy socket which connects to a network e.g "en0", "en1" pkt = bytes(sock.recv()) # the packets get read and converted to bytes if pkt[12:14] != b'\x70\x00': # only the packets with protocol "0x7000" get filtered continue dest_mac, src_mac, eth_proto, data = ethernet_frame(pkt) # calls the function to convert the information of the packets print('\nEthernet Frame:') print("Destination MAC: {}".format(dest_mac)) # prints the converted destination MAC-address print("Source MAC: {}".format(src_mac)) # prints the converted source MAC-address print("Protocol: {}".format(eth_proto)) # prints the converted protocol print("Packet: ", data) # prints the payout break return data
1,253
0
92
d527756039814af170d4be81d8e19538b9c99d78
3,033
py
Python
commands/text.py
Commodoreprime/Command-Block-Assembly
b54c2afee3ea7bdfddfe619b9b207ce30d160e45
[ "MIT" ]
223
2017-05-10T18:27:44.000Z
2022-03-06T22:44:18.000Z
commands/text.py
Commodoreprime/Command-Block-Assembly
b54c2afee3ea7bdfddfe619b9b207ce30d160e45
[ "MIT" ]
25
2017-12-07T15:37:37.000Z
2021-02-05T14:28:59.000Z
commands/text.py
Commodoreprime/Command-Block-Assembly
b54c2afee3ea7bdfddfe619b9b207ce30d160e45
[ "MIT" ]
30
2017-12-07T15:16:36.000Z
2022-03-16T03:29:59.000Z
import json from .core import Command, EntityRef, Resolvable from .scoreboard import ScoreRef from .nbt import Path, NBTStorable
29.446602
74
0.598088
import json from .core import Command, EntityRef, Resolvable from .scoreboard import ScoreRef from .nbt import Path, NBTStorable class Tellraw(Command): def __init__(self, text, target): assert isinstance(text, TextComponentHolder) assert isinstance(target, EntityRef) self.text = text self.target = target def resolve(self, scope): return 'tellraw %s %s' % (self.target.resolve(scope), self.text.resolve_str(scope)) class TextComponent(Resolvable): pass class TextComponentHolder(TextComponent): def __init__(self, style, children): self.style = style self.children = children def resolve_str(self, scope): return json.dumps(self.resolve(scope), separators=(',', ':')) def resolve(self, scope): text = {} for key, value in self.style.items(): text[key] = self._resolve_style(key, value, scope) extra = [] for child in self.children: if isinstance(child, TextComponentHolder) and not child.style: for child_child in child.children: extra.append(child_child.resolve(scope)) else: extra.append(child.resolve(scope)) if not self.style: return extra if extra: if len(extra) == 1 and type(extra[0]) == dict: text.update(extra[0]) else: text['extra'] = extra return text def _resolve_style(self, key, value, scope): if key == 'clickEvent': assert isinstance(value, TextClickAction) return value.resolve(scope) return value class TextStringComponent(TextComponent): def __init__(self, stringval): self.val = stringval def resolve(self, scope): return {'text': self.val} class TextNBTComponent(TextComponent): def __init__(self, storage, path): assert isinstance(storage, NBTStorable) assert isinstance(path, Path) self.storage = storage self.path = path def resolve(self, scope): obj = {'nbt': self.path.resolve(scope) } obj.update(self.storage.as_text(scope)) return obj class TextScoreComponent(TextComponent): def __init__(self, ref): assert isinstance(ref, ScoreRef) self.ref = ref def resolve(self, scope): return {'score': {'name': self.ref.target.resolve(scope), 'objective': self.ref.objective.resolve(scope)}} class TextClickAction(Resolvable): def __init__(self, action, value): self.action = action self.value = value def resolve(self, scope): if type(self.value) == str: value = self.value else: assert self.action in ['run_command', 'suggest_command'] \ and isinstance(self.value, Command) value = self.value.resolve(scope) return {'action': self.action, 'value': value}
2,253
111
539
624d0d0443d3ba5cb2b1fae2f1dd5f70165b3739
2,868
py
Python
environments/gym_pycolab/protocols/logging.py
braemt/attentive-multi-task-deep-reinforcement-learning
921feefce98076f88c892f0b7e6db8572f596763
[ "MIT" ]
12
2019-04-07T02:04:48.000Z
2022-03-22T12:57:47.000Z
environments/gym_pycolab/protocols/logging.py
braemt/attentive-multi-task-deep-reinforcement-learning
921feefce98076f88c892f0b7e6db8572f596763
[ "MIT" ]
null
null
null
environments/gym_pycolab/protocols/logging.py
braemt/attentive-multi-task-deep-reinforcement-learning
921feefce98076f88c892f0b7e6db8572f596763
[ "MIT" ]
7
2019-04-07T02:04:49.000Z
2020-12-28T10:30:27.000Z
# Copyright 2017 the pycolab 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 # # https://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. """Simple message logging for pycolab game entities. The interactive nature of pycolab games makes it difficult to do useful things like "printf debugging"---if you're using an interface like the Curses UI, you won't be able to see printed strings. This protocol allows game entities to log messages to the Plot object. User interfaces can query this object and display accumulated messages to the user in whatever way is best. Most game implementations will not need to import this protocol directly--- logging is so fundamental that the Plot object expresses a `log` method that's syntactic sugar for the log function in this file. """ from __future__ import absolute_import from __future__ import division from __future__ import print_function def log(the_plot, message): """Log a message for eventual disposal by the game engine user. Here, "game engine user" means a user interface or an environment interface, for example. (Clients are not required to deal with messages, but if they do, this is how to get a message to them.) Most game implementations will not need to call this function directly--- logging is so fundamental that the Plot object expresses a `log` method that's syntactic sugar for this function. Args: the_plot: the pycolab game's `Plot` object. message: A string message to convey to the game engine user. """ the_plot.setdefault('log_messages', []).append(message) def consume(the_plot): """Obtain messages logged by game entities since the last call to `consume`. This function is meant to be called by "game engine users" (user interfaces, environment interfaces, etc.) to obtain the latest set of log messages emitted by the game entities. These systems can then dispose of these messages in whatever manner is the most appropriate. Args: the_plot: the pycolab game's `Plot` object. Returns: The list of all log messages supplied by the `log` method since the last time `consume` was called (or ever, if `consume` has never been called). """ messages = the_plot.setdefault('log_messages', []) # Hand off the current messages to a new list that we return. our_messages = messages[:] del messages[:] return our_messages
40.394366
82
0.74477
# Copyright 2017 the pycolab 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 # # https://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. """Simple message logging for pycolab game entities. The interactive nature of pycolab games makes it difficult to do useful things like "printf debugging"---if you're using an interface like the Curses UI, you won't be able to see printed strings. This protocol allows game entities to log messages to the Plot object. User interfaces can query this object and display accumulated messages to the user in whatever way is best. Most game implementations will not need to import this protocol directly--- logging is so fundamental that the Plot object expresses a `log` method that's syntactic sugar for the log function in this file. """ from __future__ import absolute_import from __future__ import division from __future__ import print_function def log(the_plot, message): """Log a message for eventual disposal by the game engine user. Here, "game engine user" means a user interface or an environment interface, for example. (Clients are not required to deal with messages, but if they do, this is how to get a message to them.) Most game implementations will not need to call this function directly--- logging is so fundamental that the Plot object expresses a `log` method that's syntactic sugar for this function. Args: the_plot: the pycolab game's `Plot` object. message: A string message to convey to the game engine user. """ the_plot.setdefault('log_messages', []).append(message) def consume(the_plot): """Obtain messages logged by game entities since the last call to `consume`. This function is meant to be called by "game engine users" (user interfaces, environment interfaces, etc.) to obtain the latest set of log messages emitted by the game entities. These systems can then dispose of these messages in whatever manner is the most appropriate. Args: the_plot: the pycolab game's `Plot` object. Returns: The list of all log messages supplied by the `log` method since the last time `consume` was called (or ever, if `consume` has never been called). """ messages = the_plot.setdefault('log_messages', []) # Hand off the current messages to a new list that we return. our_messages = messages[:] del messages[:] return our_messages
0
0
0
76e13b55d98ab2dbca05ab4638b9827bc2fc8afe
1,076
py
Python
pylith/materials/__init__.py
joegeisz/pylith
f74060b7b19d7e90abf8597bbe9250c96593c0ad
[ "MIT" ]
1
2021-01-20T17:18:28.000Z
2021-01-20T17:18:28.000Z
pylith/materials/__init__.py
joegeisz/pylith
f74060b7b19d7e90abf8597bbe9250c96593c0ad
[ "MIT" ]
null
null
null
pylith/materials/__init__.py
joegeisz/pylith
f74060b7b19d7e90abf8597bbe9250c96593c0ad
[ "MIT" ]
null
null
null
#!/usr/bin/env python # # ---------------------------------------------------------------------- # # Brad T. Aagaard, U.S. Geological Survey # Charles A. Williams, GNS Science # Matthew G. Knepley, University of Chicago # # This code was developed as part of the Computational Infrastructure # for Geodynamics (http://geodynamics.org). # # Copyright (c) 2010-2017 University of California, Davis # # See COPYING for license information. # # ---------------------------------------------------------------------- # ## @file pylith/materials/__init__.py ## @brief Python PyLith materials module initialization __all__ = ['ElasticMaterial', 'ElasticIsotropic3D', 'ElasticPlaneStrain', 'ElasticPlaneStress', 'ElasticStrain1D', 'ElasticStress1D', 'GenMaxwellIsotropic3D', 'GenMaxwellQpQsIsotropic3D', 'Homogeneous', 'Material', 'MaxwellIsotropic3D', 'PowerLaw3D', 'PowerLawPlaneStrain', 'DruckerPrager3D', ] # End of file
26.243902
72
0.546468
#!/usr/bin/env python # # ---------------------------------------------------------------------- # # Brad T. Aagaard, U.S. Geological Survey # Charles A. Williams, GNS Science # Matthew G. Knepley, University of Chicago # # This code was developed as part of the Computational Infrastructure # for Geodynamics (http://geodynamics.org). # # Copyright (c) 2010-2017 University of California, Davis # # See COPYING for license information. # # ---------------------------------------------------------------------- # ## @file pylith/materials/__init__.py ## @brief Python PyLith materials module initialization __all__ = ['ElasticMaterial', 'ElasticIsotropic3D', 'ElasticPlaneStrain', 'ElasticPlaneStress', 'ElasticStrain1D', 'ElasticStress1D', 'GenMaxwellIsotropic3D', 'GenMaxwellQpQsIsotropic3D', 'Homogeneous', 'Material', 'MaxwellIsotropic3D', 'PowerLaw3D', 'PowerLawPlaneStrain', 'DruckerPrager3D', ] # End of file
0
0
0
4f22a2d7f5fa7d72c3510a14657615fe75aacb01
3,193
py
Python
utils.py
LynnHongLiu/replayed_distillation
943169e3b37f5453b386ae652af81db935efc7bd
[ "MIT" ]
79
2017-07-20T07:27:59.000Z
2022-02-13T14:10:35.000Z
utils.py
LynnHongLiu/replayed_distillation
943169e3b37f5453b386ae652af81db935efc7bd
[ "MIT" ]
4
2018-02-03T14:43:07.000Z
2018-04-21T08:47:18.000Z
utils.py
iRapha/replayed_distillation
943169e3b37f5453b386ae652af81db935efc7bd
[ "MIT" ]
20
2017-07-22T16:22:38.000Z
2021-05-17T14:03:31.000Z
import datetime as dt import json import os import sys import tensorflow as tf import numpy as np from subprocess import check_output from itertools import zip_longest def grouper(iterable, batch_size, fill_value=None): """ Helper method for returning batches of size batch_size of a dataset. grouper('ABCDEF', 3) -> 'ABC', 'DEF' """ args = [iter(iterable)] * batch_size return zip_longest(*args, fillvalue=fill_value)
29.027273
76
0.658628
import datetime as dt import json import os import sys import tensorflow as tf import numpy as np from subprocess import check_output from itertools import zip_longest def get_logger(f): if len(f.commit) == 0: print('No commit hash provided, using most recent on HEAD') f.commit = check_output(['git', 'rev-parse', 'HEAD']) if any(map( lambda x: x == 0, [len(f.run_name), len(f.dataset), len(f.model), len(f.procedure)])): print('No Run Name, Dataset, Model, or Procedure provided!') sys.exit(-1) log = {} log['run_file'] = 'train.py' log['start_time'] = dt.datetime.now().timestamp() log['end_time'] = None log['run_name'] = f.run_name log['commit'] = f.commit.decode('utf-8') log['dataset'] = f.dataset log['model'] = f.model log['rng_seed'] = f.rng_seed log['train_procedure'] = f.procedure log['epochs'] = f.epochs log['train_batch_size'] = f.train_batch_size log['test_batch_size'] = f.test_batch_size log['eval_interval'] = f.eval_interval log['checkpoint_interval'] = f.checkpoint_interval return log def save_log(log, summary_folder, run_name, log_file): log['end_time'] = dt.datetime.now().timestamp() dirname = os.path.join(summary_folder, run_name) ensure_dir_exists(dirname) with open(os.path.join(dirname, log_file), 'w') as f: f.write(json.dumps(log)) def ensure_dir_exists(dir_name): if not os.path.exists(dir_name): os.makedirs(dir_name) def get_sess_config(use_gpu=True): if use_gpu: config = tf.ConfigProto() config.gpu_options.allow_growth = True return config else: return tf.ConfigProto(device_count={'GPU': 0}) def get_uninitted_vars(sess): uninitialized_vars = [] for var in tf.global_variables(): try: sess.run(var) except tf.errors.FailedPreconditionError: uninitialized_vars.append(var) return uninitialized_vars def init_uninitted_vars(sess): sess.run(tf.variables_initializer(get_uninitted_vars(sess))) def merge_summary_list(summary_list, do_print=False): summary_dict = {} for summary in summary_list: summary_proto = tf.Summary() summary_proto.ParseFromString(summary) for val in summary_proto.value: if val.tag not in summary_dict: summary_dict[val.tag] = [] summary_dict[val.tag].append(val.simple_value) # get mean of each tag for k, v in summary_dict.items(): summary_dict[k] = np.mean(v) if do_print: print(summary_dict) # create final Summary with mean of values final_summary = tf.Summary() final_summary.ParseFromString(summary_list[0]) for i, val in enumerate(final_summary.value): final_summary.value[i].simple_value = summary_dict[val.tag] return final_summary def grouper(iterable, batch_size, fill_value=None): """ Helper method for returning batches of size batch_size of a dataset. grouper('ABCDEF', 3) -> 'ABC', 'DEF' """ args = [iter(iterable)] * batch_size return zip_longest(*args, fillvalue=fill_value)
2,585
0
161
9d71d09623ea6dba322c262bfb4c0d049a1a2533
14,351
py
Python
src/finn/custom_op/logicnets/truthtable.py
jalezeta/finn-base
14051a23670834ce41fd19a7134968648d2d112b
[ "BSD-3-Clause" ]
null
null
null
src/finn/custom_op/logicnets/truthtable.py
jalezeta/finn-base
14051a23670834ce41fd19a7134968648d2d112b
[ "BSD-3-Clause" ]
null
null
null
src/finn/custom_op/logicnets/truthtable.py
jalezeta/finn-base
14051a23670834ce41fd19a7134968648d2d112b
[ "BSD-3-Clause" ]
null
null
null
# Copyright (c) 2021 Xilinx, 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: # # * Redistributions of source code must retain the above copyright notice, this # list of conditions and the following disclaimer. # # * 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. # # * Neither the name of Xilinx nor the names of its # contributors may be used to endorse or promote products derived from # this software without specific prior written permission. # # THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" # AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE # IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE # DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE # FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL # DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR # SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER # CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, # OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE # OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. import numpy as np import onnx import os from onnx import helper from pyverilator import PyVerilator from finn.core.datatype import DataType from finn.core.modelwrapper import ModelWrapper from finn.custom_op.base import CustomOp from finn.util.basic import make_build_dir from finn.util.data_packing import ( npy_to_rtlsim_input, unpack_innermost_dim_from_hex_string, ) def _truthtable(input, care_set, results, in_bits): """Returns the output to a combination of x-bit input value. The care_set array reflects the specific input combinations considered. The result vector represents every output to every combination in the care_set. Thus, the length of care_set and results must be the same. All the arrays are numpy arrays The MSB in the input numpy array represents the LSB in the LUT. An example is presented: in_bits = 3 out_bits = 3 input[0:2] = [1, 0, 1] care_set = [1, 5] results = [3, 1] The function checks if the decimal representation of the binary input is in the care_set. If it is in the care_set, we check the result of the binary input combination in the result. If the input is not part of the care_set, the output will be zero. The input in this example is [1,0,1], which is '5' in decimal representation. The input is part of the care_set. Then, we check what is the position of 5 in the care_set, and we extract the value to input combination '5' from the results vector, which in this case is '1' Possible combinations[2:0]: input[0:2] | results[0:2] 0 0 0 | 0 0 0 0 0 1 | 0 1 1 0 1 0 | 0 0 0 0 1 1 | 0 0 0 > 1 0 0 | 0 0 1 1 0 1 | 0 0 0 1 1 0 | 0 0 0 1 1 1 | 0 0 0 """ # calculate integer value of binary input input_int = npy_to_rtlsim_input(input, DataType.BINARY, in_bits, False)[0] if input_int in care_set: index = np.where(care_set == input_int)[0][0] output = results[index] else: output = 0 return output class TruthTable(CustomOp): """The class corresponing to the TruthTable function."""
39.534435
88
0.594035
# Copyright (c) 2021 Xilinx, 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: # # * Redistributions of source code must retain the above copyright notice, this # list of conditions and the following disclaimer. # # * 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. # # * Neither the name of Xilinx nor the names of its # contributors may be used to endorse or promote products derived from # this software without specific prior written permission. # # THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" # AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE # IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE # DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE # FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL # DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR # SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER # CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, # OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE # OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. import numpy as np import onnx import os from onnx import helper from pyverilator import PyVerilator from finn.core.datatype import DataType from finn.core.modelwrapper import ModelWrapper from finn.custom_op.base import CustomOp from finn.util.basic import make_build_dir from finn.util.data_packing import ( npy_to_rtlsim_input, unpack_innermost_dim_from_hex_string, ) def _truthtable(input, care_set, results, in_bits): """Returns the output to a combination of x-bit input value. The care_set array reflects the specific input combinations considered. The result vector represents every output to every combination in the care_set. Thus, the length of care_set and results must be the same. All the arrays are numpy arrays The MSB in the input numpy array represents the LSB in the LUT. An example is presented: in_bits = 3 out_bits = 3 input[0:2] = [1, 0, 1] care_set = [1, 5] results = [3, 1] The function checks if the decimal representation of the binary input is in the care_set. If it is in the care_set, we check the result of the binary input combination in the result. If the input is not part of the care_set, the output will be zero. The input in this example is [1,0,1], which is '5' in decimal representation. The input is part of the care_set. Then, we check what is the position of 5 in the care_set, and we extract the value to input combination '5' from the results vector, which in this case is '1' Possible combinations[2:0]: input[0:2] | results[0:2] 0 0 0 | 0 0 0 0 0 1 | 0 1 1 0 1 0 | 0 0 0 0 1 1 | 0 0 0 > 1 0 0 | 0 0 1 1 0 1 | 0 0 0 1 1 0 | 0 0 0 1 1 1 | 0 0 0 """ # calculate integer value of binary input input_int = npy_to_rtlsim_input(input, DataType.BINARY, in_bits, False)[0] if input_int in care_set: index = np.where(care_set == input_int)[0][0] output = results[index] else: output = 0 return output class TruthTable(CustomOp): """The class corresponing to the TruthTable function.""" def get_nodeattr_types(self): return { # number of intput bits, 4 by default "in_bits": ("i", True, 4), # number of output bits, 4 by default "out_bits": ("i", True, 4), # code generation mode "code_mode": ("s", False, "Verilog"), # output code directory "code_dir": ("s", False, ""), # execution mode, "python" by default "exec_mode": ("s", True, "python"), } def make_shape_compatible_op(self, model): node = self.onnx_node out_bits = self.get_nodeattr("out_bits") val = np.random.randint(2, size=out_bits) tensor_name = ModelWrapper.make_new_valueinfo_name(model) node = helper.make_node( "Constant", inputs=[], outputs=["val"], value=helper.make_tensor( name=tensor_name, data_type=onnx.TensorProto.FLOAT, dims=val.shape, vals=val.flatten().astype(float), ), ) return node def infer_node_datatype(self, model): node = self.onnx_node # check that the input[0] is binary assert ( model.get_tensor_datatype(node.input[0]) == DataType["BINARY"] ), """ The input vector DataType is not BINARY.""" # check that the input[1] is UINT32 assert ( model.get_tensor_datatype(node.input[1]) == DataType["UINT32"] ), """ The input vector DataType is not UINT32.""" # check that the input[2] is UINT32 assert ( model.get_tensor_datatype(node.input[2]) == DataType["UINT32"] ), """ The input vector DataType is not UINT32.""" # set the output[0] tensor datatype to BINARY model.set_tensor_datatype(node.output[0], DataType["BINARY"]) def execute_node(self, context, graph): node = self.onnx_node # Load inputs # We assume input[0] is the input_vector, input[1] the care_set # and the input[2] the results input_entry = context[node.input[0]] care_set = context[node.input[1]] results = context[node.input[2]] # VERIFICATION: care_set and results tensor shape and sizes # # check input_entry size in_size = input_entry.size in_bits = self.get_nodeattr("in_bits") out_bits = self.get_nodeattr("out_bits") assert ( in_size == in_bits ), """The input bit array vector is %i and should be %i""" % ( in_size, in_bits, ) # check the maximum value of care_set values is smaller than 2^in_bits max_care_set = np.amax(care_set) max_in = 1 << in_bits assert max_care_set < max_in # check the maximum value of the results is smaller than 2^out_bits max_results = np.amax(results) max_out = 1 << out_bits assert max_results < max_out # check input_entry shape assert ( len(input_entry.shape) == 1 ), """The input vector has more than one dimension.""" # check care_set shape assert ( len(care_set.shape) == 1 ), """The care_set vector has more than one dimension.""" # check results shape assert ( len(results.shape) == 1 ), """The results vector has more than one dimension.""" # check the care_set and results sizes are the same assert ( care_set.size == results.size ), """The care_set size is %s and results size is %s. Must be the same """ % ( care_set.size, results.size, ) # load execution mode mode = self.get_nodeattr("exec_mode") if mode == "python": # calculate output in Python mode output = _truthtable(input_entry, care_set, results, in_bits) elif mode == "rtlsim": # check the code directory is not empty nodeName = self.onnx_node.name code_dir = self.get_nodeattr("code_dir") verilog_dir = code_dir + "/" + nodeName + ".v" if not os.path.exists(verilog_dir): raise Exception("Non valid path for the Verilog file: %s" % verilog_dir) # Create PyVerilator object sim = PyVerilator.build(verilog_dir) # Convert input binary array into an integer representation value = npy_to_rtlsim_input(input_entry, DataType.BINARY, in_bits, False)[0] # Set input value into the Verilog module sim.io["in"] = value # read result value output = sim.io["result"] else: raise Exception( """Invalid value for attribute exec_mode! Is currently set to: {} has to be set to one of the following value ("python", "rtlsim")""".format( mode ) ) # return output and convert it back into a binary array output_hex = np.array([hex(int(output))]) out_array = unpack_innermost_dim_from_hex_string( output_hex, DataType.BINARY, (out_bits,), out_bits ) context[node.output[0]] = out_array def verify_node(self): info_messages = [] # verify number of attributes num_of_attr = 5 if len(self.onnx_node.attribute) == num_of_attr: info_messages.append("The number of attributes is correct") else: info_messages.append( """The number of attributes is incorrect, {} should have {} attributes""".format( self.onnx_node.op_type, num_of_attr ) ) # verify that all necessary attributes exist try: self.get_nodeattr("in_bits") self.get_nodeattr("out_bits") self.get_nodeattr("exec_mode") except Exception: info_messages.append( """The required attributes are not set. BinaryTruthTable operation reqires in_bits, out_bits andb exec_mode attributes.""" ) # verify the number of inputs if len(self.onnx_node.input) == 3: info_messages.append("The number of inputs is correct") else: info_messages.append("BinaryTruthTable needs 3 data inputs") return info_messages def generate_verilog(self, care_set, results): input_bits = self.get_nodeattr("in_bits") output_bits = self.get_nodeattr("out_bits") nodeName = self.onnx_node.name # VERIFICATION: care_set and results tensor shape and sizes # # check the maximum value of care_set values is smaller than 2^in_bits max_care_set = np.amax(care_set) max_in = 1 << input_bits assert max_care_set < max_in # check the maximum value of the results is smaller than 2^out_bits max_results = np.amax(results) max_out = 1 << output_bits assert max_results < max_out # check care_set shape assert ( len(care_set.shape) == 1 ), """The care_set vector has more than one dimension.""" # check results shape assert ( len(results.shape) == 1 ), """The results vector has more than one dimension.""" # check the care_set and results sizes are the same care_set_size = care_set.size results_size = results.size assert ( care_set_size == results_size ), """The care_set size is %s and results size is %s. Must be the same """ % ( care_set_size, results_size, ) # the module name is kept constant to "incomplete_table" # the input name is kept constant to "in" # the output is kept constant to "result" verilog_string = "module %s (\n" % (nodeName) verilog_string += "\tinput [%d:0] in,\n" % (input_bits - 1) verilog_string += "\t output reg [%d:0] result\n" % (output_bits - 1) verilog_string += ");\n\n" verilog_string += "\talways @(in) begin\n" verilog_string += "\t\tcase(in)\n" # fill the one entries for index, val in enumerate(care_set): val = int(val) verilog_string += "\t\t\t%d'b" % (input_bits) verilog_string += bin(val)[2:].zfill(input_bits) verilog_string += " : result = %d'b" % (output_bits) verilog_string += bin(results[index])[2:].zfill(output_bits) verilog_string += ";\n" # fill the rest of the combinations with 0 verilog_string += "\t\t\tdefault: result = %d'b" % (output_bits) verilog_string += bin(0)[2:].zfill(output_bits) verilog_string += ";\n" # close the module verilog_string += "\t\tendcase\n\tend\nendmodule\n" # create temporary folder and save attribute value self.set_nodeattr("code_dir", make_build_dir("TruthTable_files_")) # create and write verilog file verilog_file = open(self.get_nodeattr("code_dir") + "/" + nodeName + ".v", "w") verilog_file.write(verilog_string) verilog_file.close() def generate_pla(self, care_set, results): input_bits = self.get_nodeattr("in_bits") output_bits = self.get_nodeattr("out_bits") nodeName = self.onnx_node.name pla_string = ".i %d\n" % (input_bits) pla_string += ".o %d\n" % (output_bits) pla_string += ".ilb" for i in range(input_bits): pla_string += " in_%d" % (i) pla_string += "\n" pla_string += ".ob" for i in range(output_bits): pla_string += " out_%d" % (i) pla_string += "\n" pla_string += ".type fd\n" for index, val in enumerate(care_set): pla_string += bin(val)[2:].zfill(input_bits) pla_string += " " pla_string += bin(results[index])[2:].zfill(output_bits) pla_string += "\n" pla_string += "\n.e" pla_file = open(self.get_nodeattr("code_dir") + "/" + nodeName + ".pla", "w") pla_file.write(pla_string) pla_file.close()
10,148
0
189
c27a8b95b59e8ad90ba6e52a8fbf028a76e98858
1,086
py
Python
dnm_cohorts/cohorts/oroak_nature.py
jeremymcrae/dnm_cohorts
e968357797d2d370b44904129c32c2e74b36b903
[ "MIT" ]
1
2020-12-10T05:17:21.000Z
2020-12-10T05:17:21.000Z
dnm_cohorts/cohorts/oroak_nature.py
jeremymcrae/dnm_cohorts
e968357797d2d370b44904129c32c2e74b36b903
[ "MIT" ]
null
null
null
dnm_cohorts/cohorts/oroak_nature.py
jeremymcrae/dnm_cohorts
e968357797d2d370b44904129c32c2e74b36b903
[ "MIT" ]
null
null
null
import pandas from dnm_cohorts.person import Person url = 'https://static-content.springer.com/esm/art%3A10.1038%2Fnature10989/MediaObjects/41586_2012_BFnature10989_MOESM11_ESM.xls' def open_oroak_cohort(): """ get proband data from the O'Roak et al autism exome study O'Roak et al. (2012) Nature 485:246-250 doi: 10.1038/nature10989 Supplementary table 1 """ data = pandas.read_excel(url, sheet_name='Supplementary Table 1', skipfooter=1, engine='xlrd') study = ['10.1038/nature10989'] persons = set() for i, row in data.iterrows(): status = ['HP:0000717'] person_type = row.child.split('.')[1] # ignore the siblings, since they don't have any de novos recorded, so # don't contribute to the exome-sequence populations if person_type.startswith('s'): continue if row['non-verbal_IQ'] < 70: status.append('HP:0001249') person = Person(row.child + '|asd_cohorts', row.sex, status, study) persons.add(person) return persons
31.941176
129
0.644567
import pandas from dnm_cohorts.person import Person url = 'https://static-content.springer.com/esm/art%3A10.1038%2Fnature10989/MediaObjects/41586_2012_BFnature10989_MOESM11_ESM.xls' def open_oroak_cohort(): """ get proband data from the O'Roak et al autism exome study O'Roak et al. (2012) Nature 485:246-250 doi: 10.1038/nature10989 Supplementary table 1 """ data = pandas.read_excel(url, sheet_name='Supplementary Table 1', skipfooter=1, engine='xlrd') study = ['10.1038/nature10989'] persons = set() for i, row in data.iterrows(): status = ['HP:0000717'] person_type = row.child.split('.')[1] # ignore the siblings, since they don't have any de novos recorded, so # don't contribute to the exome-sequence populations if person_type.startswith('s'): continue if row['non-verbal_IQ'] < 70: status.append('HP:0001249') person = Person(row.child + '|asd_cohorts', row.sex, status, study) persons.add(person) return persons
0
0
0
be78eee36931eb4bac4c4c3c6c4acf2ae89f68d4
2,308
py
Python
JumpscaleLibs/sal/zosv2/billing.py
grimpy/jumpscaleX_libs
4cd8a8b69dd3aa7a1a558c81befc97894ab2ec39
[ "Apache-2.0" ]
null
null
null
JumpscaleLibs/sal/zosv2/billing.py
grimpy/jumpscaleX_libs
4cd8a8b69dd3aa7a1a558c81befc97894ab2ec39
[ "Apache-2.0" ]
null
null
null
JumpscaleLibs/sal/zosv2/billing.py
grimpy/jumpscaleX_libs
4cd8a8b69dd3aa7a1a558c81befc97894ab2ec39
[ "Apache-2.0" ]
null
null
null
from .resource import ResourceParser
38.466667
117
0.679809
from .resource import ResourceParser class Billing: def __init__(self, explorer): self._explorer = explorer def reservation_resources(self, reservation): """ compute how much resource units is reserved in the reservation :param reservation: reservation object :type reservation: tfgrid.workloads.reservation.1 :return: list of ResourceUnitsNode object :rtype: list """ rp = ResourceParser(self._explorer, reservation) return rp.calculate_used_resources() def reservation_resources_cost(self, reservation): """ compute how much resource units is reserved in the reservation :param reservation: reservation object :type reservation: tfgrid.workloads.reservation.1 :return: list of ResourceUnitsNode object with costs filled in :rtype: list """ rp = ResourceParser(self._explorer, reservation) return rp.calculate_used_resources_cost() def payout_farmers(self, client, reservation): """ payout farmer based on the resources per node used :param client: tfchain wallet or stellar client :type client: a wallet of j.clients.tfchain or a client of j.client.stellar :param reservation: reservation object :type reservation: tfgrid.workloads.reservation.1 :return: list of transactions :rtype: list """ rp = ResourceParser(self._explorer, reservation) costs = rp.calculate_used_resources_cost() return rp.payout_farmers(client, costs, reservation.id) def verify_payments(self, client, reservation): """ verify that a reservation with a given ID has been paid for, for all farms belonging to the current user 3bot :param client: tfchain wallet or stellar client :type client: a wallet of j.clients.tfchain or a client of j.client.stellar :param reservation: reservation object :type reservation: tfgrid.workloads.reservation.1 :return: if the reservation has been fully funded for the farms owned by the current user 3bot :rtype: bool """ rp = ResourceParser(self._explorer, reservation) return rp.validate_reservation_payment(client, reservation.id)
42
2,205
23
ab66010ad825163ec3980b41cacb3534407aba8b
414
py
Python
once/clean-ep-nums.py
erikfastermann/etc
a85ad6f0cb87dab208716dcc5a58c3f71a9b202c
[ "MIT" ]
null
null
null
once/clean-ep-nums.py
erikfastermann/etc
a85ad6f0cb87dab208716dcc5a58c3f71a9b202c
[ "MIT" ]
null
null
null
once/clean-ep-nums.py
erikfastermann/etc
a85ad6f0cb87dab208716dcc5a58c3f71a9b202c
[ "MIT" ]
null
null
null
import os path = os.getcwd() content = os.listdir(path) last = 0 for f in content: name, ext = os.path.splitext(f) ep_num = name.split('x', 1)[1] ep_num = int(ep_num.split(' -', 1)[0]) if ep_num != last + 1: ep_num = last + 1 last += 1 season = name.split('x', 1)[0] name = name.split(' - ', 1)[1] new = f'{season}x{ep_num:02} - {name}{ext}' os.rename(os.path.join(path, f), os.path.join(path, new))
21.789474
58
0.599034
import os path = os.getcwd() content = os.listdir(path) last = 0 for f in content: name, ext = os.path.splitext(f) ep_num = name.split('x', 1)[1] ep_num = int(ep_num.split(' -', 1)[0]) if ep_num != last + 1: ep_num = last + 1 last += 1 season = name.split('x', 1)[0] name = name.split(' - ', 1)[1] new = f'{season}x{ep_num:02} - {name}{ext}' os.rename(os.path.join(path, f), os.path.join(path, new))
0
0
0
25e0e8cc87b2e760d45a0a5d8f84d75189109445
3,695
py
Python
projects/realtek/amebaD/IAR/aws_demos/python_custom_ecdsa_D.py
ambiot/ambd_amazon-freertos
5ac9a8782bdcdd46838459111141fbf483d8aa5a
[ "MIT" ]
2
2020-09-03T02:00:25.000Z
2021-05-20T07:44:22.000Z
projects/realtek/amebaD/IAR/aws_demos/python_custom_ecdsa_D.py
ambiot/ambd_amazon-freertos
5ac9a8782bdcdd46838459111141fbf483d8aa5a
[ "MIT" ]
null
null
null
projects/realtek/amebaD/IAR/aws_demos/python_custom_ecdsa_D.py
ambiot/ambd_amazon-freertos
5ac9a8782bdcdd46838459111141fbf483d8aa5a
[ "MIT" ]
1
2020-08-16T07:14:55.000Z
2020-08-16T07:14:55.000Z
from OpenSSL import crypto from socket import gethostname import os import array as arr import subprocess Major = 0 Minor = 0 Build = 0 with open('../../../../../demos/include/aws_application_version.h') as f: for line in f: if line.find('APP_VERSION_MAJOR') != -1: x = line.split() Major = int(x[2]) if line.find('APP_VERSION_MINOR') != -1: x = line.split() Minor = int(x[2]) if line.find('APP_VERSION_BUILD') != -1: x = line.split() Build = int(x[2]) print('Major:' + str(Major)) print('Minor:' + str(Minor)) print('Build:' + str(Build)) #version = 0xffffffff version = Major*1000000 + Minor*1000 + Build version_byte = version.to_bytes(4,'little') headernum = 0x00000001 headernum_byte = headernum.to_bytes(4,'little') signature = 0x3141544f signature_byte = signature.to_bytes(4,'little') headerlen = 0x00000018 headerlen_byte = headerlen.to_bytes(4,'little') checksum = 0; with open("./Debug/Exe/km4_image/km0_km4_image2.bin", "rb") as f: byte = f.read(1) num = int.from_bytes(byte, 'big') checksum += num while byte != b"": byte = f.read(1) num = int.from_bytes(byte, 'big') checksum += num checksum_byte = checksum.to_bytes(4,'little') imagelen = os.path.getsize("./Debug/Exe/km4_image/km0_km4_image2.bin") imagelen_bytes = imagelen.to_bytes(4, 'little') offset = 0x00000020 offset_bytes = offset.to_bytes(4, 'little') rvsd = 0x0800b000 rvsd_bytes = rvsd.to_bytes(4, 'little') img2_bin = open('./Debug/Exe/km4_image/km0_km4_image2.bin', 'br').read() f = open("./Debug/Exe/km4_image/OTA_ALL.bin", 'wb') f.write(version_byte) f.write(headernum_byte) f.write(signature_byte) f.write(headerlen_byte) f.write(checksum_byte) f.write(imagelen_bytes) f.write(offset_bytes) f.write(rvsd_bytes) f.write(img2_bin) f.close() #Reading the Private key generated using openssl(should be generated using ECDSA P256 curve) f = open("ecdsa-sha256-signer.key.pem") pv_buf = f.read() f.close() priv_key = crypto.load_privatekey(crypto.FILETYPE_PEM, pv_buf) #Reading the certificate generated using openssl(should be generated using ECDSA P256 curve) f = open("ecdsa-sha256-signer.crt.pem") ss_buf = f.read() f.close() ss_cert = crypto.load_certificate(crypto.FILETYPE_PEM, ss_buf) #Reading OTA1 binary and individually signing it using the ECDSA P256 curve ota1_bin = open('./Debug/Exe/km4_image/km0_km4_image2.bin', 'br').read() # sign and verify PASS ota1_sig = crypto.sign(priv_key, ota1_bin, 'sha256') crypto.verify(ss_cert, ota1_sig, ota1_bin, 'sha256') ota1_sig_size = len(ota1_sig) #print(ota1_sig_size) #opening the ota_all.bin and getting the number of padding bytes f = open("./Debug/Exe/km4_image/OTA_All.bin", 'rb') ota_all_buff = f.read() f.close() ota_all_size = os.path.getsize("./Debug/Exe/km4_image/OTA_All.bin") #print(ota_all_size) ota_padding = 1024-(ota_all_size%1024) #print(int(ota_padding)) #padding 0's to make the last block of OTA equal to an integral multiple of block size x = bytes([0] * ota_padding) #append the 0 padding bytes followed by the 2 individual signatures of ota1 and ota2 along with their signature sizes f = open("./Debug/Exe/km4_image/OTA_ALL_sig.bin", 'wb') f.write(ota_all_buff) f.write(x) f.write(ota1_sig) f.write(bytes([ota1_sig_size])) f.close() print('done') #Debug info in case you want to check the actual signature binaries generated separately ''' sf = open("ota1.sig", 'wb') sf.write(ota1_sig) sf.close() sf = open("ota2.sig", 'wb') sf.write(ota2_sig) sf.close() '''
29.798387
118
0.68498
from OpenSSL import crypto from socket import gethostname import os import array as arr import subprocess Major = 0 Minor = 0 Build = 0 with open('../../../../../demos/include/aws_application_version.h') as f: for line in f: if line.find('APP_VERSION_MAJOR') != -1: x = line.split() Major = int(x[2]) if line.find('APP_VERSION_MINOR') != -1: x = line.split() Minor = int(x[2]) if line.find('APP_VERSION_BUILD') != -1: x = line.split() Build = int(x[2]) print('Major:' + str(Major)) print('Minor:' + str(Minor)) print('Build:' + str(Build)) #version = 0xffffffff version = Major*1000000 + Minor*1000 + Build version_byte = version.to_bytes(4,'little') headernum = 0x00000001 headernum_byte = headernum.to_bytes(4,'little') signature = 0x3141544f signature_byte = signature.to_bytes(4,'little') headerlen = 0x00000018 headerlen_byte = headerlen.to_bytes(4,'little') checksum = 0; with open("./Debug/Exe/km4_image/km0_km4_image2.bin", "rb") as f: byte = f.read(1) num = int.from_bytes(byte, 'big') checksum += num while byte != b"": byte = f.read(1) num = int.from_bytes(byte, 'big') checksum += num checksum_byte = checksum.to_bytes(4,'little') imagelen = os.path.getsize("./Debug/Exe/km4_image/km0_km4_image2.bin") imagelen_bytes = imagelen.to_bytes(4, 'little') offset = 0x00000020 offset_bytes = offset.to_bytes(4, 'little') rvsd = 0x0800b000 rvsd_bytes = rvsd.to_bytes(4, 'little') img2_bin = open('./Debug/Exe/km4_image/km0_km4_image2.bin', 'br').read() f = open("./Debug/Exe/km4_image/OTA_ALL.bin", 'wb') f.write(version_byte) f.write(headernum_byte) f.write(signature_byte) f.write(headerlen_byte) f.write(checksum_byte) f.write(imagelen_bytes) f.write(offset_bytes) f.write(rvsd_bytes) f.write(img2_bin) f.close() #Reading the Private key generated using openssl(should be generated using ECDSA P256 curve) f = open("ecdsa-sha256-signer.key.pem") pv_buf = f.read() f.close() priv_key = crypto.load_privatekey(crypto.FILETYPE_PEM, pv_buf) #Reading the certificate generated using openssl(should be generated using ECDSA P256 curve) f = open("ecdsa-sha256-signer.crt.pem") ss_buf = f.read() f.close() ss_cert = crypto.load_certificate(crypto.FILETYPE_PEM, ss_buf) #Reading OTA1 binary and individually signing it using the ECDSA P256 curve ota1_bin = open('./Debug/Exe/km4_image/km0_km4_image2.bin', 'br').read() # sign and verify PASS ota1_sig = crypto.sign(priv_key, ota1_bin, 'sha256') crypto.verify(ss_cert, ota1_sig, ota1_bin, 'sha256') ota1_sig_size = len(ota1_sig) #print(ota1_sig_size) #opening the ota_all.bin and getting the number of padding bytes f = open("./Debug/Exe/km4_image/OTA_All.bin", 'rb') ota_all_buff = f.read() f.close() ota_all_size = os.path.getsize("./Debug/Exe/km4_image/OTA_All.bin") #print(ota_all_size) ota_padding = 1024-(ota_all_size%1024) #print(int(ota_padding)) #padding 0's to make the last block of OTA equal to an integral multiple of block size x = bytes([0] * ota_padding) #append the 0 padding bytes followed by the 2 individual signatures of ota1 and ota2 along with their signature sizes f = open("./Debug/Exe/km4_image/OTA_ALL_sig.bin", 'wb') f.write(ota_all_buff) f.write(x) f.write(ota1_sig) f.write(bytes([ota1_sig_size])) f.close() print('done') #Debug info in case you want to check the actual signature binaries generated separately ''' sf = open("ota1.sig", 'wb') sf.write(ota1_sig) sf.close() sf = open("ota2.sig", 'wb') sf.write(ota2_sig) sf.close() '''
0
0
0
bcd3b65d9c0e74bcd69032f281dd72460d9c3725
5,133
py
Python
base/modules/utils/root/sb_utils/general.py
g2-inc/openc2-oif-orchestrator
85102bb41aa0d558a3fa088e4fd6f51613599ad0
[ "Apache-2.0" ]
1
2019-04-29T12:47:17.000Z
2019-04-29T12:47:17.000Z
base/modules/utils/root/sb_utils/general.py
g2-inc/openc2-oif-orchestrator
85102bb41aa0d558a3fa088e4fd6f51613599ad0
[ "Apache-2.0" ]
null
null
null
base/modules/utils/root/sb_utils/general.py
g2-inc/openc2-oif-orchestrator
85102bb41aa0d558a3fa088e4fd6f51613599ad0
[ "Apache-2.0" ]
null
null
null
import base64 import binascii import json import re import struct import sys import uuid from typing import ( Any, Callable, Dict, Type, Union ) # Util Functions def toStr(s: Any) -> str: """ Convert a given type to a default string :param s: item to convert to a string :return: converted string """ return s.decode(sys.getdefaultencoding(), 'backslashreplace') if hasattr(s, 'decode') else str(s) def prefixUUID(pre: str = 'PREFIX', max_len: int = 30) -> str: """ Prefix a uuid with the given prefix with a max length :param pre: prefix str :param max_len: max length of prefix + UUID :return: prefixed UUID """ uid_max = max_len - (len(pre) + 10) uid = str(uuid.uuid4()).replace('-', '')[:uid_max] return f'{pre}-{uid}'[:max] def safe_cast(val: Any, to_type: Type, default: Any = None) -> Any: """ Cast the given value to the goven type safely without an exception being thrown :param val: value to cast :param to_type: type to cast as :param default: default value if casting fails :return: casted value or given default/None """ try: return to_type(val) except (ValueError, TypeError): return default def safe_json(msg: Union[dict, str], encoders: Dict[Type, Callable[[Any], Any]] = None, *args, **kwargs) -> Union[dict, str]: # pylint: disable=keyword-arg-before-vararg """ Load JSON data if given a str and able Dump JSON data otherwise, encoding using encoders & JSON Defaults :param msg: str JSON to attempt to load :param encoders: custom type encoding - Ex) -> {bytes: lambda b: b.decode('utf-8', 'backslashreplace')} :return: loaded JSON data or original str """ if isinstance(msg, str): try: return json.loads(msg, *args, **kwargs) except ValueError: return msg msg = default_encode(msg, encoders or {}) return json.dumps(msg, *args, **kwargs) def check_values(val: Any) -> Any: """ Check the value of given and attempt to convert it to a bool, int, float :param val: value to check :return: converted/original value """ if isinstance(val, str): if val.lower() in ("true", "false"): return safe_cast(val, bool, val) if re.match(r"^\d+\.\d+$", val): return safe_cast(val, float, val) if val.isdigit(): return safe_cast(val, int, val) return val def default_encode(itm: Any, encoders: Dict[Type, Callable[[Any], Any]] = None) -> Any: """ Default encode the given object to the predefined types :param itm: object to encode/decode, :param encoders: custom type encoding - Ex) -> {bytes: lambda b: b.decode('utf-8', 'backslashreplace')} :return: default system encoded object """ if encoders and isinstance(itm, tuple(encoders.keys())): return encoders[type(itm)](itm) if isinstance(itm, dict): return {default_encode(k): default_encode(v, encoders) for k, v in itm.items()} if isinstance(itm, (list, set, tuple)): return type(itm)(default_encode(i, encoders) for i in itm) if isinstance(itm, (int, float)): return itm return toStr(itm) def default_decode(itm: Any, decoders: Dict[Type, Callable[[Any], Any]] = None) -> Any: """ Default decode the given object to the predefined types :param itm: object to encode/decode, :param decoders: custom type decoding - Ex) -> {bytes: lambda b: b.decode('utf-8', 'backslashreplace')} :return: default system encoded object """ print(itm) if decoders and isinstance(itm, tuple(decoders.keys())): return decoders[type(itm)](itm) if isinstance(itm, dict): return {default_decode(k, decoders): default_decode(v, decoders) for k, v in itm.items()} if isinstance(itm, (list, set, tuple)): return type(itm)(default_decode(i, decoders) for i in itm) if isinstance(itm, (int, float)): return itm if isinstance(itm, str): return check_values(itm) return itm # Utility Classes
29.5
170
0.629651
import base64 import binascii import json import re import struct import sys import uuid from typing import ( Any, Callable, Dict, Type, Union ) # Util Functions def toStr(s: Any) -> str: """ Convert a given type to a default string :param s: item to convert to a string :return: converted string """ return s.decode(sys.getdefaultencoding(), 'backslashreplace') if hasattr(s, 'decode') else str(s) def prefixUUID(pre: str = 'PREFIX', max_len: int = 30) -> str: """ Prefix a uuid with the given prefix with a max length :param pre: prefix str :param max_len: max length of prefix + UUID :return: prefixed UUID """ uid_max = max_len - (len(pre) + 10) uid = str(uuid.uuid4()).replace('-', '')[:uid_max] return f'{pre}-{uid}'[:max] def safe_cast(val: Any, to_type: Type, default: Any = None) -> Any: """ Cast the given value to the goven type safely without an exception being thrown :param val: value to cast :param to_type: type to cast as :param default: default value if casting fails :return: casted value or given default/None """ try: return to_type(val) except (ValueError, TypeError): return default def safe_json(msg: Union[dict, str], encoders: Dict[Type, Callable[[Any], Any]] = None, *args, **kwargs) -> Union[dict, str]: # pylint: disable=keyword-arg-before-vararg """ Load JSON data if given a str and able Dump JSON data otherwise, encoding using encoders & JSON Defaults :param msg: str JSON to attempt to load :param encoders: custom type encoding - Ex) -> {bytes: lambda b: b.decode('utf-8', 'backslashreplace')} :return: loaded JSON data or original str """ if isinstance(msg, str): try: return json.loads(msg, *args, **kwargs) except ValueError: return msg msg = default_encode(msg, encoders or {}) return json.dumps(msg, *args, **kwargs) def check_values(val: Any) -> Any: """ Check the value of given and attempt to convert it to a bool, int, float :param val: value to check :return: converted/original value """ if isinstance(val, str): if val.lower() in ("true", "false"): return safe_cast(val, bool, val) if re.match(r"^\d+\.\d+$", val): return safe_cast(val, float, val) if val.isdigit(): return safe_cast(val, int, val) return val def default_encode(itm: Any, encoders: Dict[Type, Callable[[Any], Any]] = None) -> Any: """ Default encode the given object to the predefined types :param itm: object to encode/decode, :param encoders: custom type encoding - Ex) -> {bytes: lambda b: b.decode('utf-8', 'backslashreplace')} :return: default system encoded object """ if encoders and isinstance(itm, tuple(encoders.keys())): return encoders[type(itm)](itm) if isinstance(itm, dict): return {default_encode(k): default_encode(v, encoders) for k, v in itm.items()} if isinstance(itm, (list, set, tuple)): return type(itm)(default_encode(i, encoders) for i in itm) if isinstance(itm, (int, float)): return itm return toStr(itm) def default_decode(itm: Any, decoders: Dict[Type, Callable[[Any], Any]] = None) -> Any: """ Default decode the given object to the predefined types :param itm: object to encode/decode, :param decoders: custom type decoding - Ex) -> {bytes: lambda b: b.decode('utf-8', 'backslashreplace')} :return: default system encoded object """ print(itm) if decoders and isinstance(itm, tuple(decoders.keys())): return decoders[type(itm)](itm) if isinstance(itm, dict): return {default_decode(k, decoders): default_decode(v, decoders) for k, v in itm.items()} if isinstance(itm, (list, set, tuple)): return type(itm)(default_decode(i, decoders) for i in itm) if isinstance(itm, (int, float)): return itm if isinstance(itm, str): return check_values(itm) return itm def isBase64(sb: Union[bytes, str]) -> bool: try: if isinstance(sb, str): # If there's any unicode here, an exception will be thrown and the function will return false sb_bytes = bytes(sb, 'ascii') elif isinstance(sb, bytes): sb_bytes = sb else: raise ValueError("Argument must be string or bytes") return base64.b64encode(base64.b64decode(sb_bytes)) == sb_bytes except (binascii.Error, ValueError): return False def floatByte(num: Union[float, bytes]) -> Union[float, bytes]: if isinstance(num, float): return struct.pack("!f", num) if isinstance(num, bytes) and len(num) == 4: return struct.unpack("!f", num)[0] return num def floatString(num: Union[float, str]) -> Union[float, str]: if isinstance(num, float): return f"f{num}" if isinstance(num, str) and num.startswith("f") and num[1:].replace(".", "", 1).isdigit(): return float(num[1:]) return num # Utility Classes
945
0
69
994fbf1a06a98785c519373eb80211528ef9f780
1,363
py
Python
src/elevatorChecker.py
wennycooper/cross_map_navigation
01564cda841603b7cc81b7bfd10ea0cae1c5a4b7
[ "Apache-2.0" ]
null
null
null
src/elevatorChecker.py
wennycooper/cross_map_navigation
01564cda841603b7cc81b7bfd10ea0cae1c5a4b7
[ "Apache-2.0" ]
null
null
null
src/elevatorChecker.py
wennycooper/cross_map_navigation
01564cda841603b7cc81b7bfd10ea0cae1c5a4b7
[ "Apache-2.0" ]
null
null
null
#!/usr/bin/env python from threading import Timer import rospy from geometry_msgs.msg import Twist, Pose2D, PoseStamped from std_msgs.msg import * from move_base_msgs.msg import * from actionlib_msgs.msg import * from apriltags_ros.msg import * avalability = False tagOne = False tagTwo = False checkCBPub = rospy.Publisher('/checkEVcb',Bool,queue_size=1) if __name__=="__main__": rospy.init_node('elevator_checker') rospy.Subscriber('/camera_rear/tag_detections',AprilTagDetectionArray,detectionCB) rospy.Subscriber('/checkEV',Bool,chekc_elevator) rospy.spin()
23.101695
86
0.644901
#!/usr/bin/env python from threading import Timer import rospy from geometry_msgs.msg import Twist, Pose2D, PoseStamped from std_msgs.msg import * from move_base_msgs.msg import * from actionlib_msgs.msg import * from apriltags_ros.msg import * avalability = False tagOne = False tagTwo = False checkCBPub = rospy.Publisher('/checkEVcb',Bool,queue_size=1) def detectionCB(tagArray): global tagOne, tagTwo if len(tagArray.detections) != 0: for tag in tagArray.detections: if tag.id == 1: tagOne = True print 'tag one OK' elif tag.id == 2: tagTwo= True print 'tag two OK' else: pass else: return return def chekc_elevator(msg): global tagOne, tagTwo tagOne = False tagTwo = False t = Timer(3,chekc_elevatorCB) t.daemon = True t.start() return def chekc_elevatorCB(): global tagOne, tagTwo, checkCBPub print str(tagOne),str(tagTwo) if tagOne and tagTwo: checkCBPub.publish(True) else: checkCBPub.publish(False) return if __name__=="__main__": rospy.init_node('elevator_checker') rospy.Subscriber('/camera_rear/tag_detections',AprilTagDetectionArray,detectionCB) rospy.Subscriber('/checkEV',Bool,chekc_elevator) rospy.spin()
705
0
73
26864c90522bcced2776b665faf31d612440e695
1,897
py
Python
beorn_lib/dialog/base/field_element.py
PAntoine/beorn_lib
a5bb8859acfb136f33559b6ddbf3bb20f61bd310
[ "MIT" ]
null
null
null
beorn_lib/dialog/base/field_element.py
PAntoine/beorn_lib
a5bb8859acfb136f33559b6ddbf3bb20f61bd310
[ "MIT" ]
null
null
null
beorn_lib/dialog/base/field_element.py
PAntoine/beorn_lib
a5bb8859acfb136f33559b6ddbf3bb20f61bd310
[ "MIT" ]
null
null
null
#!/usr/bin/env python # -*- coding: utf-8 -*- #--------------------------------------------------------------------------------- # # ,--. # | |-. ,---. ,---. ,--.--.,--,--, # | .-. '| .-. :| .-. || .--'| \ # | `-' |\ --.' '-' '| | | || | # `---' `----' `---' `--' `--''--' # # file: field_element # desc: Base class for the field element. # # author: Peter Antoine # date: 11/09/2015 #--------------------------------------------------------------------------------- # Copyright (c) 2015 Peter Antoine # All rights Reserved. # Released Under the MIT Licence #--------------------------------------------------------------------------------- import beorn_lib.dialog from beorn_lib.dialog.base.element import ElementItem REQUIRED_PARAMETERS = [ 'height', 'items' ] # vim: ts=4 sw=4 noexpandtab nocin ai
28.313433
82
0.489193
#!/usr/bin/env python # -*- coding: utf-8 -*- #--------------------------------------------------------------------------------- # # ,--. # | |-. ,---. ,---. ,--.--.,--,--, # | .-. '| .-. :| .-. || .--'| \ # | `-' |\ --.' '-' '| | | || | # `---' `----' `---' `--' `--''--' # # file: field_element # desc: Base class for the field element. # # author: Peter Antoine # date: 11/09/2015 #--------------------------------------------------------------------------------- # Copyright (c) 2015 Peter Antoine # All rights Reserved. # Released Under the MIT Licence #--------------------------------------------------------------------------------- import beorn_lib.dialog from beorn_lib.dialog.base.element import ElementItem REQUIRED_PARAMETERS = [ 'height', 'items' ] class FieldElement(ElementItem): def __init__(self, parameters): """ Init """ # defaults for a FieldElement self.width = 32 self.read_only = False self.input_type = 'text' # now bring in the parameters - may override the defaults super(FieldElement, self).__init__(parameters) @classmethod def create(cls, parameters): """ create This function will create a TextFieldElement. As the parameters are validated before the element is created. """ result = None # Ok, all the required parameters exist. result = cls(parameters) # option parameters if 'input_type' in parameters: if parameters['input_type'] in ['text', 'numeric', 'secret', 'error']: result.input_type = parameters['input_type'] if result: # error fields are always read-only if result.input_type == 'error': result.read_only = True result.loadDefault() return result # vim: ts=4 sw=4 noexpandtab nocin ai
0
877
23
52f575289ebdd1210d2528436783985cff1f850b
32,153
py
Python
databaseobjects.py
judev1/sqlitewrapper
4506c7d51bb8387865443194f690f35ee9d7c823
[ "MIT" ]
3
2021-08-31T18:33:43.000Z
2022-01-10T16:26:58.000Z
databaseobjects.py
judev1/sqlitewrapper
4506c7d51bb8387865443194f690f35ee9d7c823
[ "MIT" ]
1
2021-08-31T20:31:37.000Z
2021-09-01T10:53:59.000Z
databaseobjects.py
judev1/sqlitewrapper
4506c7d51bb8387865443194f690f35ee9d7c823
[ "MIT" ]
null
null
null
import sqlite3 from sqlite3.dbapi2 import DataError import threading import random import string from .datatypes import * from .errors import * # TODO: in-code documentation # TODO: pragma values QueryObjects = (RawReadObject, RawWriteObject, CreateTableObject, AddColumnObject, AddRowObject, RemoveRowObject, GetObject, SetObject) LogicObjects = (RemoveRowObject, GetObject, SetObject) WriteObjects = (RawWriteObject, CreateTableObject, AddColumnObject, AddRowObject, RemoveRowObject, SetObject)
31.491675
104
0.580755
import sqlite3 from sqlite3.dbapi2 import DataError import threading import random import string from .datatypes import * from .errors import * # TODO: in-code documentation def database(path, table=None, daemon=True, await_completion=True): database = DatabaseObject(path, daemon, await_completion) if not table: return database return TableObject(database, table) def _serial(): serial = "" while len(serial) != 8: serial += random.choice(string.hexdigits) return serial class ExecuctionObject: _toRead = list() _toWrite = list() _awaited = list() _results = dict() def __init__(self): super(ExecuctionObject, self).__init__() if not isinstance(self, DatabaseObject): raise InstanceError("instance is not a DatabaseObject") def waitForQueue(self): while self.alive: if not self._toRead and not self._toWrite: return raise DatabaseError("cannot wait for queue in closed database") def _read(self, object): object.serial = _serial() self._toRead.append(object) self._awaitCompletion(object, False) return self._getResults(object) def _write(self, object): object.serial = _serial() self._toWrite.append(object) self._awaitCompletion(object, False) def _awaitCompletion(self, object, preference): await_completion = preference if object.await_completion is not None: await_completion = object.await_completion elif self.await_completion is not None: await_completion = self.await_completion if not await_completion: return while self.alive: if object.serial in self._awaited: index = self._awaited.index(object.serial) self._awaited.pop(index) return raise DatabaseError("cannot await completion from closed database") def _getResults(self, object): while self.alive: if object.serial in self._results: result = self._results[object.serial] del self._results[object.serial] return result raise DatabaseError("cannot retrieve data from closed database") def _simplify(self, object, result): if len(object.items) != 1: return False if object.items[0] == "*": return False if result is None: return False return True def _execute(self, object): if not isinstance(object, QueryObjects): raise InstanceError("instance is not a valid QueryObject") failed = True cursor = self.connection.cursor() try: cursor.execute(object.query, tuple(object.inputs)) failed = False except sqlite3.OperationalError as exception: error_message = exception.args[0] except sqlite3.IntegrityError as exception: error_message = exception.args[0] if failed: inputs = list() for input in object.inputs: if not isinstance(input, (str, blob)): inputs.append(str(input)) continue inputs.append("'" + str(input) + "'") raise QueryError(error_message, object.query, inputs) if isinstance(object, RawReadObject): result = cursor.fetchall() self._results[object.serial] = result if isinstance(object, GetObject): if object.get_type == "first": result = cursor.fetchone() if self._simplify(object, result): result = result[0] elif object.get_type == "all": result = cursor.fetchall() # TODO: simplify single row lists if self._simplify(object, result): pass self._results[object.serial] = result cursor.close() if isinstance(object, WriteObjects): self.connection.commit() if object.await_completion or (object.await_completion is None and self.await_completion): self._awaited.append(object.serial) def _executions(self): while self.alive: if self._toRead: object = self._toRead[0] self._execute(object) index = self._toRead.index(object) self._toRead.pop(index) elif self._toWrite: object = self._toWrite[0] self._execute(object) index = self._toWrite.index(object) self._toWrite.pop(index) # TODO: pragma values class DatabaseObject(ExecuctionObject): alive = False def __init__(self, path, daemon=True, await_completion=True): super(DatabaseObject, self).__init__() if not path.endswith(".pydb"): path += ".pydb" self.path = path self.name = path.replace("\\", "/").split("/")[-1][:-5] self.daemon = daemon self.await_completion = await_completion self.start() def table(self, name): table = TableObject(self, name) if not table.exists: raise TableError("table does not exist") return table def create(self, name, columns=None, await_completion=True, must_not_exist=False, **kwargs): if must_not_exist: if TableObject(self, name).exists: raise TableError("table already exists") return CreateTableObject(self, name, columns, **kwargs).run(await_completion) # TODO: optimse database def optimise(self): raise NotImplemented("database optimising has not yet been implemented") @property def tables(self): self.waitForQueue() query = f"SELECT name FROM sqlite_master WHERE type='table'" tables = list() for item in RawReadObject(query, database=self).run(): tables.append(item[0]) return tables @property def queue(self): return len(self._toRead + self._toWrite) def start(self): if self.alive: raise DataError("DatabaseObject has already been started") self.alive = True threading.Thread(target=self._executions, daemon=self.daemon).start() self.connection = sqlite3.connect(self.path, check_same_thread=False) def close(self, ignore_queue=False): if not self.alive: raise DataError("DatabaseObject is already closed")# if not ignore_queue: self.waitForQueue() self.alive = False self._toRead = list() self._toWrite = list() self.connection.close() def __enter__(self): return self def __exit__(self, *args): self.close() def __repr__(self): tables = len(self.tables()) return f"<{self.name} database object: {tables} tables>" class TableObject: def __init__(self, database, table): super(TableObject, self).__init__() if not isinstance(database, DatabaseObject): raise InstanceError("instance is not a DatabaseObject") self.database = database self.name = table def __enter__(self): return self def __exit__(self, *args): self.database.close() def rename(self, name): if name in self.database.tables: raise TableError("table already exists") query = f"ALTER TABLE {self.name} RENAME TO '{name}'" RawWriteObject(query, table=self).run() self.name = name def delete(self): query = f"DROP TABLE {self.name}" RawWriteObject(query, table=self).run() del self def addColumn(self, *values, **kwargs): # TODO: refitting table AddColumnObject(self, values, refit=False, **kwargs).run() # TODO: remove column def removeColumn(self): raise NotImplemented("removing columns has not yet been implemented") def add(self, values=None, **kwargs): AddRowObject(self, values, **kwargs).run() def remove(self): return RemoveRowObject(self) def get(self, *items): return GetObject(self, "first", *items) getFirst = get def getAll(self, *items): return GetObject(self, "all", *items) def set(self, *values, **kwargs): return SetObject(self, *values, **kwargs) @property def exists(self): self.database.waitForQueue() query = f"SELECT name FROM sqlite_master WHERE type='table' AND name='{self.name}'" return bool(RawReadObject(query, table=self).run()) @property def columns(self): self.database.waitForQueue() query = f"SELECT name FROM PRAGMA_TABLE_INFO('{self.name}')" columns = list() for item in RawReadObject(query, table=self).run(): columns.append(item[0]) return columns @property def rows(self): self.database.waitForQueue() query = f"SELECT COUNT(*) AS count FROM {self.name}" return RawReadObject(query, table=self).run()[0][0] def __repr__(self): columns = len(self.columns) return f"<{self.name} table object: {columns} columns, {self.rows} rows>" class QueryObject: def __init__(self): super(QueryObject, self).__init__() if not isinstance(self, QueryObjects): raise InstanceError("instance is not a valid QueryObject") def run(self, await_completion=None): if not self.database.alive: raise DatabaseError("cannot run query in a closed database") self.await_completion = await_completion return self._run() async def asyncRun(self): return self.run(await_completion=True) @property def query(self): if not isinstance(self, QueryObjects): raise InstanceError("instance is not a valid QueryObject") self.inputs = list() if hasattr(self, "serial"): return self._query query = self._query for input in self.inputs: query = query.replace("?", input, 1) return query def __repr__(self): return f"<{self.type} query object>" class LogicObject: def __init__(self, object, item, conjunctive=None): super(LogicObject, self).__init__() if not isinstance(object, LogicObjects): raise InstanceError("instance is not a valid LogicObject") self.object = object self.item = item self.conjunctive = conjunctive def eq(self, value): self.operation = "=" self.value = value return self._filter equalto = equal = eq def neq(self, value): self.operation = "!=" self.value = value return self._filter notequalto = notequal = eq def gt(self, value): self._isNumber(value) self.operation = ">" self.value = value return self._filter greaterthan = gt def lt(self, value): self._isNumber(value) self.operation = "<" self.value = value return self._filter lessthan = lt def gteq(self, value): self._isNumber(value) self.operation = ">=" self.value = value return self._filter greaterthanorequalto = gteq def lteq(self, value): self._isNumber(value) self.operation = "<=" self.value = value return self._filter lessthanorequalto = lteq def like(self, value): self._isString(value) self.operation = "LIKE" self.value = value return self._filter def nlike(self, value): self._isString(value) self.operation = "NOT LIKE" self.value = value return self._filter notlike = nlike def contains(self, value): self._isString(value) self.operation = "LIKE" self.value = "%" + value + "%" return self._filter def ncontains(self, value): self._isString(value) self.operation = "NOT LIKE" self.value = "%" + value + "%" return self._filter notcontains = ncontains def startswith(self, value): self._isString(value) self.operation = "LIKE" self.value = value + "%" return self._filter def nstartswith(self, value): self._isString(value) self.operation = "NOT LIKE" self.value = value + "%" return self._filter notstartswith = nstartswith def endswith(self, value): self._isString(value) self.operation = "LIKE" self.value = "%" + value return self._filter def nendswith(self, value): self._isString(value) self.operation = "NOT LIKE" self.value = "%" + value return self._filter notendswith = nendswith def IN(self, *values): if isinstance(values[0], (list, tuple, set)): values = values[0] self.operation = "IN" self.value = values return self._filter def NOTIN(self, *values): if isinstance(values[0], (list, tuple, set)): values = values[0] self.operation = "NOT IN" self.value = values return self._filter def _isNumber(self, value): if not isinstance(value, (int, float)): raise TypeError("comparison number must be an integer or float") def _isString(self, value): if not isinstance(value, (str, blob)): raise TypeError("comparison item must be a string") @property def _filter(self): self.object.filtered.append(self) return self.object @property def _logic(self): logic = "" if self.conjunctive: logic += " " + self.conjunctive logic += f" {self.item} " + self.operation if self.operation in ["IN", "NOTIN"]: for value in self.value: self.object.inputs.append(value) logic += "(" + ", ".join("?" * len(self.value)) + ")" else: logic += " ?" self.object.inputs.append(self.value) return logic def __repr__(self): return f"<{self.object.type} logic object>" class FilterObject: def __init__(self): super(FilterObject, self).__init__() if not isinstance(self, QueryObject): raise InstanceError("instance is not a QueryObject") self.filtered = list() def where(self, item): if not self.filtered: return LogicObject(self, item) raise LogicError("already performing logic") def eq(self, value): assert self._isItem return LogicObject(self, self._getItem).eq(value) def neq(self, value): assert self._isItem return LogicObject(self, self._getItem).neq(value) def gt(self, value): assert self._isItem return LogicObject(self, self._getItem).gt(value) greaterthan = gt def lt(self, value): assert self._isItem return LogicObject(self, self._getItem).lt(value) lessthan = lt def gteq(self, value): assert self._isItem return LogicObject(self, self._getItem).gteq(value) greaterthanorequalto = gteq def lteq(self, value): assert self._isItem return LogicObject(self, self._getItem).lteq(value) lessthanorequalto = lteq def like(self, value): assert self._isItem return LogicObject(self, self._getItem).like(value) def nlike(self, value): assert self._isItem return LogicObject(self, self._getItem).nlike(value) def contains(self, value): assert self._isItem return LogicObject(self, self._getItem).contains(value) def ncontains(self, value): assert self._isItem return LogicObject(self, self._getItem).ncontains(value) notcontains = ncontains def startswith(self, value): assert self._isItem return LogicObject(self, self._getItem).startswith(value) def nstartswith(self, value): assert self._isItem return LogicObject(self, self._getItem).nstartswith(value) notstartswith = nstartswith def endswith(self, value): assert self._isItem return LogicObject(self, self._getItem).endswith(value) def nendswith(self, value): assert self._isItem return LogicObject(self, self._getItem).nendswith(value) notendswith = nendswith def IN(self, *values): assert self._isItem return LogicObject(self, self._getItem).IN(*values) def NOTIN(self, *values): assert self._isItem return LogicObject(self, self._getItem).NOTIN(*values) def AND(self, item): if self.filtered: return LogicObject(self, item, conjunctive="AND") raise LogicError("no item to perform logic on") def OR(self, item): if self.filtered: return LogicObject(self, item, conjunctive="OR") raise LogicError("no item to perform logic on") @property def _isItem(self): if not self.filtered: if len(self.items) == 1 and "*" not in self.items: return True raise LogicError("cannot perform logic on multiple items") raise LogicError("no item to perform logic on") @property def _getItem(self): if isinstance(self, GetObject): return self.items[0] elif isinstance(self, SetObject): return list(self.items.keys())[0] raise LogicError("instance cannot be used as a LogicObject") @property def _filter(self): if not self.filtered: return "" query = " WHERE" for filter in self.filtered: query += filter._logic return query class SortObject: def __init__(self): super(SortObject, self).__init__() if not isinstance(self, QueryObject): raise InstanceError("instance is not a valid QueryObject") self.order = "DESC" self.sorted = list() self.sortlimit = None def sort(self, *items): if isinstance(items[0], (list, tuple, set)): items = items[0] self.sorted = items return self def asc(self): if not self.sorted: raise SortError("items must be provided to sort by before using asc") self.order = "ASC" return self def desc(self): if not self.sorted: raise SortError("items must be provided to sort by before using desc") self.order = "DESC" return self def limit(self, limit): if not self.sorted: raise SortError("items must be provided to sort before providing a limit") self.sortlimit = limit return self def _sort(self): if not self.sorted: return "" statement = " ORDER BY " statement += ", ".join("?" * len(self.sorted)) self.inputs += self.sorted statement += " " + self.order if self.sortlimit is not None: statement += " LIMIT " + str(self.sortlimit) return statement class RawReadObject(QueryObject): type = "raw read" def __init__(self, rawquery, table=None, database=None): super(RawReadObject, self).__init__() if table is not None: if not isinstance(table, TableObject): raise InstanceError("instance is not a TableObject") database = table.database elif database is not None: if not isinstance(database, DatabaseObject): raise InstanceError("instance is not a DatabaseObject") self.database = database self.rawquery = rawquery def _run(self): return self.database._read(self) @property def _query(self): return self.rawquery class RawWriteObject(QueryObject): type = "raw write" def __init__(self, rawquery, table=None, database=None): super(RawWriteObject, self).__init__() if table is not None: if not isinstance(table, TableObject): raise InstanceError("instance is not a TableObject") database = table.database elif database is not None: if not isinstance(database, DatabaseObject): raise InstanceError("instance is not a DatabaseObject") self.database = database self.rawquery = rawquery def _run(self): return self.database._write(self) @property def _query(self): return self.rawquery class CreateTableObject(QueryObject): type = "create table" def __init__(self, database, table, columns, **kwargs): super(CreateTableObject, self).__init__() if not isinstance(database, DatabaseObject): raise InstanceError("instance is not a DatabaseObject") if not (columns or kwargs): raise InputError("you must provide columns for the table") if kwargs: columns = kwargs items = dict() for item in columns: value = columns[item] if isinstance(value, primary): if value.autoincrement and value.type is not int: raise TypeError("primary keys with autoincrementation must be integers") elif value.type not in [str, blob, int, float]: raise TypeError(f"'{value.type}' is an invalid data type") items[item] = value elif isinstance(value, (unique, default, null, notnull)): if value.type not in [str, blob, int, float]: raise TypeError(f"'{value.type}' is an invalid data type") items[item] = value elif value in [primary, str, blob, int, float]: items[item] = null(value) else: raise TypeError(f"'{value}' is an invalid data type") self.database = database self.name = table self.items = items def _run(self): self.database._write(self) return TableObject(self.database, self.name) @property def _query(self): query = f"CREATE TABLE IF NOT EXISTS {self.name} (" lines = list() primary_count = 0 for item in self.items: value = self.items[item] if value.type is primary: primary_count += 1 elif isinstance(value, primary): primary_count += 1 primaries = list() for item in self.items: line = item + " " value = self.items[item] if value.type is str: line += "TEXT" elif value.type is int: line += "INTEGER" elif value.type is float: line += "REAL" elif value.type is blob: line += "BLOB" elif value.type is primary: line += "INTEGER" if primary_count == 1: line += " PRIMARY KEY" else: line += " NOT NULL" primaries.append(item) if isinstance(value, primary): if value.autoincrement: if primary_count == 1: line += " PRIMARY KEY AUTOINCREMENT" else: raise TypeError("cannot autoincrement primary key with two or more prmary keys." " Try using the UNIQUE constraint for the other keys") else: line += " NOT NULL" primaries.append(item) elif isinstance(value, default): line += " DEFAULT " if value.type in [str, blob]: line += "'" + value.value + "'" elif value.type in [int, float]: line += str(value.value) elif isinstance(value, unique): line += " UNIQUE" elif isinstance(value, notnull): line += " NOT NULL" lines.append(line) query += ", ".join(lines) if primaries: query += ", PRIMARY KEY (" + ", ".join(primaries) + ")" query += ")" return query class AddColumnObject(QueryObject): type = "add column" def __init__(self, table, values, refit=False, **kwargs): super(AddColumnObject, self).__init__() if not isinstance(table, TableObject): raise InstanceError("instance is not a TableObject") if not (values or kwargs): raise InputError("you must provide values to be added") if kwargs: values = kwargs name = list(values.keys())[0] value = values[name] if isinstance(value, primary): if value.autoincrement and value.type is not int: raise TypeError("primary keys with autoincrementation must be integers") elif value.type not in [str, blob, int, float]: raise TypeError(f"'{value.type}' is an invalid data type") elif isinstance(value, (unique, default, null, notnull)): if value.type not in [str, blob, int, float]: raise TypeError(f"'{value.type}' is an invalid data type") elif value in [primary, str, blob, int, float]: value = null(value) else: raise TypeError(f"'{value}' is an invalid data type") if name in table.columns: raise TableError("column already exists") self.database = table.database self.table = table self.refit = refit self.name = name self.value = value def andAdd(self, **kwargs): for item in kwargs: self.items[item] = kwargs[item] return self def _run(self): return self.database._write(self) @property def _query(self): if not self.refit: query = f"ALTER TABLE {self.table.name} " query += f"ADD COLUMN {self.name} " value = self.value if value.type is str: query += "TEXT" elif value.type is int: query += "INTEGER" elif value.type is float: query += "REAL" elif value.type is blob: query += "BLOB" elif value.type is primary: query += "INTEGER PRIMARY KEY" if isinstance(value, primary): if value.autoincrement: raise TypeError("cannot add an autoincrement value to a new column") query += " PRIMARY KEY" elif isinstance(value, default): query += " DEFAULT " if value.type in [str, blob]: query += "'" + value.value + "'" elif value.type in [int, float]: query += str(value.value) elif isinstance(value, unique): raise TypeError("cannot add a unique value to a new column") elif isinstance(value, notnull): raise TypeError("cannot add a not null value to a new column") return query class AddRowObject(QueryObject): type = "add row" def __init__(self, table, values, **kwargs): super(AddRowObject, self).__init__() if not isinstance(table, TableObject): raise InstanceError("instance is not a TableObject") if not (values or kwargs): raise InputError("you must provide values to be added") if kwargs: values = kwargs items = dict() for item in values: items[item] = values[item] self.database = table.database self.table = table self.items = items # essentially useless def andAdd(self, **kwargs): for item in kwargs: self.items[item] = kwargs[item] return self def _run(self): return self.database._write(self) @property def _query(self): query = f"INSERT INTO {self.table.name} ({', '.join(self.items)}) " query += f"VALUES ({', '.join('?' * len(self.items))})" self.inputs = list(self.items.values()) return query class RemoveRowObject(QueryObject, FilterObject): type = "remove row" def __init__(self, table): super(RemoveRowObject, self).__init__() if not isinstance(table, TableObject): raise InstanceError("instance is not a TableObject") self.database = table.database self.table = table def _run(self): return self.database._write(self) @property def _query(self): query = f"DELETE FROM {self.table.name}" return query + self._filter class GetObject(QueryObject, FilterObject, SortObject): type = "get row" def __init__(self, table, get_type, *items): super(GetObject, self).__init__() if not isinstance(table, TableObject): raise InstanceError("instance is not a TableObject") if get_type not in ["first", "all"]: raise TypeError("invalid get type") if not items: items = ["*"] elif isinstance(items[0], (list, tuple, set)): items = items[0] self.database = table.database self.table = table self.get_type = get_type self.items = items def andGet(self, *items): if "*" in self.items: return self if isinstance(items[0], (list, tuple, set)): items = items[0] self.items += items return self def _run(self): return self.database._read(self) @property def _query(self): query = f"SELECT {', '.join(self.items)} FROM {self.table.name}" return query + self._filter + self._sort() class SetObject(QueryObject, FilterObject, SortObject): type = "set row" def __init__(self, table, values=None, **kwargs): super(SetObject, self).__init__() if not isinstance(table, TableObject): raise InstanceError("instance is not a TableObject") if not (values or kwargs): raise InputError("you must provide values to be set") if kwargs: values = kwargs items = dict() for item in values: items[item] = values[item] self.database = table.database self.table = table self.items = items def andSet(self, **kwargs): for item in kwargs: self.items[item] = kwargs[item] return self def _run(self): return self.database._write(self) @property def _query(self): query = f"UPDATE {self.table.name} SET " items = list() for item in self.items: value = self.items[item] if isinstance(value, (str, blob, int, float)): if isinstance(value, blob): value = value.value items.append(f"{item}=?") self.inputs.append(value) elif isinstance(value, increment): items.append(f"{item}={item}+?") self.inputs.append(value.increment) elif isinstance(value, concatenate): items.append(f"{item}={item} || ?") self.inputs.append(value.concatenate) elif value is null or isinstance(value, null): items.append(f"{item}=NULL") else: raise TypeError(f"'{type(value)}' is an invalid data type") return query + ", ".join(items) + self._filter + self._sort() QueryObjects = (RawReadObject, RawWriteObject, CreateTableObject, AddColumnObject, AddRowObject, RemoveRowObject, GetObject, SetObject) LogicObjects = (RemoveRowObject, GetObject, SetObject) WriteObjects = (RawWriteObject, CreateTableObject, AddColumnObject, AddRowObject, RemoveRowObject, SetObject)
26,676
4,360
552
c0daa3074cb06ba61b6b6a5474d78f1a3b93f764
413
py
Python
__examples__/correct_checksums/b.py
jeremywiebe/checksync
e626707492dbcb77fd1b13841e2f261b0c4796ba
[ "MIT" ]
15
2019-09-11T21:44:29.000Z
2022-01-24T12:54:59.000Z
__examples__/correct_checksums/b.py
jeremywiebe/checksync
e626707492dbcb77fd1b13841e2f261b0c4796ba
[ "MIT" ]
874
2019-09-03T20:17:16.000Z
2022-03-30T14:04:58.000Z
__examples__/correct_checksums/b.py
jeremywiebe/checksync
e626707492dbcb77fd1b13841e2f261b0c4796ba
[ "MIT" ]
2
2020-11-04T19:16:37.000Z
2021-06-02T21:30:34.000Z
# Test file in Python style # sync-start:correct 770446101 __examples__/correct_checksums/a.js code = 1 # sync-end:correct # sync-start:correct2 322927876 __examples__/correct_checksums/a.js genwebpack/khan-apollo/fragment-types.js genfiles/graphql_schema.json: $(shell find */graphql */*/graphql -name '*.py' -a ! -name '*_test.py') $(MAKE) update_secrets build/compile_graphql_schemas.py # sync-end:correct2
37.545455
142
0.774818
# Test file in Python style # sync-start:correct 770446101 __examples__/correct_checksums/a.js code = 1 # sync-end:correct # sync-start:correct2 322927876 __examples__/correct_checksums/a.js genwebpack/khan-apollo/fragment-types.js genfiles/graphql_schema.json: $(shell find */graphql */*/graphql -name '*.py' -a ! -name '*_test.py') $(MAKE) update_secrets build/compile_graphql_schemas.py # sync-end:correct2
0
0
0
7facb7933bd8ce6cda2b29652b8361ed79e2b8ab
130
py
Python
src/linakdeskapp/__main__.py
nilp0inter/LinakDeskApp
0cf287ee96002f5c270c087ba73b72c548baa8c5
[ "MIT" ]
121
2018-09-19T20:10:21.000Z
2022-03-31T08:07:33.000Z
src/feedsfix/__main__.py
anetczuk/thunderbird-feeds-recover
996536bada6961df87873313e2e4b9a6e1bb9431
[ "MIT" ]
13
2020-02-19T15:58:37.000Z
2022-03-05T03:20:42.000Z
src/feedsfix/__main__.py
anetczuk/thunderbird-feeds-recover
996536bada6961df87873313e2e4b9a6e1bb9431
[ "MIT" ]
12
2020-02-13T23:55:30.000Z
2022-01-30T15:11:31.000Z
## ## Entry file when package is used as the main program. ## if __name__ == '__main__': from .main import main main()
13
55
0.630769
## ## Entry file when package is used as the main program. ## if __name__ == '__main__': from .main import main main()
0
0
0
376d488896fc2ff1dc1e86ef65758221a5f8051d
783
py
Python
tests/test_multiple.py
abraia/abraia-python
e49e3869b2ee7e6b1bcb41e0cc1ae126ac39e202
[ "MIT" ]
4
2018-03-23T22:32:53.000Z
2020-08-25T12:42:00.000Z
tests/test_multiple.py
abraia/abraia-multiple
e49e3869b2ee7e6b1bcb41e0cc1ae126ac39e202
[ "MIT" ]
5
2021-02-18T20:29:09.000Z
2022-03-29T09:28:57.000Z
tests/test_multiple.py
abraia/abraia-python
e49e3869b2ee7e6b1bcb41e0cc1ae126ac39e202
[ "MIT" ]
1
2021-01-22T23:51:14.000Z
2021-01-22T23:51:14.000Z
import numpy as np from abraia import Multiple multiple = Multiple()
23.029412
55
0.706258
import numpy as np from abraia import Multiple multiple = Multiple() def test_load_image(): img = multiple.load_image('lion.jpg') assert isinstance(img, np.ndarray) def test_load_metadata(): meta = multiple.load_metadata('lion.jpg') assert meta['MIMEType'] == 'image/jpeg' def test_save_image(): img = multiple.load_image('lion.jpg') path = multiple.save_image('lion.png', img) assert path == 'lion.png' def test_load_tiff_image(): multiple.upload_file('images/AnnualCrop_1896.tiff') img = multiple.load_image('AnnualCrop_1896.tiff') assert isinstance(img, np.ndarray) def test_save_tiff_image(): img = multiple.load_image('AnnualCrop_1896.tiff') path = multiple.save_image('test.tiff', img) assert path == 'test.tiff'
592
0
115
07fb5058c7a297096cbf1ff7f21aedcf66b7d3ad
985
py
Python
shogitk/usikif.py
koji-hirono/pytk-shogi-replayer
a10819a797faecbee5c7b0654beb3694eb522840
[ "MIT" ]
null
null
null
shogitk/usikif.py
koji-hirono/pytk-shogi-replayer
a10819a797faecbee5c7b0654beb3694eb522840
[ "MIT" ]
null
null
null
shogitk/usikif.py
koji-hirono/pytk-shogi-replayer
a10819a797faecbee5c7b0654beb3694eb522840
[ "MIT" ]
null
null
null
# -*- coding: utf-8 -*- from __future__ import unicode_literals from shogitk.shogi import Coords, Move, BLACK, WHITE, DROP, PROMOTE RANKNUM = { 'a': 1, 'b': 2, 'c': 3, 'd': 4, 'e': 5, 'f': 6, 'g': 7, 'h': 8, 'i': 9 }
25.921053
74
0.450761
# -*- coding: utf-8 -*- from __future__ import unicode_literals from shogitk.shogi import Coords, Move, BLACK, WHITE, DROP, PROMOTE RANKNUM = { 'a': 1, 'b': 2, 'c': 3, 'd': 4, 'e': 5, 'f': 6, 'g': 7, 'h': 8, 'i': 9 } def decoder(f): color = [BLACK, WHITE] step = 0 for line in f: line = line.strip() if line[0] == '[': pass elif line[0].isdigit(): src = Coords(int(line[0]), RANKNUM[line[1]]) dst = Coords(int(line[2]), RANKNUM[line[3]]) if line[-1] == '+': modifier = PROMOTE else: modifier = None yield Move(color[step & 1], dst, src, None, modifier=modifier) step += 1 elif line[0].isupper(): dst = Coords(int(line[2]), RANKNUM[line[3]]) yield Move(color[step & 1], dst, None, line[0], modifier=DROP) step += 1
671
0
23
0b8b5527516fdb912956613a39b881648f901319
213
py
Python
doc/src/modules/mpmath/plots/bessely.py
shipci/sympy
4b59927bed992b980c9b3faac01becb36feef26b
[ "BSD-3-Clause" ]
319
2016-09-22T15:54:48.000Z
2022-03-18T02:36:58.000Z
doc/src/modules/mpmath/plots/bessely.py
shipci/sympy
4b59927bed992b980c9b3faac01becb36feef26b
[ "BSD-3-Clause" ]
9
2016-11-03T21:56:41.000Z
2020-08-09T19:27:37.000Z
doc/src/modules/mpmath/plots/bessely.py
shipci/sympy
4b59927bed992b980c9b3faac01becb36feef26b
[ "BSD-3-Clause" ]
27
2016-10-06T16:05:32.000Z
2022-03-18T02:37:00.000Z
# Bessel function of 2nd kind Y_n(x) on the real line for n=0,1,2,3 y0 = lambda x: bessely(0,x) y1 = lambda x: bessely(1,x) y2 = lambda x: bessely(2,x) y3 = lambda x: bessely(3,x) plot([y0,y1,y2,y3],[0,10],[-4,1])
35.5
67
0.643192
# Bessel function of 2nd kind Y_n(x) on the real line for n=0,1,2,3 y0 = lambda x: bessely(0,x) y1 = lambda x: bessely(1,x) y2 = lambda x: bessely(2,x) y3 = lambda x: bessely(3,x) plot([y0,y1,y2,y3],[0,10],[-4,1])
0
0
0
a7bdc9328f5e2ca030f44bdfe27a9bb538f3ee6b
2,442
py
Python
h5flow/modules/__init__.py
peter-madigan/h5flow
b90e93677c6a45495e989cf578c96ddf42ffb3c8
[ "MIT" ]
null
null
null
h5flow/modules/__init__.py
peter-madigan/h5flow
b90e93677c6a45495e989cf578c96ddf42ffb3c8
[ "MIT" ]
7
2021-05-21T20:23:22.000Z
2021-11-24T21:06:34.000Z
h5flow/modules/__init__.py
peter-madigan/h5flow
b90e93677c6a45495e989cf578c96ddf42ffb3c8
[ "MIT" ]
1
2021-08-13T21:46:05.000Z
2021-08-13T21:46:05.000Z
from inspect import isclass import os import importlib.util import sys import logging from pkgutil import iter_modules def find_class(classname, directory): ''' Search the specified directory for a file containing a python implementation with the specified class name :param classname: class name to look for :param directory: directory to search for ``*.py`` files describing the class :returns: ``class`` object of matching desired class (if found), or ``None`` (if not found) ''' path = directory for (finder, name, _) in iter_modules([path]): if name == 'setup' or name == 'h5flow': continue try: spec = finder.find_spec(name) module = importlib.util.module_from_spec(spec) sys.modules[name] = module spec.loader.exec_module(module) for attribute_name in dir(module): attribute = getattr(module, attribute_name) if isclass(attribute): if attribute_name == classname: logging.info(f'Using {classname} from {directory}/{name}.py') return attribute except Exception as e: logging.debug(f'Encountered import error: {e}') return None def get_class(classname): ''' Look in current directory, ``./h5flow_modules/``, and ``h5flow/modules/`` for the specified class. Raises a ``RuntimeError`` if class can't be found in any of those directories. :param classname: class name to search for :returns: ``class`` object of desired class ''' # first search in local directory found_class = find_class(classname, './') if found_class is None: # then recurse into subdirectories if found_class is None: for parent, dirs, files in os.walk('./'): for directory in dirs: found_class = find_class(classname, os.path.join(parent, directory)) if found_class is not None: break if found_class is not None: break if found_class is None: # then search in source found_class = find_class(classname, os.path.dirname(__file__)) if found_class is None: raise RuntimeError(f'no matching class {classname} found!') return found_class
33
99
0.599509
from inspect import isclass import os import importlib.util import sys import logging from pkgutil import iter_modules def find_class(classname, directory): ''' Search the specified directory for a file containing a python implementation with the specified class name :param classname: class name to look for :param directory: directory to search for ``*.py`` files describing the class :returns: ``class`` object of matching desired class (if found), or ``None`` (if not found) ''' path = directory for (finder, name, _) in iter_modules([path]): if name == 'setup' or name == 'h5flow': continue try: spec = finder.find_spec(name) module = importlib.util.module_from_spec(spec) sys.modules[name] = module spec.loader.exec_module(module) for attribute_name in dir(module): attribute = getattr(module, attribute_name) if isclass(attribute): if attribute_name == classname: logging.info(f'Using {classname} from {directory}/{name}.py') return attribute except Exception as e: logging.debug(f'Encountered import error: {e}') return None def get_class(classname): ''' Look in current directory, ``./h5flow_modules/``, and ``h5flow/modules/`` for the specified class. Raises a ``RuntimeError`` if class can't be found in any of those directories. :param classname: class name to search for :returns: ``class`` object of desired class ''' # first search in local directory found_class = find_class(classname, './') if found_class is None: # then recurse into subdirectories if found_class is None: for parent, dirs, files in os.walk('./'): for directory in dirs: found_class = find_class(classname, os.path.join(parent, directory)) if found_class is not None: break if found_class is not None: break if found_class is None: # then search in source found_class = find_class(classname, os.path.dirname(__file__)) if found_class is None: raise RuntimeError(f'no matching class {classname} found!') return found_class
0
0
0
0f7f3a5f87b4462c9b5d7faab0e44b67fbe81c22
1,182
py
Python
nameless/__main__.py
ElliotPenson/Nameless
54bf7a4d2e8fe6bf73722938970cb1d8c509c97d
[ "MIT" ]
6
2017-08-14T17:22:29.000Z
2022-01-02T14:54:13.000Z
nameless/__main__.py
ElliotPenson/nameless
54bf7a4d2e8fe6bf73722938970cb1d8c509c97d
[ "MIT" ]
1
2020-04-13T22:00:40.000Z
2022-02-24T23:24:12.000Z
nameless/__main__.py
ElliotPenson/nameless
54bf7a4d2e8fe6bf73722938970cb1d8c509c97d
[ "MIT" ]
2
2017-10-01T17:09:18.000Z
2019-05-20T06:12:42.000Z
#!/usr/bin/python # -*- coding: UTF-8 -*- """ main.py @author ejnp """ from lexer import Lexer from parser import Parser, ParserError from visitors import BetaReduction def interpret(input_string, print_reductions=False): """Performs normal order reduction on the given string lambda calculus expression. Returns the expression's normal form if it exists. """ lexer = Lexer(input_string) try: ast = Parser(lexer).parse() except ParserError as discrepancy: print 'ParseError: ' + discrepancy.message return None normal_form = False while not normal_form: reducer = BetaReduction() reduced_ast = reducer.visit(ast) normal_form = not reducer.reduced if print_reductions: print unicode(ast) ast = reduced_ast return unicode(ast) def main(): """Begins an interactive lambda calculus interpreter""" print "nameless!\nType 'quit' to exit." while True: read = raw_input('> ').decode('utf-8') if read == 'quit': break if read != '': interpret(read, print_reductions=True) if __name__ == '__main__': main()
24.122449
74
0.63621
#!/usr/bin/python # -*- coding: UTF-8 -*- """ main.py @author ejnp """ from lexer import Lexer from parser import Parser, ParserError from visitors import BetaReduction def interpret(input_string, print_reductions=False): """Performs normal order reduction on the given string lambda calculus expression. Returns the expression's normal form if it exists. """ lexer = Lexer(input_string) try: ast = Parser(lexer).parse() except ParserError as discrepancy: print 'ParseError: ' + discrepancy.message return None normal_form = False while not normal_form: reducer = BetaReduction() reduced_ast = reducer.visit(ast) normal_form = not reducer.reduced if print_reductions: print unicode(ast) ast = reduced_ast return unicode(ast) def main(): """Begins an interactive lambda calculus interpreter""" print "nameless!\nType 'quit' to exit." while True: read = raw_input('> ').decode('utf-8') if read == 'quit': break if read != '': interpret(read, print_reductions=True) if __name__ == '__main__': main()
0
0
0
98dcc11cfe8014ee9fb08412398f5c5c35e4a380
3,350
py
Python
basic/inlines/parser.py
neechadi/django-basic-apps
3a90090857549ea4198a72c44f45f6edb238e2a8
[ "BSD-3-Clause" ]
548
2015-01-02T21:41:29.000Z
2022-03-23T09:10:04.000Z
basic/inlines/parser.py
neechadi/django-basic-apps
3a90090857549ea4198a72c44f45f6edb238e2a8
[ "BSD-3-Clause" ]
4
2015-01-13T16:27:02.000Z
2016-11-01T01:51:31.000Z
basic/inlines/parser.py
neechadi/django-basic-apps
3a90090857549ea4198a72c44f45f6edb238e2a8
[ "BSD-3-Clause" ]
182
2015-01-02T21:41:29.000Z
2021-08-09T07:01:07.000Z
from django.template import TemplateSyntaxError from django.conf import settings from django.contrib.contenttypes.models import ContentType from django.http import Http404 from django.utils.encoding import smart_unicode from django.template.loader import render_to_string from django.utils.safestring import mark_safe def render_inline(inline): """ Replace inline markup with template markup that matches the appropriate app and model. """ # Look for inline type, 'app.model' try: app_label, model_name = inline['type'].split('.') except: if settings.DEBUG: raise TemplateSyntaxError, "Couldn't find the attribute 'type' in the <inline> tag." else: return '' # Look for content type try: content_type = ContentType.objects.get(app_label=app_label, model=model_name) model = content_type.model_class() except ContentType.DoesNotExist: if settings.DEBUG: raise TemplateSyntaxError, "Inline ContentType not found." else: return '' # Check for an inline class attribute try: inline_class = smart_unicode(inline['class']) except: inline_class = '' try: try: id_list = [int(i) for i in inline['ids'].split(',')] obj_list = model.objects.in_bulk(id_list) obj_list = list(obj_list[int(i)] for i in id_list) context = { 'object_list': obj_list, 'class': inline_class } except ValueError: if settings.DEBUG: raise ValueError, "The <inline> ids attribute is missing or invalid." else: return '' except KeyError: try: obj = model.objects.get(pk=inline['id']) context = { 'content_type':"%s.%s" % (app_label, model_name), 'object': obj, 'class': inline_class, 'settings': settings } except model.DoesNotExist: if settings.DEBUG: raise model.DoesNotExist, "%s with pk of '%s' does not exist" % (model_name, inline['id']) else: return '' except: if settings.DEBUG: raise TemplateSyntaxError, "The <inline> id attribute is missing or invalid." else: return '' template = ["inlines/%s_%s.html" % (app_label, model_name), "inlines/default.html"] rendered_inline = {'template':template, 'context':context} return rendered_inline
35.263158
134
0.624776
from django.template import TemplateSyntaxError from django.conf import settings from django.contrib.contenttypes.models import ContentType from django.http import Http404 from django.utils.encoding import smart_unicode from django.template.loader import render_to_string from django.utils.safestring import mark_safe def inlines(value, return_list=False): try: from BeautifulSoup import BeautifulStoneSoup except ImportError: from beautifulsoup import BeautifulStoneSoup content = BeautifulStoneSoup(value, selfClosingTags=['inline','img','br','input','meta','link','hr']) inline_list = [] if return_list: for inline in content.findAll('inline'): rendered_inline = render_inline(inline) inline_list.append(rendered_inline['context']) return inline_list else: for inline in content.findAll('inline'): rendered_inline = render_inline(inline) if rendered_inline: inline.replaceWith(render_to_string(rendered_inline['template'], rendered_inline['context'])) else: inline.replaceWith('') return mark_safe(content) def render_inline(inline): """ Replace inline markup with template markup that matches the appropriate app and model. """ # Look for inline type, 'app.model' try: app_label, model_name = inline['type'].split('.') except: if settings.DEBUG: raise TemplateSyntaxError, "Couldn't find the attribute 'type' in the <inline> tag." else: return '' # Look for content type try: content_type = ContentType.objects.get(app_label=app_label, model=model_name) model = content_type.model_class() except ContentType.DoesNotExist: if settings.DEBUG: raise TemplateSyntaxError, "Inline ContentType not found." else: return '' # Check for an inline class attribute try: inline_class = smart_unicode(inline['class']) except: inline_class = '' try: try: id_list = [int(i) for i in inline['ids'].split(',')] obj_list = model.objects.in_bulk(id_list) obj_list = list(obj_list[int(i)] for i in id_list) context = { 'object_list': obj_list, 'class': inline_class } except ValueError: if settings.DEBUG: raise ValueError, "The <inline> ids attribute is missing or invalid." else: return '' except KeyError: try: obj = model.objects.get(pk=inline['id']) context = { 'content_type':"%s.%s" % (app_label, model_name), 'object': obj, 'class': inline_class, 'settings': settings } except model.DoesNotExist: if settings.DEBUG: raise model.DoesNotExist, "%s with pk of '%s' does not exist" % (model_name, inline['id']) else: return '' except: if settings.DEBUG: raise TemplateSyntaxError, "The <inline> id attribute is missing or invalid." else: return '' template = ["inlines/%s_%s.html" % (app_label, model_name), "inlines/default.html"] rendered_inline = {'template':template, 'context':context} return rendered_inline
836
0
23
b643d0886806c4dd0b4e934d942a30b98ea669c2
1,015
py
Python
033/main.py
jasonmobley/euler-python
cd483da472e525be625c1fe0c791ac075bd3a3ef
[ "Unlicense" ]
null
null
null
033/main.py
jasonmobley/euler-python
cd483da472e525be625c1fe0c791ac075bd3a3ef
[ "Unlicense" ]
null
null
null
033/main.py
jasonmobley/euler-python
cd483da472e525be625c1fe0c791ac075bd3a3ef
[ "Unlicense" ]
null
null
null
from math import gcd fractions = list() for numerator in range(10, 100): for denominator in range(numerator+1, 100): actual = numerator / denominator a = numerator // 10 b = numerator % 10 c = denominator // 10 d = denominator % 10 if (b == 0 and d == 0) or (a == b and c == d) or (a != d and b != c): continue if (a == d and c != 0 and actual == b/c): fractions.append((numerator, denominator)) print('{0}/{1} == {2}/{3}'.format(numerator, denominator, a, c)) if (b == c and d != 0 and actual == a/d): fractions.append((numerator, denominator)) print('{0}/{1} == {2}/{3}'.format(numerator, denominator, a, c)) n_product = 1 d_product = 1 for f in fractions: print(f) n_product *= f[0] d_product *= f[1] greatest_divisor = gcd(n_product, d_product) final_denominator = d_product // greatest_divisor print(final_denominator)
24.756098
73
0.591133
from math import gcd def intFromList(l): n = 0 m = 1 for i in range(len(l)-1, -1, -1): n += m * l[i] m *= 10 return n fractions = list() for numerator in range(10, 100): for denominator in range(numerator+1, 100): actual = numerator / denominator a = numerator // 10 b = numerator % 10 c = denominator // 10 d = denominator % 10 if (b == 0 and d == 0) or (a == b and c == d) or (a != d and b != c): continue if (a == d and c != 0 and actual == b/c): fractions.append((numerator, denominator)) print('{0}/{1} == {2}/{3}'.format(numerator, denominator, a, c)) if (b == c and d != 0 and actual == a/d): fractions.append((numerator, denominator)) print('{0}/{1} == {2}/{3}'.format(numerator, denominator, a, c)) n_product = 1 d_product = 1 for f in fractions: print(f) n_product *= f[0] d_product *= f[1] greatest_divisor = gcd(n_product, d_product) final_denominator = d_product // greatest_divisor print(final_denominator)
91
0
23
688ee5545254622e1ce44b690ca4611724abbcc6
5,835
py
Python
datatables_ajax/datatables.py
ntbrown/django-datatables-ajax
33d7d2088f83b292ddc86bb04fb6d3198c64e384
[ "BSD-2-Clause" ]
null
null
null
datatables_ajax/datatables.py
ntbrown/django-datatables-ajax
33d7d2088f83b292ddc86bb04fb6d3198c64e384
[ "BSD-2-Clause" ]
null
null
null
datatables_ajax/datatables.py
ntbrown/django-datatables-ajax
33d7d2088f83b292ddc86bb04fb6d3198c64e384
[ "BSD-2-Clause" ]
null
null
null
import datetime import json from django.conf import settings from django.utils import timezone
36.93038
94
0.538817
import datetime import json from django.conf import settings from django.utils import timezone class DjangoDatatablesServerProc(object): def __init__(self, request, model, columns): """ model = StatoUtenzaCorso columns = ['pk', 'cliente', 'corso', 'altro', 'contattato_mediante', 'data_creazione', 'stato'] """ self.columns = columns self.model = model.objects if hasattr(model, 'objects') else model self.request = request self.method = 'POST' if request.POST.get('args') else 'GET' if self.method == 'POST': r = json.loads(request.POST.get('args')) import pprint pprint.pprint(r) print("R DEBUG ^") else: r = dict(request.GET) self.dt_ajax_request = r # queryset attributes self.aqs = None self.fqs = None # response object will be similar to this, but with datas! # Since DataTables never sends draw as 0, it should never be # returned as 0 (assuming that was the issue). As the documentation # says, it should be returned as the same value that was sent # (cast as an integer) self.order_col = None if self.method == 'GET': self.d = {'draw': int(self.dt_ajax_request['draw'][0]), 'recordsTotal': 0, 'recordsFiltered': 0, 'data': []} self.search_key = self.dt_ajax_request['search[value]'] self.order_col = self.dt_ajax_request.get('order[0][column]', None) self.order_dir = self.dt_ajax_request.get('order[0][dir]', None) else: # request.POST self.d = {'draw': int(self.dt_ajax_request['draw']), 'recordsTotal': 0, 'recordsFiltered': 0, 'data': []} self.search_key = self.dt_ajax_request['search']['value'] if len(self.dt_ajax_request['order']): self.order_col = self.dt_ajax_request['order'][0]['column'] self.order_dir = self.dt_ajax_request['order'][0]['dir'] self.lenght = self.dt_ajax_request['length'] self.start = self.dt_ajax_request['start'] # casting for field in ['lenght', 'start', 'search_key', 'order_col', 'order_dir']: attr = getattr(self, field) if isinstance(attr, list): setattr(self, field, attr[0]) else: setattr(self, field, attr) if isinstance(attr, int): continue if attr is not None and attr.isdigit(): v = getattr(self, field) setattr(self, field, int(v)) def get_queryset(self): """ Overload me. The query must be customized to get it work """ if self.search_key: self.aqs = self.model.objects.filter( Q(cliente__nome__icontains=self.search_key) | \ Q(cliente__cognome__icontains=self.search_key) | \ Q(cliente__nominativo__icontains=self.search_key) | \ Q(corso__nome__istartswith=self.search_key) | \ Q(contattato_mediante__nome__istartswith=self.search_key) | \ Q(altro__nome__istartswith=self.search_key)) else: self.aqs = self.model.objects.all() def get_ordering(self): """ overload me if you need different ordering approach """ if not self.aqs: self.get_queryset() # if lenght is -1 means ALL the records, sliceless if self.lenght == -1: self.lenght = self.aqs.count() # fare ordinamento qui # 'order[0][column]': ['2'], # bisogna mappare la colonna con il numero di sequenza eppoi # fare order_by if self.order_col: self.col_name = self.columns[self.order_col] if self.order_dir == 'asc': self.aqs = self.aqs.order_by(self.col_name) else: self.aqs = self.aqs.order_by('-'+self.col_name) def get_paging(self): # paging requirement self.get_ordering() self.fqs = self.aqs[self.start:self.start+self.lenght] def _make_aware(self, dt): if hasattr(dt, 'tzinfo') and dt.tzinfo != timezone.get_default_timezone(): return dt.astimezone(timezone.get_default_timezone()) return timezone.make_aware(dt, timezone=timezone.get_current_timezone()) def _dt_strftime_as_naive(self, dt): """ todo """ pass def fill_data(self): """ overload me if you need some clean up """ if not self.fqs: self.get_paging() for r in self.fqs: cleaned_data = [] for e in self.columns: # this avoid null json value v = getattr(r, e) if v: if isinstance(v, datetime.datetime): vrepr = self._make_aware(v).strftime(settings.DEFAULT_DATETIME_FORMAT) elif isinstance(v, datetime.date): vrepr = v.strftime(settings.DEFAULT_DATE_FORMAT) elif callable(v): vrepr = str(v()) else: vrepr = v.__str__() else: vrepr = '' cleaned_data.append(vrepr) self.d['data'].append( cleaned_data ) self.d['recordsTotal'] = self.model.count() self.d['recordsFiltered'] = self.aqs.count() def get_dict(self): if not self.d['data']: self.fill_data() return self.d
435
5,281
23
42710362f7c9593935a7f782e4bf40278b85164a
3,605
py
Python
src/modules/ZapBot/__init__.py
Icaro-G-Silva/Bot-Suite
d18e17ea0432524c71f83db7c83603eb88c0c3cd
[ "MIT" ]
null
null
null
src/modules/ZapBot/__init__.py
Icaro-G-Silva/Bot-Suite
d18e17ea0432524c71f83db7c83603eb88c0c3cd
[ "MIT" ]
null
null
null
src/modules/ZapBot/__init__.py
Icaro-G-Silva/Bot-Suite
d18e17ea0432524c71f83db7c83603eb88c0c3cd
[ "MIT" ]
null
null
null
from selenium import webdriver from selenium.webdriver.common.by import By from selenium.webdriver.support.ui import WebDriverWait from selenium.webdriver.support import expected_conditions as EC from datetime import datetime import time
40.055556
140
0.612205
from selenium import webdriver from selenium.webdriver.common.by import By from selenium.webdriver.support.ui import WebDriverWait from selenium.webdriver.support import expected_conditions as EC from datetime import datetime import time def verifyInput(message, sendTo): if type(message) != str or type(sendTo) != list: raise Exception(f"Invalid format for message:{type(message)} or sendTo:{type(sendTo)}\nNeed to be message:{str} and sendTo:{list}") def verifyTimeInput(hour, minute): if type(hour) != int or type(minute) != int: raise Exception(f"Invalid format for hour:{type(hour)} or minute:{type(minute)}\nNeed to be hour:{int} and minute:{int}") if hour > 23 or hour < 0: raise Exception(f"Hour:{hour} is not suitable to hour pattern 0 - 23") elif minute > 59 or minute < 0: raise Exception(f"Minute:{minute} is not suitable to minute pattern 0 - 59") def wait(seconds): time.sleep(seconds) class WhatsappBot: def __init__(self, message, sendTo): verifyInput(message, sendTo) self.message = message self.sendTo = sendTo self.cooldown = (0.005 * len(self.message)) self.time = [False, False] options = webdriver.ChromeOptions() options.add_argument('lang=pt-br') self.driver = webdriver.Chrome(executable_path=r'./chromedriver.exe') def connectToWhatsapp(self): self.driver.get("https://web.whatsapp.com/") try: WebDriverWait(self.driver, 10).until(EC.presence_of_element_located((By.ID, "pane-side"))) except: raise Exception("Take too time to load the page.") def quitFromWhatsappAndChrome(self): menu = self.driver.find_element_by_xpath(f"//*[@id='side']/header/div[2]/div/span/div[3]/div/span") menu.click() exitButton = self.driver.find_element_by_xpath(f"//*[@id='side']/header/div[2]/div/span/div[3]/span/div/ul/li[7]/div") exitButton.click() time.sleep(2) self.driver.close() self.driver.quit() def scheduleTime(self, hour = datetime.now().hour, minute = datetime.now().minute): verifyTimeInput(hour, minute) self.time = [hour, minute] def verifyTime(self): if not self.time[0] and not self.time[1]: return while True: time = datetime.now() if time.hour == self.time[0] and time.minute == self.time[1]: return def sendMessages(self, isFlood = False): if not isFlood: self.connectToWhatsapp() self.verifyTime() for contact in self.sendTo: contacts = self.driver.find_element_by_xpath(f"//span[@title='{contact}']") wait(self.cooldown) contacts.click() chatBox = self.driver.find_element_by_xpath(f"//*[@id='main']/footer/div[1]/div[2]/div/div[2]") wait(self.cooldown) chatBox.click() chatBox.send_keys(self.message) sendButton = self.driver.find_element_by_xpath(f"//*[@id='main']/footer/div[1]/div[3]/button/span") wait(self.cooldown) sendButton.click() wait(self.cooldown + 0.2) if not isFlood: time.sleep(3) self.quitFromWhatsappAndChrome() def sendFlood(self, times): self.connectToWhatsapp() self.verifyTime() for _ in range(0, times): self.sendMessages(True) time.sleep(3) self.quitFromWhatsappAndChrome()
3,041
-3
317
432b32f7744af2c2ec20833b2b229f79eee61e8a
1,424
py
Python
MiddleKit/Run/SQLiteObjectStore.py
PeaceWorksTechnologySolutions/w4py
74f5a03a63f1a93563502b908474aefaae2abda2
[ "MIT" ]
null
null
null
MiddleKit/Run/SQLiteObjectStore.py
PeaceWorksTechnologySolutions/w4py
74f5a03a63f1a93563502b908474aefaae2abda2
[ "MIT" ]
null
null
null
MiddleKit/Run/SQLiteObjectStore.py
PeaceWorksTechnologySolutions/w4py
74f5a03a63f1a93563502b908474aefaae2abda2
[ "MIT" ]
null
null
null
import sqlite3 as sqlite from SQLObjectStore import SQLObjectStore class SQLiteObjectStore(SQLObjectStore): """SQLiteObjectStore implements an object store backed by a SQLite database. See the SQLite docs or the DB API 2.0 docs for more information: https://docs.python.org/2/library/sqlite3.html https://www.python.org/dev/peps/pep-0249/ """
29.061224
80
0.624298
import sqlite3 as sqlite from SQLObjectStore import SQLObjectStore class SQLiteObjectStore(SQLObjectStore): """SQLiteObjectStore implements an object store backed by a SQLite database. See the SQLite docs or the DB API 2.0 docs for more information: https://docs.python.org/2/library/sqlite3.html https://www.python.org/dev/peps/pep-0249/ """ def augmentDatabaseArgs(self, args, pool=False): if not args.get('database'): args['database'] = '%s.db' % self._model.sqlDatabaseName() def newConnection(self): kwargs = self._dbArgs.copy() self.augmentDatabaseArgs(kwargs) return self.dbapiModule().connect(**kwargs) def dbapiModule(self): return sqlite def dbVersion(self): return "SQLite %s" % sqlite.sqlite_version def _executeSQL(self, cur, sql): try: cur.execute(sql) except sqlite.Warning: if not self.setting('IgnoreSQLWarnings', False): raise except sqlite.OperationalError as e: if 'database is locked' in str(e): print ('Please consider installing a newer SQLite version' ' or increasing the timeout.') raise def sqlNowCall(self): return "datetime('now')" class StringAttr(object): def sqlForNonNone(self, value): return "'%s'" % value.replace("'", "''")
836
4
212
9cba84af39093c2f8e33ef840cac70750d953876
692
py
Python
itdagene/graphql/middleware.py
itdagene-ntnu/itdagene
b972cd3d803debccebbc33641397a39834b8d69a
[ "MIT" ]
9
2018-10-17T20:58:09.000Z
2021-12-16T16:16:45.000Z
itdagene/graphql/middleware.py
itdagene-ntnu/itdagene
b972cd3d803debccebbc33641397a39834b8d69a
[ "MIT" ]
177
2018-10-27T18:15:56.000Z
2022-03-28T04:29:06.000Z
itdagene/graphql/middleware.py
itdagene-ntnu/itdagene
b972cd3d803debccebbc33641397a39834b8d69a
[ "MIT" ]
null
null
null
from django.conf import settings from graphql import GraphQLError from itdagene.graphql.loaders import Loaders
32.952381
65
0.66185
from django.conf import settings from graphql import GraphQLError from itdagene.graphql.loaders import Loaders class LoaderMiddleware: def resolve(self, next, root, info, **args): if not hasattr(info.context, "loaders"): info.context.loaders = Loaders() return next(root, info, **args) class ResolveLimitMiddleware: def resolve(self, next, root, info, **args): if not hasattr(info.context, "count"): info.context.count = 1 info.context.count = info.context.count + 1 if info.context.count > settings.GRAPHENE_RESOLVER_LIMIT: raise GraphQLError("query too big :/") return next(root, info, **args)
471
10
98
8317afd021e220b555dc36ab7cec6b22207fd711
1,497
py
Python
oneoff.py
Bevan0/oneoff
619a16e1eaaf7c6d841dfa32f1dccfd741bf891d
[ "MIT" ]
1
2022-02-01T03:27:13.000Z
2022-02-01T03:27:13.000Z
oneoff.py
Bevan0/oneoff
619a16e1eaaf7c6d841dfa32f1dccfd741bf891d
[ "MIT" ]
null
null
null
oneoff.py
Bevan0/oneoff
619a16e1eaaf7c6d841dfa32f1dccfd741bf891d
[ "MIT" ]
null
null
null
import click import subprocess import random import string import os @click.group() @cli.command() @click.argument("runner") @click.option("--editor", default="nano")
30.55102
115
0.603206
import click import subprocess import random import string import os @click.group() def cli(): pass @cli.command() @click.argument("runner") @click.option("--editor", default="nano") def run(runner, editor): file_name = None realrunner = runner if runner == "!": prevfile = open(f"{os.environ['HOME']}/.config/oneoff-previousfile", "r") file_name = prevfile.read().split('\n')[1] realrunner = prevfile.read().split('\n')[0] prevfile.close() elif runner == "EXPORT": prevfile = open(f"{os.environ['HOME']}/.config/oneoff-previousfile", "r") file_name = prevfile.read().split('\n')[1] prevfile.close() save_loc = click.prompt("Where do you want to save this? ", type=click.Path()) if save_loc[0] == "~": save_loc = os.environ["HOME"] + save_loc[1:] old_file = open(file_name, "r") new_file = open(save_loc, "w") new_file.write(old_file.read()) click.echo(f"Saved to {save_loc}") return else: file_name = f"/tmp/oneoff-{''.join(random.choice(string.ascii_letters + string.digits) for i in range(8))}" edit = subprocess.run([f"{editor}", f"{file_name}"]) if (edit.returncode != 0): click.echo("Editor returned non-zero error code, quitting") return subprocess.run([f"{realrunner}", f"{file_name}"]) f = open(f"{os.environ['HOME']}/.config/oneoff-previousfile", "w") f.write(f"{runner}\n{file_name}")
1,284
0
44
86c037e23ad6dc6e733532c71365e27da825f860
1,194
py
Python
neutron/tests/functional/__init__.py
NeCTAR-RC/neutron
acf78cc3c88aff638180819419a65145a9a79695
[ "Apache-2.0" ]
null
null
null
neutron/tests/functional/__init__.py
NeCTAR-RC/neutron
acf78cc3c88aff638180819419a65145a9a79695
[ "Apache-2.0" ]
null
null
null
neutron/tests/functional/__init__.py
NeCTAR-RC/neutron
acf78cc3c88aff638180819419a65145a9a79695
[ "Apache-2.0" ]
null
null
null
# Copyright 2015 Red Hat, Inc. # # Licensed under the Apache License, Version 2.0 (the "License"); you may # not use this file except in compliance with the License. You may obtain # a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, WITHOUT # WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the # License for the specific language governing permissions and limitations # under the License. """ In order to save gate resources, test paths that have similar environmental requirements to the functional path are marked for discovery. """ import os.path
33.166667
78
0.711055
# Copyright 2015 Red Hat, Inc. # # Licensed under the Apache License, Version 2.0 (the "License"); you may # not use this file except in compliance with the License. You may obtain # a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, WITHOUT # WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the # License for the specific language governing permissions and limitations # under the License. """ In order to save gate resources, test paths that have similar environmental requirements to the functional path are marked for discovery. """ import os.path def load_tests(loader, tests, pattern): this_dir = os.path.dirname(__file__) parent_dir = os.path.dirname(this_dir) target_dirs = [ this_dir, os.path.join(parent_dir, 'retargetable'), os.path.join(parent_dir, 'fullstack'), ] for start_dir in target_dirs: new_tests = loader.discover(start_dir=start_dir, pattern=pattern) tests.addTests(new_tests) return tests
402
0
23
65c631fbb803e3fbc0221f0843c0f33c68e1b661
8,179
py
Python
examples/privacy/membership_inference/train.py
hboshnak/mindarmour
0609a4eaea875a84667bed279add9305752880cc
[ "Apache-2.0" ]
139
2020-03-28T02:37:07.000Z
2022-03-24T15:35:39.000Z
examples/privacy/membership_inference/train.py
hboshnak/mindarmour
0609a4eaea875a84667bed279add9305752880cc
[ "Apache-2.0" ]
2
2020-04-02T09:50:21.000Z
2020-05-09T06:52:57.000Z
examples/privacy/membership_inference/train.py
hboshnak/mindarmour
0609a4eaea875a84667bed279add9305752880cc
[ "Apache-2.0" ]
12
2020-03-28T02:52:42.000Z
2021-07-15T08:05:06.000Z
# Copyright 2020 Huawei Technologies Co., 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. # ============================================================================ """ #################train vgg16 example on cifar10######################## python train.py --data_path=$DATA_HOME --device_id=$DEVICE_ID """ import argparse import datetime import os import random import numpy as np import mindspore.nn as nn from mindspore import Tensor from mindspore import context from mindspore.nn.optim.momentum import Momentum from mindspore.train.callback import ModelCheckpoint, CheckpointConfig, LossMonitor from mindspore.train.model import Model from mindspore.train.serialization import load_param_into_net, load_checkpoint from mindarmour.utils import LogUtil from examples.common.dataset.data_processing import vgg_create_dataset100 from examples.common.networks.vgg.warmup_step_lr import warmup_step_lr from examples.common.networks.vgg.warmup_cosine_annealing_lr import warmup_cosine_annealing_lr from examples.common.networks.vgg.warmup_step_lr import lr_steps from examples.common.networks.vgg.utils.util import get_param_groups from examples.common.networks.vgg.vgg import vgg16 from examples.common.networks.vgg.config import cifar_cfg as cfg TAG = "train" random.seed(1) np.random.seed(1) def parse_args(cloud_args=None): """parameters""" parser = argparse.ArgumentParser('mindspore classification training') parser.add_argument('--device_target', type=str, default='Ascend', choices=['Ascend', 'GPU'], help='device where the code will be implemented. (Default: Ascend)') parser.add_argument('--device_id', type=int, default=1, help='device id of GPU or Ascend. (Default: None)') # dataset related parser.add_argument('--data_path', type=str, default='', help='train data dir') # network related parser.add_argument('--pre_trained', default='', type=str, help='model_path, local pretrained model to load') parser.add_argument('--lr_gamma', type=float, default=0.1, help='decrease lr by a factor of exponential lr_scheduler') parser.add_argument('--eta_min', type=float, default=0., help='eta_min in cosine_annealing scheduler') parser.add_argument('--T_max', type=int, default=150, help='T-max in cosine_annealing scheduler') # logging and checkpoint related parser.add_argument('--log_interval', type=int, default=100, help='logging interval') parser.add_argument('--ckpt_path', type=str, default='outputs/', help='checkpoint save location') parser.add_argument('--ckpt_interval', type=int, default=2, help='ckpt_interval') parser.add_argument('--is_save_on_master', type=int, default=1, help='save ckpt on master or all rank') args_opt = parser.parse_args() args_opt = merge_args(args_opt, cloud_args) args_opt.rank = 0 args_opt.group_size = 1 args_opt.label_smooth = cfg.label_smooth args_opt.label_smooth_factor = cfg.label_smooth_factor args_opt.lr_scheduler = cfg.lr_scheduler args_opt.loss_scale = cfg.loss_scale args_opt.max_epoch = cfg.max_epoch args_opt.warmup_epochs = cfg.warmup_epochs args_opt.lr = cfg.lr args_opt.lr_init = cfg.lr_init args_opt.lr_max = cfg.lr_max args_opt.momentum = cfg.momentum args_opt.weight_decay = cfg.weight_decay args_opt.per_batch_size = cfg.batch_size args_opt.num_classes = cfg.num_classes args_opt.buffer_size = cfg.buffer_size args_opt.ckpt_save_max = cfg.keep_checkpoint_max args_opt.pad_mode = cfg.pad_mode args_opt.padding = cfg.padding args_opt.has_bias = cfg.has_bias args_opt.batch_norm = cfg.batch_norm args_opt.initialize_mode = cfg.initialize_mode args_opt.has_dropout = cfg.has_dropout args_opt.lr_epochs = list(map(int, cfg.lr_epochs.split(','))) args_opt.image_size = list(map(int, cfg.image_size.split(','))) return args_opt def merge_args(args_opt, cloud_args): """dictionary""" args_dict = vars(args_opt) if isinstance(cloud_args, dict): for key_arg in cloud_args.keys(): val = cloud_args[key_arg] if key_arg in args_dict and val: arg_type = type(args_dict[key_arg]) if arg_type is not None: val = arg_type(val) args_dict[key_arg] = val return args_opt if __name__ == '__main__': args = parse_args() device_num = int(os.environ.get("DEVICE_NUM", 1)) context.set_context(device_id=args.device_id) context.set_context(mode=context.GRAPH_MODE, device_target=args.device_target) # select for master rank save ckpt or all rank save, compatiable for model parallel args.rank_save_ckpt_flag = 0 if args.is_save_on_master: if args.rank == 0: args.rank_save_ckpt_flag = 1 else: args.rank_save_ckpt_flag = 1 # logger args.outputs_dir = os.path.join(args.ckpt_path, datetime.datetime.now().strftime('%Y-%m-%d_time_%H_%M_%S')) args.logger = LogUtil.get_instance() args.logger.set_level(20) # load train data set dataset = vgg_create_dataset100(args.data_path, args.image_size, args.per_batch_size, args.rank, args.group_size) batch_num = dataset.get_dataset_size() args.steps_per_epoch = dataset.get_dataset_size() # network args.logger.info(TAG, 'start create network') # get network and init network = vgg16(args.num_classes, args) # pre_trained if args.pre_trained: load_param_into_net(network, load_checkpoint(args.pre_trained)) # lr scheduler if args.lr_scheduler == 'exponential': lr = warmup_step_lr(args.lr, args.lr_epochs, args.steps_per_epoch, args.warmup_epochs, args.max_epoch, gamma=args.lr_gamma, ) elif args.lr_scheduler == 'cosine_annealing': lr = warmup_cosine_annealing_lr(args.lr, args.steps_per_epoch, args.warmup_epochs, args.max_epoch, args.T_max, args.eta_min) elif args.lr_scheduler == 'step': lr = lr_steps(0, lr_init=args.lr_init, lr_max=args.lr_max, warmup_epochs=args.warmup_epochs, total_epochs=args.max_epoch, steps_per_epoch=batch_num) else: raise NotImplementedError(args.lr_scheduler) # optimizer opt = Momentum(params=get_param_groups(network), learning_rate=Tensor(lr), momentum=args.momentum, weight_decay=args.weight_decay, loss_scale=args.loss_scale) loss = nn.SoftmaxCrossEntropyWithLogits(sparse=True, reduction='mean') model = Model(network, loss_fn=loss, optimizer=opt, metrics={'acc'}, amp_level="O2", keep_batchnorm_fp32=False, loss_scale_manager=None) # checkpoint save callbacks = [LossMonitor()] if args.rank_save_ckpt_flag: ckpt_config = CheckpointConfig(save_checkpoint_steps=args.ckpt_interval*args.steps_per_epoch, keep_checkpoint_max=args.ckpt_save_max) ckpt_cb = ModelCheckpoint(config=ckpt_config, directory=args.outputs_dir, prefix='{}'.format(args.rank)) callbacks.append(ckpt_cb) model.train(args.max_epoch, dataset, callbacks=callbacks)
40.895
117
0.669275
# Copyright 2020 Huawei Technologies Co., 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. # ============================================================================ """ #################train vgg16 example on cifar10######################## python train.py --data_path=$DATA_HOME --device_id=$DEVICE_ID """ import argparse import datetime import os import random import numpy as np import mindspore.nn as nn from mindspore import Tensor from mindspore import context from mindspore.nn.optim.momentum import Momentum from mindspore.train.callback import ModelCheckpoint, CheckpointConfig, LossMonitor from mindspore.train.model import Model from mindspore.train.serialization import load_param_into_net, load_checkpoint from mindarmour.utils import LogUtil from examples.common.dataset.data_processing import vgg_create_dataset100 from examples.common.networks.vgg.warmup_step_lr import warmup_step_lr from examples.common.networks.vgg.warmup_cosine_annealing_lr import warmup_cosine_annealing_lr from examples.common.networks.vgg.warmup_step_lr import lr_steps from examples.common.networks.vgg.utils.util import get_param_groups from examples.common.networks.vgg.vgg import vgg16 from examples.common.networks.vgg.config import cifar_cfg as cfg TAG = "train" random.seed(1) np.random.seed(1) def parse_args(cloud_args=None): """parameters""" parser = argparse.ArgumentParser('mindspore classification training') parser.add_argument('--device_target', type=str, default='Ascend', choices=['Ascend', 'GPU'], help='device where the code will be implemented. (Default: Ascend)') parser.add_argument('--device_id', type=int, default=1, help='device id of GPU or Ascend. (Default: None)') # dataset related parser.add_argument('--data_path', type=str, default='', help='train data dir') # network related parser.add_argument('--pre_trained', default='', type=str, help='model_path, local pretrained model to load') parser.add_argument('--lr_gamma', type=float, default=0.1, help='decrease lr by a factor of exponential lr_scheduler') parser.add_argument('--eta_min', type=float, default=0., help='eta_min in cosine_annealing scheduler') parser.add_argument('--T_max', type=int, default=150, help='T-max in cosine_annealing scheduler') # logging and checkpoint related parser.add_argument('--log_interval', type=int, default=100, help='logging interval') parser.add_argument('--ckpt_path', type=str, default='outputs/', help='checkpoint save location') parser.add_argument('--ckpt_interval', type=int, default=2, help='ckpt_interval') parser.add_argument('--is_save_on_master', type=int, default=1, help='save ckpt on master or all rank') args_opt = parser.parse_args() args_opt = merge_args(args_opt, cloud_args) args_opt.rank = 0 args_opt.group_size = 1 args_opt.label_smooth = cfg.label_smooth args_opt.label_smooth_factor = cfg.label_smooth_factor args_opt.lr_scheduler = cfg.lr_scheduler args_opt.loss_scale = cfg.loss_scale args_opt.max_epoch = cfg.max_epoch args_opt.warmup_epochs = cfg.warmup_epochs args_opt.lr = cfg.lr args_opt.lr_init = cfg.lr_init args_opt.lr_max = cfg.lr_max args_opt.momentum = cfg.momentum args_opt.weight_decay = cfg.weight_decay args_opt.per_batch_size = cfg.batch_size args_opt.num_classes = cfg.num_classes args_opt.buffer_size = cfg.buffer_size args_opt.ckpt_save_max = cfg.keep_checkpoint_max args_opt.pad_mode = cfg.pad_mode args_opt.padding = cfg.padding args_opt.has_bias = cfg.has_bias args_opt.batch_norm = cfg.batch_norm args_opt.initialize_mode = cfg.initialize_mode args_opt.has_dropout = cfg.has_dropout args_opt.lr_epochs = list(map(int, cfg.lr_epochs.split(','))) args_opt.image_size = list(map(int, cfg.image_size.split(','))) return args_opt def merge_args(args_opt, cloud_args): """dictionary""" args_dict = vars(args_opt) if isinstance(cloud_args, dict): for key_arg in cloud_args.keys(): val = cloud_args[key_arg] if key_arg in args_dict and val: arg_type = type(args_dict[key_arg]) if arg_type is not None: val = arg_type(val) args_dict[key_arg] = val return args_opt if __name__ == '__main__': args = parse_args() device_num = int(os.environ.get("DEVICE_NUM", 1)) context.set_context(device_id=args.device_id) context.set_context(mode=context.GRAPH_MODE, device_target=args.device_target) # select for master rank save ckpt or all rank save, compatiable for model parallel args.rank_save_ckpt_flag = 0 if args.is_save_on_master: if args.rank == 0: args.rank_save_ckpt_flag = 1 else: args.rank_save_ckpt_flag = 1 # logger args.outputs_dir = os.path.join(args.ckpt_path, datetime.datetime.now().strftime('%Y-%m-%d_time_%H_%M_%S')) args.logger = LogUtil.get_instance() args.logger.set_level(20) # load train data set dataset = vgg_create_dataset100(args.data_path, args.image_size, args.per_batch_size, args.rank, args.group_size) batch_num = dataset.get_dataset_size() args.steps_per_epoch = dataset.get_dataset_size() # network args.logger.info(TAG, 'start create network') # get network and init network = vgg16(args.num_classes, args) # pre_trained if args.pre_trained: load_param_into_net(network, load_checkpoint(args.pre_trained)) # lr scheduler if args.lr_scheduler == 'exponential': lr = warmup_step_lr(args.lr, args.lr_epochs, args.steps_per_epoch, args.warmup_epochs, args.max_epoch, gamma=args.lr_gamma, ) elif args.lr_scheduler == 'cosine_annealing': lr = warmup_cosine_annealing_lr(args.lr, args.steps_per_epoch, args.warmup_epochs, args.max_epoch, args.T_max, args.eta_min) elif args.lr_scheduler == 'step': lr = lr_steps(0, lr_init=args.lr_init, lr_max=args.lr_max, warmup_epochs=args.warmup_epochs, total_epochs=args.max_epoch, steps_per_epoch=batch_num) else: raise NotImplementedError(args.lr_scheduler) # optimizer opt = Momentum(params=get_param_groups(network), learning_rate=Tensor(lr), momentum=args.momentum, weight_decay=args.weight_decay, loss_scale=args.loss_scale) loss = nn.SoftmaxCrossEntropyWithLogits(sparse=True, reduction='mean') model = Model(network, loss_fn=loss, optimizer=opt, metrics={'acc'}, amp_level="O2", keep_batchnorm_fp32=False, loss_scale_manager=None) # checkpoint save callbacks = [LossMonitor()] if args.rank_save_ckpt_flag: ckpt_config = CheckpointConfig(save_checkpoint_steps=args.ckpt_interval*args.steps_per_epoch, keep_checkpoint_max=args.ckpt_save_max) ckpt_cb = ModelCheckpoint(config=ckpt_config, directory=args.outputs_dir, prefix='{}'.format(args.rank)) callbacks.append(ckpt_cb) model.train(args.max_epoch, dataset, callbacks=callbacks)
0
0
0
0cbeb629e794b65cf7a6c61177377cd5ccd4028a
386
py
Python
armada_command/command_name.py
firesoft/armada
245115fcf21d988db5da71f18b3123479de5f2c1
[ "Apache-2.0" ]
281
2015-07-08T12:52:19.000Z
2022-01-14T22:56:25.000Z
armada_command/command_name.py
firesoft/armada
245115fcf21d988db5da71f18b3123479de5f2c1
[ "Apache-2.0" ]
15
2015-08-03T14:54:30.000Z
2021-01-27T12:30:06.000Z
armada_command/command_name.py
firesoft/armada
245115fcf21d988db5da71f18b3123479de5f2c1
[ "Apache-2.0" ]
39
2015-07-13T14:43:44.000Z
2022-01-12T15:41:32.000Z
from armada_command import armada_api
25.733333
84
0.668394
from armada_command import armada_api def add_arguments(parser): parser.add_argument('name', help='New name for the ship', nargs='?', default='') def command_name(args): if args.name: result = armada_api.post('name', {'name': args.name}) armada_api.print_result_from_armada_api(result) else: result = armada_api.get('name') print(result)
300
0
46
213120ab7d47e5368a0a6d21cf7ba3a46730eda8
7,282
py
Python
src/controllers/mainController.py
shimadasoftware/ATM-Simulator
2d3b0cdc06f9b5a5ea2ba1b9b17053227e322dc4
[ "Apache-2.0" ]
2
2021-09-08T16:57:51.000Z
2021-09-14T19:41:25.000Z
src/controllers/mainController.py
shimadasoftware/ATM-Simulator
2d3b0cdc06f9b5a5ea2ba1b9b17053227e322dc4
[ "Apache-2.0" ]
null
null
null
src/controllers/mainController.py
shimadasoftware/ATM-Simulator
2d3b0cdc06f9b5a5ea2ba1b9b17053227e322dc4
[ "Apache-2.0" ]
null
null
null
#!/usr/bin/env python3 # -*- coding: utf-8 -*- """ Main Controller Created on Tue Aug 17 14:16:44 2021 Version: 1.0 Universidad Santo Tomás Tunja Simulation @author: Juana Valentina Mendoza Santamaría @author: Alix Ivonne Chaparro Vasquez presented to: Martha Susana Contreras Ortiz """ from random import randint import time from controllers.settings import config from models.atms import ATMs from models.clients import Clients from models.accounts import Accounts from models.cards import Cards from models.transactions import Transactions from models.record import Record from views.mainView import mainView, insertCardView, insertCardDeepelyView, insertCardCompletelyView from views.mainView import mainMenuView from controllers.bankController import createBank from controllers.balanceController import balanceController from controllers.withdrawController import withdrawController from controllers.depositController import depositController from controllers.statsController import stats from controllers.reportController import stage, showTransactionData from controllers.plotController import resultPlots __author__ = ["Juana Valentina Mendoza Santamaría", "Alix Ivonne Chaparro Vasquez"] __copyright__ = "Copyright 2021, Universidad Santo Tomás Tunja" __credits__ = ["Martha Susana Contreras Ortiz"] __license__ = "GPL" __version__ = "1.0.1" __maintainer__= ["Juana Valentina Mendoza Santamaría", "Alix Ivonne Chaparro Vasquez"] __email__ = ["juana.mendoza@usantoto.edu.co", "alix.ivonne@usantoto.edu.co"] __status__ = "Develpment" #%% def previousScreens(): """ Project the screens """ mainView() time.sleep(2) insertCardView() time.sleep(2) insertCardDeepelyView() time.sleep(2) insertCardCompletelyView() time.sleep(2) #%% def initialize(simulation): """Initializing variables Args: simulation (boolean): True (simulation) - False (Demo) """ global maxSimulationTime global minWithdrawAccount, maxWithdrawAccount global minDepositAccount, maxDepositAccount global minBill global record maxATMs = config.PARAMETERS['maxATMs'] minATMCash = config.PARAMETERS['minATMCash'] maxATMCash = config.PARAMETERS['maxATMCash'] minBill = config.PARAMETERS['minBill'] maxClients = config.PARAMETERS['maxClients'] maxAccounts = config.PARAMETERS['maxAccounts'] maxAccountBalance = config.PARAMETERS['maxAccountBalance'] maxCards = config.PARAMETERS['maxCards'] minWithdrawAccount = config.PARAMETERS['minWithdrawAccount'] maxWithdrawAccount = config.PARAMETERS['maxWithdrawAccount'] minDepositAccount = config.PARAMETERS['minDepositAccount'] maxDepositAccount = config.PARAMETERS['maxDepositAccount'] maxTransactions = config.PARAMETERS['maxTransactions'] maxSimulationTime = config.PARAMETERS['maxSimulationTime'] global bank, atms global clients, accounts, cards global transactions bank = createBank() atms = ATMs( bank, maxATMs, minATMCash, maxATMCash, minBill ) if simulation: # Simulation atms.createRandomATMs() else: # Controlled demo atms.createATMs() clients = Clients(maxClients) if simulation: clients.createRandomClients() else: clients.createClients() accounts = Accounts( clients.clients[0], maxAccounts, maxAccountBalance, minBill ) if simulation: for client in clients.clients: oldList = accounts.accounts accounts.client = client accounts.createRandomAccounts() newList = accounts.accounts accounts.accounts = oldList + newList else: accounts.createAccounts() cards = Cards(accounts.accounts[0], maxCards) if simulation: for account in accounts.accounts: oldList = cards.cards cards.account = account cards.createRandomCards() newList = cards.cards cards.cards = oldList + newList else: cards.createCards() transactions = Transactions( atms, cards, minWithdrawAccount, maxWithdrawAccount, minDepositAccount, maxDepositAccount, minBill, maxTransactions ) record = Record() #%% def getOption(simulation): """Select the type of transaction to be made. Args: simulation (boolean): demo or simulation. """ global record loop = 0 option = 0 while option != -1: # Finish atm = atms.randomSelectedATM() client = clients.randomSelectedClient() account = accounts.randomSelectedAccount(client) card = cards.randomSelectedCard(account) loop += 1 if not simulation: mainMenuView() # Balance, Withdraw, Deposit, Consult Trasactions while option not in [-1, 1, 2, 3, 99]: option = int(input('-> ')) else: if loop >= maxSimulationTime: option = -1 # End of simulation else: option = randint(1, 3) if option == 1: # Balance option, transaction = balanceController(atm, card, simulation) transactions.add(transaction) elif option == 2: # Withdraw option, transaction = withdrawController( atm, card, simulation, minWithdrawAccount, maxWithdrawAccount, minBill ) transactions.add(transaction) if transaction.transactionStatus == 'Successful': atm.atmCash -= transaction.transactionAmount card.cardAccount.accountBalance -= transaction.transactionAmount elif option == 3: # Deposit option, transaction = depositController( atm, card, simulation, minDepositAccount, maxDepositAccount, minBill ) transactions.add(transaction) if transaction.transactionStatus == 'Successful': atm.atmCash += transaction.transactionAmount card.cardAccount.accountBalance += transaction.transactionAmount elif option == 99: print(transactions) option = input("Press Enter to continue...") if option != -1: option = -1 if option == 2 else 0 # option = 2 (finish) if simulation: showTransactionData(loop, transaction, bank, atms, accounts) record.recordTransaction(loop, transaction) #%% def mainController(simulation): """Start of application Args: simulation (boolean): demo or simulation. """ global bank, atms, accounts global record initialize(simulation) if not simulation: previousScreens() stage(bank, atms, accounts) getOption(simulation) stats(record) resultPlots(record)
29.24498
100
0.633068
#!/usr/bin/env python3 # -*- coding: utf-8 -*- """ Main Controller Created on Tue Aug 17 14:16:44 2021 Version: 1.0 Universidad Santo Tomás Tunja Simulation @author: Juana Valentina Mendoza Santamaría @author: Alix Ivonne Chaparro Vasquez presented to: Martha Susana Contreras Ortiz """ from random import randint import time from controllers.settings import config from models.atms import ATMs from models.clients import Clients from models.accounts import Accounts from models.cards import Cards from models.transactions import Transactions from models.record import Record from views.mainView import mainView, insertCardView, insertCardDeepelyView, insertCardCompletelyView from views.mainView import mainMenuView from controllers.bankController import createBank from controllers.balanceController import balanceController from controllers.withdrawController import withdrawController from controllers.depositController import depositController from controllers.statsController import stats from controllers.reportController import stage, showTransactionData from controllers.plotController import resultPlots __author__ = ["Juana Valentina Mendoza Santamaría", "Alix Ivonne Chaparro Vasquez"] __copyright__ = "Copyright 2021, Universidad Santo Tomás Tunja" __credits__ = ["Martha Susana Contreras Ortiz"] __license__ = "GPL" __version__ = "1.0.1" __maintainer__= ["Juana Valentina Mendoza Santamaría", "Alix Ivonne Chaparro Vasquez"] __email__ = ["juana.mendoza@usantoto.edu.co", "alix.ivonne@usantoto.edu.co"] __status__ = "Develpment" #%% def previousScreens(): """ Project the screens """ mainView() time.sleep(2) insertCardView() time.sleep(2) insertCardDeepelyView() time.sleep(2) insertCardCompletelyView() time.sleep(2) #%% def initialize(simulation): """Initializing variables Args: simulation (boolean): True (simulation) - False (Demo) """ global maxSimulationTime global minWithdrawAccount, maxWithdrawAccount global minDepositAccount, maxDepositAccount global minBill global record maxATMs = config.PARAMETERS['maxATMs'] minATMCash = config.PARAMETERS['minATMCash'] maxATMCash = config.PARAMETERS['maxATMCash'] minBill = config.PARAMETERS['minBill'] maxClients = config.PARAMETERS['maxClients'] maxAccounts = config.PARAMETERS['maxAccounts'] maxAccountBalance = config.PARAMETERS['maxAccountBalance'] maxCards = config.PARAMETERS['maxCards'] minWithdrawAccount = config.PARAMETERS['minWithdrawAccount'] maxWithdrawAccount = config.PARAMETERS['maxWithdrawAccount'] minDepositAccount = config.PARAMETERS['minDepositAccount'] maxDepositAccount = config.PARAMETERS['maxDepositAccount'] maxTransactions = config.PARAMETERS['maxTransactions'] maxSimulationTime = config.PARAMETERS['maxSimulationTime'] global bank, atms global clients, accounts, cards global transactions bank = createBank() atms = ATMs( bank, maxATMs, minATMCash, maxATMCash, minBill ) if simulation: # Simulation atms.createRandomATMs() else: # Controlled demo atms.createATMs() clients = Clients(maxClients) if simulation: clients.createRandomClients() else: clients.createClients() accounts = Accounts( clients.clients[0], maxAccounts, maxAccountBalance, minBill ) if simulation: for client in clients.clients: oldList = accounts.accounts accounts.client = client accounts.createRandomAccounts() newList = accounts.accounts accounts.accounts = oldList + newList else: accounts.createAccounts() cards = Cards(accounts.accounts[0], maxCards) if simulation: for account in accounts.accounts: oldList = cards.cards cards.account = account cards.createRandomCards() newList = cards.cards cards.cards = oldList + newList else: cards.createCards() transactions = Transactions( atms, cards, minWithdrawAccount, maxWithdrawAccount, minDepositAccount, maxDepositAccount, minBill, maxTransactions ) record = Record() #%% def getOption(simulation): """Select the type of transaction to be made. Args: simulation (boolean): demo or simulation. """ global record loop = 0 option = 0 while option != -1: # Finish atm = atms.randomSelectedATM() client = clients.randomSelectedClient() account = accounts.randomSelectedAccount(client) card = cards.randomSelectedCard(account) loop += 1 if not simulation: mainMenuView() # Balance, Withdraw, Deposit, Consult Trasactions while option not in [-1, 1, 2, 3, 99]: option = int(input('-> ')) else: if loop >= maxSimulationTime: option = -1 # End of simulation else: option = randint(1, 3) if option == 1: # Balance option, transaction = balanceController(atm, card, simulation) transactions.add(transaction) elif option == 2: # Withdraw option, transaction = withdrawController( atm, card, simulation, minWithdrawAccount, maxWithdrawAccount, minBill ) transactions.add(transaction) if transaction.transactionStatus == 'Successful': atm.atmCash -= transaction.transactionAmount card.cardAccount.accountBalance -= transaction.transactionAmount elif option == 3: # Deposit option, transaction = depositController( atm, card, simulation, minDepositAccount, maxDepositAccount, minBill ) transactions.add(transaction) if transaction.transactionStatus == 'Successful': atm.atmCash += transaction.transactionAmount card.cardAccount.accountBalance += transaction.transactionAmount elif option == 99: print(transactions) option = input("Press Enter to continue...") if option != -1: option = -1 if option == 2 else 0 # option = 2 (finish) if simulation: showTransactionData(loop, transaction, bank, atms, accounts) record.recordTransaction(loop, transaction) #%% def mainController(simulation): """Start of application Args: simulation (boolean): demo or simulation. """ global bank, atms, accounts global record initialize(simulation) if not simulation: previousScreens() stage(bank, atms, accounts) getOption(simulation) stats(record) resultPlots(record)
0
0
0
8dd6e9731c0a7723cdc7ad07c5dc2364c7e82ae3
198
py
Python
zksync_sdk/types/__init__.py
toobit/zksync-python
49b774dfda6a6b5f2e879bfee831b1ce3bf64ad0
[ "MIT" ]
null
null
null
zksync_sdk/types/__init__.py
toobit/zksync-python
49b774dfda6a6b5f2e879bfee831b1ce3bf64ad0
[ "MIT" ]
null
null
null
zksync_sdk/types/__init__.py
toobit/zksync-python
49b774dfda6a6b5f2e879bfee831b1ce3bf64ad0
[ "MIT" ]
null
null
null
from enum import IntEnum from .responses import * from .signatures import * from .transactions import *
15.230769
27
0.686869
from enum import IntEnum from .responses import * from .signatures import * from .transactions import * class ChainId(IntEnum): MAINNET = 10 RINKEBY = 4 ROPSTEN = 3 LOCALHOST = 9
0
69
23
281ec0bf45a2ac0a1f920b77e99794caa55c4669
1,188
py
Python
tools/harmonics/show.py
jjzhang166/OpenGLEngine
e5d86f41536834499f4dd534c590fbeed045ff7c
[ "MIT" ]
1
2021-08-12T07:35:49.000Z
2021-08-12T07:35:49.000Z
tools/harmonics/show.py
jjzhang166/OpenGLEngine
e5d86f41536834499f4dd534c590fbeed045ff7c
[ "MIT" ]
null
null
null
tools/harmonics/show.py
jjzhang166/OpenGLEngine
e5d86f41536834499f4dd534c590fbeed045ff7c
[ "MIT" ]
null
null
null
#!/usr/bin/env python3 # -*- coding: utf-8 -*- # @Author: penghuailiang # @Date : 1/1/20 """ 此脚本使用scipy.special绘制球谐函数 """ import numpy as np import matplotlib.pyplot as plt from scipy.special import sph_harm from mpl_toolkits.mplot3d import Axes3D from matplotlib import cm theta_1d = np.linspace(0, np.pi, 181) # colatitude phi_1d = np.linspace(0, 2 * np.pi, 361) # longitude theta_2d, phi_2d = np.meshgrid(theta_1d, phi_1d) xyz_2d = np.array([np.sin(theta_2d) * np.sin(phi_2d), np.sin(theta_2d) * np.cos(phi_2d), np.cos(theta_2d)]) colormap = cm.ScalarMappable(cmap=plt.get_cmap("cool")) colormap.set_clim(-0.45, 0.45) limit = 0.5 show_Y_lm(2, 0) show_Y_lm(3, 3) show_Y_lm(4, 2)
26.4
107
0.670875
#!/usr/bin/env python3 # -*- coding: utf-8 -*- # @Author: penghuailiang # @Date : 1/1/20 """ 此脚本使用scipy.special绘制球谐函数 """ import numpy as np import matplotlib.pyplot as plt from scipy.special import sph_harm from mpl_toolkits.mplot3d import Axes3D from matplotlib import cm theta_1d = np.linspace(0, np.pi, 181) # colatitude phi_1d = np.linspace(0, 2 * np.pi, 361) # longitude theta_2d, phi_2d = np.meshgrid(theta_1d, phi_1d) xyz_2d = np.array([np.sin(theta_2d) * np.sin(phi_2d), np.sin(theta_2d) * np.cos(phi_2d), np.cos(theta_2d)]) colormap = cm.ScalarMappable(cmap=plt.get_cmap("cool")) colormap.set_clim(-0.45, 0.45) limit = 0.5 def show_Y_lm(l, m): print('Y_{:d}_{:d}'.format(l, m)) plt.figure(dpi=100) ax = plt.gca(projection='3d') Y_lm = sph_harm(m, l, phi_2d, theta_2d) r = np.abs(Y_lm.real) * xyz_2d # need to distort the radius by some function ax.plot_surface(r[0], r[1], r[2], facecolors=colormap.to_rgba(Y_lm.real)) plt.title('$Y^{:d}_{:d}$'.format(m, l)) ax.set_xlim(-limit, limit) ax.set_ylim(-limit, limit) ax.set_zlim(-limit, limit) ax.set_axis_off() plt.show() show_Y_lm(2, 0) show_Y_lm(3, 3) show_Y_lm(4, 2)
473
0
23
f78a15aad41a1b7a1db447dc27b33c377969ed73
1,081
py
Python
uploads/core/migrations/0004_auto_20211123_1244.py
Borna07/IFC2Data
8a3f287785b165ea4f0090c4f50c08a3d3b0c75c
[ "MIT" ]
null
null
null
uploads/core/migrations/0004_auto_20211123_1244.py
Borna07/IFC2Data
8a3f287785b165ea4f0090c4f50c08a3d3b0c75c
[ "MIT" ]
null
null
null
uploads/core/migrations/0004_auto_20211123_1244.py
Borna07/IFC2Data
8a3f287785b165ea4f0090c4f50c08a3d3b0c75c
[ "MIT" ]
null
null
null
# Generated by Django 3.2.7 on 2021-11-23 11:44 from django.db import migrations, models
27.717949
62
0.565217
# Generated by Django 3.2.7 on 2021-11-23 11:44 from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('core', '0003_auto_20211028_1323'), ] operations = [ migrations.AddField( model_name='document', name='author', field=models.CharField(max_length=200, null=True), ), migrations.AddField( model_name='document', name='organization', field=models.CharField(max_length=200, null=True), ), migrations.AddField( model_name='document', name='project_name', field=models.CharField(max_length=200, null=True), ), migrations.AddField( model_name='document', name='schema_identifiers', field=models.CharField(max_length=200, null=True), ), migrations.AddField( model_name='document', name='software', field=models.CharField(max_length=200, null=True), ), ]
0
967
23
8a26904370270bb9ef3f9739a127a6f42fb2fd42
1,954
py
Python
25-Scheme/lab09/lab09/tests/composed.py
ericchen12377/CS61A_LearningDoc
31f23962b0e2834795bf61eeb0f4884cc5da1809
[ "MIT" ]
2
2020-04-24T18:36:53.000Z
2020-04-25T00:15:55.000Z
25-Scheme/lab09/lab09/tests/composed.py
ericchen12377/CS61A_LearningDoc
31f23962b0e2834795bf61eeb0f4884cc5da1809
[ "MIT" ]
null
null
null
25-Scheme/lab09/lab09/tests/composed.py
ericchen12377/CS61A_LearningDoc
31f23962b0e2834795bf61eeb0f4884cc5da1809
[ "MIT" ]
null
null
null
test = { 'name': 'composed', 'points': 1, 'suites': [ { 'cases': [ { 'code': r""" scm> ((composed add-one add-one) 2) a1e11865670a42d05e20b9a3455dc457 # locked """, 'hidden': False, 'locked': True }, { 'code': r""" scm> ((composed multiply-by-two multiply-by-two) 2) 2bfcd627609c82ebd017c2edfad00c89 # locked """, 'hidden': False, 'locked': True }, { 'code': r""" scm> ((composed add-one multiply-by-two) 2) 8d3d95b1350833ea7b81c9454d1af611 # locked """, 'hidden': False, 'locked': True }, { 'code': r""" scm> ((composed multiply-by-two add-one) 2) aae76aca9259a704209b44193fad5f6a # locked """, 'hidden': False, 'locked': True }, { 'code': r""" scm> ((composed (composed add-one add-one) add-one) 2) 8d3d95b1350833ea7b81c9454d1af611 # locked """, 'hidden': False, 'locked': True }, { 'code': r""" scm> ((composed (composed add-one add-one) multiply-by-two) 2) aae76aca9259a704209b44193fad5f6a # locked """, 'hidden': False, 'locked': True }, { 'code': r""" scm> ((composed multiply-by-two (composed add-one add-one)) 2) 2bfcd627609c82ebd017c2edfad00c89 # locked """, 'hidden': False, 'locked': True } ], 'scored': False, 'setup': r""" scm> (load-all ".") scm> (define (add-one a) (+ a 1)) scm> (define (multiply-by-two a) (* a 2)) """, 'teardown': '', 'type': 'scheme' } ] }
23.829268
72
0.420676
test = { 'name': 'composed', 'points': 1, 'suites': [ { 'cases': [ { 'code': r""" scm> ((composed add-one add-one) 2) a1e11865670a42d05e20b9a3455dc457 # locked """, 'hidden': False, 'locked': True }, { 'code': r""" scm> ((composed multiply-by-two multiply-by-two) 2) 2bfcd627609c82ebd017c2edfad00c89 # locked """, 'hidden': False, 'locked': True }, { 'code': r""" scm> ((composed add-one multiply-by-two) 2) 8d3d95b1350833ea7b81c9454d1af611 # locked """, 'hidden': False, 'locked': True }, { 'code': r""" scm> ((composed multiply-by-two add-one) 2) aae76aca9259a704209b44193fad5f6a # locked """, 'hidden': False, 'locked': True }, { 'code': r""" scm> ((composed (composed add-one add-one) add-one) 2) 8d3d95b1350833ea7b81c9454d1af611 # locked """, 'hidden': False, 'locked': True }, { 'code': r""" scm> ((composed (composed add-one add-one) multiply-by-two) 2) aae76aca9259a704209b44193fad5f6a # locked """, 'hidden': False, 'locked': True }, { 'code': r""" scm> ((composed multiply-by-two (composed add-one add-one)) 2) 2bfcd627609c82ebd017c2edfad00c89 # locked """, 'hidden': False, 'locked': True } ], 'scored': False, 'setup': r""" scm> (load-all ".") scm> (define (add-one a) (+ a 1)) scm> (define (multiply-by-two a) (* a 2)) """, 'teardown': '', 'type': 'scheme' } ] }
0
0
0
cde1909da181e5ecc25ad5f5fd545a95d8f60d11
2,580
py
Python
src/visualize.py
Mirofil/RobustDARTS
da8654f63c89b28207c1253bdc6ad20222e99c9d
[ "Apache-2.0" ]
151
2019-09-25T06:25:38.000Z
2022-02-05T04:35:11.000Z
src/visualize.py
Mirofil/RobustDARTS
da8654f63c89b28207c1253bdc6ad20222e99c9d
[ "Apache-2.0" ]
6
2019-12-27T08:10:22.000Z
2020-11-10T16:01:20.000Z
src/visualize.py
Mirofil/RobustDARTS
da8654f63c89b28207c1253bdc6ad20222e99c9d
[ "Apache-2.0" ]
39
2019-09-26T07:14:08.000Z
2021-12-27T10:20:27.000Z
import sys import genotypes from graphviz import Digraph from genotypes import PRIMITIVES if __name__ == '__main__': if len(sys.argv) != 2: print("usage:\n python {} ARCH_NAME".format(sys.argv[0])) sys.exit(1) genotype_name = sys.argv[1] try: genotype = eval('genotypes.{}'.format(genotype_name)) except AttributeError: print("{} is not specified in genotypes.py".format(genotype_name)) sys.exit(1) plot(genotype.normal, "normal_"+str(sys.argv[1])) plot(genotype.reduce, "reduction_"+str(sys.argv[1])) #plot_space(P['primitives_normal'], "space_normal") #plot_space(P['primitives_reduct'], "space_reduction")
26.326531
141
0.60969
import sys import genotypes from graphviz import Digraph from genotypes import PRIMITIVES def plot_space(primitives, filename): g = Digraph( format='pdf', edge_attr=dict(fontsize='20', fontname="times"), node_attr=dict(style='filled', shape='rect', align='center', fontsize='20', height='0.5', width='0.5', penwidth='2', fontname="times"), engine='dot') g.body.extend(['rankdir=LR']) g.node("c_{k-2}", fillcolor='darkseagreen2') g.node("c_{k-1}", fillcolor='darkseagreen2') steps = 4 for i in range(steps): g.node(str(i), fillcolor='lightblue') n = 2 start = 0 nodes_indx = ["c_{k-2}", "c_{k-1}"] for i in range(steps): end = start + n p = primitives[start:end] v = str(i) for node, prim in zip(nodes_indx, p): u = node for op in prim: g.edge(u, v, label=op, fillcolor="gray") start = end n += 1 nodes_indx.append(v) g.node("c_{k}", fillcolor='palegoldenrod') for i in range(steps): g.edge(str(i), "c_{k}", fillcolor="gray") g.render(filename, view=False) def plot(genotype, filename): g = Digraph( format='pdf', edge_attr=dict(fontsize='20', fontname="times"), node_attr=dict(style='filled', shape='rect', align='center', fontsize='20', height='0.5', width='0.5', penwidth='2', fontname="times"), engine='dot') g.body.extend(['rankdir=LR']) g.node("c_{k-2}", fillcolor='darkseagreen2') g.node("c_{k-1}", fillcolor='darkseagreen2') assert len(genotype) % 2 == 0 steps = len(genotype) // 2 for i in range(steps): g.node(str(i), fillcolor='lightblue') for i in range(steps): for k in [2*i, 2*i + 1]: op, j = genotype[k] if j == 0: u = "c_{k-2}" elif j == 1: u = "c_{k-1}" else: u = str(j-2) v = str(i) g.edge(u, v, label=op, fillcolor="gray") g.node("c_{k}", fillcolor='palegoldenrod') for i in range(steps): g.edge(str(i), "c_{k}", fillcolor="gray") g.render(filename, view=False) if __name__ == '__main__': if len(sys.argv) != 2: print("usage:\n python {} ARCH_NAME".format(sys.argv[0])) sys.exit(1) genotype_name = sys.argv[1] try: genotype = eval('genotypes.{}'.format(genotype_name)) except AttributeError: print("{} is not specified in genotypes.py".format(genotype_name)) sys.exit(1) plot(genotype.normal, "normal_"+str(sys.argv[1])) plot(genotype.reduce, "reduction_"+str(sys.argv[1])) #plot_space(P['primitives_normal'], "space_normal") #plot_space(P['primitives_reduct'], "space_reduction")
1,882
0
46
f86649417dde7d4997f359927c0844d691b94fbb
845
py
Python
app/backend/meridien/settings/local.py
NicholasCF/meridien
dd00caf341d4c9979b89dc8441224ff2b97eac7f
[ "MIT" ]
null
null
null
app/backend/meridien/settings/local.py
NicholasCF/meridien
dd00caf341d4c9979b89dc8441224ff2b97eac7f
[ "MIT" ]
41
2020-05-24T06:47:53.000Z
2022-02-27T11:10:41.000Z
app/backend/meridien/settings/local.py
NicholasCF/meridien
dd00caf341d4c9979b89dc8441224ff2b97eac7f
[ "MIT" ]
2
2020-11-26T12:19:30.000Z
2020-12-19T01:14:02.000Z
from meridien.settings.base import * # SECURITY WARNING: don't run with debug turned on in production! DEBUG = True # SECURITY WARNING: keep the secret key used in production secret! SECRET_KEY = '8ka@=25ffr7377i_s*$$6n_=sepb1jpwhrbbgviphal7q=(3zz' # Database # https://docs.djangoproject.com/en/3.0/ref/settings/#databases DATABASES = { 'default': { 'ENGINE': 'django.db.backends.postgresql', 'NAME': 'postgres', 'USER': 'postgres', 'PASSWORD': 'sooperuser', 'HOST': '127.0.0.1', 'PORT': '5432', } } # CORS settings CORS_ORIGIN_ALLOW_ALL = False CORS_ORIGIN_WHITELIST = ( 'http://localhost:4200', 'http://127.0.0.1:4200', ) # Email settings EMAIL_BACKEND = 'django.core.mail.backends.console.EmailBackend' # Communication settings FRONT_END_DOMAIN = 'http://localhost:4200'
24.142857
66
0.67574
from meridien.settings.base import * # SECURITY WARNING: don't run with debug turned on in production! DEBUG = True # SECURITY WARNING: keep the secret key used in production secret! SECRET_KEY = '8ka@=25ffr7377i_s*$$6n_=sepb1jpwhrbbgviphal7q=(3zz' # Database # https://docs.djangoproject.com/en/3.0/ref/settings/#databases DATABASES = { 'default': { 'ENGINE': 'django.db.backends.postgresql', 'NAME': 'postgres', 'USER': 'postgres', 'PASSWORD': 'sooperuser', 'HOST': '127.0.0.1', 'PORT': '5432', } } # CORS settings CORS_ORIGIN_ALLOW_ALL = False CORS_ORIGIN_WHITELIST = ( 'http://localhost:4200', 'http://127.0.0.1:4200', ) # Email settings EMAIL_BACKEND = 'django.core.mail.backends.console.EmailBackend' # Communication settings FRONT_END_DOMAIN = 'http://localhost:4200'
0
0
0
7c9f348b03d42a72fc76f0d7f884d0b24a4362d0
807
py
Python
Easy/StringMatching.py
revanthsenthil/dCoder_select
20662123f1d3e1f9c7e8225eea7732be3a19ae57
[ "MIT" ]
1
2021-08-03T21:23:08.000Z
2021-08-03T21:23:08.000Z
Easy/StringMatching.py
revanthsenthil/dCoder-Solved
20662123f1d3e1f9c7e8225eea7732be3a19ae57
[ "MIT" ]
null
null
null
Easy/StringMatching.py
revanthsenthil/dCoder-Solved
20662123f1d3e1f9c7e8225eea7732be3a19ae57
[ "MIT" ]
1
2021-04-22T09:20:12.000Z
2021-04-22T09:20:12.000Z
""" Problem Description: Cody has a sequence of characters N. He likes a sequence if it contains his favourite sequence as a substring. Given the sequence and his favourite sequence F, check whether the favourite sequence is present in the sequence. Input: The first line of input contains a single line T, which represents the number of test cases. Each test case consists of 2 strings separated by space N and F respectively. Output: Print "Yes" if the sequence contains the favorite sequence in it, otherwise print "No". Constraints: 1<=T<=10. 1<=|N|,|F|<=100. All the characters are lowercase alphabets. Sample Input: 2 abcde abc pqrst pr Sample Output: Yes No """ n = int(input()) for i in range(n): a = input().split() if a[1] in a[0]: print("Yes") else: print("No")
23.057143
113
0.716233
""" Problem Description: Cody has a sequence of characters N. He likes a sequence if it contains his favourite sequence as a substring. Given the sequence and his favourite sequence F, check whether the favourite sequence is present in the sequence. Input: The first line of input contains a single line T, which represents the number of test cases. Each test case consists of 2 strings separated by space N and F respectively. Output: Print "Yes" if the sequence contains the favorite sequence in it, otherwise print "No". Constraints: 1<=T<=10. 1<=|N|,|F|<=100. All the characters are lowercase alphabets. Sample Input: 2 abcde abc pqrst pr Sample Output: Yes No """ n = int(input()) for i in range(n): a = input().split() if a[1] in a[0]: print("Yes") else: print("No")
0
0
0
03987ead140b81c6c957329556d3dd9eb6b94c02
3,079
py
Python
SLB.py
kinglionsoft/ali-ecs
8a7cd902dc0c691ba486585c42b80043da4a1597
[ "MIT" ]
null
null
null
SLB.py
kinglionsoft/ali-ecs
8a7cd902dc0c691ba486585c42b80043da4a1597
[ "MIT" ]
null
null
null
SLB.py
kinglionsoft/ali-ecs
8a7cd902dc0c691ba486585c42b80043da4a1597
[ "MIT" ]
null
null
null
# -*- coding: utf-8 -*- import sys from typing import List import requests from alibabacloud_slb20140515.client import Client as Slb20140515Client from alibabacloud_tea_openapi import models as open_api_models from alibabacloud_slb20140515 import models as slb_20140515_models if __name__ == '__main__': Sample.main(['<accessKeyId>', '<accessSecret>', '<region>', 'acl-id'])
33.467391
119
0.634622
# -*- coding: utf-8 -*- import sys from typing import List import requests from alibabacloud_slb20140515.client import Client as Slb20140515Client from alibabacloud_tea_openapi import models as open_api_models from alibabacloud_slb20140515 import models as slb_20140515_models class Sample: def __init__(self): pass @staticmethod def getCidr(url = 'http://140.246.36.49:40080'): response = requests.get(url) return response.text.replace('\n', '').replace('\r', '') @staticmethod def create_client( access_key_id: str, access_key_secret: str ) -> Slb20140515Client: """ 使用AK&SK初始化账号Client @param access_key_id: @param access_key_secret: @return: Client @throws Exception """ config = open_api_models.Config( # 您的AccessKey ID, access_key_id=access_key_id, # 您的AccessKey Secret, access_key_secret=access_key_secret ) # 访问的域名 config.endpoint = 'slb.aliyuncs.com' return Slb20140515Client(config) @staticmethod def main( args: List[str], ) -> None: region_id = args[2] acl_id = args[3] client = Sample.create_client(args[0], args[1]) describe_access_control_list_attribute_request = slb_20140515_models.DescribeAccessControlListAttributeRequest( region_id= region_id, acl_id=acl_id ) acl = client.describe_access_control_list_attribute(describe_access_control_list_attribute_request) print(acl.body) public_ip = '{0}/32'.format(Sample.getCidr()) print('public ip: ' + public_ip) if acl.body.acl_entrys is not None: public_entry = next((el for el in acl.body.acl_entrys.acl_entry if el.acl_entry_ip == public_ip), None) if public_entry is not None: print('public ip is already exists.') return 0 to_be_removing = acl.AclEntrys.AclEntry[:] else: to_be_removing = None add_access_control_list_entry_request = slb_20140515_models.AddAccessControlListEntryRequest( acl_entrys='[{"entry":"'+ public_ip +'","comment":"dev"}]', region_id= region_id, acl_id=acl_id ) client.add_access_control_list_entry(add_access_control_list_entry_request) print('added ' + public_ip) if to_be_removing is None: return 0 for entry in to_be_removing: remove_access_control_list_entry_request = slb_20140515_models.RemoveAccessControlListEntryRequest( region_id= region_id, acl_id=acl_id, acl_entrys='[{"entry":"{0}","comment":"dev"}]'.format(entry.AclEntryIP) ) client.remove_access_control_list_entry(remove_access_control_list_entry_request) print('removed '+ entry.AclEntryIP) if __name__ == '__main__': Sample.main(['<accessKeyId>', '<accessSecret>', '<region>', 'acl-id'])
1,965
740
23
e47cd2291ace2b554a9ac4ba430c9bd2a9575e07
7,555
py
Python
Robovest/robovest.py
yingluwang/Fin-Tech_Intelligent-Portforlio-Recommendation
7e1ef0ecc71d8335d25d5c2c5f219b5c5f9cdb66
[ "MIT" ]
2
2017-10-08T11:06:28.000Z
2019-06-10T07:43:46.000Z
Robovest/robovest.py
yingluwang/Fin-Tech_Intelligent-Portforlio-Recommendation
7e1ef0ecc71d8335d25d5c2c5f219b5c5f9cdb66
[ "MIT" ]
1
2020-06-05T18:10:52.000Z
2020-06-05T18:10:52.000Z
Robovest/robovest.py
yingluwang/Fin-Tech_Intelligent-Portforlio-Recommendation
7e1ef0ecc71d8335d25d5c2c5f219b5c5f9cdb66
[ "MIT" ]
1
2018-06-13T02:49:22.000Z
2018-06-13T02:49:22.000Z
# all the imports import psycopg2 import nltk from robovest.portfolio import* #nltk.download() import tweepy import os import sqlite3 import datetime import numpy as np from nltk.sentiment.vader import SentimentIntensityAnalyzer from flask import Flask, request, session, g, redirect, url_for, abort, \ render_template, flash app = Flask(__name__) # create the application instance :) app.config.from_object(__name__) # load config from this file , flaskr.py tickers = ["MINT","EMB","IAU","VCIT","MUB","SCHA","VEA","VYM","SCHH","VWO","FENY","VTIP","VGLT","ITE"] Twitter_Average=.0091 Twitter_STD=.154 consumer_key = os.environ["TWITTER_API_KEY"] consumer_secret = os.environ["TWITTER_API_SECRET"] access_token = os.environ["TWITTER_ACCESS_TOKEN"] access_token_secret = os.environ["TWITTER_ACCESS_TOKEN_SECRET"] # AUTHENTICATE auth = tweepy.OAuthHandler(consumer_key, consumer_secret) auth.set_access_token(access_token, access_token_secret) # INITIALIZE API CLIENT api = tweepy.API(auth) startDate = datetime.datetime(2017, 7, 1, 0, 0, 0) endDate = datetime.datetime(2017, 8, 4, 0, 0, 0) # Load default config and override config from an environment variable app.config.update(dict( DATABASE=os.path.join(app.root_path, 'robovest.db'), SECRET_KEY='development key', USERNAME='robo', PASSWORD='vest' )) app.config.from_envvar('ROBOVEST_SETTINGS', silent=True) def connect_db(): """Connects to the specific database.""" rv = sqlite3.connect(app.config['DATABASE']) rv.row_factory = sqlite3.Row return rv def get_db(): """Opens a new database connection if there is none yet for the current application context. """ if not hasattr(g, 'sqlite_db'): g.sqlite_db = connect_db() return g.sqlite_db # def portfolio_recommendation(score): # weights_bl, return_bl, risk_bl = portfolio(score) # return weights_bl, return_bl, risk_bl @app.route('/add', methods=['POST']) @app.route('/index', methods=['GET','POST']) @app.route('/') @app.cli.command('initdb') def initdb_command(): """Initializes the database.""" init_db() print('Initialized the database.') @app.teardown_appcontext def close_db(error): """Closes the database again at the end of the request.""" if hasattr(g, 'sqlite_db'): g.sqlite_db.close() @app.route('/login', methods=['GET', 'POST']) @app.route('/logout')
31.348548
401
0.647386
# all the imports import psycopg2 import nltk from robovest.portfolio import* #nltk.download() import tweepy import os import sqlite3 import datetime import numpy as np from nltk.sentiment.vader import SentimentIntensityAnalyzer from flask import Flask, request, session, g, redirect, url_for, abort, \ render_template, flash app = Flask(__name__) # create the application instance :) app.config.from_object(__name__) # load config from this file , flaskr.py tickers = ["MINT","EMB","IAU","VCIT","MUB","SCHA","VEA","VYM","SCHH","VWO","FENY","VTIP","VGLT","ITE"] Twitter_Average=.0091 Twitter_STD=.154 consumer_key = os.environ["TWITTER_API_KEY"] consumer_secret = os.environ["TWITTER_API_SECRET"] access_token = os.environ["TWITTER_ACCESS_TOKEN"] access_token_secret = os.environ["TWITTER_ACCESS_TOKEN_SECRET"] # AUTHENTICATE auth = tweepy.OAuthHandler(consumer_key, consumer_secret) auth.set_access_token(access_token, access_token_secret) # INITIALIZE API CLIENT api = tweepy.API(auth) startDate = datetime.datetime(2017, 7, 1, 0, 0, 0) endDate = datetime.datetime(2017, 8, 4, 0, 0, 0) # Load default config and override config from an environment variable app.config.update(dict( DATABASE=os.path.join(app.root_path, 'robovest.db'), SECRET_KEY='development key', USERNAME='robo', PASSWORD='vest' )) app.config.from_envvar('ROBOVEST_SETTINGS', silent=True) def connect_db(): """Connects to the specific database.""" rv = sqlite3.connect(app.config['DATABASE']) rv.row_factory = sqlite3.Row return rv def init_db(): db = get_db() with app.open_resource('schema.sql', mode='r') as f: db.cursor().executescript(f.read()) db.commit() def get_db(): """Opens a new database connection if there is none yet for the current application context. """ if not hasattr(g, 'sqlite_db'): g.sqlite_db = connect_db() return g.sqlite_db def age_adj(): db = get_db() cur = db.execute('select age from entries') age1 = cur.fetchone()[0] if age1 > 82 or age1 == 82: age1_adj = 0 elif age1 < 35 or age1 == 35: age1_adj = 1 else: age1_adj = (-0.021)*(age1 -35+1)+1.02 return age1_adj def income_adj(): db = get_db() cur = db.execute('select income from entries order by id desc') income1 = cur.fetchone()[0] if income1 > 10500 or income1 == 10500: income_adj1 = 1 elif income1 < 3750 or income1 == 3750: income_adj1 = 0 else: income_adj1 = (-0.00015)*(10500-income1)+1 return income_adj1 def worth_adj(): db = get_db() cur = db.execute('select worth from entries order by id desc') worth1 = cur.fetchone()[0] if worth1 > 25000 or worth1 == 25000: worth_adj1 = 1 elif worth1 < 5000 or worth1 == 5000: worth_adj1 = 0 else: worth_adj1 = (-0.00005)*(25000-worth1)+1 return worth_adj1 def pref_adj(): db = get_db() cur = db.execute('select preference from entries order by id desc') pref1 = cur.fetchone()[0] if pref1 == "b": q1 = 1 else: q1 = 2 return q1 def house_adj(): db = get_db() cur = db.execute('select household from entries order by id desc') house = cur.fetchone()[0] if house == "b" or house == "d": q2 = 1.5 else: q2 = 2 return q2 def action_adj(): db = get_db() cur = db.execute('select action from entries order by id desc') action1 = cur.fetchone()[0] if action1 == "a": q3 = 1 elif action1 == "b": q3 = 2 elif action1 == "c": q3 = 2.5 else: q3 = 3 return q3 def adj_sentiment(): db = get_db() cur = db.execute('select handle from entries order by id desc') handle1 = cur.fetchone() tweetxt=[] tweets = api.user_timeline(screen_name= handle1, count=1000, includerts=False) for tweet in tweets: if tweet.created_at < endDate and tweet.created_at > startDate: tweetxt.append(tweet.text) sa = SentimentIntensityAnalyzer() scores_ind = [] for twit in tweetxt: score = sa.polarity_scores(twit) scores_ind.append(score) diff_ind_list = [ ] for row in scores_ind: pos = row["pos"] neg = row["neg"] def dif(pos,neg): return float(pos-neg) diff_ind = dif(pos,neg) diff_ind_list.append(diff_ind) avg_ind = np.mean([diff_ind_list]) adj1_sentiment= (avg_ind-Twitter_Average)/(1.96*Twitter_STD) return adj1_sentiment def risk_tolerance(): z=age_adj() y=income_adj() x=worth_adj() w=pref_adj() v=house_adj() u=action_adj() t=adj_sentiment() #risk_score=age_adj+income_adj+worth_adj+q1+q2+q3 risk_score=z+y+x+w+v+u+t return risk_score # def portfolio_recommendation(score): # weights_bl, return_bl, risk_bl = portfolio(score) # return weights_bl, return_bl, risk_bl @app.route('/add', methods=['POST']) def add_entry(): if not session.get('logged_in'): abort(401) db = get_db() db.execute('insert into entries (alias, age, income, worth, preference, household, action, handle) values (?, ?, ?, ?, ?, ?, ?, ?)', [request.form['alias'], request.form['age'], request.form['income'], request.form['worth'], request.form['preference'], request.form['household'], request.form['action'],request.form['handle']]) risk1=risk_tolerance() db.execute('insert into entries (risk) values (?)',[risk1]) weights_bl, return_bl, risk_bl = portfolio(risk1) db.execute('insert into entries (etf1, etf2, etf3, etf4, etf5, etf6, etf7, etf8, etf9, etf10, etf11, etf12, etf13, etf14, return, vol) values (?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?)',[weights_bl[0],weights_bl[1],weights_bl[2],weights_bl[3],weights_bl[4],weights_bl[5],weights_bl[6],weights_bl[7],weights_bl[8],weights_bl[9],weights_bl[10],weights_bl[11],weights_bl[12],weights_bl[13],return_bl,risk_bl]) db.commit() flash('New entry was successfully posted') return redirect(url_for('show_entries')) @app.route('/index', methods=['GET','POST']) def image(): return render_template('index.html') @app.route('/') def show_entries(): db = get_db() cur = db.execute('select alias, age, income, worth, preference, household, action, risk, etf1, etf2, etf3, etf4, etf5, etf6, etf7, etf8, etf9, etf10, etf11, etf12, etf13, etf14, return, vol from entries order by id desc') entries = cur.fetchall() return render_template('show_entries.html', entries=entries) @app.cli.command('initdb') def initdb_command(): """Initializes the database.""" init_db() print('Initialized the database.') @app.teardown_appcontext def close_db(error): """Closes the database again at the end of the request.""" if hasattr(g, 'sqlite_db'): g.sqlite_db.close() @app.route('/login', methods=['GET', 'POST']) def login(): error = None if request.method == 'POST': if request.form['username'] != app.config['USERNAME']: error = 'Invalid username' elif request.form['password'] != app.config['PASSWORD']: error = 'Invalid password' else: session['logged_in'] = True flash('Thanks for logging in, lets get started!') return redirect(url_for('show_entries')) return render_template('login.html', error=error) @app.route('/logout') def logout(): session.pop('logged_in', None) flash('You were logged out') return redirect(url_for('show_entries'))
4,845
0
317
72c35ea74260260a0e6d310370bc1e461a820f05
6,051
py
Python
metadata-ingestion/src/datahub/ingestion/sink/datahub_rest.py
LucaBassanesecuebiq/datahub
f659cc89388cc6322795c7ba7758d65775a7dedf
[ "Apache-2.0" ]
null
null
null
metadata-ingestion/src/datahub/ingestion/sink/datahub_rest.py
LucaBassanesecuebiq/datahub
f659cc89388cc6322795c7ba7758d65775a7dedf
[ "Apache-2.0" ]
1
2022-02-02T17:26:16.000Z
2022-02-02T17:26:16.000Z
metadata-ingestion/src/datahub/ingestion/sink/datahub_rest.py
liftoffio/datahub
ff163059587a137a22fa0c655f568a40eda44236
[ "Apache-2.0" ]
null
null
null
import concurrent.futures import functools import logging from dataclasses import dataclass from typing import Union, cast from datahub.cli.cli_utils import set_env_variables_override_config from datahub.configuration.common import OperationalError from datahub.emitter.mcp import MetadataChangeProposalWrapper from datahub.emitter.rest_emitter import DatahubRestEmitter from datahub.ingestion.api.common import PipelineContext, RecordEnvelope, WorkUnit from datahub.ingestion.api.sink import Sink, SinkReport, WriteCallback from datahub.ingestion.api.workunit import MetadataWorkUnit from datahub.ingestion.graph.client import DatahubClientConfig from datahub.metadata.com.linkedin.pegasus2avro.mxe import ( MetadataChangeEvent, MetadataChangeProposal, ) from datahub.metadata.com.linkedin.pegasus2avro.usage import UsageAggregation from datahub.utilities.server_config_util import set_gms_config logger = logging.getLogger(__name__) @dataclass @dataclass
39.03871
97
0.632788
import concurrent.futures import functools import logging from dataclasses import dataclass from typing import Union, cast from datahub.cli.cli_utils import set_env_variables_override_config from datahub.configuration.common import OperationalError from datahub.emitter.mcp import MetadataChangeProposalWrapper from datahub.emitter.rest_emitter import DatahubRestEmitter from datahub.ingestion.api.common import PipelineContext, RecordEnvelope, WorkUnit from datahub.ingestion.api.sink import Sink, SinkReport, WriteCallback from datahub.ingestion.api.workunit import MetadataWorkUnit from datahub.ingestion.graph.client import DatahubClientConfig from datahub.metadata.com.linkedin.pegasus2avro.mxe import ( MetadataChangeEvent, MetadataChangeProposal, ) from datahub.metadata.com.linkedin.pegasus2avro.usage import UsageAggregation from datahub.utilities.server_config_util import set_gms_config logger = logging.getLogger(__name__) class DatahubRestSinkConfig(DatahubClientConfig): pass @dataclass class DataHubRestSinkReport(SinkReport): gms_version: str = "" @dataclass class DatahubRestSink(Sink): config: DatahubRestSinkConfig emitter: DatahubRestEmitter report: DataHubRestSinkReport treat_errors_as_warnings: bool = False def __init__(self, ctx: PipelineContext, config: DatahubRestSinkConfig): super().__init__(ctx) self.config = config self.report = DataHubRestSinkReport() self.emitter = DatahubRestEmitter( self.config.server, self.config.token, connect_timeout_sec=self.config.timeout_sec, # reuse timeout_sec for connect timeout read_timeout_sec=self.config.timeout_sec, retry_status_codes=self.config.retry_status_codes, retry_max_times=self.config.retry_max_times, extra_headers=self.config.extra_headers, ca_certificate_path=self.config.ca_certificate_path, ) gms_config = self.emitter.test_connection() self.report.gms_version = ( gms_config.get("versions", {}) .get("linkedin/datahub", {}) .get("version", "") ) logger.debug("Setting env variables to override config") set_env_variables_override_config(self.config.server, self.config.token) logger.debug("Setting gms config") set_gms_config(gms_config) self.executor = concurrent.futures.ThreadPoolExecutor( max_workers=self.config.max_threads ) @classmethod def create(cls, config_dict: dict, ctx: PipelineContext) -> "DatahubRestSink": config = DatahubRestSinkConfig.parse_obj(config_dict) return cls(ctx, config) def handle_work_unit_start(self, workunit: WorkUnit) -> None: if isinstance(workunit, MetadataWorkUnit): mwu: MetadataWorkUnit = cast(MetadataWorkUnit, workunit) self.treat_errors_as_warnings = mwu.treat_errors_as_warnings def handle_work_unit_end(self, workunit: WorkUnit) -> None: pass def _write_done_callback( self, record_envelope: RecordEnvelope, write_callback: WriteCallback, future: concurrent.futures.Future, ) -> None: if future.cancelled(): self.report.report_failure({"error": "future was cancelled"}) write_callback.on_failure( record_envelope, OperationalError("future was cancelled"), {} ) elif future.done(): e = future.exception() if not e: self.report.report_record_written(record_envelope) start_time, end_time = future.result() self.report.report_downstream_latency(start_time, end_time) write_callback.on_success(record_envelope, {}) elif isinstance(e, OperationalError): # only OperationalErrors should be ignored if not self.treat_errors_as_warnings: self.report.report_failure({"error": e.message, "info": e.info}) else: # trim exception stacktraces when reporting warnings if "stackTrace" in e.info: try: e.info["stackTrace"] = "\n".join( e.info["stackTrace"].split("\n")[0:2] ) except Exception: # ignore failures in trimming pass record = record_envelope.record if isinstance(record, MetadataChangeProposalWrapper): # include information about the entity that failed entity_id = cast( MetadataChangeProposalWrapper, record ).entityUrn e.info["id"] = entity_id else: entity_id = None self.report.report_warning({"warning": e.message, "info": e.info}) write_callback.on_failure(record_envelope, e, e.info) else: self.report.report_failure({"e": e}) write_callback.on_failure(record_envelope, Exception(e), {}) def write_record_async( self, record_envelope: RecordEnvelope[ Union[ MetadataChangeEvent, MetadataChangeProposal, MetadataChangeProposalWrapper, UsageAggregation, ] ], write_callback: WriteCallback, ) -> None: record = record_envelope.record write_future = self.executor.submit(self.emitter.emit, record) write_future.add_done_callback( functools.partial( self._write_done_callback, record_envelope, write_callback ) ) def get_report(self) -> SinkReport: return self.report def close(self): self.executor.shutdown(wait=True)
4,547
465
67
9c43110fdc192b45c3d8ed5df71194250983b1d9
63
py
Python
django_project/kv_settings/__init__.py
eshandas/django_key_value_settings
70ba8c0877f4b59cb66e69507b1e78bbd62f7e65
[ "MIT" ]
null
null
null
django_project/kv_settings/__init__.py
eshandas/django_key_value_settings
70ba8c0877f4b59cb66e69507b1e78bbd62f7e65
[ "MIT" ]
7
2020-06-06T00:25:53.000Z
2022-03-12T00:03:44.000Z
kv_settings/__init__.py
eshandas/django_key_value_settings
70ba8c0877f4b59cb66e69507b1e78bbd62f7e65
[ "MIT" ]
null
null
null
default_app_config = 'kv_settings.apps.KeyValueSettingsConfig'
31.5
62
0.873016
default_app_config = 'kv_settings.apps.KeyValueSettingsConfig'
0
0
0
794b4ed15c8f93c479bec99b65b51a11d39732e7
377
py
Python
flows/models.py
sergioisidoro/django-flows
326baa3e216a15bd7a8d13b2a09ba9752e250dbb
[ "BSD-2-Clause" ]
104
2015-01-05T14:29:16.000Z
2021-11-08T11:20:24.000Z
flows/models.py
sergioisidoro/django-flows
326baa3e216a15bd7a8d13b2a09ba9752e250dbb
[ "BSD-2-Clause" ]
4
2015-09-23T11:14:50.000Z
2020-03-21T06:08:34.000Z
flows/models.py
sergioisidoro/django-flows
326baa3e216a15bd7a8d13b2a09ba9752e250dbb
[ "BSD-2-Clause" ]
16
2015-01-05T10:13:44.000Z
2022-02-14T05:21:23.000Z
# -*- coding: UTF-8 -*- # Note: this is mainly required because using the Django test runner # requires that apps under test have a 'models' module, even if it's # just empty. from flows import config if config.FLOWS_STATE_STORE == 'flows.statestore.django_store': from flows.statestore.django_store import StateModel #@UnusedImport only used to registed with django ORM
37.7
109
0.763926
# -*- coding: UTF-8 -*- # Note: this is mainly required because using the Django test runner # requires that apps under test have a 'models' module, even if it's # just empty. from flows import config if config.FLOWS_STATE_STORE == 'flows.statestore.django_store': from flows.statestore.django_store import StateModel #@UnusedImport only used to registed with django ORM
0
0
0
b1c9d24c4d92140fd0fc0bd73cab307649f1602b
439
py
Python
Thread_Socket/Thread-Multiprocess.py
dumin199101/Scrapy-Project
b4135beb73a2c5aad1728f747c1856266af649dd
[ "Apache-2.0" ]
1
2019-07-11T03:28:25.000Z
2019-07-11T03:28:25.000Z
Thread_Socket/Thread-Multiprocess.py
dumin199101/Scrapy-Project
b4135beb73a2c5aad1728f747c1856266af649dd
[ "Apache-2.0" ]
null
null
null
Thread_Socket/Thread-Multiprocess.py
dumin199101/Scrapy-Project
b4135beb73a2c5aad1728f747c1856266af649dd
[ "Apache-2.0" ]
null
null
null
# coding=utf-8 """ 使用multiprocessing模块创建多进程 """ import os from multiprocessing import Process # 子进程要执行的代码 if __name__ == '__main__': print('Parent process %s.'% os.getpid()) for i in range(5): p = Process(target=run_proc,args=(str(i),)) print('Process will start.') p.start() p.join() print('Process will end.')
23.105263
65
0.626424
# coding=utf-8 """ 使用multiprocessing模块创建多进程 """ import os from multiprocessing import Process # 子进程要执行的代码 def run_proc(name): print('Child progress %s (%s) Running...'%(name,os.getpid())) if __name__ == '__main__': print('Parent process %s.'% os.getpid()) for i in range(5): p = Process(target=run_proc,args=(str(i),)) print('Process will start.') p.start() p.join() print('Process will end.')
64
0
22
874402dc3739cdffb2a6dc31b45049338e340ffd
5,258
py
Python
web/server/views.py
p-schlickmann/proffy-app
2c8edb3195993e29f2c4033eed1f330ea79a5cd6
[ "MIT" ]
null
null
null
web/server/views.py
p-schlickmann/proffy-app
2c8edb3195993e29f2c4033eed1f330ea79a5cd6
[ "MIT" ]
null
null
null
web/server/views.py
p-schlickmann/proffy-app
2c8edb3195993e29f2c4033eed1f330ea79a5cd6
[ "MIT" ]
null
null
null
from django.shortcuts import render import time import datetime from server import models # Create your views here.
33.922581
132
0.579498
from django.shortcuts import render import time import datetime from server import models # Create your views here. def index(request): return render(request, "server/index.html") def study(request): return render(request, "server/study.html", { 'proffys': models.Teacher.objects.all() }) def teach(main_request): if main_request.method == 'GET': return render(main_request, "server/give-classes.html") elif main_request.method == 'POST': request = dict(main_request.POST) print(request) name = request.get('name')[0] img_url = request.get('avatar')[0] whatsapp = int(request.get('whatsapp')[0]) bio = request.get('bio')[0] subject_id = request.get('subject')[0] subject_name = convert_id(subject_id) cost = int(request.get('cost')[0]) week_day = request['weekday[]'] week_day_name = [convert_id(week_day_id, day=True) for week_day_id in week_day] starts = request['time_from[]'] start_seconds = [convert_to_seconds(start) for start in starts] ends = request.get('time_to[]') end_seconds = [convert_to_seconds(end) for end in ends] new_teacher = models.Teacher(name=name, avatar_url=img_url, whatsapp=whatsapp, bio=bio, subject=subject_id, subject_name=subject_name, cost=cost) new_teacher.save() for wk_day, wk_day_name, st, st_sec, en, end_secs in zip(week_day, week_day_name, starts, start_seconds, ends, end_seconds): new_class = models.Class(teacher=new_teacher, week_day=wk_day, week_day_name=wk_day_name, start=st, end=en, start_seconds=st_sec, end_seconds=end_secs) new_class.save() return render(main_request, "server/study.html", { 'proffys': models.Teacher.objects.all() }) def search(request): subject = request.GET.get('subject', None) week_day = request.GET.get('weekday', None) time = convert_to_seconds(request.GET.get('time', None)) matches = [] if subject and week_day and time: teachers = models.Teacher.objects.filter(subject=subject) for teacher in teachers: classes = teacher.classes.filter(week_day=week_day) for _class in classes: start = _class.start_seconds end = _class.end_seconds - 3600 if end >= time >= start: if _class.teacher not in matches: matches.append(_class.teacher) elif subject and week_day: teachers = models.Teacher.objects.filter(subject=subject) classes = [teacher.classes.filter(week_day=week_day) for teacher in teachers][0] for _class in classes: if _class.teacher not in matches: matches.append(_class.teacher) elif week_day and time: classes = models.Class.objects.filter(week_day=week_day) for _class in classes: start = _class.start_seconds end = _class.end_seconds - 3600 if end >= time >= start: if _class.teacher not in matches: matches.append(_class.teacher) elif subject and time: teachers = models.Teacher.objects.filter(subject=subject) for teacher in teachers: classes = teacher.classes.all() for _class in classes: start = _class.start_seconds end = _class.end_seconds - 3600 if end >= time >= start: if _class.teacher not in matches: matches.append(_class.teacher) elif subject: matches = models.Teacher.objects.filter(subject=subject) elif week_day: classes = models.Class.objects.filter(week_day=week_day) for _class in classes: if _class.teacher not in matches: matches.append(_class.teacher) elif time: classes = models.Class.objects.all() for _class in classes: start = _class.start_seconds end = _class.end_seconds - 3600 if end >= time >= start: if _class.teacher not in matches: matches.append(_class.teacher) elif not week_day and not subject and not time: matches = models.Teacher.objects.all() else: matches = None return render(request, "server/study.html", { 'proffys': matches }) def convert_id(_id, day=False): if not day: conv = { 1: 'Artes', 2: 'Biologia', 3: 'Ciências', 4: 'Educação Física', 5: 'Física', 6: 'Geografia', 7: 'História', 8: 'Matemática', 9: 'Português', 10: 'Química', } else: conv = { 1: 'Domingo', 2: 'Segunda', 3: 'Terça', 4: 'Quarta', 5: 'Quinta', 6: 'Sexta', 7: 'Sábado', } return conv[int(_id)] def convert_to_seconds(time): if not time: return None ftr = [3600, 60] return sum([a * b for a, b in zip(ftr, map(int, time.split(':')))])
5,006
0
138
7354772c1b94e715c0a4c2319b9b462e99ca7ccd
739
py
Python
tests/data.py
szymonmaszke/torchtraining
1ddf169325b7239d6d6686b20072a406b69a0180
[ "MIT" ]
3
2020-08-26T06:11:58.000Z
2020-08-27T08:11:15.000Z
tests/data.py
klaudiapalasz/torchtraining
7ac54009eea2fd84aa635b6f3cbfe306f317d087
[ "MIT" ]
1
2020-08-25T19:19:43.000Z
2020-08-25T19:19:43.000Z
tests/data.py
klaudiapalasz/torchtraining
7ac54009eea2fd84aa635b6f3cbfe306f317d087
[ "MIT" ]
1
2021-04-15T18:55:57.000Z
2021-04-15T18:55:57.000Z
import typing import torch import torchtraining as tt import torchvision
28.423077
84
0.638701
import typing import torch import torchtraining as tt import torchvision def get(batch_size: int) -> typing.Dict: train, validation = tt.functional.data.random_split( torchvision.datasets.FakeData( size=64, image_size=(3, 28, 28), transform=torchvision.transforms.ToTensor(), ), 0.8, 0.2, ) test = torchvision.datasets.FakeData( size=32, image_size=(3, 28, 28), transform=torchvision.transforms.ToTensor() ) return { "train": torch.utils.data.DataLoader(train, batch_size, shuffle=True), "validation": torch.utils.data.DataLoader(validation, batch_size), "test": torch.utils.data.DataLoader(test, batch_size), }
641
0
23
06f067b36da9ed63fc57904f7389ad728f45b423
425
py
Python
setup.py
rlugojr/pygments-snowball
4d9b086f4e2f81a3cd351c1fd2eaddf0d20abee9
[ "BSD-2-Clause" ]
2
2018-03-01T05:38:42.000Z
2021-02-08T15:49:59.000Z
setup.py
rlugojr/pygments-snowball
4d9b086f4e2f81a3cd351c1fd2eaddf0d20abee9
[ "BSD-2-Clause" ]
1
2015-10-09T04:33:10.000Z
2015-10-09T04:33:10.000Z
setup.py
rlugojr/pygments-snowball
4d9b086f4e2f81a3cd351c1fd2eaddf0d20abee9
[ "BSD-2-Clause" ]
2
2015-10-09T00:23:46.000Z
2017-02-20T06:28:33.000Z
from setuptools import setup setup( name="Pygments Snowball Plugin", version = "1.0", scripts = ['pygments_snowball.py'], entry_points = """ [pygments.lexers] snowball_lexer = pygments_snowball:SnowballLexer """, description = 'Pygments Lexer Plugin for Snowball', license = 'BSD 2-Clause License', author = 'Hajime Senuma', author_email = 'hajime.senuma@gmail.com', )
28.333333
56
0.649412
from setuptools import setup setup( name="Pygments Snowball Plugin", version = "1.0", scripts = ['pygments_snowball.py'], entry_points = """ [pygments.lexers] snowball_lexer = pygments_snowball:SnowballLexer """, description = 'Pygments Lexer Plugin for Snowball', license = 'BSD 2-Clause License', author = 'Hajime Senuma', author_email = 'hajime.senuma@gmail.com', )
0
0
0
6f8359d5ef293b0acd6612a7956555e5aaa066b7
2,664
py
Python
GSAS-II-WONDER/imports/G2img_Rigaku.py
WONDER-project/GSAS-II-WONDER-OSX
f90ab85f89f282d1b9686a1cbbf5adc5c48ceac9
[ "MIT" ]
null
null
null
GSAS-II-WONDER/imports/G2img_Rigaku.py
WONDER-project/GSAS-II-WONDER-OSX
f90ab85f89f282d1b9686a1cbbf5adc5c48ceac9
[ "MIT" ]
null
null
null
GSAS-II-WONDER/imports/G2img_Rigaku.py
WONDER-project/GSAS-II-WONDER-OSX
f90ab85f89f282d1b9686a1cbbf5adc5c48ceac9
[ "MIT" ]
null
null
null
# -*- coding: utf-8 -*- ########### SVN repository information ################### # $Date: 2017-10-23 11:39:16 -0500 (Mon, 23 Oct 2017) $ # $Author: vondreele $ # $Revision: 3136 $ # $URL: https://subversion.xray.aps.anl.gov/pyGSAS/trunk/imports/G2img_Rigaku.py $ # $Id: G2img_Rigaku.py 3136 2017-10-23 16:39:16Z vondreele $ ########### SVN repository information ################### ''' *Module G2img_Rigaku: .stl image file* -------------------------------------- ''' from __future__ import division, print_function import os import GSASIIobj as G2obj import GSASIIpath import numpy as np GSASIIpath.SetVersionNumber("$Revision: 3136 $") class Rigaku_ReaderClass(G2obj.ImportImage): '''Routine to read a Rigaku R-Axis IV image file. ''' def ContentsValidator(self, filename): '''Test by checking if the file size makes sense. ''' fileSize = os.stat(filename).st_size Npix = (fileSize-6000)/2 if Npix == 9000000 or Npix == 2250000 or Npix == 36000000: return True return False # not valid size def GetRigaku(filename,imageOnly=False): 'Read Rigaku R-Axis IV image file' import array as ar if not imageOnly: print ('Read Rigaku R-Axis IV file: '+filename) File = open(filename,'rb') fileSize = os.stat(filename).st_size Npix = (fileSize-6000)/2 File.read(6000) head = ['Rigaku R-Axis IV detector data',] image = np.array(ar.array('H',File.read(fileSize-6000)),dtype=np.int32) print ('%s %s'%(fileSize,str(image.shape))) print (head) if Npix == 9000000: sizexy = [3000,3000] pixSize = [100.,100.] elif Npix == 2250000: sizexy = [1500,1500] pixSize = [200.,200.] else: sizexy = [6000,6000] pixSize = [50.,50.] image = np.reshape(image,(sizexy[1],sizexy[0])) data = {'pixelSize':pixSize,'wavelength':1.5428,'distance':250.0,'center':[150.,150.],'size':sizexy} File.close() if imageOnly: return image else: return head,data,Npix,image
34.597403
106
0.596471
# -*- coding: utf-8 -*- ########### SVN repository information ################### # $Date: 2017-10-23 11:39:16 -0500 (Mon, 23 Oct 2017) $ # $Author: vondreele $ # $Revision: 3136 $ # $URL: https://subversion.xray.aps.anl.gov/pyGSAS/trunk/imports/G2img_Rigaku.py $ # $Id: G2img_Rigaku.py 3136 2017-10-23 16:39:16Z vondreele $ ########### SVN repository information ################### ''' *Module G2img_Rigaku: .stl image file* -------------------------------------- ''' from __future__ import division, print_function import os import GSASIIobj as G2obj import GSASIIpath import numpy as np GSASIIpath.SetVersionNumber("$Revision: 3136 $") class Rigaku_ReaderClass(G2obj.ImportImage): '''Routine to read a Rigaku R-Axis IV image file. ''' def __init__(self): super(self.__class__,self).__init__( # fancy way to self-reference extensionlist=('.stl',), strictExtension=True, formatName = 'Rigaku image', longFormatName = 'Read Rigaku R-Axis IV image file' ) def ContentsValidator(self, filename): '''Test by checking if the file size makes sense. ''' fileSize = os.stat(filename).st_size Npix = (fileSize-6000)/2 if Npix == 9000000 or Npix == 2250000 or Npix == 36000000: return True return False # not valid size def Reader(self,filename, ParentFrame=None, **unused): self.Comments,self.Data,self.Npix,self.Image = GetRigaku(filename) if self.Npix == 0 or not self.Comments: return False self.LoadImage(ParentFrame,filename) return True def GetRigaku(filename,imageOnly=False): 'Read Rigaku R-Axis IV image file' import array as ar if not imageOnly: print ('Read Rigaku R-Axis IV file: '+filename) File = open(filename,'rb') fileSize = os.stat(filename).st_size Npix = (fileSize-6000)/2 File.read(6000) head = ['Rigaku R-Axis IV detector data',] image = np.array(ar.array('H',File.read(fileSize-6000)),dtype=np.int32) print ('%s %s'%(fileSize,str(image.shape))) print (head) if Npix == 9000000: sizexy = [3000,3000] pixSize = [100.,100.] elif Npix == 2250000: sizexy = [1500,1500] pixSize = [200.,200.] else: sizexy = [6000,6000] pixSize = [50.,50.] image = np.reshape(image,(sizexy[1],sizexy[0])) data = {'pixelSize':pixSize,'wavelength':1.5428,'distance':250.0,'center':[150.,150.],'size':sizexy} File.close() if imageOnly: return image else: return head,data,Npix,image
509
0
61
0119dceea660beaed65024aa33059b7c1e1cc25a
1,889
py
Python
src/m6_your_turtles.py
shaneecho/01-IntroductionToPython
4bd03dd0631b24a8a58c6709c05c73eea9dc1567
[ "MIT" ]
null
null
null
src/m6_your_turtles.py
shaneecho/01-IntroductionToPython
4bd03dd0631b24a8a58c6709c05c73eea9dc1567
[ "MIT" ]
null
null
null
src/m6_your_turtles.py
shaneecho/01-IntroductionToPython
4bd03dd0631b24a8a58c6709c05c73eea9dc1567
[ "MIT" ]
null
null
null
""" Your chance to explore Loops and Turtles! Authors: David Mutchler, Vibha Alangar, Matt Boutell, Dave Fisher, Aaron Wilkin, their colleagues, and Shixin Yan. """ ######################################################################## # DONE: 1. # On Line 5 above, replace PUT_YOUR_NAME_HERE with your own name. ######################################################################## ######################################################################## # TODO: 2. # You should have RUN the m5e_loopy_turtles module and READ its code. # (Do so now if you have not already done so.) # # Below this comment, add ANY CODE THAT YOU WANT, as long as: # 1. You construct at least 2 rg.SimpleTurtle objects. # 2. Each rg.SimpleTurtle object draws something # (by moving, using its rg.Pen). ANYTHING is fine! # 3. Each rg.SimpleTurtle moves inside a LOOP. # # Be creative! Strive for way-cool pictures! Abstract pictures rule! # # If you make syntax (notational) errors, no worries -- get help # fixing them at either this session OR at the NEXT session. # # Don't forget to COMMIT-and-PUSH when you are done with this module. # ######################################################################## import rosegraphics as rg window = rg.TurtleWindow() flash = rg.SimpleTurtle('turtle') flash.pen = rg.Pen('yellow', 3) zoom = rg.SimpleTurtle('turtle') zoom.pen = rg.Pen('black', 3) flash.speed = 50 zoom.speed = 50 size = 70 for k in range(18): flash.draw_square(size) zoom.draw_circle(size) flash.pen_down() flash.right(20) flash.forward(30) zoom.pen_down() zoom.left(20) zoom.backward(30) window.tracer(20) damage = rg.SimpleTurtle('triangle') damage.pen = rg.Pen('dark blue',1) damage.backward(30) for k in range(1000): damage.right(50) damage.forward(2*k) window.close_on_mouse_click()
31.483333
73
0.586024
""" Your chance to explore Loops and Turtles! Authors: David Mutchler, Vibha Alangar, Matt Boutell, Dave Fisher, Aaron Wilkin, their colleagues, and Shixin Yan. """ ######################################################################## # DONE: 1. # On Line 5 above, replace PUT_YOUR_NAME_HERE with your own name. ######################################################################## ######################################################################## # TODO: 2. # You should have RUN the m5e_loopy_turtles module and READ its code. # (Do so now if you have not already done so.) # # Below this comment, add ANY CODE THAT YOU WANT, as long as: # 1. You construct at least 2 rg.SimpleTurtle objects. # 2. Each rg.SimpleTurtle object draws something # (by moving, using its rg.Pen). ANYTHING is fine! # 3. Each rg.SimpleTurtle moves inside a LOOP. # # Be creative! Strive for way-cool pictures! Abstract pictures rule! # # If you make syntax (notational) errors, no worries -- get help # fixing them at either this session OR at the NEXT session. # # Don't forget to COMMIT-and-PUSH when you are done with this module. # ######################################################################## import rosegraphics as rg window = rg.TurtleWindow() flash = rg.SimpleTurtle('turtle') flash.pen = rg.Pen('yellow', 3) zoom = rg.SimpleTurtle('turtle') zoom.pen = rg.Pen('black', 3) flash.speed = 50 zoom.speed = 50 size = 70 for k in range(18): flash.draw_square(size) zoom.draw_circle(size) flash.pen_down() flash.right(20) flash.forward(30) zoom.pen_down() zoom.left(20) zoom.backward(30) window.tracer(20) damage = rg.SimpleTurtle('triangle') damage.pen = rg.Pen('dark blue',1) damage.backward(30) for k in range(1000): damage.right(50) damage.forward(2*k) window.close_on_mouse_click()
0
0
0
ccb90990658e51c1364711573c5224ef470491c3
2,810
py
Python
script/MakeRef.py
weefuzzy/flucoma-docs
bc7cc6b9f4f2b35ba20659a894590fa1879a34f7
[ "BSD-3-Clause" ]
2
2020-09-03T21:24:14.000Z
2020-09-30T07:54:41.000Z
script/MakeRef.py
weefuzzy/flucoma-docs
bc7cc6b9f4f2b35ba20659a894590fa1879a34f7
[ "BSD-3-Clause" ]
66
2021-06-10T10:29:26.000Z
2022-03-29T11:24:16.000Z
script/MakeRef.py
weefuzzy/flucoma-docs
bc7cc6b9f4f2b35ba20659a894590fa1879a34f7
[ "BSD-3-Clause" ]
4
2021-06-24T12:06:05.000Z
2021-09-20T10:48:54.000Z
# Part of the Fluid Corpus Manipulation Project (http://www.flucoma.org/) # Copyright 2017-2019 University of Huddersfield. # Licensed under the BSD-3 License. # See license.md file in the project root for full license information. # This project has received funding from the European Research Council (ERC) # under the European Union’s Horizon 2020 research and innovation programme # (grant agreement No 725899). import argparse from pathlib import Path from FluidRefData import * import json import locale """ Set default locale, in case it hasn't been, otherwise we can't read text """ locale.setlocale(locale.LC_ALL,'') parser = argparse.ArgumentParser( description='Generate FluCoMa documentation for a given host, using input JSON and YAML data and a jinja template') parser.add_argument('host', choices=['max','pd','cli']) parser.add_argument('json_path', type=Path, help='Path to generated JSON client data') parser.add_argument('yaml_path', type=Path, help='Path to human made YAML client documentation') parser.add_argument('output_path', type=Path, help='Path to write output files to') parser.add_argument('template_path', type=Path, help='Path containing Jinja template(s)') args = parser.parse_args() clients = list(args.json_path.glob(host_vars[args.host]['glob'])) args.output_path.mkdir(exist_ok=True) print('OUTPUT PATH {}'.format(args.output_path)) index = {} for c in clients: d = process_client_data(c, args.yaml_path) index[c] = process_template(args.template_path, args.output_path, d, host_vars[args.host]) index_path = args.output_path / '../interfaces' index_path.mkdir(exist_ok=True) write_max_indices(index,index_path) topics = list(Path('/Users/owen/flucoma_paramdump/topics').glob('*.yaml')) for t in topics: process_topic(t,args.template_path,args.output_path,host_vars[args.host]) # print(topics)
33.855422
119
0.677224
# Part of the Fluid Corpus Manipulation Project (http://www.flucoma.org/) # Copyright 2017-2019 University of Huddersfield. # Licensed under the BSD-3 License. # See license.md file in the project root for full license information. # This project has received funding from the European Research Council (ERC) # under the European Union’s Horizon 2020 research and innovation programme # (grant agreement No 725899). import argparse from pathlib import Path from FluidRefData import * import json import locale def write_max_indices(idx,path): maxdb_objs = {'maxdb':{'externals':{}}} qlookup = {} for client,data in idx.items(): maxname = 'fluid.{}~'.format(data['client'].lower()) if 'messages' in data: if 'dump' in data['messages']: maxdb_objs['maxdb']['externals'][maxname]={ 'object':'fluid.libmanipulation', 'package':'Fluid Corpus Manipulation' } qlookup[maxname] = { 'digest': data['digest'],'category':['Fluid Corpus Manuipulation'] } maxdbfile = path / 'max.db.json' with open(maxdbfile,'w') as f: json.dump(maxdb_objs,f,sort_keys=True, indent=4) qlookup_file = path / 'flucoma-obj-qlookup.json' with open(qlookup_file,'w') as f: json.dump(qlookup,f,sort_keys=True, indent=4) """ Set default locale, in case it hasn't been, otherwise we can't read text """ locale.setlocale(locale.LC_ALL,'') parser = argparse.ArgumentParser( description='Generate FluCoMa documentation for a given host, using input JSON and YAML data and a jinja template') parser.add_argument('host', choices=['max','pd','cli']) parser.add_argument('json_path', type=Path, help='Path to generated JSON client data') parser.add_argument('yaml_path', type=Path, help='Path to human made YAML client documentation') parser.add_argument('output_path', type=Path, help='Path to write output files to') parser.add_argument('template_path', type=Path, help='Path containing Jinja template(s)') args = parser.parse_args() clients = list(args.json_path.glob(host_vars[args.host]['glob'])) args.output_path.mkdir(exist_ok=True) print('OUTPUT PATH {}'.format(args.output_path)) index = {} for c in clients: d = process_client_data(c, args.yaml_path) index[c] = process_template(args.template_path, args.output_path, d, host_vars[args.host]) index_path = args.output_path / '../interfaces' index_path.mkdir(exist_ok=True) write_max_indices(index,index_path) topics = list(Path('/Users/owen/flucoma_paramdump/topics').glob('*.yaml')) for t in topics: process_topic(t,args.template_path,args.output_path,host_vars[args.host]) # print(topics)
832
0
23
04d616b61bd8c5c92992d7d948f74bfe17e96634
1,535
py
Python
api/migrations/0003_auto_20161111_2324.py
gdelnegro/orders_api
e6cc45e0b486ae5bb50c095174f251a941733d6b
[ "MIT" ]
null
null
null
api/migrations/0003_auto_20161111_2324.py
gdelnegro/orders_api
e6cc45e0b486ae5bb50c095174f251a941733d6b
[ "MIT" ]
null
null
null
api/migrations/0003_auto_20161111_2324.py
gdelnegro/orders_api
e6cc45e0b486ae5bb50c095174f251a941733d6b
[ "MIT" ]
null
null
null
# -*- coding: utf-8 -*- # Generated by Django 1.10.3 on 2016-11-11 23:24 from __future__ import unicode_literals from django.db import migrations, models import django.db.models.deletion
39.358974
136
0.607818
# -*- coding: utf-8 -*- # Generated by Django 1.10.3 on 2016-11-11 23:24 from __future__ import unicode_literals from django.db import migrations, models import django.db.models.deletion class Migration(migrations.Migration): dependencies = [ ('api', '0002_auto_20161111_2309'), ] operations = [ migrations.CreateModel( name='Item', fields=[ ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')), ('created_at', models.DateTimeField(auto_now_add=True, help_text='DTST1', null=True, verbose_name='DTSM1')), ('updated_at', models.DateTimeField(auto_now=True, help_text='DTST2', null=True, verbose_name='DTSM2')), ('code', models.CharField(max_length=200)), ('catalog_price', models.DecimalField(decimal_places=2, max_digits=10)), ('retail_price', models.DecimalField(decimal_places=2, max_digits=10)), ('quantity', models.PositiveIntegerField()), ('available', models.BooleanField()), ('client', models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, related_name='item_client', to='api.Client')), ], ), migrations.DeleteModel( name='Items', ), migrations.AlterField( model_name='order', name='items', field=models.ManyToManyField(related_name='order_itens', to='api.Item'), ), ]
0
1,323
23
fa31827beee52528e022c7012ef90988bb621e78
23,958
py
Python
ppci/binutils/linker.py
rakati/ppci-mirror
8f5b0282fd1122d7c389b39c86fcf5d9352b7bb2
[ "BSD-2-Clause" ]
null
null
null
ppci/binutils/linker.py
rakati/ppci-mirror
8f5b0282fd1122d7c389b39c86fcf5d9352b7bb2
[ "BSD-2-Clause" ]
null
null
null
ppci/binutils/linker.py
rakati/ppci-mirror
8f5b0282fd1122d7c389b39c86fcf5d9352b7bb2
[ "BSD-2-Clause" ]
1
2021-11-23T14:23:04.000Z
2021-11-23T14:23:04.000Z
""" Linker utility. """ import logging from collections import defaultdict from .objectfile import ObjectFile, Image, get_object, RelocationEntry from ..common import CompilerError from .layout import Layout, Section, SectionData, SymbolDefinition, Align from .layout import get_layout from .debuginfo import SymbolIdAdjustingReplicator, DebugInfo from .archive import get_archive def link( objects, layout=None, use_runtime=False, partial_link=False, reporter=None, debug=False, extra_symbols=None, libraries=None, entry=None, ): """ Links the iterable of objects into one using the given layout. Args: objects: a collection of objects to be linked together. layout: optional memory layout. use_runtime (bool): also link compiler runtime functions partial_link: Set this to true if you want to perform a partial link. This means, undefined symbols are no error. debug (bool): when true, keep debug information. Otherwise remove this debug information from the result. extra_symbols: a dict of extra symbols which can be used during linking. libraries: a list of libraries to use when searching for symbols. entry: the entry symbol where execution should begin. Returns: The linked object file .. doctest:: >>> import io >>> from ppci.api import asm, c3c, link >>> asm_source = io.StringIO("db 0x77") >>> obj1 = asm(asm_source, 'arm') >>> c3_source = io.StringIO("module main; var int a;") >>> obj2 = c3c([c3_source], [], 'arm') >>> obj = link([obj1, obj2]) >>> print(obj) CodeObject of 8 bytes """ objects = list(map(get_object, objects)) if not objects: raise ValueError("Please provide at least one object as input") if layout: layout = get_layout(layout) march = objects[0].arch if use_runtime: objects.append(march.runtime) libraries = list(map(get_archive, libraries)) if libraries else [] linker = Linker(march, reporter) output_obj = linker.link( objects, layout=layout, partial_link=partial_link, debug=debug, extra_symbols=extra_symbols, libraries=libraries, entry_symbol_name=entry, ) return output_obj class Linker: """ Merges the sections of several object files and performs relocation """ logger = logging.getLogger("linker") def link( self, input_objects, layout=None, partial_link=False, debug=False, extra_symbols=None, libraries=None, entry_symbol_name=None, ): """ Link together the given object files using the layout """ assert isinstance(input_objects, (list, tuple)) if self.reporter: self.reporter.heading(2, "Linking") # Check all incoming objects for same architecture: for input_object in input_objects: assert input_object.arch == self.arch # Create new object file to store output: self.dst = ObjectFile(self.arch) if debug: self.dst.debug_info = DebugInfo() # Take entry symbol from layout if not specified alreay: if not entry_symbol_name and layout and layout.entry: # TODO: what to do if two symbols are defined? # for now the symbol given via command line overrides # the entry in the linker script. entry_symbol_name = layout.entry.symbol_name # Define entry symbol: if entry_symbol_name: self.dst.entry_symbol_id = self.inject_symbol( entry_symbol_name, "global", None, None ).id # Define extra symbols: extra_symbols = extra_symbols or {} for symbol_name, value in extra_symbols.items(): self.logger.debug("Defining extra symbol %s", symbol_name) self.inject_symbol(symbol_name, "global", None, value) # First merge all sections into output sections: self.merge_objects(input_objects, debug) if partial_link: if layout: # Layout makes only sense in the final binary. raise ValueError("Can only apply layout in non-partial links") else: if libraries: # Find missing symbols in libraries: self.add_missing_symbols_from_libraries(libraries) # Apply layout rules: if layout: assert isinstance(layout, Layout) self.layout_sections(layout) self.check_undefined_symbols() self.do_relaxations() self.do_relocations() if self.reporter: self.report_link_result() return self.dst def report_link_result(self): """ After linking is complete, this function can be used to dump information to a reporter. """ for section in self.dst.sections: self.reporter.message("{} at {}".format(section, section.address)) for image in self.dst.images: self.reporter.message("{} at {}".format(image, image.address)) symbols = [ (s, self.dst.get_symbol_id_value(s.id) if s.defined else -1) for s in self.dst.symbols ] symbols.sort(key=lambda x: x[1]) for symbol, address in symbols: self.reporter.message( "Symbol {} {} at 0x{:X}".format( symbol.binding, symbol.name, address ) ) self.reporter.message("Linking complete") def merge_objects(self, input_objects, debug): """ Merge object files into a single object file """ for input_object in input_objects: self.inject_object(input_object, debug) def inject_object(self, obj, debug): """ Paste object into destination object. """ self.logger.debug("Merging %s", obj) section_offsets = {} for input_section in obj.sections: # Get or create the output section: output_section = self.dst.get_section( input_section.name, create=True ) # Alter the minimum section alignment if required: if input_section.alignment > output_section.alignment: output_section.alignment = input_section.alignment # Align section: while output_section.size % input_section.alignment != 0: self.logger.debug("Padding output to ensure alignment") output_section.add_data(bytes([0])) # Add new section: offset = output_section.size section_offsets[input_section.name] = offset output_section.add_data(input_section.data) self.logger.debug( "at offset 0x%x section %s", section_offsets[input_section.name], input_section, ) symbol_id_mapping = {} for symbol in obj.symbols: # Shift symbol value if required: if symbol.defined: value = section_offsets[symbol.section] + symbol.value section = symbol.section else: value = section = None if symbol.binding == "global": new_symbol = self.merge_global_symbol( symbol.name, section, value ) else: new_symbol = self.inject_symbol( symbol.name, symbol.binding, section, value ) symbol_id_mapping[symbol.id] = new_symbol.id for reloc in obj.relocations: offset = section_offsets[reloc.section] + reloc.offset symbol_id = symbol_id_mapping[reloc.symbol_id] new_reloc = RelocationEntry( reloc.reloc_type, symbol_id, reloc.section, offset, reloc.addend, ) self.dst.add_relocation(new_reloc) # Merge entry symbol: if obj.entry_symbol_id is not None: if self.dst.entry_symbol_id is None: self.dst.entry_symbol_id = symbol_id_mapping[ obj.entry_symbol_id ] else: # TODO: improve error message? raise CompilerError("Multiple entry points defined") # Merge debug info: if debug and obj.debug_info: replicator = SymbolIdAdjustingReplicator(symbol_id_mapping) replicator.replicate(obj.debug_info, self.dst.debug_info) def merge_global_symbol(self, name, section, value): """ Insert or merge a global name. """ if self.dst.has_symbol(name): new_symbol = self.dst.get_symbol(name) assert new_symbol.binding == "global" if value is not None: # we define this symbol. # We require merging. if new_symbol.undefined: new_symbol.value = value new_symbol.section = section else: # TODO: accumulate errors.. raise CompilerError( "Multiple defined symbol: {}".format(name) ) else: new_symbol = self.inject_symbol(name, "global", section, value) return new_symbol def inject_symbol(self, name, binding, section, value): """ Generate new symbol into object file. """ symbol_id = len(self.dst.symbols) new_symbol = self.dst.add_symbol( symbol_id, name, binding, value, section ) return new_symbol def layout_sections(self, layout): """ Use the given layout to place sections into memories """ # Create sections with address: for mem in layout.memories: image = Image(mem.name, mem.location) current_address = mem.location for memory_input in mem.inputs: if isinstance(memory_input, Section): section = self.dst.get_section( memory_input.section_name, create=True ) while current_address % section.alignment != 0: current_address += 1 section.address = current_address self.logger.debug( "Memory: %s Section: %s Address: 0x%x Size: 0x%x", mem.name, section.name, section.address, section.size, ) current_address += section.size image.add_section(section) elif isinstance(memory_input, SectionData): section_name = "_${}_".format(memory_input.section_name) # Each section must be unique: assert not self.dst.has_section(section_name) section = self.dst.get_section(section_name, create=True) section.address = current_address section.alignment = 1 # TODO: is this correct alignment? src_section = self.dst.get_section( memory_input.section_name ) section.add_data(src_section.data) current_address += section.size image.add_section(section) elif isinstance(memory_input, SymbolDefinition): # Create a new section, and place it at current spot: symbol_name = memory_input.symbol_name section_name = "_${}_".format(symbol_name) # Each section must be unique: assert not self.dst.has_section(section_name) section = self.dst.get_section(section_name, create=True) section.address = current_address section.alignment = 1 self.merge_global_symbol(symbol_name, section_name, 0) image.add_section(section) elif isinstance(memory_input, Align): while (current_address % memory_input.alignment) != 0: current_address += 1 else: # pragma: no cover raise NotImplementedError(str(memory_input)) # Check that the memory fits! if image.size > mem.size: raise CompilerError( "Memory exceeds size ({} > {})".format( image.size, mem.size ) ) self.dst.add_image(image) def get_symbol_value(self, symbol_id): """ Get value of a symbol from object or fallback """ # Lookup symbol: return self.dst.get_symbol_id_value(symbol_id) # raise CompilerError('Undefined reference "{}"'.format(name)) def add_missing_symbols_from_libraries(self, libraries): """ Try to fetch extra code from libraries to resolve symbols. Note that this can be a rabbit hole, since libraries can have undefined symbols as well. """ undefined_symbols = self.get_undefined_symbols() if not undefined_symbols: self.logger.debug( "No undefined symbols, no need to check libraries" ) return # Keep adding objects while we have undefined symbols. reloop = True while reloop: reloop = False for library in libraries: self.logger.debug("scanning library for symbols %s", library) for obj in library: has_sym = any(map(obj.has_symbol, undefined_symbols)) if has_sym: self.logger.debug( "Using object file %s from library", obj ) self.inject_object(obj, False) undefined_symbols = self.get_undefined_symbols() reloop = True def get_undefined_symbols(self): """ Get a list of currently undefined symbols. """ return self.dst.get_undefined_symbols() def check_undefined_symbols(self): """ Find undefined symbols. """ undefined_symbols = self.get_undefined_symbols() for symbol in undefined_symbols: self.logger.error("Undefined reference: %s", symbol) if undefined_symbols: undefined = ", ".join(undefined_symbols) raise CompilerError("Undefined references: {}".format(undefined)) def do_relaxations(self): """ Linker relaxation. Just relax ;). Linker relaxation is the process of finding shorted opcodes for jumps to addresses nearby. For example, an instruction set might define two jump operations. One with a 32 bits offset, and one with an 8 bits offset. Most likely the compiler will generate conservative code, so always 32 bits branches. During the relaxation phase, the code is scanned for possible replacements of the 32 bits jump by an 8 bit jump. Possible issues that might occur during this phase: - alignment of code. Code that was previously aligned might be shifted. - Linker relaxations might cause the opposite effect on jumps whose distance increases due to relaxation. This occurs when jumping over a memory whole between sections. """ self.logger.debug("Doing linker relaxations") # TODO: general note. Alignment must still be taken into account. # A wrong situation occurs, when reducing the image by small amount # of bytes. Locations that were aligned before, might become unaligned. # First, determine the list of possible optimizations! lst = [] for relocation in self.dst.relocations: sym_value = self.get_symbol_value(relocation.symbol_id) reloc_section = self.dst.get_section(relocation.section) reloc_value = reloc_section.address + relocation.offset rcls = self.dst.arch.isa.relocation_map[relocation.reloc_type] reloc = rcls( None, offset=relocation.offset, addend=relocation.addend ) if reloc.can_shrink(sym_value, reloc_value): # Apply code patching: begin = relocation.offset size = reloc.size() end = begin + size data = reloc_section.data[begin:end] assert len(data) == size, "len({}) ({}-{}) != {}".format( data, begin, end, size ) # Apply code patch: self.logger.debug("Applying patch for %s", reloc) data, new_relocs = reloc.do_shrink( sym_value, data, reloc_value ) new_size = len(data) diff = size - new_size assert 0 <= diff <= size # assert len(data) == size new_end = begin + new_size assert new_end + new_size == end # Do not shrink the data here, we will do this later on. reloc_section.data[begin:new_end] = data # Define new memory hole, starting after instruction hole = (new_end, diff) # Record this reduction occurence: lst.append((hole, relocation, reloc, new_relocs)) if not lst: self.logger.debug("No linker relaxations found") return s = ", ".join(str(x) for x in lst) self.logger.debug("Relaxable relocations: %s", s) # Define a map with the byte holes: holes_map = defaultdict(list) # section name to list of holes. # Remove old relocations by new ones. for hole, relocation, reloc, new_relocs in lst: # Remove old relocation which is superceeded: self.dst.relocations.remove(relocation) # Inject new relocations: for new_reloc in new_relocs: # TODO: maybe deal with somewhat shifted new relocations? # Create fresh relocation entry for patched code. new_relocation = RelocationEntry( new_reloc.name, relocation.symbol_id, relocation.section, relocation.offset, relocation.addend, ) self.dst.add_relocation(new_relocation) # Register hole: assert relocation.section holes_map[relocation.section].append(hole) for holes in holes_map.values(): holes.sort(key=lambda x: x[0]) # TODO: at this point, there can be the situation that we have two # sections which become further apart (due to them being in different # memory images. In this case, some relative jumps can become # unreachable. What should be do in this case? # Code has been patched here. Now update all relocations, symbols and # section addresses. self._apply_relaxation_holes(holes_map) def _apply_relaxation_holes(self, hole_map): """ Punch holes in the destination object file. Do adjustments to section addresses, symbol offsets and relocation offsets. """ def count_holes(offset, holes): """ Count how much holes we have until the given offset. """ diff = 0 for hole_offset, hole_size in holes: if hole_offset < offset: diff += hole_size else: break return diff # Update symbols which are located in sections. for symbol in self.dst.symbols: # Ignore global section-less symbols. if symbol.section is None: continue holes = hole_map[symbol.section] delta = count_holes(symbol.value, holes) self.logger.debug( "symbol changing %s (id=%s) at %08x with -%08x", symbol.name, symbol.id, symbol.value, delta, ) symbol.value -= delta # Update relocations (which are always located in a section) for relocation in self.dst.relocations: assert relocation.section holes = hole_map[relocation.section] delta = count_holes(relocation.offset, holes) self.logger.debug( "relocation changing %s at offset %08x with -%08x", relocation.symbol_id, relocation.offset, delta, ) relocation.offset -= delta # Update section data: for section in self.dst.sections: # Loop over holes in reverse, since earlier holes influence later # holes. holes = hole_map[section.name] for hole_offset, hole_size in reversed(holes): for _ in range(hole_size): section.data.pop(hole_offset) # Calculate total change per section section_changes = { name: sum(h[1] for h in holes) for name, holes in hole_map.items() } # Update layout of section in images for image in self.dst.images: delta = 0 for section in image.sections: self.logger.debug( "sectororchanging %s at %08x with -%08x to %08x", section.name, section.address, delta, ) # TODO: tricky stuff might go wrong here with alignment # requirements of sections. # Idea: re-do the layout phase? section.address -= delta delta += section_changes[section.name] def do_relocations(self): """ Perform the correct relocation as listed """ self.logger.debug( "Performing {} linker relocations".format( len(self.dst.relocations) ) ) for reloc in self.dst.relocations: self._do_relocation(reloc) def _do_relocation(self, relocation): """ Perform a single relocation. This involves hammering some specific bits in the section data according to symbol location and relocation location in the file. """ sym_value = self.get_symbol_value(relocation.symbol_id) section = self.dst.get_section(relocation.section) # Determine address in memory of reloc patchup position: reloc_value = section.address + relocation.offset # reloc_function = self.arch.get_reloc(reloc.typ) # Construct architecture specific relocation: rcls = self.dst.arch.isa.relocation_map[relocation.reloc_type] reloc = rcls(None, offset=relocation.offset, addend=relocation.addend) begin = relocation.offset size = reloc.size() end = begin + size data = section.data[begin:end] assert len(data) == size, "len({}) ({}-{}) != {}".format( data, begin, end, size ) data = reloc.apply(sym_value, data, reloc_value) assert len(data) == size section.data[begin:end] = data
37.086687
79
0.570457
""" Linker utility. """ import logging from collections import defaultdict from .objectfile import ObjectFile, Image, get_object, RelocationEntry from ..common import CompilerError from .layout import Layout, Section, SectionData, SymbolDefinition, Align from .layout import get_layout from .debuginfo import SymbolIdAdjustingReplicator, DebugInfo from .archive import get_archive def link( objects, layout=None, use_runtime=False, partial_link=False, reporter=None, debug=False, extra_symbols=None, libraries=None, entry=None, ): """ Links the iterable of objects into one using the given layout. Args: objects: a collection of objects to be linked together. layout: optional memory layout. use_runtime (bool): also link compiler runtime functions partial_link: Set this to true if you want to perform a partial link. This means, undefined symbols are no error. debug (bool): when true, keep debug information. Otherwise remove this debug information from the result. extra_symbols: a dict of extra symbols which can be used during linking. libraries: a list of libraries to use when searching for symbols. entry: the entry symbol where execution should begin. Returns: The linked object file .. doctest:: >>> import io >>> from ppci.api import asm, c3c, link >>> asm_source = io.StringIO("db 0x77") >>> obj1 = asm(asm_source, 'arm') >>> c3_source = io.StringIO("module main; var int a;") >>> obj2 = c3c([c3_source], [], 'arm') >>> obj = link([obj1, obj2]) >>> print(obj) CodeObject of 8 bytes """ objects = list(map(get_object, objects)) if not objects: raise ValueError("Please provide at least one object as input") if layout: layout = get_layout(layout) march = objects[0].arch if use_runtime: objects.append(march.runtime) libraries = list(map(get_archive, libraries)) if libraries else [] linker = Linker(march, reporter) output_obj = linker.link( objects, layout=layout, partial_link=partial_link, debug=debug, extra_symbols=extra_symbols, libraries=libraries, entry_symbol_name=entry, ) return output_obj class Linker: """ Merges the sections of several object files and performs relocation """ logger = logging.getLogger("linker") def __init__(self, arch, reporter=None): self.arch = arch self.extra_symbols = None self.reporter = reporter def link( self, input_objects, layout=None, partial_link=False, debug=False, extra_symbols=None, libraries=None, entry_symbol_name=None, ): """ Link together the given object files using the layout """ assert isinstance(input_objects, (list, tuple)) if self.reporter: self.reporter.heading(2, "Linking") # Check all incoming objects for same architecture: for input_object in input_objects: assert input_object.arch == self.arch # Create new object file to store output: self.dst = ObjectFile(self.arch) if debug: self.dst.debug_info = DebugInfo() # Take entry symbol from layout if not specified alreay: if not entry_symbol_name and layout and layout.entry: # TODO: what to do if two symbols are defined? # for now the symbol given via command line overrides # the entry in the linker script. entry_symbol_name = layout.entry.symbol_name # Define entry symbol: if entry_symbol_name: self.dst.entry_symbol_id = self.inject_symbol( entry_symbol_name, "global", None, None ).id # Define extra symbols: extra_symbols = extra_symbols or {} for symbol_name, value in extra_symbols.items(): self.logger.debug("Defining extra symbol %s", symbol_name) self.inject_symbol(symbol_name, "global", None, value) # First merge all sections into output sections: self.merge_objects(input_objects, debug) if partial_link: if layout: # Layout makes only sense in the final binary. raise ValueError("Can only apply layout in non-partial links") else: if libraries: # Find missing symbols in libraries: self.add_missing_symbols_from_libraries(libraries) # Apply layout rules: if layout: assert isinstance(layout, Layout) self.layout_sections(layout) self.check_undefined_symbols() self.do_relaxations() self.do_relocations() if self.reporter: self.report_link_result() return self.dst def report_link_result(self): """ After linking is complete, this function can be used to dump information to a reporter. """ for section in self.dst.sections: self.reporter.message("{} at {}".format(section, section.address)) for image in self.dst.images: self.reporter.message("{} at {}".format(image, image.address)) symbols = [ (s, self.dst.get_symbol_id_value(s.id) if s.defined else -1) for s in self.dst.symbols ] symbols.sort(key=lambda x: x[1]) for symbol, address in symbols: self.reporter.message( "Symbol {} {} at 0x{:X}".format( symbol.binding, symbol.name, address ) ) self.reporter.message("Linking complete") def merge_objects(self, input_objects, debug): """ Merge object files into a single object file """ for input_object in input_objects: self.inject_object(input_object, debug) def inject_object(self, obj, debug): """ Paste object into destination object. """ self.logger.debug("Merging %s", obj) section_offsets = {} for input_section in obj.sections: # Get or create the output section: output_section = self.dst.get_section( input_section.name, create=True ) # Alter the minimum section alignment if required: if input_section.alignment > output_section.alignment: output_section.alignment = input_section.alignment # Align section: while output_section.size % input_section.alignment != 0: self.logger.debug("Padding output to ensure alignment") output_section.add_data(bytes([0])) # Add new section: offset = output_section.size section_offsets[input_section.name] = offset output_section.add_data(input_section.data) self.logger.debug( "at offset 0x%x section %s", section_offsets[input_section.name], input_section, ) symbol_id_mapping = {} for symbol in obj.symbols: # Shift symbol value if required: if symbol.defined: value = section_offsets[symbol.section] + symbol.value section = symbol.section else: value = section = None if symbol.binding == "global": new_symbol = self.merge_global_symbol( symbol.name, section, value ) else: new_symbol = self.inject_symbol( symbol.name, symbol.binding, section, value ) symbol_id_mapping[symbol.id] = new_symbol.id for reloc in obj.relocations: offset = section_offsets[reloc.section] + reloc.offset symbol_id = symbol_id_mapping[reloc.symbol_id] new_reloc = RelocationEntry( reloc.reloc_type, symbol_id, reloc.section, offset, reloc.addend, ) self.dst.add_relocation(new_reloc) # Merge entry symbol: if obj.entry_symbol_id is not None: if self.dst.entry_symbol_id is None: self.dst.entry_symbol_id = symbol_id_mapping[ obj.entry_symbol_id ] else: # TODO: improve error message? raise CompilerError("Multiple entry points defined") # Merge debug info: if debug and obj.debug_info: replicator = SymbolIdAdjustingReplicator(symbol_id_mapping) replicator.replicate(obj.debug_info, self.dst.debug_info) def merge_global_symbol(self, name, section, value): """ Insert or merge a global name. """ if self.dst.has_symbol(name): new_symbol = self.dst.get_symbol(name) assert new_symbol.binding == "global" if value is not None: # we define this symbol. # We require merging. if new_symbol.undefined: new_symbol.value = value new_symbol.section = section else: # TODO: accumulate errors.. raise CompilerError( "Multiple defined symbol: {}".format(name) ) else: new_symbol = self.inject_symbol(name, "global", section, value) return new_symbol def inject_symbol(self, name, binding, section, value): """ Generate new symbol into object file. """ symbol_id = len(self.dst.symbols) new_symbol = self.dst.add_symbol( symbol_id, name, binding, value, section ) return new_symbol def layout_sections(self, layout): """ Use the given layout to place sections into memories """ # Create sections with address: for mem in layout.memories: image = Image(mem.name, mem.location) current_address = mem.location for memory_input in mem.inputs: if isinstance(memory_input, Section): section = self.dst.get_section( memory_input.section_name, create=True ) while current_address % section.alignment != 0: current_address += 1 section.address = current_address self.logger.debug( "Memory: %s Section: %s Address: 0x%x Size: 0x%x", mem.name, section.name, section.address, section.size, ) current_address += section.size image.add_section(section) elif isinstance(memory_input, SectionData): section_name = "_${}_".format(memory_input.section_name) # Each section must be unique: assert not self.dst.has_section(section_name) section = self.dst.get_section(section_name, create=True) section.address = current_address section.alignment = 1 # TODO: is this correct alignment? src_section = self.dst.get_section( memory_input.section_name ) section.add_data(src_section.data) current_address += section.size image.add_section(section) elif isinstance(memory_input, SymbolDefinition): # Create a new section, and place it at current spot: symbol_name = memory_input.symbol_name section_name = "_${}_".format(symbol_name) # Each section must be unique: assert not self.dst.has_section(section_name) section = self.dst.get_section(section_name, create=True) section.address = current_address section.alignment = 1 self.merge_global_symbol(symbol_name, section_name, 0) image.add_section(section) elif isinstance(memory_input, Align): while (current_address % memory_input.alignment) != 0: current_address += 1 else: # pragma: no cover raise NotImplementedError(str(memory_input)) # Check that the memory fits! if image.size > mem.size: raise CompilerError( "Memory exceeds size ({} > {})".format( image.size, mem.size ) ) self.dst.add_image(image) def get_symbol_value(self, symbol_id): """ Get value of a symbol from object or fallback """ # Lookup symbol: return self.dst.get_symbol_id_value(symbol_id) # raise CompilerError('Undefined reference "{}"'.format(name)) def add_missing_symbols_from_libraries(self, libraries): """ Try to fetch extra code from libraries to resolve symbols. Note that this can be a rabbit hole, since libraries can have undefined symbols as well. """ undefined_symbols = self.get_undefined_symbols() if not undefined_symbols: self.logger.debug( "No undefined symbols, no need to check libraries" ) return # Keep adding objects while we have undefined symbols. reloop = True while reloop: reloop = False for library in libraries: self.logger.debug("scanning library for symbols %s", library) for obj in library: has_sym = any(map(obj.has_symbol, undefined_symbols)) if has_sym: self.logger.debug( "Using object file %s from library", obj ) self.inject_object(obj, False) undefined_symbols = self.get_undefined_symbols() reloop = True def get_undefined_symbols(self): """ Get a list of currently undefined symbols. """ return self.dst.get_undefined_symbols() def check_undefined_symbols(self): """ Find undefined symbols. """ undefined_symbols = self.get_undefined_symbols() for symbol in undefined_symbols: self.logger.error("Undefined reference: %s", symbol) if undefined_symbols: undefined = ", ".join(undefined_symbols) raise CompilerError("Undefined references: {}".format(undefined)) def do_relaxations(self): """ Linker relaxation. Just relax ;). Linker relaxation is the process of finding shorted opcodes for jumps to addresses nearby. For example, an instruction set might define two jump operations. One with a 32 bits offset, and one with an 8 bits offset. Most likely the compiler will generate conservative code, so always 32 bits branches. During the relaxation phase, the code is scanned for possible replacements of the 32 bits jump by an 8 bit jump. Possible issues that might occur during this phase: - alignment of code. Code that was previously aligned might be shifted. - Linker relaxations might cause the opposite effect on jumps whose distance increases due to relaxation. This occurs when jumping over a memory whole between sections. """ self.logger.debug("Doing linker relaxations") # TODO: general note. Alignment must still be taken into account. # A wrong situation occurs, when reducing the image by small amount # of bytes. Locations that were aligned before, might become unaligned. # First, determine the list of possible optimizations! lst = [] for relocation in self.dst.relocations: sym_value = self.get_symbol_value(relocation.symbol_id) reloc_section = self.dst.get_section(relocation.section) reloc_value = reloc_section.address + relocation.offset rcls = self.dst.arch.isa.relocation_map[relocation.reloc_type] reloc = rcls( None, offset=relocation.offset, addend=relocation.addend ) if reloc.can_shrink(sym_value, reloc_value): # Apply code patching: begin = relocation.offset size = reloc.size() end = begin + size data = reloc_section.data[begin:end] assert len(data) == size, "len({}) ({}-{}) != {}".format( data, begin, end, size ) # Apply code patch: self.logger.debug("Applying patch for %s", reloc) data, new_relocs = reloc.do_shrink( sym_value, data, reloc_value ) new_size = len(data) diff = size - new_size assert 0 <= diff <= size # assert len(data) == size new_end = begin + new_size assert new_end + new_size == end # Do not shrink the data here, we will do this later on. reloc_section.data[begin:new_end] = data # Define new memory hole, starting after instruction hole = (new_end, diff) # Record this reduction occurence: lst.append((hole, relocation, reloc, new_relocs)) if not lst: self.logger.debug("No linker relaxations found") return s = ", ".join(str(x) for x in lst) self.logger.debug("Relaxable relocations: %s", s) # Define a map with the byte holes: holes_map = defaultdict(list) # section name to list of holes. # Remove old relocations by new ones. for hole, relocation, reloc, new_relocs in lst: # Remove old relocation which is superceeded: self.dst.relocations.remove(relocation) # Inject new relocations: for new_reloc in new_relocs: # TODO: maybe deal with somewhat shifted new relocations? # Create fresh relocation entry for patched code. new_relocation = RelocationEntry( new_reloc.name, relocation.symbol_id, relocation.section, relocation.offset, relocation.addend, ) self.dst.add_relocation(new_relocation) # Register hole: assert relocation.section holes_map[relocation.section].append(hole) for holes in holes_map.values(): holes.sort(key=lambda x: x[0]) # TODO: at this point, there can be the situation that we have two # sections which become further apart (due to them being in different # memory images. In this case, some relative jumps can become # unreachable. What should be do in this case? # Code has been patched here. Now update all relocations, symbols and # section addresses. self._apply_relaxation_holes(holes_map) def _apply_relaxation_holes(self, hole_map): """ Punch holes in the destination object file. Do adjustments to section addresses, symbol offsets and relocation offsets. """ def count_holes(offset, holes): """ Count how much holes we have until the given offset. """ diff = 0 for hole_offset, hole_size in holes: if hole_offset < offset: diff += hole_size else: break return diff # Update symbols which are located in sections. for symbol in self.dst.symbols: # Ignore global section-less symbols. if symbol.section is None: continue holes = hole_map[symbol.section] delta = count_holes(symbol.value, holes) self.logger.debug( "symbol changing %s (id=%s) at %08x with -%08x", symbol.name, symbol.id, symbol.value, delta, ) symbol.value -= delta # Update relocations (which are always located in a section) for relocation in self.dst.relocations: assert relocation.section holes = hole_map[relocation.section] delta = count_holes(relocation.offset, holes) self.logger.debug( "relocation changing %s at offset %08x with -%08x", relocation.symbol_id, relocation.offset, delta, ) relocation.offset -= delta # Update section data: for section in self.dst.sections: # Loop over holes in reverse, since earlier holes influence later # holes. holes = hole_map[section.name] for hole_offset, hole_size in reversed(holes): for _ in range(hole_size): section.data.pop(hole_offset) # Calculate total change per section section_changes = { name: sum(h[1] for h in holes) for name, holes in hole_map.items() } # Update layout of section in images for image in self.dst.images: delta = 0 for section in image.sections: self.logger.debug( "sectororchanging %s at %08x with -%08x to %08x", section.name, section.address, delta, ) # TODO: tricky stuff might go wrong here with alignment # requirements of sections. # Idea: re-do the layout phase? section.address -= delta delta += section_changes[section.name] def do_relocations(self): """ Perform the correct relocation as listed """ self.logger.debug( "Performing {} linker relocations".format( len(self.dst.relocations) ) ) for reloc in self.dst.relocations: self._do_relocation(reloc) def _do_relocation(self, relocation): """ Perform a single relocation. This involves hammering some specific bits in the section data according to symbol location and relocation location in the file. """ sym_value = self.get_symbol_value(relocation.symbol_id) section = self.dst.get_section(relocation.section) # Determine address in memory of reloc patchup position: reloc_value = section.address + relocation.offset # reloc_function = self.arch.get_reloc(reloc.typ) # Construct architecture specific relocation: rcls = self.dst.arch.isa.relocation_map[relocation.reloc_type] reloc = rcls(None, offset=relocation.offset, addend=relocation.addend) begin = relocation.offset size = reloc.size() end = begin + size data = section.data[begin:end] assert len(data) == size, "len({}) ({}-{}) != {}".format( data, begin, end, size ) data = reloc.apply(sym_value, data, reloc_value) assert len(data) == size section.data[begin:end] = data
111
0
27
dfe16477368e24a4f2172694856b8591a7539edf
511
py
Python
rest_api/api/models.py
markbirds/Django-Code-Repo
b55762d2dab00640acf2e8e00ddc66716d53c6b5
[ "MIT" ]
1
2021-11-25T00:02:36.000Z
2021-11-25T00:02:36.000Z
rest_api/api/models.py
markbirds/Django-Code-Repo
b55762d2dab00640acf2e8e00ddc66716d53c6b5
[ "MIT" ]
null
null
null
rest_api/api/models.py
markbirds/Django-Code-Repo
b55762d2dab00640acf2e8e00ddc66716d53c6b5
[ "MIT" ]
null
null
null
from django.db import models import uuid # Create your models here.
36.5
101
0.737769
from django.db import models import uuid # Create your models here. class User(models.Model): id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False) name = models.CharField(max_length=50) age = models.IntegerField() language = models.CharField(null=True,max_length=50,verbose_name="Favorite Programming language") programmer = models.BooleanField(default=False,verbose_name="Likes Programming or not?") def __str__(self): return f'{self.name} - {self.id}'
39
381
22
d4c139e44c9983284d65e44c0b0cfcc570e4e8b9
140
py
Python
setup.py
SaradhaVenkatachalapathy/annotate_images
fd10672909211d87c24e5e3eedaebb1f5d3ebda3
[ "MIT" ]
1
2021-08-06T18:40:14.000Z
2021-08-06T18:40:14.000Z
setup.py
SaradhaVenkatachalapathy/annotate_images
fd10672909211d87c24e5e3eedaebb1f5d3ebda3
[ "MIT" ]
1
2021-08-19T10:54:47.000Z
2021-08-19T11:03:00.000Z
setup.py
SaradhaVenkatachalapathy/annotate_images
fd10672909211d87c24e5e3eedaebb1f5d3ebda3
[ "MIT" ]
1
2021-08-11T11:41:48.000Z
2021-08-11T11:41:48.000Z
from setuptools import setup setup( name='interactive_segmentation', version='1.0', packages=['annotate'], license='MIT' )
15.555556
36
0.664286
from setuptools import setup setup( name='interactive_segmentation', version='1.0', packages=['annotate'], license='MIT' )
0
0
0