hexsha
string
size
int64
ext
string
lang
string
max_stars_repo_path
string
max_stars_repo_name
string
max_stars_repo_head_hexsha
string
max_stars_repo_licenses
list
max_stars_count
int64
max_stars_repo_stars_event_min_datetime
string
max_stars_repo_stars_event_max_datetime
string
max_issues_repo_path
string
max_issues_repo_name
string
max_issues_repo_head_hexsha
string
max_issues_repo_licenses
list
max_issues_count
int64
max_issues_repo_issues_event_min_datetime
string
max_issues_repo_issues_event_max_datetime
string
max_forks_repo_path
string
max_forks_repo_name
string
max_forks_repo_head_hexsha
string
max_forks_repo_licenses
list
max_forks_count
int64
max_forks_repo_forks_event_min_datetime
string
max_forks_repo_forks_event_max_datetime
string
content
string
avg_line_length
float64
max_line_length
int64
alphanum_fraction
float64
qsc_code_num_words_quality_signal
int64
qsc_code_num_chars_quality_signal
float64
qsc_code_mean_word_length_quality_signal
float64
qsc_code_frac_words_unique_quality_signal
float64
qsc_code_frac_chars_top_2grams_quality_signal
float64
qsc_code_frac_chars_top_3grams_quality_signal
float64
qsc_code_frac_chars_top_4grams_quality_signal
float64
qsc_code_frac_chars_dupe_5grams_quality_signal
float64
qsc_code_frac_chars_dupe_6grams_quality_signal
float64
qsc_code_frac_chars_dupe_7grams_quality_signal
float64
qsc_code_frac_chars_dupe_8grams_quality_signal
float64
qsc_code_frac_chars_dupe_9grams_quality_signal
float64
qsc_code_frac_chars_dupe_10grams_quality_signal
float64
qsc_code_frac_chars_replacement_symbols_quality_signal
float64
qsc_code_frac_chars_digital_quality_signal
float64
qsc_code_frac_chars_whitespace_quality_signal
float64
qsc_code_size_file_byte_quality_signal
float64
qsc_code_num_lines_quality_signal
float64
qsc_code_num_chars_line_max_quality_signal
float64
qsc_code_num_chars_line_mean_quality_signal
float64
qsc_code_frac_chars_alphabet_quality_signal
float64
qsc_code_frac_chars_comments_quality_signal
float64
qsc_code_cate_xml_start_quality_signal
float64
qsc_code_frac_lines_dupe_lines_quality_signal
float64
qsc_code_cate_autogen_quality_signal
float64
qsc_code_frac_lines_long_string_quality_signal
float64
qsc_code_frac_chars_string_length_quality_signal
float64
qsc_code_frac_chars_long_word_length_quality_signal
float64
qsc_code_frac_lines_string_concat_quality_signal
float64
qsc_code_cate_encoded_data_quality_signal
float64
qsc_code_frac_chars_hex_words_quality_signal
float64
qsc_code_frac_lines_prompt_comments_quality_signal
float64
qsc_code_frac_lines_assert_quality_signal
float64
qsc_codepython_cate_ast_quality_signal
float64
qsc_codepython_frac_lines_func_ratio_quality_signal
float64
qsc_codepython_cate_var_zero_quality_signal
bool
qsc_codepython_frac_lines_pass_quality_signal
float64
qsc_codepython_frac_lines_import_quality_signal
float64
qsc_codepython_frac_lines_simplefunc_quality_signal
float64
qsc_codepython_score_lines_no_logic_quality_signal
float64
qsc_codepython_frac_lines_print_quality_signal
float64
qsc_code_num_words
int64
qsc_code_num_chars
int64
qsc_code_mean_word_length
int64
qsc_code_frac_words_unique
null
qsc_code_frac_chars_top_2grams
int64
qsc_code_frac_chars_top_3grams
int64
qsc_code_frac_chars_top_4grams
int64
qsc_code_frac_chars_dupe_5grams
int64
qsc_code_frac_chars_dupe_6grams
int64
qsc_code_frac_chars_dupe_7grams
int64
qsc_code_frac_chars_dupe_8grams
int64
qsc_code_frac_chars_dupe_9grams
int64
qsc_code_frac_chars_dupe_10grams
int64
qsc_code_frac_chars_replacement_symbols
int64
qsc_code_frac_chars_digital
int64
qsc_code_frac_chars_whitespace
int64
qsc_code_size_file_byte
int64
qsc_code_num_lines
int64
qsc_code_num_chars_line_max
int64
qsc_code_num_chars_line_mean
int64
qsc_code_frac_chars_alphabet
int64
qsc_code_frac_chars_comments
int64
qsc_code_cate_xml_start
int64
qsc_code_frac_lines_dupe_lines
int64
qsc_code_cate_autogen
int64
qsc_code_frac_lines_long_string
int64
qsc_code_frac_chars_string_length
int64
qsc_code_frac_chars_long_word_length
int64
qsc_code_frac_lines_string_concat
null
qsc_code_cate_encoded_data
int64
qsc_code_frac_chars_hex_words
int64
qsc_code_frac_lines_prompt_comments
int64
qsc_code_frac_lines_assert
int64
qsc_codepython_cate_ast
int64
qsc_codepython_frac_lines_func_ratio
int64
qsc_codepython_cate_var_zero
int64
qsc_codepython_frac_lines_pass
int64
qsc_codepython_frac_lines_import
int64
qsc_codepython_frac_lines_simplefunc
int64
qsc_codepython_score_lines_no_logic
int64
qsc_codepython_frac_lines_print
int64
effective
string
hits
int64
810028e77fa49197f58461ee88815f3bf00eba42
2,029
py
Python
weasyprint/tests/test_stacking.py
Smylers/WeasyPrint
25ce91a34755386b3350d898aa1638c349723b57
[ "BSD-3-Clause" ]
null
null
null
weasyprint/tests/test_stacking.py
Smylers/WeasyPrint
25ce91a34755386b3350d898aa1638c349723b57
[ "BSD-3-Clause" ]
null
null
null
weasyprint/tests/test_stacking.py
Smylers/WeasyPrint
25ce91a34755386b3350d898aa1638c349723b57
[ "BSD-3-Clause" ]
null
null
null
# coding: utf8 """ weasyprint.tests.stacking ------------------------- :copyright: Copyright 2011-2012 Simon Sapin and contributors, see AUTHORS. :license: BSD, see LICENSE for details. """ from __future__ import division, unicode_literals from ..stacking import StackingContext from .test_boxes import serialize from .test_layout import parse from .testing_utils import assert_no_logs def to_lists(page): html, = page.children return serialize_stacking(StackingContext.from_box(html, page)) def serialize_box(box): return '%s %s' % (box.element_tag, box.sourceline) def serialize_stacking(context): return ( serialize_box(context.box), [serialize_box(b) for b in context.blocks_and_cells], [serialize_stacking(c) for c in context.zero_z_contexts], ) @assert_no_logs def test_nested(): page, = parse('''\ <p id=lorem></p> <div style="position: relative"> <p id=lipsum></p> </p> ''') assert to_lists(page) == ( 'html 1', ['body 1', 'p 1'], [( 'div 2', ['p 3'], [])]) page, = parse('''\ <div style="position: relative"> <p style="position: relative"></p> </div> ''') assert to_lists(page) == ( 'html 1', ['body 1'], [('div 1', [], []), # In this order ('p 2', [], [])]) @assert_no_logs def test_image_contexts(): page, = parse(''' <body>Some text: <img style="position: relative" src=pattern.png>''') html, = page.children context = StackingContext.from_box(html, page) # The image is *not* in this context: assert serialize([context.box]) == [ ('html', 'Block', [ ('body', 'Block', [ ('body', 'Line', [ ('body', 'Text', 'Some text: ')])])])] # ... but in a sub-context: assert serialize(c.box for c in context.zero_z_contexts) == [ ('img', 'InlineReplaced', '<replaced>')]
25.683544
78
0.556925
234
2,029
4.679487
0.376068
0.029224
0.076712
0.041096
0.231963
0.096804
0.096804
0.049315
0
0
0
0.01222
0.274027
2,029
78
79
26.012821
0.731161
0.126663
0
0.259259
0
0
0.239679
0
0
0
0
0
0.12963
1
0.092593
false
0
0.092593
0.037037
0.240741
0
0
0
0
null
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
null
0
0
0
0
0
0
0
0
0
0
0
0
1
0
8100832c0d5bc42056a44079c84eec3ee522ecd0
1,143
py
Python
django-magic-link/customers/views.py
industrydive/sourcelist
9db4ec5c9cb9246a644615ca401a3c8f8d560b6e
[ "MIT" ]
5
2017-10-28T17:17:35.000Z
2020-06-24T21:43:22.000Z
django-magic-link/customers/views.py
greglinch/sourcelist
8267bb060e55f036d6d2dd9648698a5b8e48c0b3
[ "MIT" ]
2
2020-02-11T21:50:49.000Z
2021-04-08T18:25:26.000Z
django-magic-link/customers/views.py
industrydive/sourcelist
9db4ec5c9cb9246a644615ca401a3c8f8d560b6e
[ "MIT" ]
2
2017-11-02T02:14:25.000Z
2019-05-28T15:35:44.000Z
from django.shortcuts import render from django.contrib.auth.models import User from django.contrib.auth.decorators import login_required from sesame import utils from django.core.mail import send_mail def login_page(request): if request.method == "POST": email = request.POST.get("emailId") user = User.objects.get(email=email) login_token = utils.get_query_string(user) login_link = "http://127.0.0.1:8000/customers/{}".format(login_token) html_message = """ <p>Hi there,</p> <p>Here is your <a href="{}">magic link</a> </p> <p>Thanks,</p> <p>Django Admin</p> """.format(login_link) send_mail( 'Django Magic Link', html_message, 'wishlist@kissflow.com', [email], fail_silently=False, html_message = html_message ) return render(request, "login.html", context={"message":"Please check your email for magic link."}) return render(request, "login.html") @login_required def customers_home_page(request): return render(request, "customers/index.html")
31.75
107
0.630796
145
1,143
4.848276
0.441379
0.056899
0.081081
0.059744
0.079659
0
0
0
0
0
0
0.011561
0.24322
1,143
36
108
31.75
0.801156
0
0
0
0
0
0.271853
0.018357
0
0
0
0
0
1
0.066667
false
0
0.166667
0.033333
0.333333
0
0
0
0
null
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
null
0
0
0
0
0
0
0
0
0
0
0
0
1
0
81014d9aa2fe1551a160b448cdc227329bca693d
3,079
py
Python
python-lib/config/dss_parameter.py
dataiku/dss-plugin-nlp-analysis
ff9dce56500dc8f28f83158afbdf7db01074ee38
[ "Apache-2.0" ]
1
2021-03-12T10:45:53.000Z
2021-03-12T10:45:53.000Z
python-lib/config/dss_parameter.py
dataiku/dss-plugin-nlp-analysis
ff9dce56500dc8f28f83158afbdf7db01074ee38
[ "Apache-2.0" ]
22
2021-03-01T18:49:54.000Z
2021-06-08T15:16:30.000Z
python-lib/config/dss_parameter.py
dataiku/dss-plugin-nlp-analysis
ff9dce56500dc8f28f83158afbdf7db01074ee38
[ "Apache-2.0" ]
1
2021-02-22T15:19:43.000Z
2021-02-22T15:19:43.000Z
from .custom_check import CustomCheck, CustomCheckError from typing import Any, List import logging logger = logging.getLogger(__name__) class DSSParameterError(Exception): """Exception raised when at least one CustomCheck fails.""" pass class DSSParameter: """Object related to one parameter. It is mainly used for checks to run in backend for custom forms. Attributes: name(str): Name of the parameter value(Any): Value of the parameter checks(list[dict], optional): Checks to run on provided value required(bool, optional): Whether the value can be None """ def __init__( self, name: str, value: Any, checks: List[dict] = None, required: bool = False ): """Initialization method for the DSSParameter class Args: name(str): Name of the parameter value(Any): Value of the parameter checks(list[dict], optional): Checks to run on provided value required(bool, optional): Whether the value can be None """ if checks is None: checks = [] self.name = name self.value = value self.checks = [CustomCheck(**check) for check in checks] if required: self.checks.append(CustomCheck(type="exists")) self.run_checks() def run_checks(self): """Runs all checks provided for this parameter""" errors = [] for check in self.checks: try: check.run(self.value) except CustomCheckError as err: errors.append(err) if errors: self.handle_failure(errors) self.handle_success() def handle_failure(self, errors: List[CustomCheckError]): """Is called when at least one test fails. It will raise an Exception with understandable text Args: errors(list[CustomCheckError]: Errors met when running checks Raises: DSSParameterError: Raises if at least on check fails """ raise DSSParameterError(self.format_failure_message(errors)) def format_failure_message(self, errors: List[CustomCheckError]) -> str: """Format failure text Args: errors(list[CustomCheckError]: Errors met when running checks Returns: str: Formatted error message """ return """ Error for parameter \"{name}\" : {errors} """.format( name=self.name, errors="\n".join(["\t {}".format(e) for e in errors]) ) def handle_success(self): """Called if all checks are successful. Prints a success message""" self.print_success_message() def print_success_message(self): """Formats the succee message""" logger.info("All checks have been successfully done for {}.".format(self.name)) def __repr__(self): return "DSSParameter(name={}, value={})".format(self.name, self.value) def __str__(self): return "DSSParameter(name={}, value={})".format(self.name, self.value)
33.835165
104
0.618383
358
3,079
5.231844
0.304469
0.025627
0.029899
0.014949
0.275494
0.275494
0.275494
0.275494
0.275494
0.275494
0
0
0.284183
3,079
90
105
34.211111
0.849819
0.363105
0
0.044444
0
0
0.106576
0.02381
0
0
0
0
0
1
0.177778
false
0.022222
0.066667
0.044444
0.355556
0.044444
0
0
0
null
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
null
0
0
0
0
0
0
0
0
0
0
0
0
1
0
81017170c94b85c3925c1875676b310a658ce79c
21,868
py
Python
misc/import_ch_zurich.py
mstarikov/transitfeed
c018d7b14f6fccaa670629c00c83a390b5461fc1
[ "Apache-2.0" ]
null
null
null
misc/import_ch_zurich.py
mstarikov/transitfeed
c018d7b14f6fccaa670629c00c83a390b5461fc1
[ "Apache-2.0" ]
null
null
null
misc/import_ch_zurich.py
mstarikov/transitfeed
c018d7b14f6fccaa670629c00c83a390b5461fc1
[ "Apache-2.0" ]
null
null
null
#!/usr/bin/python2.4 # Copyright (C) 2008 Google Inc. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. """imports Zurich timetables, converting them from DIVA export format to Google Transit format.""" from __future__ import print_function # This was written before transitfeed.py and we haven't yet found the # motivation to port it. Please see the examples directory for better # examples. try: from io import StringIO as cStringIO except ImportError: import cStringIO import csv import datetime import optparse import sys import urllib import zipfile # Zurich tram lines TRAM_LINES = {'2': ['FF3300', 'FFFFFF'], '3': ['009933', 'FFFFFF'], '4': ['333399', 'FFFFFF'], '5': ['996600', 'FFFFFF'], '6': ['CC9933', 'FFFFFF'], '7': ['000000', 'FFFFFF'], '8': ['99CC00', '000000'], '9': ['333399', 'FFFFFF'], '10': ['FF6699', 'FFFFFF'], '11': ['009933', 'FFFFFF'], '12': ['FFFFFF', '000000'], '13': ['FFCC33', '000000'], '14': ['3399CC', 'FFFFFF'], '15': ['FF3300', 'FFFFFF']} # Terms that indicate points of interest. Used to split station names # to (name, city). POI_TERMS = {'Bahnhof': 1, 'Dorfzentrum': 1, 'Schiffstation': 1, 'Station': 1, u'Zentrum': 1, 'Dorfplatz': 1, 'Zentrum/Bahnhof': 1, 'Dorf': 1} # Maps station names to (name, city). Used as exception list where our # simple heuristcs doesn't work. SPECIAL_NAMES = { 'Freienbach SOB, Bahnhof': ('Freienbach SOB', 'Freienbach'), 'Herrliberg-Feldmeilen,Bhf West': ('Bahnhof West', 'Herrliberg-Feldmeilen'), 'Neue Forch': ('Neue Forch', u'Z\u00fcrich'), 'Oberrieden Dorf Bahnhof': ('Oberrieden Dorf', 'Oberrieden'), 'Spital Zollikerberg': ('Spital', 'Zollikerberg'), 'Triemli': ('Triemli', u'Z\u00fcrich'), 'Zentrum Glatt': ('Zentrum Glatt', 'Wallisellen'), } # Cities whose names we want to prettify/correct at import time. SPECIAL_CITIES = { 'Affoltern a. A.': 'Affoltern am Albis', 'Wangen b. D.': 'Wangen' } def read_csv(s, cols): csv_dialect = csv.Sniffer().sniff(s[0]) reader = csv.reader(s, csv_dialect) header = next(reader) col_index = [-1] * len(cols) for i in range(len(cols)): if cols[i] in header: col_index[i] = header.index(cols[i]) for row in reader: result = [None] * len(cols) for i in range(len(cols)): ci = col_index[i] if ci >= 0: result[i] = row[ci].decode('iso-8859-1').strip() yield result def convert_c_h1903(x, y): "Converts coordinates from the 1903 Swiss national grid system to WGS-84." yb = (x - 600000.0) / 1e6; xb = (y - 200000.0) / 1e6; lam = 2.6779094 \ + 4.728982 * yb \ + 0.791484 * yb * xb \ + 0.1306 * yb * xb * xb \ - 0.0436 * yb * yb * yb phi = 16.9023892 \ + 3.238372 * xb \ - 0.270978 * yb * yb \ - 0.002582 * xb * xb \ - 0.0447 * yb * yb * xb \ - 0.0140 * xb * xb * xb return phi * 100.0 / 36.0, lam * 100.0 / 36.0 def encode_for_csv(x): "Encodes one value for CSV." k = x.encode('utf-8') if ',' in k or '"' in k: return '"%s"' % k.replace('"', '""') else: return k def write_row(stream, values): "writes one row of comma-separated values to stream." stream.write(','.join([encode_for_csv(val) for val in values])) stream.write('\n') class Station: pass class Route: pass class Pattern: pass class Trip: pass # https://developers.google.com/transit/gtfs/ TYPE_TRAM = 0 TYPE_BUS = 3 class Divaimporter: def __init__(self, coord_converter, drop_unadvertised_lines): self.coord_converter = coord_converter self.stations = {} # id --> Station self.routes = {} # id --> Route self.patterns = {} # id --> Pattern self.services = {} # id --> [date, date, ...] (sorted) self.pickup_type = {} # (trip_id, stop_seq) --> '0'=normal/'1'=no pickup self.drop_off_type = {} # (trip_id, stop_seq) --> '0'/'1', '1'=no drop-off self.trips = {} # id --> Trip self.goodTrips = {} self._drop_unadvertised_lines = drop_unadvertised_lines @staticmethod def demangle_name(name): "Applies some simple heuristics to split names into (city, name)." # Handle special cases where our heuristcs doesn't work. # Example:"Triemli" --> ("Triemli", "Zurich"). if name in SPECIAL_NAMES: return SPECIAL_NAMES[name] # Expand abbreviations. for abbrev, expanded in [('str.', 'strasse'), ('Schiffst.', 'Schiffstation')]: suffix_pos = name.rfind(abbrev) if suffix_pos > 0: name = name[:suffix_pos] + expanded # end for names = name.split(", ", 1) if len(names) == 2: if names[1] in POI_TERMS: nam = u'%s %s' % (names[0], names[1]) else: nam = names[1] city = names[0] else: # "Zurich Enge": First word of station name designates the city nam = names[0] city = nam.split(' ')[0] return nam, SPECIAL_CITIES.get(city, city) def import_feeds(self, inpath): inzip = zipfile.ZipFile(inpath, mode="r") read = lambda name, prefix="": (prefix + inzip.read(name)).splitlines() # The advertised lines file has no column headers. self.import_stations(read('rec_ort.mdv'), read('bedienendeLinien_google.csv', "ORT_NR;LI_NR;;;;")) self.import_routes(read('rec_lin_ber.mdv')) self.import_patterns(read('lid_verlauf.mdv')) self.import_services(read('tagesart_merkmal.mdv'), read('firmenkalender.mdv')) self.import_traffic_restrictions(read('vb_regio.mdv')) self.import_boarding(read('bedverb.mdv')) self.import_stop_times(read('lid_fahrzeitart.mdv')) self.import_trips(read('rec_frt.mdv')) def import_stations(self, station_file, adv_file): "imports the rec_ort.mdv file." for id, name, x, y, uic_code in \ read_csv(station_file, ['ORT_NR', 'ORT_NAME', 'ORT_POS_X', 'ORT_POS_Y', 'ORT_NR_NATIONAL']): station = Station() station.id = id station.position = self.coord_converter(float(x), float(y)) station.uic_code = '' if uic_code and len(uic_code) == 7 and uic_code[:2] == '85': station.uic_code = uic_code station.name, station.city = self.demangle_name(name) station.country = 'CH' station.url = 'http://fahrplan.zvv.ch/?to.0=' + \ urllib.quote(name.encode('iso-8859-1')) station.advertised_lines = set() self.stations[id] = station for station_id, line_id in read_csv(adv_file, ['ORT_NR', 'LI_NR']): if station_id in self.stations: # Line ids in this file have leading zeroes, remove. self.stations[station_id].advertised_lines.add(line_id.lstrip("0")) else: print("Warning, advertised lines file references " \ "unknown station, id " + station_id) def import_routes(self, s): "imports the rec_lin_ber.mdv file." # the line id is really qualified with an area_id (BEREICH_NR), but the # table of advertised lines does not include area. Fortunately, it seems # that line ids are unique across all areas, so we can just throw it away. for line_id, name in \ read_csv(s, ['LI_NR', 'LINIEN_BEZ_DRUCK']): route = Route() route.id = line_id route.name = name route.color = "FFFFFF" route.color_text = "000000" if name in TRAM_LINES: route.type = TYPE_TRAM route.color = TRAM_LINES[name][0] route.color_text = TRAM_LINES[name][1] else: route.type = TYPE_BUS if route.name[0:1] == "N": route.color = "000000" route.color_text = "FFFF00" self.routes[route.id] = route def import_patterns(self, s): "imports the lid_verlauf.mdv file." for line, strli, direction, seq, station_id in \ read_csv(s, ['LI_NR', 'STR_LI_VAR', 'LI_RI_NR', 'LI_LFD_NR', 'ORT_NR']): pattern_id = u'Pat.%s.%s.%s' % (line, strli, direction) pattern = self.patterns.get(pattern_id, None) if not pattern: pattern = Pattern() pattern.id = pattern_id pattern.stops = [] pattern.stoptimes = {} self.patterns[pattern_id] = pattern seq = int(seq) - 1 if len(pattern.stops) <= seq: pattern.stops.extend([None] * (seq - len(pattern.stops) + 1)) pattern.stops[seq] = station_id def import_boarding(self, drop_off_file): "Reads the bedverb.mdv file." for trip_id, seq, code in \ read_csv(drop_off_file, ['FRT_FID', 'LI_LFD_NR', 'BEDVERB_CODE']): key = (trip_id, int(seq) - 1) if code == 'A': self.pickup_type[key] = '1' # '1' = no pick-up elif code == 'E': self.drop_off_type[key] = '1' # '1' = no drop-off elif code == 'B': # 'B' just means that rider needs to push a button to have the driver # stop. We don't encode this for now. pass else: raise ValueError('Unexpected code in bedverb.mdv; ' 'FRT_FID=%s BEDVERB_CODE=%s' % (trip_id, code)) def import_services(self, daytype_file, days_file): daytypes = {} # 'j06' --> {20060713:1, 20060714:1, ...} schedules = {} # {'j06':1, 'p27':1} for schedule, daytype, date in \ read_csv(days_file, ['FPL_KUERZEL', 'TAGESART_NR', 'BETRIEBSTAG']): schedule = schedule.strip() daytypes.setdefault('%s.%s' % (schedule, daytype), {})[int(date)] = 1 schedules[schedule] = 1 schedules = schedules.keys() service_days = {} # 'Cj06.H9' --> {20060713:1, 20060714:1, ...} for daytype, service_id in \ read_csv(daytype_file, ['TAGESART_NR', 'TAGESMERKMAL_NR']): for schedule in schedules: service = 'C%s.%s' % (schedule, service_id) for date in daytypes['%s.%s' % (schedule, daytype)].iterkeys(): service_days.setdefault(service, {})[date] = 1 for k in service_days.iterkeys(): self.services[k] = service_days[k].keys() self.services[k].sort() def import_traffic_restrictions(self, restrictions_file): "Reads the vb_regio.mdv file." ParseDate = lambda x: datetime.date(int(x[:4]), int(x[4:6]), int(x[6:8])) MonthNr = lambda x: int(x[:4]) * 12 + int(x[4:6]) for schedule, id, bitmask, start_date, end_date in \ read_csv(restrictions_file, ['FPL_KUERZEL', 'VB', 'VB_DATUM', 'DATUM_VON', 'DATUM_BIS']): id = u"VB%s.%s" % (schedule, id) bitmask = bitmask.strip() dates = {} # This is ugly as hell, I know. I briefly explain what I do: # 8 characters in the bitmask equal a month ( 8 * 4bits = 32, no month has # more than 31 days, so it's ok). # Then I check if the current day of the month is in the bitmask (by # shifting the bit by x days and comparing it to the bitmask). # If so I calculate back what year month and actual day I am in # (very disgusting) and mark that date... for i in range(MonthNr(end_date) - MonthNr(start_date) + 1): mask = int(bitmask[i * 8:i * 8 + 8], 16) for d in range(32): if 1 << d & mask: year = int(start_date[0:4]) + ((int(start_date[4:6]) + i - 1)) / 12 month = ((int(start_date[4:6]) + i - 1) % 12) + 1 day = d + 1 cur_date = str(year) + ("0" + str(month))[-2:] + ("0" + str(day))[-2:] dates[int(cur_date)] = 1 self.services[id] = dates.keys() self.services[id].sort() def import_stop_times(self, stoptimes_file): "imports the lid_fahrzeitart.mdv file." for line, strli, direction, seq, stoptime_id, drive_secs, wait_secs in \ read_csv(stoptimes_file, ['LI_NR', 'STR_LI_VAR', 'LI_RI_NR', 'LI_LFD_NR', 'FGR_NR', 'FZT_REL', 'HZEIT']): pattern = self.patterns[u'Pat.%s.%s.%s' % (line, strli, direction)] stoptimes = pattern.stoptimes.setdefault(stoptime_id, []) seq = int(seq) - 1 drive_secs = int(drive_secs) wait_secs = int(wait_secs) assert len(stoptimes) == seq # fails if seq not in order stoptimes.append((drive_secs, wait_secs)) def import_trips(self, trips_file): "imports the rec_frt.mdv file." for trip_id, trip_starttime, line, strli, direction, \ stoptime_id, schedule_id, daytype_id, restriction_id, \ dest_station_id, dest_stop_id, trip_type in \ read_csv(trips_file, ['FRT_FID', 'FRT_START', 'LI_NR', 'STR_LI_VAR', 'LI_RI_NR', 'FGR_NR', 'FPL_KUERZEL', 'TAGESMERKMAL_NR', 'VB', 'FRT_HP_AUS', 'HALTEPUNKT_NR_ZIEL', 'FAHRTART_NR']): if trip_type != '1': print("skipping Trip ", trip_id, line, direction, \ dest_station_id, trip_type) continue # 1=normal, 2=empty, 3=from depot, 4=to depot, 5=other trip = Trip() # The trip_id (FRT_FID) field is not unique in the vbz data, as of Dec 2009 # to prevent overwritingimported trips when we key them by trip.id # we should make trip.id unique, by combining trip_id and line trip.id = ("%s_%s") % (trip_id, line) trip.starttime = int(trip_starttime) trip.route = self.routes[line] dest_station = self.stations[dest_station_id] pattern_id = u'Pat.%s.%s.%s' % (line, strli, direction) trip.pattern = self.patterns[pattern_id] trip.stoptimes = trip.pattern.stoptimes[stoptime_id] if restriction_id: service_id = u'VB%s.%s' % (schedule_id, restriction_id) else: service_id = u'C%s.%s' % (schedule_id, daytype_id) trip.service_id = service_id assert len(self.services[service_id]) > 0 assert not trip.id in self.trips self.trips[trip.id] = trip def write(self, outpath): "writes a .zip file in Google Transit format." out = zipfile.ZipFile(outpath, mode="w", compression=zipfile.ZIP_DEFLATED) for filename, func in [('agency.txt', self.write_agency), ('calendar.txt', self.write_calendar), ('calendar_dates.txt', self.write_calendarDates), ('routes.txt', self.write_routes), ('trips.txt', self.write_trips), ('stops.txt', self.write_stations), ('stop_times.txt', self.write_stop_times)]: s = cStringIO.StringIO() func(s) out.writestr(filename, s.getvalue()) out.close() @staticmethod def write_agency(out): out.write('agency_name,agency_url,agency_lang,agency_timezone\n') out.write('VBZ,http://www.vbz.ch/,de,Europe/Zurich\n') def write_routes(self, out): out.write('route_id,route_short_name,route_long_name,route_type,' 'route_color,route_text_color\n') k = [(r.id, r) for r in self.routes.itervalues()] k.sort() for id, route in k: name = encode_for_csv(route.name) out.write('%s,%s,%s,%s,%s,%s\n' % ( id, name, name, route.type, route.color, route.color_text)) def write_stations(self, out): out.write('stop_id,stop_uic_code,stop_name,stop_city,stop_country,' 'stop_lat,stop_lon,stop_url\n') stations = [(s.id, s) for s in self.stations.itervalues()] stations.sort() for id, s in stations: write_row(out, [id, s.uic_code, s.name, s.city, s.country, str(s.position[0]), str(s.position[1]), s.url]) def write_calendar(self, out): out.write('service_id,monday,tuesday,wednesday,thursday,' 'friday,saturday,sunday,start_date,end_date\n') for service_id, service in self.services.iteritems(): out.write('%s,0,0,0,0,0,0,0,%d,%d\n' % (encode_for_csv(service_id), service[0], service[-1])) def write_calendarDates(self, out): out.write('service_id,date,exception_type\n') for service_id, service in self.services.iteritems(): encoded_service_id = encode_for_csv(service_id) for date in service: out.write('%s,%d,1\n' % (encoded_service_id, date)) def write_trips(self, out): out.write('trip_id,route_id,service_id,trip_headsign\n') trips = [(t.id, t) for t in self.trips.itervalues()] trips.sort() for (trip_id, trip) in trips: if (not len(trip.pattern.stops)) or (None in trip.pattern.stops): print("*** Skipping bad trip: ", [trip.id]) continue self.goodTrips[trip_id] = True headsign = self.stations[trip.pattern.stops[-1]].name write_row(out, [trip.id, trip.route.id, trip.service_id, headsign]) @staticmethod def format_time(t): return "%02d:%02d:%02d" % (t / 3600, (t % 3600) / 60, t % 60) def write_stop_times(self, out): out.write('trip_id,stop_sequence,stop_id,arrival_time,departure_time,' 'pickup_type,drop_off_type\n') trips = [(t.id, t) for t in self.trips.itervalues()] trips.sort() for (trip_id, trip) in trips: if trip_id not in self.goodTrips: continue assert len(trip.stoptimes) == len(trip.pattern.stops) time = trip.starttime for seq in range(len(trip.stoptimes)): drive_time, wait_time = trip.stoptimes[seq] time += drive_time station = self.stations[trip.pattern.stops[seq]] if not self._drop_unadvertised_lines or \ trip.route.id in station.advertised_lines: write_row(out, [trip.id, str(seq + 1), station.id, self.format_time(time), self.format_time(time + wait_time), self.pickup_type.get((trip.id, seq), '0'), self.drop_off_type.get((trip.id, seq), '0')]) time += wait_time def main(argv): # It's hard to replicate the old behavior of --drop_unadvertised_lines, so we # don't. Instead, there are only two options without arguments: # nothing drop # --nodrop_unadvertised_lines do not drop # --drop_unadvertised_lines drop opt_parser = optparse.OptionParser() # drop_unadvertised_lines: Only export the departures of lines that # are advertised at the station in question. This is used to remove # depot trips etc, to not confuse the data in schedule bubbles. Use # --nodrop_unadvertised_lines to disable that. opt_parser.add_option('--drop_unadvertised_lines', action='store_true', dest='drop_unadvertised_lines', default=True) opt_parser.add_option('--nodrop_unadvertised_lines', action='store_false', dest='drop_unadvertised_lines') opt_parser.add_option('--in_file', action='store', type='string') opt_parser.add_option('--out_file', action='store', type='string') options, unused_arguments = opt_parser.parse_args(argv[1:]) if options.in_file is None: raise SystemExit('Please provide a value to the --in_file flag.') if options.out_file is None: raise SystemExit('Please provide a value to the --out_file flag.') importer = Divaimporter(convert_c_h1903, options.drop_unadvertised_lines) importer.Import(options.in_file) importer.write(options.out_file) print('Wrote output to', options.out_file) if __name__ == '__main__': main(sys.argv)
42.62768
94
0.559813
2,779
21,868
4.24937
0.222022
0.01321
0.019561
0.007621
0.104751
0.076721
0.055805
0.047676
0.036752
0.029469
0
0.02959
0.313838
21,868
512
95
42.710938
0.757414
0.171163
0
0.080808
0
0.002525
0.160013
0.035714
0
0
0
0
0.010101
1
0.063131
false
0.012626
0.090909
0.002525
0.181818
0.012626
0
0
0
null
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
null
0
0
0
0
0
0
0
0
0
0
0
0
1
0
810397b3d3caaed833502145ab5542c3eb653710
723
py
Python
csat/django/fields.py
GaretJax/csat
db63441136369436140a91c9657444353c8944e6
[ "MIT" ]
null
null
null
csat/django/fields.py
GaretJax/csat
db63441136369436140a91c9657444353c8944e6
[ "MIT" ]
7
2020-06-05T17:15:29.000Z
2022-02-11T03:38:15.000Z
csat/django/fields.py
GaretJax/csat
db63441136369436140a91c9657444353c8944e6
[ "MIT" ]
null
null
null
from lxml import etree from django import forms from django.db import models class XMLFileField(models.FileField): def __init__(self, *args, **kwargs): self.schema = kwargs.pop('schema') super(XMLFileField, self).__init__(*args, **kwargs) def clean(self, *args, **kwargs): data = super(XMLFileField, self).clean(*args, **kwargs) with data as fh: doc = etree.parse(fh) with open(self.schema) as fh: schema = etree.XMLSchema(etree.parse(fh)) if not schema.validate(doc): raise forms.ValidationError('The XML file failed to validate ' 'against the supplied schema.') return data
28.92
74
0.60166
85
723
5.023529
0.482353
0.093677
0.065574
0
0
0
0
0
0
0
0
0
0.29184
723
24
75
30.125
0.833984
0
0
0
0
0
0.091286
0
0
0
0
0
0
1
0.117647
false
0
0.176471
0
0.411765
0
0
0
0
null
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
null
0
0
0
0
0
0
0
0
0
0
0
0
1
0
8104cf1d7fdf7aff507bf4b2cd4aa7b19708a446
15,658
py
Python
keras_cv_attention_models/yolox/yolox.py
RishabhSehgal/keras_cv_attention_models
c1e20e45815339d70a987ec7dd9e6f926b4eb21d
[ "MIT" ]
null
null
null
keras_cv_attention_models/yolox/yolox.py
RishabhSehgal/keras_cv_attention_models
c1e20e45815339d70a987ec7dd9e6f926b4eb21d
[ "MIT" ]
null
null
null
keras_cv_attention_models/yolox/yolox.py
RishabhSehgal/keras_cv_attention_models
c1e20e45815339d70a987ec7dd9e6f926b4eb21d
[ "MIT" ]
null
null
null
import tensorflow as tf from tensorflow import keras from keras_cv_attention_models.attention_layers import ( activation_by_name, batchnorm_with_activation, conv2d_no_bias, depthwise_conv2d_no_bias, add_pre_post_process, ) from keras_cv_attention_models import model_surgery from keras_cv_attention_models.download_and_load import reload_model_weights from keras_cv_attention_models.coco.eval_func import DecodePredictions PRETRAINED_DICT = { "yolox_nano": {"coco": "7c97d60d4cc9d54321176f844acee627"}, "yolox_tiny": {"coco": "f9b51ff24290090c86a10a45f811140b"}, "yolox_s": {"coco": "a989f5a808ddc4a8242157a6a3e64977"}, "yolox_m": {"coco": "5c2333d2f12b2f48e3ec8555b29d242f"}, "yolox_l": {"coco": "a07c48994b7a67dba421025ef39b858b"}, "yolox_x": {"coco": "de9741d3f67f50c54856bcae0f07b7ef"}, } """ CSPDarknet backbone """ BATCH_NORM_EPSILON = 1e-3 BATCH_NORM_MOMENTUM = 0.03 def conv_dw_pw_block(inputs, filters, kernel_size=1, strides=1, use_depthwise_conv=False, activation="swish", name=""): nn = inputs if use_depthwise_conv: nn = depthwise_conv2d_no_bias(nn, kernel_size, strides, padding="SAME", name=name) nn = batchnorm_with_activation(nn, activation=activation, epsilon=BATCH_NORM_EPSILON, momentum=BATCH_NORM_MOMENTUM, name=name + "dw_") kernel_size, strides = 1, 1 nn = conv2d_no_bias(nn, filters, kernel_size, strides, padding="SAME", name=name) nn = batchnorm_with_activation(nn, activation=activation, epsilon=BATCH_NORM_EPSILON, momentum=BATCH_NORM_MOMENTUM, name=name) return nn def csp_block(inputs, expansion=0.5, use_shortcut=True, use_depthwise_conv=False, activation="swish", name=""): input_channels = inputs.shape[-1] nn = conv_dw_pw_block(inputs, int(input_channels * expansion), activation=activation, name=name + "1_") nn = conv_dw_pw_block(nn, input_channels, kernel_size=3, strides=1, use_depthwise_conv=use_depthwise_conv, activation=activation, name=name + "2_") if use_shortcut: nn = keras.layers.Add()([inputs, nn]) return nn def csp_stack(inputs, depth, out_channels=-1, expansion=0.5, use_shortcut=True, use_depthwise_conv=False, activation="swish", name=""): out_channels = inputs.shape[-1] if out_channels == -1 else out_channels hidden_channels = int(out_channels * expansion) short = conv_dw_pw_block(inputs, hidden_channels, kernel_size=1, activation=activation, name=name + "short_") deep = conv_dw_pw_block(inputs, hidden_channels, kernel_size=1, activation=activation, name=name + "deep_") for id in range(depth): block_name = name + "block{}_".format(id + 1) deep = csp_block(deep, 1, use_shortcut=use_shortcut, use_depthwise_conv=use_depthwise_conv, activation=activation, name=block_name) out = tf.concat([deep, short], axis=-1) out = conv_dw_pw_block(out, out_channels, kernel_size=1, activation=activation, name=name + "output_") return out def spatial_pyramid_pooling(inputs, pool_sizes=(5, 9, 13), activation="swish", name=""): input_channels = inputs.shape[-1] nn = conv_dw_pw_block(inputs, input_channels // 2, kernel_size=1, activation=activation, name=name + "1_") pp = [keras.layers.MaxPooling2D(pool_size=ii, strides=1, padding="SAME")(nn) for ii in pool_sizes] nn = tf.concat([nn, *pp], axis=-1) nn = conv_dw_pw_block(nn, input_channels, kernel_size=1, activation=activation, name=name + "2_") return nn def focus_stem(inputs, filters, kernel_size=3, strides=1, padding="valid", activation="swish", name=""): if padding.lower() == "same": # Handling odd input_shape inputs = tf.pad(inputs, [[0, 0], [0, 1], [0, 1], [0, 0]]) patch_top_left = inputs[:, :-1:2, :-1:2] patch_top_right = inputs[:, :-1:2, 1::2] patch_bottom_left = inputs[:, 1::2, :-1:2] patch_bottom_right = inputs[:, 1::2, 1::2] else: patch_top_left = inputs[:, ::2, ::2] patch_top_right = inputs[:, ::2, 1::2] patch_bottom_left = inputs[:, 1::2, ::2] patch_bottom_right = inputs[:, 1::2, 1::2] nn = tf.concat([patch_top_left, patch_bottom_left, patch_top_right, patch_bottom_right], axis=-1) nn = conv_dw_pw_block(nn, filters, kernel_size=kernel_size, strides=strides, activation=activation, name=name) return nn def CSPDarknet(width_mul=1, depth_mul=1, out_features=[-3, -2, -1], use_depthwise_conv=False, input_shape=(512, 512, 3), activation="swish", model_name=""): base_channels, base_depth = int(width_mul * 64), max(round(depth_mul * 3), 1) inputs = keras.layers.Input(input_shape) """ Stem """ nn = focus_stem(inputs, base_channels, activation=activation, name="stem_") features = [nn] """ dark blocks """ depthes = [base_depth, base_depth * 3, base_depth * 3, base_depth] channels = [base_channels * 2, base_channels * 4, base_channels * 8, base_channels * 16] use_spps = [False, False, False, True] use_shortcuts = [True, True, True, False] for id, (channel, depth, use_spp, use_shortcut) in enumerate(zip(channels, depthes, use_spps, use_shortcuts)): stack_name = "stack{}_".format(id + 1) nn = conv_dw_pw_block(nn, channel, kernel_size=3, strides=2, use_depthwise_conv=use_depthwise_conv, activation=activation, name=stack_name) if use_spp: nn = spatial_pyramid_pooling(nn, activation=activation, name=stack_name + "spp_") # nn = SPPBottleneck(base_channels * 16, base_channels * 16, activation=act) nn = csp_stack(nn, depth, use_shortcut=use_shortcut, use_depthwise_conv=use_depthwise_conv, activation=activation, name=stack_name) features.append(nn) nn = [features[ii] for ii in out_features] model = keras.models.Model(inputs, nn, name=model_name) return model """ path aggregation fpn """ def upsample_merge(inputs, csp_depth, use_depthwise_conv=False, activation="swish", name=""): # print(f">>>> upsample_merge inputs: {[ii.shape for ii in inputs] = }") target_channel = inputs[-1].shape[-1] fpn_out = conv_dw_pw_block(inputs[0], target_channel, activation=activation, name=name + "fpn_") # inputs[0] = keras.layers.UpSampling2D(size=(2, 2), interpolation="nearest", name=name + "up")(fpn_out) inputs[0] = tf.image.resize(fpn_out, tf.shape(inputs[-1])[1:-1], method="nearest") nn = tf.concat(inputs, axis=-1) nn = csp_stack(nn, csp_depth, target_channel, 0.5, False, use_depthwise_conv, activation=activation, name=name) return fpn_out, nn def downsample_merge(inputs, csp_depth, use_depthwise_conv=False, activation="swish", name=""): # print(f">>>> downsample_merge inputs: {[ii.shape for ii in inputs] = }") inputs[0] = conv_dw_pw_block(inputs[0], inputs[-1].shape[-1], 3, 2, use_depthwise_conv, activation=activation, name=name + "down_") nn = tf.concat(inputs, axis=-1) nn = csp_stack(nn, csp_depth, nn.shape[-1], 0.5, False, use_depthwise_conv, activation=activation, name=name) return nn def path_aggregation_fpn(features, depth_mul=1, use_depthwise_conv=False, activation="swish", name=""): # p5 ─> fpn_out0 ───────────> pan_out0 # ↓ ↑ # p4 ─> f_out0 ─> fpn_out1 ─> pan_out1 # ↓ ↑ # p3 ───────────> pan_out2 ──────┘ csp_depth = max(round(depth_mul * 3), 1) p3, p4, p5 = features # p3: [64, 64, 256], p4: [32, 32, 512], p5: [16, 16, 1024] # fpn_out0: [16, 16, 512], f_out0: [32, 32, 512] fpn_out0, f_out0 = upsample_merge([p5, p4], csp_depth, use_depthwise_conv=use_depthwise_conv, activation=activation, name=name + "c3p4_") # fpn_out1: [32, 32, 256], pan_out2: [64, 64, 256] fpn_out1, pan_out2 = upsample_merge([f_out0, p3], csp_depth, use_depthwise_conv=use_depthwise_conv, activation=activation, name=name + "c3p3_") # pan_out1: [32, 32, 512] pan_out1 = downsample_merge([pan_out2, fpn_out1], csp_depth, use_depthwise_conv=use_depthwise_conv, activation=activation, name=name + "c3n3_") # pan_out0: [16, 16, 1024] pan_out0 = downsample_merge([pan_out1, fpn_out0], csp_depth, use_depthwise_conv=use_depthwise_conv, activation=activation, name=name + "c3n4_") return [pan_out2, pan_out1, pan_out0] """ YOLOXHead """ def yolox_head_single(inputs, out_channels, num_classes=80, num_anchors=1, use_depthwise_conv=False, use_object_scores=True, activation="swish", name=""): bias_init = tf.constant_initializer(-tf.math.log((1 - 0.01) / 0.01).numpy()) # stem stem = conv_dw_pw_block(inputs, out_channels, activation=activation, name=name + "stem_") # cls_convs, cls_preds cls_nn = conv_dw_pw_block(stem, out_channels, kernel_size=3, use_depthwise_conv=use_depthwise_conv, activation=activation, name=name + "cls_1_") cls_nn = conv_dw_pw_block(cls_nn, out_channels, kernel_size=3, use_depthwise_conv=use_depthwise_conv, activation=activation, name=name + "cls_2_") cls_out = keras.layers.Conv2D(num_classes * num_anchors, kernel_size=1, bias_initializer=bias_init, name=name + "class_out")(cls_nn) cls_out = activation_by_name(cls_out, "sigmoid", name=name + "class_out_") cls_out = keras.layers.Reshape([-1, num_classes], name=name + "class_out_reshape")(cls_out) # reg_convs, reg_preds reg_nn = conv_dw_pw_block(stem, out_channels, kernel_size=3, use_depthwise_conv=use_depthwise_conv, activation=activation, name=name + "reg_1_") reg_nn = conv_dw_pw_block(reg_nn, out_channels, kernel_size=3, use_depthwise_conv=use_depthwise_conv, activation=activation, name=name + "reg_2_") reg_out = keras.layers.Conv2D(4 * num_anchors, kernel_size=1, name=name + "regression_out")(reg_nn) reg_out = keras.layers.Reshape([-1, 4], name=name + "regression_out_reshape")(reg_out) # obj_preds if use_object_scores: obj_out = keras.layers.Conv2D(1 * num_anchors, kernel_size=1, bias_initializer=bias_init, name=name + "object_out")(reg_nn) obj_out = activation_by_name(obj_out, "sigmoid", name=name + "object_out_") obj_out = keras.layers.Reshape([-1, 1], name=name + "object_out_reshape")(obj_out) return tf.concat([reg_out, cls_out, obj_out], axis=-1) else: return tf.concat([reg_out, cls_out], axis=-1) def yolox_head(inputs, width_mul=1.0, num_classes=80, num_anchors=1, use_depthwise_conv=False, use_object_scores=True, activation="swish", name=""): out_channel = int(256 * width_mul) outputs = [] for id, input in enumerate(inputs): cur_name = name + "{}_".format(id + 1) out = yolox_head_single(input, out_channel, num_classes, num_anchors, use_depthwise_conv, use_object_scores, activation=activation, name=cur_name) outputs.append(out) # outputs = tf.concat([keras.layers.Reshape([-1, ii.shape[-1]])(ii) for ii in outputs], axis=1) outputs = tf.concat(outputs, axis=1) return outputs """ YOLOX models """ def YOLOX( backbone=None, features_pick=[-3, -2, -1], depth_mul=1, width_mul=-1, # -1 means: `min([ii.shape[-1] for ii in features]) / 256` for custom backbones. use_depthwise_conv=False, use_anchor_free_mode=True, num_anchors="auto", # "auto" means 1 if use_anchor_free_mode else 9 use_object_scores="auto", # "auto" means same with use_anchor_free_mode input_shape=(640, 640, 3), num_classes=80, activation="swish", freeze_backbone=False, pretrained=None, model_name="yolox", pyramid_levels_min=3, # Init anchors for model prediction. anchor_scale="auto", # Init anchors for model prediction. "auto" means 1 if use_anchor_free_mode else 4 rescale_mode="raw", # For decode predictions, raw means input value in range [0, 255]. kwargs=None, # Not using, recieving parameter ): if backbone is None: width_mul = width_mul if width_mul > 0 else 1 backbone = CSPDarknet(width_mul, depth_mul, features_pick, use_depthwise_conv, input_shape, activation=activation, model_name="darknet") features = backbone.outputs else: if isinstance(features_pick[0], str): features = [backbone.get_layer(layer_name) for layer_name in features_pick] else: features = model_surgery.get_pyramide_feture_layers(backbone) features = [features[id] for id in features_pick] print(">>>> features:", {ii.name: ii.output_shape for ii in features}) features = [ii.output for ii in features] width_mul = width_mul if width_mul > 0 else min([ii.shape[-1] for ii in features]) / 256 print(">>>> width_mul:", width_mul) if freeze_backbone: backbone.trainable = False else: backbone.trainable = True inputs = backbone.inputs[0] use_object_scores = use_anchor_free_mode if use_object_scores == "auto" else use_object_scores num_anchors = (1 if use_anchor_free_mode else 9) if num_anchors == "auto" else num_anchors fpn_features = path_aggregation_fpn(features, depth_mul=depth_mul, use_depthwise_conv=use_depthwise_conv, activation=activation, name="pafpn_") outputs = yolox_head(fpn_features, width_mul, num_classes, num_anchors, use_depthwise_conv, use_object_scores, activation=activation, name="head_") outputs = keras.layers.Activation("linear", dtype="float32", name="outputs_fp32")(outputs) model = keras.models.Model(inputs, outputs, name=model_name) reload_model_weights(model, PRETRAINED_DICT, "yolox", pretrained) # AA = {"aspect_ratios": anchor_aspect_ratios, "num_scales": anchor_num_scales, "anchor_scale": anchor_scale, "grid_zero_start": anchor_grid_zero_start} pyramid_levels = [pyramid_levels_min, pyramid_levels_min + len(features_pick) - 1] # -> [3, 5] anchor_scale = (1 if use_anchor_free_mode else 4) if anchor_scale == "auto" else anchor_scale post_process = DecodePredictions(backbone.input_shape[1:], pyramid_levels, anchor_scale, use_anchor_free_mode, use_object_scores) add_pre_post_process(model, rescale_mode=rescale_mode, post_process=post_process) return model def YOLOXNano(input_shape=(416, 416, 3), freeze_backbone=False, num_classes=80, backbone=None, activation="swish", pretrained="coco", **kwargs): return YOLOX(**locals(), depth_mul=0.33, width_mul=0.25, use_depthwise_conv=True, model_name=kwargs.pop("model_name", "yolox_nano"), **kwargs) def YOLOXTiny(input_shape=(416, 416, 3), freeze_backbone=False, num_classes=80, backbone=None, activation="swish", pretrained="coco", **kwargs): return YOLOX(**locals(), depth_mul=0.33, width_mul=0.375, model_name=kwargs.pop("model_name", "yolox_tiny"), **kwargs) def YOLOXS(input_shape=(640, 640, 3), freeze_backbone=False, num_classes=80, backbone=None, activation="swish", pretrained="coco", **kwargs): return YOLOX(**locals(), depth_mul=0.33, width_mul=0.5, model_name=kwargs.pop("model_name", "yolox_s"), **kwargs) def YOLOXM(input_shape=(640, 640, 3), freeze_backbone=False, num_classes=80, backbone=None, activation="swish", pretrained="coco", **kwargs): return YOLOX(**locals(), depth_mul=0.67, width_mul=0.75, model_name=kwargs.pop("model_name", "yolox_m"), **kwargs) def YOLOXL(input_shape=(640, 640, 3), freeze_backbone=False, num_classes=80, backbone=None, activation="swish", pretrained="coco", **kwargs): return YOLOX(**locals(), depth_mul=1.0, width_mul=1.0, model_name=kwargs.pop("model_name", "yolox_l"), **kwargs) def YOLOXX(input_shape=(640, 640, 3), freeze_backbone=False, num_classes=80, backbone=None, activation="swish", pretrained="coco", **kwargs): return YOLOX(**locals(), depth_mul=1.33, width_mul=1.25, model_name=kwargs.pop("model_name", "yolox_x"), **kwargs)
54.940351
156
0.709158
2,273
15,658
4.609327
0.120106
0.050396
0.067195
0.056123
0.484872
0.424454
0.406223
0.366517
0.338074
0.304858
0
0.042312
0.154745
15,658
284
157
55.133803
0.746505
0.090305
0
0.089552
0
0
0.061245
0.015187
0
0
0
0
0
1
0.089552
false
0
0.029851
0.029851
0.21393
0.00995
0
0
0
null
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
null
0
0
0
0
0
0
0
0
0
0
0
0
1
0
8104ee7a90ab52a7bdf79ad5abbc624a2b356482
4,064
py
Python
robot-server/tests/service/json_api/test_response.py
mrod0101/opentrons
6450edb0421f1c2484c292f8583602d8f6fd13b8
[ "Apache-2.0" ]
null
null
null
robot-server/tests/service/json_api/test_response.py
mrod0101/opentrons
6450edb0421f1c2484c292f8583602d8f6fd13b8
[ "Apache-2.0" ]
2
2022-02-15T03:28:35.000Z
2022-02-28T01:34:18.000Z
robot-server/tests/service/json_api/test_response.py
mrod0101/opentrons
6450edb0421f1c2484c292f8583602d8f6fd13b8
[ "Apache-2.0" ]
null
null
null
from pytest import raises from pydantic import ValidationError from robot_server.service.json_api.response import ( ResponseDataModel, ResponseModel, MultiResponseModel, ) from tests.service.helpers import ItemResponseModel def test_attributes_as_dict() -> None: MyResponse = ResponseModel[ResponseDataModel, None] obj_to_validate = { "data": {"id": "123"}, "links": None, } my_response_object = MyResponse(**obj_to_validate) assert my_response_object.dict() == { "links": None, "data": { "id": "123", }, } def test_attributes_as_item_model() -> None: ItemResponse = ResponseModel[ItemResponseModel, None] obj_to_validate = { "links": None, "data": {"id": "123", "name": "apple", "quantity": 10, "price": 1.20}, } my_response_obj = ItemResponse(**obj_to_validate) assert my_response_obj.dict() == { "links": None, "data": { "id": "123", "name": "apple", "quantity": 10, "price": 1.20, }, } def test_list_item_model() -> None: ItemResponse = MultiResponseModel[ItemResponseModel, None] obj_to_validate = { "links": None, "data": [ {"id": "123", "name": "apple", "quantity": 10, "price": 1.20}, {"id": "321", "name": "banana", "quantity": 20, "price": 2.34}, ], } my_response_obj = ItemResponse(**obj_to_validate) assert my_response_obj.dict() == { "links": None, "data": [ { "id": "123", "name": "apple", "quantity": 10, "price": 1.20, }, { "id": "321", "name": "banana", "quantity": 20, "price": 2.34, }, ], } def test_attributes_as_item_model_empty_dict() -> None: ItemResponse = ResponseModel[ItemResponseModel, None] obj_to_validate = { "links": None, "data": { "id": "123", }, } with raises(ValidationError) as e: ItemResponse(**obj_to_validate) assert e.value.errors() == [ { "loc": ("data", "name"), "msg": "field required", "type": "value_error.missing", }, { "loc": ("data", "quantity"), "msg": "field required", "type": "value_error.missing", }, { "loc": ("data", "price"), "msg": "field required", "type": "value_error.missing", }, ] def test_response_constructed_with_resource_object() -> None: ItemResponse = ResponseModel[ItemResponseModel, None] item = ItemResponseModel(id="abc123", name="pear", price=1.2, quantity=10) data = item.dict() assert ItemResponse(data=data, links=None).dict() == { "links": None, "data": { "id": "abc123", "name": "pear", "price": 1.2, "quantity": 10, }, } def test_response_constructed_with_resource_object_list() -> None: ItemResponse = MultiResponseModel[ItemResponseModel, None] items = [ ItemResponseModel(id="1", name="apple", price=1.5, quantity=3), ItemResponseModel(id="2", name="pear", price=1.2, quantity=10), ItemResponseModel(id="3", name="orange", price=2.2, quantity=5), ] response = ItemResponse(data=items, links=None) assert response.dict() == { "links": None, "data": [ { "id": "1", "name": "apple", "price": 1.5, "quantity": 3, }, { "id": "2", "name": "pear", "price": 1.2, "quantity": 10, }, { "id": "3", "name": "orange", "price": 2.2, "quantity": 5, }, ], }
26.913907
78
0.483514
369
4,064
5.162602
0.189702
0.051969
0.054593
0.062992
0.685564
0.578478
0.52231
0.456693
0.456693
0.286614
0
0.037308
0.360236
4,064
150
79
27.093333
0.695385
0
0
0.407407
0
0
0.135335
0
0
0
0
0
0.044444
1
0.044444
false
0
0.02963
0
0.074074
0
0
0
0
null
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
null
0
0
0
0
0
0
0
0
0
0
0
0
1
0
81053c6c0f8dac07d6cae3bc4a12cf5b1f575105
2,300
py
Python
neutron/db/migration/alembic_migrations/versions/mitaka/contract/c6c112992c9_rbac_qos_policy.py
congnt95/neutron
6a73a362c5ff5b7c28c15a49f47a9900c0d2b4e1
[ "Apache-2.0" ]
1,080
2015-01-04T08:35:00.000Z
2022-03-27T09:15:52.000Z
neutron/db/migration/alembic_migrations/versions/mitaka/contract/c6c112992c9_rbac_qos_policy.py
congnt95/neutron
6a73a362c5ff5b7c28c15a49f47a9900c0d2b4e1
[ "Apache-2.0" ]
24
2015-02-21T01:48:28.000Z
2021-11-26T02:38:56.000Z
neutron/db/migration/alembic_migrations/versions/mitaka/contract/c6c112992c9_rbac_qos_policy.py
congnt95/neutron
6a73a362c5ff5b7c28c15a49f47a9900c0d2b4e1
[ "Apache-2.0" ]
1,241
2015-01-02T10:47:10.000Z
2022-03-27T09:42:23.000Z
# Copyright 2015 OpenStack Foundation # # Licensed under the Apache License, Version 2.0 (the "License"); you may # not use this file except in compliance with the License. You may obtain # a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, WITHOUT # WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the # License for the specific language governing permissions and limitations # under the License. # from alembic import op from oslo_utils import uuidutils import sqlalchemy as sa from neutron.db import rbac_db_models """rbac_qos_policy Revision ID: c6c112992c9 Revises: 8a6d8bdae39 Create Date: 2015-11-25 18:45:03.831359 """ # revision identifiers, used by Alembic. revision = 'c6c112992c9' down_revision = 'e3278ee65050' depends_on = ('15e43b934f81',) qos_rbacs = sa.Table( 'qospolicyrbacs', sa.MetaData(), sa.Column('id', sa.String(length=36), nullable=False), sa.Column('tenant_id', sa.String(length=255), nullable=True), sa.Column('target_tenant', sa.String(length=255), nullable=False), sa.Column('action', sa.String(length=255), nullable=False), sa.Column('object_id', sa.String(length=36), nullable=False)) # A simple model of the qos_policies table with only the fields needed for # the migration. qos_policy = sa.Table('qos_policies', sa.MetaData(), sa.Column('id', sa.String(length=36), nullable=False), sa.Column('tenant_id', sa.String(length=255)), sa.Column('shared', sa.Boolean(), nullable=False)) def upgrade(): op.bulk_insert(qos_rbacs, get_values()) op.drop_column('qos_policies', 'shared') def get_values(): session = sa.orm.Session(bind=op.get_bind()) values = [] for row in session.query(qos_policy).filter(qos_policy.c.shared).all(): values.append({'id': uuidutils.generate_uuid(), 'object_id': row[0], 'tenant_id': row[1], 'target_tenant': '*', 'action': rbac_db_models.ACCESS_SHARED}) session.commit() return values
33.333333
78
0.665652
309
2,300
4.854369
0.466019
0.042667
0.065333
0.053333
0.186
0.180667
0.180667
0.16
0.109333
0.109333
0
0.048199
0.215217
2,300
68
79
33.823529
0.782825
0.309565
0
0.060606
0
0
0.119863
0
0
0
0
0
0
1
0.060606
false
0
0.121212
0
0.212121
0
0
0
0
null
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
null
0
0
0
0
0
0
0
0
0
0
0
0
1
0
8105a101c915deb0c3d41bd2462e33e9a3a8584e
1,200
py
Python
chapter5/ch5_gcp_subscriber.py
ericchou1/network-devops-kafka-up-and-running
c128cf7359ba40c3005a02d3033b16b67c196779
[ "Apache-2.0" ]
1
2021-12-30T08:55:09.000Z
2021-12-30T08:55:09.000Z
chapter5/ch5_gcp_subscriber.py
ericchou1/network-devops-kafka-up-and-running
c128cf7359ba40c3005a02d3033b16b67c196779
[ "Apache-2.0" ]
null
null
null
chapter5/ch5_gcp_subscriber.py
ericchou1/network-devops-kafka-up-and-running
c128cf7359ba40c3005a02d3033b16b67c196779
[ "Apache-2.0" ]
2
2021-11-22T09:56:30.000Z
2022-02-06T22:55:55.000Z
from concurrent.futures import TimeoutError from google.cloud import pubsub_v1 project_id = "pubsub-testing-331300" subscription_id = "test-sub" # Number of seconds the subscriber should listen for messages timeout = 5.0 subscriber = pubsub_v1.SubscriberClient() # The `subscription_path` method creates a fully qualified identifier # in the form `projects/{project_id}/subscriptions/{subscription_id}` subscription_path = subscriber.subscription_path(project_id, subscription_id) def callback(message: pubsub_v1.subscriber.message.Message) -> None: print(f"Received {message}.") message.ack() streaming_pull_future = subscriber.subscribe(subscription_path, callback=callback) print(f"Listening for messages on {subscription_path}..\n") # Wrap subscriber in a 'with' block to automatically call close() when done. with subscriber: try: # When `timeout` is not set, result() will block indefinitely, # unless an exception is encountered first. streaming_pull_future.result(timeout=timeout) except TimeoutError: streaming_pull_future.cancel() # Trigger the shutdown. streaming_pull_future.result() # Block until the shutdown is complete.
38.709677
82
0.766667
151
1,200
5.94702
0.543046
0.089087
0.084633
0.055679
0
0
0
0
0
0
0
0.010763
0.148333
1,200
30
83
40
0.867906
0.360833
0
0
0
0
0.128137
0.058124
0
0
0
0
0
1
0.055556
false
0
0.111111
0
0.166667
0.111111
0
0
0
null
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
null
0
0
0
0
0
0
0
0
0
0
0
0
1
0
8107dd8d87df5ce3c83ed8d4993880ee03266544
2,136
py
Python
odoo-13.0/addons/google_drive/models/res_config_settings.py
VaibhavBhujade/Blockchain-ERP-interoperability
b5190a037fb6615386f7cbad024d51b0abd4ba03
[ "MIT" ]
null
null
null
odoo-13.0/addons/google_drive/models/res_config_settings.py
VaibhavBhujade/Blockchain-ERP-interoperability
b5190a037fb6615386f7cbad024d51b0abd4ba03
[ "MIT" ]
null
null
null
odoo-13.0/addons/google_drive/models/res_config_settings.py
VaibhavBhujade/Blockchain-ERP-interoperability
b5190a037fb6615386f7cbad024d51b0abd4ba03
[ "MIT" ]
null
null
null
# -*- coding: utf-8 -*- # Part of Odoo. See LICENSE file for full copyright and licensing details. from odoo import api, fields, models, _ class ResConfigSettings(models.TransientModel): _inherit = "res.config.settings" google_drive_authorization_code = fields.Char(string='Authorization Code', config_parameter='google_drive_authorization_code') google_drive_uri = fields.Char(compute='_compute_drive_uri', string='URI', help="The URL to generate the authorization code from Google") is_google_drive_token_generated = fields.Boolean(string='Refresh Token Generated') @api.depends('google_drive_authorization_code') def _compute_drive_uri(self): google_drive_uri = self.env['google.service']._get_google_token_uri('drive', scope=self.env['google.drive.config'].get_google_scope()) for config in self: config.google_drive_uri = google_drive_uri def get_values(self): res = super(ResConfigSettings, self).get_values() refresh_token = self.env['ir.config_parameter'].sudo().get_param('google_drive_refresh_token', False) res.update(is_google_drive_token_generated=bool(refresh_token)) return res def confirm_setup_token(self): params = self.env['ir.config_parameter'].sudo() authorization_code_before = params.get_param('google_drive_authorization_code') authorization_code = self.google_drive_authorization_code if authorization_code != authorization_code_before: refresh_token = ( self.env['google.service'].generate_refresh_token('drive', authorization_code) if authorization_code else False ) params.set_param('google_drive_refresh_token', refresh_token) def action_setup_token(self): self.ensure_one() template = self.env.ref('google_drive.google_drive_auth_code_wizard') return { 'name': _('Set up refresh token'), 'type': 'ir.actions.act_window', 'res_model': 'res.config.settings', 'views': [(template.id, 'form')], 'target': 'new', }
45.446809
142
0.69382
258
2,136
5.410853
0.344961
0.126075
0.094556
0.100287
0.17765
0.098854
0
0
0
0
0
0.000585
0.199438
2,136
46
143
46.434783
0.815789
0.044007
0
0
0
0
0.251103
0.102011
0
0
0
0
0
1
0.111111
false
0
0.027778
0
0.333333
0
0
0
0
null
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
null
0
0
0
0
0
0
0
0
0
0
0
0
1
0
81081edbfb2a07d5868f34f5440db42fe2a2e90a
17,308
py
Python
dataloaders/loader.py
sanger640/attMPTI
a2784b784e0900f3603baa3779631da67bcd0562
[ "MIT" ]
93
2021-03-18T13:56:42.000Z
2022-03-30T03:31:35.000Z
dataloaders/loader.py
sanger640/attMPTI
a2784b784e0900f3603baa3779631da67bcd0562
[ "MIT" ]
20
2021-03-30T12:36:05.000Z
2022-03-28T09:01:34.000Z
dataloaders/loader.py
sanger640/attMPTI
a2784b784e0900f3603baa3779631da67bcd0562
[ "MIT" ]
14
2021-04-17T17:19:19.000Z
2022-03-09T13:49:30.000Z
""" Data Loader for Generating Tasks Author: Zhao Na, 2020 """ import os import random import math import glob import numpy as np import h5py as h5 import transforms3d from itertools import combinations import torch from torch.utils.data import Dataset def sample_K_pointclouds(data_path, num_point, pc_attribs, pc_augm, pc_augm_config, scan_names, sampled_class, sampled_classes, is_support=False): '''sample K pointclouds and the corresponding labels for one class (one_way)''' ptclouds = [] labels = [] for scan_name in scan_names: ptcloud, label = sample_pointcloud(data_path, num_point, pc_attribs, pc_augm, pc_augm_config, scan_name, sampled_classes, sampled_class, support=is_support) ptclouds.append(ptcloud) labels.append(label) ptclouds = np.stack(ptclouds, axis=0) labels = np.stack(labels, axis=0) return ptclouds, labels def sample_pointcloud(data_path, num_point, pc_attribs, pc_augm, pc_augm_config, scan_name, sampled_classes, sampled_class=0, support=False, random_sample=False): sampled_classes = list(sampled_classes) data = np.load(os.path.join(data_path, 'data', '%s.npy' %scan_name)) N = data.shape[0] #number of points in this scan if random_sample: sampled_point_inds = np.random.choice(np.arange(N), num_point, replace=(N < num_point)) else: # If this point cloud is for support/query set, make sure that the sampled points contain target class valid_point_inds = np.nonzero(data[:,6] == sampled_class)[0] # indices of points belonging to the sampled class if N < num_point: sampled_valid_point_num = len(valid_point_inds) else: valid_ratio = len(valid_point_inds)/float(N) sampled_valid_point_num = int(valid_ratio*num_point) sampled_valid_point_inds = np.random.choice(valid_point_inds, sampled_valid_point_num, replace=False) sampled_other_point_inds = np.random.choice(np.arange(N), num_point-sampled_valid_point_num, replace=(N<num_point)) sampled_point_inds = np.concatenate([sampled_valid_point_inds, sampled_other_point_inds]) data = data[sampled_point_inds] xyz = data[:, 0:3] rgb = data[:, 3:6] labels = data[:,6].astype(np.int) xyz_min = np.amin(xyz, axis=0) xyz -= xyz_min if pc_augm: xyz = augment_pointcloud(xyz, pc_augm_config) if 'XYZ' in pc_attribs: xyz_min = np.amin(xyz, axis=0) XYZ = xyz - xyz_min xyz_max = np.amax(XYZ, axis=0) XYZ = XYZ/xyz_max ptcloud = [] if 'xyz' in pc_attribs: ptcloud.append(xyz) if 'rgb' in pc_attribs: ptcloud.append(rgb/255.) if 'XYZ' in pc_attribs: ptcloud.append(XYZ) ptcloud = np.concatenate(ptcloud, axis=1) if support: groundtruth = labels==sampled_class else: groundtruth = np.zeros_like(labels) for i, label in enumerate(labels): if label in sampled_classes: groundtruth[i] = sampled_classes.index(label)+1 return ptcloud, groundtruth def augment_pointcloud(P, pc_augm_config): """" Augmentation on XYZ and jittering of everything """ M = transforms3d.zooms.zfdir2mat(1) if pc_augm_config['scale'] > 1: s = random.uniform(1 / pc_augm_config['scale'], pc_augm_config['scale']) M = np.dot(transforms3d.zooms.zfdir2mat(s), M) if pc_augm_config['rot'] == 1: angle = random.uniform(0, 2 * math.pi) M = np.dot(transforms3d.axangles.axangle2mat([0, 0, 1], angle), M) # z=upright assumption if pc_augm_config['mirror_prob'] > 0: # mirroring x&y, not z if random.random() < pc_augm_config['mirror_prob'] / 2: M = np.dot(transforms3d.zooms.zfdir2mat(-1, [1, 0, 0]), M) if random.random() < pc_augm_config['mirror_prob'] / 2: M = np.dot(transforms3d.zooms.zfdir2mat(-1, [0, 1, 0]), M) P[:, :3] = np.dot(P[:, :3], M.T) if pc_augm_config['jitter']: sigma, clip = 0.01, 0.05 # https://github.com/charlesq34/pointnet/blob/master/provider.py#L74 P = P + np.clip(sigma * np.random.randn(*P.shape), -1 * clip, clip).astype(np.float32) return P class MyDataset(Dataset): def __init__(self, data_path, dataset_name, cvfold=0, num_episode=50000, n_way=3, k_shot=5, n_queries=1, phase=None, mode='train', num_point=4096, pc_attribs='xyz', pc_augm=False, pc_augm_config=None): super(MyDataset).__init__() self.data_path = data_path self.n_way = n_way self.k_shot = k_shot self.n_queries = n_queries self.num_episode = num_episode self.phase = phase self.mode = mode self.num_point = num_point self.pc_attribs = pc_attribs self.pc_augm = pc_augm self.pc_augm_config = pc_augm_config if dataset_name == 's3dis': from dataloaders.s3dis import S3DISDataset self.dataset = S3DISDataset(cvfold, data_path) elif dataset_name == 'scannet': from dataloaders.scannet import ScanNetDataset self.dataset = ScanNetDataset(cvfold, data_path) else: raise NotImplementedError('Unknown dataset %s!' % dataset_name) if mode == 'train': self.classes = np.array(self.dataset.train_classes) elif mode == 'test': self.classes = np.array(self.dataset.test_classes) else: raise NotImplementedError('Unkown mode %s! [Options: train/test]' % mode) print('MODE: {0} | Classes: {1}'.format(mode, self.classes)) self.class2scans = self.dataset.class2scans def __len__(self): return self.num_episode def __getitem__(self, index, n_way_classes=None): if n_way_classes is not None: sampled_classes = np.array(n_way_classes) else: sampled_classes = np.random.choice(self.classes, self.n_way, replace=False) support_ptclouds, support_masks, query_ptclouds, query_labels = self.generate_one_episode(sampled_classes) if self.mode == 'train' and self.phase == 'metatrain': remain_classes = list(set(self.classes) - set(sampled_classes)) try: sampled_valid_classes = np.random.choice(np.array(remain_classes), self.n_way, replace=False) except: raise NotImplementedError('Error! The number remaining classes is less than %d_way' %self.n_way) valid_support_ptclouds, valid_support_masks, valid_query_ptclouds, \ valid_query_labels = self.generate_one_episode(sampled_valid_classes) return support_ptclouds.astype(np.float32), \ support_masks.astype(np.int32), \ query_ptclouds.astype(np.float32), \ query_labels.astype(np.int64), \ valid_support_ptclouds.astype(np.float32), \ valid_support_masks.astype(np.int32), \ valid_query_ptclouds.astype(np.float32), \ valid_query_labels.astype(np.int64) else: return support_ptclouds.astype(np.float32), \ support_masks.astype(np.int32), \ query_ptclouds.astype(np.float32), \ query_labels.astype(np.int64), \ sampled_classes.astype(np.int32) def generate_one_episode(self, sampled_classes): support_ptclouds = [] support_masks = [] query_ptclouds = [] query_labels = [] black_list = [] # to store the sampled scan names, in order to prevent sampling one scan several times... for sampled_class in sampled_classes: all_scannames = self.class2scans[sampled_class].copy() if len(black_list) != 0: all_scannames = [x for x in all_scannames if x not in black_list] selected_scannames = np.random.choice(all_scannames, self.k_shot+self.n_queries, replace=False) black_list.extend(selected_scannames) query_scannames = selected_scannames[:self.n_queries] support_scannames = selected_scannames[self.n_queries:] query_ptclouds_one_way, query_labels_one_way = sample_K_pointclouds(self.data_path, self.num_point, self.pc_attribs, self.pc_augm, self.pc_augm_config, query_scannames, sampled_class, sampled_classes, is_support=False) support_ptclouds_one_way, support_masks_one_way = sample_K_pointclouds(self.data_path, self.num_point, self.pc_attribs, self.pc_augm, self.pc_augm_config, support_scannames, sampled_class, sampled_classes, is_support=True) query_ptclouds.append(query_ptclouds_one_way) query_labels.append(query_labels_one_way) support_ptclouds.append(support_ptclouds_one_way) support_masks.append(support_masks_one_way) support_ptclouds = np.stack(support_ptclouds, axis=0) support_masks = np.stack(support_masks, axis=0) query_ptclouds = np.concatenate(query_ptclouds, axis=0) query_labels = np.concatenate(query_labels, axis=0) return support_ptclouds, support_masks, query_ptclouds, query_labels def batch_train_task_collate(batch): task_train_support_ptclouds, task_train_support_masks, task_train_query_ptclouds, task_train_query_labels, \ task_valid_support_ptclouds, task_valid_support_masks, task_valid_query_ptclouds, task_valid_query_labels = list(zip(*batch)) task_train_support_ptclouds = np.stack(task_train_support_ptclouds) task_train_support_masks = np.stack(task_train_support_masks) task_train_query_ptclouds = np.stack(task_train_query_ptclouds) task_train_query_labels = np.stack(task_train_query_labels) task_valid_support_ptclouds = np.stack(task_valid_support_ptclouds) task_valid_support_masks = np.stack(task_valid_support_masks) task_valid_query_ptclouds = np.array(task_valid_query_ptclouds) task_valid_query_labels = np.stack(task_valid_query_labels) data = [torch.from_numpy(task_train_support_ptclouds).transpose(3,4), torch.from_numpy(task_train_support_masks), torch.from_numpy(task_train_query_ptclouds).transpose(2,3), torch.from_numpy(task_train_query_labels), torch.from_numpy(task_valid_support_ptclouds).transpose(3,4), torch.from_numpy(task_valid_support_masks), torch.from_numpy(task_valid_query_ptclouds).transpose(2,3), torch.from_numpy(task_valid_query_labels)] return data ################################################ Static Testing Dataset ################################################ class MyTestDataset(Dataset): def __init__(self, data_path, dataset_name, cvfold=0, num_episode_per_comb=100, n_way=3, k_shot=5, n_queries=1, num_point=4096, pc_attribs='xyz', mode='valid'): super(MyTestDataset).__init__() dataset = MyDataset(data_path, dataset_name, cvfold=cvfold, n_way=n_way, k_shot=k_shot, n_queries=n_queries, mode='test', num_point=num_point, pc_attribs=pc_attribs, pc_augm=False) self.classes = dataset.classes if mode == 'valid': test_data_path = os.path.join(data_path, 'S_%d_N_%d_K_%d_episodes_%d_pts_%d' % ( cvfold, n_way, k_shot, num_episode_per_comb, num_point)) elif mode == 'test': test_data_path = os.path.join(data_path, 'S_%d_N_%d_K_%d_test_episodes_%d_pts_%d' % ( cvfold, n_way, k_shot, num_episode_per_comb, num_point)) else: raise NotImplementedError('Mode (%s) is unknown!' %mode) if os.path.exists(test_data_path): self.file_names = glob.glob(os.path.join(test_data_path, '*.h5')) self.num_episode = len(self.file_names) else: print('Test dataset (%s) does not exist...\n Constructing...' %test_data_path) os.mkdir(test_data_path) class_comb = list(combinations(self.classes, n_way)) # [(),(),(),...] self.num_episode = len(class_comb) * num_episode_per_comb episode_ind = 0 self.file_names = [] for sampled_classes in class_comb: sampled_classes = list(sampled_classes) for i in range(num_episode_per_comb): data = dataset.__getitem__(episode_ind, sampled_classes) out_filename = os.path.join(test_data_path, '%d.h5' % episode_ind) write_episode(out_filename, data) self.file_names.append(out_filename) episode_ind += 1 def __len__(self): return self.num_episode def __getitem__(self, index): file_name = self.file_names[index] return read_episode(file_name) def batch_test_task_collate(batch): batch_support_ptclouds, batch_support_masks, batch_query_ptclouds, batch_query_labels, batch_sampled_classes = batch[0] data = [torch.from_numpy(batch_support_ptclouds).transpose(2,3), torch.from_numpy(batch_support_masks), torch.from_numpy(batch_query_ptclouds).transpose(1,2), torch.from_numpy(batch_query_labels.astype(np.int64))] return data, batch_sampled_classes def write_episode(out_filename, data): support_ptclouds, support_masks, query_ptclouds, query_labels, sampled_classes = data data_file = h5.File(out_filename, 'w') data_file.create_dataset('support_ptclouds', data=support_ptclouds, dtype='float32') data_file.create_dataset('support_masks', data=support_masks, dtype='int32') data_file.create_dataset('query_ptclouds', data=query_ptclouds, dtype='float32') data_file.create_dataset('query_labels', data=query_labels, dtype='int64') data_file.create_dataset('sampled_classes', data=sampled_classes, dtype='int32') data_file.close() print('\t {0} saved! | classes: {1}'.format(out_filename, sampled_classes)) def read_episode(file_name): data_file = h5.File(file_name, 'r') support_ptclouds = data_file['support_ptclouds'][:] support_masks = data_file['support_masks'][:] query_ptclouds = data_file['query_ptclouds'][:] query_labels = data_file['query_labels'][:] sampled_classes = data_file['sampled_classes'][:] return support_ptclouds, support_masks, query_ptclouds, query_labels, sampled_classes ################################################ Pre-train Dataset ################################################ class MyPretrainDataset(Dataset): def __init__(self, data_path, classes, class2scans, mode='train', num_point=4096, pc_attribs='xyz', pc_augm=False, pc_augm_config=None): super(MyPretrainDataset).__init__() self.data_path = data_path self.classes = classes self.num_point = num_point self.pc_attribs = pc_attribs self.pc_augm = pc_augm self.pc_augm_config = pc_augm_config train_block_names = [] all_block_names = [] for k, v in sorted(class2scans.items()): all_block_names.extend(v) n_blocks = len(v) n_test_blocks = int(n_blocks * 0.1) n_train_blocks = n_blocks - n_test_blocks train_block_names.extend(v[:n_train_blocks]) if mode == 'train': self.block_names = list(set(train_block_names)) elif mode == 'test': self.block_names = list(set(all_block_names) - set(train_block_names)) else: raise NotImplementedError('Mode is unknown!') print('[Pretrain Dataset] Mode: {0} | Num_blocks: {1}'.format(mode, len(self.block_names))) def __len__(self): return len(self.block_names) def __getitem__(self, index): block_name = self.block_names[index] ptcloud, label = sample_pointcloud(self.data_path, self.num_point, self.pc_attribs, self.pc_augm, self.pc_augm_config, block_name, self.classes, random_sample=True) return torch.from_numpy(ptcloud.transpose().astype(np.float32)), torch.from_numpy(label.astype(np.int64))
46.526882
129
0.621389
2,140
17,308
4.68972
0.120561
0.021523
0.026305
0.014348
0.459845
0.371762
0.311379
0.26933
0.205161
0.172579
0
0.014474
0.273515
17,308
372
130
46.526882
0.783681
0.035475
0
0.19244
0
0
0.043093
0.004309
0
0
0
0
0
1
0.058419
false
0
0.041237
0.010309
0.158076
0.013746
0
0
0
null
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
null
0
0
0
0
0
0
0
0
0
0
0
0
1
0
810978ce9b3f6467c879457442fbbbac1342a8e8
3,065
py
Python
homeassistant/components/hunterdouglas_powerview/entity.py
pp81381/home-assistant
23e362faf387c1535be0abab81b30d8e4631df4b
[ "Apache-2.0" ]
null
null
null
homeassistant/components/hunterdouglas_powerview/entity.py
pp81381/home-assistant
23e362faf387c1535be0abab81b30d8e4631df4b
[ "Apache-2.0" ]
31
2020-07-23T07:13:38.000Z
2021-06-07T13:21:18.000Z
homeassistant/components/hunterdouglas_powerview/entity.py
pp81381/home-assistant
23e362faf387c1535be0abab81b30d8e4631df4b
[ "Apache-2.0" ]
null
null
null
"""The nexia integration base entity.""" from aiopvapi.resources.shade import ATTR_TYPE from homeassistant.const import ATTR_MODEL, ATTR_SW_VERSION import homeassistant.helpers.device_registry as dr from homeassistant.helpers.entity import DeviceInfo from homeassistant.helpers.update_coordinator import CoordinatorEntity from .const import ( DEVICE_FIRMWARE, DEVICE_MAC_ADDRESS, DEVICE_MODEL, DEVICE_NAME, DEVICE_SERIAL_NUMBER, DOMAIN, FIRMWARE, FIRMWARE_BUILD, FIRMWARE_REVISION, FIRMWARE_SUB_REVISION, MANUFACTURER, ) class HDEntity(CoordinatorEntity): """Base class for hunter douglas entities.""" def __init__(self, coordinator, device_info, room_name, unique_id): """Initialize the entity.""" super().__init__(coordinator) self._room_name = room_name self._unique_id = unique_id self._device_info = device_info @property def unique_id(self): """Return the unique id.""" return self._unique_id @property def device_info(self) -> DeviceInfo: """Return the device_info of the device.""" firmware = self._device_info[DEVICE_FIRMWARE] sw_version = f"{firmware[FIRMWARE_REVISION]}.{firmware[FIRMWARE_SUB_REVISION]}.{firmware[FIRMWARE_BUILD]}" return DeviceInfo( identifiers={(DOMAIN, self._device_info[DEVICE_SERIAL_NUMBER])}, connections={ (dr.CONNECTION_NETWORK_MAC, self._device_info[DEVICE_MAC_ADDRESS]) }, name=self._device_info[DEVICE_NAME], suggested_area=self._room_name, model=self._device_info[DEVICE_MODEL], sw_version=sw_version, manufacturer=MANUFACTURER, ) class ShadeEntity(HDEntity): """Base class for hunter douglas shade entities.""" def __init__(self, coordinator, device_info, room_name, shade, shade_name): """Initialize the shade.""" super().__init__(coordinator, device_info, room_name, shade.id) self._shade_name = shade_name self._shade = shade @property def device_info(self) -> DeviceInfo: """Return the device_info of the device.""" device_info = DeviceInfo( identifiers={(DOMAIN, self._shade.id)}, name=self._shade_name, suggested_area=self._room_name, manufacturer=MANUFACTURER, model=str(self._shade.raw_data[ATTR_TYPE]), via_device=(DOMAIN, self._device_info[DEVICE_SERIAL_NUMBER]), ) for shade in self._shade.shade_types: if shade.shade_type == device_info[ATTR_MODEL]: device_info[ATTR_MODEL] = shade.description break if FIRMWARE not in self._shade.raw_data: return device_info firmware = self._shade.raw_data[FIRMWARE] sw_version = f"{firmware[FIRMWARE_REVISION]}.{firmware[FIRMWARE_SUB_REVISION]}.{firmware[FIRMWARE_BUILD]}" device_info[ATTR_SW_VERSION] = sw_version return device_info
32.606383
114
0.669494
347
3,065
5.54755
0.210375
0.109091
0.050909
0.072727
0.326753
0.300779
0.25039
0.210909
0.210909
0.161039
0
0
0.239152
3,065
93
115
32.956989
0.825472
0.085808
0
0.19403
0
0
0.065194
0.065194
0
0
0
0
0
1
0.074627
false
0
0.089552
0
0.253731
0
0
0
0
null
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
null
0
0
0
0
0
0
0
0
0
0
0
0
1
0
810a3b9f5eeaf3e888067a624f744f48f465345b
9,244
py
Python
keycast_env/lib/python3.8/site-packages/Xlib/ext/res.py
daxter-army/key-cast
cadc88c6760839b37b7fef969294800d4c38fb1b
[ "MIT" ]
10
2021-09-15T16:29:59.000Z
2022-01-15T11:51:56.000Z
lib/Xlib/ext/res.py
ITZProGamerDieYT/SpeedrunningTimerLinux
4383c8fdfff476fdb81a99a1d6271218e6e9eee3
[ "CC-BY-3.0" ]
7
2021-09-16T06:21:44.000Z
2022-03-18T03:11:25.000Z
lib/Xlib/ext/res.py
ITZProGamerDieYT/SpeedrunningTimerLinux
4383c8fdfff476fdb81a99a1d6271218e6e9eee3
[ "CC-BY-3.0" ]
3
2021-09-20T13:08:43.000Z
2022-03-18T03:09:08.000Z
# Xlib.ext.res -- X-Resource extension module # # Copyright (C) 2021 Aleksei Bavshin <alebastr89@gmail.com> # # This library is free software; you can redistribute it and/or # modify it under the terms of the GNU Lesser General Public License # as published by the Free Software Foundation; either version 2.1 # of the License, or (at your option) any later version. # # This library is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. # See the GNU Lesser General Public License for more details. # # You should have received a copy of the GNU Lesser General Public # License along with this library; if not, write to the # Free Software Foundation, Inc., # 51 Franklin Street, # Fifth Floor, # Boston, MA 02110-1301 USA """X-Resource extension allows a client to query the X server about its usage of various resources. For detailed description see any of the following documents. Protocol specification: https://www.x.org/releases/current/doc/resourceproto/resproto.txt XCB Protocol specification: https://cgit.freedesktop.org/xcb/proto/tree/src/res.xml """ from Xlib.protocol import rq RES_MAJOR_VERSION = 1 RES_MINOR_VERSION = 2 extname = "X-Resource" # v1.0 ResQueryVersion = 0 ResQueryClients = 1 ResQueryClientResources = 2 ResQueryClientPixmapBytes = 3 # v1.2 ResQueryClientIds = 4 ResQueryResourceBytes = 5 class QueryVersion(rq.ReplyRequest): _request = rq.Struct( rq.Card8("opcode"), rq.Opcode(ResQueryVersion), rq.RequestLength(), rq.Card8("client_major"), rq.Card8("client_minor"), rq.Pad(2)) _reply = rq.Struct( rq.ReplyCode(), rq.Pad(1), rq.Card16("sequence_number"), rq.ReplyLength(), rq.Card16("server_major"), rq.Card16("server_minor"), rq.Pad(20)) def query_version(self, client_major=RES_MAJOR_VERSION, client_minor=RES_MINOR_VERSION): """ Query the protocol version supported by the X server. The client sends the highest supported version to the server and the server sends the highest version it supports, but no higher than the requested version.""" return QueryVersion( display=self.display, opcode=self.display.get_extension_major(extname), client_major=client_major, client_minor=client_minor) Client = rq.Struct( rq.Card32("resource_base"), rq.Card32("resource_mask")) class QueryClients(rq.ReplyRequest): _request = rq.Struct( rq.Card8("opcode"), rq.Opcode(ResQueryClients), rq.RequestLength()) _reply = rq.Struct( rq.ReplyCode(), rq.Pad(1), rq.Card16("sequence_number"), rq.ReplyLength(), rq.LengthOf("clients", 4), rq.Pad(20), rq.List("clients", Client)) def query_clients(self): """Request the list of all currently connected clients.""" return QueryClients( display=self.display, opcode=self.display.get_extension_major(extname)) Type = rq.Struct( rq.Card32("resource_type"), rq.Card32("count")) class QueryClientResources(rq.ReplyRequest): _request = rq.Struct( rq.Card8("opcode"), rq.Opcode(ResQueryClientResources), rq.RequestLength(), rq.Card32("client")) _reply = rq.Struct( rq.ReplyCode(), rq.Pad(1), rq.Card16("sequence_number"), rq.ReplyLength(), rq.LengthOf("types", 4), rq.Pad(20), rq.List("types", Type)) def query_client_resources(self, client): """Request the number of resources owned by a client. The server will return the counts of each type of resource. """ return QueryClientResources( display=self.display, opcode=self.display.get_extension_major(extname), client=client) class QueryClientPixmapBytes(rq.ReplyRequest): _request = rq.Struct( rq.Card8("opcode"), rq.Opcode(ResQueryClientPixmapBytes), rq.RequestLength(), rq.Card32("client")) _reply = rq.Struct( rq.ReplyCode(), rq.Pad(1), rq.Card16("sequence_number"), rq.ReplyLength(), rq.Card32("bytes"), rq.Card32("bytes_overflow"), rq.Pad(16)) def query_client_pixmap_bytes(self, client): """Query the pixmap usage of some client. The returned number is a sum of memory usage of each pixmap that can be attributed to the given client. """ return QueryClientPixmapBytes( display=self.display, opcode=self.display.get_extension_major(extname), client=client) class SizeOf(rq.LengthOf): """A SizeOf stores the size in bytes of some other Field whose size may vary, e.g. List """ def __init__(self, name, size, item_size): rq.LengthOf.__init__(self, name, size) self.item_size = item_size def parse_value(self, length, display): return length // self.item_size ClientXIDMask = 1 << 0 LocalClientPIDMask = 1 << 1 ClientIdSpec = rq.Struct( rq.Card32("client"), rq.Card32("mask")) ClientIdValue = rq.Struct( rq.Object("spec", ClientIdSpec), SizeOf("value", 4, 4), rq.List("value", rq.Card32Obj)) class QueryClientIds(rq.ReplyRequest): _request = rq.Struct( rq.Card8("opcode"), rq.Opcode(ResQueryClientIds), rq.RequestLength(), rq.LengthOf("specs", 4), rq.List("specs", ClientIdSpec)) _reply = rq.Struct( rq.ReplyCode(), rq.Pad(1), rq.Card16("sequence_number"), rq.ReplyLength(), rq.LengthOf("ids", 4), rq.Pad(20), rq.List("ids", ClientIdValue)) def query_client_ids(self, specs): """Request to identify a given set of clients with some identification method. The request sends a list of specifiers that select clients and identification methods to server. The server then tries to identify the chosen clients using the identification methods specified for each client. The server returns IDs for those clients that were successfully identified. """ return QueryClientIds( display=self.display, opcode=self.display.get_extension_major(extname), specs=specs) ResourceIdSpec = rq.Struct( rq.Card32("resource"), rq.Card32("type")) ResourceSizeSpec = rq.Struct( # inline struct ResourceIdSpec to work around # a parser bug with nested objects rq.Card32("resource"), rq.Card32("type"), rq.Card32("bytes"), rq.Card32("ref_count"), rq.Card32("use_count")) ResourceSizeValue = rq.Struct( rq.Object("size", ResourceSizeSpec), rq.LengthOf("cross_references", 4), rq.List("cross_references", ResourceSizeSpec)) class QueryResourceBytes(rq.ReplyRequest): _request = rq.Struct( rq.Card8("opcode"), rq.Opcode(ResQueryResourceBytes), rq.RequestLength(), rq.Card32("client"), rq.LengthOf("specs", 4), rq.List("specs", ResourceIdSpec)) _reply = rq.Struct( rq.ReplyCode(), rq.Pad(1), rq.Card16("sequence_number"), rq.ReplyLength(), rq.LengthOf("sizes", 4), rq.Pad(20), rq.List("sizes", ResourceSizeValue)) def query_resource_bytes(self, client, specs): """Query the sizes of resources from X server. The request sends a list of specifiers that selects resources for size calculation. The server tries to calculate the sizes of chosen resources and returns an estimate for a resource only if the size could be determined """ return QueryResourceBytes( display=self.display, opcode=self.display.get_extension_major(extname), client=client, specs=specs) def init(disp, info): disp.extension_add_method("display", "res_query_version", query_version) disp.extension_add_method("display", "res_query_clients", query_clients) disp.extension_add_method("display", "res_query_client_resources", query_client_resources) disp.extension_add_method("display", "res_query_client_pixmap_bytes", query_client_pixmap_bytes) disp.extension_add_method("display", "res_query_client_ids", query_client_ids) disp.extension_add_method("display", "res_query_resource_bytes", query_resource_bytes)
31.986159
83
0.609801
1,051
9,244
5.249286
0.253092
0.027551
0.032626
0.025014
0.344571
0.321914
0.295813
0.25358
0.217147
0.217147
0
0.019081
0.291324
9,244
288
84
32.097222
0.82308
0.268066
0
0.434286
0
0
0.095877
0.012478
0
0
0
0
0
1
0.051429
false
0
0.005714
0.005714
0.205714
0
0
0
0
null
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
null
0
0
0
0
0
0
0
0
0
0
0
0
1
0
810a45957301a3d3e19c056d8cdd8e9cf5349711
1,690
py
Python
rubra/cmdline_args.py
scwatts/rubra
0be2c1e8d56badf134954baab9705f3aeb38d426
[ "MIT" ]
14
2015-04-13T04:10:43.000Z
2022-03-28T08:42:43.000Z
rubra/cmdline_args.py
afcarl/rubra
82905bbbd7077d201363b96ffbbc78c099095764
[ "MIT" ]
3
2016-12-27T17:24:04.000Z
2018-12-21T17:43:36.000Z
rubra/cmdline_args.py
afcarl/rubra
82905bbbd7077d201363b96ffbbc78c099095764
[ "MIT" ]
9
2015-04-29T03:00:16.000Z
2020-01-30T00:56:52.000Z
# Process the unix command line of the pipeline. import argparse from version import rubra_version def get_cmdline_args(): return parser.parse_args() parser = argparse.ArgumentParser( description='A bioinformatics pipeline system.') parser.add_argument( 'pipeline', metavar='PIPELINE_FILE', type=str, help='Your Ruffus pipeline stages (a Python module)') parser.add_argument( '--config', metavar='CONFIG_FILE', type=str, nargs='+', required=True, help='One or more configuration files (Python modules)') parser.add_argument( '--verbose', type=int, choices=(0, 1, 2), required=False, default=1, help='Output verbosity level: 0 = quiet; 1 = normal; \ 2 = chatty (default is 1)') parser.add_argument( '--style', type=str, choices=('print', 'run', 'flowchart', 'touchfiles'), required=False, default='print', help='Pipeline behaviour: print; run; touchfiles; flowchart (default is print)') parser.add_argument( '--force', metavar='TASKNAME', type=str, required=False, default=[], nargs='+', help='tasks which are forced to be out of date regardless of timestamps') parser.add_argument( '--end', metavar='TASKNAME', type=str, required=False, help='end points (tasks) for the pipeline') parser.add_argument( '--rebuild', type=str, choices=('fromstart', 'fromend'), required=False, default='fromstart', help='rebuild outputs by working back from end tasks or forwards \ from start tasks (default is fromstart)') parser.add_argument( '--version', action='version', version='%(prog)s ' + rubra_version)
26.825397
84
0.657396
203
1,690
5.399015
0.463054
0.065693
0.124088
0.040146
0.063869
0.063869
0
0
0
0
0
0.005966
0.206509
1,690
62
85
27.258065
0.811335
0.027219
0
0.403509
0
0
0.289281
0
0
0
0
0
0
1
0.017544
false
0
0.035088
0.017544
0.070175
0.052632
0
0
0
null
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
null
0
0
0
0
0
0
0
0
0
0
0
0
1
0
810b6e9e54a3c45eed3b42ac6920a9d12535f63c
6,579
py
Python
PyTradier/data.py
zlopez101/PyTradier
83397cf38bd636c471993b57fb71a12885affcb7
[ "MIT" ]
1
2021-04-30T23:59:20.000Z
2021-04-30T23:59:20.000Z
PyTradier/data.py
zlopez101/PyTradier
83397cf38bd636c471993b57fb71a12885affcb7
[ "MIT" ]
7
2021-05-08T00:47:59.000Z
2021-05-12T01:45:37.000Z
PyTradier/data.py
zlopez101/PyTradier
83397cf38bd636c471993b57fb71a12885affcb7
[ "MIT" ]
null
null
null
from PyTradier.base import BasePyTradier from typing import Union from datetime import datetime class MarketData(BasePyTradier): """All Methods currently only support string API calls, no datetime, bools, etc """ def quotes(self, symbols: Union[str, list], greeks: bool = False) -> dict: """Get a list of symbols using a keyword lookup on the symbols description. Results are in descending order by average volume of the security. This can be used for simple search functions :param symbols: Comma-delimited list of symbols (equity or option) :type symbols: Union[str, list] :param greeks: Add greeks and volatility information (option only), defaults to False :type greeks: bool, optional :return: quotes for requested symbols :rtype: dict """ symbols = self._symbol_prep(symbols) return self._get( "/v1/markets/quotes", params=self.create_params(locals()), dict_args=("quotes", "quotes"), ) def option_chain( self, symbol: str, expiration: Union[str, datetime], greeks: Union[str, bool] = "false", ) -> dict: """Get all quotes in an option chain. Greek and IV data is included courtesy of ORATS. Please check out their APIs for more in-depth options data. :param symbol: Underlying symbol of the chain :type symbol: str :param expiration: Expiration for the chain :type expiration: Union[str, datetime] :param greeks: Add greeks and volatility information, defaults to "false" :type greeks: Union[str, bool], optional :return: Get all quotes in an option chain :rtype: dict """ return self._get( "/v1/markets/options/chains", params=self.create_params(locals()), dict_args=("options", "option"), ) def option_strike(self, symbol: str, expiration: Union[str, datetime]) -> list: """Get an options strike prices for a specified expiration date. :param symbol: Underlying symbol of the chain :type symbol: str :param expiration: Expiration for the chain :type expiration: Union[str, datetime] :return: [description] :rtype: list """ return self._get( "/v1/markets/options/strikes", params=self.create_params(locals()) ) def option_lookup(self, underlying: str) -> dict: """Get all options symbols for the given underlying. This will include additional option roots (ex. SPXW, RUTW) if applicable. :param underlying: Underlying symbol of the chain :type underlying: str :return: dict {"rootSymbol": underlying, "options": [list of option symbols]} :rtype: dict """ return self._get( "/v1/markets/options/lookup", params=self.create_params(locals()) ) def option_expirations( self, symbol: str, includeAllRoots: Union[str, bool] = "", strikes: Union[str, bool] = "", ) -> list: """Get expiration dates for a particular underlying. Note that some underlying securities use a different symbol for their weekly options (RUT/RUTW, SPX/SPXW). To make sure you see all expirations, make sure to send the includeAllRoots parameter. This will also ensure any unique options due to corporate actions (AAPL1) are returned. :param symbol: Underlying symbol of the chain :type symbol: str :param includeAllRoots: Send expirations related to all option roots, defaults to '' :type includeAllRoots: Union[str, bool], optional :param strikes: Add strike prices to each expiration, defaults to '' :type strikes: Union[str, bool], optional :return: list of expiration dates as str %Y-%m-%d :rtype: list """ response = self._get( "/v1/markets/options/expirations", params=self.create_params(locals()) ) return response def historic_quotes( self, symbol: str, interval: str = "daily", start: str = None, end: str = None ) -> list: """Get historical pricing for a security. This data will usually cover the entire lifetime of the company if sending reasonable start/end times. You can fetch historical pricing for options by passing the OCC option symbol (ex. AAPL220617C00270000) as the symbol. :param symbol: Symbol to query :type symbol: str :param interval: Interval of time per timesale. One of: daily, weekly, monthly, defaults to "daily" :type interval: str, optional :param start: Start date represented as YYYY-MM-DD, defaults to None :type start: str, optional :param end: End date represented as YYYY-MM-DD, defaults to None :type end: str, optional :return: [description] :rtype: list """ return self._get( "/v1/markets/history", params=self.create_params(locals()), dict_args=("history", "day"), ) def time_and_sales( self, symbol: str, start: str, end: str, interval: str = "1min" ) -> list: """Time and Sales (timesales) is typically used for charting purposes. It captures pricing across a time slice at predefined intervals. Tick data is also available through this endpoint. This results in a very large data set for high-volume symbols, so the time slice needs to be much smaller to keep downloads time reasonable.` :param symbol: A single security symbol. :type symbol: str :param start: Start date/time for timesales range represented as YYYY-MM-DD HH:MM :type start: str :param end: Start date/time for timesales range represented as YYYY-MM-DD HH:MM :type end: str :param interval: Interval of time per timesale. One of: tick, 1min, 5min, 15min, defaults to "1min" :type interval: str, optional :return: list of dictionaries containing keys of ['time', 'timestamp', 'price', 'open', 'high', 'close', low', 'volume', 'vwap'] :rtype: list """ return self._get( "/v1/markets/timesales", params=self.create_params(locals()), dict_args=("series", "data"), ) if __name__ == "__main__": from utils import printer data = MarketData() symbol = "AAPL" response = data.option_lookup(symbol) # response = data.option_strike(symbol, dates[0]) printer(response)
42.173077
289
0.637635
815
6,579
5.10184
0.28589
0.023088
0.015152
0.026936
0.345358
0.303271
0.294372
0.181578
0.1633
0.140212
0
0.006038
0.26995
6,579
155
290
42.445161
0.859671
0.577899
0
0.274194
0
0
0.106649
0.058456
0
0
0
0
0
1
0.112903
false
0
0.064516
0
0.306452
0.032258
0
0
0
null
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
null
0
0
0
0
0
0
0
0
0
0
0
0
1
0
810c05c71eb3fa5c73eabbeb8e2c1122faa7ac10
3,528
py
Python
joulescope_ui/meter_widget.py
Axel-Jacobsen/pyjoulescope_ui
7d296b1ead0d36c6524dc399372f7888a340e9fa
[ "Apache-2.0" ]
1
2019-08-08T21:10:26.000Z
2019-08-08T21:10:26.000Z
joulescope_ui/meter_widget.py
Axel-Jacobsen/pyjoulescope_ui
7d296b1ead0d36c6524dc399372f7888a340e9fa
[ "Apache-2.0" ]
null
null
null
joulescope_ui/meter_widget.py
Axel-Jacobsen/pyjoulescope_ui
7d296b1ead0d36c6524dc399372f7888a340e9fa
[ "Apache-2.0" ]
null
null
null
# Copyright 2018 Jetperch LLC # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. from PySide2 import QtCore, QtWidgets from . import joulescope_rc from .meter_value_widget import MeterValueWidget import logging log = logging.getLogger(__name__) FIELDS = [ ('current', 'A', 'Amps'), ('voltage', 'V', 'Volts'), ('power', 'W', 'Watts'), ('energy', 'J', 'Joules'), ] class MeterWidget(QtWidgets.QWidget): def __init__(self, *args, **kwargs): QtWidgets.QWidget.__init__(self, *args, **kwargs) self.verticalLayout = QtWidgets.QVBoxLayout(self) self.verticalLayout.setObjectName("verticalLayout") self.verticalLayout.setSpacing(0) self.controlWidget = QtWidgets.QWidget(self) self.controlLayout = QtWidgets.QHBoxLayout(self.controlWidget) self.verticalLayout.addWidget(self.controlWidget) self.accumulateButton = QtWidgets.QPushButton(self.controlWidget) self.accumulateButton.setCheckable(True) self.accumulateButton.setObjectName("accumulateButton") self.controlLayout.addWidget(self.accumulateButton) self.accumulateButton.toggled.connect(self.on_accumulate_toggled) self.controlSpacer = QtWidgets.QSpacerItem(40, 20, QtWidgets.QSizePolicy.Expanding, QtWidgets.QSizePolicy.Minimum) self.controlLayout.addItem(self.controlSpacer) self.values = {} for name, units_short, units_long in FIELDS: w = MeterValueWidget(self) w.setStyleSheet("QWidget { background-color : black; color : green; }") w.configure(name.capitalize(), units_short, units_long) self.values[name] = w w.setContentsMargins(0, 0, 0, 0) self.verticalLayout.addWidget(w) self.values['energy'].configure_energy() self.sizePolicy = QtWidgets.QSizePolicy(QtWidgets.QSizePolicy.Expanding, QtWidgets.QSizePolicy.Expanding) self.sizePolicy.setHorizontalStretch(0) self.sizePolicy.setVerticalStretch(0) self.setSizePolicy(self.sizePolicy) self.retranslateUi() @QtCore.Slot(bool) def on_accumulate_toggled(self, checked): self.values['current'].accumulate_enable = checked self.values['voltage'].accumulate_enable = checked self.values['power'].accumulate_enable = checked def update(self, statistics): """Update the multimeter display :param statistics: The statistics data structure """ for name, field in statistics['signals'].items(): d = field['statistics'] self.values[name].update_value(mean=d['μ'], variance=d['σ2'], v_min=d['min'], v_max=d['max']) energy = statistics['accumulators']['energy']['value'] charge = statistics['accumulators']['charge']['value'] self.values['energy'].update_energy(energy, charge) def retranslateUi(self): _translate = QtCore.QCoreApplication.translate self.accumulateButton.setText(_translate("meter_widget", "Accumulate"))
40.090909
122
0.693311
385
3,528
6.264935
0.425974
0.033168
0.026119
0.013267
0.067993
0
0
0
0
0
0
0.007379
0.193311
3,528
87
123
40.551724
0.840126
0.178571
0
0
0
0
0.089417
0
0
0
0
0
0
1
0.071429
false
0
0.071429
0
0.160714
0
0
0
0
null
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
null
0
0
0
0
0
0
0
0
0
0
0
0
1
0
810c343fb0a1f912fe6668116ca4d1081009f872
7,677
py
Python
rpyc/core/service.py
bbonf/rpyc
2c66dd6936a0d9e6e36c1ba0cda1139676acf95c
[ "MIT" ]
null
null
null
rpyc/core/service.py
bbonf/rpyc
2c66dd6936a0d9e6e36c1ba0cda1139676acf95c
[ "MIT" ]
null
null
null
rpyc/core/service.py
bbonf/rpyc
2c66dd6936a0d9e6e36c1ba0cda1139676acf95c
[ "MIT" ]
null
null
null
""" Services are the heart of RPyC: each side of the connection exposes a *service*, which define the capabilities available to the other side. Note that the services by both parties need not be symmetric, e.g., one side may exposed *service A*, while the other may expose *service B*. As long as the two can interoperate, you're good to go. """ from functools import partial from rpyc.lib import hybridmethod from rpyc.lib.compat import execute, is_py3k from rpyc.core.protocol import Connection class Service(object): """The service base-class. Derive from this class to implement custom RPyC services: * The name of the class implementing the ``Foo`` service should match the pattern ``FooService`` (suffixed by the word 'Service') :: class FooService(Service): pass FooService.get_service_name() # 'FOO' FooService.get_service_aliases() # ['FOO'] * To supply a different name or aliases, use the ``ALIASES`` class attribute :: class Foobar(Service): ALIASES = ["foo", "bar", "lalaland"] Foobar.get_service_name() # 'FOO' Foobar.get_service_aliases() # ['FOO', 'BAR', 'LALALAND'] * Override :func:`on_connect` to perform custom initialization * Override :func:`on_disconnect` to perform custom finalization * To add exposed methods or attributes, simply define them normally, but prefix their name by ``exposed_``, e.g. :: class FooService(Service): def exposed_add(self, x, y): return x + y * All other names (not prefixed by ``exposed_``) are local (not accessible to the other party) .. note:: You can override ``_rpyc_getattr``, ``_rpyc_setattr`` and ``_rpyc_delattr`` to change attribute lookup -- but beware of possible **security implications!** """ __slots__ = () ALIASES = () _protocol = Connection def on_connect(self, conn): """called when the connection is established""" pass def on_disconnect(self, conn): """called when the connection had already terminated for cleanup (must not perform any IO on the connection)""" pass # Using default defined in 'protocol.Connection._access_attr' for: # def _rpyc_getattr(self, name): def _rpyc_delattr(self, name): raise AttributeError("access denied") def _rpyc_setattr(self, name, value): raise AttributeError("access denied") @classmethod def get_service_aliases(cls): """returns a list of the aliases of this service""" if cls.ALIASES: return tuple(str(n).upper() for n in cls.ALIASES) name = cls.__name__.upper() if name.endswith("SERVICE"): name = name[:-7] return (name,) @classmethod def get_service_name(cls): """returns the canonical name of the service (which is its first alias)""" return cls.get_service_aliases()[0] exposed_get_service_aliases = get_service_aliases exposed_get_service_name = get_service_name @hybridmethod def _connect(self, channel, config={}): """Setup a connection via the given channel.""" if isinstance(self, type): # autovivify if accessed as class method self = self() # Note that we are here passing in `self` as root object for backward # compatibility and convenience. You could pass in a different root if # you wanted: conn = self._protocol(self, channel, config) self.on_connect(conn) return conn class VoidService(Service): """void service - an do-nothing service""" __slots__ = () class ModuleNamespace(object): """used by the :class:`SlaveService` to implement the magical 'module namespace'""" __slots__ = ["__getmodule", "__cache", "__weakref__"] def __init__(self, getmodule): self.__getmodule = getmodule self.__cache = {} def __contains__(self, name): try: self[name] except ImportError: return False else: return True def __getitem__(self, name): if type(name) is tuple: name = ".".join(name) if name not in self.__cache: self.__cache[name] = self.__getmodule(name) return self.__cache[name] def __getattr__(self, name): return self[name] class Slave(object): __slots__ = ["_conn", "namespace"] def __init__(self): self._conn = None self.namespace = {} def execute(self, text): """execute arbitrary code (using ``exec``)""" execute(text, self.namespace) def eval(self, text): """evaluate arbitrary code (using ``eval``)""" return eval(text, self.namespace) def getmodule(self, name): """imports an arbitrary module""" return __import__(name, None, None, "*") def getconn(self): """returns the local connection instance to the other side""" return self._conn class SlaveService(Slave, Service): """The SlaveService allows the other side to perform arbitrary imports and execution arbitrary code on the server. This is provided for compatibility with the classic RPyC (2.6) modus operandi. This service is very useful in local, secure networks, but it exposes a **major security risk** otherwise.""" __slots__ = () def on_connect(self, conn): self._conn = conn self._conn._config.update(dict( allow_all_attrs = True, allow_pickle = True, allow_getattr = True, allow_setattr = True, allow_delattr = True, allow_exposed_attrs = False, import_custom_exceptions = True, instantiate_custom_exceptions = True, instantiate_oldstyle_exceptions = True, )) super(SlaveService, self).on_connect(conn) class FakeSlaveService(VoidService): """VoidService that can be used for connecting to peers that operate a :class:`MasterService`, :class:`ClassicService`, or the old ``SlaveService`` (pre v3.5) without exposing any functionality to them.""" __slots__ = () exposed_namespace = None exposed_execute = None exposed_eval = None exposed_getmodule = None exposed_getconn = None class MasterService(Service): """Peer for a new-style (>=v3.5) :class:`SlaveService`. Use this service if you want to connect to a ``SlaveService`` without exposing any functionality to them.""" __slots__ = () def on_connect(self, conn): super(MasterService, self).on_connect(conn) self._install(conn, conn.root) @staticmethod def _install(conn, slave): modules = ModuleNamespace(slave.getmodule) builtin = modules.builtins if is_py3k else modules.__builtin__ conn.modules = modules conn.eval = slave.eval conn.execute = slave.execute conn.namespace = slave.namespace conn.builtin = builtin conn.builtins = builtin from rpyc.utils.classic import teleport_function conn.teleport = partial(teleport_function, conn) class ClassicService(MasterService, SlaveService): """Full duplex master/slave service, i.e. both parties have full control over the other. Must be used by both parties.""" __slots__ = () class ClassicClient(MasterService, FakeSlaveService): """MasterService that can be used for connecting to peers that operate a :class:`MasterService`, :class:`ClassicService` without exposing any functionality to them.""" __slots__ = ()
34.426009
86
0.64804
917
7,677
5.237732
0.2988
0.022902
0.021237
0.009994
0.096814
0.082657
0.060379
0.034145
0.034145
0.034145
0
0.001753
0.256871
7,677
222
87
34.581081
0.84014
0.441188
0
0.13913
0
0
0.019369
0
0
0
0
0
0
1
0.165217
false
0.017391
0.069565
0.008696
0.565217
0
0
0
0
null
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
null
0
0
0
0
0
0
0
0
0
0
0
0
1
0
810e20d4bc8d21dc6f3aae023a1133ca2d856392
1,218
py
Python
test/workload/tpch_loop_workload_test.py
ChenYi015/Raven
e732e03f8dd118ed805a143fc6916f0e5fc53c2c
[ "Apache-2.0" ]
1
2022-03-03T05:54:25.000Z
2022-03-03T05:54:25.000Z
test/workload/tpch_loop_workload_test.py
ChenYi015/Raven
e732e03f8dd118ed805a143fc6916f0e5fc53c2c
[ "Apache-2.0" ]
null
null
null
test/workload/tpch_loop_workload_test.py
ChenYi015/Raven
e732e03f8dd118ed805a143fc6916f0e5fc53c2c
[ "Apache-2.0" ]
null
null
null
# Copyright 2021 Raven Authors. All rights reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. from queue import Queue from threading import Thread from benchmark.workload.tpch import TpchLoopWorkload def print_queries(queue: Queue): while True: query = queue.get() print(query) if __name__ == '__main__': workload = TpchLoopWorkload() print(workload) queue = Queue() generate_thread = Thread( target=workload.generate_one_loop_queries, args=(queue,), name='QueryGenerator' ) generate_thread.start() print_thread = Thread( target=print_queries, args=(queue,), name='QueryPrinter' ) print_thread.start()
26.478261
74
0.705255
157
1,218
5.363057
0.592357
0.071259
0.030879
0.038005
0
0
0
0
0
0
0
0.008359
0.214286
1,218
45
75
27.066667
0.871473
0.46798
0
0.086957
0
0
0.053628
0
0
0
0
0
0
1
0.043478
false
0
0.130435
0
0.173913
0.26087
0
0
0
null
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
null
0
0
0
0
0
0
0
0
0
0
0
0
1
0
8111119b844622ccdb3004ede98c4e13a46f452c
398
py
Python
api/tests/ver1/test_base.py
codacy-badger/politico-api
10d926bf34f12631cb19bb9c82ccded36557c790
[ "MIT" ]
null
null
null
api/tests/ver1/test_base.py
codacy-badger/politico-api
10d926bf34f12631cb19bb9c82ccded36557c790
[ "MIT" ]
null
null
null
api/tests/ver1/test_base.py
codacy-badger/politico-api
10d926bf34f12631cb19bb9c82ccded36557c790
[ "MIT" ]
null
null
null
import unittest from api import create_app class TestBase(unittest.TestCase): """Default super class for api ver 1 tests""" # setup testing def setUp(self): self.app = create_app('testing') self.client = self.app.test_client() self.item_list = [] # deconstructs test elements def tearDown(self): self.app = None self.item_list.clear()
23.411765
49
0.640704
51
398
4.901961
0.54902
0.084
0.088
0
0
0
0
0
0
0
0
0.00339
0.258794
398
16
50
24.875
0.844068
0.203518
0
0
0
0
0.022581
0
0
0
0
0
0
1
0.2
false
0
0.2
0
0.5
0
0
0
0
null
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
null
0
0
0
0
0
0
0
0
0
0
0
0
1
0
81118158b2fe646b1e3b2899f2e0b74a521117c9
3,234
py
Python
alipay/aop/api/domain/MetroOdItem.py
antopen/alipay-sdk-python-all
8e51c54409b9452f8d46c7bb10eea7c8f7e8d30c
[ "Apache-2.0" ]
213
2018-08-27T16:49:32.000Z
2021-12-29T04:34:12.000Z
alipay/aop/api/domain/MetroOdItem.py
antopen/alipay-sdk-python-all
8e51c54409b9452f8d46c7bb10eea7c8f7e8d30c
[ "Apache-2.0" ]
29
2018-09-29T06:43:00.000Z
2021-09-02T03:27:32.000Z
alipay/aop/api/domain/MetroOdItem.py
antopen/alipay-sdk-python-all
8e51c54409b9452f8d46c7bb10eea7c8f7e8d30c
[ "Apache-2.0" ]
59
2018-08-27T16:59:26.000Z
2022-03-25T10:08:15.000Z
#!/usr/bin/env python # -*- coding: utf-8 -*- import json from alipay.aop.api.constant.ParamConstants import * from alipay.aop.api.domain.CloudbusUserInfo import CloudbusUserInfo class MetroOdItem(object): def __init__(self): self._dest_geo = None self._od = None self._time = None self._user_info = None self._week_od = None self._work_od = None @property def dest_geo(self): return self._dest_geo @dest_geo.setter def dest_geo(self, value): self._dest_geo = value @property def od(self): return self._od @od.setter def od(self, value): self._od = value @property def time(self): return self._time @time.setter def time(self, value): self._time = value @property def user_info(self): return self._user_info @user_info.setter def user_info(self, value): if isinstance(value, CloudbusUserInfo): self._user_info = value else: self._user_info = CloudbusUserInfo.from_alipay_dict(value) @property def week_od(self): return self._week_od @week_od.setter def week_od(self, value): self._week_od = value @property def work_od(self): return self._work_od @work_od.setter def work_od(self, value): self._work_od = value def to_alipay_dict(self): params = dict() if self.dest_geo: if hasattr(self.dest_geo, 'to_alipay_dict'): params['dest_geo'] = self.dest_geo.to_alipay_dict() else: params['dest_geo'] = self.dest_geo if self.od: if hasattr(self.od, 'to_alipay_dict'): params['od'] = self.od.to_alipay_dict() else: params['od'] = self.od if self.time: if hasattr(self.time, 'to_alipay_dict'): params['time'] = self.time.to_alipay_dict() else: params['time'] = self.time if self.user_info: if hasattr(self.user_info, 'to_alipay_dict'): params['user_info'] = self.user_info.to_alipay_dict() else: params['user_info'] = self.user_info if self.week_od: if hasattr(self.week_od, 'to_alipay_dict'): params['week_od'] = self.week_od.to_alipay_dict() else: params['week_od'] = self.week_od if self.work_od: if hasattr(self.work_od, 'to_alipay_dict'): params['work_od'] = self.work_od.to_alipay_dict() else: params['work_od'] = self.work_od return params @staticmethod def from_alipay_dict(d): if not d: return None o = MetroOdItem() if 'dest_geo' in d: o.dest_geo = d['dest_geo'] if 'od' in d: o.od = d['od'] if 'time' in d: o.time = d['time'] if 'user_info' in d: o.user_info = d['user_info'] if 'week_od' in d: o.week_od = d['week_od'] if 'work_od' in d: o.work_od = d['work_od'] return o
26.95
70
0.548856
421
3,234
3.945368
0.114014
0.077062
0.093919
0.065021
0.267911
0.216135
0
0
0
0
0
0.000471
0.343847
3,234
119
71
27.176471
0.782281
0.012987
0
0.128713
0
0
0.072773
0
0
0
0
0
0
1
0.148515
false
0
0.029703
0.059406
0.277228
0
0
0
0
null
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
null
0
0
0
0
0
0
0
0
0
0
0
0
1
0
811909fd3d9bc00f5888c3293282a4df3cefdd8c
14,970
py
Python
extras/python/fogbench/__main__.py
foglamp/FogLAMP
918dff88b440e6ad580efdaa5f0fbdf4143a73d4
[ "Apache-2.0" ]
65
2017-05-15T21:55:04.000Z
2022-01-19T01:30:42.000Z
extras/python/fogbench/__main__.py
foglamp/FogLAMP
918dff88b440e6ad580efdaa5f0fbdf4143a73d4
[ "Apache-2.0" ]
576
2017-05-22T05:41:07.000Z
2020-02-13T07:48:58.000Z
extras/python/fogbench/__main__.py
foglamp/FogLAMP
918dff88b440e6ad580efdaa5f0fbdf4143a73d4
[ "Apache-2.0" ]
52
2017-05-09T22:45:47.000Z
2022-03-10T18:49:02.000Z
#!/usr/bin/env python3 # -*- coding: utf-8 -*- # FOGLAMP_BEGIN # See: http://foglamp.readthedocs.io/ # FOGLAMP_END """ fogbench -- a Python script used to test FogLAMP. The objective is to simulate payloads for input, REST and other requests against one or more FogLAMP instances. This version of fogbench is meant to test the CoAP and HTTP plugins interface of FogLAMP southbound services. fogbench [IN] -h --help Print this help -i --interval The interval in seconds between each iteration (default: 0) [IN] -k --keep Do not delete (keep) the running sample (default: no) [IN] -o --output Set the output file for statistics [IN] -p --payload Type of payload and protocol (default: coap) [IN] -t --template Set the template to use [IN] -v --version Display the version and exit [IN] -H --host The FogLAMP host (default: localhost) -I --iterations The number of iterations of the test (default: 1) [IN] -O --occurrences The number of occurrences of the template (default: 1) [IN] -P --port The FogLAMP port. Default depends on payload and protocol [IN] -S --statistic The type of statistics to collect Example: $ cd $FOGLAMP_ROOT/bin $ ./fogbench Help: $ ./fogbench -h * Create reading objects from given template, as per the json file name specified with -t * Save those objects to the file, as per the file name specified with -o * Read those objects * Send those to CoAP or HTTP south plugin server, on specific host and port .. todo:: * Try generators """ import sys import os import random import json from datetime import datetime, timezone import argparse import collections import asyncio import aiohttp from .exceptions import * __author__ = "Praveen Garg" __copyright__ = "Copyright (c) 2017 OSIsoft, LLC" __license__ = "Apache 2.0" __version__ = "${VERSION}" _FOGBENCH_VERSION = u"0.1.1" _start_time = [] _end_time = [] _tot_msgs_transferred = [] _tot_byte_transferred = [] _num_iterated = 0 """Statistics to be collected""" # _logger = logger.setup(__name__) def local_timestamp(): """ :return: str - current time stamp with microseconds and machine timezone info :example '2018-05-08 14:06:40.517313+05:30' """ return str(datetime.now(timezone.utc).astimezone()) def read_templates(): templates = [] return templates def parse_template_and_prepare_json(_template_file, _write_to_file=None, _occurrences=1): # template_file = os.path.join(os.path.dirname(__file__), "templates/" + _template_file) with open(_template_file) as data_file: data = json.load(data_file) supported_format_types = ["number", "enum"] for _ in range(_occurrences): readings_ = _prepare_sensor_reading(data, supported_format_types) for r in readings_: _write_readings_to_file(_write_to_file, r) def _write_readings_to_file(to_file, r): with open(to_file, 'a') as the_file: json.dump(r, the_file) the_file.write(os.linesep) def _prepare_sensor_reading(data, supported_format_types): readings = [] for d in data: x_sensor_values = dict() _sensor_value_object_formats = d["sensor_values"] for fmt in _sensor_value_object_formats: if fmt["type"] not in supported_format_types: raise InvalidSensorValueObjectTemplateFormat(u"Invalid format, " u"Can not parse type {}".format(fmt["type"])) if fmt["type"] == "number": # check float precision if any precision = fmt.get("precision", None) min_val = fmt.get("min", None) max_val = fmt.get("max", None) if min_val is None or max_val is None: raise InvalidSensorValueObjectTemplateFormat(u"Invalid format, " u"Min and Max values must be defined for type number.") # print(precision) # print(min_val) # print(max_val) reading = round(random.uniform(min_val, max_val), precision) elif fmt["type"] == "enum": reading = random.choice(fmt["list"]) # print(fmt["name"], reading) x_sensor_values[fmt["name"]] = reading # print(d["name"]) sensor_value_object = dict() sensor_value_object["asset"] = d['name'] sensor_value_object["readings"] = x_sensor_values sensor_value_object["timestamp"] = "{!s}".format(local_timestamp()) # print(json.dumps(sensor_value_object)) ord_dict = collections.OrderedDict(sorted(sensor_value_object.items())) readings.append(ord_dict) return readings def read_out_file(_file=None, _keep=False, _iterations=1, _interval=0, send_to='coap'): global _start_time global _end_time global _tot_msgs_transferred global _tot_byte_transferred global _num_iterated # from pprint import pprint import time # _file = os.path.join(os.path.dirname(__file__), "out/{}".format(outfile)) with open(_file) as f: readings_list = [json.loads(line) for line in f] loop = asyncio.get_event_loop() while _iterations > 0: # Pre-calculate the messages and size msg_transferred_itr = 0 # Messages transferred in every iteration byte_transferred_itr = 0 # Bytes transferred in every iteration for r in readings_list: msg_transferred_itr += 1 byte_transferred_itr += sys.getsizeof(r) if send_to == 'coap': _start_time.append(datetime.now()) for r in readings_list: is_sent = loop.run_until_complete(send_to_coap(r)) if not is_sent: break elif send_to == 'http': _start_time.append(datetime.now()) loop.run_until_complete(send_to_http(readings_list)) _end_time.append(datetime.now()) # End time of every iteration _tot_msgs_transferred.append(msg_transferred_itr) _tot_byte_transferred.append(byte_transferred_itr) _iterations -= 1 _num_iterated += 1 if _iterations != 0: # print(u"Iteration {} completed, waiting for {} seconds".format(_iterations, _interval)) time.sleep(_interval) if not _keep: os.remove(_file) async def send_to_coap(payload): """ POST request to: localhost port 5683 (official IANA assigned CoAP port), URI "/other/sensor-values". """ from aiocoap import Context, Message from aiocoap.numbers.codes import Code from cbor2 import dumps context = await Context.create_client_context() request = Message(payload=dumps(payload), code=Code.POST) request.opt.uri_host = arg_host request.opt.uri_port = arg_port request.opt.uri_path = ("other", "sensor-values") response = await context.request(request).response str_res = str(response.code) status_code = str_res[:4] # or str_res.split()[0] if status_code == "4.00" or status_code == "5.00": print("Error: ", str_res) return False return True async def send_to_http(payload): """ POST request to: host localhost port 6683 (default HTTP south plugin port), uri sensor-reading """ headers = {'content-type': 'application/json'} url = 'http://{}:{}/sensor-reading'.format(arg_host, arg_port) async with aiohttp.ClientSession() as session: async with session.post(url, data=json.dumps(payload), headers=headers) as resp: await resp.text() status_code = resp.status if status_code in range(400, 500): print("Bad request error | code:{}, reason: {}".format(status_code, resp.reason)) return False if status_code in range(500, 600): print("Server error | code:{}, reason: {}".format(status_code, resp.reason)) return False return True def get_statistics(_stats_type=None, _out_file=None): stat = '' global _start_time global _end_time global _tot_msgs_transferred global _tot_byte_transferred global _num_iterated if _stats_type == 'total': stat += u"Total Statistics:\n" stat += (u"\nStart Time: {}".format(datetime.strftime(_start_time[0], "%Y-%m-%d %H:%M:%S.%f"))) stat += (u"\nEnd Time: {}\n".format(datetime.strftime(_end_time[-1], "%Y-%m-%d %H:%M:%S.%f"))) stat += (u"\nTotal Messages Transferred: {}".format(sum(_tot_msgs_transferred))) stat += (u"\nTotal Bytes Transferred: {}\n".format(sum(_tot_byte_transferred))) stat += (u"\nTotal Iterations: {}".format(_num_iterated)) stat += (u"\nTotal Messages per Iteration: {}".format(sum(_tot_msgs_transferred)/_num_iterated)) stat += (u"\nTotal Bytes per Iteration: {}\n".format(sum(_tot_byte_transferred)/_num_iterated)) _msg_rate = [] _byte_rate = [] for itr in range(_num_iterated): time_taken = _end_time[itr] - _start_time[itr] _msg_rate.append(_tot_msgs_transferred[itr]/(time_taken.seconds+time_taken.microseconds/1E6)) _byte_rate.append(_tot_byte_transferred[itr] / (time_taken.seconds+time_taken.microseconds/1E6)) stat += (u"\nMin messages/second: {}".format(min(_msg_rate))) stat += (u"\nMax messages/second: {}".format(max(_msg_rate))) stat += (u"\nAvg messages/second: {}\n".format(sum(_msg_rate)/_num_iterated)) stat += (u"\nMin Bytes/second: {}".format(min(_byte_rate))) stat += (u"\nMax Bytes/second: {}".format(max(_byte_rate))) stat += (u"\nAvg Bytes/second: {}".format(sum(_byte_rate)/_num_iterated)) if _out_file: with open(_out_file, 'w') as f: f.write(stat) else: print(stat) # should we also show total time diff? end_time - start_time def check_server(payload_type='coap'): template_str = ">>> Make sure south {} plugin service is running \n & listening on specified host and port \n" if payload_type == 'coap': print(template_str.format("CoAP")) elif payload_type == 'http': print(template_str.format("HTTP")) parser = argparse.ArgumentParser(prog='fogbench') parser.description = '%(prog)s -- a Python script used to test FogLAMP (simulate payloads)' parser.epilog = 'The initial version of %(prog)s is meant to test the south plugin interface of ' \ 'FogLAMP using CoAP or HTTP' parser.add_argument('-v', '--version', action='version', version='%(prog)s {0!s}'.format(_FOGBENCH_VERSION)) parser.add_argument('-k', '--keep', default=False, choices=['y', 'yes', 'n', 'no'], help='Do not delete the running sample (default: no)') parser.add_argument('-t', '--template', required=True, help='Set the template file, json extension') parser.add_argument('-o', '--output', default=None, help='Set the statistics output file') parser.add_argument('-p', '--payload', default='coap', choices=['coap', 'http'], help='Type of payload ' 'and protocol (default: coap)') parser.add_argument('-I', '--iterations', help='The number of iterations of the test (default: 1)') parser.add_argument('-O', '--occurrences', help='The number of occurrences of the template (default: 1)') parser.add_argument('-H', '--host', help='Server host address (default: localhost)') parser.add_argument('-P', '--port', help='The FogLAMP port. (default: 5683)') parser.add_argument('-i', '--interval', default=0, help='The interval in seconds for each iteration (default: 0)') parser.add_argument('-S', '--statistics', default='total', choices=['total'], help='The type of statistics to collect ' '(default: total)') namespace = parser.parse_args(sys.argv[1:]) infile = '{0}'.format(namespace.template if namespace.template else '') statistics_file = os.path.join(os.path.dirname(__file__), "out/{}".format(namespace.output)) if namespace.output else None keep_the_file = True if namespace.keep in ['y', 'yes'] else False # iterations and occurrences arg_iterations = int(namespace.iterations) if namespace.iterations else 1 arg_occurrences = int(namespace.occurrences) if namespace.occurrences else 1 # interval between each iteration arg_interval = int(namespace.interval) if namespace.interval else 0 arg_stats_type = '{0}'.format(namespace.statistics) if namespace.statistics else 'total' if namespace.payload: arg_payload_protocol = namespace.payload arg_host = '{0}'.format(namespace.host) if namespace.host else 'localhost' default_port = 6683 if arg_payload_protocol == 'http' else 5683 arg_port = int(namespace.port) if namespace.port else default_port check_server(arg_payload_protocol) sample_file = os.path.join("/tmp", "foglamp_running_sample.{}".format(os.getpid())) parse_template_and_prepare_json(_template_file=infile, _write_to_file=sample_file, _occurrences=arg_occurrences) read_out_file(_file=sample_file, _keep=keep_the_file, _iterations=arg_iterations, _interval=arg_interval, send_to=arg_payload_protocol) get_statistics(_stats_type=arg_stats_type, _out_file=statistics_file) # TODO: Change below per local_timestamp() values """ Expected output from given template { "timestamp" : "2017-08-04T06:59:57.503Z", "asset" : "TI sensorTag/luxometer", "sensor_values" : { "lux" : 49 } } { "timestamp" : "2017-08-04T06:59:57.863Z", "asset" : "TI sensorTag/pressure", "sensor_values" : { "pressure" : 1021.2 } } { "timestamp" : "2017-08-04T06:59:58.863Z", "asset" : "TI sensorTag/humidity", "sensor_values" : { "humidity" : 71.2, "temperature" : 18.6 } } { "timestamp" : "2017-08-04T06:59:59.863Z", "asset" : "TI sensorTag/temperature", "sensor_values" : { "object" : 18.2, "ambient" : 21.6 } } { "timestamp" : "2017-08-04T07:00:00.863Z", "asset" : "TI sensorTag/accelerometer", "sensor_values" : { "x" : 1.2, "y" : 0.0, "z" : -0.6 } } { "timestamp" : "2017-08-04T07:00:01.863Z", "asset" : "TI sensorTag/gyroscope", "sensor_values" : { "x" : 101.2, "y" : 46.2, "z" : -12.6 } } { "timestamp" : "2017-08-04T07:00:02.863Z", "asset" : "TI sensorTag/magnetometer", "sensor_values" : { "x" : 101.2, "y" : 46.2, "z" : -12.6 } } { "timestamp" : "2017-08-04T07:00:03.863Z", "asset" : "mouse", "sensor_values" : { "button" : "down" } } { "timestamp" : "2017-08-04T07:00:04.863Z", "asset" : "wall clock", "sensor_values" : { "tick" : "tock" } } """
36.601467
122
0.638277
1,919
14,970
4.763418
0.205315
0.019692
0.020457
0.013128
0.213215
0.159611
0.118696
0.086314
0.082923
0.05076
0
0.026688
0.234068
14,970
408
123
36.691176
0.770539
0.167001
0
0.102439
0
0
0.169304
0.002327
0
0
0
0.004902
0
1
0.039024
false
0
0.068293
0
0.146341
0.029268
0
0
0
null
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
null
0
0
0
0
0
0
0
0
0
0
0
0
1
0
81197e9fdd38be14f8210f08e7cec2020796f260
19,888
py
Python
qiskit/ignis/mitigation/measurement/filters.py
paulineollitrault/qiskit-ignis
99f24ea6533cd284be4c44a48d43e54f62f05674
[ "Apache-2.0" ]
182
2019-02-19T22:52:42.000Z
2022-02-28T05:48:07.000Z
qiskit/ignis/mitigation/measurement/filters.py
paulineollitrault/qiskit-ignis
99f24ea6533cd284be4c44a48d43e54f62f05674
[ "Apache-2.0" ]
384
2019-02-19T21:30:18.000Z
2021-12-02T21:13:34.000Z
qiskit/ignis/mitigation/measurement/filters.py
paulineollitrault/qiskit-ignis
99f24ea6533cd284be4c44a48d43e54f62f05674
[ "Apache-2.0" ]
203
2019-02-19T21:06:27.000Z
2022-03-02T14:16:50.000Z
# -*- coding: utf-8 -*- # This code is part of Qiskit. # # (C) Copyright IBM 2019. # # This code is licensed under the Apache License, Version 2.0. You may # obtain a copy of this license in the LICENSE.txt file in the root directory # of this source tree or at http://www.apache.org/licenses/LICENSE-2.0. # # Any modifications or derivative works of this code must retain this # copyright notice, and modified files need to carry a notice indicating # that they have been altered from the originals. # pylint: disable=cell-var-from-loop,invalid-name """ Measurement correction filters. """ from typing import List, Union from copy import deepcopy from scipy.optimize import minimize import scipy.linalg as la import numpy as np import qiskit from qiskit import QiskitError from qiskit.tools import parallel_map from qiskit.ignis.verification.tomography import count_keys class MeasurementFilter(): """ Measurement error mitigation filter. Produced from a measurement calibration fitter and can be applied to data. """ def __init__(self, cal_matrix: np.matrix, state_labels: list): """ Initialize a measurement error mitigation filter using the cal_matrix from a measurement calibration fitter. Args: cal_matrix: the calibration matrix for applying the correction state_labels: the states for the ordering of the cal matrix """ self._cal_matrix = cal_matrix self._state_labels = state_labels @property def cal_matrix(self): """Return cal_matrix.""" return self._cal_matrix @property def state_labels(self): """return the state label ordering of the cal matrix""" return self._state_labels @state_labels.setter def state_labels(self, new_state_labels): """set the state label ordering of the cal matrix""" self._state_labels = new_state_labels @cal_matrix.setter def cal_matrix(self, new_cal_matrix): """Set cal_matrix.""" self._cal_matrix = new_cal_matrix def apply(self, raw_data, method='least_squares'): """Apply the calibration matrix to results. Args: raw_data (dict or list): The data to be corrected. Can be in a number of forms: Form 1: a counts dictionary from results.get_counts Form 2: a list of counts of `length==len(state_labels)` Form 3: a list of counts of `length==M*len(state_labels)` where M is an integer (e.g. for use with the tomography data) Form 4: a qiskit Result method (str): fitting method. If `None`, then least_squares is used. ``pseudo_inverse``: direct inversion of the A matrix ``least_squares``: constrained to have physical probabilities Returns: dict or list: The corrected data in the same form as `raw_data` Raises: QiskitError: if `raw_data` is not an integer multiple of the number of calibrated states. """ # check forms of raw_data if isinstance(raw_data, dict): # counts dictionary for data_label in raw_data.keys(): if data_label not in self._state_labels: raise QiskitError("Unexpected state label '" + data_label + "', verify the fitter's state labels " "correspond to the input data") data_format = 0 # convert to form2 raw_data2 = [np.zeros(len(self._state_labels), dtype=float)] for stateidx, state in enumerate(self._state_labels): raw_data2[0][stateidx] = raw_data.get(state, 0) elif isinstance(raw_data, list): size_ratio = len(raw_data)/len(self._state_labels) if len(raw_data) == len(self._state_labels): data_format = 1 raw_data2 = [raw_data] elif int(size_ratio) == size_ratio: data_format = 2 size_ratio = int(size_ratio) # make the list into chunks the size of state_labels for easier # processing raw_data2 = np.zeros([size_ratio, len(self._state_labels)]) for i in range(size_ratio): raw_data2[i][:] = raw_data[ i * len(self._state_labels):(i + 1)*len( self._state_labels)] else: raise QiskitError("Data list is not an integer multiple " "of the number of calibrated states") elif isinstance(raw_data, qiskit.result.result.Result): # extract out all the counts, re-call the function with the # counts and push back into the new result new_result = deepcopy(raw_data) new_counts_list = parallel_map( self._apply_correction, [resultidx for resultidx, _ in enumerate(raw_data.results)], task_args=(raw_data, method)) for resultidx, new_counts in new_counts_list: new_result.results[resultidx].data.counts = new_counts return new_result else: raise QiskitError("Unrecognized type for raw_data.") if method == 'pseudo_inverse': pinv_cal_mat = la.pinv(self._cal_matrix) # Apply the correction for data_idx, _ in enumerate(raw_data2): if method == 'pseudo_inverse': raw_data2[data_idx] = np.dot( pinv_cal_mat, raw_data2[data_idx]) elif method == 'least_squares': nshots = sum(raw_data2[data_idx]) def fun(x): return sum( (raw_data2[data_idx] - np.dot(self._cal_matrix, x))**2) x0 = np.random.rand(len(self._state_labels)) x0 = x0 / sum(x0) cons = ({'type': 'eq', 'fun': lambda x: nshots - sum(x)}) bnds = tuple((0, nshots) for x in x0) res = minimize(fun, x0, method='SLSQP', constraints=cons, bounds=bnds, tol=1e-6) raw_data2[data_idx] = res.x else: raise QiskitError("Unrecognized method.") if data_format == 2: # flatten back out the list raw_data2 = raw_data2.flatten() elif data_format == 0: # convert back into a counts dictionary new_count_dict = {} for stateidx, state in enumerate(self._state_labels): if raw_data2[0][stateidx] != 0: new_count_dict[state] = raw_data2[0][stateidx] raw_data2 = new_count_dict else: # TODO: should probably change to: # raw_data2 = raw_data2[0].tolist() raw_data2 = raw_data2[0] return raw_data2 def _apply_correction(self, resultidx, raw_data, method): """Wrapper to call apply with a counts dictionary.""" new_counts = self.apply( raw_data.get_counts(resultidx), method=method) return resultidx, new_counts class TensoredFilter(): """ Tensored measurement error mitigation filter. Produced from a tensored measurement calibration fitter and can be applied to data. """ def __init__(self, cal_matrices: np.matrix, substate_labels_list: list, mit_pattern: list): """ Initialize a tensored measurement error mitigation filter using the cal_matrices from a tensored measurement calibration fitter. A simple usage this class is explained [here] (https://qiskit.org/documentation/tutorials/noise/3_measurement_error_mitigation.html). Args: cal_matrices: the calibration matrices for applying the correction. substate_labels_list: for each calibration matrix a list of the states (as strings, states in the subspace) mit_pattern: for each calibration matrix a list of the logical qubit indices (as int, states in the subspace) """ self._cal_matrices = cal_matrices self._qubit_list_sizes = [] self._indices_list = [] self._substate_labels_list = [] self.substate_labels_list = substate_labels_list self._mit_pattern = mit_pattern @property def cal_matrices(self): """Return cal_matrices.""" return self._cal_matrices @cal_matrices.setter def cal_matrices(self, new_cal_matrices): """Set cal_matrices.""" self._cal_matrices = deepcopy(new_cal_matrices) @property def substate_labels_list(self): """Return _substate_labels_list""" return self._substate_labels_list @substate_labels_list.setter def substate_labels_list(self, new_substate_labels_list): """Return _substate_labels_list""" self._substate_labels_list = new_substate_labels_list # get the number of qubits in each subspace self._qubit_list_sizes = [] for _, substate_label_list in enumerate(self._substate_labels_list): self._qubit_list_sizes.append( int(np.log2(len(substate_label_list)))) # get the indices in the calibration matrix self._indices_list = [] for _, sub_labels in enumerate(self._substate_labels_list): self._indices_list.append( {lab: ind for ind, lab in enumerate(sub_labels)}) @property def qubit_list_sizes(self): """Return _qubit_list_sizes.""" return self._qubit_list_sizes @property def nqubits(self): """Return the number of qubits. See also MeasurementFilter.apply() """ return sum(self._qubit_list_sizes) def apply(self, raw_data: Union[qiskit.result.result.Result, dict], method: str = 'least_squares', meas_layout: List[int] = None): """ Apply the calibration matrices to results. Args: raw_data (dict or Result): The data to be corrected. Can be in one of two forms: * A counts dictionary from results.get_counts * A Qiskit Result method (str): fitting method. The following methods are supported: * 'pseudo_inverse': direct inversion of the cal matrices. Mitigated counts can contain negative values and the sum of counts would not equal to the shots. Mitigation is conducted qubit wise: For each qubit, mitigate the whole counts using the calibration matrices which affect the corresponding qubit. For example, assume we are mitigating the 3rd bit of the 4-bit counts using '2\times 2' calibration matrix `A_3`. When mitigating the count of '0110' in this step, the following formula is applied: `count['0110'] = A_3^{-1}[1, 0]*count['0100'] + A_3^{-1}[1, 1]*count['0110']`. The total time complexity of this method is `O(m2^{n + t})`, where `n` is the size of calibrated qubits, `m` is the number of sets in `mit_pattern`, and `t` is the size of largest set of mit_pattern. If the `mit_pattern` is shaped like `[[0], [1], [2], ..., [n-1]]`, which corresponds to the tensor product noise model without cross-talk, then the time complexity would be `O(n2^n)`. If the `mit_pattern` is shaped like `[[0, 1, 2, ..., n-1]]`, which exactly corresponds to the complete error mitigation, then the time complexity would be `O(2^(n+n)) = O(4^n)`. * 'least_squares': constrained to have physical probabilities. Instead of directly applying inverse calibration matrices, this method solve a constrained optimization problem to find the closest probability vector to the result from 'pseudo_inverse' method. Sequential least square quadratic programming (SLSQP) is used in the internal process. Every updating step in SLSQP takes `O(m2^{n+t})` time. Since this method is using the SLSQP optimization over the vector with lenght `2^n`, the mitigation for 8 bit counts with the `mit_pattern = [[0], [1], [2], ..., [n-1]]` would take 10 seconds or more. * If `None`, 'least_squares' is used. meas_layout (list of int): the mapping from classical registers to qubits * If you measure qubit `2` to clbit `0`, `0` to `1`, and `1` to `2`, the list becomes `[2, 0, 1]` * If `None`, flatten(mit_pattern) is used. Returns: dict or Result: The corrected data in the same form as raw_data Raises: QiskitError: if raw_data is not in a one of the defined forms. """ all_states = count_keys(self.nqubits) num_of_states = 2**self.nqubits if meas_layout is None: meas_layout = [] for qubits in self._mit_pattern: meas_layout += qubits # check forms of raw_data if isinstance(raw_data, dict): # counts dictionary # convert to list raw_data2 = [np.zeros(num_of_states, dtype=float)] for state, count in raw_data.items(): stateidx = int(state, 2) raw_data2[0][stateidx] = count elif isinstance(raw_data, qiskit.result.result.Result): # extract out all the counts, re-call the function with the # counts and push back into the new result new_result = deepcopy(raw_data) new_counts_list = parallel_map( self._apply_correction, [resultidx for resultidx, _ in enumerate(raw_data.results)], task_args=(raw_data, method, meas_layout)) for resultidx, new_counts in new_counts_list: new_result.results[resultidx].data.counts = new_counts return new_result else: raise QiskitError("Unrecognized type for raw_data.") if method == 'pseudo_inverse': pinv_cal_matrices = [] for cal_mat in self._cal_matrices: pinv_cal_matrices.append(la.pinv(cal_mat)) meas_layout = meas_layout[::-1] # reverse endian qubits_to_clbits = [-1 for _ in range(max(meas_layout) + 1)] for i, qubit in enumerate(meas_layout): qubits_to_clbits[qubit] = i # Apply the correction for data_idx, _ in enumerate(raw_data2): if method == 'pseudo_inverse': for pinv_cal_mat, pos_qubits, indices in zip(pinv_cal_matrices, self._mit_pattern, self._indices_list): inv_mat_dot_x = np.zeros([num_of_states], dtype=float) pos_clbits = [qubits_to_clbits[qubit] for qubit in pos_qubits] for state_idx, state in enumerate(all_states): first_index = self.compute_index_of_cal_mat(state, pos_clbits, indices) for i in range(len(pinv_cal_mat)): # i is index of pinv_cal_mat source_state = self.flip_state(state, i, pos_clbits) second_index = self.compute_index_of_cal_mat(source_state, pos_clbits, indices) inv_mat_dot_x[state_idx] += pinv_cal_mat[first_index, second_index]\ * raw_data2[data_idx][int(source_state, 2)] raw_data2[data_idx] = inv_mat_dot_x elif method == 'least_squares': def fun(x): mat_dot_x = deepcopy(x) for cal_mat, pos_qubits, indices in zip(self._cal_matrices, self._mit_pattern, self._indices_list): res_mat_dot_x = np.zeros([num_of_states], dtype=float) pos_clbits = [qubits_to_clbits[qubit] for qubit in pos_qubits] for state_idx, state in enumerate(all_states): second_index = self.compute_index_of_cal_mat(state, pos_clbits, indices) for i in range(len(cal_mat)): target_state = self.flip_state(state, i, pos_clbits) first_index =\ self.compute_index_of_cal_mat(target_state, pos_clbits, indices) res_mat_dot_x[int(target_state, 2)]\ += cal_mat[first_index, second_index] * mat_dot_x[state_idx] mat_dot_x = res_mat_dot_x return sum((raw_data2[data_idx] - mat_dot_x) ** 2) x0 = np.random.rand(num_of_states) x0 = x0 / sum(x0) nshots = sum(raw_data2[data_idx]) cons = ({'type': 'eq', 'fun': lambda x: nshots - sum(x)}) bnds = tuple((0, nshots) for x in x0) res = minimize(fun, x0, method='SLSQP', constraints=cons, bounds=bnds, tol=1e-6) raw_data2[data_idx] = res.x else: raise QiskitError("Unrecognized method.") # convert back into a counts dictionary new_count_dict = {} for state_idx, state in enumerate(all_states): if raw_data2[0][state_idx] != 0: new_count_dict[state] = raw_data2[0][state_idx] return new_count_dict def flip_state(self, state: str, mat_index: int, flip_poses: List[int]) -> str: """Flip the state according to the chosen qubit positions""" flip_poses = [pos for i, pos in enumerate(flip_poses) if (mat_index >> i) & 1] flip_poses = sorted(flip_poses) new_state = "" pos = 0 for flip_pos in flip_poses: new_state += state[pos:flip_pos] new_state += str(int(state[flip_pos], 2) ^ 1) # flip the state pos = flip_pos + 1 new_state += state[pos:] return new_state def compute_index_of_cal_mat(self, state: str, pos_qubits: List[int], indices: dict) -> int: """Return the index of (pseudo inverse) calibration matrix for the input quantum state""" sub_state = "" for pos in pos_qubits: sub_state += state[pos] return indices[sub_state] def _apply_correction(self, resultidx: int, raw_data: qiskit.result.result.Result, method: str, meas_layout: List[int]): """Wrapper to call apply with a counts dictionary.""" new_counts = self.apply( raw_data.get_counts(resultidx), method=method, meas_layout=meas_layout) return resultidx, new_counts
40.422764
100
0.569389
2,404
19,888
4.493344
0.158486
0.022033
0.026662
0.013886
0.455934
0.408998
0.374097
0.288002
0.233753
0.233753
0
0.012043
0.352826
19,888
491
101
40.505092
0.827208
0.332864
0
0.336032
0
0
0.031934
0
0
0
0
0.002037
0
1
0.080972
false
0
0.036437
0.004049
0.190283
0
0
0
0
null
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
null
0
0
0
0
0
0
0
0
0
0
0
0
1
0
811bbfb3266a619b867f934c6f82a6ecb7783e88
111,660
py
Python
pymatgen/analysis/graphs.py
Roy027/pymatgen
a4aa91d011033c1151b82335abd080e2b1a310d5
[ "MIT" ]
null
null
null
pymatgen/analysis/graphs.py
Roy027/pymatgen
a4aa91d011033c1151b82335abd080e2b1a310d5
[ "MIT" ]
null
null
null
pymatgen/analysis/graphs.py
Roy027/pymatgen
a4aa91d011033c1151b82335abd080e2b1a310d5
[ "MIT" ]
null
null
null
# coding: utf-8 # Copyright (c) Pymatgen Development Team. # Distributed under the terms of the MIT License. """ Module for graph representations of crystals. """ import copy import logging import os.path import subprocess import warnings from collections import defaultdict, namedtuple from itertools import combinations from operator import itemgetter import networkx as nx import networkx.algorithms.isomorphism as iso import numpy as np from monty.json import MSONable from monty.os.path import which from networkx.drawing.nx_agraph import write_dot from networkx.readwrite import json_graph from scipy.spatial import KDTree from scipy.stats import describe from pymatgen.core import Lattice, Molecule, PeriodicSite, Structure from pymatgen.core.structure import FunctionalGroups from pymatgen.util.coord import lattice_points_in_supercell from pymatgen.vis.structure_vtk import EL_COLORS try: import igraph IGRAPH_AVAILABLE = True except ImportError: IGRAPH_AVAILABLE = False logger = logging.getLogger(__name__) logger.setLevel(logging.INFO) __author__ = "Matthew Horton, Evan Spotte-Smith, Samuel Blau" __version__ = "0.1" __maintainer__ = "Matthew Horton" __email__ = "mkhorton@lbl.gov" __status__ = "Production" __date__ = "August 2017" ConnectedSite = namedtuple("ConnectedSite", "site, jimage, index, weight, dist") def _compare(g1, g2, i1, i2): """ Helper function called by isomorphic to ensure comparison of node identities. """ return g1.vs[i1]["species"] == g2.vs[i2]["species"] def _igraph_from_nxgraph(graph): """ Helper function that converts a networkx graph object into an igraph graph object. """ nodes = graph.nodes(data=True) new_igraph = igraph.Graph() for node in nodes: new_igraph.add_vertex(name=str(node[0]), species=node[1]["specie"], coords=node[1]["coords"]) new_igraph.add_edges([(str(edge[0]), str(edge[1])) for edge in graph.edges()]) return new_igraph def _isomorphic(frag1, frag2): """ Internal function to check if two graph objects are isomorphic, using igraph if if is available and networkx if it is not. """ f1_nodes = frag1.nodes(data=True) f2_nodes = frag2.nodes(data=True) if len(f1_nodes) != len(f2_nodes): return False f2_edges = frag2.edges() if len(f2_edges) != len(f2_edges): return False f1_comp_dict = {} f2_comp_dict = {} for node in f1_nodes: if node[1]["specie"] not in f1_comp_dict: f1_comp_dict[node[1]["specie"]] = 1 else: f1_comp_dict[node[1]["specie"]] += 1 for node in f2_nodes: if node[1]["specie"] not in f2_comp_dict: f2_comp_dict[node[1]["specie"]] = 1 else: f2_comp_dict[node[1]["specie"]] += 1 if f1_comp_dict != f2_comp_dict: return False if IGRAPH_AVAILABLE: ifrag1 = _igraph_from_nxgraph(frag1) ifrag2 = _igraph_from_nxgraph(frag2) return ifrag1.isomorphic_vf2(ifrag2, node_compat_fn=_compare) nm = iso.categorical_node_match("specie", "ERROR") return nx.is_isomorphic(frag1.to_undirected(), frag2.to_undirected(), node_match=nm) class StructureGraph(MSONable): """ This is a class for annotating a Structure with bond information, stored in the form of a graph. A "bond" does not necessarily have to be a chemical bond, but can store any kind of information that connects two Sites. """ def __init__(self, structure, graph_data=None): """ If constructing this class manually, use the `with_empty_graph` method or `with_local_env_strategy` method (using an algorithm provided by the `local_env` module, such as O'Keeffe). This class that contains connection information: relationships between sites represented by a Graph structure, and an associated structure object. This class uses the NetworkX package to store and operate on the graph itself, but contains a lot of helper methods to make associating a graph with a given crystallographic structure easier. Use cases for this include storing bonding information, NMR J-couplings, Heisenberg exchange parameters, etc. For periodic graphs, class stores information on the graph edges of what lattice image the edge belongs to. :param structure: a Structure object :param graph_data: dict containing graph information in dict format (not intended to be constructed manually, see as_dict method for format) """ if isinstance(structure, StructureGraph): # just make a copy from input graph_data = structure.as_dict()["graphs"] self.structure = structure self.graph = nx.readwrite.json_graph.adjacency_graph(graph_data) # tidy up edge attr dicts, reading to/from json duplicates # information for u, v, k, d in self.graph.edges(keys=True, data=True): if "id" in d: del d["id"] if "key" in d: del d["key"] # ensure images are tuples (conversion to lists happens # when serializing back from json), it's important images # are hashable/immutable if "to_jimage" in d: d["to_jimage"] = tuple(d["to_jimage"]) if "from_jimage" in d: d["from_jimage"] = tuple(d["from_jimage"]) @classmethod def with_empty_graph(cls, structure, name="bonds", edge_weight_name=None, edge_weight_units=None): """ Constructor for StructureGraph, returns a StructureGraph object with an empty graph (no edges, only nodes defined that correspond to Sites in Structure). :param structure (Structure): :param name (str): name of graph, e.g. "bonds" :param edge_weight_name (str): name of edge weights, e.g. "bond_length" or "exchange_constant" :param edge_weight_units (str): name of edge weight units e.g. "Å" or "eV" :return (StructureGraph): """ if edge_weight_name and (edge_weight_units is None): raise ValueError( "Please specify units associated " "with your edge weights. Can be " "empty string if arbitrary or " "dimensionless." ) # construct graph with one node per site # graph attributes don't change behavior of graph, # they're just for book-keeping graph = nx.MultiDiGraph( edge_weight_name=edge_weight_name, edge_weight_units=edge_weight_units, name=name, ) graph.add_nodes_from(range(len(structure))) graph_data = json_graph.adjacency_data(graph) return cls(structure, graph_data=graph_data) @staticmethod def with_edges(structure, edges): """ Constructor for MoleculeGraph, using pre-existing or pre-defined edges with optional edge parameters. :param molecule: Molecule object :param edges: dict representing the bonds of the functional group (format: {(from_index, to_index, from_image, to_image): props}, where props is a dictionary of properties, including weight. Props should be None if no additional properties are to be specified. :return: sg, a StructureGraph """ sg = StructureGraph.with_empty_graph(structure, name="bonds", edge_weight_name="weight", edge_weight_units="") for edge, props in edges.items(): try: from_index = edge[0] to_index = edge[1] from_image = edge[2] to_image = edge[3] except TypeError: raise ValueError("Edges must be given as (from_index, to_index," " from_image, to_image) tuples") if props is not None: if "weight" in props.keys(): weight = props["weight"] del props["weight"] else: weight = None if len(props.items()) == 0: props = None else: weight = None nodes = sg.graph.nodes if not (from_index in nodes and to_index in nodes): raise ValueError( "Edges cannot be added if nodes are not" " present in the graph. Please check your" " indices." ) sg.add_edge( from_index, to_index, from_jimage=from_image, to_jimage=to_image, weight=weight, edge_properties=props, ) sg.set_node_attributes() return sg @staticmethod def with_local_env_strategy(structure, strategy, weights=False): """ Constructor for StructureGraph, using a strategy from :Class: `pymatgen.analysis.local_env`. :param structure: Structure object :param strategy: an instance of a :Class: `pymatgen.analysis.local_env.NearNeighbors` object :param weights: if True, use weights from local_env class (consult relevant class for their meaning) :return: """ if not strategy.structures_allowed: raise ValueError( "Chosen strategy is not designed for use with structures! " "Please choose another strategy." ) sg = StructureGraph.with_empty_graph(structure, name="bonds") for n, neighbors in enumerate(strategy.get_all_nn_info(structure)): for neighbor in neighbors: # local_env will always try to add two edges # for any one bond, one from site u to site v # and another form site v to site u: this is # harmless, so warn_duplicates=False sg.add_edge( from_index=n, from_jimage=(0, 0, 0), to_index=neighbor["site_index"], to_jimage=neighbor["image"], weight=neighbor["weight"] if weights else None, warn_duplicates=False, ) return sg @property def name(self): """ :return: Name of graph """ return self.graph.graph["name"] @property def edge_weight_name(self): """ :return: Name of the edge weight property of graph """ return self.graph.graph["edge_weight_name"] @property def edge_weight_unit(self): """ :return: Units of the edge weight property of graph """ return self.graph.graph["edge_weight_units"] def add_edge( self, from_index, to_index, from_jimage=(0, 0, 0), to_jimage=None, weight=None, warn_duplicates=True, edge_properties=None, ): """ Add edge to graph. Since physically a 'bond' (or other connection between sites) doesn't have a direction, from_index, from_jimage can be swapped with to_index, to_jimage. However, images will always always be shifted so that from_index < to_index and from_jimage becomes (0, 0, 0). :param from_index: index of site connecting from :param to_index: index of site connecting to :param from_jimage (tuple of ints): lattice vector of periodic image, e.g. (1, 0, 0) for periodic image in +x direction :param to_jimage (tuple of ints): lattice vector of image :param weight (float): e.g. bond length :param warn_duplicates (bool): if True, will warn if trying to add duplicate edges (duplicate edges will not be added in either case) :param edge_properties (dict): any other information to store on graph edges, similar to Structure's site_properties :return: """ # this is not necessary for the class to work, but # just makes it neater if to_index < from_index: to_index, from_index = from_index, to_index to_jimage, from_jimage = from_jimage, to_jimage # constrain all from_jimages to be (0, 0, 0), # initial version of this class worked even if # from_jimage != (0, 0, 0), but making this # assumption simplifies logic later if not np.array_equal(from_jimage, (0, 0, 0)): shift = from_jimage from_jimage = np.subtract(from_jimage, shift) to_jimage = np.subtract(to_jimage, shift) # automatic detection of to_jimage if user doesn't specify # will try and detect all equivalent images and add multiple # edges if appropriate if to_jimage is None: # assume we want the closest site warnings.warn("Please specify to_jimage to be unambiguous, " "trying to automatically detect.") dist, to_jimage = self.structure[from_index].distance_and_image(self.structure[to_index]) if dist == 0: # this will happen when from_index == to_index, # typically in primitive single-atom lattices images = [1, 0, 0], [0, 1, 0], [0, 0, 1] dists = [] for image in images: dists.append( self.structure[from_index].distance_and_image(self.structure[from_index], jimage=image)[0] ) dist = min(dists) equiv_sites = self.structure.get_neighbors_in_shell( self.structure[from_index].coords, dist, dist * 0.01, include_index=True ) for nnsite in equiv_sites: to_jimage = np.subtract(nnsite.frac_coords, self.structure[from_index].frac_coords) to_jimage = np.round(to_jimage).astype(int) self.add_edge( from_index=from_index, from_jimage=(0, 0, 0), to_jimage=to_jimage, to_index=nnsite.index, ) return # sanitize types from_jimage, to_jimage = ( tuple(map(int, from_jimage)), tuple(map(int, to_jimage)), ) from_index, to_index = int(from_index), int(to_index) # check we're not trying to add a duplicate edge # there should only ever be at most one edge # between a given (site, jimage) pair and another # (site, jimage) pair existing_edge_data = self.graph.get_edge_data(from_index, to_index) if existing_edge_data: for key, d in existing_edge_data.items(): if d["to_jimage"] == to_jimage: if warn_duplicates: warnings.warn( "Trying to add an edge that already exists from " "site {} to site {} in {}.".format(from_index, to_index, to_jimage) ) return # generic container for additional edge properties, # similar to site properties edge_properties = edge_properties or {} if weight: self.graph.add_edge(from_index, to_index, to_jimage=to_jimage, weight=weight, **edge_properties) else: self.graph.add_edge(from_index, to_index, to_jimage=to_jimage, **edge_properties) def insert_node( self, i, species, coords, coords_are_cartesian=False, validate_proximity=False, site_properties=None, edges=None, ): """ A wrapper around Molecule.insert(), which also incorporates the new site into the MoleculeGraph. :param i: Index at which to insert the new site :param species: Species for the new site :param coords: 3x1 array representing coordinates of the new site :param coords_are_cartesian: Whether coordinates are cartesian. Defaults to False. :param validate_proximity: For Molecule.insert(); if True (default False), distance will be checked to ensure that site can be safely added. :param site_properties: Site properties for Molecule :param edges: List of dicts representing edges to be added to the MoleculeGraph. These edges must include the index of the new site i, and all indices used for these edges should reflect the MoleculeGraph AFTER the insertion, NOT before. Each dict should at least have a "to_index" and "from_index" key, and can also have a "weight" and a "properties" key. :return: """ self.structure.insert( i, species, coords, coords_are_cartesian=coords_are_cartesian, validate_proximity=validate_proximity, properties=site_properties, ) mapping = {} for j in range(len(self.structure) - 1): if j < i: mapping[j] = j else: mapping[j] = j + 1 nx.relabel_nodes(self.graph, mapping, copy=False) self.graph.add_node(i) self.set_node_attributes() if edges is not None: for edge in edges: try: self.add_edge( edge["from_index"], edge["to_index"], from_jimage=(0, 0, 0), to_jimage=edge["to_jimage"], weight=edge.get("weight", None), edge_properties=edge.get("properties", None), ) except KeyError: raise RuntimeError("Some edges are invalid.") def set_node_attributes(self): """ Gives each node a "specie" and a "coords" attribute, updated with the current species and coordinates. :return: """ species = {} coords = {} properties = {} for node in self.graph.nodes(): species[node] = self.structure[node].specie.symbol coords[node] = self.structure[node].coords properties[node] = self.structure[node].properties nx.set_node_attributes(self.graph, species, "specie") nx.set_node_attributes(self.graph, coords, "coords") nx.set_node_attributes(self.graph, properties, "properties") def alter_edge( self, from_index, to_index, to_jimage=None, new_weight=None, new_edge_properties=None, ): """ Alters either the weight or the edge_properties of an edge in the StructureGraph. :param from_index: int :param to_index: int :param to_jimage: tuple :param new_weight: alter_edge does not require that weight be altered. As such, by default, this is None. If weight is to be changed, it should be a float. :param new_edge_properties: alter_edge does not require that edge_properties be altered. As such, by default, this is None. If any edge properties are to be changed, it should be a dictionary of edge properties to be changed. :return: """ existing_edges = self.graph.get_edge_data(from_index, to_index) # ensure that edge exists before attempting to change it if not existing_edges: raise ValueError( "Edge between {} and {} cannot be altered;\ no edge exists between those sites.".format( from_index, to_index ) ) if to_jimage is None: edge_index = 0 else: for i, properties in existing_edges.items(): if properties["to_jimage"] == to_jimage: edge_index = i if new_weight is not None: self.graph[from_index][to_index][edge_index]["weight"] = new_weight if new_edge_properties is not None: for prop in list(new_edge_properties.keys()): self.graph[from_index][to_index][edge_index][prop] = new_edge_properties[prop] def break_edge(self, from_index, to_index, to_jimage=None, allow_reverse=False): """ Remove an edge from the StructureGraph. If no image is given, this method will fail. :param from_index: int :param to_index: int :param to_jimage: tuple :param allow_reverse: If allow_reverse is True, then break_edge will attempt to break both (from_index, to_index) and, failing that, will attempt to break (to_index, from_index). :return: """ # ensure that edge exists before attempting to remove it existing_edges = self.graph.get_edge_data(from_index, to_index) existing_reverse = None if to_jimage is None: raise ValueError("Image must be supplied, to avoid ambiguity.") if existing_edges: for i, properties in existing_edges.items(): if properties["to_jimage"] == to_jimage: edge_index = i self.graph.remove_edge(from_index, to_index, edge_index) else: if allow_reverse: existing_reverse = self.graph.get_edge_data(to_index, from_index) if existing_reverse: for i, properties in existing_reverse.items(): if properties["to_jimage"] == to_jimage: edge_index = i self.graph.remove_edge(to_index, from_index, edge_index) else: raise ValueError( "Edge cannot be broken between {} and {};\ no edge exists between those sites.".format( from_index, to_index ) ) def remove_nodes(self, indices): """ A wrapper for Molecule.remove_sites(). :param indices: list of indices in the current Molecule (and graph) to be removed. :return: """ self.structure.remove_sites(indices) self.graph.remove_nodes_from(indices) mapping = {} for correct, current in enumerate(sorted(self.graph.nodes)): mapping[current] = correct nx.relabel_nodes(self.graph, mapping, copy=False) self.set_node_attributes() def substitute_group( self, index, func_grp, strategy, bond_order=1, graph_dict=None, strategy_params=None, ): """ Builds off of Structure.substitute to replace an atom in self.structure with a functional group. This method also amends self.graph to incorporate the new functional group. NOTE: Care must be taken to ensure that the functional group that is substituted will not place atoms to close to each other, or violate the dimensions of the Lattice. :param index: Index of atom to substitute. :param func_grp: Substituent molecule. There are two options: 1. Providing an actual Molecule as the input. The first atom must be a DummySpecies X, indicating the position of nearest neighbor. The second atom must be the next nearest atom. For example, for a methyl group substitution, func_grp should be X-CH3, where X is the first site and C is the second site. What the code will do is to remove the index site, and connect the nearest neighbor to the C atom in CH3. The X-C bond indicates the directionality to connect the atoms. 2. A string name. The molecule will be obtained from the relevant template in func_groups.json. :param strategy: Class from pymatgen.analysis.local_env. :param bond_order: A specified bond order to calculate the bond length between the attached functional group and the nearest neighbor site. Defaults to 1. :param graph_dict: Dictionary representing the bonds of the functional group (format: {(u, v): props}, where props is a dictionary of properties, including weight. If None, then the algorithm will attempt to automatically determine bonds using one of a list of strategies defined in pymatgen.analysis.local_env. :param strategy_params: dictionary of keyword arguments for strategy. If None, default parameters will be used. :return: """ def map_indices(grp): grp_map = {} # Get indices now occupied by functional group # Subtracting 1 because the dummy atom X should not count atoms = len(grp) - 1 offset = len(self.structure) - atoms for i in range(atoms): grp_map[i] = i + offset return grp_map if isinstance(func_grp, Molecule): func_grp = copy.deepcopy(func_grp) else: try: func_grp = copy.deepcopy(FunctionalGroups[func_grp]) except Exception: raise RuntimeError("Can't find functional group in list. " "Provide explicit coordinate instead") self.structure.substitute(index, func_grp, bond_order=bond_order) mapping = map_indices(func_grp) # Remove dummy atom "X" func_grp.remove_species("X") if graph_dict is not None: for (u, v) in graph_dict.keys(): edge_props = graph_dict[(u, v)] if "to_jimage" in edge_props.keys(): to_jimage = edge_props["to_jimage"] del edge_props["to_jimage"] else: # By default, assume that all edges should stay remain # inside the initial image to_jimage = (0, 0, 0) if "weight" in edge_props.keys(): weight = edge_props["weight"] del edge_props["weight"] self.add_edge( mapping[u], mapping[v], to_jimage=to_jimage, weight=weight, edge_properties=edge_props, ) else: if strategy_params is None: strategy_params = {} strat = strategy(**strategy_params) for site in mapping.values(): neighbors = strat.get_nn_info(self.structure, site) for neighbor in neighbors: self.add_edge( from_index=site, from_jimage=(0, 0, 0), to_index=neighbor["site_index"], to_jimage=neighbor["image"], weight=neighbor["weight"], warn_duplicates=False, ) def get_connected_sites(self, n, jimage=(0, 0, 0)): """ Returns a named tuple of neighbors of site n: periodic_site, jimage, index, weight. Index is the index of the corresponding site in the original structure, weight can be None if not defined. :param n: index of Site in Structure :param jimage: lattice vector of site :return: list of ConnectedSite tuples, sorted by closest first """ connected_sites = set() connected_site_images = set() out_edges = [(u, v, d, "out") for u, v, d in self.graph.out_edges(n, data=True)] in_edges = [(u, v, d, "in") for u, v, d in self.graph.in_edges(n, data=True)] for u, v, d, dir in out_edges + in_edges: to_jimage = d["to_jimage"] if dir == "in": u, v = v, u to_jimage = np.multiply(-1, to_jimage) to_jimage = tuple(map(int, np.add(to_jimage, jimage))) site_d = self.structure[v].as_dict() site_d["abc"] = np.add(site_d["abc"], to_jimage).tolist() site = PeriodicSite.from_dict(site_d) # from_site if jimage arg != (0, 0, 0) relative_jimage = np.subtract(to_jimage, jimage) dist = self.structure[u].distance(self.structure[v], jimage=relative_jimage) weight = d.get("weight", None) if (v, to_jimage) not in connected_site_images: connected_site = ConnectedSite(site=site, jimage=to_jimage, index=v, weight=weight, dist=dist) connected_sites.add(connected_site) connected_site_images.add((v, to_jimage)) # return list sorted by closest sites first connected_sites = list(connected_sites) connected_sites.sort(key=lambda x: x.dist) return connected_sites def get_coordination_of_site(self, n): """ Returns the number of neighbors of site n. In graph terms, simply returns degree of node corresponding to site n. :param n: index of site :return (int): """ number_of_self_loops = sum([1 for n, v in self.graph.edges(n) if n == v]) return self.graph.degree(n) - number_of_self_loops def draw_graph_to_file( self, filename="graph", diff=None, hide_unconnected_nodes=False, hide_image_edges=True, edge_colors=False, node_labels=False, weight_labels=False, image_labels=False, color_scheme="VESTA", keep_dot=False, algo="fdp", ): """ Draws graph using GraphViz. The networkx graph object itself can also be drawn with networkx's in-built graph drawing methods, but note that this might give misleading results for multigraphs (edges are super-imposed on each other). If visualization is difficult to interpret, `hide_image_edges` can help, especially in larger graphs. :param filename: filename to output, will detect filetype from extension (any graphviz filetype supported, such as pdf or png) :param diff (StructureGraph): an additional graph to compare with, will color edges red that do not exist in diff and edges green that are in diff graph but not in the reference graph :param hide_unconnected_nodes: if True, hide unconnected nodes :param hide_image_edges: if True, do not draw edges that go through periodic boundaries :param edge_colors (bool): if True, use node colors to color edges :param node_labels (bool): if True, label nodes with species and site index :param weight_labels (bool): if True, label edges with weights :param image_labels (bool): if True, label edges with their periodic images (usually only used for debugging, edges to periodic images always appear as dashed lines) :param color_scheme (str): "VESTA" or "JMOL" :param keep_dot (bool): keep GraphViz .dot file for later visualization :param algo: any graphviz algo, "neato" (for simple graphs) or "fdp" (for more crowded graphs) usually give good outputs :return: """ if not which(algo): raise RuntimeError("StructureGraph graph drawing requires " "GraphViz binaries to be in the path.") # Developer note: NetworkX also has methods for drawing # graphs using matplotlib, these also work here. However, # a dedicated tool like GraphViz allows for much easier # control over graph appearance and also correctly displays # mutli-graphs (matplotlib can superimpose multiple edges). g = self.graph.copy() g.graph = {"nodesep": 10.0, "dpi": 300, "overlap": "false"} # add display options for nodes for n in g.nodes(): # get label by species name label = "{}({})".format(str(self.structure[n].specie), n) if node_labels else "" # use standard color scheme for nodes c = EL_COLORS[color_scheme].get(str(self.structure[n].specie.symbol), [0, 0, 0]) # get contrasting font color # magic numbers account for perceived luminescence # https://stackoverflow.com/questions/1855884/determine-font-color-based-on-background-color fontcolor = "#000000" if 1 - (c[0] * 0.299 + c[1] * 0.587 + c[2] * 0.114) / 255 < 0.5 else "#ffffff" # convert color to hex string color = "#{:02x}{:02x}{:02x}".format(c[0], c[1], c[2]) g.add_node( n, fillcolor=color, fontcolor=fontcolor, label=label, fontname="Helvetica-bold", style="filled", shape="circle", ) edges_to_delete = [] # add display options for edges for u, v, k, d in g.edges(keys=True, data=True): # retrieve from/to images, set as origin if not defined to_image = d["to_jimage"] # set edge style d["style"] = "solid" if to_image != (0, 0, 0): d["style"] = "dashed" if hide_image_edges: edges_to_delete.append((u, v, k)) # don't show edge directions d["arrowhead"] = "none" # only add labels for images that are not the origin if image_labels: d["headlabel"] = "" if to_image == (0, 0, 0) else "to {}".format((to_image)) d["arrowhead"] = "normal" if d["headlabel"] else "none" # optionally color edges using node colors color_u = g.nodes[u]["fillcolor"] color_v = g.nodes[v]["fillcolor"] d["color_uv"] = "{};0.5:{};0.5".format(color_u, color_v) if edge_colors else "#000000" # optionally add weights to graph if weight_labels: units = g.graph.get("edge_weight_units", "") if d.get("weight"): d["label"] = "{:.2f} {}".format(d["weight"], units) # update edge with our new style attributes g.edges[u, v, k].update(d) # optionally remove periodic image edges, # these can be confusing due to periodic boundaries if hide_image_edges: for edge_to_delete in edges_to_delete: g.remove_edge(*edge_to_delete) # optionally hide unconnected nodes, # these can appear when removing periodic edges if hide_unconnected_nodes: g = g.subgraph([n for n in g.degree() if g.degree()[n] != 0]) # optionally highlight differences with another graph if diff: diff = self.diff(diff, strict=True) green_edges = [] red_edges = [] for u, v, k, d in g.edges(keys=True, data=True): if (u, v, d["to_jimage"]) in diff["self"]: # edge has been deleted red_edges.append((u, v, k)) elif (u, v, d["to_jimage"]) in diff["other"]: # edge has been added green_edges.append((u, v, k)) for u, v, k in green_edges: g.edges[u, v, k].update({"color_uv": "#00ff00"}) for u, v, k in red_edges: g.edges[u, v, k].update({"color_uv": "#ff0000"}) basename, extension = os.path.splitext(filename) extension = extension[1:] write_dot(g, basename + ".dot") with open(filename, "w") as f: args = [algo, "-T", extension, basename + ".dot"] rs = subprocess.Popen(args, stdout=f, stdin=subprocess.PIPE, close_fds=True) rs.communicate() if rs.returncode != 0: raise RuntimeError("{} exited with return code {}.".format(algo, rs.returncode)) if not keep_dot: os.remove(basename + ".dot") @property def types_and_weights_of_connections(self): """ Extract a dictionary summarizing the types and weights of edges in the graph. :return: A dictionary with keys specifying the species involved in a connection in alphabetical order (e.g. string 'Fe-O') and values which are a list of weights for those connections (e.g. bond lengths). """ def get_label(u, v): u_label = self.structure[u].species_string v_label = self.structure[v].species_string return "-".join(sorted((u_label, v_label))) types = defaultdict(list) for u, v, d in self.graph.edges(data=True): label = get_label(u, v) types[label].append(d["weight"]) return dict(types) @property def weight_statistics(self): """ Extract a statistical summary of edge weights present in the graph. :return: A dict with an 'all_weights' list, 'minimum', 'maximum', 'median', 'mean', 'std_dev' """ all_weights = [d.get("weight", None) for u, v, d in self.graph.edges(data=True)] stats = describe(all_weights, nan_policy="omit") return { "all_weights": all_weights, "min": stats.minmax[0], "max": stats.minmax[1], "mean": stats.mean, "variance": stats.variance, } def types_of_coordination_environments(self, anonymous=False): """ Extract information on the different co-ordination environments present in the graph. :param anonymous: if anonymous, will replace specie names with A, B, C, etc. :return: a list of co-ordination environments, e.g. ['Mo-S(6)', 'S-Mo(3)'] """ motifs = set() for idx, site in enumerate(self.structure): centre_sp = site.species_string connected_sites = self.get_connected_sites(idx) connected_species = [connected_site.site.species_string for connected_site in connected_sites] labels = [] for sp in set(connected_species): count = connected_species.count(sp) labels.append((count, sp)) labels = sorted(labels, reverse=True) if anonymous: mapping = {centre_sp: "A"} available_letters = [chr(66 + i) for i in range(25)] for label in labels: sp = label[1] if sp not in mapping: mapping[sp] = available_letters.pop(0) centre_sp = "A" labels = [(label[0], mapping[label[1]]) for label in labels] labels = ["{}({})".format(label[1], label[0]) for label in labels] motif = "{}-{}".format(centre_sp, ",".join(labels)) motifs.add(motif) return sorted(list(motifs)) def as_dict(self): """ As in :Class: `pymatgen.core.Structure` except with using `to_dict_of_dicts` from NetworkX to store graph information. """ d = { "@module": self.__class__.__module__, "@class": self.__class__.__name__, "structure": self.structure.as_dict(), "graphs": json_graph.adjacency_data(self.graph), } return d @classmethod def from_dict(cls, d): """ As in :Class: `pymatgen.core.Structure` except restoring graphs using `from_dict_of_dicts` from NetworkX to restore graph information. """ s = Structure.from_dict(d["structure"]) return cls(s, d["graphs"]) def __mul__(self, scaling_matrix): """ Replicates the graph, creating a supercell, intelligently joining together edges that lie on periodic boundaries. In principle, any operations on the expanded graph could also be done on the original graph, but a larger graph can be easier to visualize and reason about. :param scaling_matrix: same as Structure.__mul__ :return: """ # Developer note: a different approach was also trialed, using # a simple Graph (instead of MultiDiGraph), with node indices # representing both site index and periodic image. Here, the # number of nodes != number of sites in the Structure. This # approach has many benefits, but made it more difficult to # keep the graph in sync with its corresponding Structure. # Broadly, it would be easier to multiply the Structure # *before* generating the StructureGraph, but this isn't # possible when generating the graph using critic2 from # charge density. # Multiplication works by looking for the expected position # of an image node, and seeing if that node exists in the # supercell. If it does, the edge is updated. This is more # computationally expensive than just keeping track of the # which new lattice images present, but should hopefully be # easier to extend to a general 3x3 scaling matrix. # code adapted from Structure.__mul__ scale_matrix = np.array(scaling_matrix, np.int16) if scale_matrix.shape != (3, 3): scale_matrix = np.array(scale_matrix * np.eye(3), np.int16) else: # TODO: test __mul__ with full 3x3 scaling matrices raise NotImplementedError("Not tested with 3x3 scaling matrices yet.") new_lattice = Lattice(np.dot(scale_matrix, self.structure.lattice.matrix)) f_lat = lattice_points_in_supercell(scale_matrix) c_lat = new_lattice.get_cartesian_coords(f_lat) new_sites = [] new_graphs = [] for v in c_lat: # create a map of nodes from original graph to its image mapping = {n: n + len(new_sites) for n in range(len(self.structure))} for idx, site in enumerate(self.structure): s = PeriodicSite( site.species, site.coords + v, new_lattice, properties=site.properties, coords_are_cartesian=True, to_unit_cell=False, ) new_sites.append(s) new_graphs.append(nx.relabel_nodes(self.graph, mapping, copy=True)) new_structure = Structure.from_sites(new_sites) # merge all graphs into one big graph new_g = nx.MultiDiGraph() for new_graph in new_graphs: new_g = nx.union(new_g, new_graph) edges_to_remove = [] # tuple of (u, v, k) edges_to_add = [] # tuple of (u, v, attr_dict) # list of new edges inside supercell # for duplicate checking edges_inside_supercell = [{u, v} for u, v, d in new_g.edges(data=True) if d["to_jimage"] == (0, 0, 0)] new_periodic_images = [] orig_lattice = self.structure.lattice # use k-d tree to match given position to an # existing Site in Structure kd_tree = KDTree(new_structure.cart_coords) # tolerance in Å for sites to be considered equal # this could probably be a lot smaller tol = 0.05 for u, v, k, d in new_g.edges(keys=True, data=True): to_jimage = d["to_jimage"] # for node v # reduce unnecessary checking if to_jimage != (0, 0, 0): # get index in original site n_u = u % len(self.structure) n_v = v % len(self.structure) # get fractional co-ordinates of where atoms defined # by edge are expected to be, relative to original # lattice (keeping original lattice has # significant benefits) v_image_frac = np.add(self.structure[n_v].frac_coords, to_jimage) u_frac = self.structure[n_u].frac_coords # using the position of node u as a reference, # get relative Cartesian co-ordinates of where # atoms defined by edge are expected to be v_image_cart = orig_lattice.get_cartesian_coords(v_image_frac) u_cart = orig_lattice.get_cartesian_coords(u_frac) v_rel = np.subtract(v_image_cart, u_cart) # now retrieve position of node v in # new supercell, and get asgolute Cartesian # co-ordinates of where atoms defined by edge # are expected to be v_expec = new_structure[u].coords + v_rel # now search in new structure for these atoms # query returns (distance, index) v_present = kd_tree.query(v_expec) v_present = v_present[1] if v_present[0] <= tol else None # check if image sites now present in supercell # and if so, delete old edge that went through # periodic boundary if v_present is not None: new_u = u new_v = v_present new_d = d.copy() # node now inside supercell new_d["to_jimage"] = (0, 0, 0) edges_to_remove.append((u, v, k)) # make sure we don't try to add duplicate edges # will remove two edges for everyone one we add if {new_u, new_v} not in edges_inside_supercell: # normalize direction if new_v < new_u: new_u, new_v = new_v, new_u edges_inside_supercell.append({new_u, new_v}) edges_to_add.append((new_u, new_v, new_d)) else: # want to find new_v such that we have # full periodic boundary conditions # so that nodes on one side of supercell # are connected to nodes on opposite side v_expec_frac = new_structure.lattice.get_fractional_coords(v_expec) # find new to_jimage # use np.around to fix issues with finite precision leading to incorrect image v_expec_image = np.around(v_expec_frac, decimals=3) v_expec_image = v_expec_image - v_expec_image % 1 v_expec_frac = np.subtract(v_expec_frac, v_expec_image) v_expec = new_structure.lattice.get_cartesian_coords(v_expec_frac) v_present = kd_tree.query(v_expec) v_present = v_present[1] if v_present[0] <= tol else None if v_present is not None: new_u = u new_v = v_present new_d = d.copy() new_to_jimage = tuple(map(int, v_expec_image)) # normalize direction if new_v < new_u: new_u, new_v = new_v, new_u new_to_jimage = tuple(np.multiply(-1, d["to_jimage"]).astype(int)) new_d["to_jimage"] = new_to_jimage edges_to_remove.append((u, v, k)) if (new_u, new_v, new_to_jimage) not in new_periodic_images: edges_to_add.append((new_u, new_v, new_d)) new_periodic_images.append((new_u, new_v, new_to_jimage)) logger.debug("Removing {} edges, adding {} new edges.".format(len(edges_to_remove), len(edges_to_add))) # add/delete marked edges for edges_to_remove in edges_to_remove: new_g.remove_edge(*edges_to_remove) for (u, v, d) in edges_to_add: new_g.add_edge(u, v, **d) # return new instance of StructureGraph with supercell d = { "@module": self.__class__.__module__, "@class": self.__class__.__name__, "structure": new_structure.as_dict(), "graphs": json_graph.adjacency_data(new_g), } sg = StructureGraph.from_dict(d) return sg def __rmul__(self, other): return self.__mul__(other) @classmethod def _edges_to_string(cls, g): header = "from to to_image " header_line = "---- ---- ------------" edge_weight_name = g.graph["edge_weight_name"] if edge_weight_name: print_weights = ["weight"] edge_label = g.graph["edge_weight_name"] edge_weight_units = g.graph["edge_weight_units"] if edge_weight_units: edge_label += " ({})".format(edge_weight_units) header += " {}".format(edge_label) header_line += " {}".format("-" * max([18, len(edge_label)])) else: print_weights = False s = header + "\n" + header_line + "\n" edges = list(g.edges(data=True)) # sort edges for consistent ordering edges.sort(key=itemgetter(0, 1)) if print_weights: for u, v, data in edges: s += "{:4} {:4} {:12} {:.3e}\n".format( u, v, str(data.get("to_jimage", (0, 0, 0))), data.get("weight", 0) ) else: for u, v, data in edges: s += "{:4} {:4} {:12}\n".format(u, v, str(data.get("to_jimage", (0, 0, 0)))) return s def __str__(self): s = "Structure Graph" s += "\nStructure: \n{}".format(self.structure.__str__()) s += "\nGraph: {}\n".format(self.name) s += self._edges_to_string(self.graph) return s def __repr__(self): s = "Structure Graph" s += "\nStructure: \n{}".format(self.structure.__repr__()) s += "\nGraph: {}\n".format(self.name) s += self._edges_to_string(self.graph) return s def __len__(self): """ :return: length of Structure / number of nodes in graph """ return len(self.structure) def sort(self, key=None, reverse=False): """ Same as Structure.sort(), also remaps nodes in graph. :param key: :param reverse: :return: """ old_structure = self.structure.copy() # sort Structure self.structure._sites = sorted(self.structure._sites, key=key, reverse=reverse) # apply Structure ordering to graph mapping = {idx: self.structure.index(site) for idx, site in enumerate(old_structure)} self.graph = nx.relabel_nodes(self.graph, mapping, copy=True) # normalize directions of edges edges_to_remove = [] edges_to_add = [] for u, v, k, d in self.graph.edges(keys=True, data=True): if v < u: new_v, new_u, new_d = u, v, d.copy() new_d["to_jimage"] = tuple(np.multiply(-1, d["to_jimage"]).astype(int)) edges_to_remove.append((u, v, k)) edges_to_add.append((new_u, new_v, new_d)) # add/delete marked edges for edges_to_remove in edges_to_remove: self.graph.remove_edge(*edges_to_remove) for (u, v, d) in edges_to_add: self.graph.add_edge(u, v, **d) def __copy__(self): return StructureGraph.from_dict(self.as_dict()) def __eq__(self, other): """ Two StructureGraphs are equal if they have equal Structures, and have the same edges between Sites. Edge weights can be different and StructureGraphs can still be considered equal. :param other: StructureGraph :return (bool): """ # sort for consistent node indices # PeriodicSite should have a proper __hash__() value, # using its frac_coords as a convenient key mapping = {tuple(site.frac_coords): self.structure.index(site) for site in other.structure} other_sorted = other.__copy__() other_sorted.sort(key=lambda site: mapping[tuple(site.frac_coords)]) edges = {(u, v, d["to_jimage"]) for u, v, d in self.graph.edges(keys=False, data=True)} edges_other = {(u, v, d["to_jimage"]) for u, v, d in other_sorted.graph.edges(keys=False, data=True)} return (edges == edges_other) and (self.structure == other_sorted.structure) def diff(self, other, strict=True): """ Compares two StructureGraphs. Returns dict with keys 'self', 'other', 'both' with edges that are present in only one StructureGraph ('self' and 'other'), and edges that are present in both. The Jaccard distance is a simple measure of the dissimilarity between two StructureGraphs (ignoring edge weights), and is defined by 1 - (size of the intersection / size of the union) of the sets of edges. This is returned with key 'dist'. Important note: all node indices are in terms of the StructureGraph this method is called from, not the 'other' StructureGraph: there is no guarantee the node indices will be the same if the underlying Structures are ordered differently. :param other: StructureGraph :param strict: if False, will compare bonds from different Structures, with node indices replaced by Species strings, will not count number of occurrences of bonds :return: """ if self.structure != other.structure and strict: return ValueError("Meaningless to compare StructureGraphs if " "corresponding Structures are different.") if strict: # sort for consistent node indices # PeriodicSite should have a proper __hash__() value, # using its frac_coords as a convenient key mapping = {tuple(site.frac_coords): self.structure.index(site) for site in other.structure} other_sorted = other.__copy__() other_sorted.sort(key=lambda site: mapping[tuple(site.frac_coords)]) edges = {(u, v, d["to_jimage"]) for u, v, d in self.graph.edges(keys=False, data=True)} edges_other = {(u, v, d["to_jimage"]) for u, v, d in other_sorted.graph.edges(keys=False, data=True)} else: edges = { (str(self.structure[u].specie), str(self.structure[v].specie)) for u, v, d in self.graph.edges(keys=False, data=True) } edges_other = { (str(other.structure[u].specie), str(other.structure[v].specie)) for u, v, d in other.graph.edges(keys=False, data=True) } if len(edges) == 0 and len(edges_other) == 0: jaccard_dist = 0 # by definition else: jaccard_dist = 1 - len(edges.intersection(edges_other)) / len(edges.union(edges_other)) return { "self": edges - edges_other, "other": edges_other - edges, "both": edges.intersection(edges_other), "dist": jaccard_dist, } def get_subgraphs_as_molecules(self, use_weights=False): """ Retrieve subgraphs as molecules, useful for extracting molecules from periodic crystals. Will only return unique molecules, not any duplicates present in the crystal (a duplicate defined as an isomorphic subgraph). :param use_weights (bool): If True, only treat subgraphs as isomorphic if edges have the same weights. Typically, this means molecules will need to have the same bond lengths to be defined as duplicates, otherwise bond lengths can differ. This is a fairly robust approach, but will treat e.g. enantiomers as being duplicates. :return: list of unique Molecules in Structure """ # creating a supercell is an easy way to extract # molecules (and not, e.g., layers of a 2D crystal) # without adding extra logic if getattr(self, "_supercell_sg", None) is None: self._supercell_sg = supercell_sg = self * (3, 3, 3) # make undirected to find connected subgraphs supercell_sg.graph = nx.Graph(supercell_sg.graph) # find subgraphs all_subgraphs = [supercell_sg.graph.subgraph(c) for c in nx.connected_components(supercell_sg.graph)] # discount subgraphs that lie across *supercell* boundaries # these will subgraphs representing crystals molecule_subgraphs = [] for subgraph in all_subgraphs: intersects_boundary = any(d["to_jimage"] != (0, 0, 0) for u, v, d in subgraph.edges(data=True)) if not intersects_boundary: molecule_subgraphs.append(nx.MultiDiGraph(subgraph)) # add specie names to graph to be able to test for isomorphism for subgraph in molecule_subgraphs: for n in subgraph: subgraph.add_node(n, specie=str(supercell_sg.structure[n].specie)) # now define how we test for isomorphism def node_match(n1, n2): return n1["specie"] == n2["specie"] def edge_match(e1, e2): if use_weights: return e1["weight"] == e2["weight"] return True # prune duplicate subgraphs unique_subgraphs = [] for subgraph in molecule_subgraphs: already_present = [ nx.is_isomorphic(subgraph, g, node_match=node_match, edge_match=edge_match) for g in unique_subgraphs ] if not any(already_present): unique_subgraphs.append(subgraph) # get Molecule objects for each subgraph molecules = [] for subgraph in unique_subgraphs: coords = [supercell_sg.structure[n].coords for n in subgraph.nodes()] species = [supercell_sg.structure[n].specie for n in subgraph.nodes()] molecule = Molecule(species, coords) # shift so origin is at center of mass molecule = molecule.get_centered_molecule() molecules.append(molecule) return molecules class MolGraphSplitError(Exception): """ Raised when a molecule graph is failed to split into two disconnected subgraphs """ pass class MoleculeGraph(MSONable): """ This is a class for annotating a Molecule with bond information, stored in the form of a graph. A "bond" does not necessarily have to be a chemical bond, but can store any kind of information that connects two Sites. """ def __init__(self, molecule, graph_data=None): """ If constructing this class manually, use the `with_empty_graph` method or `with_local_env_strategy` method (using an algorithm provided by the `local_env` module, such as O'Keeffe). This class that contains connection information: relationships between sites represented by a Graph structure, and an associated structure object. This class uses the NetworkX package to store and operate on the graph itself, but contains a lot of helper methods to make associating a graph with a given molecule easier. Use cases for this include storing bonding information, NMR J-couplings, Heisenberg exchange parameters, etc. :param molecule: Molecule object :param graph_data: dict containing graph information in dict format (not intended to be constructed manually, see as_dict method for format) """ if isinstance(molecule, MoleculeGraph): # just make a copy from input graph_data = molecule.as_dict()["graphs"] self.molecule = molecule self.graph = nx.readwrite.json_graph.adjacency_graph(graph_data) # tidy up edge attr dicts, reading to/from json duplicates # information for u, v, k, d in self.graph.edges(keys=True, data=True): if "id" in d: del d["id"] if "key" in d: del d["key"] # ensure images are tuples (conversion to lists happens # when serializing back from json), it's important images # are hashable/immutable if "to_jimage" in d: d["to_jimage"] = tuple(d["to_jimage"]) if "from_jimage" in d: d["from_jimage"] = tuple(d["from_jimage"]) self.set_node_attributes() @classmethod def with_empty_graph(cls, molecule, name="bonds", edge_weight_name=None, edge_weight_units=None): """ Constructor for MoleculeGraph, returns a MoleculeGraph object with an empty graph (no edges, only nodes defined that correspond to Sites in Molecule). :param molecule (Molecule): :param name (str): name of graph, e.g. "bonds" :param edge_weight_name (str): name of edge weights, e.g. "bond_length" or "exchange_constant" :param edge_weight_units (str): name of edge weight units e.g. "Å" or "eV" :return (MoleculeGraph): """ if edge_weight_name and (edge_weight_units is None): raise ValueError( "Please specify units associated " "with your edge weights. Can be " "empty string if arbitrary or " "dimensionless." ) # construct graph with one node per site # graph attributes don't change behavior of graph, # they're just for book-keeping graph = nx.MultiDiGraph( edge_weight_name=edge_weight_name, edge_weight_units=edge_weight_units, name=name, ) graph.add_nodes_from(range(len(molecule))) graph_data = json_graph.adjacency_data(graph) return cls(molecule, graph_data=graph_data) @staticmethod def with_edges(molecule, edges): """ Constructor for MoleculeGraph, using pre-existing or pre-defined edges with optional edge parameters. :param molecule: Molecule object :param edges: dict representing the bonds of the functional group (format: {(u, v): props}, where props is a dictionary of properties, including weight. Props should be None if no additional properties are to be specified. :return: mg, a MoleculeGraph """ mg = MoleculeGraph.with_empty_graph(molecule, name="bonds", edge_weight_name="weight", edge_weight_units="") for edge, props in edges.items(): try: from_index = edge[0] to_index = edge[1] except TypeError: raise ValueError("Edges must be given as (from_index, to_index)" "tuples") if props is not None: if "weight" in props.keys(): weight = props["weight"] del props["weight"] else: weight = None if len(props.items()) == 0: props = None else: weight = None nodes = mg.graph.nodes if not (from_index in nodes and to_index in nodes): raise ValueError( "Edges cannot be added if nodes are not" " present in the graph. Please check your" " indices." ) mg.add_edge(from_index, to_index, weight=weight, edge_properties=props) mg.set_node_attributes() return mg @staticmethod def with_local_env_strategy(molecule, strategy): """ Constructor for MoleculeGraph, using a strategy from :Class: `pymatgen.analysis.local_env`. :param molecule: Molecule object :param strategy: an instance of a :Class: `pymatgen.analysis.local_env.NearNeighbors` object :return: mg, a MoleculeGraph """ if not strategy.molecules_allowed: raise ValueError( "Chosen strategy is not designed for use with molecules! " "Please choose another strategy." ) extend_structure = strategy.extend_structure_molecules mg = MoleculeGraph.with_empty_graph(molecule, name="bonds", edge_weight_name="weight", edge_weight_units="") # NearNeighbor classes only (generally) work with structures # molecules have to be boxed first coords = molecule.cart_coords if extend_structure: a = max(coords[:, 0]) - min(coords[:, 0]) + 100 b = max(coords[:, 1]) - min(coords[:, 1]) + 100 c = max(coords[:, 2]) - min(coords[:, 2]) + 100 structure = molecule.get_boxed_structure(a, b, c, no_cross=True, reorder=False) else: structure = None for n in range(len(molecule)): if structure is None: neighbors = strategy.get_nn_info(molecule, n) else: neighbors = strategy.get_nn_info(structure, n) for neighbor in neighbors: # all bonds in molecules should not cross # (artificial) periodic boundaries if not np.array_equal(neighbor["image"], [0, 0, 0]): continue if n > neighbor["site_index"]: from_index = neighbor["site_index"] to_index = n else: from_index = n to_index = neighbor["site_index"] mg.add_edge( from_index=from_index, to_index=to_index, weight=neighbor["weight"], warn_duplicates=False, ) duplicates = [] for edge in mg.graph.edges: if edge[2] != 0: duplicates.append(edge) for duplicate in duplicates: mg.graph.remove_edge(duplicate[0], duplicate[1], key=duplicate[2]) mg.set_node_attributes() return mg @property def name(self): """ :return: Name of graph """ return self.graph.graph["name"] @property def edge_weight_name(self): """ :return: Name of the edge weight property of graph """ return self.graph.graph["edge_weight_name"] @property def edge_weight_unit(self): """ :return: Units of the edge weight property of graph """ return self.graph.graph["edge_weight_units"] def add_edge( self, from_index, to_index, weight=None, warn_duplicates=True, edge_properties=None, ): """ Add edge to graph. Since physically a 'bond' (or other connection between sites) doesn't have a direction, from_index, from_jimage can be swapped with to_index, to_jimage. However, images will always always be shifted so that from_index < to_index and from_jimage becomes (0, 0, 0). :param from_index: index of site connecting from :param to_index: index of site connecting to :param weight (float): e.g. bond length :param warn_duplicates (bool): if True, will warn if trying to add duplicate edges (duplicate edges will not be added in either case) :param edge_properties (dict): any other information to store on graph edges, similar to Structure's site_properties :return: """ # this is not necessary for the class to work, but # just makes it neater if to_index < from_index: to_index, from_index = from_index, to_index # sanitize types from_index, to_index = int(from_index), int(to_index) # check we're not trying to add a duplicate edge # there should only ever be at most one edge # between two sites existing_edge_data = self.graph.get_edge_data(from_index, to_index) if existing_edge_data and warn_duplicates: warnings.warn( "Trying to add an edge that already exists from " "site {} to site {}.".format(from_index, to_index) ) return # generic container for additional edge properties, # similar to site properties edge_properties = edge_properties or {} if weight: self.graph.add_edge(from_index, to_index, weight=weight, **edge_properties) else: self.graph.add_edge(from_index, to_index, **edge_properties) def insert_node( self, i, species, coords, validate_proximity=False, site_properties=None, edges=None, ): """ A wrapper around Molecule.insert(), which also incorporates the new site into the MoleculeGraph. :param i: Index at which to insert the new site :param species: Species for the new site :param coords: 3x1 array representing coordinates of the new site :param validate_proximity: For Molecule.insert(); if True (default False), distance will be checked to ensure that site can be safely added. :param site_properties: Site properties for Molecule :param edges: List of dicts representing edges to be added to the MoleculeGraph. These edges must include the index of the new site i, and all indices used for these edges should reflect the MoleculeGraph AFTER the insertion, NOT before. Each dict should at least have a "to_index" and "from_index" key, and can also have a "weight" and a "properties" key. :return: """ self.molecule.insert( i, species, coords, validate_proximity=validate_proximity, properties=site_properties, ) mapping = {} for j in range(len(self.molecule) - 1): if j < i: mapping[j] = j else: mapping[j] = j + 1 nx.relabel_nodes(self.graph, mapping, copy=False) self.graph.add_node(i) self.set_node_attributes() if edges is not None: for edge in edges: try: self.add_edge( edge["from_index"], edge["to_index"], weight=edge.get("weight", None), edge_properties=edge.get("properties", None), ) except KeyError: raise RuntimeError("Some edges are invalid.") def set_node_attributes(self): """ Replicates molecule site properties (specie, coords, etc.) in the MoleculeGraph. :return: """ species = {} coords = {} properties = {} for node in self.graph.nodes(): species[node] = self.molecule[node].specie.symbol coords[node] = self.molecule[node].coords properties[node] = self.molecule[node].properties nx.set_node_attributes(self.graph, species, "specie") nx.set_node_attributes(self.graph, coords, "coords") nx.set_node_attributes(self.graph, properties, "properties") def alter_edge(self, from_index, to_index, new_weight=None, new_edge_properties=None): """ Alters either the weight or the edge_properties of an edge in the MoleculeGraph. :param from_index: int :param to_index: int :param new_weight: alter_edge does not require that weight be altered. As such, by default, this is None. If weight is to be changed, it should be a float. :param new_edge_properties: alter_edge does not require that edge_properties be altered. As such, by default, this is None. If any edge properties are to be changed, it should be a dictionary of edge properties to be changed. :return: """ existing_edge = self.graph.get_edge_data(from_index, to_index) # ensure that edge exists before attempting to change it if not existing_edge: raise ValueError( "Edge between {} and {} cannot be altered;\ no edge exists between those sites.".format( from_index, to_index ) ) # Third index should always be 0 because there should only be one edge between any two nodes if new_weight is not None: self.graph[from_index][to_index][0]["weight"] = new_weight if new_edge_properties is not None: for prop in list(new_edge_properties.keys()): self.graph[from_index][to_index][0][prop] = new_edge_properties[prop] def break_edge(self, from_index, to_index, allow_reverse=False): """ Remove an edge from the MoleculeGraph :param from_index: int :param to_index: int :param allow_reverse: If allow_reverse is True, then break_edge will attempt to break both (from_index, to_index) and, failing that, will attempt to break (to_index, from_index). :return: """ # ensure that edge exists before attempting to remove it existing_edge = self.graph.get_edge_data(from_index, to_index) existing_reverse = None if existing_edge: self.graph.remove_edge(from_index, to_index) else: if allow_reverse: existing_reverse = self.graph.get_edge_data(to_index, from_index) if existing_reverse: self.graph.remove_edge(to_index, from_index) else: raise ValueError( "Edge cannot be broken between {} and {};\ no edge exists between those sites.".format( from_index, to_index ) ) def remove_nodes(self, indices): """ A wrapper for Molecule.remove_sites(). :param indices: list of indices in the current Molecule (and graph) to be removed. :return: """ self.molecule.remove_sites(indices) self.graph.remove_nodes_from(indices) mapping = {} for correct, current in enumerate(sorted(self.graph.nodes)): mapping[current] = correct nx.relabel_nodes(self.graph, mapping, copy=False) self.set_node_attributes() def get_disconnected_fragments(self): """ Determine if the MoleculeGraph is connected. If it is not, separate the MoleculeGraph into different MoleculeGraphs, where each resulting MoleculeGraph is a disconnected subgraph of the original. Currently, this function naively assigns the charge of the total molecule to a single submolecule. A later effort will be to actually accurately assign charge. NOTE: This function does not modify the original MoleculeGraph. It creates a copy, modifies that, and returns two or more new MoleculeGraph objects. :return: list of MoleculeGraphs """ if nx.is_weakly_connected(self.graph): return [copy.deepcopy(self)] original = copy.deepcopy(self) sub_mols = list() # Had to use nx.weakly_connected_components because of deprecation # of nx.weakly_connected_component_subgraphs subgraphs = [original.graph.subgraph(c) for c in nx.weakly_connected_components(original.graph)] for subg in subgraphs: nodes = sorted(list(subg.nodes)) # Molecule indices are essentially list-based, so node indices # must be remapped, incrementing from 0 mapping = {} for i, n in enumerate(nodes): mapping[n] = i # just give charge to whatever subgraph has node with index 0 # TODO: actually figure out how to distribute charge if 0 in nodes: charge = self.molecule.charge else: charge = 0 # relabel nodes in graph to match mapping new_graph = nx.relabel_nodes(subg, mapping) species = nx.get_node_attributes(new_graph, "specie") coords = nx.get_node_attributes(new_graph, "coords") raw_props = nx.get_node_attributes(new_graph, "properties") properties = {} for prop_set in raw_props.values(): for prop in prop_set.keys(): if prop in properties: properties[prop].append(prop_set[prop]) else: properties[prop] = [prop_set[prop]] # Site properties must be present for all atoms in the molecule # in order to be used for Molecule instantiation for k, v in properties.items(): if len(v) != len(species): del properties[k] new_mol = Molecule(species, coords, charge=charge, site_properties=properties) graph_data = json_graph.adjacency_data(new_graph) # create new MoleculeGraph sub_mols.append(MoleculeGraph(new_mol, graph_data=graph_data)) return sub_mols def split_molecule_subgraphs(self, bonds, allow_reverse=False, alterations=None): """ Split MoleculeGraph into two or more MoleculeGraphs by breaking a set of bonds. This function uses MoleculeGraph.break_edge repeatedly to create disjoint graphs (two or more separate molecules). This function does not only alter the graph information, but also changes the underlying Molecules. If the bonds parameter does not include sufficient bonds to separate two molecule fragments, then this function will fail. Currently, this function naively assigns the charge of the total molecule to a single submolecule. A later effort will be to actually accurately assign charge. NOTE: This function does not modify the original MoleculeGraph. It creates a copy, modifies that, and returns two or more new MoleculeGraph objects. :param bonds: list of tuples (from_index, to_index) representing bonds to be broken to split the MoleculeGraph. :param alterations: a dict {(from_index, to_index): alt}, where alt is a dictionary including weight and/or edge properties to be changed following the split. :param allow_reverse: If allow_reverse is True, then break_edge will attempt to break both (from_index, to_index) and, failing that, will attempt to break (to_index, from_index). :return: list of MoleculeGraphs """ self.set_node_attributes() original = copy.deepcopy(self) for bond in bonds: original.break_edge(bond[0], bond[1], allow_reverse=allow_reverse) if nx.is_weakly_connected(original.graph): raise MolGraphSplitError( "Cannot split molecule; \ MoleculeGraph is still connected." ) # alter any bonds before partition, to avoid remapping if alterations is not None: for (u, v) in alterations.keys(): if "weight" in alterations[(u, v)]: weight = alterations[(u, v)]["weight"] del alterations[(u, v)]["weight"] edge_properties = alterations[(u, v)] if len(alterations[(u, v)]) != 0 else None original.alter_edge(u, v, new_weight=weight, new_edge_properties=edge_properties) else: original.alter_edge(u, v, new_edge_properties=alterations[(u, v)]) return original.get_disconnected_fragments() def build_unique_fragments(self): """ Find all possible fragment combinations of the MoleculeGraphs (in other words, all connected induced subgraphs) :return: """ self.set_node_attributes() graph = self.graph.to_undirected() # find all possible fragments, aka connected induced subgraphs frag_dict = {} for ii in range(1, len(self.molecule)): for combination in combinations(graph.nodes, ii): mycomp = [] for idx in combination: mycomp.append(str(self.molecule[idx].specie)) mycomp = "".join(sorted(mycomp)) subgraph = nx.subgraph(graph, combination) if nx.is_connected(subgraph): mykey = mycomp + str(len(subgraph.edges())) if mykey not in frag_dict: frag_dict[mykey] = [copy.deepcopy(subgraph)] else: frag_dict[mykey].append(copy.deepcopy(subgraph)) # narrow to all unique fragments using graph isomorphism unique_frag_dict = {} for key in frag_dict: unique_frags = [] for frag in frag_dict[key]: found = False for f in unique_frags: if _isomorphic(frag, f): found = True break if not found: unique_frags.append(frag) unique_frag_dict[key] = copy.deepcopy(unique_frags) # convert back to molecule graphs unique_mol_graph_dict = {} for key in unique_frag_dict: unique_mol_graph_list = [] for fragment in unique_frag_dict[key]: mapping = {e: i for i, e in enumerate(sorted(fragment.nodes))} remapped = nx.relabel_nodes(fragment, mapping) species = nx.get_node_attributes(remapped, "specie") coords = nx.get_node_attributes(remapped, "coords") edges = {} for from_index, to_index, key in remapped.edges: edge_props = fragment.get_edge_data(from_index, to_index, key=key) edges[(from_index, to_index)] = edge_props unique_mol_graph_list.append( self.with_edges( Molecule(species=species, coords=coords, charge=self.molecule.charge), edges, ) ) frag_key = ( str(unique_mol_graph_list[0].molecule.composition.alphabetical_formula) + " E" + str(len(unique_mol_graph_list[0].graph.edges())) ) unique_mol_graph_dict[frag_key] = copy.deepcopy(unique_mol_graph_list) return unique_mol_graph_dict def substitute_group( self, index, func_grp, strategy, bond_order=1, graph_dict=None, strategy_params=None, ): """ Builds off of Molecule.substitute to replace an atom in self.molecule with a functional group. This method also amends self.graph to incorporate the new functional group. NOTE: using a MoleculeGraph will generally produce a different graph compared with using a Molecule or str (when not using graph_dict). :param index: Index of atom to substitute. :param func_grp: Substituent molecule. There are three options: 1. Providing an actual molecule as the input. The first atom must be a DummySpecies X, indicating the position of nearest neighbor. The second atom must be the next nearest atom. For example, for a methyl group substitution, func_grp should be X-CH3, where X is the first site and C is the second site. What the code will do is to remove the index site, and connect the nearest neighbor to the C atom in CH3. The X-C bond indicates the directionality to connect the atoms. 2. A string name. The molecule will be obtained from the relevant template in func_groups.json. 3. A MoleculeGraph object. :param strategy: Class from pymatgen.analysis.local_env. :param bond_order: A specified bond order to calculate the bond length between the attached functional group and the nearest neighbor site. Defaults to 1. :param graph_dict: Dictionary representing the bonds of the functional group (format: {(u, v): props}, where props is a dictionary of properties, including weight. If None, then the algorithm will attempt to automatically determine bonds using one of a list of strategies defined in pymatgen.analysis.local_env. :param strategy_params: dictionary of keyword arguments for strategy. If None, default parameters will be used. :return: """ def map_indices(grp): grp_map = {} # Get indices now occupied by functional group # Subtracting 1 because the dummy atom X should not count atoms = len(grp) - 1 offset = len(self.molecule) - atoms for i in range(atoms): grp_map[i] = i + offset return grp_map # Work is simplified if a graph is already in place if isinstance(func_grp, MoleculeGraph): self.molecule.substitute(index, func_grp.molecule, bond_order=bond_order) mapping = map_indices(func_grp.molecule) for (u, v) in list(func_grp.graph.edges()): edge_props = func_grp.graph.get_edge_data(u, v)[0] weight = None if "weight" in edge_props.keys(): weight = edge_props["weight"] del edge_props["weight"] self.add_edge(mapping[u], mapping[v], weight=weight, edge_properties=edge_props) else: if isinstance(func_grp, Molecule): func_grp = copy.deepcopy(func_grp) else: try: func_grp = copy.deepcopy(FunctionalGroups[func_grp]) except Exception: raise RuntimeError("Can't find functional group in list. " "Provide explicit coordinate instead") self.molecule.substitute(index, func_grp, bond_order=bond_order) mapping = map_indices(func_grp) # Remove dummy atom "X" func_grp.remove_species("X") if graph_dict is not None: for (u, v) in graph_dict.keys(): edge_props = graph_dict[(u, v)] if "weight" in edge_props.keys(): weight = edge_props["weight"] del edge_props["weight"] self.add_edge( mapping[u], mapping[v], weight=weight, edge_properties=edge_props, ) else: if strategy_params is None: strategy_params = {} strat = strategy(**strategy_params) graph = self.with_local_env_strategy(func_grp, strat) for (u, v) in list(graph.graph.edges()): edge_props = graph.graph.get_edge_data(u, v)[0] weight = None if "weight" in edge_props.keys(): weight = edge_props["weight"] del edge_props["weight"] if 0 not in list(graph.graph.nodes()): # If graph indices have different indexing u, v = (u - 1), (v - 1) self.add_edge( mapping[u], mapping[v], weight=weight, edge_properties=edge_props, ) def replace_group( self, index, func_grp, strategy, bond_order=1, graph_dict=None, strategy_params=None, ): """ Builds off of Molecule.substitute and MoleculeGraph.substitute_group to replace a functional group in self.molecule with a functional group. This method also amends self.graph to incorporate the new functional group. TODO: Figure out how to replace into a ring structure. :param index: Index of atom to substitute. :param func_grp: Substituent molecule. There are three options: 1. Providing an actual molecule as the input. The first atom must be a DummySpecies X, indicating the position of nearest neighbor. The second atom must be the next nearest atom. For example, for a methyl group substitution, func_grp should be X-CH3, where X is the first site and C is the second site. What the code will do is to remove the index site, and connect the nearest neighbor to the C atom in CH3. The X-C bond indicates the directionality to connect the atoms. 2. A string name. The molecule will be obtained from the relevant template in func_groups.json. 3. A MoleculeGraph object. :param strategy: Class from pymatgen.analysis.local_env. :param bond_order: A specified bond order to calculate the bond length between the attached functional group and the nearest neighbor site. Defaults to 1. :param graph_dict: Dictionary representing the bonds of the functional group (format: {(u, v): props}, where props is a dictionary of properties, including weight. If None, then the algorithm will attempt to automatically determine bonds using one of a list of strategies defined in pymatgen.analysis.local_env. :param strategy_params: dictionary of keyword arguments for strategy. If None, default parameters will be used. :return: """ self.set_node_attributes() neighbors = self.get_connected_sites(index) # If the atom at index is terminal if len(neighbors) == 1: self.substitute_group( index, func_grp, strategy, bond_order=bond_order, graph_dict=graph_dict, strategy_params=strategy_params, ) else: rings = self.find_rings(including=[index]) if len(rings) != 0: raise RuntimeError( "Currently functional group replacement" "cannot occur at an atom within a ring" "structure." ) to_remove = set() sizes = dict() disconnected = self.graph.to_undirected() disconnected.remove_node(index) for neighbor in neighbors: sizes[neighbor[2]] = len(nx.descendants(disconnected, neighbor[2])) keep = max(sizes, key=lambda x: sizes[x]) for i in sizes.keys(): if i != keep: to_remove.add(i) self.remove_nodes(list(to_remove)) self.substitute_group( index, func_grp, strategy, bond_order=bond_order, graph_dict=graph_dict, strategy_params=strategy_params, ) def find_rings(self, including=None): """ Find ring structures in the MoleculeGraph. :param including: list of site indices. If including is not None, then find_rings will only return those rings including the specified sites. By default, this parameter is None, and all rings will be returned. :return: dict {index:cycle}. Each entry will be a ring (cycle, in graph theory terms) including the index found in the Molecule. If there is no cycle including an index, the value will be an empty list. """ # Copies self.graph such that all edges (u, v) matched by edges (v, u) undirected = self.graph.to_undirected() directed = undirected.to_directed() cycles_nodes = [] cycles_edges = [] # Remove all two-edge cycles all_cycles = [c for c in nx.simple_cycles(directed) if len(c) > 2] # Using to_directed() will mean that each cycle always appears twice # So, we must also remove duplicates unique_sorted = [] unique_cycles = [] for cycle in all_cycles: if sorted(cycle) not in unique_sorted: unique_sorted.append(sorted(cycle)) unique_cycles.append(cycle) if including is None: cycles_nodes = unique_cycles else: for i in including: for cycle in unique_cycles: if i in cycle and cycle not in cycles_nodes: cycles_nodes.append(cycle) for cycle in cycles_nodes: edges = [] for i, e in enumerate(cycle): edges.append((cycle[i - 1], e)) cycles_edges.append(edges) return cycles_edges def get_connected_sites(self, n): """ Returns a named tuple of neighbors of site n: periodic_site, jimage, index, weight. Index is the index of the corresponding site in the original structure, weight can be None if not defined. :param n: index of Site in Molecule :param jimage: lattice vector of site :return: list of ConnectedSite tuples, sorted by closest first """ connected_sites = set() out_edges = list(self.graph.out_edges(n, data=True)) in_edges = list(self.graph.in_edges(n, data=True)) for u, v, d in out_edges + in_edges: weight = d.get("weight", None) if v == n: site = self.molecule[u] dist = self.molecule[v].distance(self.molecule[u]) connected_site = ConnectedSite(site=site, jimage=(0, 0, 0), index=u, weight=weight, dist=dist) else: site = self.molecule[v] dist = self.molecule[u].distance(self.molecule[v]) connected_site = ConnectedSite(site=site, jimage=(0, 0, 0), index=v, weight=weight, dist=dist) connected_sites.add(connected_site) # return list sorted by closest sites first connected_sites = list(connected_sites) connected_sites.sort(key=lambda x: x.dist) return connected_sites def get_coordination_of_site(self, n): """ Returns the number of neighbors of site n. In graph terms, simply returns degree of node corresponding to site n. :param n: index of site :return (int): """ number_of_self_loops = sum([1 for n, v in self.graph.edges(n) if n == v]) return self.graph.degree(n) - number_of_self_loops def draw_graph_to_file( self, filename="graph", diff=None, hide_unconnected_nodes=False, hide_image_edges=True, edge_colors=False, node_labels=False, weight_labels=False, image_labels=False, color_scheme="VESTA", keep_dot=False, algo="fdp", ): """ Draws graph using GraphViz. The networkx graph object itself can also be drawn with networkx's in-built graph drawing methods, but note that this might give misleading results for multigraphs (edges are super-imposed on each other). If visualization is difficult to interpret, `hide_image_edges` can help, especially in larger graphs. :param filename: filename to output, will detect filetype from extension (any graphviz filetype supported, such as pdf or png) :param diff (StructureGraph): an additional graph to compare with, will color edges red that do not exist in diff and edges green that are in diff graph but not in the reference graph :param hide_unconnected_nodes: if True, hide unconnected nodes :param hide_image_edges: if True, do not draw edges that go through periodic boundaries :param edge_colors (bool): if True, use node colors to color edges :param node_labels (bool): if True, label nodes with species and site index :param weight_labels (bool): if True, label edges with weights :param image_labels (bool): if True, label edges with their periodic images (usually only used for debugging, edges to periodic images always appear as dashed lines) :param color_scheme (str): "VESTA" or "JMOL" :param keep_dot (bool): keep GraphViz .dot file for later visualization :param algo: any graphviz algo, "neato" (for simple graphs) or "fdp" (for more crowded graphs) usually give good outputs :return: """ if not which(algo): raise RuntimeError("StructureGraph graph drawing requires " "GraphViz binaries to be in the path.") # Developer note: NetworkX also has methods for drawing # graphs using matplotlib, these also work here. However, # a dedicated tool like GraphViz allows for much easier # control over graph appearance and also correctly displays # mutli-graphs (matplotlib can superimpose multiple edges). g = self.graph.copy() g.graph = {"nodesep": 10.0, "dpi": 300, "overlap": "false"} # add display options for nodes for n in g.nodes(): # get label by species name label = "{}({})".format(str(self.molecule[n].specie), n) if node_labels else "" # use standard color scheme for nodes c = EL_COLORS[color_scheme].get(str(self.molecule[n].specie.symbol), [0, 0, 0]) # get contrasting font color # magic numbers account for perceived luminescence # https://stackoverflow.com/questions/1855884/determine-font-color-based-on-background-color fontcolor = "#000000" if 1 - (c[0] * 0.299 + c[1] * 0.587 + c[2] * 0.114) / 255 < 0.5 else "#ffffff" # convert color to hex string color = "#{:02x}{:02x}{:02x}".format(c[0], c[1], c[2]) g.add_node( n, fillcolor=color, fontcolor=fontcolor, label=label, fontname="Helvetica-bold", style="filled", shape="circle", ) edges_to_delete = [] # add display options for edges for u, v, k, d in g.edges(keys=True, data=True): # retrieve from/to images, set as origin if not defined if "to_image" in d: to_image = d["to_jimage"] else: to_image = (0, 0, 0) # set edge style d["style"] = "solid" if to_image != (0, 0, 0): d["style"] = "dashed" if hide_image_edges: edges_to_delete.append((u, v, k)) # don't show edge directions d["arrowhead"] = "none" # only add labels for images that are not the origin if image_labels: d["headlabel"] = "" if to_image == (0, 0, 0) else "to {}".format((to_image)) d["arrowhead"] = "normal" if d["headlabel"] else "none" # optionally color edges using node colors color_u = g.node[u]["fillcolor"] color_v = g.node[v]["fillcolor"] d["color_uv"] = "{};0.5:{};0.5".format(color_u, color_v) if edge_colors else "#000000" # optionally add weights to graph if weight_labels: units = g.graph.get("edge_weight_units", "") if d.get("weight"): d["label"] = "{:.2f} {}".format(d["weight"], units) # update edge with our new style attributes g.edges[u, v, k].update(d) # optionally remove periodic image edges, # these can be confusing due to periodic boundaries if hide_image_edges: for edge_to_delete in edges_to_delete: g.remove_edge(*edge_to_delete) # optionally hide unconnected nodes, # these can appear when removing periodic edges if hide_unconnected_nodes: g = g.subgraph([n for n in g.degree() if g.degree()[n] != 0]) # optionally highlight differences with another graph if diff: diff = self.diff(diff, strict=True) green_edges = [] red_edges = [] for u, v, k, d in g.edges(keys=True, data=True): if (u, v, d["to_jimage"]) in diff["self"]: # edge has been deleted red_edges.append((u, v, k)) elif (u, v, d["to_jimage"]) in diff["other"]: # edge has been added green_edges.append((u, v, k)) for u, v, k in green_edges: g.edges[u, v, k].update({"color_uv": "#00ff00"}) for u, v, k in red_edges: g.edges[u, v, k].update({"color_uv": "#ff0000"}) basename, extension = os.path.splitext(filename) extension = extension[1:] write_dot(g, basename + ".dot") with open(filename, "w") as f: args = [algo, "-T", extension, basename + ".dot"] rs = subprocess.Popen(args, stdout=f, stdin=subprocess.PIPE, close_fds=True) rs.communicate() if rs.returncode != 0: raise RuntimeError("{} exited with return code {}.".format(algo, rs.returncode)) if not keep_dot: os.remove(basename + ".dot") def as_dict(self): """ As in :Class: `pymatgen.core.Molecule` except with using `to_dict_of_dicts` from NetworkX to store graph information. """ d = { "@module": self.__class__.__module__, "@class": self.__class__.__name__, "molecule": self.molecule.as_dict(), "graphs": json_graph.adjacency_data(self.graph), } return d @classmethod def from_dict(cls, d): """ As in :Class: `pymatgen.core.Molecule` except restoring graphs using `from_dict_of_dicts` from NetworkX to restore graph information. """ m = Molecule.from_dict(d["molecule"]) return cls(m, d["graphs"]) @classmethod def _edges_to_string(cls, g): header = "from to to_image " header_line = "---- ---- ------------" edge_weight_name = g.graph["edge_weight_name"] if edge_weight_name: print_weights = ["weight"] edge_label = g.graph["edge_weight_name"] edge_weight_units = g.graph["edge_weight_units"] if edge_weight_units: edge_label += " ({})".format(edge_weight_units) header += " {}".format(edge_label) header_line += " {}".format("-" * max([18, len(edge_label)])) else: print_weights = False s = header + "\n" + header_line + "\n" edges = list(g.edges(data=True)) # sort edges for consistent ordering edges.sort(key=itemgetter(0, 1)) if print_weights: for u, v, data in edges: s += "{:4} {:4} {:12} {:.3e}\n".format( u, v, str(data.get("to_jimage", (0, 0, 0))), data.get("weight", 0) ) else: for u, v, data in edges: s += "{:4} {:4} {:12}\n".format(u, v, str(data.get("to_jimage", (0, 0, 0)))) return s def __str__(self): s = "Molecule Graph" s += "\nMolecule: \n{}".format(self.molecule.__str__()) s += "\nGraph: {}\n".format(self.name) s += self._edges_to_string(self.graph) return s def __repr__(self): s = "Molecule Graph" s += "\nMolecule: \n{}".format(self.molecule.__repr__()) s += "\nGraph: {}\n".format(self.name) s += self._edges_to_string(self.graph) return s def __len__(self): """ :return: length of Molecule / number of nodes in graph """ return len(self.molecule) def sort(self, key=None, reverse=False): """ Same as Molecule.sort(), also remaps nodes in graph. :param key: :param reverse: :return: """ old_molecule = self.molecule.copy() # sort Molecule self.molecule._sites = sorted(self.molecule._sites, key=key, reverse=reverse) # apply Molecule ordering to graph mapping = {idx: self.molecule.index(site) for idx, site in enumerate(old_molecule)} self.graph = nx.relabel_nodes(self.graph, mapping, copy=True) # normalize directions of edges edges_to_remove = [] edges_to_add = [] for u, v, k, d in self.graph.edges(keys=True, data=True): if v < u: new_v, new_u, new_d = u, v, d.copy() new_d["to_jimage"] = (0, 0, 0) edges_to_remove.append((u, v, k)) edges_to_add.append((new_u, new_v, new_d)) # add/delete marked edges for edges_to_remove in edges_to_remove: self.graph.remove_edge(*edges_to_remove) for (u, v, d) in edges_to_add: self.graph.add_edge(u, v, **d) def __copy__(self): return MoleculeGraph.from_dict(self.as_dict()) def __eq__(self, other): """ Two MoleculeGraphs are equal if they have equal Molecules, and have the same edges between Sites. Edge weights can be different and MoleculeGraphs can still be considered equal. :param other: MoleculeGraph :return (bool): """ # sort for consistent node indices # PeriodicSite should have a proper __hash__() value, # using its frac_coords as a convenient key try: mapping = {tuple(site.coords): self.molecule.index(site) for site in other.molecule} except ValueError: return False other_sorted = other.__copy__() other_sorted.sort(key=lambda site: mapping[tuple(site.coords)]) edges = {(u, v) for u, v, d in self.graph.edges(keys=False, data=True)} edges_other = {(u, v) for u, v, d in other_sorted.graph.edges(keys=False, data=True)} return (edges == edges_other) and (self.molecule == other_sorted.molecule) def isomorphic_to(self, other): """ Checks if the graphs of two MoleculeGraphs are isomorphic to one another. In order to prevent problems with misdirected edges, both graphs are converted into undirected nx.Graph objects. :param other: MoleculeGraph object to be compared. :return: bool """ if len(self.molecule) != len(other.molecule): return False if self.molecule.composition.alphabetical_formula != other.molecule.composition.alphabetical_formula: return False if len(self.graph.edges()) != len(other.graph.edges()): return False return _isomorphic(self.graph, other.graph) def diff(self, other, strict=True): """ Compares two MoleculeGraphs. Returns dict with keys 'self', 'other', 'both' with edges that are present in only one MoleculeGraph ('self' and 'other'), and edges that are present in both. The Jaccard distance is a simple measure of the dissimilarity between two MoleculeGraphs (ignoring edge weights), and is defined by 1 - (size of the intersection / size of the union) of the sets of edges. This is returned with key 'dist'. Important note: all node indices are in terms of the MoleculeGraph this method is called from, not the 'other' MoleculeGraph: there is no guarantee the node indices will be the same if the underlying Molecules are ordered differently. :param other: MoleculeGraph :param strict: if False, will compare bonds from different Molecules, with node indices replaced by Species strings, will not count number of occurrences of bonds :return: """ if self.molecule != other.molecule and strict: return ValueError("Meaningless to compare MoleculeGraphs if " "corresponding Molecules are different.") if strict: # sort for consistent node indices # PeriodicSite should have a proper __hash__() value, # using its frac_coords as a convenient key mapping = {tuple(site.frac_coords): self.molecule.index(site) for site in other.molecule} other_sorted = other.__copy__() other_sorted.sort(key=lambda site: mapping[tuple(site.frac_coords)]) edges = {(u, v, d.get("to_jimage", (0, 0, 0))) for u, v, d in self.graph.edges(keys=False, data=True)} edges_other = { (u, v, d.get("to_jimage", (0, 0, 0))) for u, v, d in other_sorted.graph.edges(keys=False, data=True) } else: edges = { (str(self.molecule[u].specie), str(self.molecule[v].specie)) for u, v, d in self.graph.edges(keys=False, data=True) } edges_other = { (str(other.structure[u].specie), str(other.structure[v].specie)) for u, v, d in other.graph.edges(keys=False, data=True) } if len(edges) == 0 and len(edges_other) == 0: jaccard_dist = 0 # by definition else: jaccard_dist = 1 - len(edges.intersection(edges_other)) / len(edges.union(edges_other)) return { "self": edges - edges_other, "other": edges_other - edges, "both": edges.intersection(edges_other), "dist": jaccard_dist, }
37.748479
118
0.579393
13,644
111,660
4.59528
0.079962
0.003445
0.010144
0.013015
0.679033
0.65538
0.635299
0.623082
0.608074
0.597068
0
0.006777
0.33791
111,660
2,957
119
37.761245
0.841307
0.33225
0
0.573937
0
0
0.062088
0
0
0
0
0.001015
0
1
0.049966
false
0.000675
0.01553
0.002701
0.113437
0.004051
0
0
0
null
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
null
0
0
0
0
0
0
0
0
0
0
0
0
1
0
811c0a3b1e48996b84a2d4750219f62c35f29d83
1,064
py
Python
articles/views.py
Ahmed-skb/blogyfy
2cfa3d9503f1846ccd89c2bf1934293eb97ad44a
[ "MIT" ]
null
null
null
articles/views.py
Ahmed-skb/blogyfy
2cfa3d9503f1846ccd89c2bf1934293eb97ad44a
[ "MIT" ]
null
null
null
articles/views.py
Ahmed-skb/blogyfy
2cfa3d9503f1846ccd89c2bf1934293eb97ad44a
[ "MIT" ]
null
null
null
from django.shortcuts import render, redirect from django.http import HttpResponse from .models import Article from django.contrib.auth.decorators import login_required from . import forms def Articles(request): articles = Article.objects.all().order_by('date') return render(request, 'articles/article_list.html', {'articles': articles}) def article_detail(request, slug): # return HttpResponse(slug) article = Article.objects.get(slug=slug) return render(request, 'articles/article_details.html', {'article': article}) @login_required(login_url="/accounts/login") def article_create(request): if request.method == 'POST': form = forms.CreateArticle(request.POST, request.FILES) if form.is_valid(): #save article to DB instance = form.save(commit=False) instance.author = request.user instance.save( ) return redirect ('articles:list') else: form = forms.CreateArticle() return render(request, 'articles/article_create.html', {'form':form})
34.322581
81
0.693609
125
1,064
5.824
0.408
0.082418
0.120879
0.111264
0.14011
0
0
0
0
0
0
0
0.190789
1,064
30
82
35.466667
0.845528
0.041353
0
0
0
0
0.135693
0.081613
0
0
0
0
0
1
0.130435
false
0
0.217391
0
0.521739
0
0
0
0
null
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
null
0
0
0
0
0
0
0
0
0
0
0
0
1
0
8120aa4d76824186b0ed660869921ca64f9eaede
667
py
Python
wsgi.py
javicacheiro/salt-git-synchronizer-proxy
c93de5c0b26afe2b9ec72156497894df7f15d692
[ "Apache-2.0" ]
null
null
null
wsgi.py
javicacheiro/salt-git-synchronizer-proxy
c93de5c0b26afe2b9ec72156497894df7f15d692
[ "Apache-2.0" ]
null
null
null
wsgi.py
javicacheiro/salt-git-synchronizer-proxy
c93de5c0b26afe2b9ec72156497894df7f15d692
[ "Apache-2.0" ]
null
null
null
#!/usr/bin/env python import logging import sys from app import app as application def setup_flask_logging(): # Log to stdout handler = logging.StreamHandler(sys.stdout) # Log to a file #handler = logging.FileHandler('./application.log') handler.setLevel(logging.INFO) handler.setFormatter(logging.Formatter( '%(asctime)s [%(funcName)s] %(levelname)s: %(message)s ' )) application.logger.addHandler(handler) # Set default log level for the general logger # each handler can then restrict the messages logged application.logger.setLevel(logging.INFO) setup_flask_logging() if __name__ == '__main__': application.run()
24.703704
64
0.721139
84
667
5.583333
0.583333
0.042644
0.072495
0
0
0
0
0
0
0
0
0
0.169415
667
26
65
25.653846
0.84657
0.290855
0
0
0
0
0.132762
0
0
0
0
0
0
1
0.071429
false
0
0.214286
0
0.285714
0
0
0
0
null
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
null
0
0
0
0
0
0
0
0
0
0
0
0
1
0
81229a54be34a90af845ce0b0f142321ea5ad691
11,115
py
Python
youtube_dl/extractor/turner.py
jonyg80/youtube-dl
ef3a87fb77891329de1d3dbebfee53bf50645261
[ "Unlicense" ]
66,635
2019-03-10T21:34:18.000Z
2022-03-31T23:50:31.000Z
youtube_dl/extractor/turner.py
jonyg80/youtube-dl
ef3a87fb77891329de1d3dbebfee53bf50645261
[ "Unlicense" ]
10,936
2019-03-10T21:35:47.000Z
2022-03-31T23:46:52.000Z
youtube_dl/extractor/turner.py
jonyg80/youtube-dl
ef3a87fb77891329de1d3dbebfee53bf50645261
[ "Unlicense" ]
15,194
2019-03-10T21:09:27.000Z
2022-03-31T22:13:49.000Z
# coding: utf-8 from __future__ import unicode_literals import re from .adobepass import AdobePassIE from ..compat import compat_str from ..utils import ( fix_xml_ampersands, xpath_text, int_or_none, determine_ext, float_or_none, parse_duration, xpath_attr, update_url_query, ExtractorError, strip_or_none, url_or_none, ) class TurnerBaseIE(AdobePassIE): _AKAMAI_SPE_TOKEN_CACHE = {} def _extract_timestamp(self, video_data): return int_or_none(xpath_attr(video_data, 'dateCreated', 'uts')) def _add_akamai_spe_token(self, tokenizer_src, video_url, content_id, ap_data, custom_tokenizer_query=None): secure_path = self._search_regex(r'https?://[^/]+(.+/)', video_url, 'secure path') + '*' token = self._AKAMAI_SPE_TOKEN_CACHE.get(secure_path) if not token: query = { 'path': secure_path, } if custom_tokenizer_query: query.update(custom_tokenizer_query) else: query['videoId'] = content_id if ap_data.get('auth_required'): query['accessToken'] = self._extract_mvpd_auth(ap_data['url'], content_id, ap_data['site_name'], ap_data['site_name']) auth = self._download_xml( tokenizer_src, content_id, query=query) error_msg = xpath_text(auth, 'error/msg') if error_msg: raise ExtractorError(error_msg, expected=True) token = xpath_text(auth, 'token') if not token: return video_url self._AKAMAI_SPE_TOKEN_CACHE[secure_path] = token return video_url + '?hdnea=' + token def _extract_cvp_info(self, data_src, video_id, path_data={}, ap_data={}, fatal=False): video_data = self._download_xml( data_src, video_id, transform_source=lambda s: fix_xml_ampersands(s).strip(), fatal=fatal) if not video_data: return {} video_id = video_data.attrib['id'] title = xpath_text(video_data, 'headline', fatal=True) content_id = xpath_text(video_data, 'contentId') or video_id # rtmp_src = xpath_text(video_data, 'akamai/src') # if rtmp_src: # split_rtmp_src = rtmp_src.split(',') # if len(split_rtmp_src) == 2: # rtmp_src = split_rtmp_src[1] # aifp = xpath_text(video_data, 'akamai/aifp', default='') urls = [] formats = [] thumbnails = [] subtitles = {} rex = re.compile( r'(?P<width>[0-9]+)x(?P<height>[0-9]+)(?:_(?P<bitrate>[0-9]+))?') # Possible formats locations: files/file, files/groupFiles/files # and maybe others for video_file in video_data.findall('.//file'): video_url = url_or_none(video_file.text.strip()) if not video_url: continue ext = determine_ext(video_url) if video_url.startswith('/mp4:protected/'): continue # TODO Correct extraction for these files # protected_path_data = path_data.get('protected') # if not protected_path_data or not rtmp_src: # continue # protected_path = self._search_regex( # r'/mp4:(.+)\.[a-z0-9]', video_url, 'secure path') # auth = self._download_webpage( # protected_path_data['tokenizer_src'], query={ # 'path': protected_path, # 'videoId': content_id, # 'aifp': aifp, # }) # token = xpath_text(auth, 'token') # if not token: # continue # video_url = rtmp_src + video_url + '?' + token elif video_url.startswith('/secure/'): secure_path_data = path_data.get('secure') if not secure_path_data: continue video_url = self._add_akamai_spe_token( secure_path_data['tokenizer_src'], secure_path_data['media_src'] + video_url, content_id, ap_data) elif not re.match('https?://', video_url): base_path_data = path_data.get(ext, path_data.get('default', {})) media_src = base_path_data.get('media_src') if not media_src: continue video_url = media_src + video_url if video_url in urls: continue urls.append(video_url) format_id = video_file.get('bitrate') if ext in ('scc', 'srt', 'vtt'): subtitles.setdefault('en', []).append({ 'ext': ext, 'url': video_url, }) elif ext == 'png': thumbnails.append({ 'id': format_id, 'url': video_url, }) elif ext == 'smil': formats.extend(self._extract_smil_formats( video_url, video_id, fatal=False)) elif re.match(r'https?://[^/]+\.akamaihd\.net/[iz]/', video_url): formats.extend(self._extract_akamai_formats( video_url, video_id, { 'hds': path_data.get('f4m', {}).get('host'), # nba.cdn.turner.com, ht.cdn.turner.com, ht2.cdn.turner.com # ht3.cdn.turner.com, i.cdn.turner.com, s.cdn.turner.com # ssl.cdn.turner.com 'http': 'pmd.cdn.turner.com', })) elif ext == 'm3u8': m3u8_formats = self._extract_m3u8_formats( video_url, video_id, 'mp4', m3u8_id=format_id or 'hls', fatal=False) if '/secure/' in video_url and '?hdnea=' in video_url: for f in m3u8_formats: f['_seekable'] = False formats.extend(m3u8_formats) elif ext == 'f4m': formats.extend(self._extract_f4m_formats( update_url_query(video_url, {'hdcore': '3.7.0'}), video_id, f4m_id=format_id or 'hds', fatal=False)) else: f = { 'format_id': format_id, 'url': video_url, 'ext': ext, } mobj = rex.search(video_url) if mobj: f.update({ 'width': int(mobj.group('width')), 'height': int(mobj.group('height')), 'tbr': int_or_none(mobj.group('bitrate')), }) elif isinstance(format_id, compat_str): if format_id.isdigit(): f['tbr'] = int(format_id) else: mobj = re.match(r'ios_(audio|[0-9]+)$', format_id) if mobj: if mobj.group(1) == 'audio': f.update({ 'vcodec': 'none', 'ext': 'm4a', }) else: f['tbr'] = int(mobj.group(1)) formats.append(f) self._sort_formats(formats) for source in video_data.findall('closedCaptions/source'): for track in source.findall('track'): track_url = url_or_none(track.get('url')) if not track_url or track_url.endswith('/big'): continue lang = track.get('lang') or track.get('label') or 'en' subtitles.setdefault(lang, []).append({ 'url': track_url, 'ext': { 'scc': 'scc', 'webvtt': 'vtt', 'smptett': 'tt', }.get(source.get('format')) }) thumbnails.extend({ 'id': image.get('cut') or image.get('name'), 'url': image.text, 'width': int_or_none(image.get('width')), 'height': int_or_none(image.get('height')), } for image in video_data.findall('images/image')) is_live = xpath_text(video_data, 'isLive') == 'true' return { 'id': video_id, 'title': self._live_title(title) if is_live else title, 'formats': formats, 'subtitles': subtitles, 'thumbnails': thumbnails, 'thumbnail': xpath_text(video_data, 'poster'), 'description': strip_or_none(xpath_text(video_data, 'description')), 'duration': parse_duration(xpath_text(video_data, 'length') or xpath_text(video_data, 'trt')), 'timestamp': self._extract_timestamp(video_data), 'upload_date': xpath_attr(video_data, 'metas', 'version'), 'series': xpath_text(video_data, 'showTitle'), 'season_number': int_or_none(xpath_text(video_data, 'seasonNumber')), 'episode_number': int_or_none(xpath_text(video_data, 'episodeNumber')), 'is_live': is_live, } def _extract_ngtv_info(self, media_id, tokenizer_query, ap_data=None): streams_data = self._download_json( 'http://medium.ngtv.io/media/%s/tv' % media_id, media_id)['media']['tv'] duration = None chapters = [] formats = [] for supported_type in ('unprotected', 'bulkaes'): stream_data = streams_data.get(supported_type, {}) m3u8_url = stream_data.get('secureUrl') or stream_data.get('url') if not m3u8_url: continue if stream_data.get('playlistProtection') == 'spe': m3u8_url = self._add_akamai_spe_token( 'http://token.ngtv.io/token/token_spe', m3u8_url, media_id, ap_data or {}, tokenizer_query) formats.extend(self._extract_m3u8_formats( m3u8_url, media_id, 'mp4', m3u8_id='hls', fatal=False)) duration = float_or_none(stream_data.get('totalRuntime')) if not chapters: for chapter in stream_data.get('contentSegments', []): start_time = float_or_none(chapter.get('start')) chapter_duration = float_or_none(chapter.get('duration')) if start_time is None or chapter_duration is None: continue chapters.append({ 'start_time': start_time, 'end_time': start_time + chapter_duration, }) self._sort_formats(formats) return { 'formats': formats, 'chapters': chapters, 'duration': duration, }
42.586207
134
0.506163
1,173
11,115
4.499574
0.197783
0.045472
0.03183
0.040925
0.14172
0.056461
0.034862
0.025009
0
0
0
0.007947
0.377328
11,115
260
135
42.75
0.75466
0.087449
0
0.171296
0
0.00463
0.106288
0.011568
0
0
0
0.003846
0
1
0.018519
false
0.009259
0.023148
0.00463
0.078704
0
0
0
0
null
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
null
0
0
0
0
0
0
0
0
0
0
0
0
1
0
81231c1bf7b40bb3a00ed96fce4e7257f1de32c5
1,188
py
Python
ml/sandbox/00-data.py
robk-dev/algo-trading
aa8d76ee739431ab24407fe094e0753c588dc8c6
[ "MIT" ]
1
2021-03-14T23:52:04.000Z
2021-03-14T23:52:04.000Z
ml/sandbox/00-data.py
robk-dev/algo-trading
aa8d76ee739431ab24407fe094e0753c588dc8c6
[ "MIT" ]
null
null
null
ml/sandbox/00-data.py
robk-dev/algo-trading
aa8d76ee739431ab24407fe094e0753c588dc8c6
[ "MIT" ]
null
null
null
from alpha_vantage.timeseries import TimeSeries from pprint import pprint import json import argparse def save_dataset(symbol='MSFT', time_window='daily_adj'): credentials = json.load(open('creds.json', 'r')) api_key = credentials['av_api_key'] print(symbol, time_window) ts = TimeSeries(key=api_key, output_format='pandas') if time_window == 'intraday': data, meta_data = ts.get_intraday( symbol=symbol, interval='1min', outputsize='full') elif time_window == 'daily': data, meta_data = ts.get_daily(symbol, outputsize='full') elif time_window == 'daily_adj': data, meta_data = ts.get_daily_adjusted(symbol, outputsize='full') pprint(data.head(10)) data.to_csv(f'./{symbol}_{time_window}.csv') if __name__ == "__main__": parser = argparse.ArgumentParser() parser.add_argument('symbol', type=str, help="the stock symbol you want to download") parser.add_argument('time_window', type=str, choices=[ 'intraday', 'daily', 'daily_adj'], help="the time period you want to download the stock history for") namespace = parser.parse_args() save_dataset(**vars(namespace))
34.941176
125
0.683502
156
1,188
4.961538
0.435897
0.090439
0.05814
0.054264
0.164083
0.142119
0
0
0
0
0
0.003099
0.185185
1,188
33
126
36
0.796488
0
0
0
0
0
0.208754
0.023569
0
0
0
0
0
1
0.04
false
0
0.16
0
0.2
0.12
0
0
0
null
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
null
0
0
0
0
0
0
0
0
0
0
0
0
1
0
8123847da358e93698586a58b0a106958f59df07
12,570
py
Python
tests/zpill.py
al3pht/cloud-custodian
ce6613d1b716f336384c5e308eee300389e6bf50
[ "Apache-2.0" ]
2,415
2018-12-04T00:37:58.000Z
2022-03-31T12:28:56.000Z
tests/zpill.py
al3pht/cloud-custodian
ce6613d1b716f336384c5e308eee300389e6bf50
[ "Apache-2.0" ]
3,272
2018-12-03T23:58:17.000Z
2022-03-31T21:15:32.000Z
tests/zpill.py
al3pht/cloud-custodian
ce6613d1b716f336384c5e308eee300389e6bf50
[ "Apache-2.0" ]
773
2018-12-06T09:43:23.000Z
2022-03-30T20:44:43.000Z
# Copyright The Cloud Custodian Authors. # SPDX-License-Identifier: Apache-2.0 import fnmatch from io import StringIO import json import os import shutil import zipfile import re from datetime import datetime, timedelta, tzinfo from distutils.util import strtobool import boto3 import placebo from botocore.response import StreamingBody from placebo import pill from c7n.testing import CustodianTestCore from .constants import ACCOUNT_ID # Custodian Test Account. This is used only for testing. # Access is available for community project maintainers. ########################################################################### # BEGIN PLACEBO MONKEY PATCH # # Placebo is effectively abandoned upstream, since mitch went back to work at AWS, irony... # These monkeypatch patches represent fixes on trunk of that repo that have not been released # into an extant version, we carry them here. We can drop this when this issue is resolved # # https://github.com/garnaat/placebo/issues/63 # # License - Apache 2.0 # Copyright (c) 2015 Mitch Garnaat class UTC(tzinfo): """UTC""" def utcoffset(self, dt): return timedelta(0) def tzname(self, dt): return "UTC" def dst(self, dt): return timedelta(0) utc = UTC() def deserialize(obj): """Convert JSON dicts back into objects.""" # Be careful of shallow copy here target = dict(obj) class_name = None if "__class__" in target: class_name = target.pop("__class__") if "__module__" in obj: obj.pop("__module__") # Use getattr(module, class_name) for custom types if needed if class_name == "datetime": return datetime(tzinfo=utc, **target) if class_name == "StreamingBody": return StringIO(target["body"]) # Return unrecognized structures as-is return obj def serialize(obj): """Convert objects into JSON structures.""" # Record class and module information for deserialization result = {"__class__": obj.__class__.__name__} try: result["__module__"] = obj.__module__ except AttributeError: pass # Convert objects to dictionary representation based on type if isinstance(obj, datetime): result["year"] = obj.year result["month"] = obj.month result["day"] = obj.day result["hour"] = obj.hour result["minute"] = obj.minute result["second"] = obj.second result["microsecond"] = obj.microsecond return result if isinstance(obj, StreamingBody): result["body"] = obj.read() obj._raw_stream = StringIO(result["body"]) obj._amount_read = 0 return result if isinstance(obj, bytes): return obj.decode('utf8') # Raise a TypeError if the object isn't recognized raise TypeError("Type not serializable") pill.FakeHttpResponse.raw = None placebo.pill.serialize = serialize placebo.pill.deserialize = deserialize # END PLACEBO MONKEY ########################################################################## class BluePill(pill.Pill): def playback(self): super(BluePill, self).playback() self._avail = self.get_available() def get_available(self): return { os.path.join(self.data_path, n) for n in fnmatch.filter(os.listdir(self.data_path), "*.json") } def get_next_file_path(self, service, operation): fn, format = super(BluePill, self).get_next_file_path(service, operation) # couple of double use cases if fn in self._avail: self._avail.remove(fn) else: print("\ndouble use %s\n" % fn) return (fn, format) def stop(self): result = super(BluePill, self).stop() if self._avail: print("Unused json files \n %s" % ("\n".join(sorted(self._avail)))) return result class ZippedPill(pill.Pill): def __init__(self, path, prefix=None, debug=False): super(ZippedPill, self).__init__(prefix, debug) self.path = path self._used = set() self.archive = None def playback(self): self.archive = zipfile.ZipFile(self.path, "r") self._files = set(self.archive.namelist()) return super(ZippedPill, self).playback() def record(self): self.archive = zipfile.ZipFile(self.path, "a", zipfile.ZIP_DEFLATED) self._files = set() files = {n for n in self.archive.namelist() if n.startswith(self.prefix)} if not files: return super(ZippedPill, self).record() # We can't update files in a zip, so copy self.archive.close() os.rename(self.path, "%s.tmp" % self.path) src = zipfile.ZipFile("%s.tmp" % self.path, "r") self.archive = zipfile.ZipFile(self.path, "w", zipfile.ZIP_DEFLATED) for n in src.namelist(): if n in files: continue self.archive.writestr(n, src.read(n)) os.remove("%s.tmp" % self.path) return super(ZippedPill, self).record() def stop(self): super(ZippedPill, self).stop() if self.archive: self.archive.close() def save_response(self, service, operation, response_data, http_response=200): filepath = self.get_new_file_path(service, operation) pill.LOG.debug("save_response: path=%s", filepath) json_data = {"status_code": http_response, "data": response_data} self.archive.writestr( filepath, json.dumps(json_data, indent=4, default=pill.serialize), zipfile.ZIP_DEFLATED, ) self._files.add(filepath) def load_response(self, service, operation): response_file = self.get_next_file_path(service, operation) self._used.add(response_file) pill.LOG.debug("load_responses: %s", response_file) response_data = json.loads( self.archive.read(response_file), object_hook=pill.deserialize ) return ( pill.FakeHttpResponse(response_data["status_code"]), response_data["data"] ) def get_new_file_path(self, service, operation): base_name = "{0}.{1}".format(service, operation) if self.prefix: base_name = "{0}.{1}".format(self.prefix, base_name) pill.LOG.debug("get_new_file_path: %s", base_name) index = 0 glob_pattern = os.path.join(self._data_path, base_name + "*") for file_path in fnmatch.filter(self._files, glob_pattern): file_name = os.path.basename(file_path) m = self.filename_re.match(file_name) if m: i = int(m.group("index")) if i > index: index = i index += 1 return os.path.join(self._data_path, "{0}_{1}.json".format(base_name, index)) def get_next_file_path(self, service, operation): base_name = "{0}.{1}".format(service, operation) if self.prefix: base_name = "{0}.{1}".format(self.prefix, base_name) pill.LOG.debug("get_next_file_path: %s", base_name) next_file = None while next_file is None: index = self._index.setdefault(base_name, 1) fn = os.path.join(self._data_path, base_name + "_{0}.json".format(index)) fn = fn.replace('\\', '/') if fn in self._files: next_file = fn self._index[base_name] += 1 self._files.add(fn) elif index != 1: self._index[base_name] = 1 else: # we are looking for the first index and it's not here raise IOError("response file ({0}) not found".format(fn)) return fn def attach(session, data_path, prefix=None, debug=False): pill = ZippedPill(data_path, prefix=prefix, debug=debug) pill.attach(session, prefix) return pill class RedPill(pill.Pill): def datetime_converter(self, obj): if isinstance(obj, datetime): return obj.isoformat() def save_response(self, service, operation, response_data, http_response=200): """ Override to sanitize response metadata and account_ids """ # aws sso setups involve a short lived credential transfer if service == "portal.sso": return if 'ResponseMetadata' in response_data: response_data['ResponseMetadata'] = {} response_data = json.dumps(response_data, default=serialize) response_data = re.sub(r"\b\d{12}\b", ACCOUNT_ID, response_data) # noqa response_data = json.loads(response_data, object_hook=deserialize) super(RedPill, self).save_response(service, operation, response_data, http_response) class PillTest(CustodianTestCore): archive_path = os.path.join( os.path.dirname(os.path.abspath(__file__)), "placebo_data.zip" ) placebo_dir = os.path.join( os.path.dirname(os.path.abspath(__file__)), "data", "placebo" ) output_dir = os.path.join( os.path.dirname(os.path.abspath(__file__)), "data", "output" ) recording = False def cleanUp(self): self.pill = None def record_flight_data(self, test_case, zdata=False, augment=False, region=None): self.recording = True test_dir = os.path.join(self.placebo_dir, test_case) if not (zdata or augment): if os.path.exists(test_dir): shutil.rmtree(test_dir) os.makedirs(test_dir) session = boto3.Session(region_name=region) default_region = session.region_name if not zdata: pill = RedPill() pill.attach(session, test_dir) else: pill = attach(session, self.archive_path, test_case, debug=True) pill.record() self.pill = pill self.addCleanup(pill.stop) self.addCleanup(self.cleanUp) class FakeFactory: def __call__(fake, region=None, assume=None): new_session = None # slightly experimental for test recording, using # cross account assumes, note this will record sts # assume role api calls creds into test data, they will # go stale, but its best to modify before commiting. # Disabled by default. if 0 and (assume is not False and fake.assume_role): client = session.client('sts') creds = client.assume_role( RoleArn=fake.assume_role, RoleSessionName='CustodianTest')['Credentials'] new_session = boto3.Session( aws_access_key_id=creds['AccessKeyId'], aws_secret_access_key=creds['SecretAccessKey'], aws_session_token=creds['SessionToken'], region_name=region or fake.region or default_region) elif region and region != default_region: new_session = boto3.Session(region_name=region) if new_session: assert not zdata new_pill = placebo.attach(new_session, test_dir, debug=True) new_pill.record() self.addCleanup(new_pill.stop) return new_session return session return FakeFactory() def replay_flight_data(self, test_case, zdata=False, region=None): """ The `region` argument is to allow functional tests to override the default region. It is unused when replaying stored data. """ if strtobool(os.environ.get('C7N_FUNCTIONAL', 'no')): self.recording = True return lambda region=region, assume=None: boto3.Session(region_name=region) if not zdata: test_dir = os.path.join(self.placebo_dir, test_case) if not os.path.exists(test_dir): raise RuntimeError("Invalid Test Dir for flight data %s" % test_dir) session = boto3.Session(region_name=region) if not zdata: pill = placebo.attach(session, test_dir) # pill = BluePill() # pill.attach(session, test_dir) else: pill = attach(session, self.archive_path, test_case, False) pill.playback() self.addCleanup(pill.stop) self.addCleanup(self.cleanUp) return lambda region=None, assume=None: session
33.699732
93
0.605091
1,510
12,570
4.872848
0.235099
0.014678
0.012232
0.011416
0.249796
0.194618
0.184697
0.143789
0.098396
0.098396
0
0.005536
0.281464
12,570
372
94
33.790323
0.809123
0.127765
0
0.155642
0
0
0.058994
0
0
0
0
0
0.003891
1
0.093385
false
0.003891
0.058366
0.015564
0.291829
0.007782
0
0
0
null
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
null
0
0
0
0
0
0
0
0
0
0
0
0
1
0
8124c6b98bb9251fb25a500d047b7426b2a988cd
2,721
py
Python
ccg/supertagger/any2int.py
stanojevic/ccgtools
d87521d66fcd1b3110fbecc6b78b15a60e5095a3
[ "MIT" ]
null
null
null
ccg/supertagger/any2int.py
stanojevic/ccgtools
d87521d66fcd1b3110fbecc6b78b15a60e5095a3
[ "MIT" ]
null
null
null
ccg/supertagger/any2int.py
stanojevic/ccgtools
d87521d66fcd1b3110fbecc6b78b15a60e5095a3
[ "MIT" ]
null
null
null
class Any2Int: def __init__(self, min_count: int, include_UNK: bool, include_PAD: bool): self.min_count = min_count self.include_UNK = include_UNK self.include_PAD = include_PAD self.frozen = False self.UNK_i = -1 self.UNK_s = "<UNK>" self.PAD_i = -2 self.PAD_s = "<PAD>" self.voc_size = 0 self._s2i = dict() self._i2s = [] self.frequency = dict() def iter_item(self): return enumerate(self._i2s) def get_s2i(self, s, default: int): assert self.frozen i = self._s2i.get(s, -1) if i >= 0: return i elif self.include_UNK: return self.UNK_i else: return default def __getitem__(self, s): return self.s2i(s) def s2i(self, s): i = self.get_s2i(s, -1) if i >= 0: return i else: raise Exception(f"out of vocabulary entry {s}") def contains(self, s): return self.get_s2i(s, -1) != -1 def i2s(self, i): assert self.frozen if 0 <= i < self.voc_size: return self._i2s[i] else: raise Exception(f"not entry at position {i} for a vocabulary of size {self.voc_size}") def add_to_counts(self, s): assert not self.frozen self.frequency[s] = self.frequency.get(s, 0)+1 def freeze(self): assert not self.frozen if self.include_UNK: self.UNK_i = len(self._i2s) self._i2s.append(self.UNK_s) if self.include_PAD: self.PAD_i = len(self._i2s) self._i2s.append(self.PAD_s) for s, count in sorted(self.frequency.items(), key=lambda x: -x[1]): if count >= self.min_count: self._i2s.append(s) for i, s in enumerate(self._i2s): self._s2i[s] = i self.voc_size = len(self._i2s) self.frozen = True def __reduce__(self): return Any2Int, (2, self.include_UNK, self.include_PAD), (self.min_count, self.include_UNK, self.frozen, self.UNK_i, self.UNK_s, self.PAD_i, self.PAD_s, self.voc_size, self._s2i, self._i2s, self.frequency) def __setstate__(self, state): self.min_count = state[0] self.include_UNK = state[1] self.frozen = state[2] self.UNK_i = state[3] self.UNK_s = state[4] self.PAD_i = state[5] self.PAD_s = state[6] self.voc_size = state[7] self._s2i = state[8] self._i2s = state[9] self.frequency = state[10]
30.573034
118
0.529585
373
2,721
3.646113
0.19571
0.061765
0.061765
0.039706
0.172794
0.060294
0.060294
0.041176
0
0
0
0.02926
0.359427
2,721
88
119
30.920455
0.751004
0
0
0.146667
0
0
0.037882
0
0
0
0
0
0.053333
1
0.146667
false
0
0
0.053333
0.28
0
0
0
0
null
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
null
0
0
0
0
0
0
0
0
0
0
0
0
1
0
812522326c06afbf43f1bd6cee31bd8b7b273277
6,805
py
Python
app/sensor.py
sosprz/nettemp
334b3124263267c931bd7dc5c1bd8eb70614b4ef
[ "MIT" ]
51
2015-01-03T01:37:25.000Z
2021-11-03T18:07:42.000Z
app/sensor.py
sosprz/nettemp
334b3124263267c931bd7dc5c1bd8eb70614b4ef
[ "MIT" ]
18
2015-03-06T18:46:51.000Z
2021-04-02T08:02:01.000Z
app/sensor.py
sosprz/nettemp
334b3124263267c931bd7dc5c1bd8eb70614b4ef
[ "MIT" ]
51
2015-02-04T18:53:54.000Z
2022-02-16T20:40:45.000Z
from app import app from flask import Flask, request, jsonify, g import sqlite3 import os import json from random import randint from flask_jwt_extended import jwt_required import datetime from flask_mysqldb import MySQL mysql = MySQL() def get_db(rom): db = getattr(g, '_database', None) if db is None: db = g._database = sqlite3.connect(rom) return db @app.teardown_appcontext def close_connection(exception): db = getattr(g, '_database', None) if db is not None: db.close() def check_value(value, type, rom): adj='' tm='' value=float(value) m = mysql.connection.cursor() sql = "SELECT adj, tmp FROM sensors WHERE rom=%s" m.execute(sql, [rom]) sensor=m.fetchall() for adj, tmp in sensor: tmp=float(tmp) adj=float(adj) msg=[] sql = "SELECT min, max, value1, value2, value3 FROM types WHERE type=%s" m.execute(sql, [type]) list=m.fetchall() msg.append("IN VALUE: %f" % value) msg.append(list) m.close() if adj: value=float(value)+(adj) msg.append("ADJ: %d" % value) for min, max, v1, v2, v3 in list: if (value>=float(min)) and (value<=float(max)): if(value==v1) or (value==v2) or (value==v3): msg.append("filter 2 back to previous %f" % tmp) value=tmp else: value=float(value) else: msg.append("filter 1 back to previous %f" % tmp) value=tmp msg.append("VALUE OUT: %f" % value) print(msg) return value def new_db(rom): rom = rom+'.sql' conn = sqlite3.connect(app.romdir+rom) c = conn.cursor() sql = "SELECT count() FROM sqlite_master WHERE type='table' AND name='def'" c.execute(sql) if c.fetchone()[0]==1: print ("Database %s exists" %rom) return True else: with app.app_context(): db = get_db(app.romdir+rom) with app.open_resource('schema/sensors_db_schema.sql', mode='r') as f: db.cursor().executescript(f.read()) db.commit() print ("Database %s created" %rom) return False def insert_db(rom,value): rom = rom+'.sql' conn = sqlite3.connect(app.romdir+rom) c = conn.cursor() sql = "SELECT count() FROM sqlite_master WHERE type='table' AND name='def'" c.execute(sql) if c.fetchone()[0]==1: data = [value] sql = "INSERT OR IGNORE INTO def (value) VALUES (?)" c.execute(sql, data) conn.commit() conn.close() print ("[ nettemp ][ sensor ] Database %s insert ok" %rom) return True else: print ("[ nettemp ][ sensor ] Database %s not exist" %rom) return False def update_sensor_tmp(rom,value): m = mysql.connection.cursor() rom1 = [rom] sql="SELECT count(*) FROM sensors WHERE rom=%s" m.execute(sql, rom1) coun=m.fetchone() if coun[0]==1: if int(datetime.datetime.now().strftime("%M"))%5==0: tmp_5ago=value sql = "UPDATE sensors SET tmp=%s, tmp_5ago=%s, nodata='', time=CURRENT_TIMESTAMP() WHERE rom=%s" data = [value,tmp_5ago,rom] else: sql = "UPDATE sensors SET tmp=%s, nodata='', time=CURRENT_TIMESTAMP() WHERE rom=%s" data = [value,rom] m.execute(sql, data) # stat min max data = [value, value, rom] sql = "UPDATE sensors SET stat_min=%s, stat_min_time=CURRENT_TIMESTAMP() WHERE (stat_min>%s OR stat_min is null OR stat_min='0.0') AND rom=%s" m.execute(sql, data) sql = "UPDATE sensors SET stat_max=%s, stat_max_time=CURRENT_TIMESTAMP() WHERE (stat_max<%s OR stat_max is null OR stat_max='0.0') AND rom=%s" m.execute(sql, data) m.connection.commit() m.close() print ("[ nettemp ][ sensor ] Sensor %s updated" %rom) return True else: print ("[ nettemp ][ sensor ] Sensor %s not exist" %rom) return False def delete_db(rom): rom=rom+'.sql' if os.path.isfile(app.romdir+rom): os.remove(rom) print ("[ nettemp ][ sensor ] Database %s deleted" %rom) return True else: print ("[ nettemp ][ sensor ] Database %s not exist" %rom) return False def delete_sensor(id,rom): data = [id, rom] m = mysql.connection.cursor() sql="DELETE FROM sensors WHERE id=? AND rom=%s" m.execute(sql, data) m.connection.commit() m.close() delete_db(rom) print ("[ nettemp ][ sensor ] Sensor %s removed ok" %rom) def create_sensor(rom, data, data2, map_settings): m = mysql.connection.cursor() rom1 = [rom] sql = "SELECT count(*) FROM sensors WHERE rom=%s" m.execute(sql, rom1) coun = m.fetchone() if coun[0]==0: sql = "INSERT INTO sensors (rom,type,device,ip,gpio,i2c,usb,name) VALUES (%s, %s, %s, %s, %s, %s, %s, %s)" m.execute(sql, data) sql2 = "UPDATE sensors SET alarm='off', adj='0', charts='on', status='on', ch_group=%s, tmp_min='0', tmp_max='0', minmax='off', stat_min='0', stat_max='0', tmp_5ago='0', fiveago='on', map_id=%s, nodata_time='5', email_delay='10' WHERE rom=%s" m.execute(sql2, data2) map = "INSERT INTO maps (type, pos_x, pos_y, map_on, map_id, display_name) VALUES (%s, %s, %s, %s, %s, %s)" m.execute(map, map_settings) m.connection.commit() m.close() print ("[ nettemp ][ sensor ] Sensor %s added ok" %rom) else: print ("[ nettemp ][ sensor ] Sensor %s already exist" %rom) return None def sensor(): data = request.get_json() for j in data: rom = None if 'rom' in j: rom=j['rom'] type = None if 'type' in j: type=j['type'] device = None if 'device' in j: device=j['device'] ip = None if 'ip' in j: ip = j['ip'] gpio = None if 'gpio' in j: gpio=j['gpio'] i2c = None if 'i2c' in j: i2c=j['i2c'] usb = None if 'usb' in j: usb=j['usb'] name = randint(1000,9000) if 'name' in j: name=j['name'] if not j['name']: name = randint(1000,9000) tmp = None if 'tmp' in j: tmp=j['tmp'] value = None if 'value' in j: value=j['value'] group = type if 'group' in j: group=j['group'] map_id = randint(1000,9000) map_y = randint(50,600) map_x = randint(50,600) data = [rom, type, device, ip, gpio, i2c, usb, name] data2 = [group, map_id, rom] map_settings = [type, map_y, map_x, 'on', map_id, 'on'] value=check_value(value, type, rom) if insert_db(rom, value) == False: new_db(rom) insert_db(rom,value) if update_sensor_tmp(rom,value) == False: create_sensor(rom,data,data2,map_settings) update_sensor_tmp(rom,value) @app.route('/sensor', methods=['POST']) @jwt_required def url_sensor(): sensor() return '', 200 @app.route('/local', methods=['POST']) def url_localhost(): if request.remote_addr == '127.0.0.1': sensor() return 'Local' else: return '', 404
27.439516
246
0.603527
1,032
6,805
3.898256
0.175388
0.029828
0.022371
0.023863
0.429779
0.331842
0.311956
0.272931
0.216008
0.209545
0
0.020147
0.24144
6,805
247
247
27.550607
0.759202
0.001763
0
0.306977
0
0.027907
0.288218
0.02651
0
0
0
0
0
1
0.055814
false
0
0.04186
0
0.162791
0.055814
0
0
0
null
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
null
0
0
0
0
0
0
0
0
0
0
0
0
1
0
81265c7215ed57cef680d0ec0a27f1c4d35a191a
5,340
bzl
Python
tao_compiler/mlir/disc/tests/glob_op_test.bzl
JamesTheZ/BladeDISC
e6c76ee557ebfccd560d44f6b6276bbc4e0a8a34
[ "Apache-2.0" ]
328
2021-12-20T03:29:35.000Z
2022-03-31T14:27:23.000Z
tao_compiler/mlir/disc/tests/glob_op_test.bzl
JamesTheZ/BladeDISC
e6c76ee557ebfccd560d44f6b6276bbc4e0a8a34
[ "Apache-2.0" ]
82
2021-12-20T09:15:16.000Z
2022-03-31T09:33:48.000Z
tao_compiler/mlir/disc/tests/glob_op_test.bzl
JamesTheZ/BladeDISC
e6c76ee557ebfccd560d44f6b6276bbc4e0a8a34
[ "Apache-2.0" ]
66
2021-12-21T17:28:27.000Z
2022-03-29T12:08:34.000Z
# Test definitions for Lit, the LLVM test runner. # # This is reusing the LLVM Lit test runner in the interim until the new build # rules are upstreamed. # TODO(b/136126535): remove this custom rule. """Lit runner globbing test """ load("//tensorflow:tensorflow.bzl", "filegroup") load("@bazel_skylib//lib:paths.bzl", "paths") load("//tensorflow:tensorflow.bzl", "tf_cc_test", "tf_native_cc_binary", "tf_copts") # Default values used by the test runner. _default_test_file_exts = ["mlir", ".pbtxt", ".td"] _default_driver = "@llvm-project//mlir:run_lit.sh" _default_size = "small" _default_tags = [] # These are patterns which we should never match, for tests, subdirectories, or # test input data files. _ALWAYS_EXCLUDE = [ "**/LICENSE.txt", "**/README.txt", "**/lit.local.cfg", # Exclude input files that have spaces in their names, since bazel # cannot cope with such "targets" in the srcs list. "**/* *", "**/* */**", ] def _run_lit_test(name, test_file, data, size, tags, driver, features, exec_properties): """Runs lit on all tests it can find in `data` under tensorflow/compiler/mlir. Note that, due to Bazel's hermetic builds, lit only sees the tests that are included in the `data` parameter, regardless of what other tests might exist in the directory searched. Args: name: str, the name of the test, including extension. data: [str], the data input to the test. size: str, the size of the test. tags: [str], tags to attach to the test. driver: str, label of the driver shell script. Note: use of a custom driver is not currently supported and specifying a default driver will abort the tests. features: [str], list of extra features to enable. """ name_without_suffix = test_file[0].split('.')[0] local_test_files = name + ".test_files" filegroup( name = local_test_files, srcs = native.glob([ "data/" + name_without_suffix + "*.mlir", ]), ) tf_cc_test( name = name, srcs = test_file, size = size, deps = [ "//tensorflow/compiler/mlir/disc/tests:mlir_feature_test", "//tensorflow/core:test", "//tensorflow/core:test_main", "//tensorflow/core:testlib", ], data = [":" + local_test_files] + data + [ "//tensorflow/compiler/mlir/disc:disc_compiler_main", "//tensorflow/compiler/mlir:tf-mlir-translate", "//tensorflow/compiler/mlir:tf-opt", ], ) def glob_op_tests( exclude = [], test_file_exts = _default_test_file_exts, default_size = _default_size, size_override = {}, data = [], per_test_extra_data = {}, default_tags = _default_tags, tags_override = {}, driver = _default_driver, features = [], exec_properties = {}): """Creates all plausible Lit tests (and their inputs) under this directory. Args: exclude: [str], paths to exclude (for tests and inputs). test_file_exts: [str], extensions for files that are tests. default_size: str, the test size for targets not in "size_override". size_override: {str: str}, sizes to use for specific tests. data: [str], additional input data to the test. per_test_extra_data: {str: [str]}, extra data to attach to a given file. default_tags: [str], additional tags to attach to the test. tags_override: {str: str}, tags to add to specific tests. driver: str, label of the driver shell script. Note: use of a custom driver is not currently supported and specifying a default driver will abort the tests. features: [str], list of extra features to enable. exec_properties: a dictionary of properties to pass on. """ # Ignore some patterns by default for tests and input data. exclude = _ALWAYS_EXCLUDE + exclude tests = native.glob( ["*." + ext for ext in test_file_exts], exclude = exclude, ) # Run tests individually such that errors can be attributed to a specific # failure. for i in range(len(tests)): curr_test = tests[i] # Instantiate this test with updated parameters. lit_test( name = curr_test, data = data + per_test_extra_data.get(curr_test, []), size = size_override.get(curr_test, default_size), tags = default_tags + tags_override.get(curr_test, []), driver = driver, features = features, exec_properties = exec_properties, ) def lit_test( name, data = [], size = _default_size, tags = _default_tags, driver = _default_driver, features = [], exec_properties = {}): """Runs test files under lit. Args: name: str, the name of the test. data: [str], labels that should be provided as data inputs. size: str, the size of the test. tags: [str], tags to attach to the test. driver: str, label of the driver shell script. Note: use of a custom driver is not currently supported and specifying a default driver will abort the tests. features: [str], list of extra features to enable. """ _run_lit_test(name + ".test", [name], data, size, tags, driver, features, exec_properties)
35.364238
94
0.639888
710
5,340
4.659155
0.257746
0.023277
0.018138
0.033857
0.303204
0.250302
0.219166
0.194982
0.178658
0.178658
0
0.002764
0.254682
5,340
150
95
35.6
0.828392
0.494757
0
0.131579
0
0
0.209729
0.14673
0
0
0
0.006667
0
1
0.039474
false
0
0
0
0.039474
0
0
0
0
null
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
null
0
0
0
0
0
0
0
0
0
0
0
0
1
0
812723d2076c258aebc37a64fed06e3f495c2735
2,181
py
Python
build-scripts/PackageCheckHelpers.py
yulicrunchy/JALoP
a474b464d4916fe559cf1df97c855232e5ec24ab
[ "Apache-2.0" ]
4
2016-01-18T20:49:23.000Z
2020-03-04T22:23:57.000Z
build-scripts/PackageCheckHelpers.py
yulicrunchy/JALoP
a474b464d4916fe559cf1df97c855232e5ec24ab
[ "Apache-2.0" ]
2
2019-09-23T21:04:25.000Z
2020-01-31T18:10:17.000Z
build-scripts/PackageCheckHelpers.py
yulicrunchy/JALoP
a474b464d4916fe559cf1df97c855232e5ec24ab
[ "Apache-2.0" ]
2
2021-04-01T20:53:12.000Z
2021-04-01T21:10:53.000Z
""" These are functions to add to the configure context. """ def __checkCanLink(context, source, source_type, message_libname, real_libs=[]): """ Check that source can be successfully compiled and linked against real_libs. Keyword arguments: source -- source to try to compile source_type -- type of source file, (probably should be ".c") message_libname -- library name to show in the message output from scons real_libs -- list of actual libraries to link against (defaults to a list with one element, the value of messager_libname) """ if not real_libs: real_libs = [message_libname] context.Message("Checking for %s..." % message_libname) libsave = context.env.get('LIBS') context.env.AppendUnique(LIBS=real_libs) ret = context.TryLink(source, source_type) context.Result( ret ) if libsave is None: del(context.env['LIBS']) else: context.env['LIBS'] = libsave return ret libuuid_source = ''' #include <uuid/uuid.h> int main() { uuid_t uu; char uuid_str[37]; uuid_generate(uu); uuid_unparse(uu, uuid_str); return 0; } ''' def CheckLibUUID(context): return __checkCanLink(context, libuuid_source, ".c", "libuuid", ["uuid"]) selinux_source = ''' #include <selinux/selinux.h> int main() { security_context_t ctx; getpeercon(0, &ctx); return 0; } ''' def CheckSeLinux(context): return __checkCanLink(context, selinux_source, '.cpp', 'selinux', ['selinux']) byteswap_source = ''' #include <byteswap.h> #include <stdint.h> int main() { uint16_t b16 = 0x00FF; uint32_t b32 = 0x0011EEFF; uint64_t b64 = 0x00112233CCDDEEFF; bswap_16(b16); bswap_32(b32); bswap_64(b64); return 0; } ''' def CheckByteswap(context): context.Message("Checking for byteswap.h...") ret = context.TryCompile(byteswap_source, '.c') context.Result( ret ) return ret bdb_source = ''' #include <db.h> #if defined(DB_VERSION_MAJOR) && DB_VERSION_MAJOR >= 4 #if DB_VERSION_MAJOR == 4 #if defined(DB_VERSION_MINOR) && DB_VERSION_MINOR >= 3 #else #error "" #endif #endif #else #error "" #endif ''' def CheckBDB(context): context.Message("Checking for BDB >= 4.3...") ret = context.TryCompile(bdb_source, '.c') context.Result(ret) return ret
22.484536
80
0.710683
305
2,181
4.914754
0.386885
0.032021
0.044029
0.050033
0.108072
0.042695
0.042695
0
0
0
0
0.028108
0.151765
2,181
96
81
22.71875
0.782162
0.214122
0
0.323944
0
0
0.453271
0.029206
0
0
0.01986
0
0
1
0.070423
false
0
0
0.028169
0.183099
0
0
0
0
null
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
null
0
0
0
0
0
0
0
0
0
0
0
0
1
0
81290326c9beb0af3fd98f2bdd52b65974d13cd3
12,950
py
Python
src/transformers/modeling_tf_pytorch_utils.py
ari-holtzman/transformers
8725c545e8feeecdcee0ad92ca1d80cee8f0c6e4
[ "Apache-2.0" ]
5,129
2019-09-30T11:21:03.000Z
2022-03-31T22:35:12.000Z
src/transformers/modeling_tf_pytorch_utils.py
ari-holtzman/transformers
8725c545e8feeecdcee0ad92ca1d80cee8f0c6e4
[ "Apache-2.0" ]
604
2019-10-05T00:39:46.000Z
2022-03-31T11:12:07.000Z
src/transformers/modeling_tf_pytorch_utils.py
ari-holtzman/transformers
8725c545e8feeecdcee0ad92ca1d80cee8f0c6e4
[ "Apache-2.0" ]
1,034
2019-09-30T15:01:32.000Z
2022-03-31T06:14:50.000Z
# coding=utf-8 # Copyright 2018 The Google AI Language Team Authors and The HuggingFace Inc. team. # Copyright (c) 2018, NVIDIA CORPORATION. All rights reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. """ PyTorch - TF 2.0 general utilities.""" import logging import os import re import numpy logger = logging.getLogger(__name__) def convert_tf_weight_name_to_pt_weight_name(tf_name, start_prefix_to_remove=""): """ Convert a TF 2.0 model variable name in a pytorch model weight name. Conventions for TF2.0 scopes -> PyTorch attribute names conversions: - '$1___$2' is replaced by $2 (can be used to duplicate or remove layers in TF2.0 vs PyTorch) - '_._' is replaced by a new level separation (can be used to convert TF2.0 lists in PyTorch nn.ModulesList) return tuple with: - pytorch model weight name - transpose: boolean indicating weither TF2.0 and PyTorch weights matrices are transposed with regards to each other """ tf_name = tf_name.replace(":0", "") # device ids tf_name = re.sub( r"/[^/]*___([^/]*)/", r"/\1/", tf_name ) # '$1___$2' is replaced by $2 (can be used to duplicate or remove layers in TF2.0 vs PyTorch) tf_name = tf_name.replace( "_._", "/" ) # '_._' is replaced by a level separation (can be used to convert TF2.0 lists in PyTorch nn.ModulesList) tf_name = re.sub(r"//+", "/", tf_name) # Remove empty levels at the end tf_name = tf_name.split("/") # Convert from TF2.0 '/' separators to PyTorch '.' separators tf_name = tf_name[1:] # Remove level zero # When should we transpose the weights transpose = bool(tf_name[-1] == "kernel" or "emb_projs" in tf_name or "out_projs" in tf_name) # Convert standard TF2.0 names in PyTorch names if tf_name[-1] == "kernel" or tf_name[-1] == "embeddings" or tf_name[-1] == "gamma": tf_name[-1] = "weight" if tf_name[-1] == "beta": tf_name[-1] = "bias" # Remove prefix if needed tf_name = ".".join(tf_name) if start_prefix_to_remove: tf_name = tf_name.replace(start_prefix_to_remove, "", 1) return tf_name, transpose ##################### # PyTorch => TF 2.0 # ##################### def load_pytorch_checkpoint_in_tf2_model(tf_model, pytorch_checkpoint_path, tf_inputs=None, allow_missing_keys=False): """ Load pytorch checkpoints in a TF 2.0 model """ try: import tensorflow as tf # noqa: F401 import torch # noqa: F401 except ImportError: logger.error( "Loading a PyTorch model in TensorFlow, requires both PyTorch and TensorFlow to be installed. Please see " "https://pytorch.org/ and https://www.tensorflow.org/install/ for installation instructions." ) raise pt_path = os.path.abspath(pytorch_checkpoint_path) logger.info("Loading PyTorch weights from {}".format(pt_path)) pt_state_dict = torch.load(pt_path, map_location="cpu") logger.info("PyTorch checkpoint contains {:,} parameters".format(sum(t.numel() for t in pt_state_dict.values()))) return load_pytorch_weights_in_tf2_model( tf_model, pt_state_dict, tf_inputs=tf_inputs, allow_missing_keys=allow_missing_keys ) def load_pytorch_model_in_tf2_model(tf_model, pt_model, tf_inputs=None, allow_missing_keys=False): """ Load pytorch checkpoints in a TF 2.0 model """ pt_state_dict = pt_model.state_dict() return load_pytorch_weights_in_tf2_model( tf_model, pt_state_dict, tf_inputs=tf_inputs, allow_missing_keys=allow_missing_keys ) def load_pytorch_weights_in_tf2_model(tf_model, pt_state_dict, tf_inputs=None, allow_missing_keys=False): """ Load pytorch state_dict in a TF 2.0 model. """ try: import torch # noqa: F401 import tensorflow as tf # noqa: F401 from tensorflow.python.keras import backend as K except ImportError: logger.error( "Loading a PyTorch model in TensorFlow, requires both PyTorch and TensorFlow to be installed. Please see " "https://pytorch.org/ and https://www.tensorflow.org/install/ for installation instructions." ) raise if tf_inputs is None: tf_inputs = tf_model.dummy_inputs if tf_inputs is not None: tf_model(tf_inputs, training=False) # Make sure model is built # Adapt state dict - TODO remove this and update the AWS weights files instead # Convert old format to new format if needed from a PyTorch state_dict old_keys = [] new_keys = [] for key in pt_state_dict.keys(): new_key = None if "gamma" in key: new_key = key.replace("gamma", "weight") if "beta" in key: new_key = key.replace("beta", "bias") if new_key: old_keys.append(key) new_keys.append(new_key) for old_key, new_key in zip(old_keys, new_keys): pt_state_dict[new_key] = pt_state_dict.pop(old_key) # Make sure we are able to load PyTorch base models as well as derived models (with heads) # TF models always have a prefix, some of PyTorch models (base ones) don't start_prefix_to_remove = "" if not any(s.startswith(tf_model.base_model_prefix) for s in pt_state_dict.keys()): start_prefix_to_remove = tf_model.base_model_prefix + "." symbolic_weights = tf_model.trainable_weights + tf_model.non_trainable_weights tf_loaded_numel = 0 weight_value_tuples = [] all_pytorch_weights = set(list(pt_state_dict.keys())) for symbolic_weight in symbolic_weights: sw_name = symbolic_weight.name name, transpose = convert_tf_weight_name_to_pt_weight_name( sw_name, start_prefix_to_remove=start_prefix_to_remove ) # Find associated numpy array in pytorch model state dict if name not in pt_state_dict: if allow_missing_keys: continue raise AttributeError("{} not found in PyTorch model".format(name)) array = pt_state_dict[name].numpy() if transpose: array = numpy.transpose(array) if len(symbolic_weight.shape) < len(array.shape): array = numpy.squeeze(array) elif len(symbolic_weight.shape) > len(array.shape): array = numpy.expand_dims(array, axis=0) try: assert list(symbolic_weight.shape) == list(array.shape) except AssertionError as e: e.args += (symbolic_weight.shape, array.shape) raise e tf_loaded_numel += array.size # logger.warning("Initialize TF weight {}".format(symbolic_weight.name)) weight_value_tuples.append((symbolic_weight, array)) all_pytorch_weights.discard(name) K.batch_set_value(weight_value_tuples) if tf_inputs is not None: tf_model(tf_inputs, training=False) # Make sure restore ops are run logger.info("Loaded {:,} parameters in the TF 2.0 model.".format(tf_loaded_numel)) logger.info("Weights or buffers not loaded from PyTorch model: {}".format(all_pytorch_weights)) return tf_model ##################### # TF 2.0 => PyTorch # ##################### def load_tf2_checkpoint_in_pytorch_model(pt_model, tf_checkpoint_path, tf_inputs=None, allow_missing_keys=False): """ Load TF 2.0 HDF5 checkpoint in a PyTorch model We use HDF5 to easily do transfer learning (see https://github.com/tensorflow/tensorflow/blob/ee16fcac960ae660e0e4496658a366e2f745e1f0/tensorflow/python/keras/engine/network.py#L1352-L1357). """ try: import tensorflow as tf # noqa: F401 import torch # noqa: F401 except ImportError: logger.error( "Loading a TensorFlow model in PyTorch, requires both PyTorch and TensorFlow to be installed. Please see " "https://pytorch.org/ and https://www.tensorflow.org/install/ for installation instructions." ) raise import transformers logger.info("Loading TensorFlow weights from {}".format(tf_checkpoint_path)) # Instantiate and load the associated TF 2.0 model tf_model_class_name = "TF" + pt_model.__class__.__name__ # Add "TF" at the beggining tf_model_class = getattr(transformers, tf_model_class_name) tf_model = tf_model_class(pt_model.config) if tf_inputs is None: tf_inputs = tf_model.dummy_inputs if tf_inputs is not None: tf_model(tf_inputs, training=False) # Make sure model is built tf_model.load_weights(tf_checkpoint_path, by_name=True) return load_tf2_model_in_pytorch_model(pt_model, tf_model, allow_missing_keys=allow_missing_keys) def load_tf2_model_in_pytorch_model(pt_model, tf_model, allow_missing_keys=False): """ Load TF 2.0 model in a pytorch model """ weights = tf_model.weights return load_tf2_weights_in_pytorch_model(pt_model, weights, allow_missing_keys=allow_missing_keys) def load_tf2_weights_in_pytorch_model(pt_model, tf_weights, allow_missing_keys=False): """ Load TF2.0 symbolic weights in a PyTorch model """ try: import tensorflow as tf # noqa: F401 import torch # noqa: F401 except ImportError: logger.error( "Loading a TensorFlow model in PyTorch, requires both PyTorch and TensorFlow to be installed. Please see " "https://pytorch.org/ and https://www.tensorflow.org/install/ for installation instructions." ) raise new_pt_params_dict = {} current_pt_params_dict = dict(pt_model.named_parameters()) # Make sure we are able to load PyTorch base models as well as derived models (with heads) # TF models always have a prefix, some of PyTorch models (base ones) don't start_prefix_to_remove = "" if not any(s.startswith(pt_model.base_model_prefix) for s in current_pt_params_dict.keys()): start_prefix_to_remove = pt_model.base_model_prefix + "." # Build a map from potential PyTorch weight names to TF 2.0 Variables tf_weights_map = {} for tf_weight in tf_weights: pt_name, transpose = convert_tf_weight_name_to_pt_weight_name( tf_weight.name, start_prefix_to_remove=start_prefix_to_remove ) tf_weights_map[pt_name] = (tf_weight.numpy(), transpose) all_tf_weights = set(list(tf_weights_map.keys())) loaded_pt_weights_data_ptr = {} missing_keys_pt = [] for pt_weight_name, pt_weight in current_pt_params_dict.items(): # Handle PyTorch shared weight ()not duplicated in TF 2.0 if pt_weight.data_ptr() in loaded_pt_weights_data_ptr: new_pt_params_dict[pt_weight_name] = loaded_pt_weights_data_ptr[pt_weight.data_ptr()] continue # Find associated numpy array in pytorch model state dict if pt_weight_name not in tf_weights_map: if allow_missing_keys: missing_keys_pt.append(pt_weight_name) continue raise AttributeError("{} not found in TF 2.0 model".format(pt_weight_name)) array, transpose = tf_weights_map[pt_weight_name] if transpose: array = numpy.transpose(array) if len(pt_weight.shape) < len(array.shape): array = numpy.squeeze(array) elif len(pt_weight.shape) > len(array.shape): array = numpy.expand_dims(array, axis=0) try: assert list(pt_weight.shape) == list(array.shape) except AssertionError as e: e.args += (pt_weight.shape, array.shape) raise e # logger.warning("Initialize PyTorch weight {}".format(pt_weight_name)) new_pt_params_dict[pt_weight_name] = torch.from_numpy(array) loaded_pt_weights_data_ptr[pt_weight.data_ptr()] = torch.from_numpy(array) all_tf_weights.discard(pt_weight_name) missing_keys, unexpected_keys = pt_model.load_state_dict(new_pt_params_dict, strict=False) missing_keys += missing_keys_pt if len(missing_keys) > 0: logger.info( "Weights of {} not initialized from TF 2.0 model: {}".format(pt_model.__class__.__name__, missing_keys) ) if len(unexpected_keys) > 0: logger.info( "Weights from TF 2.0 model not used in {}: {}".format(pt_model.__class__.__name__, unexpected_keys) ) logger.info("Weights or buffers not loaded from TF 2.0 model: {}".format(all_tf_weights)) return pt_model
39.242424
155
0.680386
1,848
12,950
4.50487
0.164502
0.019459
0.008168
0.025105
0.537538
0.471351
0.429429
0.416697
0.386306
0.348108
0
0.015574
0.226486
12,950
329
156
39.361702
0.815514
0.252046
0
0.352041
0
0.020408
0.139281
0
0
0
0
0.00304
0.020408
1
0.035714
false
0
0.091837
0
0.163265
0
0
0
0
null
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
null
0
0
0
0
0
0
0
0
0
0
0
0
1
0
81292f7ed0f85cfcaaa5e1e9abfd5ae7b048469d
4,906
py
Python
hail/python/test/hail/helpers.py
mitochon/hail
25e5e5b8da1d978468d2cee393426ade46484a87
[ "MIT" ]
null
null
null
hail/python/test/hail/helpers.py
mitochon/hail
25e5e5b8da1d978468d2cee393426ade46484a87
[ "MIT" ]
3
2017-06-16T18:10:45.000Z
2017-07-21T17:44:13.000Z
hail/python/test/hail/helpers.py
mitochon/hail
25e5e5b8da1d978468d2cee393426ade46484a87
[ "MIT" ]
2
2018-01-30T00:50:52.000Z
2018-03-22T20:04:01.000Z
import os from timeit import default_timer as timer import unittest import pytest from decorator import decorator from hail.utils.java import Env import hail as hl from hail.backend.local_backend import LocalBackend _initialized = False def startTestHailContext(): global _initialized if not _initialized: backend_name = os.environ.get('HAIL_QUERY_BACKEND', 'spark') if backend_name == 'spark': hl.init(master='local[1]', min_block_size=0, quiet=True) else: Env.hc() # force initialization _initialized = True def stopTestHailContext(): pass _test_dir = os.environ.get('HAIL_TEST_RESOURCES_DIR', '../src/test/resources') _doctest_dir = os.environ.get('HAIL_DOCTEST_DATA_DIR', 'hail/docs/data') def resource(filename): return os.path.join(_test_dir, filename) def doctest_resource(filename): return os.path.join(_doctest_dir, filename) def schema_eq(x, y): x_fds = dict(x) y_fds = dict(y) return x_fds == y_fds def convert_struct_to_dict(x): if isinstance(x, hl.Struct): return {k: convert_struct_to_dict(v) for k, v in x._fields.items()} elif isinstance(x, list): return [convert_struct_to_dict(elt) for elt in x] elif isinstance(x, tuple): return tuple([convert_struct_to_dict(elt) for elt in x]) elif isinstance(x, dict): return {k: convert_struct_to_dict(v) for k, v in x.items()} else: return x _dataset = None def get_dataset(): global _dataset if _dataset is None: _dataset = hl.split_multi_hts(hl.import_vcf(resource('sample.vcf'))).cache() return _dataset def assert_time(f, max_duration): start = timer() x = f() end = timer() assert (start - end) < max_duration print(f'took {end - start:.3f}') return x def create_all_values(): return hl.struct( f32=hl.float32(3.14), i64=hl.int64(-9), m=hl.null(hl.tfloat64), astruct=hl.struct(a=hl.null(hl.tint32), b=5.5), mstruct=hl.null(hl.tstruct(x=hl.tint32, y=hl.tstr)), aset=hl.set(['foo', 'bar', 'baz']), mset=hl.null(hl.tset(hl.tfloat64)), d=hl.dict({hl.array(['a', 'b']): 0.5, hl.array(['x', hl.null(hl.tstr), 'z']): 0.3}), md=hl.null(hl.tdict(hl.tint32, hl.tstr)), h38=hl.locus('chr22', 33878978, 'GRCh38'), ml=hl.null(hl.tlocus('GRCh37')), i=hl.interval( hl.locus('1', 999), hl.locus('1', 1001)), c=hl.call(0, 1), mc=hl.null(hl.tcall), t=hl.tuple([hl.call(1, 2, phased=True), 'foo', hl.null(hl.tstr)]), mt=hl.null(hl.ttuple(hl.tlocus('GRCh37'), hl.tbool)), nd=hl.nd.arange(0, 10).reshape((2, 5)), ) def prefix_struct(s, prefix): return hl.struct(**{prefix + k: s[k] for k in s}) def create_all_values_table(): all_values = create_all_values() return (hl.utils.range_table(5, n_partitions=3) .annotate_globals(**prefix_struct(all_values, 'global_')) .annotate(**all_values) .cache()) def create_all_values_matrix_table(): all_values = create_all_values() return (hl.utils.range_matrix_table(3, 2, n_partitions=2) .annotate_globals(**prefix_struct(all_values, 'global_')) .annotate_rows(**prefix_struct(all_values, 'row_')) .annotate_cols(**prefix_struct(all_values, 'col_')) .annotate_entries(**prefix_struct(all_values, 'entry_')) .cache()) def create_all_values_datasets(): return (create_all_values_table(), create_all_values_matrix_table()) def skip_unless_spark_backend(): from hail.backend.spark_backend import SparkBackend @decorator def wrapper(func, *args, **kwargs): if isinstance(hl.utils.java.Env.backend(), SparkBackend): return func(*args, **kwargs) else: raise unittest.SkipTest('requires Spark') return wrapper fails_local_backend = pytest.mark.xfail( os.environ.get('HAIL_QUERY_BACKEND') == 'local', reason="doesn't yet work on local backend", strict=True) def run_with_cxx_compile(): @decorator def wrapper(func, *args, **kwargs): return return wrapper def assert_evals_to(e, v): res = hl.eval(e) if res != v: raise ValueError(f' actual: {res}\n expected: {v}') def assert_all_eval_to(*expr_and_expected): exprs, expecteds = zip(*expr_and_expected) assert_evals_to(hl.tuple(exprs), expecteds) def lower_only(): @decorator def wrapper(func, *args, **kwargs): flags = hl._get_flags() prev_lower = flags.get('lower') prev_lower_only = flags.get('lower_only') hl._set_flags(lower='1', lower_only='1') try: return func(*args, **kwargs) finally: hl._set_flags(lower=prev_lower, lower_only=prev_lower_only) return wrapper
28.858824
92
0.637994
695
4,906
4.28777
0.305036
0.048322
0.026846
0.031879
0.239597
0.192953
0.119463
0.119463
0.085906
0.085906
0
0.019362
0.220954
4,906
170
93
28.858824
0.760335
0.004077
0
0.167939
0
0
0.068577
0.013306
0
0
0
0
0.038168
1
0.160305
false
0.007634
0.076336
0.045802
0.389313
0.007634
0
0
0
null
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
null
0
0
0
0
0
0
0
0
0
0
0
0
1
0
812941051eea955290efb0cfdb0e29b4664e5ad1
2,728
py
Python
src/entity_linker/models/figer_model/labeling_model.py
mjstrobl/WEXEA
0af0be1cdb93fc00cd81f885aa15ef8d6579b304
[ "Apache-2.0" ]
10
2020-06-14T15:46:53.000Z
2021-04-29T15:02:23.000Z
src/entity_linker/models/figer_model/labeling_model.py
mjstrobl/WEXEA
0af0be1cdb93fc00cd81f885aa15ef8d6579b304
[ "Apache-2.0" ]
3
2021-08-25T16:16:45.000Z
2022-02-10T04:29:10.000Z
src/entity_linker/models/figer_model/labeling_model.py
mjstrobl/WEXEA
0af0be1cdb93fc00cd81f885aa15ef8d6579b304
[ "Apache-2.0" ]
1
2021-02-17T17:44:06.000Z
2021-02-17T17:44:06.000Z
""" Modifications copyright (C) 2020 Michael Strobl """ import time import tensorflow as tf import numpy as np from entity_linker.models.base import Model class LabelingModel(Model): """Unsupervised Clustering using Discrete-State VAE""" def __init__(self, batch_size, num_labels, context_encoded_dim, true_entity_embeddings, word_embed_dim, context_encoded, mention_embed, scope_name, device): self.batch_size = batch_size self.num_labels = num_labels self.word_embed_dim = word_embed_dim with tf.variable_scope(scope_name) as s, tf.device(device) as d: if mention_embed == None: self.label_weights = tf.get_variable( name="label_weights", shape=[context_encoded_dim, num_labels], initializer=tf.random_normal_initializer(mean=0.0, stddev=1.0/(100.0))) else: context_encoded = tf.concat( 1, [context_encoded, mention_embed], name='con_ment_repr') self.label_weights = tf.get_variable( name="label_weights", shape=[context_encoded_dim+word_embed_dim, num_labels], initializer=tf.random_normal_initializer(mean=0.0, stddev=1.0/(100.0))) # [B, L] self.label_scores = tf.matmul(context_encoded, self.label_weights) self.label_probs = tf.sigmoid(self.label_scores) ### PREDICT TYPES FROM ENTITIES #true_entity_embeddings = tf.nn.dropout(true_entity_embeddings, keep_prob=0.5) self.entity_label_scores = tf.matmul(true_entity_embeddings, self.label_weights) self.entity_label_probs = tf.sigmoid(self.label_scores) def loss_graph(self, true_label_ids, scope_name, device_gpu): with tf.variable_scope(scope_name) as s, tf.device(device_gpu) as d: # [B, L] self.cross_entropy_losses = tf.nn.sigmoid_cross_entropy_with_logits( logits=self.label_scores, targets=true_label_ids, name="labeling_loss") self.labeling_loss = tf.reduce_sum( self.cross_entropy_losses) / tf.to_float(self.batch_size) self.enlabel_cross_entropy_losses = tf.nn.sigmoid_cross_entropy_with_logits( logits=self.entity_label_scores, targets=true_label_ids, name="entity_labeling_loss") self.entity_labeling_loss = tf.reduce_sum( self.enlabel_cross_entropy_losses) / tf.to_float(self.batch_size)
40.716418
92
0.615836
328
2,728
4.777439
0.295732
0.051691
0.033184
0.051053
0.48947
0.486918
0.44097
0.35418
0.35418
0.303127
0
0.012061
0.300953
2,728
66
93
41.333333
0.809649
0.079179
0
0.227273
0
0
0.028869
0
0
0
0
0
0
1
0.045455
false
0
0.090909
0
0.159091
0
0
0
0
null
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
null
0
0
0
0
0
0
0
0
0
0
0
0
1
0
812a80140e19ea007dd9ab25b6b57d63cc6eb659
2,425
py
Python
examples/text_classification/yelp_reviews_polarity/train.py
liorshk/simpletransformers
226cf4d11edf5157c1beafcc44aaa78f65ccc985
[ "Apache-2.0" ]
3,151
2019-10-05T11:14:44.000Z
2022-03-31T17:02:54.000Z
examples/text_classification/yelp_reviews_polarity/train.py
liorshk/simpletransformers
226cf4d11edf5157c1beafcc44aaa78f65ccc985
[ "Apache-2.0" ]
1,165
2019-10-05T14:48:55.000Z
2022-03-31T11:12:58.000Z
examples/text_classification/yelp_reviews_polarity/train.py
liorshk/simpletransformers
226cf4d11edf5157c1beafcc44aaa78f65ccc985
[ "Apache-2.0" ]
739
2019-10-06T15:11:54.000Z
2022-03-28T11:07:36.000Z
import sys import pandas as pd from simpletransformers.classification import ClassificationModel prefix = "data/" train_df = pd.read_csv(prefix + "train.csv", header=None) train_df.head() eval_df = pd.read_csv(prefix + "test.csv", header=None) eval_df.head() train_df[0] = (train_df[0] == 2).astype(int) eval_df[0] = (eval_df[0] == 2).astype(int) train_df = pd.DataFrame( {"text": train_df[1].replace(r"\n", " ", regex=True), "labels": train_df[0]} ) print(train_df.head()) eval_df = pd.DataFrame( {"text": eval_df[1].replace(r"\n", " ", regex=True), "labels": eval_df[0]} ) print(eval_df.head()) model_type = sys.argv[1] if model_type == "bert": model_name = "bert-base-cased" elif model_type == "roberta": model_name = "roberta-base" elif model_type == "distilbert": model_name = "distilbert-base-cased" elif model_type == "distilroberta": model_type = "roberta" model_name = "distilroberta-base" elif model_type == "electra-base": model_type = "electra" model_name = "google/electra-base-discriminator" elif model_type == "electra-small": model_type = "electra" model_name = "google/electra-small-discriminator" elif model_type == "xlnet": model_name = "xlnet-base-cased" train_args = { "reprocess_input_data": True, "overwrite_output_dir": True, "use_cached_eval_features": True, "output_dir": f"outputs/{model_type}", "best_model_dir": f"outputs/{model_type}/best_model", "evaluate_during_training": True, "max_seq_length": 128, "num_train_epochs": 3, "evaluate_during_training_steps": 1000, "wandb_project": "Classification Model Comparison", "wandb_kwargs": {"name": model_name}, "save_model_every_epoch": False, "save_eval_checkpoints": False, # "use_early_stopping": True, # "early_stopping_metric": "mcc", # "n_gpu": 2, # "manual_seed": 4, # "use_multiprocessing": False, "train_batch_size": 128, "eval_batch_size": 64, # "config": { # "output_hidden_states": True # } } if model_type == "xlnet": train_args["train_batch_size"] = 64 train_args["gradient_accumulation_steps"] = 2 # Create a ClassificationModel model = ClassificationModel(model_type, model_name, args=train_args) # Train the model model.train_model(train_df, eval_df=eval_df) # # # Evaluate the model # result, model_outputs, wrong_predictions = model.eval_model(eval_df)
25.260417
80
0.68701
327
2,425
4.795107
0.327217
0.086097
0.049745
0.014031
0.234056
0.144133
0.119898
0.034439
0
0
0
0.014293
0.163299
2,425
95
81
25.526316
0.758502
0.124124
0
0.034483
0
0
0.325747
0.1266
0
0
0
0
0
1
0
false
0
0.051724
0
0.051724
0.034483
0
0
0
null
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
null
0
0
0
0
0
0
0
0
0
0
0
0
1
0
812bc4e483e6787a26d9b7a22c0e31832c78af55
5,853
py
Python
mayan/apps/document_signatures/models.py
wan1869/dushuhu
934dd178e67140cffc6b9203e793fdf8bbc73a54
[ "Apache-2.0" ]
null
null
null
mayan/apps/document_signatures/models.py
wan1869/dushuhu
934dd178e67140cffc6b9203e793fdf8bbc73a54
[ "Apache-2.0" ]
null
null
null
mayan/apps/document_signatures/models.py
wan1869/dushuhu
934dd178e67140cffc6b9203e793fdf8bbc73a54
[ "Apache-2.0" ]
1
2021-04-30T09:44:14.000Z
2021-04-30T09:44:14.000Z
import logging import uuid from django.db import models from django.urls import reverse from django.utils.encoding import force_text from django.utils.translation import ugettext_lazy as _ from model_utils.managers import InheritanceManager from mayan.apps.django_gpg.exceptions import VerificationError from mayan.apps.django_gpg.models import Key from mayan.apps.documents.models import DocumentVersion from mayan.apps.storage.classes import DefinedStorageLazy from .literals import STORAGE_NAME_DOCUMENT_SIGNATURES_DETACHED_SIGNATURE from .managers import DetachedSignatureManager, EmbeddedSignatureManager logger = logging.getLogger(name=__name__) def upload_to(*args, **kwargs): return force_text(s=uuid.uuid4()) class SignatureBaseModel(models.Model): """ Fields: * key_id - Key Identifier - This is what identifies uniquely a key. Not two keys in the world have the same Key ID. The Key ID is also used to locate a key in the key servers: http://pgp.mit.edu * signature_id - Signature ID - Every time a key is used to sign something it will generate a unique signature ID. No two signature IDs are the same, even when using the same key. """ document_version = models.ForeignKey( editable=False, on_delete=models.CASCADE, related_name='signatures', to=DocumentVersion, verbose_name=_('Document version') ) # Basic fields date = models.DateField( blank=True, editable=False, null=True, verbose_name=_('Date signed') ) key_id = models.CharField( help_text=_('ID of the key that will be used to sign the document.'), max_length=40, verbose_name=_('Key ID') ) # With proper key signature_id = models.CharField( blank=True, editable=False, null=True, max_length=64, verbose_name=_('Signature ID') ) public_key_fingerprint = models.CharField( blank=True, editable=False, null=True, max_length=40, verbose_name=_('Public key fingerprint') ) objects = InheritanceManager() class Meta: ordering = ('pk',) verbose_name = _('Document version signature') verbose_name_plural = _('Document version signatures') def __str__(self): return self.signature_id or '{} - {}'.format(self.date, self.key_id) def get_absolute_url(self): return reverse( viewname='signatures:document_version_signature_details', kwargs={'signature_id': self.pk} ) def get_key_id(self): if self.public_key_fingerprint: return self.public_key_fingerprint[-16:] else: return self.key_id def get_signature_type_display(self): if self.is_detached: return _('Detached') else: return _('Embedded') @property def is_detached(self): return hasattr(self, 'signature_file') @property def is_embedded(self): return not hasattr(self, 'signature_file') class EmbeddedSignature(SignatureBaseModel): objects = EmbeddedSignatureManager() class Meta: verbose_name = _('Document version embedded signature') verbose_name_plural = _('Document version embedded signatures') def save(self, *args, **kwargs): logger.debug(msg='checking for embedded signature') if self.pk: raw = True else: raw = False with self.document_version.open(raw=raw) as file_object: try: verify_result = Key.objects.verify_file( file_object=file_object ) except VerificationError as exception: # Not signed logger.debug( 'embedded signature verification error; %s', exception ) else: self.date = verify_result.date self.key_id = verify_result.key_id self.signature_id = verify_result.signature_id self.public_key_fingerprint = verify_result.pubkey_fingerprint super(EmbeddedSignature, self).save(*args, **kwargs) class DetachedSignature(SignatureBaseModel): signature_file = models.FileField( blank=True, help_text=_( 'Signature file previously generated.' ), null=True, storage=DefinedStorageLazy( name=STORAGE_NAME_DOCUMENT_SIGNATURES_DETACHED_SIGNATURE ), upload_to=upload_to, verbose_name=_('Signature file') ) objects = DetachedSignatureManager() class Meta: verbose_name = _('Document version detached signature') verbose_name_plural = _('Document version detached signatures') def __str__(self): return '{}-{}'.format(self.document_version, _('signature')) def delete(self, *args, **kwargs): if self.signature_file.name: self.signature_file.storage.delete(name=self.signature_file.name) super(DetachedSignature, self).delete(*args, **kwargs) def save(self, *args, **kwargs): with self.document_version.open() as file_object: try: verify_result = Key.objects.verify_file( file_object=file_object, signature_file=self.signature_file ) except VerificationError as exception: # Not signed logger.debug( 'detached signature verification error; %s', exception ) else: self.signature_file.seek(0) self.date = verify_result.date self.key_id = verify_result.key_id self.signature_id = verify_result.signature_id self.public_key_fingerprint = verify_result.pubkey_fingerprint return super(DetachedSignature, self).save(*args, **kwargs)
34.02907
79
0.651973
655
5,853
5.607634
0.253435
0.016335
0.032399
0.028315
0.350667
0.280697
0.194936
0.172066
0.142663
0.142663
0
0.002323
0.26448
5,853
171
80
34.22807
0.850871
0.07415
0
0.24
0
0
0.113839
0.008371
0
0
0
0
0
1
0.088
false
0
0.104
0.048
0.4
0.048
0
0
0
null
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
null
0
0
0
0
0
0
0
0
0
0
0
0
1
0
812c3f30e6e3ff5facc02e59cfdcff8d05e984ea
2,226
py
Python
scripts/sync_reports_config.py
ramezrawas/galaxy-1
c03748dd49c060a68d07bce56eae33e0ba154414
[ "CC-BY-3.0" ]
6
2018-11-03T22:43:35.000Z
2022-02-15T17:51:33.000Z
scripts/sync_reports_config.py
igorhollaender/OBSOLETE_sirv_dashboard
85aec60b80ef6f561d89398e3da5963d3d0f2aa4
[ "CC-BY-3.0" ]
7
2016-12-07T22:19:37.000Z
2019-01-30T15:04:26.000Z
scripts/sync_reports_config.py
igorhollaender/OBSOLETE_sirv_dashboard
85aec60b80ef6f561d89398e3da5963d3d0f2aa4
[ "CC-BY-3.0" ]
10
2017-04-10T21:40:22.000Z
2022-02-21T16:50:10.000Z
from ConfigParser import ConfigParser from sys import argv REPLACE_PROPERTIES = ["file_path", "database_connection", "new_file_path"] MAIN_SECTION = "app:main" def sync(): # Add or replace the relevant properites from galaxy.ini # into reports.ini reports_config_file = "config/reports.ini" if len(argv) > 1: reports_config_file = argv[1] universe_config_file = "config/galaxy.ini" if len(argv) > 2: universe_config_file = argv[2] parser = ConfigParser() parser.read(universe_config_file) with open(reports_config_file, "r") as f: reports_config_lines = f.readlines() replaced_properties = set([]) with open(reports_config_file, "w") as f: # Write all properties from reports config replacing as # needed. for reports_config_line in reports_config_lines: (line, replaced_property) = get_synced_line(reports_config_line, parser) if replaced_property: replaced_properties.add(replaced_property) f.write(line) # If any properties appear in universe config and not in # reports write these as well. for replacement_property in REPLACE_PROPERTIES: if parser.has_option(MAIN_SECTION, replacement_property) and \ not (replacement_property in replaced_properties): f.write(get_universe_line(replacement_property, parser)) def get_synced_line(reports_line, universe_config): # Cycle through properties to replace and perform replacement on # this line if needed. synced_line = reports_line replaced_property = None for replacement_property in REPLACE_PROPERTIES: if reports_line.startswith(replacement_property) and \ universe_config.has_option(MAIN_SECTION, replacement_property): synced_line = get_universe_line(replacement_property, universe_config) replaced_property = replacement_property break return (synced_line, replaced_property) def get_universe_line(property_name, universe_config): return "%s=%s\n" % (property_name, universe_config.get(MAIN_SECTION, property_name)) if __name__ == '__main__': sync()
35.903226
88
0.700359
271
2,226
5.439114
0.280443
0.079376
0.046133
0.016282
0.191316
0.111262
0.058345
0
0
0
0
0.002326
0.227314
2,226
61
89
36.491803
0.854651
0.13522
0
0.05
0
0
0.052714
0
0
0
0
0
0
1
0.075
false
0
0.05
0.025
0.175
0
0
0
0
null
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
null
0
0
0
0
0
0
0
0
0
0
0
0
1
0
812e0d88c6e6c1e7a35a42781edb6b394196778c
3,838
py
Python
models/utils.py
wyshi/Unsupervised-Structure-Learning
19b49320b46e5f7d990ab9e5b3054b331b86e59d
[ "Apache-2.0" ]
34
2019-06-25T06:21:03.000Z
2022-01-24T06:57:40.000Z
models/utils.py
wyshi/Unsupervised-Structure-Learning
19b49320b46e5f7d990ab9e5b3054b331b86e59d
[ "Apache-2.0" ]
3
2019-07-19T02:33:03.000Z
2021-11-03T09:06:25.000Z
models/utils.py
wyshi/Unsupervised-Structure-Learning
19b49320b46e5f7d990ab9e5b3054b331b86e59d
[ "Apache-2.0" ]
4
2019-06-25T06:46:12.000Z
2021-01-13T06:57:06.000Z
# Original work Copyright (C) 2017 Tiancheng Zhao, Carnegie Mellon University # Modified work Copyright 2018 Weiyan Shi. import tensorflow as tf import numpy as np from nltk.translate.bleu_score import sentence_bleu from nltk.translate.bleu_score import SmoothingFunction def get_bleu_stats(ref, hyps): scores = [] for hyp in hyps: try: scores.append(sentence_bleu([ref], hyp, smoothing_function=SmoothingFunction().method7, weights=[1./3, 1./3,1./3])) except: scores.append(0.0) return np.max(scores), np.mean(scores) def gaussian_kld(recog_mu, recog_logvar, prior_mu, prior_logvar): kld = -0.5 * tf.reduce_sum(1 + (recog_logvar - prior_logvar) - tf.div(tf.pow(prior_mu - recog_mu, 2), tf.exp(prior_logvar)) - tf.div(tf.exp(recog_logvar), tf.exp(prior_logvar)), reduction_indices=1) return kld def norm_log_liklihood(x, mu, logvar): return -0.5*tf.reduce_sum(tf.log(2*np.pi) + logvar + tf.div(tf.pow((x-mu), 2), tf.exp(logvar)), reduction_indices=1) def sample_gaussian(mu, logvar): epsilon = tf.random_normal(tf.shape(logvar), name="epsilon") std = tf.exp(0.5 * logvar) z= mu + tf.multiply(std, epsilon) return z def get_bow(embedding, avg=False): """ Assumption, the last dimension is the embedding The second last dimension is the sentence length. The rank must be 3 """ embedding_size = embedding.get_shape()[2].value if avg: return tf.reduce_mean(embedding, reduction_indices=[1]), embedding_size else: return tf.reduce_sum(embedding, reduction_indices=[1]), embedding_size def get_rnn_encode(embedding, cell, length_mask=None, scope=None, reuse=None): """ Assumption, the last dimension is the embedding The second last dimension is the sentence length. The rank must be 3 The padding should have zero """ with tf.variable_scope(scope, 'RnnEncoding', reuse=reuse): if length_mask is None: length_mask = tf.reduce_sum(tf.sign(tf.reduce_max(tf.abs(embedding), reduction_indices=2)),reduction_indices=1) length_mask = tf.to_int32(length_mask) _, encoded_input = tf.nn.dynamic_rnn(cell, embedding, sequence_length=length_mask, dtype=tf.float32) return encoded_input, cell.state_size def get_bi_rnn_encode(embedding, f_cell, b_cell, length_mask=None, scope=None, reuse=None): """ Assumption, the last dimension is the embedding The second last dimension is the sentence length. The rank must be 3 The padding should have zero """ with tf.variable_scope(scope, 'RnnEncoding', reuse=reuse): if length_mask is None: length_mask = tf.reduce_sum(tf.sign(tf.reduce_max(tf.abs(embedding), reduction_indices=2)),reduction_indices=1) length_mask = tf.to_int32(length_mask) _, encoded_input = tf.nn.bidirectional_dynamic_rnn(f_cell, b_cell, embedding, sequence_length=length_mask, dtype=tf.float32) encoded_input = tf.concat(encoded_input, 1) return encoded_input, f_cell.state_size+b_cell.state_size def get_prob_for_one_sent(vocab_prob, sent, length_mask=None): """ :param vocab_prob: :param sent: :param length_mask: :return: """ tf.boolean_mask(tf.reshape(usr_input_sent, [-1, 50]), tf.sequence_mask(length_mask, 50)) def tf_repeat(tensor, repeats): """ :param tensor: :param repeats: :return: """ with tf.variable_scope("repeat"): expanded_tensor = tf.expand_dims(tensor, -1) multiples = [1] + repeats tiled_tensor = tf.tile(expanded_tensor, multiples=multiples) repeated_tensor = tf.reshape(tiled_tensor, tf.shape(tensor) * repeats) return repeated_tensor
38
132
0.680823
545
3,838
4.594495
0.26789
0.059904
0.040735
0.043131
0.461661
0.414137
0.357428
0.357428
0.357428
0.316693
0
0.018158
0.210787
3,838
101
133
38
0.808518
0.163366
0
0.145455
0
0
0.011316
0
0
0
0
0
0
1
0.163636
false
0
0.072727
0.018182
0.4
0
0
0
0
null
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
null
0
0
0
0
0
0
0
0
0
0
0
0
1
0
812eae9e0a007577935e4a756403808aa1018593
4,927
py
Python
gluoncv/data/transforms/block.py
Kh4L/gluon-cv
849411ed56632cd854850b07142087d599f97dcb
[ "Apache-2.0" ]
5,447
2018-04-25T18:02:51.000Z
2022-03-31T00:59:49.000Z
gluoncv/data/transforms/block.py
Kh4L/gluon-cv
849411ed56632cd854850b07142087d599f97dcb
[ "Apache-2.0" ]
1,566
2018-04-25T21:14:04.000Z
2022-03-31T06:42:42.000Z
gluoncv/data/transforms/block.py
Kh4L/gluon-cv
849411ed56632cd854850b07142087d599f97dcb
[ "Apache-2.0" ]
1,345
2018-04-25T18:44:13.000Z
2022-03-30T19:32:53.000Z
# Licensed to the Apache Software Foundation (ASF) under one # or more contributor license agreements. See the NOTICE file # distributed with this work for additional information # regarding copyright ownership. The ASF licenses this file # to you 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. # coding: utf-8 # pylint: disable= arguments-differ # pylint: disable= missing-docstring "Addtional image transforms." import random import math import numpy as np from mxnet import image, nd from mxnet.gluon import Block __all__ = ['RandomCrop', 'RandomErasing'] class RandomCrop(Block): """Randomly crop `src` with `size` (width, height). Padding is optional. Upsample result if `src` is smaller than `size`. Parameters ---------- size : int or tuple of (W, H) Size of the final output. pad: int or tuple if int, size of the zero-padding if tuple, number of values padded to the edges of each axis. ((before_1, after_1), ... (before_N, after_N)) unique pad widths for each axis. ((before, after),) yields same before and after pad for each axis. (pad,) or int is a shortcut for before = after = pad width for all axes. interpolation : int Interpolation method for resizing. By default uses bilinear interpolation. See OpenCV's resize function for available choices. Inputs: - **data**: input tensor with (Hi x Wi x C) shape. Outputs: - **out**: output tensor with (size[0] x size[1] x C) or (size x size x C) shape. """ def __init__(self, size, pad=None, interpolation=2): super(RandomCrop, self).__init__() numeric_types = (float, int, np.generic) if isinstance(size, numeric_types): size = (size, size) self._args = (size, interpolation) self.pad = ((pad, pad), (pad, pad), (0, 0)) if isinstance(pad, int) else pad def forward(self, x): if self.pad: return image.random_crop(nd.array( np.pad(x.asnumpy(), self.pad, mode='constant', constant_values=0)), *self._args)[0] else: return image.random_crop(x, *self._args)[0] class RandomErasing(Block): """Randomly erasing the area in `src` between `s_min` and `s_max` with `probability`. `ratio` controls the ratio between width and height. `mean` means the value in erasing area. Parameters ---------- probability : float Probability of erasing. s_min : float Min area to all area. s_max : float Max area to all area. ratio : float The ratio between width and height. mean : int or tuple of (R, G, B) The value in erasing area. Inputs: - **data**: input tensor with (Hi x Wi x C) shape. Outputs: - **out**: output tensor with (Hi x Wi x C) shape. """ def __init__(self, probability=0.5, s_min=0.02, s_max=0.4, ratio=0.3, mean=(125.31, 122.96, 113.86)): super(RandomErasing, self).__init__() self.probability = probability self.mean = mean self.s_min = s_min self.s_max = s_max self.ratio = ratio def forward(self, x): if not isinstance(self.probability, float): raise TypeError('Got inappropriate size arg') if not isinstance(self.s_min, float): raise TypeError('Got inappropriate size arg') if not isinstance(self.s_max, float): raise TypeError('Got inappropriate size arg') if not isinstance(self.ratio, float): raise TypeError('Got inappropriate size arg') if not isinstance(self.mean, (int, tuple)): raise TypeError('Got inappropriate size arg') if random.uniform(0, 1) > self.probability: return x width, height, _ = x.shape area = width * height target_area = random.uniform(self.s_min, self.s_max) * area aspect_ratio = random.uniform(self.ratio, 1/self.ratio) w = int(round(math.sqrt(target_area * aspect_ratio))) h = int(round(math.sqrt(target_area / aspect_ratio))) if w < width and h < height: x1 = random.randint(0, width - w) y1 = random.randint(0, height - h) x[x1:x1+w, y1:y1+h, 0] = self.mean[0] x[x1:x1+w, y1:y1+h, 1] = self.mean[1] x[x1:x1+w, y1:y1+h, 2] = self.mean[2] return x
36.496296
99
0.628983
698
4,927
4.363897
0.30659
0.009192
0.024622
0.031188
0.238017
0.205187
0.195666
0.150361
0.122127
0.122127
0
0.017699
0.266085
4,927
134
100
36.768657
0.824668
0.470672
0
0.160714
0
0
0.076766
0
0
0
0
0
0
1
0.071429
false
0
0.089286
0
0.267857
0
0
0
0
null
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
null
0
0
0
0
0
0
0
0
0
0
0
0
1
0
812fdf7c80ff79f192233383d15152b1c334cad3
3,631
py
Python
explore.py
lribiere/explore-mit-bih-arrhythmia-db
44eb2601ed437cb9766ae9cfd3c3553bf108d4f1
[ "MIT" ]
3
2020-02-26T20:01:11.000Z
2020-06-24T17:44:11.000Z
explore.py
lribiere/explore-mit-bih-arrhythmia-db
44eb2601ed437cb9766ae9cfd3c3553bf108d4f1
[ "MIT" ]
2
2020-07-01T09:38:58.000Z
2020-07-01T09:40:02.000Z
explore.py
lribiere/explore-mit-bih-arrhythmia-db
44eb2601ed437cb9766ae9cfd3c3553bf108d4f1
[ "MIT" ]
null
null
null
import plotly.graph_objects as go import streamlit as st import pandas as pd from utils import * import glob import wfdb import os ANNOTATIONS_COL_NAME = 'annotations' ''' # MIT-BIH Arrhythmia DB Exploration ''' record_ids = [os.path.basename(file)[:-4] for file in glob.glob('data/*.dat')] if len(record_ids) == 0: st.write('Warning ! No data could be found under the ./data/ directory.', '*\*.dat*, *\*.hea*, *\*.atr* files and such should be placed ', 'immediately under the ./data/ directory') else: record_ids.sort() record_id = st.selectbox('Select a record id', record_ids) record = wfdb.rdrecord(f'data/{record_id}') annotation = wfdb.rdann(f'data/{record_id}', 'atr') st.write('Signals found in this record :') for idx, signal in enumerate(record.sig_name): st.write(f'- `{signal}` : in {record.units[idx]}, with a frequency of ' f'{record.fs * record.samps_per_frame[idx]}hz') st.write(f'Comments for this record : {record.comments}') signals_df = pd.DataFrame(record.p_signal, columns=record.sig_name) annot_serie = pd.Series(annotation.symbol, index=annotation.sample, name=ANNOTATIONS_COL_NAME) full_df = pd.concat([signals_df, annot_serie], axis=1) ''' ## Annotations ''' beat_annot_count = annot_serie.isin(dict(beat_annotations)).sum() non_beat_annot_count = annot_serie.isin(dict(non_beat_annotations)).sum() unique_annot = annot_serie.value_counts().index.values st.write(f'This record contains `{annot_serie.size}` annotations ' f'among which `{beat_annot_count}` beat annotations and ' f'`{non_beat_annot_count}` non beat annotation(s).') st.write('The annotations are the followings :') for annot in unique_annot: st.write(f'- `{annot}` : {annotation_definitions[annot]}') st.write('More explanations on the annotations are available here : ' 'https://archive.physionet.org/physiobank/annotations.shtml') # Plot counts for each annotation annot_counts_df = annot_serie \ .value_counts() \ .rename_axis(ANNOTATIONS_COL_NAME) \ .reset_index(name='counts') bar_fig = go.Figure(data=[go.Bar(x=annot_counts_df[ANNOTATIONS_COL_NAME], y=annot_counts_df['counts'], text=annot_counts_df['counts'], textposition='auto' )]) bar_fig.update_layout(title='Annotations by count', yaxis_title='counts', xaxis_title='annotations') st.write(bar_fig) ''' ## Explore full dataset ''' signal = st.selectbox('Select a signal', record.sig_name) # Plot signals and annotations matching_rows_by_annot = {} for annot in unique_annot: matching_rows_by_annot[annot] = full_df[ANNOTATIONS_COL_NAME] == annot fig = go.Figure(layout=go.Layout(title=go.layout.Title( text='{} signal with annotations'.format(signal)))) fig.add_trace(go.Scatter(x=full_df.index.values, y=full_df[signal], mode='lines', name=signal)) for annot, annot_matching_rows in matching_rows_by_annot.items(): fig.add_trace(go.Scatter(x=full_df.index[annot_matching_rows].values, y=full_df[annot_matching_rows][signal].values, mode='markers', name='{} (annot)'.format(annot))) st.plotly_chart(fig)
44.82716
79
0.619664
457
3,631
4.722101
0.334792
0.029194
0.041705
0.026413
0.078777
0.059314
0.059314
0.029657
0.029657
0
0
0.001113
0.25778
3,631
80
80
45.3875
0.799629
0.016524
0
0.030303
0
0
0.255184
0.024482
0
0
0
0
0
1
0
false
0
0.106061
0
0.106061
0
0
0
0
null
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
null
0
0
0
0
0
0
0
0
0
0
0
0
1
0
81353ee4f1a632a7e8022d2ce8c431b95559fb7b
12,262
py
Python
traitarm/reconstruction/visualize_recon.py
hzi-bifo/Model-T
197b52f6fe9b73e0411dbfc66f6d2a43081f5697
[ "Apache-2.0" ]
1
2021-04-07T16:10:55.000Z
2021-04-07T16:10:55.000Z
traitarm/reconstruction/visualize_recon.py
hzi-bifo/Model-T
197b52f6fe9b73e0411dbfc66f6d2a43081f5697
[ "Apache-2.0" ]
null
null
null
traitarm/reconstruction/visualize_recon.py
hzi-bifo/Model-T
197b52f6fe9b73e0411dbfc66f6d2a43081f5697
[ "Apache-2.0" ]
null
null
null
import pandas as pd import ete2 from ete2 import faces, Tree, AttrFace, TreeStyle import pylab from matplotlib.colors import hex2color, rgb2hex, hsv_to_rgb, rgb_to_hsv kelly_colors_hex = [ 0xFFB300, # Vivid Yellow 0x803E75, # Strong Purple 0xFF6800, # Vivid Orange 0xA6BDD7, # Very Light Blue 0xC10020, # Vivid Red 0xCEA262, # Grayish Yellow 0x817066, # Medium Gray # The following don't work well for people with defective color vision 0x007D34, # Vivid Green 0xF6768E, # Strong Purplish Pink 0x00538A, # Strong Blue 0xFF7A5C, # Strong Yellowish Pink 0x53377A, # Strong Violet 0xFF8E00, # Vivid Orange Yellow 0xB32851, # Strong Purplish Red 0xF4C800, # Vivid Greenish Yellow 0x7F180D, # Strong Reddish Brown 0x93AA00, # Vivid Yellowish Green 0x593315, # Deep Yellowish Brown 0xF13A13, # Vivid Reddish Orange 0x232C16, # Dark Olive Green ] def my_layout(node): if node.is_leaf(): # If terminal node, draws its name name_face = AttrFace("name") else: # If internal node, draws label with smaller font size name_face = AttrFace("name", fsize=10) # Adds the name face to the image at the preferred position faces.add_face_to_node(name_face, node, column=0, position="branch-right") def adjust_kelly_brightness(hex_color, val, recon_min, recon_max): """set brightness according to change in continuous reconstruction value""" h, s, v = rgb_to_hsv(hex2color('#{0:06X}'.format(hex_color))) scale_factor = 1 - (recon_max - val) / (recon_max - recon_min) v_new = v - (v * (scale_factor)) return rgb2hex(hsv_to_rgb(pd.np.array([h, s, v_new]))) def get_style(): ts = TreeStyle() # Do not add leaf names automatically ts.show_leaf_name = False ts.show_scale = True ts.force_topology = False # Use my custom layout ts.layout_fn = my_layout return ts def plot_tree(pt_tree, target_node, out): #pt_tree, feats, pf2color = get_tree(phenotype = phenotype, feat_list = "top_cor", is_ml_plus_phypat = True, target_node = target_node) pt_tree.dist = 0 target = pt_tree.search_nodes(name = target_node)[0] target.render(out + '_tree.pdf', tree_style = get_style()) #target.render(out + '_tree.png', tree_style = get_style()) return target, feats, pf2color def plot_legend(feats, out, pf2color, pf_desc = False, pf_acc = True, include_class = False): fig = pylab.figure() figlegend = pylab.figure(figsize = (9, 6)) ax = fig.add_subplot(111) x = [0,1] lines = [ax.plot(x, pd.np.ones(len(x)), 'o', color = "#%06x" % (pf2color[feats.index[i]]))[0] for i in range(len(pf2color))] labels= [i for i in feats.index] #labels= ["%s" %(feats.loc[:,"Pfam_acc"].iloc[i]) for i in range(feats.shape[0])] #if include_class: # labels= ["%s %s" %(labels[i], feats.loc[:, "class"].iloc[i]) for i in range(len(labels))] #if pf_desc: # labels = ["%s %s" % (labels[i], pf2short_desc.loc[feats.loc[:,"Pfam_acc"].iloc[i], 1]) for i in range(len(labels))] #if pf_acc: # labels = ["%s %s" % (labels[i], pf2acc.loc[feats.loc[:,"Pfam_acc"].iloc[i], 1]) for i in range(len(labels))] figlegend.legend(lines, labels, markerscale = 2.5, numpoints = 1, frameon = False) #fig.show() fig.tight_layout() figlegend.savefig(out + "_legend.svg") figlegend.savefig(out + "_legend.png") return figlegend def get_tree(phenotype, tree, gain_recon, loss_recon, node_recon, pfam_mapping, feat_list, sample_mapping, threshold = 0.5, target_node = None, are_continuous_features_with_discrete_phenotype = False, max_feats = 10, miscl = None, node_annotation = None): #read target feats feats = pd.read_csv(feat_list, index_col = 0, sep = "\t") pt_tree = ete2.Tree(tree, format = 1) pt_tree.ladderize() if not node_annotation is None: node_table = pd.read_csv(node_annotation, sep = "\t", index_col = 0) sample_mapping = pd.read_csv(sample_mapping, index_col = 0, sep = "\t") #read node and edge reconstruction matrices node_recon = pd.read_csv(node_recon, sep = "\t", index_col = 0) gain_recon = pd.read_csv(gain_recon, sep = "\t", index_col = 0) gain_recon.index = ["_".join(("_".join(i.split("_")[:-1]), i.split("_")[-1])) for i in gain_recon.index.values] loss_recon = pd.read_csv(loss_recon, sep = "\t", index_col = 0) loss_recon.index = ["_".join(("_".join(i.split("_")[:-1]), i.split("_")[-1])) for i in loss_recon.index.values] #prune to target node if target_node is not None: pt_tree = pt_tree.search_nodes(name = target_node)[0] node2name = dict((i.name, i.name) for i in pt_tree.traverse(strategy = 'preorder')) pfams_with_event = set() pfam2color = {} #set the style of the branches and nodes according to the posterior probability top10_feats = feats.iloc[:max_feats,] #for visualization of continuous feature get the range of values for each feature if are_continuous_features_with_discrete_phenotype: recon_min = gain_recon.abs().apply(pd.np.min) recon_max = gain_recon.abs().apply(pd.np.max) if not miscl is None: miscl_m = pd.read_csv(miscl, sep = "\t", index_col = 0) for n in pt_tree.traverse(): #ignore the root if n.name == "N1": continue if not node_annotation is None: if n.name in node_table.index: for attr,i in zip(node_table.columns, range(len(node_table.columns))): value = node_table.loc[n.name, attr] if not pd.isnull(value): if value == 0: rf = ete2.CircleFace(radius = 8, style = "circle", color = 'red') elif value == 2: rf = faces.CircleFace(radius = 8, style = "circle", color = 'orange') else: rf = faces.CircleFace(radius = 8, style = "circle", color = 'green') else: rf = faces.CircleFace(radius = 8, style = "circle", color = 'grey') n.add_face(rf, column = i, position = "aligned") ns = node_recon.loc[n.name, phenotype] style = ete2.NodeStyle() style["shape"] = 'square' style['size'] = 10 if pd.isnull(ns): style['fgcolor'] = 'grey' elif ns < threshold: style['fgcolor'] = 'darkred' else: style['fgcolor'] = 'green' if not n.name == "N1": branch_id = n.name + "_" + n.up.name if gain_recon.loc[branch_id, phenotype] > threshold: style["hz_line_type"] = 1 style["hz_line_color"] = 'green' style["hz_line_width"] = 3 elif loss_recon.loc[branch_id, phenotype] > threshold: style["hz_line_type"] = 1 style["hz_line_color"] = 'red' style["hz_line_width"] = 3 else: style["hz_line_type"] = 0 style["hz_line_color"] = 'black' n.set_style(style) #check if sample was misclassified and add misclassified label if not miscl is None: if node2name[n.name] in miscl_m.index: tf = faces.TextFace("misclassified") n.add_face(tf, column = 0, position = "branch-right") #set species name instead of tax id if n.name in sample_mapping.index: node2name[n.name] = sample_mapping.loc[n.name,][0] #add majority feature gains and losses events = [] for i in range(top10_feats.shape[0]): if not are_continuous_features_with_discrete_phenotype: cf = faces.CircleFace(radius = 8, style = "circle", color = kelly_colors_hex[i]) #gain events if gain_recon.loc[branch_id, top10_feats.index[i]] > threshold: pfam2color[top10_feats.index[i]] = kelly_colors_hex[i] tf = faces.TextFace("-") events.append(tf) pfams_with_event.add(node_recon.index[i]) events.append(cf) #loss events elif loss_recon.loc[branch_id, top10_feats.index[i]] > threshold: pfam2color[top10_feats.index[i]] = kelly_colors_hex[i] tf = faces.TextFace("-") events.append(tf) pfams_with_event.add(node_recon.index[i]) events.append(cf) #continuous features else: adjusted_color = adjust_kelly_brightness(kelly_colors_hex[i], abs(loss_recon.loc[branch_id, top10_feats.index[i]]), recon_min.loc[top10_feats.index[i]], recon_max.loc[top10_feats.index[i]]) #tf = faces.TextFace(gain_recon.loc[branch_id, top10_feats.index[i]]) if loss_recon.loc[branch_id, top10_feats.index[i]] < 0: tf = faces.TextFace("-") else: tf = faces.TextFace("+") cf = faces.CircleFace(radius = 8, style = "circle", color = adjusted_color) pfam2color[top10_feats.index[i]] = kelly_colors_hex[i] pfams_with_event.add(node_recon.index[i]) events.append(cf) events.append(tf) for i in range(len(events)): n.add_face(events[i], column = i, position = "branch-top") for n in pt_tree.traverse(): if n.name in node2name: n.name = node2name[n.name] #filtered_pfams = filter(lambda i: i in list(pfams_with_event), top10_feats.loc[:,"Pfam_acc"].values) #print filtered_pfams #filtered_ids = pt_gt2id.loc[filtered_pfams, 0] - 1 #print filtered_ids #top10_feats_with_event = top10_feats.loc[filtered_ids,] #process node annotation return pt_tree, top10_feats, pfam2color if __name__ == "__main__": import argparse parser = argparse.ArgumentParser("""visualize target list of features""") parser.add_argument("node_recon", help = "node ancestral character state reconstruction") parser.add_argument("gain_recon", help = "gain events ancestral character state reconstruction") parser.add_argument("loss_recon", help = "loss events ancestral character state reconstruction") parser.add_argument("tree", help = "tree with internal nodes labeled") parser.add_argument("pfam_mapping", help = "feature mapping/list") parser.add_argument("feat_list", help = "list of features") parser.add_argument("--target_node", default = "N1", help = "list of features") parser.add_argument("phenotype", help = "target phenotype") parser.add_argument("--are_continuous_features_with_discrete_phenotype", action = 'store_true', help = "set if using continuous features with a discrete phenotype") parser.add_argument("threshold", type = float, help = "threshold to call genotype/phenotype events") parser.add_argument("sample_mapping", help = "mapping between sample ids and names") parser.add_argument("out", help = "output file") parser.add_argument("--max_feats", type = int, default = 10, help = "visualize at most max_feats features") parser.add_argument("--miscl", help = "table of misclassified samples") parser.add_argument("--node_annotation", help = "table of binary features for labeling the nodes") a = parser.parse_args() pt_tree, feats, pf2color = get_tree(node_recon = a.node_recon, gain_recon = a.gain_recon, loss_recon = a.loss_recon, pfam_mapping = a.pfam_mapping, tree = a.tree, feat_list = a.feat_list, phenotype = a.phenotype, target_node = a.target_node, threshold = a.threshold, sample_mapping = a.sample_mapping, are_continuous_features_with_discrete_phenotype = a.are_continuous_features_with_discrete_phenotype, max_feats = a.max_feats, miscl = a.miscl, node_annotation = a.node_annotation) plot_tree(pt_tree, a.target_node, a.out) plot_legend(feats, a.out, pf2color)
52.178723
485
0.621921
1,627
12,262
4.484942
0.200983
0.021927
0.034946
0.021927
0.317254
0.271344
0.192682
0.175689
0.123475
0.0899
0
0.025686
0.260235
12,262
234
486
52.401709
0.778745
0.169711
0
0.171123
0
0
0.110266
0.004841
0
0
0.015809
0
0
1
0.032086
false
0
0.032086
0
0.090909
0
0
0
0
null
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
null
0
0
0
0
0
0
0
0
0
0
0
0
1
0
813a4523ca5ed1d20d9dca5c73420720f380885a
1,090
py
Python
examples/dhc/rule_example.py
fruttasecca/hay_checker
2bbf4e8e90e0abc590dd74080fb6e4f445056354
[ "MIT" ]
2
2019-05-22T08:24:38.000Z
2020-12-04T13:36:30.000Z
examples/dhc/rule_example.py
fruttasecca/hay_checker
2bbf4e8e90e0abc590dd74080fb6e4f445056354
[ "MIT" ]
null
null
null
examples/dhc/rule_example.py
fruttasecca/hay_checker
2bbf4e8e90e0abc590dd74080fb6e4f445056354
[ "MIT" ]
3
2018-09-15T13:40:40.000Z
2021-06-29T23:31:18.000Z
#!/usr/bin/python3 from pyspark.sql import SparkSession from haychecker.dhc.metrics import rule spark = SparkSession.builder.appName("rule_example").getOrCreate() df = spark.read.format("csv").option("header", "true").load("examples/resources/employees.csv") df.show() condition1 = {"column": "salary", "operator": "gt", "value": 2100} conditions = [condition1] r1 = rule(conditions, df)[0] print("Rule salary>2100: {}".format(r1)) condition1 = {"column": "salary", "operator": "lt", "value": 2100} condition2 = {"column": "title", "operator": "eq", "value": "Sales Representative"} conditions = [condition1, condition2] task1 = rule(conditions) condition1 = {"column": "salary", "operator": "lt", "value": 2100} condition2 = {"column": "city", "operator": "eq", "value": "London"} conditions = [condition1, condition2] task2 = rule(conditions) task3 = task1.add(task2) result = task3.run(df) r1 = result[0]["scores"][0] r2 = result[1]["scores"][0] print("Rule salary<2100 and title=\"Sales Representative\": {}," " rule salary<2100 and city=\"London\": {}".format(r1, r2))
31.142857
95
0.678899
132
1,090
5.598485
0.439394
0.108254
0.08931
0.121786
0.20839
0.154263
0.154263
0.154263
0.154263
0
0
0.053775
0.112844
1,090
35
96
31.142857
0.710445
0.015596
0
0.173913
0
0
0.290774
0.029823
0
0
0
0
0
1
0
false
0
0.086957
0
0.086957
0.086957
0
0
0
null
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
null
0
0
0
0
0
0
0
0
0
0
0
0
1
0
813a8ce209fa6c27b191963bd6e67321e4277566
10,579
py
Python
secure_message/common/utilities.py
uk-gov-mirror/ONSdigital.ras-secure-message
741eed651eea47dd1a13c7c93b1b1796584cdf2b
[ "MIT" ]
null
null
null
secure_message/common/utilities.py
uk-gov-mirror/ONSdigital.ras-secure-message
741eed651eea47dd1a13c7c93b1b1796584cdf2b
[ "MIT" ]
null
null
null
secure_message/common/utilities.py
uk-gov-mirror/ONSdigital.ras-secure-message
741eed651eea47dd1a13c7c93b1b1796584cdf2b
[ "MIT" ]
null
null
null
import collections import logging import urllib.parse from structlog import wrap_logger from secure_message.constants import MESSAGE_BY_ID_ENDPOINT, MESSAGE_LIST_ENDPOINT, MESSAGE_QUERY_LIMIT from secure_message.services.service_toggles import party, internal_user_service logger = wrap_logger(logging.getLogger(__name__)) MessageArgs = collections.namedtuple( 'MessageArgs', 'page limit business_id surveys cc label desc ce is_closed my_conversations new_respondent_conversations all_conversation_types unread_conversations') def get_options(args): # NOQA pylint:disable=too-complex """extract options from request , allow label to be set by caller :param args: contains search arguments. Not all end points support all args :returns: MessageArgs named tuple containing the args for the search business_id If set , restricts search to conversations regarding this specific party id surveys If set allows the count to be restricted by a list of survey_ids cc If set , allows the count to be restricted by a particular case ce If set, alows the count to be restricted by a particular collection exercise is_closed If set to 'true' only counts closed conversations, else only open conversations my_conversations If set to 'true only counts my conversations. I.e conversations where the current user id is the to actor id new_respondent_conversations If set to 'true'only counts conversations where the to actor is set to 'GROUP' all_conversation_types If set 'true', overrides is_closed, my_conversations and new_respondent_conversations and returns 4 counts 1 for each of , open , closed, my_conversations and new_respondent_conversations page If set requests the specific page of information to return limit If set it sets the maximum number of results to return desc If present, requests the information in descending order """ fields = {'page': 1, 'limit': MESSAGE_QUERY_LIMIT, 'business_id': None, 'surveys': None, 'desc': True, 'cc': None, 'label': None, 'ce': None, 'is_closed': False, 'my_conversations': False, 'new_respondent_conversations': False, 'all_conversation_types': False, 'unread_conversations': False} for field in ['cc', 'ce', 'business_id', 'label']: if args.get(field): fields[field] = str(args.get(field)) fields['surveys'] = args.getlist('survey') for field in ['limit', 'page']: if args.get(field): fields[field] = int(args.get(field)) if args.get('desc') == 'false': fields['desc'] = False if args.get('is_closed') == 'true': fields['is_closed'] = True if args.get('my_conversations') == 'true': fields['my_conversations'] = True if args.get('new_respondent_conversations') == 'true': fields['new_respondent_conversations'] = True if args.get('all_conversation_types') == 'true': fields['all_conversation_types'] = True if args.get('unread_conversations') == 'true': fields['unread_conversations'] = True return MessageArgs(page=fields['page'], limit=fields['limit'], business_id=fields['business_id'], surveys=fields['surveys'], cc=fields['cc'], label=fields['label'], desc=fields['desc'], ce=fields['ce'], is_closed=fields['is_closed'], my_conversations=fields['my_conversations'], new_respondent_conversations=fields['new_respondent_conversations'], all_conversation_types=fields['all_conversation_types'], unread_conversations=fields['unread_conversations']) def set_conversation_type_args(existing_args, is_closed=False, my_conversations=False, new_conversations=False, all_types=False, unread_conversations=False): """Returns a new set of args based on the existing args which are a named tuple, but allow the conversation type only to be changed""" return MessageArgs(page=existing_args.page, limit=existing_args.limit, business_id=existing_args.business_id, surveys=existing_args.surveys, cc=existing_args.cc, label=existing_args.label, desc=existing_args.desc, ce=existing_args.ce, is_closed=is_closed, my_conversations=my_conversations, new_respondent_conversations=new_conversations, all_conversation_types=all_types, unread_conversations=unread_conversations) def generate_string_query_args(args): params = {} for field in args._fields: if field in ['page']: continue value = getattr(args, field) if value: params[field] = value return urllib.parse.urlencode(params) def process_paginated_list(paginated_list, host_url, user, message_args, endpoint=MESSAGE_LIST_ENDPOINT, body_summary=True): """used to change a pagination object to json format with links""" messages = [] string_query_args = generate_string_query_args(message_args) for message in paginated_list.items: msg = message.serialize(user, body_summary=body_summary) msg['_links'] = {"self": {"href": f"{host_url}{MESSAGE_BY_ID_ENDPOINT}/{msg['msg_id']}"}} messages.append(msg) links = {'first': {"href": f"{host_url}{endpoint}"}, 'self': {"href": f"{host_url}{endpoint}?{string_query_args}&page={message_args.page}"}} if paginated_list.has_next: links['next'] = { "href": f"{host_url}{endpoint}?{string_query_args}&page={message_args.page + 1}"} if paginated_list.has_prev: links['prev'] = { "href": f"{host_url}{endpoint}?{string_query_args}&page={message_args.page - 1}"} return messages, links def add_to_details(messages): """Adds a @msg_to key to every message in a list of messages. Every msg_to uuid is resolved to include details of the user. If the call for the internal user id fails, an exception will be thrown. If the external user id cannot be found in the list that we got from the party service. There won't be a @msg_to value returned in the payload. The API documentation notes that these elements aren't guaranteed to be provided so we're not breaking the contract by doing this. Note: Several of these lines of code could be combined into a more succinct view, spreading them out is deliberate so that log stack traces are better able to identify the cause of log errors """ external_user_details = {} for user in party.get_users_details(get_external_user_uuid_list(messages)): external_user_details[user['id']] = user for message in messages: try: msg_to = message["msg_to"][0] from_internal = message["from_internal"] if not from_internal: msg_to_details = internal_user_service.get_user_details(msg_to) message.update({"@msg_to": [msg_to_details]}) else: msg_to_details = external_user_details.get(msg_to) if msg_to_details: message.update({'@msg_to': [msg_to_details]}) else: logger.info("No details found for the message recipient", msg_to=msg_to) except IndexError: logger.exception("Exception adding to details", msg_to=msg_to, from_internal=from_internal) raise return messages def add_from_details(messages): """Adds a @msg_from key to every message in a list of messages. Every msg_to uuid is resolved to include details of the user. If the call for the internal user id fails, an exception will be thrown. If the external user id cannot be found in the list that we got from the party service. There won't be a @msg_from value returned in the payload. The API documentation notes that these elements aren't guaranteed to be provided so we're not breaking the contract by doing this. """ external_user_details = {} for user in party.get_users_details(get_external_user_uuid_list(messages)): external_user_details[user['id']] = user for message in messages: try: msg_from = message["msg_from"] from_internal = message["from_internal"] if from_internal: message.update({"@msg_from": internal_user_service.get_user_details(msg_from)}) else: if external_user_details.get(message['msg_from']): message.update({'@msg_from': external_user_details.get(msg_from)}) except IndexError: logger.exception("Exception adding from details message", msg_from=msg_from, from_internal=from_internal) raise return messages def get_external_user_uuid_list(messages): """Compiles a list of all unique the external user (respondent) uuids from a list of messages""" external_user_uuids = set() external_msgs = [message for message in messages if message['from_internal'] is False] for message in external_msgs: external_user_uuids.add(message["msg_from"]) internal_messages = [message for message in messages if message['from_internal'] is True] for uuid in internal_messages: external_user_uuids.add(uuid["msg_to"][0]) return external_user_uuids def add_business_details(messages): """Adds a @business_details key to every message in a list of messages.""" business_ids = set() for message in messages: business_ids.add(message['business_id']) business_details = party.get_business_details(business_ids) for message in messages: message['@business_details'] = next((business for business in business_details if business["id"] == message['business_id']), None) return messages def add_users_and_business_details(messages): """Add both user and business details to messages based on data from party service""" if not messages: raise ValueError('messages is a required parameter and must not be empty') messages = add_to_details(messages) messages = add_from_details(messages) logger.info("Successfully added to and from details") messages = add_business_details(messages) logger.info("Successfully added business details") return messages
43.714876
154
0.680121
1,392
10,579
4.964799
0.181034
0.01447
0.037621
0.017364
0.392707
0.333237
0.270149
0.225004
0.195341
0.190421
0
0.000865
0.23471
10,579
241
155
43.896266
0.852767
0.269874
0
0.186207
0
0
0.187293
0.065255
0
0
0
0
0
1
0.062069
false
0
0.041379
0
0.165517
0
0
0
0
null
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
null
0
0
0
0
0
0
0
0
0
0
0
0
1
0
813b149e48d21390532f6bf57e32e5f1ed05f482
8,353
py
Python
notegame/games/nonogram/core/renderer.py
notechats/notegame
3d9538b98cb6b0b240956b1271e028b22458fc54
[ "Apache-2.0" ]
null
null
null
notegame/games/nonogram/core/renderer.py
notechats/notegame
3d9538b98cb6b0b240956b1271e028b22458fc54
[ "Apache-2.0" ]
null
null
null
notegame/games/nonogram/core/renderer.py
notechats/notegame
3d9538b98cb6b0b240956b1271e028b22458fc54
[ "Apache-2.0" ]
null
null
null
# -*- coding: utf-8 -*- """ Defines various renderers for the game of nonogram """ from abc import ABC from sys import stdout from notetool.tool.log import logger from six import integer_types, itervalues, text_type from ..utils.iter import max_safe, pad from ..utils.other import two_powers from .common import BOX, SPACE, UNKNOWN, BlottedBlock, is_list_like class Cell(object): """Represent basic rendered cell""" DEFAULT_ICON = ' ' def __init__(self, icon=None): self.icon = icon or self.DEFAULT_ICON def ascii_icon(self): """How the cell can be printed as a text""" return self.DEFAULT_ICON def __repr__(self): return '{}()'.format(self.__class__.__name__) class ThumbnailCell(Cell): """ Represent upper-left cell (where the thumbnail of the puzzle usually drawn). """ DEFAULT_ICON = '#' class ClueCell(Cell): """ Represent cell that is part of description (clue). They are usually drawn on the top and on the left. """ BLOTTED_SYMBOL = '?' def __init__(self, value): super(ClueCell, self).__init__() if is_list_like(value): self.value, self.color = value else: self.value, self.color = value, None def ascii_icon(self): """ Gets a symbolic representation of a cell given its state and predefined table `icons` """ if isinstance(self.value, integer_types): return text_type(self.value) if self.value == BlottedBlock: return self.BLOTTED_SYMBOL return self.DEFAULT_ICON def __repr__(self): return '{}(({}, {}))'.format( self.__class__.__name__, self.value, self.color) class GridCell(Cell): """Represent the main area cell""" def __init__(self, value, renderer, colored=False): super(GridCell, self).__init__() self.renderer = renderer self.colored = colored if self.colored: self.value = tuple(two_powers(value)) else: self.value = value def ascii_icon(self): value = self.value icons = self.renderer.icons if not self.colored: return icons[self.value] if len(value) == 1: value = value[0] else: # multiple colors value = UNKNOWN symbol = self.renderer.board.symbol_for_color_id(value) if symbol is not None: return symbol return icons.get(value, self.DEFAULT_ICON) def __repr__(self): return '{}({})'.format( self.__class__.__name__, self.value) class _DummyBoard(object): """ Stub for renderer initialization when it created before the corresponding board """ rows_descriptions = columns_descriptions = () width = height = 0 class Renderer(object): """Defines the abstract renderer for a nonogram board""" def __init__(self, board=None): self.cells = None self.board = None self.board_init(board) def board_init(self, board=None): """Initialize renderer's properties dependent on board it draws""" if board: logger.info('Init %r renderer with board %r', self.__class__.__name__, board) else: if self.board: return # already initialized, do nothing board = _DummyBoard() self.board = board @property def full_height(self): """The full visual height of a board""" return self.header_height + self.board.height @property def full_width(self): """The full visual width of a board""" return self.side_width + self.board.width @property def header_height(self): """The size of the header block with columns descriptions""" return max_safe(map(len, self.board.columns_descriptions), default=0) @property def side_width(self): """The width of the side block with rows descriptions""" return max_safe(map(len, self.board.rows_descriptions), default=0) def render(self): """Actually print out the board""" raise NotImplementedError() def draw(self, cells=None): """Calculate all the cells and draw an image of the board""" self.draw_header() self.draw_side() self.draw_grid(cells=cells) self.render() def draw_header(self): """ Changes the internal state to be able to draw columns descriptions """ raise NotImplementedError() def draw_side(self): """ Changes the internal state to be able to draw rows descriptions """ raise NotImplementedError() def draw_grid(self, cells=None): """ Changes the internal state to be able to draw a main grid """ raise NotImplementedError() @property def is_colored(self): """Whether the linked board is colored board""" return self.board.is_colored class StreamRenderer(Renderer, ABC): """ Simplify textual rendering of a board to a stream (stdout by default) """ DEFAULT_ICONS = { UNKNOWN: '_', BOX: 'X', SPACE: '.', } def __init__(self, board=None, stream=stdout, icons=None): self.stream = stream if icons is None: icons = dict(self.DEFAULT_ICONS) self.icons = icons super(StreamRenderer, self).__init__(board) def _print(self, *args): return print(*args, file=self.stream) class BaseAsciiRenderer(StreamRenderer): """ Renders a board as a simple text table (without grid) """ __rend_name__ = 'text' def board_init(self, board=None): super(BaseAsciiRenderer, self).board_init(board) logger.info('init cells: %sx%s', self.full_width, self.full_width) self.cells = [[Cell()] * self.full_width for _ in range(self.full_height)] def cell_icon(self, cell): """ Get a symbolic representation of a cell given its state and predefined table `icons` """ return cell.ascii_icon() def render(self): for row in self.cells: res = [] for index, cell in enumerate(row): ico = self.cell_icon(cell) # do not pad the last symbol in a line if len(ico) == 1: if index < len(row) - 1: ico += ' ' res.append(ico) self._print(''.join(res)) def draw_header(self): for i in range(self.header_height): for j in range(self.side_width): self.cells[i][j] = ThumbnailCell() for j, col in enumerate(self.board.columns_descriptions): rend_j = j + self.side_width if not col: col = [0] rend_column = [ClueCell(val) for val in col] rend_column = pad(rend_column, self.header_height, Cell()) # self.cells[:self.header_height, rend_j] = rend_column for i, cell in enumerate(rend_column): self.cells[i][rend_j] = cell def draw_side(self): for i, row in enumerate(self.board.rows_descriptions): rend_i = i + self.header_height # row = list(row) if not row: row = [0] rend_row = [ClueCell(val) for val in row] rend_row = pad(rend_row, self.side_width, Cell()) self.cells[rend_i][:self.side_width] = rend_row def draw_grid(self, cells=None): if cells is None: cells = self.board.cells is_colored = self.is_colored for i, row in enumerate(cells): rend_i = i + self.header_height for j, val in enumerate(row): rend_j = j + self.side_width self.cells[rend_i][rend_j] = GridCell( val, self, colored=is_colored) def _register_renderers(): res = dict() for obj in itervalues(globals()): if isinstance(obj, type): if issubclass(obj, StreamRenderer) and hasattr(obj, '__rend_name__'): res[obj.__rend_name__] = obj return res RENDERERS = _register_renderers()
27.386885
81
0.587932
1,016
8,353
4.641732
0.20374
0.032443
0.020356
0.015267
0.217133
0.147159
0.108991
0.108991
0.092027
0.084182
0
0.001741
0.312463
8,353
304
82
27.476974
0.819432
0.177062
0
0.198864
0
0
0.014127
0
0
0
0
0
0
1
0.170455
false
0
0.039773
0.022727
0.414773
0.017045
0
0
0
null
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
null
0
0
0
0
0
0
0
0
0
0
0
0
1
0
813c2d5f4577a87860a81df5e212cf9b2d380367
1,690
py
Python
python/fill_na_v2.py
fredmell/CS229Project
b214127485ddc587b9fe3be253937ba8378f9db7
[ "MIT" ]
null
null
null
python/fill_na_v2.py
fredmell/CS229Project
b214127485ddc587b9fe3be253937ba8378f9db7
[ "MIT" ]
null
null
null
python/fill_na_v2.py
fredmell/CS229Project
b214127485ddc587b9fe3be253937ba8378f9db7
[ "MIT" ]
1
2020-06-01T00:36:06.000Z
2020-06-01T00:36:06.000Z
""" Fill na with most common of the whole column """ import numpy as np import pandas as pd import time import matplotlib.pyplot as plt from datetime import datetime import re from collections import Counter from statistics import median from tqdm import tqdm def find_most_common_value(element_list): for element in element_list: if not pd.isna(element): break if pd.isna(element): return np.nan elif isinstance(element, np.double): array = np.array(element_list) array = array[~np.isnan(array)] if len(array) == 0: return np.nan else: array = array.astype(np.int) return np.double(np.bincount(array).argmax()) elif isinstance(element, str): count = Counter(df[col]) try: del count[np.nan] except ValueError: pass if count == dict(): return np.nan else: return count.most_common(1)[0][0] file = '/home/nicolasbievre/yelp_data.pkl' file_na = '/home/nicolasbievre/yelp_data_no_na.pkl' df = pd.read_pickle(file) categories = list(set(df['categories'].values)) n = len(categories) for i in tqdm(range(len(df.columns))): col = df.columns[i] if not col in {'review_id': 0, 'business_id': 0, 'user_id': 0, 'postal_code': 0}: df_col = df[col].values na = sum(pd.isna(df_col)) if na > 0: most_commom_term = find_most_common_value(df_col) if not pd.isna(most_commom_term): df.loc[(pd.isna(df_col)), col] = most_commom_term if i % 35 == 0 and i > 0: df.to_pickle(file_na) df.to_pickle(file_na)
23.472222
85
0.611243
246
1,690
4.060976
0.373984
0.03003
0.033033
0.038038
0.032032
0
0
0
0
0
0
0.010664
0.278698
1,690
71
86
23.802817
0.80886
0.026036
0
0.14
0
0
0.07326
0.043956
0
0
0
0
0
1
0.02
false
0.02
0.18
0
0.3
0
0
0
0
null
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
null
0
0
0
0
0
0
0
0
0
0
0
0
1
0
813cbfb2b0206a03eec11ec90ba51dbd9b92d6bd
3,071
py
Python
GUI Applications/calc.py
jaiswalIT02/pythonprograms
bc94e52121202b04c3e9112d9786f93ed6707f7a
[ "MIT" ]
null
null
null
GUI Applications/calc.py
jaiswalIT02/pythonprograms
bc94e52121202b04c3e9112d9786f93ed6707f7a
[ "MIT" ]
null
null
null
GUI Applications/calc.py
jaiswalIT02/pythonprograms
bc94e52121202b04c3e9112d9786f93ed6707f7a
[ "MIT" ]
null
null
null
from tkinter import Tk from tkinter import Entry from tkinter import Button from tkinter import StringVar t=Tk() t.title("Tarun Jaiswal") t.geometry("425x300") t.resizable(0,0) t.configure(background="black")#back ground color a=StringVar() def show(c): a.set(a.get()+c) def equal(): x=a.get() a.set(eval(x)) def clear(): a.set("") e1=Entry(font=("",30),justify="right",textvariable=a) e1.place(x=0,y=0,width=425,height=50) b1=Button(text="7",font=("",25),bg="gray",fg="white",activebackground="yellow",command=show) b1.place(x=5,y=55,width=100,height=50) b1.configure(command=lambda:show("7")) b2=Button(text="8",font=("",25),bg="gray",fg="white",activebackground="yellow") b2.place(x=110,y=55,width=100,height=50) b2.configure(command=lambda:show("8")) b3=Button(text="9",font=("",25),bg="gray",fg="white",activebackground="yellow") b3.place(x=215,y=55,width=100,height=50) b3.configure(command=lambda:show("9")) b4=Button(text="+",font=("",25),bg="gray",fg="white",activebackground="yellow") b4.place(x=320,y=55,width=100,height=50) b4.configure(command=lambda:show("+")) b5=Button(text="4",font=("",25),bg="gray",fg="white",activebackground="yellow") b5.place(x=5,y=110,width=100,height=50) b5.configure(command=lambda:show("4")) b6=Button(text="5",font=("",25),bg="gray",fg="white",activebackground="yellow") b6.place(x=110,y=110,width=100,height=50) b6.configure(command=lambda:show("5")) b7=Button(text="6",font=("",25),bg="gray",fg="white",activebackground="yellow") b7.place(x=215,y=110,width=100,height=50) b7.configure(command=lambda:show("6")) b8=Button(text="-",font=("",25),bg="gray",fg="white",activebackground="yellow") b8.place(x=320,y=110,width=100,height=50) b8.configure(command=lambda:show("-")) b9=Button(text="1",font=("",25),bg="gray",fg="white",activebackground="yellow") b9.place(x=5,y=165,width=100,height=50) b9.configure(command=lambda:show("1")) b10=Button(text="2",font=("",25),bg="gray",fg="white",activebackground="yellow") b10.place(x=110,y=165,width=100,height=50) b10.configure(command=lambda:show("2")) b11=Button(text="3",font=("",25),bg="gray",fg="white",activebackground="yellow") b11.place(x=215,y=165,width=100,height=50) b11.configure(command=lambda:show("3")) b12=Button(text="*",font=("",25),bg="gray",fg="white",activebackground="yellow") b12.place(x=320,y=165,width=100,height=50) b12.configure(command=lambda:show("*")) b13=Button(text="C",font=("",25),bg="gray",fg="white",activebackground="yellow") b13.place(x=5,y=220,width=100,height=50) b13.configure(command=clear) b14=Button(text="0",font=("",25),bg="gray",fg="white",activebackground="yellow") b14.place(x=110,y=220,width=100,height=50) b14.configure(command=lambda:show("0")) b15=Button(text="=",font=("",25),bg="gray",fg="white",activebackground="yellow",command=equal) b15.place(x=215,y=220,width=100,height=50) b15.configure(command=equal) b16=Button(text="/",font=("",25),bg="gray",fg="white",activebackground="yellow") b16.place(x=320,y=220,width=100,height=50) b16.configure(command=lambda:show("/")) t.mainloop()
33.021505
94
0.699772
518
3,071
4.148649
0.166023
0.047464
0.059563
0.089344
0.482085
0.482085
0.33504
0.33504
0.144253
0.11866
0
0.103366
0.042331
3,071
93
95
33.021505
0.627338
0.005536
0
0
0
0
0.098232
0
0
0
0
0
0
1
0.044118
false
0
0.058824
0
0.102941
0
0
0
0
null
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
null
0
0
0
0
0
0
0
0
0
0
0
0
1
0
813cfc21850f486d6ac29f7b86826c89d492a555
41,687
py
Python
core/models.py
uktrade/great-cms
f13fa335ddcb925bc33a5fa096fe73ef7bdd351a
[ "MIT" ]
10
2020-04-30T12:04:35.000Z
2021-07-21T12:48:55.000Z
core/models.py
uktrade/great-cms
f13fa335ddcb925bc33a5fa096fe73ef7bdd351a
[ "MIT" ]
1,461
2020-01-23T18:20:26.000Z
2022-03-31T08:05:56.000Z
core/models.py
uktrade/great-cms
f13fa335ddcb925bc33a5fa096fe73ef7bdd351a
[ "MIT" ]
3
2020-04-07T20:11:36.000Z
2020-10-16T16:22:59.000Z
import hashlib import mimetypes from urllib.parse import unquote from django.conf import settings from django.core.exceptions import ValidationError from django.db import models from django.http import HttpResponseRedirect from django.template.loader import render_to_string from django.urls import reverse from django.utils.functional import cached_property from django.utils.safestring import mark_safe from django.utils.text import slugify from django.utils.translation import ugettext_lazy as _ from django_extensions.db.fields import CreationDateTimeField, ModificationDateTimeField from great_components.mixins import GA360Mixin from modelcluster.contrib.taggit import ClusterTaggableManager from modelcluster.models import ClusterableModel, ParentalKey from taggit.managers import TaggableManager from taggit.models import ItemBase, TagBase, TaggedItemBase from wagtail.admin.edit_handlers import ( FieldPanel, InlinePanel, MultiFieldPanel, ObjectList, PageChooserPanel, StreamFieldPanel, TabbedInterface, ) from wagtail.contrib.redirects.models import Redirect from wagtail.contrib.settings.models import BaseSetting, register_setting from wagtail.core import blocks from wagtail.core.blocks.stream_block import StreamBlockValidationError from wagtail.core.fields import RichTextField, StreamField from wagtail.core.models import Orderable, Page from wagtail.images import get_image_model_string from wagtail.images.edit_handlers import ImageChooserPanel from wagtail.images.models import AbstractImage, AbstractRendition, Image from wagtail.snippets.models import register_snippet from wagtail.utils.decorators import cached_classmethod from wagtailmedia.models import Media from core import blocks as core_blocks, mixins from core.case_study_index import delete_cs_index, update_cs_index from core.constants import BACKLINK_QUERYSTRING_NAME, RICHTEXT_FEATURES__MINIMAL from core.context import get_context_provider from core.utils import PageTopicHelper, get_first_lesson from exportplan.core.data import ( SECTION_SLUGS as EXPORTPLAN_SLUGS, SECTIONS as EXPORTPLAN_URL_MAP, ) # If we make a Redirect appear as a Snippet, we can sync it via Wagtail-Transfer register_snippet(Redirect) class GreatMedia(Media): transcript = models.TextField( verbose_name=_('Transcript'), blank=False, null=True # left null because was an existing field ) subtitles_en = models.TextField( verbose_name=_('English subtitles'), null=True, blank=True, help_text='English-language subtitles for this video, in VTT format', ) admin_form_fields = Media.admin_form_fields + ( 'transcript', 'subtitles_en', ) @property def sources(self): return [ { 'src': self.url, 'type': mimetypes.guess_type(self.filename)[0] or 'application/octet-stream', 'transcript': self.transcript, } ] @property def subtitles(self): output = [] # TO COME: support for more than just English if self.subtitles_en: output.append( { 'srclang': 'en', 'label': 'English', 'url': reverse('core:subtitles-serve', args=[self.id, 'en']), 'default': False, }, ) return output class AbstractObjectHash(models.Model): class Meta: abstract = True content_hash = models.CharField(max_length=1000) @staticmethod def generate_content_hash(field_file): filehash = hashlib.md5() field_file.open() filehash.update(field_file.read()) field_file.close() return filehash.hexdigest() class DocumentHash(AbstractObjectHash): document = models.ForeignKey( 'wagtaildocs.Document', null=True, blank=True, on_delete=models.CASCADE, related_name='+' ) class ImageHash(AbstractObjectHash): image = models.ForeignKey('wagtailimages.Image', null=True, blank=True, on_delete=models.CASCADE, related_name='+') class AltTextImage(AbstractImage): alt_text = models.CharField(max_length=255, blank=True) admin_form_fields = Image.admin_form_fields + ('alt_text',) class Rendition(AbstractRendition): image = models.ForeignKey(AltTextImage, on_delete=models.CASCADE, related_name='renditions') class Meta: unique_together = ('image', 'filter_spec', 'focal_point_key') @property def alt(self): return self.image.alt_text @register_snippet class Tour(ClusterableModel): page = models.OneToOneField('wagtailcore.Page', on_delete=models.CASCADE, related_name='tour') title = models.CharField(max_length=255) body = models.CharField(max_length=255) button_text = models.CharField(max_length=255) panels = [ PageChooserPanel('page'), FieldPanel('title'), FieldPanel('body'), FieldPanel('button_text'), MultiFieldPanel([InlinePanel('steps')], heading='Steps'), ] def __str__(self): return self.page.title class TourStep(Orderable): title = models.CharField(max_length=255) body = models.CharField(max_length=255) position = models.CharField(max_length=255) selector = models.CharField(max_length=255) tour = ParentalKey(Tour, on_delete=models.CASCADE, related_name='steps') panels = [ FieldPanel('title'), FieldPanel('body'), FieldPanel('position'), FieldPanel('selector'), ] @register_snippet class Product(models.Model): name = models.CharField(max_length=255) panels = [ FieldPanel('name'), ] def __str__(self): return self.name @register_snippet class Region(models.Model): name = models.CharField(max_length=100, unique=True) panels = [FieldPanel('name')] class Meta: ordering = ('name',) def __str__(self): return self.name @register_snippet class Country(models.Model): name = models.CharField(max_length=255) slug = models.SlugField(max_length=100, unique=True) region = models.ForeignKey(Region, null=True, blank=True, on_delete=models.SET_NULL) panels = [ FieldPanel('name'), FieldPanel('region'), ] class Meta: verbose_name_plural = 'Countries' ordering = ('name',) def save(self, *args, **kwargs): # Automatically set slug on save, if not already set if not self.slug: self.slug = slugify(self.name) super().save(*args, **kwargs) def __str__(self): return self.name @register_snippet class Tag(models.Model): name = models.CharField(max_length=100, unique=True) panels = [FieldPanel('name')] class Meta: ordering = ('name',) def __str__(self): return self.name @register_snippet class IndustryTag(models.Model): name = models.CharField(max_length=100, unique=True) icon = models.ForeignKey( AltTextImage, null=True, blank=True, on_delete=models.SET_NULL, related_name='+', ) panels = [FieldPanel('name'), ImageChooserPanel('icon')] class Meta: ordering = ('name',) def __str__(self): return self.name class TimeStampedModel(models.Model): """Modified version of django_extensions.db.models.TimeStampedModel Unfortunately, because null=True needed to be added to create and modified fields, inheritance causes issues with field clash. """ created = CreationDateTimeField('created', null=True) modified = ModificationDateTimeField('modified', null=True) def save(self, **kwargs): self.update_modified = kwargs.pop('update_modified', getattr(self, 'update_modified', True)) super().save(**kwargs) class Meta: get_latest_by = 'modified' ordering = ( '-modified', '-created', ) abstract = True # Content models class CMSGenericPage( mixins.EnableTourMixin, mixins.AuthenticatedUserRequired, mixins.WagtailGA360Mixin, GA360Mixin, Page, ): """ Generic page, freely inspired by Codered page """ class Meta: abstract = True # Do not allow this page type to be created in wagtail admin is_creatable = False template_choices = [] ############### # Layout fields ############### template = models.CharField( max_length=255, choices=None, ) ######### # Panels ########## layout_panels = [FieldPanel('template')] settings_panels = [FieldPanel('slug')] + Page.settings_panels def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) field = self._meta.get_field('template') field.choices = self.template_choices field.required = True @cached_classmethod def get_edit_handler(cls): # NOQA N805 panels = [ ObjectList(cls.content_panels, heading='Content'), ObjectList(cls.layout_panels, heading='Layout'), ObjectList(cls.settings_panels, heading='Settings', classname='settings'), ] return TabbedInterface(panels).bind_to(model=cls) def get_template(self, request, *args, **kwargs): return self.template def get_context(self, request, *args, **kwargs): context = super().get_context(request) self.set_ga360_payload( page_id=self.id, business_unit=settings.GA360_BUSINESS_UNIT, site_section=str(self.url or '/').split('/')[1], ) self.add_ga360_data_to_payload(request) context['ga360'] = self.ga360_payload provider = get_context_provider(request=request, page=self) if provider: context.update(provider.get_context_data(request=request, page=self)) return context class LandingPage(CMSGenericPage): parent_page_types = [ 'domestic.DomesticHomePage', # TODO: once we've restructured, remove this permission 'domestic.GreatDomesticHomePage', ] subpage_types = [ 'core.ListPage', 'core.InterstitialPage', 'domestic.DomesticDashboard', ] template_choices = ( ('learn/landing_page.html', 'Learn'), ('core/generic_page.html', 'Generic'), ) ################ # Content fields ################ description = RichTextField() button = StreamField([('button', core_blocks.ButtonBlock(icon='cog'))], null=True, blank=True) image = models.ForeignKey( get_image_model_string(), null=True, blank=True, on_delete=models.SET_NULL, related_name='+' ) body = StreamField( [ ('section', core_blocks.SectionBlock()), ('title', core_blocks.TitleBlock()), ('text', blocks.RichTextBlock(icon='openquote', helptext='Add a textblock')), ('image', core_blocks.ImageBlock()), ], null=True, blank=True, ) components = StreamField( [ ('route', core_blocks.RouteSectionBlock()), ], null=True, blank=True, ) ######### # Panels ######### content_panels = CMSGenericPage.content_panels + [ FieldPanel('description'), StreamFieldPanel('button'), ImageChooserPanel('image'), StreamFieldPanel('components'), StreamFieldPanel('body'), ] class InterstitialPage(CMSGenericPage): parent_page_types = ['core.LandingPage'] template_choices = (('learn/interstitial.html', 'Learn'),) ################ # Content fields ################ button = StreamField([('button', core_blocks.ButtonBlock(icon='cog'))], null=True, blank=True) ######### # Panels ######### content_panels = CMSGenericPage.content_panels + [ StreamFieldPanel('button'), ] class ListPage(CMSGenericPage): parent_page_types = ['core.LandingPage'] subpage_types = ['core.CuratedListPage'] template_choices = (('learn/automated_list_page.html', 'Learn'),) record_read_progress = models.BooleanField( default=False, help_text='Should we record when a user views a page in this collection?', ) class Meta: verbose_name = 'Automated list page' verbose_name_plural = 'Automated list pages' def get_context(self, request, *args, **kwargs): from core.helpers import get_high_level_completion_progress from domestic.helpers import get_lesson_completion_status context = super().get_context(request) if request.user.is_authenticated: completion_status = get_lesson_completion_status(request.user) context['high_level_completion_progress'] = get_high_level_completion_progress( completion_status=completion_status, ) return context ################ # Content fields ################ description = RichTextField() button_label = models.CharField(max_length=100) ######### # Panels ######### settings_panels = CMSGenericPage.settings_panels + [FieldPanel('record_read_progress')] content_panels = CMSGenericPage.content_panels + [FieldPanel('description'), FieldPanel('button_label')] class CuratedListPage(CMSGenericPage): parent_page_types = ['core.ListPage'] subpage_types = [ 'core.TopicPage', ] template_choices = (('learn/curated_list_page.html', 'Learn'),) ################ # Content fields ################ heading = RichTextField() image = models.ForeignKey( get_image_model_string(), null=True, blank=True, on_delete=models.SET_NULL, related_name='+' ) ######## # Panels ######## content_panels = CMSGenericPage.content_panels + [ FieldPanel('heading'), ImageChooserPanel('image'), ] def get_topics(self, live=True) -> models.QuerySet: qs = TopicPage.objects.live().specific().descendant_of(self) if live: qs = qs.live() return qs @cached_property def count_topics(self): return self.get_topics().count() @cached_property def count_detail_pages(self): count = 0 for topic in self.get_topics(): count += DetailPage.objects.live().descendant_of(topic).count() return count def get_context(self, request, *args, **kwargs): from core.helpers import ( get_high_level_completion_progress, get_module_completion_progress, ) from domestic.helpers import get_lesson_completion_status context = super().get_context(request) # Give the template a simple way to link back to the parent # learning module (ListPage) context['parent_page_url'] = self.get_parent().url if request.user.is_authenticated: # get this once, so we don't waste the network call to get the data twice completion_status = get_lesson_completion_status(request.user) context['module_completion_progress'] = get_module_completion_progress( completion_status=completion_status, module_page=self, ) context['high_level_completion_progress'] = get_high_level_completion_progress( completion_status=completion_status, ) return context def hero_singular_validation(value): if value and len(value) > 1: raise StreamBlockValidationError( non_block_errors=ValidationError('Only one image or video allowed in Hero section', code='invalid'), ) class TopicPage(mixins.AuthenticatedUserRequired, Page): """Structural page to allow for cleaner mapping of lessons (`DetailPage`s) to modules (`CuratedListPage`s). Not intented to be viewed by end users, so will redirect to the parent module if accessed. Also, for the above reason, mixins.WagtailGA360Mixin and GA360Mixin are not used.""" parent_page_types = ['core.CuratedListPage'] subpage_types = [ 'core.DetailPage', 'core.LessonPlaceholderPage', ] # `title` comes from Page superclass and that's all we need here def _redirect_to_parent_module(self): return HttpResponseRedirect(self.get_parent().url) def serve_preview(self, request, mode_name='dummy'): # It doesn't matter what is passed as mode_name - we always redirect return self._redirect_to_parent_module() def serve(self, request): return self._redirect_to_parent_module() class LessonPlaceholderPage(mixins.AuthenticatedUserRequired, Page): """Structural page to allow for configuring and representing very simple to modules (`CuratedListPage`s). Not intented to be viewed by end users, so will redirect to the parent module if accessed. Also, for the above reason, mixins.WagtailGA360Mixin and GA360Mixin are not used.""" parent_page_types = ['core.TopicPage'] subpage_types = [] # No child pages allowed for placeholders # `title` comes from Page superclass and that's all we need here def _redirect_to_parent_module(self): dest = CuratedListPage.objects.ancestor_of(self).first().url return HttpResponseRedirect(dest) def serve_preview(self, request, mode_name='dummy'): # It doesn't matter what is passed as mode_name - we always redirect return self._redirect_to_parent_module() def serve(self, request): return self._redirect_to_parent_module() class DetailPage(CMSGenericPage): estimated_read_duration = models.DurationField(null=True, blank=True) parent_page_types = [ 'core.CuratedListPage', # TEMPORARY: remove after topics refactor migration has run 'core.TopicPage', ] template_choices = (('learn/detail_page.html', 'Learn'),) class Meta: verbose_name = 'Detail page' verbose_name_plural = 'Detail pages' ################ # Content fields ################ hero = StreamField( [ ('Image', core_blocks.ImageBlock(template='core/includes/_hero_image.html')), ('Video', core_blocks.SimpleVideoBlock(template='core/includes/_hero_video.html')), ], null=True, blank=True, validators=[hero_singular_validation], ) objective = StreamField( [ ( 'paragraph', blocks.RichTextBlock(options={'class': 'objectives'}), ), ('ListItem', core_blocks.Item()), ] ) body = StreamField( [ ( 'paragraph', blocks.StructBlock( [('paragraph', blocks.RichTextBlock())], template='core/struct_paragraph_block.html', icon='fa-font', ), ), ( 'video', blocks.StructBlock( [('video', core_blocks.VideoBlock())], template='core/struct_video_block.html', icon='fa-play', ), ), ('case_study', core_blocks.CaseStudyStaticBlock(icon='fa-book')), ( 'Step', core_blocks.StepByStepBlock(icon='cog'), ), ( 'fictional_example', blocks.StructBlock( [('fiction_body', blocks.RichTextBlock(icon='openquote'))], template='learn/fictional_company_example.html', icon='fa-commenting-o', ), ), ( 'ITA_Quote', core_blocks.ITAQuoteBlock(icon='fa-quote-left'), ), ( 'pros_cons', blocks.StructBlock( [ ( 'pros', blocks.StreamBlock( [ ( 'item', core_blocks.Item(icon='fa-arrow-right'), ) ] ), ), ( 'cons', blocks.StreamBlock( [ ( 'item', core_blocks.Item(icon='fa-arrow-right'), ) ] ), ), ], template='learn/pros_and_cons.html', icon='fa-arrow-right', ), ), ('choose_do_not_choose', core_blocks.ChooseDoNotChooseBlock()), ( 'image', core_blocks.ImageBlock( template='core/includes/_image_full_width.html', help_text='Image displayed within a full-page-width block', ), ), ( 'video', core_blocks.SimpleVideoBlock( template='core/includes/_video_full_width.html', help_text='Video displayed within a full-page-width block', ), ), ] ) recap = StreamField( [ ( 'recap_item', blocks.StructBlock( [ ('title', blocks.CharBlock(icon='fa-header')), ( 'item', blocks.StreamBlock( [ ( 'item', core_blocks.Item(), ) ] ), ), ], template='learn/recap.html', icon='fa-commenting-o', ), ) ] ) ######### # Panels ########## content_panels = Page.content_panels + [ StreamFieldPanel('hero'), StreamFieldPanel('objective'), StreamFieldPanel('body'), StreamFieldPanel('recap'), ] def handle_page_view(self, request): if request.user.is_authenticated: # checking if the page should record read progress # checking if the page is already marked as read list_page = ( ListPage.objects.ancestor_of(self) .filter(record_read_progress=True) .exclude(page_views_list__sso_id=request.user.pk, page_views_list__page=self) .first() ) if list_page: PageView.objects.get_or_create( page=self, list_page=list_page, sso_id=request.user.pk, ) def serve(self, request, *args, **kwargs): self.handle_page_view(request) return super().serve(request, **kwargs) @cached_property def topic_title(self): return self.get_parent().title @cached_property def module(self): """Gets the learning module this lesson belongs to""" return CuratedListPage.objects.live().specific().ancestor_of(self).first() @cached_property def _export_plan_url_map(self): """Return a lookup dictionary of URL Slugs->title for all the Export Plan sections we have.""" return {url: values['title'] for url, values in EXPORTPLAN_URL_MAP.items()} def _get_backlink(self, request): """Try to extract a backlink (used for a link to the export plan) from the querystring on the request that brought us to this view. Only accepts backlinks that we KNOW are for the export plan, else ignore it.""" backlink_path = request.GET.get(BACKLINK_QUERYSTRING_NAME, '') if backlink_path is not None: backlink_path = unquote(backlink_path) if len(backlink_path.split('/')) > 2 and ( backlink_path.split('/')[3] in EXPORTPLAN_SLUGS and '://' not in backlink_path ): # The check for '://' will stop us accepting a backlink which # features a full URL as its OWN querystring param (eg a crafted attack # URL), but that's an acceptable limitation here and is very unlikely # to happen. return backlink_path return None # safe default def _get_backlink_title(self, backlink_path): """For a given backlink, see if we can get a title that goes with it. For now, this is limited only to Export Plan pages/links. """ # We have to re-arrange EXPORT_PLAN_SECTION_TITLES_URLS after import # because it features lazily-evaluated URLs that aren't ready when # models are imported if backlink_path and len(backlink_path.split('/')) > 3: _path = backlink_path.split('/')[3] return self._export_plan_url_map.get(_path) def get_context(self, request, *args, **kwargs): context = super().get_context(request) context['refresh_on_market_change'] = True # Prepare backlink to the export plan if we detect one and can validate it _backlink = self._get_backlink(request) if _backlink: context['backlink'] = _backlink context['backlink_title'] = self._get_backlink_title(_backlink) if isinstance(self.get_parent().specific, TopicPage): # In a conditional because a DetailPage currently MAY be used as # a child of another page type... page_topic_helper = PageTopicHelper(self) next_lesson = page_topic_helper.get_next_lesson() context['current_lesson'] = self context['current_module'] = page_topic_helper.module if page_topic_helper: topic_page = page_topic_helper.get_page_topic() if topic_page: context['current_topic'] = topic_page context['page_topic'] = topic_page.title if next_lesson: context['next_lesson'] = next_lesson else: next_module = self.module.get_next_sibling() if not next_module: return context context['next_module'] = next_module.specific context['next_lesson'] = get_first_lesson(next_module) return context class PageView(TimeStampedModel): page = models.ForeignKey(DetailPage, on_delete=models.CASCADE, related_name='page_views') list_page = models.ForeignKey(ListPage, on_delete=models.CASCADE, related_name='page_views_list') sso_id = models.TextField() class Meta: ordering = ['page__pk'] unique_together = ['page', 'sso_id'] # TODO: deprecate and remove class ContentModuleTag(TaggedItemBase): content_object = ParentalKey('core.ContentModule', on_delete=models.CASCADE, related_name='tagged_items') # TODO: deprecate and remove @register_snippet class ContentModule(ClusterableModel): title = models.CharField(max_length=255) content = RichTextField() tags = TaggableManager(through=ContentModuleTag, blank=True) panels = [ FieldPanel('title'), FieldPanel('content'), FieldPanel('tags'), ] def __str__(self): return self.title class PersonalisationHSCodeTag(TagBase): """Custom tag for personalisation. Tag value will be a HS6, HS4 or HS2 code""" # free_tagging = False # DISABLED until tag data only comes via data migration class Meta: verbose_name = 'HS Code tag for personalisation' verbose_name_plural = 'HS Code tags for personalisation' class PersonalisationCountryTag(TagBase): """Custom tag for personalisation. Tag value will be an ISO-2 Country code ('DE') """ free_tagging = False class Meta: verbose_name = 'Country tag for personalisation' verbose_name_plural = 'Country tags for personalisation' class PersonalisationRegionTag(TagBase): """Custom tag for personalisation. Tag value will be a geographical string ('Europe') """ free_tagging = False class Meta: verbose_name = 'Region tag for personalisation' verbose_name_plural = 'Region tags for personalisation' class PersonalisationTradingBlocTag(TagBase): """Custom tag for personalisation. Tag value will be an Trading blocs """ free_tagging = False class Meta: verbose_name = 'Trading bloc tag for personalisation' verbose_name_plural = 'Trading bloc tags for personalisation' # If you're wondering what's going on here: # https://docs.wagtail.io/en/stable/reference/pages/model_recipes.html#custom-tag-models class HSCodeTaggedCaseStudy(ItemBase): tag = models.ForeignKey( PersonalisationHSCodeTag, related_name='hscode_tagged_case_studies', on_delete=models.CASCADE ) content_object = ParentalKey(to='core.CaseStudy', on_delete=models.CASCADE, related_name='hs_code_tagged_items') class CountryTaggedCaseStudy(ItemBase): tag = models.ForeignKey( PersonalisationCountryTag, related_name='country_tagged_case_studies', on_delete=models.CASCADE ) content_object = ParentalKey(to='core.CaseStudy', on_delete=models.CASCADE, related_name='country_tagged_items') class RegionTaggedCaseStudy(ItemBase): tag = models.ForeignKey( PersonalisationRegionTag, related_name='region_tagged_case_studies', on_delete=models.CASCADE ) content_object = ParentalKey(to='core.CaseStudy', on_delete=models.CASCADE, related_name='region_tagged_items') class TradingBlocTaggedCaseStudy(ItemBase): tag = models.ForeignKey( PersonalisationTradingBlocTag, related_name='trading_bloc_tagged_case_studies', on_delete=models.CASCADE ) content_object = ParentalKey( to='core.CaseStudy', on_delete=models.CASCADE, related_name='trading_bloc_tagged_items' ) def _high_level_validation(value, error_messages): TEXT_BLOCK = 'text' # noqa N806 MEDIA_BLOCK = 'media' # noqa N806 QUOTE_BLOCK = 'quote' # noqa N806 # we need to be strict about presence and ordering of these nodes if [node.block_type for node in value if node.block_type != QUOTE_BLOCK] != [MEDIA_BLOCK, TEXT_BLOCK]: error_messages.append( ( 'This block must contain one Media section (with one or ' 'two items in it) and/or a Quote section, then one Text section following it.' ) ) return error_messages def _low_level_validation(value, error_messages): # Check content of media node, which should be present here MEDIA_BLOCK = 'media' # noqa N806 VIDEO_BLOCK = 'video' # noqa N806 for node in value: if node.block_type == MEDIA_BLOCK: subnode_block_types = [subnode.block_type for subnode in node.value] if len(subnode_block_types) == 2: if set(subnode_block_types) == {VIDEO_BLOCK}: # Two videos: not allowed error_messages.append('Only one video may be used in a case study.') elif subnode_block_types[1] == VIDEO_BLOCK: # implicitly, [0] must be an image # video after image: not allowed error_messages.append('The video must come before a still image.') return error_messages def case_study_body_validation(value): """Ensure the case study has exactly both a media node and a text node and that the media node has the following content: * One image, only * One video, only * One video + One image * (video must comes first so that it is displayed first) * Two images """ error_messages = [] if value: error_messages = _high_level_validation(value, error_messages) error_messages = _low_level_validation(value, error_messages) if error_messages: raise StreamBlockValidationError( non_block_errors=ValidationError('; '.join(error_messages), code='invalid'), ) class MagnaPageChooserPanel(PageChooserPanel): show_label = False field_template = 'admin/wagtailadmin/edit_handlers/field_panel_field.html' def render_as_field(self): instance_obj = self.get_chosen_item() context = { 'field': self.bound_field, self.object_type_name: instance_obj, 'is_chosen': bool(instance_obj), # DEPRECATED - passed to templates for backwards compatibility only # Added obj_type on base class method render_as_field 'obj_type': instance_obj.specific.__class__.__name__ if instance_obj else None, } return mark_safe(render_to_string(self.field_template, context)) class CaseStudyRelatedPages(Orderable): case_study = ParentalKey( 'core.CaseStudy', related_name='related_pages', on_delete=models.SET_NULL, null=True, blank=True, ) page = models.ForeignKey( 'wagtailcore.Page', on_delete=models.CASCADE, related_name='+', ) panels = [ MagnaPageChooserPanel('page', [DetailPage, CuratedListPage, TopicPage]), ] class Meta: unique_together = ['case_study', 'page'] @register_snippet class CaseStudy(ClusterableModel): """Dedicated snippet for use as a case study. Supports personalised selection via its tags. The decision about the appropriate Case Study block to show will happen when the page attempts to render the relevant CaseStudyBlock. Note that this is rendered via Wagtail's ModelAdmin, so appears in the sidebar, but we have to keep it registered as a Snippet to be able to transfer it with Wagtail-Transfer """ title = models.CharField( max_length=255, blank=False, verbose_name='Internal case study title', ) # old name company_name summary_context = models.CharField(max_length=255, blank=False, default='How we did it') # old name summary lead_title = models.TextField(blank=False) # Deliberately not rich-text / no formatting body = StreamField( [ ( 'media', blocks.StreamBlock( [ ('video', core_blocks.SimpleVideoBlock(template='core/includes/_case_study_video.html')), ('image', core_blocks.ImageBlock()), ], min_num=1, max_num=2, ), ), ( 'text', blocks.RichTextBlock( features=RICHTEXT_FEATURES__MINIMAL, ), ), ( 'quote', core_blocks.CaseStudyQuoteBlock(), ), ], validators=[case_study_body_validation], help_text=( 'This block must contain one Media section (with one or two items in it) ' 'and/or Quote sections, then one Text section.' ), ) # We are keeping the personalisation-relevant tags in separate # fields to aid lookup and make the UX easier for editors hs_code_tags = ClusterTaggableManager(through='core.HSCodeTaggedCaseStudy', blank=True, verbose_name='HS-code tags') country_code_tags = ClusterTaggableManager( through='core.CountryTaggedCaseStudy', blank=True, verbose_name='Country tags' ) region_code_tags = ClusterTaggableManager( through='core.RegionTaggedCaseStudy', blank=True, verbose_name='Region tags' ) trading_bloc_code_tags = ClusterTaggableManager( through='core.TradingBlocTaggedCaseStudy', blank=True, verbose_name='Trading bloc tags' ) created = CreationDateTimeField('created', null=True) modified = ModificationDateTimeField('modified', null=True) panels = [ MultiFieldPanel( [ FieldPanel('title'), FieldPanel('lead_title'), FieldPanel('summary_context'), StreamFieldPanel('body'), ], heading='Case Study content', ), MultiFieldPanel( [ FieldPanel('hs_code_tags'), FieldPanel('country_code_tags'), FieldPanel('region_code_tags'), FieldPanel('trading_bloc_code_tags'), ], heading='Case Study tags for Personalisation', ), MultiFieldPanel( [ InlinePanel('related_pages', label='Related pages'), ], heading='Related Lesson, Topic & Module, also used for Personalisation', ), ] def __str__(self): display_name = self.title if self.title else self.summary_context return f'{display_name}' def save(self, **kwargs): # When we create a new CS need to call create to obtain an ID for indexing self.update_modified = kwargs.pop('update_modified', getattr(self, 'update_modified', True)) super().save(**kwargs) update_cs_index(self) def delete(self, **kwargs): delete_cs_index(self.id) super().delete(**kwargs) def get_cms_standalone_view_url(self): return reverse('cms_extras:case-study-view', args=[self.id]) class Meta: verbose_name_plural = 'Case studies' get_latest_by = 'modified' ordering = ( '-modified', '-created', ) @register_setting class CaseStudyScoringSettings(BaseSetting): threshold = models.DecimalField( help_text='This is the minimum score which a case study needs to have to be ' 'considered before being presented to users. ', default=10, decimal_places=3, max_digits=5, ) lesson = models.DecimalField( help_text="Score given when user's lesson is tagged in the case study.", default=8, decimal_places=3, max_digits=5, ) topic = models.DecimalField( help_text="Score given when user's lesson's topic is tagged in the case study " 'unless there is also lesson match.', default=4, decimal_places=3, max_digits=5, ) module = models.DecimalField( help_text="Score given when the user's lesson's module is tagged in the case study " 'unless there is also lesson or topic match.', default=2, decimal_places=3, max_digits=5, ) product_hs6 = models.DecimalField( help_text='Score given when any case study HS6 tag matches the complete HS6 code of ' "any of the user's products", default=8, decimal_places=3, max_digits=5, ) product_hs4 = models.DecimalField( help_text="Score given when any case study HS4 tag matches the first 4 digits of any of the user's products " 'unless there is an HS6 match.', default=4, decimal_places=3, max_digits=5, ) product_hs2 = models.DecimalField( help_text="Score given when any case study HS2 tag matches the first 2 digits of any of the user's products " 'unless there is an HS6 or HS4 match.', default=2, decimal_places=3, max_digits=5, ) country_exact = models.DecimalField( help_text="Score given when any case study country tag exactly matches one of the user's export markets.", default=4, decimal_places=3, max_digits=5, ) country_region = models.DecimalField( help_text="Score given when any case study region tag matches the region of any of the user's export markets " 'unless there is an exact country match.', default=2, decimal_places=3, max_digits=5, ) trading_blocs = models.DecimalField( help_text='Score given when any case study trading bloc tag matches the any trading bloc that any of ' "the user's export markets falls into unless there is an exact country or region match.", default=2, decimal_places=3, max_digits=5, ) product_tab = [MultiFieldPanel([FieldPanel('product_hs6'), FieldPanel('product_hs4'), FieldPanel('product_hs2')])] market_tab = [ MultiFieldPanel([FieldPanel('country_exact'), FieldPanel('country_region'), FieldPanel('trading_blocs')]) ] lesson_tab = [MultiFieldPanel([FieldPanel('lesson'), FieldPanel('topic'), FieldPanel('module')])] threshold_tab = [ MultiFieldPanel( [ FieldPanel('threshold'), ] ) ] edit_handler = TabbedInterface( [ ObjectList(product_tab, heading='Product'), ObjectList(market_tab, heading='Market'), ObjectList(lesson_tab, heading='Lesson'), ObjectList(threshold_tab, heading='Threshold'), ] ) class Meta: verbose_name = 'Case Study Scoring'
32.491816
120
0.614052
4,393
41,687
5.638061
0.163214
0.009448
0.012435
0.018411
0.338622
0.29736
0.255895
0.221495
0.203327
0.185925
0
0.006034
0.288411
41,687
1,282
121
32.517161
0.828917
0.114808
0
0.31961
0
0.002167
0.147883
0.028865
0
0
0
0.00156
0
1
0.048754
false
0
0.045504
0.019502
0.335861
0
0
0
0
null
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
null
0
0
0
0
0
0
0
0
0
0
0
0
1
0
813ec18cfeb4f9f63d67da715da440d160d1cd07
9,860
py
Python
CV/Effective Transformer-based Solution for RSNA Intracranial Hemorrhage Detection/easymia/transforms/transforms.py
dumpmemory/Research
30fd70ff331b3d9aeede0b71e7a691ed6c2b87b3
[ "Apache-2.0" ]
null
null
null
CV/Effective Transformer-based Solution for RSNA Intracranial Hemorrhage Detection/easymia/transforms/transforms.py
dumpmemory/Research
30fd70ff331b3d9aeede0b71e7a691ed6c2b87b3
[ "Apache-2.0" ]
null
null
null
CV/Effective Transformer-based Solution for RSNA Intracranial Hemorrhage Detection/easymia/transforms/transforms.py
dumpmemory/Research
30fd70ff331b3d9aeede0b71e7a691ed6c2b87b3
[ "Apache-2.0" ]
null
null
null
# -*-coding utf-8 -*- ########################################################################## # # Copyright (c) 2022 Baidu.com, Inc. All Rights Reserved # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # ########################################################################## """ 数据变换器 """ import numpy as np import numbers import collections import random import math import cv2 from . import functional as F from easymia.core.abstract_transforms import AbstractTransform from easymia.libs import manager @manager.TRANSFORMS.add_component class Compose(AbstractTransform): """ Do transformation on input data with corresponding pre-processing and augmentation operations. The shape of input data to all operations is [height, width, channels]. Args: transforms (list): A list contains data pre-processing or augmentation. Empty list means only reading images, no transformation. to_rgb (bool, optional): If converting image to RGB color space. Default: True. Raises: TypeError: When 'transforms' is not a list. ValueError: when the length of 'transforms' is less than 1. """ def __init__(self, mode, transforms): if not isinstance(transforms, list): raise TypeError('The transforms must be a list!') self.transforms = transforms super().__init__(mode) def __clas__(self, im): """ Args: im (np.ndarray): It is either image path or image object. Returns: (np.array). Image after transformation. """ for op in self.transforms: im = op(im) return im @manager.TRANSFORMS.add_component class RandomHorizontalFlip(AbstractTransform): """Horizontally flip the given PIL Image randomly with a given probability. Args: p (float): probability of the image being flipped. Default value is 0.5 """ def __init__(self, mode, prob=0.5): """ init """ self.prob = prob super().__init__(mode) def __clas__(self, img): """ Args: img (numpy ndarray): Image to be flipped. Returns: numpy ndarray: Randomly flipped image. """ if random.random() < self.prob: return F.hflip(img) return img @manager.TRANSFORMS.add_component class RandomVerticalFlip(AbstractTransform): """Vertically flip the given PIL Image randomly with a given probability. Args: p (float): probability of the image being flipped. Default value is 0.5 """ def __init__(self, mode, prob=0.5): """ init """ self.prob = prob super().__init__(mode) def __clas__(self, img): """ Args: img (numpy ndarray): Image to be flipped. Returns: numpy ndarray: Randomly flipped image. """ if random.random() < self.prob: return F.vflip(img) return img @manager.TRANSFORMS.add_component class RandomResizedCrop(AbstractTransform): """Crop the given numpy ndarray to random size and aspect ratio. A crop of random size (default: of 0.08 to 1.0) of the original size and a random aspect ratio (default: of 3/4 to 4/3) of the original aspect ratio is made. This crop is finally resized to given size. This is popularly used to train the Inception networks. Args: size: expected output size of each edge scale: range of size of the origin size cropped ratio: range of aspect ratio of the origin aspect ratio cropped interpolation: Default: cv2.INTER_CUBIC """ def __init__(self, mode, size, scale=(0.08, 1.0), ratio=(3. / 4., 4. / 3.), interpolation=cv2.INTER_CUBIC): """ init """ self.size = (size, size) self.interpolation = interpolation self.scale = scale self.ratio = ratio super().__init__(mode) def get_params(self, img, scale, ratio): """Get parameters for ``crop`` for a random sized crop. Args: img (numpy ndarray): Image to be cropped. scale (tuple): range of size of the origin size cropped ratio (tuple): range of aspect ratio of the origin aspect ratio cropped Returns: tuple: params (i, j, h, w) to be passed to ``crop`` for a random sized crop. """ params_ret = collections.namedtuple('params_ret', ['i', 'j', 'h', 'w']) for attempt in range(10): area = img.shape[0] * img.shape[1] target_area = random.uniform(*scale) * area aspect_ratio = random.uniform(*ratio) w = int(round(math.sqrt(target_area * aspect_ratio))) h = int(round(math.sqrt(target_area / aspect_ratio))) if random.random() < 0.5: w, h = h, w if w <= img.shape[1] and h <= img.shape[0]: i = random.randint(0, img.shape[0] - h) j = random.randint(0, img.shape[1] - w) return params_ret(i, j, h, w) # Fallback w = min(img.shape[0], img.shape[1]) i = (img.shape[0] - w) // 2 j = (img.shape[1] - w) // 2 return params_ret(i, j, w, w) def __clas__(self, img): """ Args: img (numpy ndarray): Image to be cropped and resized. Returns: numpy ndarray: Randomly cropped and resized image. """ i, j, h, w = self.get_params(img, self.scale, self.ratio) return F.resized_crop(img, i, j, h, w, self.size, self.interpolation) @manager.TRANSFORMS.add_component class RandomRotation(AbstractTransform): """Rotate the image by angle. Args: degrees (sequence or float or int): Range of degrees to select from. If degrees is a number instead of sequence like (min, max), the range of degrees will be (-degrees, +degrees). resample ({cv2.INTER_NEAREST, cv2.INTER_LINEAR, cv2.INTER_CUBIC, cv2.INTER_LANCZOS4}, optional): An optional resampling filter. See `filters`_ for more information. If omitted, or if the image has mode "1" or "P", it is set to PIL.Image.NEAREST. expand (bool, optional): Optional expansion flag. If true, expands the output to make it large enough to hold the entire rotated image. If false or omitted, make the output image the same size as the input image. Note that the expand flag assumes rotation around the center and no translation. center (2-tuple, optional): Optional center of rotation. Origin is the upper left corner. Default is the center of the image. """ def __init__(self, mode, degrees, center=None): """ init """ if isinstance(degrees, numbers.Number): if degrees < 0: raise ValueError( "If degrees is a single number, it must be positive.") self.degrees = (-degrees, degrees) else: if len(degrees) != 2: raise ValueError( "If degrees is a sequence, it must be of len 2.") self.degrees = degrees self.center = center super().__init__(mode) @staticmethod def get_params(degrees): """Get parameters for ``rotate`` for a random rotation. Returns: sequence: params to be passed to ``rotate`` for random rotation. """ angle = random.uniform(degrees[0], degrees[1]) return angle def __clas__(self, img): """ img (numpy ndarray): Image to be rotated. Returns: numpy ndarray: Rotated image. """ angle = self.get_params(self.degrees) return F.rotate(img, angle, self.center) @manager.TRANSFORMS.add_component class Resize(AbstractTransform): """Resize the input numpy ndarray to the given size. Args: size (sequence or int): Desired output size. If size is a sequence like (h, w), output size will be matched to this. If size is an int, smaller edge of the image will be matched to this number. i.e, if height > width, then image will be rescaled to (size * height / width, size) interpolation (int, optional): Desired interpolation. Default is ``cv2.INTER_CUBIC``, bicubic interpolation """ def __init__(self, mode, size, interpolation=cv2.INTER_LINEAR): """ resize """ # assert isinstance(size, int) or (isinstance(size, collections.Iterable) and len(size) == 2) if isinstance(size, int): self.size = (size, size) elif isinstance(size, collections.abc.Iterable) and len(size) == 2: if type(size) == list: size = tuple(size) self.size = size else: raise ValueError('Unknown inputs for size: {}'.format(size)) self.interpolation = interpolation super().__init__(mode) def __clas__(self, img): """ Args: img (numpy ndarray): Image to be scaled. Returns: numpy ndarray: Rescaled image. """ return F.resize(img, self.size, self.interpolation)
34.840989
136
0.596349
1,237
9,860
4.669361
0.236055
0.027008
0.020776
0.030125
0.272161
0.221087
0.177458
0.177458
0.141447
0.128289
0
0.010519
0.296146
9,860
283
137
34.840989
0.821758
0.471805
0
0.317308
0
0
0.038943
0
0
0
0
0
0
1
0.134615
false
0
0.086538
0
0.384615
0
0
0
0
null
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
null
0
0
0
0
0
0
0
0
0
0
0
0
1
0
813efba40d450227c03f83890923f36f0af07beb
1,370
py
Python
tests/ui/terms/test_views.py
galterlibrary/InvenioRDM-at-NU
5aff6ac7c428c9a61bdf221627bfc05f2280d1a3
[ "MIT" ]
6
2019-09-02T00:01:50.000Z
2021-11-04T08:23:40.000Z
tests/ui/terms/test_views.py
galterlibrary/InvenioRDM-at-NU
5aff6ac7c428c9a61bdf221627bfc05f2280d1a3
[ "MIT" ]
72
2019-09-04T18:52:35.000Z
2020-07-21T19:58:15.000Z
tests/ui/terms/test_views.py
galterlibrary/InvenioRDM-at-NU
5aff6ac7c428c9a61bdf221627bfc05f2280d1a3
[ "MIT" ]
null
null
null
# -*- coding: utf-8 -*- # # This file is part of menRva. # Copyright (C) 2018-present NU,FSM,GHSL. # # menRva is free software; you can redistribute it and/or modify it # under the terms of the MIT License; see LICENSE file for more details. """Test terms views.py""" from cd2h_repo_project.modules.terms.views import serialize_terms_for_edit_ui def test_serialize_terms_for_edit_ui(create_record): deposit = create_record( { 'terms': [ {'source': 'MeSH', 'value': 'Cognitive Neuroscience'}, {'source': 'FAST', 'value': 'Border terrier'} ] }, published=False ) serialized_deposit = serialize_terms_for_edit_ui(deposit) assert 'terms' not in serialized_deposit assert serialized_deposit['mesh_terms'] == [ { 'data': {'source': 'MeSH', 'value': 'Cognitive Neuroscience'} } ] assert serialized_deposit['fast_terms'] == [ { 'data': {'source': 'FAST', 'value': 'Border terrier'} } ] def test_serialize_terms_for_edit_ui_no_terms(create_record): deposit = create_record(published=False) serialized_deposit = serialize_terms_for_edit_ui(deposit) assert 'terms' not in serialized_deposit assert serialized_deposit['mesh_terms'] == [] assert serialized_deposit['fast_terms'] == []
28.541667
77
0.642336
159
1,370
5.27044
0.415094
0.162291
0.101432
0.125298
0.702864
0.372315
0.372315
0.300716
0.300716
0.300716
0
0.005753
0.238686
1,370
47
78
29.148936
0.797699
0.181022
0
0.137931
0
0
0.175676
0
0
0
0
0
0.206897
1
0.068966
false
0
0.034483
0
0.103448
0
0
0
0
null
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
null
0
0
0
0
0
0
0
0
0
0
0
0
1
0
81411abc782bf9b1f6f3f22e5119bf12fc73f345
5,777
py
Python
moe/bandit/ucb/ucb_interface.py
dstoeckel/MOE
5b5a6a2c6c3cf47320126f7f5894e2a83e347f5c
[ "Apache-2.0" ]
966
2015-01-10T05:27:30.000Z
2022-03-26T21:04:36.000Z
moe/bandit/ucb/ucb_interface.py
dstoeckel/MOE
5b5a6a2c6c3cf47320126f7f5894e2a83e347f5c
[ "Apache-2.0" ]
46
2015-01-16T22:33:08.000Z
2019-09-04T16:33:27.000Z
moe/bandit/ucb/ucb_interface.py
dstoeckel/MOE
5b5a6a2c6c3cf47320126f7f5894e2a83e347f5c
[ "Apache-2.0" ]
143
2015-01-07T03:57:19.000Z
2022-02-28T01:10:45.000Z
# -*- coding: utf-8 -*- """Classes (Python) to compute the Bandit UCB (Upper Confidence Bound) arm allocation and choosing the arm to pull next. See :mod:`moe.bandit.bandit_interface` for further details on bandit. """ import copy from abc import abstractmethod from moe.bandit.bandit_interface import BanditInterface from moe.bandit.utils import get_winning_arm_names_from_payoff_arm_name_list, get_equal_arm_allocations class UCBInterface(BanditInterface): r"""Implementation of the constructor of UCB (Upper Confidence Bound) and method allocate_arms. The method get_ucb_payoff is implemented in subclass. A class to encapsulate the computation of bandit UCB. The Algorithm: http://moodle.technion.ac.il/pluginfile.php/192340/mod_resource/content/0/UCB.pdf To inherit this class, a subclass needs to implement get_ucb_payoff (see :func:`moe.bandit.ucb.ucb1.UCB1.get_ucb_payoff` for an example), everything else is already implemented. See :mod:`moe.bandit.bandit_interface` docs for further details. """ def __init__( self, historical_info, subtype=None, ): """Construct a UCB object. :param historical_info: a dictionary of arms sampled :type historical_info: dictionary of (str, SampleArm()) pairs (see :class:`moe.bandit.data_containers.SampleArm` for more details) :param subtype: subtype of the UCB bandit algorithm (default: None) :type subtype: str """ self._historical_info = copy.deepcopy(historical_info) self._subtype = subtype @staticmethod def get_unsampled_arm_names(arms_sampled): r"""Compute the set of unsampled arm names based on the given ``arms_sampled``.. Throws an exception when arms_sampled is empty. :param arms_sampled: a dictionary of arm name to :class:`moe.bandit.data_containers.SampleArm` :type arms_sampled: dictionary of (str, SampleArm()) pairs :return: set of names of the unsampled arms :rtype: frozenset(str) :raise: ValueError when ``arms_sampled`` are empty. """ if not arms_sampled: raise ValueError('arms_sampled is empty!') unsampled_arm_name_list = [name for name, sampled_arm in arms_sampled.iteritems() if sampled_arm.total == 0] return frozenset(unsampled_arm_name_list) @abstractmethod def get_ucb_payoff(self, sampled_arm, number_sampled): r"""Compute the expected upper confidence bound payoff using the UCB subtype formula. See definition in subclasses for details. :param sampled_arm: a sampled arm :type sampled_arm: :class:`moe.bandit.data_containers.SampleArm` :param number_sampled: the overall number of pulls so far :type number_sampled: int :return: ucb payoff :rtype: float64 :raise: ValueError when ``sampled_arm`` is empty. """ pass def allocate_arms(self): r"""Compute the allocation to each arm given ``historical_info``, running bandit ``subtype`` endpoint. Computes the allocation to each arm based on the given subtype, and, historical info. Works with k-armed bandits (k >= 1). The Algorithm: http://moodle.technion.ac.il/pluginfile.php/192340/mod_resource/content/0/UCB.pdf If there is at least one unsampled arm, this method will choose to pull the unsampled arm (randomly choose an unsampled arm if there are multiple unsampled arms). If all arms are pulled at least once, this method will pull the optimal arm (best expected upper confidence bound payoff). See :func:`moe.bandit.ucb.ucb_interface.UCBInterface.get_ucb_payoff` for details on how to compute the expected upper confidence bound payoff (expected UCB payoff) In case of a tie, the method will split the allocation among the optimal arms. For example, if we have three arms (arm1, arm2, and arm3) with expected UCB payoff 0.5, 0.5, and 0.1 respectively. We split the allocation between the optimal arms arm1 and arm2. ``{arm1: 0.5, arm2: 0.5, arm3: 0.0}`` :return: the dictionary of (arm, allocation) key-value pairs :rtype: a dictionary of (str, float64) pairs :raise: ValueError when ``sample_arms`` are empty. """ arms_sampled = self._historical_info.arms_sampled if not arms_sampled: raise ValueError('sample_arms are empty!') return get_equal_arm_allocations(arms_sampled, self.get_winning_arm_names(arms_sampled)) def get_winning_arm_names(self, arms_sampled): r"""Compute the set of winning arm names based on the given ``arms_sampled``.. Throws an exception when arms_sampled is empty. :param arms_sampled: a dictionary of arm name to :class:`moe.bandit.data_containers.SampleArm` :type arms_sampled: dictionary of (str, SampleArm()) pairs :return: set of names of the winning arms :rtype: frozenset(str) :raise: ValueError when ``arms_sampled`` are empty. """ if not arms_sampled: raise ValueError('arms_sampled is empty!') # If there exists an unsampled arm, return the names of the unsampled arms unsampled_arm_names = self.get_unsampled_arm_names(arms_sampled) if unsampled_arm_names: return unsampled_arm_names number_sampled = sum([sampled_arm.total for sampled_arm in arms_sampled.itervalues()]) ucb_payoff_arm_name_list = [(self.get_ucb_payoff(sampled_arm, number_sampled), arm_name) for arm_name, sampled_arm in arms_sampled.iteritems()] return get_winning_arm_names_from_payoff_arm_name_list(ucb_payoff_arm_name_list)
41.561151
171
0.701229
797
5,777
4.912171
0.224592
0.073052
0.016858
0.018391
0.396424
0.34636
0.278416
0.223755
0.223755
0.203831
0
0.009577
0.22278
5,777
138
172
41.862319
0.862361
0.613467
0
0.125
0
0
0.036545
0
0
0
0
0
0
1
0.125
false
0.025
0.1
0
0.35
0
0
0
0
null
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
null
0
0
0
0
0
0
0
0
0
0
0
0
1
0
8141278e8aec7ffc16f0909af9f0862c9b9fc0df
296
py
Python
Hedge/Shell.py
RonaldoAPSD/Hedge
2a1550ea38a0384f39ed3541c8a91f9ca57f5a64
[ "Apache-2.0" ]
2
2020-08-16T01:42:32.000Z
2020-08-28T21:10:03.000Z
Hedge/Shell.py
RonaldoAPSD/Hedge
2a1550ea38a0384f39ed3541c8a91f9ca57f5a64
[ "Apache-2.0" ]
null
null
null
Hedge/Shell.py
RonaldoAPSD/Hedge
2a1550ea38a0384f39ed3541c8a91f9ca57f5a64
[ "Apache-2.0" ]
null
null
null
import Hedge while True: text = input('Hedge > ') if text.strip() == "": continue result, error = Hedge.run('<stdin>', text) if (error): print(error.asString()) elif result: if len(result.elements) == 1: print(repr(result.elements[0])) else: print(repr(result))
19.733333
44
0.60473
38
296
4.710526
0.578947
0.156425
0.167598
0
0
0
0
0
0
0
0
0.008658
0.219595
296
15
45
19.733333
0.766234
0
0
0
0
0
0.053004
0
0
0
0
0
0
1
0
false
0
0.076923
0
0.076923
0.230769
0
0
0
null
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
null
0
0
0
0
0
0
0
0
0
0
0
0
1
0
81433f45286c6ca7869898f63194549b86792d2f
14,420
py
Python
yt/frontends/enzo/io.py
Xarthisius/yt
321643c3abff64a6f132d98d0747f3558f7552a3
[ "BSD-3-Clause-Clear" ]
1
2021-05-20T13:03:57.000Z
2021-05-20T13:03:57.000Z
yt/frontends/enzo/io.py
Xarthisius/yt
321643c3abff64a6f132d98d0747f3558f7552a3
[ "BSD-3-Clause-Clear" ]
31
2017-04-19T21:07:18.000Z
2017-04-20T01:08:43.000Z
yt/frontends/enzo/io.py
Xarthisius/yt
321643c3abff64a6f132d98d0747f3558f7552a3
[ "BSD-3-Clause-Clear" ]
1
2021-04-21T07:01:51.000Z
2021-04-21T07:01:51.000Z
import numpy as np from yt.geometry.selection_routines import GridSelector from yt.utilities.io_handler import BaseIOHandler from yt.utilities.logger import ytLogger as mylog from yt.utilities.on_demand_imports import _h5py as h5py _convert_mass = ("particle_mass", "mass") _particle_position_names = {} class IOHandlerPackedHDF5(BaseIOHandler): _dataset_type = "enzo_packed_3d" _base = slice(None) _field_dtype = "float64" def _read_field_names(self, grid): if grid.filename is None: return [] f = h5py.File(grid.filename, mode="r") try: group = f["/Grid%08i" % grid.id] except KeyError: group = f fields = [] dtypes = set() add_io = "io" in grid.ds.particle_types add_dm = "DarkMatter" in grid.ds.particle_types for name, v in group.items(): # NOTE: This won't work with 1D datasets or references. # For all versions of Enzo I know about, we can assume all floats # are of the same size. So, let's grab one. if not hasattr(v, "shape") or v.dtype == "O": continue elif len(v.dims) == 1: if grid.ds.dimensionality == 1: fields.append(("enzo", str(name))) elif add_io: fields.append(("io", str(name))) elif add_dm: fields.append(("DarkMatter", str(name))) else: fields.append(("enzo", str(name))) dtypes.add(v.dtype) if len(dtypes) == 1: # Now, if everything we saw was the same dtype, we can go ahead and # set it here. We do this because it is a HUGE savings for 32 bit # floats, since our numpy copying/casting is way faster than # h5py's, for some reason I don't understand. This does *not* need # to be correct -- it will get fixed later -- it just needs to be # okay for now. self._field_dtype = list(dtypes)[0] f.close() return fields @property def _read_exception(self): return (KeyError,) def _read_particle_coords(self, chunks, ptf): yield from self._read_particle_fields(chunks, ptf, None) def _read_particle_fields(self, chunks, ptf, selector): chunks = list(chunks) for chunk in chunks: # These should be organized by grid filename f = None for g in chunk.objs: if g.filename is None: continue if f is None: # print("Opening (read) %s" % g.filename) f = h5py.File(g.filename, mode="r") nap = sum(g.NumberOfActiveParticles.values()) if g.NumberOfParticles == 0 and nap == 0: continue ds = f.get("/Grid%08i" % g.id) for ptype, field_list in sorted(ptf.items()): if ptype == "io": if g.NumberOfParticles == 0: continue pds = ds elif ptype == "DarkMatter": if g.NumberOfActiveParticles[ptype] == 0: continue pds = ds elif not g.NumberOfActiveParticles[ptype]: continue else: for pname in ["Active Particles", "Particles"]: pds = ds.get(f"{pname}/{ptype}") if pds is not None: break else: raise RuntimeError( "Could not find active particle group in data." ) pn = _particle_position_names.get(ptype, r"particle_position_%s") x, y, z = ( np.asarray(pds.get(pn % ax)[()], dtype="=f8") for ax in "xyz" ) if selector is None: # This only ever happens if the call is made from # _read_particle_coords. yield ptype, (x, y, z) continue mask = selector.select_points(x, y, z, 0.0) if mask is None: continue for field in field_list: data = np.asarray(pds.get(field)[()], "=f8") if field in _convert_mass: data *= g.dds.prod(dtype="f8") yield (ptype, field), data[mask] if f: f.close() def io_iter(self, chunks, fields): h5_dtype = self._field_dtype for chunk in chunks: fid = None filename = -1 for obj in chunk.objs: if obj.filename is None: continue if obj.filename != filename: # Note one really important thing here: even if we do # implement LRU caching in the _read_obj_field function, # we'll still be doing file opening and whatnot. This is a # problem, but one we can return to. if fid is not None: fid.close() fid = h5py.h5f.open( obj.filename.encode("latin-1"), h5py.h5f.ACC_RDONLY ) filename = obj.filename for field in fields: nodal_flag = self.ds.field_info[field].nodal_flag dims = obj.ActiveDimensions[::-1] + nodal_flag[::-1] data = np.empty(dims, dtype=h5_dtype) yield field, obj, self._read_obj_field(obj, field, (fid, data)) if fid is not None: fid.close() def _read_obj_field(self, obj, field, fid_data): if fid_data is None: fid_data = (None, None) fid, data = fid_data if fid is None: close = True fid = h5py.h5f.open(obj.filename.encode("latin-1"), h5py.h5f.ACC_RDONLY) else: close = False if data is None: data = np.empty(obj.ActiveDimensions[::-1], dtype=self._field_dtype) ftype, fname = field try: node = "/Grid%08i/%s" % (obj.id, fname) dg = h5py.h5d.open(fid, node.encode("latin-1")) except KeyError: if fname == "Dark_Matter_Density": data[:] = 0 return data.T raise dg.read(h5py.h5s.ALL, h5py.h5s.ALL, data) # I don't know why, but on some installations of h5py this works, but # on others, nope. Doesn't seem to be a version thing. # dg.close() if close: fid.close() return data.T class IOHandlerPackedHDF5GhostZones(IOHandlerPackedHDF5): _dataset_type = "enzo_packed_3d_gz" def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) NGZ = self.ds.parameters.get("NumberOfGhostZones", 3) self._base = (slice(NGZ, -NGZ), slice(NGZ, -NGZ), slice(NGZ, -NGZ)) def _read_obj_field(self, *args, **kwargs): return super()._read_obj_field(*args, **kwargs)[self._base] class IOHandlerInMemory(BaseIOHandler): _dataset_type = "enzo_inline" def __init__(self, ds, ghost_zones=3): self.ds = ds import enzo self.enzo = enzo self.grids_in_memory = enzo.grid_data self.old_grids_in_memory = enzo.old_grid_data self.my_slice = ( slice(ghost_zones, -ghost_zones), slice(ghost_zones, -ghost_zones), slice(ghost_zones, -ghost_zones), ) BaseIOHandler.__init__(self, ds) def _read_field_names(self, grid): fields = [] add_io = "io" in grid.ds.particle_types for name, v in self.grids_in_memory[grid.id].items(): # NOTE: This won't work with 1D datasets or references. if not hasattr(v, "shape") or v.dtype == "O": continue elif v.ndim == 1: if grid.ds.dimensionality == 1: fields.append(("enzo", str(name))) elif add_io: fields.append(("io", str(name))) else: fields.append(("enzo", str(name))) return fields def _read_fluid_selection(self, chunks, selector, fields, size): rv = {} # Now we have to do something unpleasant chunks = list(chunks) if isinstance(selector, GridSelector): if not (len(chunks) == len(chunks[0].objs) == 1): raise RuntimeError g = chunks[0].objs[0] for ftype, fname in fields: rv[(ftype, fname)] = self.grids_in_memory[g.id][fname].swapaxes(0, 2) return rv if size is None: size = sum(g.count(selector) for chunk in chunks for g in chunk.objs) for field in fields: ftype, fname = field fsize = size rv[field] = np.empty(fsize, dtype="float64") ng = sum(len(c.objs) for c in chunks) mylog.debug( "Reading %s cells of %s fields in %s grids", size, [f2 for f1, f2 in fields], ng, ) ind = 0 for chunk in chunks: for g in chunk.objs: # We want a *hard error* here. # if g.id not in self.grids_in_memory: continue for field in fields: ftype, fname = field data_view = self.grids_in_memory[g.id][fname][ self.my_slice ].swapaxes(0, 2) nd = g.select(selector, data_view, rv[field], ind) ind += nd assert ind == fsize return rv def _read_particle_coords(self, chunks, ptf): chunks = list(chunks) for chunk in chunks: # These should be organized by grid filename for g in chunk.objs: if g.id not in self.grids_in_memory: continue nap = sum(g.NumberOfActiveParticles.values()) if g.NumberOfParticles == 0 and nap == 0: continue for ptype in sorted(ptf): x, y, z = ( self.grids_in_memory[g.id]["particle_position_x"], self.grids_in_memory[g.id]["particle_position_y"], self.grids_in_memory[g.id]["particle_position_z"], ) yield ptype, (x, y, z) def _read_particle_fields(self, chunks, ptf, selector): chunks = list(chunks) for chunk in chunks: # These should be organized by grid filename for g in chunk.objs: if g.id not in self.grids_in_memory: continue nap = sum(g.NumberOfActiveParticles.values()) if g.NumberOfParticles == 0 and nap == 0: continue for ptype, field_list in sorted(ptf.items()): x, y, z = ( self.grids_in_memory[g.id]["particle_position_x"], self.grids_in_memory[g.id]["particle_position_y"], self.grids_in_memory[g.id]["particle_position_z"], ) mask = selector.select_points(x, y, z, 0.0) if mask is None: continue for field in field_list: data = self.grids_in_memory[g.id][field] if field in _convert_mass: data = data * g.dds.prod(dtype="f8") yield (ptype, field), data[mask] class IOHandlerPacked2D(IOHandlerPackedHDF5): _dataset_type = "enzo_packed_2d" _particle_reader = False def _read_data_set(self, grid, field): f = h5py.File(grid.filename, mode="r") ds = f["/Grid%08i/%s" % (grid.id, field)][:] f.close() return ds.transpose()[:, :, None] def _read_fluid_selection(self, chunks, selector, fields, size): rv = {} # Now we have to do something unpleasant chunks = list(chunks) if isinstance(selector, GridSelector): if not (len(chunks) == len(chunks[0].objs) == 1): raise RuntimeError g = chunks[0].objs[0] f = h5py.File(g.filename, mode="r") gds = f.get("/Grid%08i" % g.id) for ftype, fname in fields: rv[(ftype, fname)] = np.atleast_3d(gds.get(fname)[()].transpose()) f.close() return rv if size is None: size = sum(g.count(selector) for chunk in chunks for g in chunk.objs) for field in fields: ftype, fname = field fsize = size rv[field] = np.empty(fsize, dtype="float64") ng = sum(len(c.objs) for c in chunks) mylog.debug( "Reading %s cells of %s fields in %s grids", size, [f2 for f1, f2 in fields], ng, ) ind = 0 for chunk in chunks: f = None for g in chunk.objs: if f is None: # print("Opening (count) %s" % g.filename) f = h5py.File(g.filename, mode="r") gds = f.get("/Grid%08i" % g.id) if gds is None: gds = f for field in fields: ftype, fname = field ds = np.atleast_3d(gds.get(fname)[()].transpose()) nd = g.select(selector, ds, rv[field], ind) # caches ind += nd f.close() return rv class IOHandlerPacked1D(IOHandlerPackedHDF5): _dataset_type = "enzo_packed_1d" _particle_reader = False def _read_data_set(self, grid, field): f = h5py.File(grid.filename, mode="r") ds = f["/Grid%08i/%s" % (grid.id, field)][:] f.close() return ds.transpose()[:, None, None]
38.867925
85
0.499792
1,690
14,420
4.138462
0.179882
0.006434
0.027881
0.034029
0.582928
0.536889
0.505147
0.458393
0.420646
0.409637
0
0.013341
0.402219
14,420
370
86
38.972973
0.798028
0.091678
0
0.592233
0
0
0.047903
0
0
0
0
0
0.003236
1
0.05178
false
0
0.019417
0.006472
0.158576
0
0
0
0
null
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
null
0
0
0
0
0
0
0
0
0
0
0
0
1
0
81434230700195b62a622200418ac9737e7bcf37
1,275
py
Python
cidr_enum.py
arisada/cidr_enum
1908f20ac15a83738fc1ff74ff17a7280bec769f
[ "BSD-2-Clause" ]
null
null
null
cidr_enum.py
arisada/cidr_enum
1908f20ac15a83738fc1ff74ff17a7280bec769f
[ "BSD-2-Clause" ]
null
null
null
cidr_enum.py
arisada/cidr_enum
1908f20ac15a83738fc1ff74ff17a7280bec769f
[ "BSD-2-Clause" ]
null
null
null
#!/usr/bin/env python3 """ cidr_enum.py is a very simple tool to help enumerate IP ranges when being used with other tools """ import argparse import netaddr def enum_ranges(ranges, do_sort): cidrs=[] for r in ranges: try: cidrs.append(netaddr.IPNetwork(r)) except Exception as e: print("Error:", e) return if(do_sort): cidrs = sorted(cidrs) #print(cidrs) for cidr in cidrs: for ip in cidr: print(ip) def main(): parser = argparse.ArgumentParser(description='Enumarate CIDR ranges') parser.add_argument('ranges', metavar='range', type=str, nargs='*', help='List of CIDR ranges to enumerate') parser.add_argument('-f', '--files', metavar='file', type=str, nargs='*', help='List of files to retrieve CIDR ranges to enumerate') parser.add_argument('-s', '--sort', action='store_true', help='Sort CIDR ranges') args = parser.parse_args() if args.files: files = list(args.files) else: files = [] ranges = list(args.ranges) if not (files or ranges): print ("Please give a list or ranges or input files") parser.print_help() return for f in files: with open(f, "r") as fd: for l in fd.readlines(): ranges.append(l.strip()) enum_ranges(ranges, do_sort=args.sort) if __name__ == '__main__': main()
25
95
0.677647
193
1,275
4.373057
0.419689
0.047393
0.060427
0.042654
0.194313
0.14218
0.090047
0
0
0
0
0.000959
0.181961
1,275
50
96
25.5
0.808245
0.101176
0
0.051282
0
0
0.194371
0
0
0
0
0
0
1
0.051282
false
0
0.051282
0
0.153846
0.102564
0
0
0
null
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
null
0
0
0
0
0
0
0
0
0
0
0
0
1
0
81434e0f75802811d789efae93fbec2c949725b8
7,469
py
Python
configs/k400-fixmatch-tg-alignment-videos-ptv-simclr/8gpu/r3d_r18_8x8x1_45e_k400_rgb_offlinetg_1percent_align0123_1clip_no_contrast_precisebn_ptv.py
lambert-x/video_semisup
8ff44343bb34485f8ad08d50ca4d8de22e122c1d
[ "Apache-2.0" ]
null
null
null
configs/k400-fixmatch-tg-alignment-videos-ptv-simclr/8gpu/r3d_r18_8x8x1_45e_k400_rgb_offlinetg_1percent_align0123_1clip_no_contrast_precisebn_ptv.py
lambert-x/video_semisup
8ff44343bb34485f8ad08d50ca4d8de22e122c1d
[ "Apache-2.0" ]
null
null
null
configs/k400-fixmatch-tg-alignment-videos-ptv-simclr/8gpu/r3d_r18_8x8x1_45e_k400_rgb_offlinetg_1percent_align0123_1clip_no_contrast_precisebn_ptv.py
lambert-x/video_semisup
8ff44343bb34485f8ad08d50ca4d8de22e122c1d
[ "Apache-2.0" ]
null
null
null
# model settings model = dict( type='Semi_AppSup_TempSup_SimCLR_Crossclip_PTV_Recognizer3D', backbone=dict( type='ResNet3d', depth=18, pretrained=None, pretrained2d=False, norm_eval=False, conv_cfg=dict(type='Conv3d'), norm_cfg=dict(type='SyncBN', requires_grad=True, eps=1e-3), act_cfg=dict(type='ReLU'), conv1_kernel=(3, 7, 7), conv1_stride_t=1, pool1_stride_t=1, inflate=(1, 1, 1, 1), spatial_strides=(1, 2, 2, 2), temporal_strides=(1, 2, 2, 2), zero_init_residual=False), cls_head=dict( type='I3DHead', num_classes=400, in_channels=512, spatial_type='avg', dropout_ratio=0.5, init_std=0.01), cls_head_temp=None, temp_backbone='same', temp_sup_head='same', train_cfg=dict( warmup_epoch=10, fixmatch_threshold=0.3, temp_align_indices=(0, 1, 2, 3), align_loss_func='Cosine', pseudo_label_metric='avg', crossclip_contrast_loss=[], crossclip_contrast_range=[], ), test_cfg=dict(average_clips='score')) # dataset settings dataset_type = 'VideoDataset' dataset_type_labeled = 'VideoDataset_Contrastive' dataset_type_unlabeled = 'UnlabeledVideoDataset_MultiView_Contrastive' # dataset_type_appearance = 'RawframeDataset_withAPP' data_root = 'data/kinetics400/videos_train' data_root_val = 'data/kinetics400/videos_val' labeled_percentage = 1 ann_file_train_labeled = f'data/kinetics400/videossl_splits/kinetics400_train_{labeled_percentage}_percent_labeled_videos.txt' ann_file_train_unlabeled = 'data/kinetics400/kinetics400_train_list_videos.txt' ann_file_val = 'data/kinetics400/kinetics400_val_list_videos.txt' ann_file_test = 'data/kinetics400/kinetics400_val_list_videos.txt' img_norm_cfg = dict( mean=[123.675, 116.28, 103.53], std=[58.395, 57.12, 57.375], to_bgr=False) train_pipeline = [ dict(type='DecordInit'), dict(type='SampleFrames_Custom', clip_len=8, frame_interval=8, num_clips=1, total_frames_offset=-1), dict(type='DecordDecode_Custom', extra_modalities=['tempgrad']), dict(type='Resize', scale=(-1, 256), lazy=True), dict(type='RandomResizedCrop', lazy=True), dict(type='Resize', scale=(224, 224), keep_ratio=False, lazy=True), dict(type='Flip', flip_ratio=0.5, lazy=True), dict(type='Fuse_WithDiff'), dict(type='Normalize', **img_norm_cfg), dict(type='Normalize_Diff', **img_norm_cfg, raw_to_diff=False, redist_to_rgb=False), dict(type='FormatShape', input_format='NCTHW'), dict(type='FormatShape_Diff', input_format='NCTHW'), dict(type='Collect', keys=['imgs', 'label', 'imgs_diff'], meta_keys=[]), dict(type='ToTensor', keys=['imgs', 'label', 'imgs_diff']) ] # Get the frame and resize, shared by both weak and strong train_pipeline_weak = [ dict(type='DecordInit'), dict(type='SampleFrames_Custom', clip_len=8, frame_interval=8, num_clips=1, total_frames_offset=-1), dict(type='DecordDecode_Custom', extra_modalities=['tempgrad']), dict(type='Resize', scale=(-1, 256), lazy=True), dict(type='RandomResizedCrop', lazy=True), dict(type='Resize', scale=(224, 224), keep_ratio=False, lazy=True), dict(type='Flip', flip_ratio=0.5, lazy=True), dict(type='Fuse_WithDiff'), ] # Only used for strong augmentation train_pipeline_strong = [ dict(type='Imgaug', transforms='default'), dict(type='Imgaug_Custom', transforms='default', modality='imgs_diff') ] # Formating the input tensors, shared by both weak and strong train_pipeline_format = [ dict(type='Normalize', **img_norm_cfg), dict(type='Normalize_Diff', **img_norm_cfg, raw_to_diff=False, redist_to_rgb=False), dict(type='FormatShape', input_format='NCTHW'), dict(type='FormatShape_Diff', input_format='NCTHW'), dict(type='Collect', keys=['imgs', 'label', 'imgs_diff'], meta_keys=[]), dict(type='ToTensor', keys=['imgs', 'label', 'imgs_diff']) ] val_pipeline = [ dict(type='DecordInit'), dict( type='SampleFrames', clip_len=8, frame_interval=8, num_clips=1, test_mode=True), dict(type='DecordDecode'), dict(type='Resize', scale=(-1, 256), lazy=True), dict(type='CenterCrop', crop_size=224, lazy=True), dict(type='Flip', flip_ratio=0, lazy=True), dict(type='Fuse'), dict(type='Normalize', **img_norm_cfg), dict(type='FormatShape', input_format='NCTHW'), dict(type='Collect', keys=['imgs', 'label'], meta_keys=[]), dict(type='ToTensor', keys=['imgs']) ] test_pipeline = [ dict(type='DecordInit'), dict( type='SampleFrames', clip_len=8, frame_interval=8, num_clips=10, test_mode=True), dict(type='DecordDecode'), dict(type='Resize', scale=(-1, 256)), dict(type='ThreeCrop', crop_size=256), dict(type='Flip', flip_ratio=0), dict(type='Normalize', **img_norm_cfg), dict(type='FormatShape', input_format='NCTHW'), dict(type='Collect', keys=['imgs', 'label'], meta_keys=[]), dict(type='ToTensor', keys=['imgs']) ] data = dict( videos_per_gpu=8, # NOTE: Need to reduce batch size. 16 -> 5 workers_per_gpu=4, # Default: 4 train_dataloader=dict(drop_last=True, pin_memory=True), train_labeled=dict( type=dataset_type_labeled, ann_file=ann_file_train_labeled, data_prefix=data_root, pipeline=train_pipeline, contrast_clip_num=1 ), train_unlabeled=dict( type=dataset_type_unlabeled, ann_file=ann_file_train_unlabeled, data_prefix=data_root, pipeline_weak=train_pipeline_weak, pipeline_strong=train_pipeline_strong, pipeline_format=train_pipeline_format, contrast_clip_num=1 ), val=dict( type=dataset_type, ann_file=ann_file_val, data_prefix=data_root_val, pipeline=val_pipeline, test_mode=True), test=dict( type=dataset_type, ann_file=ann_file_val, data_prefix=data_root_val, pipeline=test_pipeline, test_mode=True), precise_bn=dict( type=dataset_type, ann_file=ann_file_train_unlabeled, data_prefix=data_root, pipeline=val_pipeline), videos_per_gpu_precise_bn=5 ) # optimizer optimizer = dict( type='SGD', lr=0.2, momentum=0.9, weight_decay=0.0001) # this lr 0.2 is used for 8 gpus optimizer_config = dict(grad_clip=dict(max_norm=40, norm_type=2)) # learning policy lr_config = dict(policy='CosineAnnealing', min_lr=0, warmup='linear', warmup_ratio=0.1, warmup_by_epoch=True, warmup_iters=10) total_epochs = 45 # Might need to increase this number for different splits. Default: 180 checkpoint_config = dict(interval=5, max_keep_ckpts=3) evaluation = dict( interval=5, metrics=['top_k_accuracy', 'mean_class_accuracy'], topk=(1, 5)) # Default: 5 log_config = dict( interval=20, # Default: 20 hooks=[ dict(type='TextLoggerHook'), dict(type='TensorboardLoggerHook'), ]) precise_bn = dict(num_iters=200, interval=5, bn_range=['backbone', 'cls_head']) dist_params = dict(backend='nccl') log_level = 'INFO' work_dir = None load_from = None resume_from = None workflow = [('train', 1)] find_unused_parameters = False
33.95
126
0.664078
985
7,469
4.75533
0.267005
0.111016
0.033305
0.037575
0.476729
0.447054
0.442357
0.422716
0.396029
0.395816
0
0.035447
0.195475
7,469
219
127
34.105023
0.744051
0.058375
0
0.379487
0
0
0.184409
0.062847
0
0
0
0
0
1
0
false
0
0
0
0
0
0
0
0
null
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
null
0
0
0
0
0
0
0
0
0
0
0
0
1
0
d48ba98f343e96c0da8c5db735d6d98bd7a3e3d3
5,370
py
Python
modules/statusbar.py
themilkman/GitGutter
355b4480e7e1507fe1f9ae1ad9eca9649400a76c
[ "MIT" ]
null
null
null
modules/statusbar.py
themilkman/GitGutter
355b4480e7e1507fe1f9ae1ad9eca9649400a76c
[ "MIT" ]
null
null
null
modules/statusbar.py
themilkman/GitGutter
355b4480e7e1507fe1f9ae1ad9eca9649400a76c
[ "MIT" ]
null
null
null
# -*- coding: utf-8 -*- import sublime from . import blame from . import templates class SimpleStatusBarTemplate(object): """A simple template class with the same interface as jinja2's one.""" # a list of variables used by this template variables = frozenset([ 'repo', 'branch', 'compare', 'inserted', 'deleted', 'modified', 'line_author', 'line_author_age' ]) @staticmethod def render(repo=None, branch=None, compare=None, inserted=0, deleted=0, modified=0, line_author=None, line_author_age=None, **kwargs): """Format the status bar text using a static set of rules. Arguments: repo (string): The repository name branch (string): The branch name. compare (string): The compared branch/tag/commit inserted (int): The amount of inserted lines deleted (int): The amount of deleted lines modified (int): The amount of modified lines line_author (string): The author of the active line line_author_age (string): The age of the active line's change Returns: string: The formatted message to display in the status bar. """ if not repo or not branch: return '' parts = ['{repo}/{branch}'] # Compare against if compare not in ('HEAD', branch, None): parts.append('Comparing against {compare}') # File statistics if inserted: parts.append('{inserted}+') if deleted: parts.append('{deleted}-') if modified: parts.append(u'{modified}≠') # blame message if line_author and line_author_age: parts.append(u'⟢ {line_author} ({line_author_age})') # join template and fill with locals return ', '.join(parts).format(**locals()) class GitGutterStatusBar(object): """The class manages status bar text rendering. It stores all information, which might get displayed in the status bar and provides functions to partially update them. """ def __init__(self, view, settings): """Initialize object.""" # the sublime.View the status bar is attached to self.view = view # the settings.ViewSettings object which stores GitGutter' settings self.settings = settings # initialize the jinja2 template self.template = None # the variables to use to render the status bar self.vars = { # sublime text git integration enabled 'st_git_status': view.settings().get('show_git_status', False), # the repository name 'repo': None, # the active branch name 'branch': None, # the branch we compare against 'compare': None, # the upstream branch name 'remote': None, # the commits the local is ahead of upstream 'ahead': 0, # the commits the local is behind of upstream 'behind': 0, # repository statistics 'added_files': 0, 'deleted_files': 0, 'modified_files': 0, 'staged_files': 0, # file statistics 'state': None, 'deleted': 0, 'inserted': 0, 'modified': 0, } # declare all blame variables for var in blame.BLAME_VARIABLES: self.vars[var] = None def is_enabled(self): """Return whether status bar text is enabled in settings or not.""" enabled = self.settings.get('show_status_bar_text', False) if self.template and not enabled: self.template = None self.vars['repo'] = None self.erase() return enabled def has(self, variables): """Check if a set of variables is used by the user defined template. Arguments: variables (iter): An iterateable object with all the variables to check for existence within the active template. Returns: bool: True - if at least one variable is used by the template. False - if no variable is used by the template. """ try: return any(var in self.template.variables for var in variables) except: return False def erase(self): """Erase status bar text.""" self.view.erase_status('00_git_gutter') def update(self, **kwargs): """Update a set of variables and redraw the status bar text. Arguments: kwargs (dict): The dictionary of possibly changed variables to update the status bar text with. Raises: KeyError, if `kwargs` contains unknown variables. """ want_update = False for key, value in kwargs.items(): if self.vars[key] != value: self.vars[key] = value want_update = True if want_update: if not self.template: self.template = templates.create( self.settings, 'status_bar_text', SimpleStatusBarTemplate) self.view.set_status( '00_git_gutter', self.template.render(**self.vars))
33.354037
78
0.570577
613
5,370
4.931485
0.278956
0.035726
0.034403
0.015878
0.046312
0.017863
0
0
0
0
0
0.005385
0.343017
5,370
160
79
33.5625
0.850907
0.390503
0
0.026667
0
0
0.129835
0
0
0
0
0
0
1
0.08
false
0
0.04
0
0.226667
0
0
0
0
null
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
null
0
0
0
0
0
0
0
0
0
0
0
0
1
0
d48e8d3a34a96d0df0efeeb8e07e14864978dc32
1,115
py
Python
test.py
LeonHodgesAustin/video_stream_processor
8014705edc37599716eb1320d46c99136fe3e262
[ "BSD-3-Clause" ]
null
null
null
test.py
LeonHodgesAustin/video_stream_processor
8014705edc37599716eb1320d46c99136fe3e262
[ "BSD-3-Clause" ]
null
null
null
test.py
LeonHodgesAustin/video_stream_processor
8014705edc37599716eb1320d46c99136fe3e262
[ "BSD-3-Clause" ]
null
null
null
# import logging # import hercules.lib.util.hercules_logging as l # from hercules.lib.util import sso as sso import opencv2 as cv2 import urllib import numpy as np # log = l.setup_logging(__name__) def main(args=None): # username, passowrd = sso.get_login_credentials("WATCHER") # Open a sample video available in sample-videos vcap = cv2.VideoCapture('https://www.sample-videos.com/video/mp4/720/big_buck_bunny_720p_2mb.mp4') #if not vcap.isOpened(): # print "File Cannot be Opened" while(True): # Capture frame-by-frame ret, frame = vcap.read() #print cap.isOpened(), ret if frame is not None: # Display the resulting frame cv2.imshow('frame',frame) # Press q to close the video windows before it ends if you want if cv2.waitKey(22) & 0xFF == ord('q'): break else: print("Frame is None") break # When everything done, release the capture vcap.release() cv2.destroyAllWindows() print("Video stop") if __name__ == "__main__": main()
27.875
102
0.6287
149
1,115
4.57047
0.597315
0.032305
0.044053
0
0
0
0
0
0
0
0
0.02214
0.270852
1,115
39
103
28.589744
0.815498
0.426009
0
0.105263
0
0
0.172524
0
0
0
0.00639
0
0
1
0.052632
false
0
0.157895
0
0.210526
0.105263
0
0
0
null
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
null
0
0
0
0
0
0
0
0
0
0
0
0
1
0
d48f61239e116e08f567623063b6adca1886ef91
3,792
py
Python
kobe-trading-bot/app.py
LeonardoM011/kobe-trading-bot
83a84ee0fb8dab3d9ae174be91e96de6d5f2d823
[ "MIT" ]
null
null
null
kobe-trading-bot/app.py
LeonardoM011/kobe-trading-bot
83a84ee0fb8dab3d9ae174be91e96de6d5f2d823
[ "MIT" ]
null
null
null
kobe-trading-bot/app.py
LeonardoM011/kobe-trading-bot
83a84ee0fb8dab3d9ae174be91e96de6d5f2d823
[ "MIT" ]
null
null
null
#!/usr/bin/env python3 # Crypto trading bot using binance api # Author: LeonardoM011<Leonardo.leo.201@gmail.com> # Created on 2021-02-05 21:56 # Set constants here: DELTA_TIME = 300 # How long can we check for setting up new trade (in seconds) # ---------------------- # Imports: import os import sys import time as t import datetime # Adding python-binance to path and importing python-binance sys.path.insert(1, "../deps/binance") from binance.client import Client from fun import * import candles as can # Globals: client = None # Main program loop def start(): hour_repeated = -1 try: while True: time = datetime.datetime.now() hour = time.hour minute = time.minute open_trade = client.futures_get_open_orders() if minute < 10: if not open_trade and hour_repeated != hour: candles = client.futures_klines(symbol="BTCUSDT", interval=Client.KLINE_INTERVAL_1HOUR, contractType="PERPETUAL") info = can.get_candle_info(candles[:-1]) candle_side = can.get_side(info) if candle_side: output.print_info('Initiating trade...') #current_price = client.futures_mark_price(symbol="BTCUSDT", contractType="PERPETUAL")['markPrice'] close_price = candles client.futures_create_order(symbol="BTCUSDT", side=candle_side, type=Client.ORDER_TYPE_MARKET, quantity=0.001) client.futures_create_order(symbol="BTCUSDT", side=can.flip_side(candle_side), type=Client.ORDER_TYPE_STOP_LOSS_LIMIT, quantity=0.001, price=57975.0, stopPrice=57976.0, workingType="MARK_PRICE") hour_repeated = hour t.sleep(300) except KeyboardInterrupt: print('Program canceled...') def connect(): while True: api_key = get_api_key("BINANCE_API_KEY") api_secret = get_api_key("BINANCE_API_SECRET_KEY") output.print_info('Connecting to binance...') global client client = Client(api_key, api_secret) if check_connectivity(client): output.print_ok('Successfully connected to binance.') if check_account_status(client): output.print_ok('Successfully connected using api keys.') return output.print_failed('Cannot connect to binance with api keys.') def main(): output.print_ok('Starting kobe trading bot...') connect() start() #try: # client.get_all_orders() #except BinanceAPIException as e: # print e.status_code # print e.message # datetime.datetime.now().year #btcusdt_price = requests.get("https://api.binance.com/api/v3/ticker/price?symbol=BTCUSDT") #if (btcusdt_price.status_code != 200): # print("Error connecting to api server to get price") # return #print("Successfully connected and got price") #while(True): # btcusdt_price = requests.get("https://api.binance.com/api/v3/ticker/price?symbol=BTCUSDT") # print("BTC/USDT: {}".format(btcusdt_price.json()['price'])) # time.sleep(1.0) #btcusdtindex = find_index_of('symbol', 'BTCUSDT', client.get_all_tickers()) #while (True): # print(client.get_all_tickers()[btcusdtindex]) # time.sleep(5.0) # client.futures_create_order(symbol="BTCUSDT", side="SELL", type="STOP", quantity=0.001, price=57975.0, stopPrice=57976.0, workingType="MARK_PRICE") # client.futures_create_order(symbol="BTCUSDT", side="BUY", type="MARKET", quantity=0.001) if __name__ == "__main__": main()
36.461538
219
0.620781
455
3,792
4.989011
0.364835
0.051542
0.03348
0.042291
0.281938
0.247577
0.212335
0.112775
0.112775
0.112775
0
0.028561
0.26134
3,792
104
220
36.461538
0.781864
0.364979
0
0.039216
0
0
0.132864
0.009679
0
0
0
0
0
1
0.058824
false
0
0.137255
0
0.215686
0.137255
0
0
0
null
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
null
0
0
0
0
0
0
0
0
0
0
0
0
1
0
d4910ca755a73b263041c7cd3c681f6108d61901
13,061
py
Python
imported_files/plotting_edh01.py
SoumyaShreeram/Locating_AGN_in_DM_halos
1cfbee69b2c000faee4ecb199d65c3235afbed42
[ "MIT" ]
null
null
null
imported_files/plotting_edh01.py
SoumyaShreeram/Locating_AGN_in_DM_halos
1cfbee69b2c000faee4ecb199d65c3235afbed42
[ "MIT" ]
null
null
null
imported_files/plotting_edh01.py
SoumyaShreeram/Locating_AGN_in_DM_halos
1cfbee69b2c000faee4ecb199d65c3235afbed42
[ "MIT" ]
null
null
null
# -*- coding: utf-8 -*- """Plotting.py for notebook 01_Exploring_DM_Halos This python file contains all the functions used for plotting graphs and maps in the 1st notebook (.ipynb) of the repository: 01. Exploring parameters in DM halos and sub-halos Script written by: Soumya Shreeram Project supervised by Johan Comparat Date created: 23rd February 2021 Last updated on 30th March 2021 """ # astropy modules import astropy.units as u import astropy.io.fits as fits from astropy.table import Table, Column from astropy.coordinates import SkyCoord from astropy.cosmology import FlatLambdaCDM, z_at_value import numpy as np # scipy modules from scipy.spatial import KDTree from scipy.interpolate import interp1d import os import importlib # plotting imports import matplotlib from mpl_toolkits import axes_grid1 import matplotlib.pyplot as plt from mpl_toolkits.mplot3d.axes3d import Axes3D from matplotlib.ticker import LinearLocator, FormatStrFormatter from matplotlib import cm from matplotlib.collections import PatchCollection from matplotlib.patches import Rectangle import Exploring_DM_Haloes as edh def setLabel(ax, xlabel, ylabel, title, xlim, ylim, legend=True): """ Function defining plot properties @param ax :: axes to be held @param xlabel, ylabel :: labels of the x-y axis @param title :: title of the plot @param xlim, ylim :: x-y limits for the axis """ ax.set_xlabel(xlabel) ax.set_ylabel(ylabel) if xlim != 'default': ax.set_xlim(xlim) if ylim != 'default': ax.set_ylim(ylim) if legend: l = ax.legend(loc='best', fontsize=14) for legend_handle in l.legendHandles: legend_handle._legmarker.set_markersize(12) ax.grid(False) ax.set_title(title, fontsize=18) return def plotAgnClusterDistribution(pos_z_clu, pos_z_AGN, pos_z_halo, cluster_params): """ Function to plot the AGN cluster distribution @pos_z_clu :: postion and redshifts of all the selected 'clusters' @pos_z_AGN :: postion and redshifts of all the selected AGNs @pos_z_gal :: postion and redshifts of all the selected galaxies """ halo_m_500c = cluster_params[0] fig, ax = plt.subplots(1,1,figsize=(9,8)) # plotting halos halos = ax.plot(pos_z_halo[0], pos_z_halo[1], '.', color='#fcd16d', markersize=0.2, label=r'All DM Halos', alpha=0.2) # plotting clusters cluster = ax.plot(pos_z_clu[0], pos_z_clu[1], 'o', color= '#03a351', markersize=3, label=r'Clusters $M_{500c}> 10^{%.1f} M_\odot$ '%(np.log10(halo_m_500c))) # plotting AGNs agn = ax.plot(pos_z_AGN[0], pos_z_AGN[1], '*', color='k', markersize=3.5, label=r'AGN', alpha=0.7) # labeling axes and defining limits xlim = [np.min(pos_z_halo[0]), np.max(pos_z_halo[0])] ylim = [np.min(pos_z_halo[1]), np.max(pos_z_halo[1])] setLabel(ax, 'R.A. (deg)', 'Dec (deg)', '', xlim, ylim, legend=True) print('Redshift z<%.2f'%(np.max(pos_z_clu[2]))) return def plotHostSubHalos(pos_z_cen_halo, pos_z_sat_halo, pos_z_AGN): """ Function to plot the host and satellite halo distribution @hd_halo :: table with all relevant info on halos, clusters, and galaxies within them --> divided into 3 because each hd_halo holds info on 1000 halos alone @pos_z_AGN :: postion and redshifts of all the selected AGNs """ ra_cen, dec_cen = pos_z_cen_halo[0], pos_z_cen_halo[1] ra_sat, dec_sat = pos_z_sat_halo[0], pos_z_sat_halo[1] fig, ax = plt.subplots(1,1,figsize=(9,8)) # plotting host halos host_halos = ax.plot(ra_cen, dec_cen, '.', color= 'k', markersize=0.06, label=r'Host-halos $P_{id}=-1$', alpha=0.4) # plotting sat halos sat_halos = ax.plot(ra_sat, dec_sat, 'o', color='#07d9f5', markersize=0.07, label=r'Satellite halos $P_{id} \neq -1$', alpha=0.7) # plotting AGNs agn = ax.plot(pos_z_AGN[0], pos_z_AGN[1], '*', color='#fff717', markersize=6.5, label=r'AGN', markeredgecolor='w', markeredgewidth=0.4) # labeling axes and defining limits xlim = [np.min(pos_z_AGN[0]), np.max(pos_z_AGN[0])] ylim = [np.min(pos_z_AGN[1]), np.max(pos_z_AGN[1])] setLabel(ax, 'R.A. (deg)', 'Dec (deg)', '', xlim, ylim, legend=True) print('AGNs: %d, Host (central) halos: %.2e, Sattelite halos: %.2e'%(len(pos_z_AGN[0]), len(ra_cen), len(ra_sat))) return def plotAGNfraction(pos_z_AGN, pos_z_gal, redshift_limit_agn, bin_size): """ Function to plot the agn fraction in the given pixel @pos_z_AGN :: postion and redshifts of all the selected AGNs @pos_z_gal :: postion and redshifts of all the selected galaxies @redshift_limit_agn :: upper limit on redshift based on the clusters found """ fig, ax = plt.subplots(1,2,figsize=(19,7)) # getting the useful histogram properties counts_agn, redshift_bins_agn = np.histogram(pos_z_AGN[2], bins = bin_size) counts_gal, redshift_bins_gal = np.histogram(pos_z_gal[2], bins = bin_size) # plotting the galaxy and agn distribution as a function of redshift ax[0].plot(redshift_bins_gal[1:], counts_gal, 'ks', ms=4, label=r'DM Halos') ax[0].plot(redshift_bins_agn[1:], counts_agn, 'bs', ms=4, label=r'AGNs') # axis properties - 0 xlim = [np.min(redshift_bins_agn[1:]), np.max(redshift_bins_agn[1:])] setLabel(ax[0], r'Redshift$_R$', 'Counts','', xlim, 'default', legend=True) ax[0].set_yscale("log") # agn fraction as a function of redshift f_agn, idx = [], [] for c, c_gal in enumerate(counts_gal): if c_gal != 0: f_agn.append(((counts_agn[c]*100)/c_gal)) idx.append(c) z_bin_modified = redshift_bins_gal[1:][np.array(idx)] # plot agn fraction ax[1].plot(z_bin_modified, f_agn, 's', color='#6b0385', ms=4) # axis properties - 1 xlim = [np.min(redshift_bins_agn[1:])-0.02, np.max(redshift_bins_agn[1:])] setLabel(ax[1], r'Redshift$_R$', r'$f_{AGN}$ (%s)'%"%", '', xlim, 'default', legend=False) ax[1].set_yscale("log") plt.savefig('figures/agn_frac.pdf', facecolor='w', edgecolor='w') print( 'Reddhift z<%.2f'%redshift_limit_agn ) return redshift_bins_gal[1:] def plotRedshiftComovingDistance(cosmo, redshift_limit, resolution = 0.0001): """Function to plot the relation between redshift and the comoving distance @cosmo :: cosmology package loaded @redshift_limit :: upper limit in redshift --> end point for interpolation @resolution :: resolution of time steps (set to e-4 based of simulation resolution) @Returns :: plot showing the dependence of redshift on comoving distance """ fig, ax = plt.subplots(1,1,figsize=(7,6)) distance_Mpc = cosmo.comoving_distance(np.arange(0,redshift_limit, resolution)) redshifts = np.arange(0,redshift_limit, resolution) ax.plot(redshifts, distance_Mpc, 'k.', ms=1) setLabel(ax, 'Redshift (z)', 'Comoving distance (Mpc)', '', 'default', 'default', legend=False) print('Redshift-Comoving distance relationship') return def plotMergerDistribution(merger_val_gal, counts_gal, merger_val_agn, counts_agn, cosmo, redshift_limit): """ Function to plot the distribution (counts) of the merger scale factor/redshift """ fig, ax = plt.subplots(1,1,figsize=(7,6)) ax1 = plt.gca() ax2 = ax1.twiny() # plot the merger distribution for galaxies and agns ax1.plot(merger_val_gal, counts_gal, 'kx', label='DM Halos') ax1.plot(merger_val_agn, counts_agn, 'bx', label='AGNs') setLabel(ax1, r'Scale, $a(t)$, of last Major Merger', 'Counts', '', 'default', 'default', legend=True) ax.set_yscale("log") # setting the x-label on top (converting a to redshift) a_min, a_max = np.min(merger_val_gal), np.max(merger_val_gal) scale_factor_arr = [a_max, a_min*4, a_min*2, a_min] ax2.set_xticks([(1/a) -1 for a in scale_factor_arr]) ax2.invert_xaxis() ax2.set_xlabel('Redshift (z)') ax2.xaxis.set_major_formatter(FormatStrFormatter('%.1f')) print("Objects with merger redshifts z < %.2f"%z_at_value(cosmo.scale_factor, a_min)) plt.savefig('figures/merger_distribution_z%.2f.pdf'%redshift_limit, facecolor='w', edgecolor='w') return def plotCentralSatelliteScaleMergers(cen_sat_AGN, cen_sat_halo, redshift_limit): """ Function to plot the central and sattelite scale factors for mergers """ fig, ax = plt.subplots(1,1,figsize=(7,6)) labels = [r'central AGNs', r'satellite AGNs', 'central DM halos', 'satellite DM halos'] c, m, ms = ['b', '#38cee8', 'k', 'grey'], ['^', '*', '^', '*'], [9, 15, 5, 9] mec, mew = ['w', 'k', 'k', '#abaeb3'], [0.7, 0.4, 1, 0.7] for i in [0, 1]: s_m_agn, c_agn = np.unique(cen_sat_AGN[i]['HALO_scale_of_last_MM'], return_counts=True) s_m_gal, c_gal = np.unique(cen_sat_halo[i]['HALO_scale_of_last_MM'], return_counts=True) # agns ax.plot(s_m_agn, c_agn, color=c[i], marker=m[i], ls='', ms=ms[i], label=labels[i], markeredgecolor=mec[i], markeredgewidth=mew[i]) # DM halos j = i + 2 ax.plot(s_m_gal, c_gal, color=c[j], marker=m[j], ls='', ms=ms[j], label=labels[j], markeredgecolor=mec[j], markeredgewidth=mew[j]) # set label setLabel(ax, r'Scale, $a(t)$, of last Major Merger', 'Counts', '', 'default', 'default', legend=True) ax.set_yscale("log") plt.savefig('figures/merger_dist_cenAndsat_z%.2f.pdf'%redshift_limit, facecolor='w', edgecolor='w') print('Objects below z: ', redshift_limit) return [labels, c, m, ms, mec, mew] def plotTimeSinceMergerDist(scale_merger_AGN, scale_merger_gal, z_AGN, z_gal, cosmo, bin_size, redshift_limit): """ Plot the distribution of halos with respective galaxies & agns given the time since merger """ # get the time difference since merger events in the halos t_merger_agn = edh.getMergerTimeDifference(scale_merger_AGN, z_AGN, cosmo) t_merger_gal = edh.getMergerTimeDifference(scale_merger_gal, z_gal, cosmo) # get the t since merger bins and counts if bin_size[0]: c_t_agn, merger_bins_agn = np.histogram(np.array(t_merger_agn), bins = bin_size[1]) c_t_gal, merger_bins_gal = np.histogram(np.array(t_merger_gal), bins = bin_size[1]) merger_bins_agn = merger_bins_agn[:-1] merger_bins_gal = merger_bins_gal[:-1] else: merger_bins_agn, c_t_agn = np.unique(t_merger_agn, return_counts=True) merger_bins_gal, c_t_gal = np.unique(t_merger_gal, return_counts=True) fig, ax = plt.subplots(1,1,figsize=(7,6)) # plot the time since merger distribution for galaxies and agns ax.plot(merger_bins_gal, np.cumsum(c_t_gal), 'k^', label='DM Halos', ms=4) ax.plot(merger_bins_agn, np.cumsum(c_t_agn), 'b^', label='AGNs', ms=4) # set labels/legends setLabel(ax, r'$\Delta t_{merger} = t(z_{merger})-t(z_{current})$ [Gyr]', 'Cumulative counts', '', 'default', 'default', legend=False) ax.legend(loc='lower left', fontsize=14) ax.set_yscale("log") ax.set_xscale("log") return ax, fig, t_merger_agn, t_merger_gal def mergerRedshiftPlot(cen_sat_AGN, cen_sat_halo, dt_m, plot_params, redshift_limit): """ Function to plot the time since merger as a function of the redshift @cen_sat_AGN(gal) :: handels to access the central and satellite AGNs(galaxies) @dt_m :: time difference after merger for cen/sat AGNs(galaxies) @plot_params :: to keep consistency between plots, array containing [labels, c, m, ms] """ fig, ax = plt.subplots(1,1,figsize=(7,6)) # change marker size for central DM halos plot_params[3][1] = 9 z_R = [cen_sat_AGN[0]['redshift_R'], cen_sat_AGN[1]['redshift_R'], cen_sat_halo[0]['redshift_R'], cen_sat_halo[1]['redshift_R']] # plot central, satellite merger distributions as per visual preference for i in [2, 3, 0, 1]: ax.plot(dt_m[i], z_R[i], plot_params[2][i], color=plot_params[1][i], ms=plot_params[3][i], label=plot_params[0][i], markeredgecolor=plot_params[4][i], markeredgewidth=plot_params[5][i]) # set labels/legends setLabel(ax, r'$\Delta t_{merger} = t(z_{merger})-t(z_{current})$ [Gyr]', r'Redshift$_R$', '', 'default', 'default', legend=True) ax.set_xscale("log") plt.savefig('figures/t_since_merger_z_plot_%.2f.pdf'%redshift_limit, facecolor='w', edgecolor='w') return ax def plotMergerTimeCuts(ax, t_merger_cut_arr, l): """ Function to plot the defined cuts in merger times within the concerned plot @t_merger_cut_arr :: array that defines the cuts in the merger times @l :: array that defines the linestyles used to denote these cuts (refer to the initial codeblock in the notebook) """ for i, t_m_cut in enumerate(t_merger_cut_arr): ax.axvline(x=t_m_cut, color='r', linestyle= l[i], label='%.1f Gyr'%t_m_cut) ax.legend(fontsize=14, loc='lower left') return
41.996785
193
0.674298
2,050
13,061
4.105366
0.180488
0.018061
0.013308
0.01616
0.25903
0.204016
0.154468
0.144368
0.137001
0.097671
0
0.024287
0.189802
13,061
311
194
41.996785
0.771026
0.256259
0
0.130719
0
0.013072
0.128219
0.022677
0
0
0
0
0
1
0.065359
false
0
0.124183
0
0.254902
0.039216
0
0
0
null
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
null
0
0
0
0
0
0
0
0
0
0
0
0
1
0
d49130f40117c9ae1a6661a583616d08186beb75
2,239
py
Python
asv_bench/benchmarks/omnisci/io.py
Rubtsowa/modin
6550939753c76e896ef2bfd65bb9468d6ad161d7
[ "ECL-2.0", "Apache-2.0" ]
null
null
null
asv_bench/benchmarks/omnisci/io.py
Rubtsowa/modin
6550939753c76e896ef2bfd65bb9468d6ad161d7
[ "ECL-2.0", "Apache-2.0" ]
null
null
null
asv_bench/benchmarks/omnisci/io.py
Rubtsowa/modin
6550939753c76e896ef2bfd65bb9468d6ad161d7
[ "ECL-2.0", "Apache-2.0" ]
null
null
null
# Licensed to Modin Development Team under one or more contributor license agreements. # See the NOTICE file distributed with this work for additional information regarding # copyright ownership. The Modin Development Team licenses this file to you 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. """IO Modin on OmniSci storage format benchmarks.""" import modin.pandas as pd from ..utils import ( generate_dataframe, RAND_LOW, RAND_HIGH, ASV_USE_IMPL, IMPL, get_shape_id, trigger_import, get_benchmark_shapes, ) from ..io.csv import TimeReadCsvTrueFalseValues # noqa: F401 class TimeReadCsvNames: shapes = get_benchmark_shapes("omnisci.TimeReadCsvNames") param_names = ["shape"] params = [shapes] def setup_cache(self, test_filename="io_test_file_csv_names"): # filenames with a metadata of saved dataframes cache = {} for shape in self.shapes: df = generate_dataframe("pandas", "int", *shape, RAND_LOW, RAND_HIGH) file_id = get_shape_id(shape) cache[file_id] = ( f"{test_filename}_{file_id}.csv", df.columns.to_list(), df.dtypes.to_dict(), ) df.to_csv(cache[file_id][0], index=False) return cache def setup(self, cache, shape): # ray init if ASV_USE_IMPL == "modin": pd.DataFrame([]) file_id = get_shape_id(shape) self.filename, self.names, self.dtype = cache[file_id] def time_read_csv_names(self, cache, shape): df = IMPL[ASV_USE_IMPL].read_csv( self.filename, names=self.names, header=0, dtype=self.dtype, ) trigger_import(df)
33.924242
87
0.663243
298
2,239
4.828859
0.442953
0.041696
0.020848
0.022238
0.029187
0.029187
0
0
0
0
0
0.00538
0.252791
2,239
65
88
34.446154
0.854752
0.389013
0
0.04878
0
0
0.069733
0.055638
0
0
0
0
0
1
0.073171
false
0
0.121951
0
0.317073
0
0
0
0
null
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
null
0
0
0
0
0
0
0
0
0
0
0
0
1
0
d4913a27e63bc4d452b162e06717cf43b3cf28c7
7,730
py
Python
benchmarks/rotation/rotated_cifar.py
ypeng22/ProgLearn
671ff6a03c156bab3eedbd9e112705eeabd59da7
[ "MIT" ]
1
2021-02-02T03:18:46.000Z
2021-02-02T03:18:46.000Z
benchmarks/rotation/rotated_cifar.py
ypeng22/ProgLearn
671ff6a03c156bab3eedbd9e112705eeabd59da7
[ "MIT" ]
null
null
null
benchmarks/rotation/rotated_cifar.py
ypeng22/ProgLearn
671ff6a03c156bab3eedbd9e112705eeabd59da7
[ "MIT" ]
null
null
null
import matplotlib.pyplot as plt import random import pickle from skimage.transform import rotate from scipy import ndimage from skimage.util import img_as_ubyte from joblib import Parallel, delayed from sklearn.ensemble.forest import _generate_unsampled_indices from sklearn.ensemble.forest import _generate_sample_indices import numpy as np from sklearn.ensemble import BaggingClassifier from sklearn.tree import DecisionTreeClassifier from itertools import product import keras from keras import layers from joblib import Parallel, delayed from multiprocessing import Pool import tensorflow as tf from numba import cuda import sys sys.path.append("../../proglearn/") from progressive_learner import ProgressiveLearner from deciders import SimpleArgmaxAverage from transformers import TreeClassificationTransformer, NeuralClassificationTransformer from voters import TreeClassificationVoter, KNNClassificationVoter def cross_val_data(data_x, data_y, total_cls=10): x = data_x.copy() y = data_y.copy() idx = [np.where(data_y == u)[0] for u in np.unique(data_y)] for i in range(total_cls): indx = idx[i]#np.roll(idx[i],(cv-1)*100) random.shuffle(indx) if i==0: train_x1 = x[indx[0:250],:] train_x2 = x[indx[250:500],:] train_y1 = y[indx[0:250]] train_y2 = y[indx[250:500]] test_x = x[indx[500:600],:] test_y = y[indx[500:600]] else: train_x1 = np.concatenate((train_x1, x[indx[0:250],:]), axis=0) train_x2 = np.concatenate((train_x2, x[indx[250:500],:]), axis=0) train_y1 = np.concatenate((train_y1, y[indx[0:250]]), axis=0) train_y2 = np.concatenate((train_y2, y[indx[250:500]]), axis=0) test_x = np.concatenate((test_x, x[indx[500:600],:]), axis=0) test_y = np.concatenate((test_y, y[indx[500:600]]), axis=0) return train_x1, train_y1, train_x2, train_y2, test_x, test_y def LF_experiment(data_x, data_y, angle, model, granularity, reps=1, ntrees=29, acorn=None): if acorn is not None: np.random.seed(acorn) errors = np.zeros(2) for rep in range(reps): print("Starting Rep {} of Angle {}".format(rep, angle)) train_x1, train_y1, train_x2, train_y2, test_x, test_y = cross_val_data(data_x, data_y, total_cls=10) #change data angle for second task tmp_data = train_x2.copy() _tmp_ = np.zeros((32,32,3), dtype=int) total_data = tmp_data.shape[0] for i in range(total_data): tmp_ = image_aug(tmp_data[i],angle) tmp_data[i] = tmp_ if model == "uf": train_x1 = train_x1.reshape((train_x1.shape[0], train_x1.shape[1] * train_x1.shape[2] * train_x1.shape[3])) tmp_data = tmp_data.reshape((tmp_data.shape[0], tmp_data.shape[1] * tmp_data.shape[2] * tmp_data.shape[3])) test_x = test_x.reshape((test_x.shape[0], test_x.shape[1] * test_x.shape[2] * test_x.shape[3])) with tf.device('/gpu:'+str(int(angle // granularity) % 4)): default_transformer_class = NeuralClassificationTransformer network = keras.Sequential() network.add(layers.Conv2D(filters=16, kernel_size=(3, 3), activation='relu', input_shape=np.shape(train_x1)[1:])) network.add(layers.BatchNormalization()) network.add(layers.Conv2D(filters=32, kernel_size=(3, 3), strides = 2, padding = "same", activation='relu')) network.add(layers.BatchNormalization()) network.add(layers.Conv2D(filters=64, kernel_size=(3, 3), strides = 2, padding = "same", activation='relu')) network.add(layers.BatchNormalization()) network.add(layers.Conv2D(filters=128, kernel_size=(3, 3), strides = 2, padding = "same", activation='relu')) network.add(layers.BatchNormalization()) network.add(layers.Conv2D(filters=254, kernel_size=(3, 3), strides = 2, padding = "same", activation='relu')) network.add(layers.Flatten()) network.add(layers.BatchNormalization()) network.add(layers.Dense(2000, activation='relu')) network.add(layers.BatchNormalization()) network.add(layers.Dense(2000, activation='relu')) network.add(layers.BatchNormalization()) network.add(layers.Dense(units=10, activation = 'softmax')) default_transformer_kwargs = {"network" : network, "euclidean_layer_idx" : -2, "num_classes" : 10, "optimizer" : keras.optimizers.Adam(3e-4) } default_voter_class = KNNClassificationVoter default_voter_kwargs = {"k" : int(np.log2(len(train_x1)))} default_decider_class = SimpleArgmaxAverage progressive_learner = ProgressiveLearner(default_transformer_class = default_transformer_class, default_transformer_kwargs = default_transformer_kwargs, default_voter_class = default_voter_class, default_voter_kwargs = default_voter_kwargs, default_decider_class = default_decider_class) progressive_learner.add_task( X = train_x1, y = train_y1, transformer_voter_decider_split = [0.67, 0.33, 0], decider_kwargs = {"classes" : np.unique(train_y1)} ) progressive_learner.add_transformer( X = tmp_data, y = train_y2, transformer_data_proportion = 1, backward_task_ids = [0] ) llf_task1=progressive_learner.predict(test_x, task_id=0) llf_single_task=progressive_learner.predict(test_x, task_id=0, transformer_ids=[0]) errors[1] = errors[1]+(1 - np.mean(llf_task1 == test_y)) errors[0] = errors[0]+(1 - np.mean(llf_single_task == test_y)) errors = errors/reps print("Errors For Angle {}: {}".format(angle, errors)) with open('rotation_results/angle_'+str(angle)+'_'+model+'.pickle', 'wb') as f: pickle.dump(errors, f, protocol = 2) def image_aug(pic, angle, centroid_x=23, centroid_y=23, win=16, scale=1.45): im_sz = int(np.floor(pic.shape[0]*scale)) pic_ = np.uint8(np.zeros((im_sz,im_sz,3),dtype=int)) pic_[:,:,0] = ndimage.zoom(pic[:,:,0],scale) pic_[:,:,1] = ndimage.zoom(pic[:,:,1],scale) pic_[:,:,2] = ndimage.zoom(pic[:,:,2],scale) image_aug = rotate(pic_, angle, resize=False) #print(image_aug.shape) image_aug_ = image_aug[centroid_x-win:centroid_x+win,centroid_y-win:centroid_y+win,:] return img_as_ubyte(image_aug_) ### MAIN HYPERPARAMS ### model = "dnn" granularity = 2 reps = 4 ######################## (X_train, y_train), (X_test, y_test) = keras.datasets.cifar100.load_data() data_x = np.concatenate([X_train, X_test]) data_y = np.concatenate([y_train, y_test]) data_y = data_y[:, 0] def perform_angle(angle): LF_experiment(data_x, data_y, angle, model, granularity, reps=reps, ntrees=16, acorn=1) if model == "dnn": for angle_adder in range(30, 180, granularity * 4): angles = angle_adder + np.arange(0, granularity * 4, granularity) with Pool(4) as p: p.map(perform_angle, angles) elif model == "uf": angles = np.arange(30,180,2) Parallel(n_jobs=-1)(delayed(LF_experiment)(data_x, data_y, angle, model, granularity, reps=20, ntrees=16, acorn=1) for angle in angles)
40.684211
139
0.625356
1,018
7,730
4.540275
0.220039
0.034617
0.055387
0.051493
0.3373
0.295976
0.217222
0.217222
0.201212
0.187581
0
0.043404
0.245925
7,730
189
140
40.899471
0.749528
0.012678
0
0.077465
0
0
0.028823
0.003027
0
0
0
0
0
1
0.028169
false
0
0.169014
0
0.211268
0.014085
0
0
0
null
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
null
0
0
0
0
0
0
0
0
0
0
0
0
1
0
d4925b374376cf8c3d1b5d0d5ddbaf90cc28fafd
3,763
py
Python
sklearn_pandas/transformers/monitor.py
toddbenanzer/sklearn_pandas
36e24c55ef4829aa261963201c346869097d4931
[ "MIT" ]
null
null
null
sklearn_pandas/transformers/monitor.py
toddbenanzer/sklearn_pandas
36e24c55ef4829aa261963201c346869097d4931
[ "MIT" ]
null
null
null
sklearn_pandas/transformers/monitor.py
toddbenanzer/sklearn_pandas
36e24c55ef4829aa261963201c346869097d4931
[ "MIT" ]
null
null
null
import numpy as np import pandas as pd from sklearn.base import BaseEstimator, TransformerMixin, clone from sklearn_pandas.util import validate_dataframe class MonitorMixin(object): def print_message(self, message): if self.logfile: with open(self.logfile, "a") as fout: fout.write(message) else: print(message) class ValidateTypes(BaseEstimator, TransformerMixin, MonitorMixin): def __init__(self, logfile=None, to_screen=True): self.logfile = logfile self.to_screen = to_screen def fit(self, X, y=None, **fitparams): X = validate_dataframe(X) self.types = {} for col in X.columns: self.types[col] = X[col].dtype.name return self def transform(self, X, **transformparams): X = validate_dataframe(X) new_col_list = [] for col in X.columns: var_type = X[col].dtype.name if var_type != self.types[col]: self.print_message( 'Data Type Mismatch for column {col}: Expected {expected} Received {received}'.format( col=col, expected=self.types[col], received=var_type) ) return X class ValidateRange(BaseEstimator, TransformerMixin, MonitorMixin): def __init__(self, logfile=None, to_screen=True, max_nunique=20): self.logfile = logfile self.to_screen = to_screen self.max_nunique = max_nunique def fit(self, X, y=None, **fitparams): X = validate_dataframe(X) self.types = {} self.unique_vals = {} self.minmax = {} for col in X.columns: self.types[col] = X[col].dtype.name if self.types[col] in ('object', 'bool', 'category'): unique_values = X[col].unique() if len(unique_values) <= self.max_nunique: self.unique_vals[col] = unique_values else: self.unique_vals[col] = None elif self.types[col] in ('int64', 'float64', 'datetime64', 'timedelta'): self.minmax[col] = (X[col].min(), X[col].max()) return self def transform(self, X, **transformparams): X = validate_dataframe(X) new_col_list = [] for col in X.columns: var_type = X[col].dtype.name if self.types[col] in ('object', 'bool', 'category'): if self.unique_vals[col] is not None: not_in_list = ~X[col].isin(self.unique_vals[col]) if sum(not_in_list) > 0: new_values = str(X[col][not_in_list].unique().tolist()) self.print_message( 'New Categories specified for column {col}: Received {received}'.format( col=col, received=new_values) ) elif self.types[col] in ('int64', 'float64', 'datetime64', 'timedelta'): minX = X[col].min() maxX = X[col].max() if minX < self.minmax[col][0]: self.print_message( 'Low Value warning for column {col}: Lowest Training value {lowtrain}, Lowest Scoring value {lowscore}'.format( col=col, lowtrain=self.minmax[col][0], lowscore=minX) ) if maxX > self.minmax[col][1]: self.print_message( 'High Value warning for column {col}: Largest Training value {hightrain}, Largest Scoring value {highscore}'.format( col=col, hightrain=self.minmax[col][1], highscore=maxX) ) return X
38.010101
140
0.543981
426
3,763
4.680751
0.237089
0.022066
0.048144
0.038114
0.451354
0.399198
0.399198
0.399198
0.361083
0.311936
0
0.007714
0.345469
3,763
98
141
38.397959
0.801868
0
0
0.469136
0
0
0.118022
0
0
0
0
0
0
1
0.08642
false
0
0.049383
0
0.222222
0.074074
0
0
0
null
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
null
0
0
0
0
0
0
0
0
0
0
0
0
1
0
d4928bbc94c4225d834897ba151f5d1146c73aa7
10,842
py
Python
Packs/ProofpointThreatResponse/Integrations/ProofpointThreatResponse/ProofpointThreatResponse_test.py
cbrake1/content
5b031129f98935c492056675eeee0fefcacbd87b
[ "MIT" ]
1
2020-11-25T00:42:27.000Z
2020-11-25T00:42:27.000Z
Packs/ProofpointThreatResponse/Integrations/ProofpointThreatResponse/ProofpointThreatResponse_test.py
cbrake1/content
5b031129f98935c492056675eeee0fefcacbd87b
[ "MIT" ]
22
2022-03-23T10:39:16.000Z
2022-03-31T11:31:37.000Z
Packs/ProofpointThreatResponse/Integrations/ProofpointThreatResponse/ProofpointThreatResponse_test.py
cbrake1/content
5b031129f98935c492056675eeee0fefcacbd87b
[ "MIT" ]
null
null
null
import pytest from CommonServerPython import * from ProofpointThreatResponse import create_incident_field_context, get_emails_context, pass_sources_list_filter, \ pass_abuse_disposition_filter, filter_incidents, prepare_ingest_alert_request_body, \ get_incidents_batch_by_time_request, get_new_incidents, get_time_delta MOCK_INCIDENT = { "id": 1, "type": "Malware", "summary": "Unsolicited Bulk Email", "description": "EvilScheme test message", "score": 4200, "state": "Open", "created_at": "2018-05-26T21:07:17Z", "event_count": 3, "event_sources": [ "Proofpoint TAP" ], "users": [ "" ], "assignee": "Unassigned", "team": "Unassigned", "hosts": { "attacker": [ "" ], "forensics": [ "", ] }, "incident_field_values": [ { "name": "Attack Vector", "value": "Email" }, { "name": "Classification", "value": "Spam" }, { "name": "Severity", "value": "Critical" }, { "name": "Abuse Disposition", "value": "Unknown" } ], "events": [ { "id": 3, "category": "malware", "severity": "Info", "source": "Proofpoint TAP", "threatname": "", "state": "Linked", "description": "", "attackDirection": "inbound", "received": "2018-05-26T21:07:17Z", "malwareName": "", "emails": [ { "sender": { "email": "test" }, "recipient": { "email": "test" }, "subject": "test", "messageId": "test", "messageDeliveryTime": { "chronology": { "zone": { "id": "UTC" } }, "millis": 1544640072000, }, "abuseCopy": "false", "body": "test", 'bodyType': "test", 'headers': "test", 'urls': "test" } ], } ], "quarantine_results": [], "successful_quarantines": 0, "failed_quarantines": 0, "pending_quarantines": 0 } INCIDENT_FIELD_CONTEXT = { "Attack_Vector": "Email", "Classification": "Spam", "Severity": "Critical", "Abuse_Disposition": "Unknown" } INCIDENT_FIELD_INPUT = [ (MOCK_INCIDENT, INCIDENT_FIELD_CONTEXT) ] def get_fetch_data(): with open('./test_data/raw_response.json', 'r') as f: file = json.loads(f.read()) return file.get('result') FETCH_RESPONSE = get_fetch_data() @pytest.mark.parametrize('incident, answer', INCIDENT_FIELD_INPUT) def test_get_incident_field_context(incident, answer): incident_field_values = create_incident_field_context(incident) assert incident_field_values == answer EMAIL_RESULT = [ { 'sender': "test", 'recipient': "test", 'subject': "test", 'message_id': "test", 'message_delivery_time': 1544640072000, 'body': "test", 'body_type': "test", 'headers': "test", 'urls': "test" } ] EMAILS_CONTEXT_INPUT = [ (MOCK_INCIDENT['events'][0], EMAIL_RESULT) ] @pytest.mark.parametrize('event, answer', EMAILS_CONTEXT_INPUT) def test_get_emails_context(event, answer): emails_context = get_emails_context(event) assert emails_context == answer SOURCE_LIST_INPUT = [ (["Proofpoint TAP"], True), ([], True), (["No such source"], False), (["No such source", "Proofpoint TAP"], True) ] @pytest.mark.parametrize('sources_list, expected_answer', SOURCE_LIST_INPUT) def test_pass_sources_list_filter(sources_list, expected_answer): result = pass_sources_list_filter(MOCK_INCIDENT, sources_list) assert result == expected_answer ABUSE_DISPOSITION_INPUT = [ (["Unknown"], True), ([], True), (["No such value"], False), (["No such value", "Unknown"], True) ] @pytest.mark.parametrize('abuse_dispotion_values, expected_answer', ABUSE_DISPOSITION_INPUT) def test_pass_abuse_disposition_filter(abuse_dispotion_values, expected_answer): result = pass_abuse_disposition_filter(MOCK_INCIDENT, abuse_dispotion_values) assert result == expected_answer DEMISTO_PARAMS = [({'event_sources': "No such source, Proofpoint TAP", 'abuse_disposition': "No such value, Unknown"}, [MOCK_INCIDENT]), ({'event_sources': "", 'abuse_disposition': ""}, [MOCK_INCIDENT]), ({'event_sources': "No such source", 'abuse_disposition': "No such value, Unknown"}, []), ({'event_sources': "No such source, Proofpoint TAP", 'abuse_disposition': "No such value"}, []), ({'event_sources': "No such source", 'abuse_disposition': "No such value"}, [])] @pytest.mark.parametrize('demisto_params, expected_answer', DEMISTO_PARAMS) def test_filter_incidents(mocker, demisto_params, expected_answer): mocker.patch.object(demisto, 'params', return_value=demisto_params) filtered_incidents = filter_incidents([MOCK_INCIDENT]) assert filtered_incidents == expected_answer INGEST_ALERT_ARGS = { "attacker": "{\"attacker\":{\"key\":\"value\"}}", "cnc_host": "{\"cnc_host\":{\"key\":\"value\"}}", "detector": "{\"detector\":{\"key\":\"value\"}}", "email": "{\"email\":{\"key\":\"value\"}}", "forensics_hosts": "{\"forensics_hosts\":{\"key\":\"value\"}}", "target": "{\"target\":{\"key\":\"value\"}}", "threat_info": "{\"threat_info\":{\"key\":\"value\"}}", "custom_fields": "{\"custom_fields\":{\"key\":\"value\"}}", "post_url_id": "value", "json_version": "value", "summary": "value" } EXPECTED_RESULT = { "attacker": {"key": "value"}, "cnc_host": {"key": "value"}, "detector": {"key": "value"}, "email": {"key": "value"}, "forensics_hosts": {"key": "value"}, "target": {"key": "value"}, "threat_info": {"key": "value"}, "custom_fields": {"key": "value"}, "post_url_id": "value", "json_version": "value", "summary": "value" } def test_prepare_ingest_alert_request_body(): prepared_body = prepare_ingest_alert_request_body(INGEST_ALERT_ARGS) assert prepared_body == EXPECTED_RESULT def test_fetch_incidents_limit_exceed(mocker): """ Given - a dict of params given to the function which is gathered originally from demisto.params() The dict includes the relevant params for the fetch e.g. fetch_delta, fetch_limit, created_after, state. - response of the api When - a single iteration of the fetch is activated with a fetch limit set to 5 Then - validate that the number or incidents that is returned is equal to the limit when the api returned more. """ params = { 'fetch_delta': '6 hours', 'fetch_limit': ' 5', 'created_after': '2021-03-30T11:44:24Z', 'state': 'closed' } mocker.patch('ProofpointThreatResponse.get_incidents_request', return_value=FETCH_RESPONSE) incidents_list = get_incidents_batch_by_time_request(params) assert len(incidents_list) == 5 def test_fetch_incidents_with_same_created_time(mocker): """ Given - a dict of params given to the function which is gathered originally from demisto.params() The dict includes the relevant params for the fetch e.g. fetch_delta, fetch_limit, created_after, state and last_fetched_id. - response of the api When - when a fetch occurs and the last fetched incident has exactly the same time of the next incident. Then - validate that only one of the incidents appear as to the fetch limit. - validate that the next incident whose time is exactly the same is brought in the next fetch loop. ( e.g. 3057 and 3058) """ expected_ids_to_fetch_first = [3055, 3056, 3057] expected_ids_to_fetch_second = [3058, 3059, 3060] params = { 'fetch_delta': '2 hours', 'fetch_limit': '3', 'created_after': '2021-03-30T10:44:24Z', 'state': 'closed' } mocker.patch('ProofpointThreatResponse.get_incidents_request', return_value=FETCH_RESPONSE) new_fetched_first = get_incidents_batch_by_time_request(params) for incident in new_fetched_first: assert incident.get('id') in expected_ids_to_fetch_first params = { 'fetch_delta': '2 hour', 'fetch_limit': '3', 'created_after': '2021-03-30T11:21:24Z', 'last_fetched_id': '3057', 'state': 'closed' } new_fetched_second = get_incidents_batch_by_time_request(params) for incident in new_fetched_second: assert incident.get('id') in expected_ids_to_fetch_second def test_get_new_incidents(mocker): """ Given - a dict of request_params to the api. - The last fetched incident id. When - Get new incidents is called during the fetch process. Then - validate that the number of expected incidents return. - validate that all of the returned incident have a bigger id then the last fetched incident. """ last_incident_fetched = 3057 request_params = { 'state': 'closed', 'created_after': '2021-03-30T10:21:24Z', 'created_before': '2021-03-31T11:21:24Z', } mocker.patch('ProofpointThreatResponse.get_incidents_request', return_value=FETCH_RESPONSE) new_incidnets = get_new_incidents(request_params, last_incident_fetched) assert len(new_incidnets) == 14 for incident in new_incidnets: assert incident.get('id') > 3057 def test_get_time_delta(): """ Given - input to the get_time_delta function which is valid and invalid When - run the get_time_delta function. Then - validate that on invalid input such as days or no units relevant errors are raised. - validate that on valid inputs the return value is as expected. """ time_delta = get_time_delta('1 minute') assert str(time_delta) == '0:01:00' time_delta = get_time_delta('2 hours') assert str(time_delta) == '2:00:00' try: get_time_delta('2') except Exception as ex: assert 'The fetch_delta is invalid. Please make sure to insert both the number and the unit of the fetch delta.' in str( ex) try: get_time_delta('2 days') except Exception as ex: assert 'The unit of fetch_delta is invalid. Possible values are "minutes" or "hours' in str(ex)
32.558559
128
0.603394
1,206
10,842
5.1733
0.21393
0.020516
0.015387
0.012181
0.363039
0.223754
0.200032
0.184966
0.184966
0.172464
0
0.025471
0.264896
10,842
332
129
32.656627
0.75734
0.141764
0
0.157258
0
0.004032
0.280762
0.027955
0
0
0
0
0.060484
1
0.044355
false
0.024194
0.012097
0
0.060484
0
0
0
0
null
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
null
0
0
0
0
0
0
0
0
0
0
0
0
1
0
d492fd9d00437e877a4501964cd431bb0546c438
3,522
py
Python
macholib/macho_methname.py
l1haoyuan/macholib
48c59841e2ca5aa308eab67f72faed384a2c0723
[ "MIT" ]
null
null
null
macholib/macho_methname.py
l1haoyuan/macholib
48c59841e2ca5aa308eab67f72faed384a2c0723
[ "MIT" ]
null
null
null
macholib/macho_methname.py
l1haoyuan/macholib
48c59841e2ca5aa308eab67f72faed384a2c0723
[ "MIT" ]
null
null
null
import sys import os import json from enum import Enum from .mach_o import LC_SYMTAB from macholib import MachO from macholib import mach_o from shutil import copy2 from shutil import SameFileError class ReplaceType(Enum): objc_methname = 1 symbol_table = 2 def replace_in_bytes(method_bytes, name_dict, type): is_prefix = False empty_byte = b'\x00' if not method_bytes.startswith(empty_byte): is_prefix = True method_bytes = empty_byte + method_bytes for key, value in name_dict.items(): if len(key) != len(value): raise("replace method name with different length may break the mach-o file, ori: " + key + ", dst: " + value) if type == ReplaceType.objc_methname: method_bytes = method_bytes.replace( empty_byte + key.encode('utf-8') + empty_byte, empty_byte + value.encode('utf-8') + empty_byte) elif type == ReplaceType.symbol_table: method_bytes = method_bytes.replace( b' ' + key.encode('utf-8') + b']', b' ' + value.encode('utf-8') + b']') if is_prefix: method_bytes = method_bytes.replace(empty_byte, b'', 1) return method_bytes def ch_methname_sect(header, name_dict): commands = header.commands lc = None sect = None for _, command_tuple in enumerate(commands): seg = command_tuple[1] data = command_tuple[2] if hasattr(seg, 'segname') and seg.segname.rstrip(b'\x00') == b'__TEXT': for tmp_sect in data: if tmp_sect.sectname.rstrip(b'\x00') == b'__objc_methname': lc = command_tuple[0] sect = tmp_sect if sect is None: raise("Can't find __objc_methname section") sect.section_data = replace_in_bytes( sect.section_data, name_dict, ReplaceType.objc_methname) header.mod_dict[lc] = [sect] def ch_symtab(header, name_dict): commands = header.commands for idx, command_tuple in enumerate(commands): lc = command_tuple[0] cmd = command_tuple[1] data = command_tuple[2] if lc.cmd == LC_SYMTAB: data = replace_in_bytes(data, name_dict, ReplaceType.symbol_table) header.mod_dict[lc] = [data] commands[idx] = (lc, cmd, data) return raise("Can't find LC_SYMTAB") def replace_methname(macho_file, methname_json, output_dir): """ Map method names in Mach-O file with the JSON file """ if not os.path.isfile(macho_file): raise("passing not exist file " + macho_file) if not os.path.isfile(methname_json): raise("passing not exist file " + methname_json) if output_dir is not None and not os.path.isdir(output_dir): raise("passing not exist dir " + output_dir) macho = MachO.MachO(macho_file) name_dict = None with open(methname_json) as json_file: name_dict = json.load(json_file) for header in macho.headers: ch_methname_sect(header, name_dict) ch_symtab(header, name_dict) ori_dir, filename = os.path.split(macho_file) if output_dir is None: output_dir = ori_dir output = os.path.join(output_dir, filename) try: copy2(macho_file, output_dir) except SameFileError: pass with open(output, 'r+b') as fp: macho.write(fp) os.chmod(output, 0o755) def main(): replace_methname(sys.argv[0], sys.argv[1], sys.argv[2]) if __name__ == '__main__': main()
30.102564
111
0.635434
487
3,522
4.367556
0.232033
0.056888
0.030089
0.03103
0.236483
0.139163
0.06582
0.030089
0
0
0
0.010798
0.263771
3,522
116
112
30.362069
0.809487
0.014196
0
0.089888
0
0
0.08044
0
0
0
0
0
0
1
0.05618
false
0.044944
0.101124
0
0.213483
0
0
0
0
null
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
null
0
0
0
0
0
0
0
0
0
0
0
0
1
0
d493cf85a9cb37a46e9d38eab9f5e238cbe228b0
1,515
py
Python
forms/snippets/delete_watch.py
soheilv/python-samples
4443431261dbcd88408dcc89d5702eeb1ac18ffd
[ "Apache-2.0" ]
255
2020-10-16T16:27:54.000Z
2022-03-31T14:26:29.000Z
forms/snippets/delete_watch.py
soheilv/python-samples
4443431261dbcd88408dcc89d5702eeb1ac18ffd
[ "Apache-2.0" ]
58
2020-10-16T14:24:27.000Z
2022-03-19T13:27:27.000Z
forms/snippets/delete_watch.py
soheilv/python-samples
4443431261dbcd88408dcc89d5702eeb1ac18ffd
[ "Apache-2.0" ]
316
2020-10-16T17:06:00.000Z
2022-03-30T19:18:31.000Z
# Copyright 2021 Google LLC # # 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. # [START forms_delete_watch] from __future__ import print_function from apiclient import discovery from httplib2 import Http from oauth2client import client, file, tools SCOPES = "https://www.googleapis.com/auth/drive" API_KEY = "<YOUR_API_KEY>" DISCOVERY_DOC = f"https://forms.googleapis.com/$discovery/rest?version=v1beta&key={API_KEY}&labels=FORMS_BETA_TESTERS" store = file.Storage('credentials.json') creds = None if not creds or creds.invalid: flow = client.flow_from_clientsecrets('client_secret.json', SCOPES) creds = tools.run_flow(flow, store) service = discovery.build('forms', 'v1beta', http=creds.authorize( Http()), discoveryServiceUrl=DISCOVERY_DOC, static_discovery=False) form_id = '<YOUR_FORM_ID>' watch_id = '<YOUR_WATCH_ID>' # Print JSON response after deleting a form watch result = service.forms().watches().delete(formId=form_id, watchId=watch_id).execute() print(result) # [END forms_delete_watch]
36.95122
118
0.770297
222
1,515
5.121622
0.554054
0.05277
0.022867
0.028144
0
0
0
0
0
0
0
0.009105
0.130033
1,515
40
119
37.875
0.853566
0.427723
0
0
0
0.055556
0.263529
0
0
0
0
0
0
1
0
false
0
0.222222
0
0.222222
0.111111
0
0
0
null
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
null
0
0
0
0
0
0
0
0
0
0
0
0
1
0
d49496c9213106a0918889d0e3a6aa3992ff1641
1,829
py
Python
data_structures/disjoint_set/disjoint_set.py
egagraha/python-algorithm
07a6a745b4ebddc93ab7c10b205c75b2427ac1fb
[ "MIT" ]
null
null
null
data_structures/disjoint_set/disjoint_set.py
egagraha/python-algorithm
07a6a745b4ebddc93ab7c10b205c75b2427ac1fb
[ "MIT" ]
null
null
null
data_structures/disjoint_set/disjoint_set.py
egagraha/python-algorithm
07a6a745b4ebddc93ab7c10b205c75b2427ac1fb
[ "MIT" ]
null
null
null
""" Disjoint set. Reference: https://en.wikipedia.org/wiki/Disjoint-set_data_structure """ class Node: def __init__(self, data: int) -> None: self.data = data self.rank: int self.parent: Node def make_set(x: Node) -> None: """ Make x as a set. """ # rank is the distance from x to its' parent # root's rank is 0 x.rank = 0 x.parent = x def union_set(x: Node, y: Node) -> None: """ Union of two sets. set with bigger rank should be parent, so that the disjoint set tree will be more flat. """ x, y = find_set(x), find_set(y) if x == y: return elif x.rank > y.rank: y.parent = x else: x.parent = y if x.rank == y.rank: y.rank += 1 def find_set(x: Node) -> Node: """ Return the parent of x """ if x != x.parent: x.parent = find_set(x.parent) return x.parent def find_python_set(node: Node) -> set: """ Return a Python Standard Library set that contains i. """ sets = ({0, 1, 2}, {3, 4, 5}) for s in sets: if node.data in s: return s raise ValueError(f"{node.data} is not in {sets}") def test_disjoint_set() -> None: """ >>> test_disjoint_set() """ vertex = [Node(i) for i in range(6)] for v in vertex: make_set(v) union_set(vertex[0], vertex[1]) union_set(vertex[1], vertex[2]) union_set(vertex[3], vertex[4]) union_set(vertex[3], vertex[5]) for node0 in vertex: for node1 in vertex: if find_python_set(node0).isdisjoint(find_python_set(node1)): assert find_set(node0) != find_set(node1) else: assert find_set(node0) == find_set(node1) if __name__ == "__main__": test_disjoint_set()
21.517647
73
0.556042
274
1,829
3.562044
0.288321
0.057377
0.057377
0.020492
0.127049
0.061475
0.061475
0
0
0
0
0.020717
0.313833
1,829
84
74
21.77381
0.756972
0.201203
0
0.045455
0
0
0.026451
0
0
0
0
0
0.045455
1
0.136364
false
0
0
0
0.227273
0
0
0
0
null
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
null
0
0
0
0
0
0
0
0
0
0
0
0
1
0
d494b4ecc12674b178766fec7fe530877b75b17d
1,391
py
Python
cw_EPR.py
tkeller12/spin_physics
271f3081bc8ca87b159ed3e3494dbd0ffdea8fa5
[ "MIT" ]
null
null
null
cw_EPR.py
tkeller12/spin_physics
271f3081bc8ca87b159ed3e3494dbd0ffdea8fa5
[ "MIT" ]
null
null
null
cw_EPR.py
tkeller12/spin_physics
271f3081bc8ca87b159ed3e3494dbd0ffdea8fa5
[ "MIT" ]
null
null
null
# Timothy Keller # S = 1/2, I = 1/2 # Spin 1/2 electron coupled to spin 1/2 nuclei import numpy as np from scipy.linalg import expm from matplotlib.pylab import * from matplotlib import cm sigma_x = 0.5*np.r_[[[0, 1],[1, 0]]] sigma_y = 0.5*np.r_[[[0,-1j],[1j, 0]]] sigma_z = 0.5*np.r_[[[1, 0],[0, -1]]] Identity = np.eye(2) Sx = np.kron(sigma_x, Identity) Sy = np.kron(sigma_y, Identity) Sz = np.kron(sigma_z, Identity) Ix = np.kron(Identity, sigma_x) Iy = np.kron(Identity, sigma_y) Iz = np.kron(Identity, sigma_z) SxIx = np.kron(sigma_x,sigma_z) SxIx2 = np.dot(Sx,Iz) print(SxIx) print(SxIx2) print(np.allclose(SxIx,SxIx2)) omega_S = 1.76e11 # rad / (s * T) omega_I = 267.522e6 # rad / (s * T) Aiso = 2*np.pi * 50.e6 # Isotropic Hyperfine coupling rad / s B0 = 0.35# T H = omega_S/(2.*np.pi)*B0*Sz + omega_I/(2.*np.pi)*B0*Iz + Aiso * np.dot(Sz,Iz) #H = omega_S/(2.*np.pi)*B0*Sz + omega_I/(2.*np.pi)*B0*Iz + Aiso * (np.dot(Sx,Ix) + np.dot(Sy,Iy) + np.dot(Sz,Iz)) print('Hamiltonian:') print(H) out = np.linalg.eig(H) E = out[0] print(E) E12 = E[0] - E[1] E34 = E[2] - E[3] E13 = E[0] - E[2] E24 = E[1] - E[3] print(E12) print(E34) print(E13) print(E24) print('Nuclear') print('%0.05f MHz'%(E12 / 1e6)) print('%0.05f MHz'%(E34 / 1e6)) print('Electron') print('%0.05f GHz'%(E13 / 1e9)) print('%0.05f GHz'%(E24 / 1e9)) matshow(abs(H), cmap = cm.jet) title('Hamiltonian') show()
21.075758
113
0.62473
282
1,391
3.010638
0.287234
0.04947
0.029446
0.03298
0.108363
0.094229
0.094229
0.094229
0.094229
0.094229
0
0.094228
0.153127
1,391
65
114
21.4
0.626486
0.183321
0
0
0
0
0.06921
0
0
0
0
0
0
1
0
false
0
0.086957
0
0.086957
0.347826
0
0
0
null
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
null
0
0
0
0
0
0
0
0
0
0
0
0
1
0
d494b73023a37a848160341332c0ded7a2a24518
1,787
py
Python
V2RaycSpider0825/MiddleKey/VMes_IO.py
TOMJERRY23333/V2RayCloudSpider
0647db8c7b67e4393d1f65dadc08d7e16c1dc324
[ "MIT" ]
1
2020-09-16T12:59:32.000Z
2020-09-16T12:59:32.000Z
V2RaycSpider0825/MiddleKey/VMes_IO.py
TOMJERRY23333/V2RayCloudSpider
0647db8c7b67e4393d1f65dadc08d7e16c1dc324
[ "MIT" ]
null
null
null
V2RaycSpider0825/MiddleKey/VMes_IO.py
TOMJERRY23333/V2RayCloudSpider
0647db8c7b67e4393d1f65dadc08d7e16c1dc324
[ "MIT" ]
null
null
null
from spiderNest.preIntro import * path_ = os.path.dirname(os.path.dirname(__file__)) + '/dataBase/log_information.csv' def save_login_info(VMess, class_): """ VMess入库 class_: ssr or v2ray """ now = str(datetime.now()).split('.')[0] with open(path_, 'a', encoding='utf-8', newline='') as f: writer = csv.writer(f) # 入库时间,Vmess,初始化状态:0 writer.writerow(['{}'.format(now), '{}'.format(VMess), class_, '0']) def vmess_IO(class_): """ 获取可用订阅链接并刷新存储池 class_: ssr ; v2ray """ def refresh_log(dataFlow): with open(path_, 'w', encoding='utf-8', newline='') as f: writer = csv.writer(f) writer.writerows(dataFlow) try: with open(path_, 'r', encoding='utf-8') as f: reader = csv.reader(f) vm_q = [vm for vm in reader] new_q = vm_q for i, value in enumerate(reversed(vm_q)): if value[-1] == '0' and value[-2] == class_: vm = value[1] new_q[-(i + 1)][-1] = '1' break refresh_log(new_q) return vm except UnboundLocalError: return '无可用订阅连接' def avi_num(): from datetime import datetime, timedelta with open(path_, 'r', encoding='utf-8') as f: reader = csv.reader(f) vm_list = [i for i in reader] # ['2020-08-06 04:27:59', 'link','class_', '1'] vm_q = [vm for vm in vm_list if vm[-1] == '0'] tag_items = '' for vm in vm_list: if vm[-1] == '0': bei_ing_time = datetime.fromisoformat(vm[0]) + timedelta(hours=12) tag_items += '\n【√可选】【{}】#{}'.format(bei_ing_time, vm[-2]) # return vm_q.__len__() return tag_items
28.365079
84
0.525462
237
1,787
3.776371
0.383966
0.01676
0.053631
0.042458
0.246927
0.246927
0.230168
0.230168
0.230168
0.18771
0
0.031941
0.316732
1,787
62
85
28.822581
0.700246
0.084499
0
0.157895
0
0
0.052665
0.018182
0
0
0
0
0
1
0.105263
false
0
0.052632
0
0.236842
0
0
0
0
null
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
null
0
0
0
0
0
0
0
0
0
0
0
0
1
0
d494cc4fdc66704176b1bdb14e2b8bf08f6d120c
29,585
py
Python
paddlespeech/s2t/frontend/audio.py
AK391/PaddleSpeech
8cdbe3a6c0fe447e54cfbcfd82139d2869f5fc49
[ "Apache-2.0" ]
null
null
null
paddlespeech/s2t/frontend/audio.py
AK391/PaddleSpeech
8cdbe3a6c0fe447e54cfbcfd82139d2869f5fc49
[ "Apache-2.0" ]
null
null
null
paddlespeech/s2t/frontend/audio.py
AK391/PaddleSpeech
8cdbe3a6c0fe447e54cfbcfd82139d2869f5fc49
[ "Apache-2.0" ]
null
null
null
# Copyright (c) 2021 PaddlePaddle Authors. All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. """Contains the audio segment class.""" import copy import io import random import re import struct import numpy as np import resampy import soundfile from scipy import signal from .utility import convert_samples_from_float32 from .utility import convert_samples_to_float32 from .utility import subfile_from_tar class AudioSegment(): """Monaural audio segment abstraction. :param samples: Audio samples [num_samples x num_channels]. :type samples: ndarray.float32 :param sample_rate: Audio sample rate. :type sample_rate: int :raises TypeError: If the sample data type is not float or int. """ def __init__(self, samples, sample_rate): """Create audio segment from samples. Samples are convert float32 internally, with int scaled to [-1, 1]. """ self._samples = self._convert_samples_to_float32(samples) self._sample_rate = sample_rate if self._samples.ndim >= 2: self._samples = np.mean(self._samples, 1) def __eq__(self, other): """Return whether two objects are equal.""" if type(other) is not type(self): return False if self._sample_rate != other._sample_rate: return False if self._samples.shape != other._samples.shape: return False if np.any(self.samples != other._samples): return False return True def __ne__(self, other): """Return whether two objects are unequal.""" return not self.__eq__(other) def __str__(self): """Return human-readable representation of segment.""" return ("%s: num_samples=%d, sample_rate=%d, duration=%.2fsec, " "rms=%.2fdB" % (type(self), self.num_samples, self.sample_rate, self.duration, self.rms_db)) @classmethod def from_file(cls, file, infos=None): """Create audio segment from audio file. Args: filepath (str|file): Filepath or file object to audio file. infos (TarLocalData, optional): tar2obj and tar2infos. Defaults to None. Returns: AudioSegment: Audio segment instance. """ if isinstance(file, str) and re.findall(r".seqbin_\d+$", file): return cls.from_sequence_file(file) elif isinstance(file, str) and file.startswith('tar:'): return cls.from_file(subfile_from_tar(file, infos)) else: samples, sample_rate = soundfile.read(file, dtype='float32') return cls(samples, sample_rate) @classmethod def slice_from_file(cls, file, start=None, end=None): """Loads a small section of an audio without having to load the entire file into the memory which can be incredibly wasteful. :param file: Input audio filepath or file object. :type file: str|file :param start: Start time in seconds. If start is negative, it wraps around from the end. If not provided, this function reads from the very beginning. :type start: float :param end: End time in seconds. If end is negative, it wraps around from the end. If not provided, the default behvaior is to read to the end of the file. :type end: float :return: AudioSegment instance of the specified slice of the input audio file. :rtype: AudioSegment :raise ValueError: If start or end is incorrectly set, e.g. out of bounds in time. """ sndfile = soundfile.SoundFile(file) sample_rate = sndfile.samplerate duration = float(len(sndfile)) / sample_rate start = 0. if start is None else start end = duration if end is None else end if start < 0.0: start += duration if end < 0.0: end += duration if start < 0.0: raise ValueError("The slice start position (%f s) is out of " "bounds." % start) if end < 0.0: raise ValueError("The slice end position (%f s) is out of bounds." % end) if start > end: raise ValueError("The slice start position (%f s) is later than " "the slice end position (%f s)." % (start, end)) if end > duration: raise ValueError("The slice end position (%f s) is out of bounds " "(> %f s)" % (end, duration)) start_frame = int(start * sample_rate) end_frame = int(end * sample_rate) sndfile.seek(start_frame) data = sndfile.read(frames=end_frame - start_frame, dtype='float32') return cls(data, sample_rate) @classmethod def from_sequence_file(cls, filepath): """Create audio segment from sequence file. Sequence file is a binary file containing a collection of multiple audio files, with several header bytes in the head indicating the offsets of each audio byte data chunk. The format is: 4 bytes (int, version), 4 bytes (int, num of utterance), 4 bytes (int, bytes per header), [bytes_per_header*(num_utterance+1)] bytes (offsets for each audio), audio_bytes_data_of_1st_utterance, audio_bytes_data_of_2nd_utterance, ...... Sequence file name must end with ".seqbin". And the filename of the 5th utterance's audio file in sequence file "xxx.seqbin" must be "xxx.seqbin_5", with "5" indicating the utterance index within this sequence file (starting from 1). :param filepath: Filepath of sequence file. :type filepath: str :return: Audio segment instance. :rtype: AudioSegment """ # parse filepath matches = re.match(r"(.+\.seqbin)_(\d+)", filepath) if matches is None: raise IOError("File type of %s is not supported" % filepath) filename = matches.group(1) fileno = int(matches.group(2)) # read headers f = io.open(filename, mode='rb', encoding='utf8') version = f.read(4) num_utterances = struct.unpack("i", f.read(4))[0] bytes_per_header = struct.unpack("i", f.read(4))[0] header_bytes = f.read(bytes_per_header * (num_utterances + 1)) header = [ struct.unpack("i", header_bytes[bytes_per_header * i: bytes_per_header * (i + 1)])[0] for i in range(num_utterances + 1) ] # read audio bytes f.seek(header[fileno - 1]) audio_bytes = f.read(header[fileno] - header[fileno - 1]) f.close() # create audio segment try: return cls.from_bytes(audio_bytes) except Exception as e: samples = np.frombuffer(audio_bytes, dtype='int16') return cls(samples=samples, sample_rate=8000) @classmethod def from_bytes(cls, bytes): """Create audio segment from a byte string containing audio samples. :param bytes: Byte string containing audio samples. :type bytes: str :return: Audio segment instance. :rtype: AudioSegment """ samples, sample_rate = soundfile.read( io.BytesIO(bytes), dtype='float32') return cls(samples, sample_rate) @classmethod def concatenate(cls, *segments): """Concatenate an arbitrary number of audio segments together. :param *segments: Input audio segments to be concatenated. :type *segments: tuple of AudioSegment :return: Audio segment instance as concatenating results. :rtype: AudioSegment :raises ValueError: If the number of segments is zero, or if the sample_rate of any segments does not match. :raises TypeError: If any segment is not AudioSegment instance. """ # Perform basic sanity-checks. if len(segments) == 0: raise ValueError("No audio segments are given to concatenate.") sample_rate = segments[0]._sample_rate for seg in segments: if sample_rate != seg._sample_rate: raise ValueError("Can't concatenate segments with " "different sample rates") if type(seg) is not cls: raise TypeError("Only audio segments of the same type " "can be concatenated.") samples = np.concatenate([seg.samples for seg in segments]) return cls(samples, sample_rate) @classmethod def make_silence(cls, duration, sample_rate): """Creates a silent audio segment of the given duration and sample rate. :param duration: Length of silence in seconds. :type duration: float :param sample_rate: Sample rate. :type sample_rate: float :return: Silent AudioSegment instance of the given duration. :rtype: AudioSegment """ samples = np.zeros(int(duration * sample_rate)) return cls(samples, sample_rate) def to_wav_file(self, filepath, dtype='float32'): """Save audio segment to disk as wav file. :param filepath: WAV filepath or file object to save the audio segment. :type filepath: str|file :param dtype: Subtype for audio file. Options: 'int16', 'int32', 'float32', 'float64'. Default is 'float32'. :type dtype: str :raises TypeError: If dtype is not supported. """ samples = self._convert_samples_from_float32(self._samples, dtype) subtype_map = { 'int16': 'PCM_16', 'int32': 'PCM_32', 'float32': 'FLOAT', 'float64': 'DOUBLE' } soundfile.write( filepath, samples, self._sample_rate, format='WAV', subtype=subtype_map[dtype]) def superimpose(self, other): """Add samples from another segment to those of this segment (sample-wise addition, not segment concatenation). Note that this is an in-place transformation. :param other: Segment containing samples to be added in. :type other: AudioSegments :raise TypeError: If type of two segments don't match. :raise ValueError: If the sample rates of the two segments are not equal, or if the lengths of segments don't match. """ if isinstance(other, type(self)): raise TypeError("Cannot add segments of different types: %s " "and %s." % (type(self), type(other))) if self._sample_rate != other._sample_rate: raise ValueError("Sample rates must match to add segments.") if len(self._samples) != len(other._samples): raise ValueError("Segment lengths must match to add segments.") self._samples += other._samples def to_bytes(self, dtype='float32'): """Create a byte string containing the audio content. :param dtype: Data type for export samples. Options: 'int16', 'int32', 'float32', 'float64'. Default is 'float32'. :type dtype: str :return: Byte string containing audio content. :rtype: str """ samples = self._convert_samples_from_float32(self._samples, dtype) return samples.tostring() def to(self, dtype='int16'): """Create a `dtype` audio content. :param dtype: Data type for export samples. Options: 'int16', 'int32', 'float32', 'float64'. Default is 'float32'. :type dtype: str :return: np.ndarray containing `dtype` audio content. :rtype: str """ samples = self._convert_samples_from_float32(self._samples, dtype) return samples def gain_db(self, gain): """Apply gain in decibels to samples. Note that this is an in-place transformation. :param gain: Gain in decibels to apply to samples. :type gain: float|1darray """ self._samples *= 10.**(gain / 20.) def change_speed(self, speed_rate): """Change the audio speed by linear interpolation. Note that this is an in-place transformation. :param speed_rate: Rate of speed change: speed_rate > 1.0, speed up the audio; speed_rate = 1.0, unchanged; speed_rate < 1.0, slow down the audio; speed_rate <= 0.0, not allowed, raise ValueError. :type speed_rate: float :raises ValueError: If speed_rate <= 0.0. """ if speed_rate == 1.0: return if speed_rate <= 0: raise ValueError("speed_rate should be greater than zero.") # numpy # old_length = self._samples.shape[0] # new_length = int(old_length / speed_rate) # old_indices = np.arange(old_length) # new_indices = np.linspace(start=0, stop=old_length, num=new_length) # self._samples = np.interp(new_indices, old_indices, self._samples) # sox, slow try: import soxbindings as sox except: try: from paddlespeech.s2t.utils import dynamic_pip_install package = "sox" dynamic_pip_install.install(package) package = "soxbindings" dynamic_pip_install.install(package) import soxbindings as sox except: raise RuntimeError("Can not install soxbindings on your system." ) tfm = sox.Transformer() tfm.set_globals(multithread=False) tfm.speed(speed_rate) self._samples = tfm.build_array( input_array=self._samples, sample_rate_in=self._sample_rate).squeeze(-1).astype( np.float32).copy() def normalize(self, target_db=-20, max_gain_db=300.0): """Normalize audio to be of the desired RMS value in decibels. Note that this is an in-place transformation. :param target_db: Target RMS value in decibels. This value should be less than 0.0 as 0.0 is full-scale audio. :type target_db: float :param max_gain_db: Max amount of gain in dB that can be applied for normalization. This is to prevent nans when attempting to normalize a signal consisting of all zeros. :type max_gain_db: float :raises ValueError: If the required gain to normalize the segment to the target_db value exceeds max_gain_db. """ gain = target_db - self.rms_db if gain > max_gain_db: raise ValueError( "Unable to normalize segment to %f dB because the " "the probable gain have exceeds max_gain_db (%f dB)" % (target_db, max_gain_db)) self.gain_db(min(max_gain_db, target_db - self.rms_db)) def normalize_online_bayesian(self, target_db, prior_db, prior_samples, startup_delay=0.0): """Normalize audio using a production-compatible online/causal algorithm. This uses an exponential likelihood and gamma prior to make online estimates of the RMS even when there are very few samples. Note that this is an in-place transformation. :param target_db: Target RMS value in decibels. :type target_bd: float :param prior_db: Prior RMS estimate in decibels. :type prior_db: float :param prior_samples: Prior strength in number of samples. :type prior_samples: float :param startup_delay: Default 0.0s. If provided, this function will accrue statistics for the first startup_delay seconds before applying online normalization. :type startup_delay: float """ # Estimate total RMS online. startup_sample_idx = min(self.num_samples - 1, int(self.sample_rate * startup_delay)) prior_mean_squared = 10.**(prior_db / 10.) prior_sum_of_squares = prior_mean_squared * prior_samples cumsum_of_squares = np.cumsum(self.samples**2) sample_count = np.arange(self.num_samples) + 1 if startup_sample_idx > 0: cumsum_of_squares[:startup_sample_idx] = \ cumsum_of_squares[startup_sample_idx] sample_count[:startup_sample_idx] = \ sample_count[startup_sample_idx] mean_squared_estimate = ((cumsum_of_squares + prior_sum_of_squares) / (sample_count + prior_samples)) rms_estimate_db = 10 * np.log10(mean_squared_estimate) # Compute required time-varying gain. gain_db = target_db - rms_estimate_db self.gain_db(gain_db) def resample(self, target_sample_rate, filter='kaiser_best'): """Resample the audio to a target sample rate. Note that this is an in-place transformation. :param target_sample_rate: Target sample rate. :type target_sample_rate: int :param filter: The resampling filter to use one of {'kaiser_best', 'kaiser_fast'}. :type filter: str """ self._samples = resampy.resample( self.samples, self.sample_rate, target_sample_rate, filter=filter) self._sample_rate = target_sample_rate def pad_silence(self, duration, sides='both'): """Pad this audio sample with a period of silence. Note that this is an in-place transformation. :param duration: Length of silence in seconds to pad. :type duration: float :param sides: Position for padding: 'beginning' - adds silence in the beginning; 'end' - adds silence in the end; 'both' - adds silence in both the beginning and the end. :type sides: str :raises ValueError: If sides is not supported. """ if duration == 0.0: return self cls = type(self) silence = self.make_silence(duration, self._sample_rate) if sides == "beginning": padded = cls.concatenate(silence, self) elif sides == "end": padded = cls.concatenate(self, silence) elif sides == "both": padded = cls.concatenate(silence, self, silence) else: raise ValueError("Unknown value for the sides %s" % sides) self._samples = padded._samples def shift(self, shift_ms): """Shift the audio in time. If `shift_ms` is positive, shift with time advance; if negative, shift with time delay. Silence are padded to keep the duration unchanged. Note that this is an in-place transformation. :param shift_ms: Shift time in millseconds. If positive, shift with time advance; if negative; shift with time delay. :type shift_ms: float :raises ValueError: If shift_ms is longer than audio duration. """ if abs(shift_ms) / 1000.0 > self.duration: raise ValueError("Absolute value of shift_ms should be smaller " "than audio duration.") shift_samples = int(shift_ms * self._sample_rate / 1000) if shift_samples > 0: # time advance self._samples[:-shift_samples] = self._samples[shift_samples:] self._samples[-shift_samples:] = 0 elif shift_samples < 0: # time delay self._samples[-shift_samples:] = self._samples[:shift_samples] self._samples[:-shift_samples] = 0 def subsegment(self, start_sec=None, end_sec=None): """Cut the AudioSegment between given boundaries. Note that this is an in-place transformation. :param start_sec: Beginning of subsegment in seconds. :type start_sec: float :param end_sec: End of subsegment in seconds. :type end_sec: float :raise ValueError: If start_sec or end_sec is incorrectly set, e.g. out of bounds in time. """ start_sec = 0.0 if start_sec is None else start_sec end_sec = self.duration if end_sec is None else end_sec if start_sec < 0.0: start_sec = self.duration + start_sec if end_sec < 0.0: end_sec = self.duration + end_sec if start_sec < 0.0: raise ValueError("The slice start position (%f s) is out of " "bounds." % start_sec) if end_sec < 0.0: raise ValueError("The slice end position (%f s) is out of bounds." % end_sec) if start_sec > end_sec: raise ValueError("The slice start position (%f s) is later than " "the end position (%f s)." % (start_sec, end_sec)) if end_sec > self.duration: raise ValueError("The slice end position (%f s) is out of bounds " "(> %f s)" % (end_sec, self.duration)) start_sample = int(round(start_sec * self._sample_rate)) end_sample = int(round(end_sec * self._sample_rate)) self._samples = self._samples[start_sample:end_sample] def random_subsegment(self, subsegment_length, rng=None): """Cut the specified length of the audiosegment randomly. Note that this is an in-place transformation. :param subsegment_length: Subsegment length in seconds. :type subsegment_length: float :param rng: Random number generator state. :type rng: random.Random :raises ValueError: If the length of subsegment is greater than the origineal segemnt. """ rng = random.Random() if rng is None else rng if subsegment_length > self.duration: raise ValueError("Length of subsegment must not be greater " "than original segment.") start_time = rng.uniform(0.0, self.duration - subsegment_length) self.subsegment(start_time, start_time + subsegment_length) def convolve(self, impulse_segment, allow_resample=False): """Convolve this audio segment with the given impulse segment. Note that this is an in-place transformation. :param impulse_segment: Impulse response segments. :type impulse_segment: AudioSegment :param allow_resample: Indicates whether resampling is allowed when the impulse_segment has a different sample rate from this signal. :type allow_resample: bool :raises ValueError: If the sample rate is not match between two audio segments when resample is not allowed. """ if allow_resample and self.sample_rate != impulse_segment.sample_rate: impulse_segment.resample(self.sample_rate) if self.sample_rate != impulse_segment.sample_rate: raise ValueError("Impulse segment's sample rate (%d Hz) is not " "equal to base signal sample rate (%d Hz)." % (impulse_segment.sample_rate, self.sample_rate)) samples = signal.fftconvolve(self.samples, impulse_segment.samples, "full") self._samples = samples def convolve_and_normalize(self, impulse_segment, allow_resample=False): """Convolve and normalize the resulting audio segment so that it has the same average power as the input signal. Note that this is an in-place transformation. :param impulse_segment: Impulse response segments. :type impulse_segment: AudioSegment :param allow_resample: Indicates whether resampling is allowed when the impulse_segment has a different sample rate from this signal. :type allow_resample: bool """ target_db = self.rms_db self.convolve(impulse_segment, allow_resample=allow_resample) self.normalize(target_db) def add_noise(self, noise, snr_dB, allow_downsampling=False, max_gain_db=300.0, rng=None): """Add the given noise segment at a specific signal-to-noise ratio. If the noise segment is longer than this segment, a random subsegment of matching length is sampled from it and used instead. Note that this is an in-place transformation. :param noise: Noise signal to add. :type noise: AudioSegment :param snr_dB: Signal-to-Noise Ratio, in decibels. :type snr_dB: float :param allow_downsampling: Whether to allow the noise signal to be downsampled to match the base signal sample rate. :type allow_downsampling: bool :param max_gain_db: Maximum amount of gain to apply to noise signal before adding it in. This is to prevent attempting to apply infinite gain to a zero signal. :type max_gain_db: float :param rng: Random number generator state. :type rng: None|random.Random :raises ValueError: If the sample rate does not match between the two audio segments when downsampling is not allowed, or if the duration of noise segments is shorter than original audio segments. """ rng = random.Random() if rng is None else rng if allow_downsampling and noise.sample_rate > self.sample_rate: noise = noise.resample(self.sample_rate) if noise.sample_rate != self.sample_rate: raise ValueError("Noise sample rate (%d Hz) is not equal to base " "signal sample rate (%d Hz)." % (noise.sample_rate, self.sample_rate)) if noise.duration < self.duration: raise ValueError("Noise signal (%f sec) must be at least as long as" " base signal (%f sec)." % (noise.duration, self.duration)) noise_gain_db = min(self.rms_db - noise.rms_db - snr_dB, max_gain_db) noise_new = copy.deepcopy(noise) noise_new.random_subsegment(self.duration, rng=rng) noise_new.gain_db(noise_gain_db) self.superimpose(noise_new) @property def samples(self): """Return audio samples. :return: Audio samples. :rtype: ndarray """ return self._samples.copy() @property def sample_rate(self): """Return audio sample rate. :return: Audio sample rate. :rtype: int """ return self._sample_rate @property def num_samples(self): """Return number of samples. :return: Number of samples. :rtype: int """ return self._samples.shape[0] @property def duration(self): """Return audio duration. :return: Audio duration in seconds. :rtype: float """ return self._samples.shape[0] / float(self._sample_rate) @property def rms_db(self): """Return root mean square energy of the audio in decibels. :return: Root mean square energy in decibels. :rtype: float """ # square root => multiply by 10 instead of 20 for dBs mean_square = np.mean(self._samples**2) return 10 * np.log10(mean_square) def _convert_samples_to_float32(self, samples): """Convert sample type to float32. Audio sample type is usually integer or float-point. Integers will be scaled to [-1, 1] in float32. """ return convert_samples_to_float32(samples) def _convert_samples_from_float32(self, samples, dtype): """Convert sample type from float32 to dtype. Audio sample type is usually integer or float-point. For integer type, float32 will be rescaled from [-1, 1] to the maximum range supported by the integer type. This is for writing a audio file. """ return convert_samples_from_float32(samples, dtype)
41.204735
84
0.598378
3,605
29,585
4.772538
0.142857
0.046498
0.018715
0.010578
0.285324
0.225167
0.206684
0.169427
0.165359
0.128858
0
0.011959
0.324489
29,585
717
85
41.262204
0.848937
0.417779
0
0.167192
0
0
0.105382
0
0
0
0
0
0
1
0.104101
false
0
0.047319
0
0.239748
0
0
0
0
null
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
null
0
0
0
0
0
0
0
0
0
0
0
0
1
0
d49613fe0b2e81e10d722fc25f0c3fd9aa1b0a51
4,119
py
Python
tornado_debugger/debug.py
bhch/tornado-debugger
4adeead7a45506eda34fc8d1e91dd32acc8cfe4e
[ "BSD-3-Clause" ]
1
2022-03-21T11:52:30.000Z
2022-03-21T11:52:30.000Z
tornado_debugger/debug.py
bhch/tornado-debugger
4adeead7a45506eda34fc8d1e91dd32acc8cfe4e
[ "BSD-3-Clause" ]
null
null
null
tornado_debugger/debug.py
bhch/tornado-debugger
4adeead7a45506eda34fc8d1e91dd32acc8cfe4e
[ "BSD-3-Clause" ]
null
null
null
import os.path import re import sys import traceback from pprint import pformat import tornado from tornado import template SENSITIVE_SETTINGS_RE = re.compile( 'api|key|pass|salt|secret|signature|token', flags=re.IGNORECASE ) class ExceptionReporter: def __init__(self, exc_info, handler): self.exc_type = exc_info[0] self.exc_value = exc_info[1] self.exc_tb = exc_info[2] self.handler = handler def get_response(self): loader = template.Loader(os.path.dirname(os.path.abspath(__file__))) t = loader.load('debug.html') return t.generate( traceback=traceback, pprint=pprint, handler=self.handler, app_settings=self.get_app_settings(), exc_type=self.exc_type, exc_value=self.exc_value, exc_tb=self.exc_tb, frames=self.get_traceback_frames(), tornado_version=tornado.version, sys_version='%d.%d.%d' % sys.version_info[0:3], sys_executable=sys.executable, sys_path=sys.path, ) def get_app_settings(self): settings = {} for arg, value in self.handler.application.settings.items(): if SENSITIVE_SETTINGS_RE.search(arg): value = '*' * 15 settings[arg] = value return settings def get_source_lines(self, tb): filename = tb.tb_frame.f_code.co_filename lineno = tb.tb_lineno lines = [] try: with open(filename, 'rb') as f: _lines = f.read().splitlines() for _lineno in range( max(lineno - 5, 0), min(lineno + 5, len(_lines)) ): lines.append((_lineno + 1, _lines[_lineno])) except Exception as e: # could not open file pass return lines def get_traceback_frames(self): frames = [] tb = self.exc_tb while tb: frames.append({ 'lineno': tb.tb_lineno, 'filename': tb.tb_frame.f_code.co_filename, 'function': tb.tb_frame.f_code.co_name, 'module_name': tb.tb_frame.f_globals.get('__name__') or '', 'vars': tb.tb_frame.f_locals, 'lines': self.get_source_lines(tb), }) tb = tb.tb_next frames.reverse() return frames exceptions = [] exc_value = self.exc_value while exc_value: exceptions.append(exc_value) exc_value = self._get_explicit_or_implicit_cause(exc_value) if exc_value in exceptions: warnings.warn( "Cycle in the exception chain detected: exception '%s' " "encountered again." % exc_value, ExceptionCycleWarning, ) # Avoid infinite loop if there's a cyclic reference (#29393). break frames = [] # No exceptions were supplied to ExceptionReporter if not exceptions: return frames # In case there's just one exception, take the traceback from self.tb exc_value = exceptions.pop() tb = self.tb if not exceptions else exc_value.__traceback__ while True: frames.extend(self.get_exception_traceback_frames(exc_value, tb)) try: exc_value = exceptions.pop() except IndexError: break tb = exc_value.__traceback__ return frames def _get_explicit_or_implicit_cause(self, exc_value): explicit = getattr(exc_value, '__cause__', None) suppress_context = getattr(exc_value, '__suppress_context__', None) implicit = getattr(exc_value, '__context__', None) return explicit or (None if suppress_context else implicit) def pprint(value): try: return pformat(value, width=1) except Exception as e: return 'Error in formatting: %s: %s' % (e.__class__.__name__, e)
31.442748
77
0.571255
472
4,119
4.70339
0.300847
0.072072
0.02027
0.022523
0.077477
0.036036
0.028829
0.028829
0
0
0
0.00625
0.339646
4,119
130
78
31.684615
0.809926
0.047342
0
0.132075
0
0
0.063808
0.010209
0
0
0
0
0
1
0.066038
false
0.018868
0.066038
0
0.226415
0.028302
0
0
0
null
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
null
0
0
0
0
0
0
0
0
0
0
0
0
1
0
d496568fcdd0e4278b5c17076444af1d96c25b39
2,426
py
Python
base/pylib/seq_iter.py
jpolitz/lambda-py-paper
746ef63fc1123714b4adaf78119028afbea7bd76
[ "Apache-2.0" ]
1
2017-12-10T00:05:54.000Z
2017-12-10T00:05:54.000Z
base/pylib/seq_iter.py
jpolitz/lambda-py-paper
746ef63fc1123714b4adaf78119028afbea7bd76
[ "Apache-2.0" ]
null
null
null
base/pylib/seq_iter.py
jpolitz/lambda-py-paper
746ef63fc1123714b4adaf78119028afbea7bd76
[ "Apache-2.0" ]
null
null
null
class SeqIter: def __init__(self,l): self.l = l self.i = 0 self.stop = False def __len__(self): return len(self.l) def __list__(self): l = [] while True: try: l.append(self.__next__()) except StopIteration: break return l def __iter__(self): return self def __next__(self): has_length = True found = False try: self.l.__len__() except AttributeError: has_length = False try: if self.stop: raise StopIteration() if has_length and self.i >= self.l.__len__(): self.stop = True raise StopIteration() ret = self.l[self.i] found = True except IndexError: raise StopIteration() except StopIteration: raise StopIteration() self.i += 1 if found: return ret else: return None ___assign("%SeqIter", SeqIter) def iter(l, *args): callable = ___id("%callable") if args.__len__() == 1: if callable(l): stopwhen = args[0] return FuncIter(l, stopwhen) else: TypeError("iter(v, w): v must be callable") elif args.__len__() == 0: try: return l.__iter__() except: try: if callable(l.__getitem__): return SeqIter(l) except: raise TypeError("object is not iterable") else: raise TypeError("iter expect at most 2 arguments") ___assign("%iter", iter) def next(it, *arg): if len(arg) == 0: return it.__next__() else: return it.__next__(arg[0]) ___assign("%next", next) class FuncIter: def __init__(self, func, stopwhen): self.func = func self.stopwhen = stopwhen self.stopped = False def __list__(self): l = [] while not self.stopped: try: l.append(self.__next__()) except StopIteration: break return l def __next__(self): f = self.func v = f() if v == self.stopwhen: self.stopped = True raise StopIteration() else: return v ___assign("%FuncIter", FuncIter)
22.462963
58
0.490107
251
2,426
4.378486
0.243028
0.036397
0.020018
0.021838
0.125569
0.094631
0.094631
0.094631
0.094631
0.094631
0
0.00563
0.414262
2,426
107
59
22.672897
0.767769
0
0
0.366667
0
0
0.049052
0
0
0
0
0
0
1
0.111111
false
0
0
0.022222
0.266667
0
0
0
0
null
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
null
0
0
0
0
0
0
0
0
0
0
0
0
1
0
d496c50445b160bee65444aedffd5152e26bcfa5
1,542
py
Python
caseworker/open_general_licences/enums.py
code-review-doctor/lite-frontend-1
cb3b885bb389ea33ef003c916bea7b03a36d86bb
[ "MIT" ]
null
null
null
caseworker/open_general_licences/enums.py
code-review-doctor/lite-frontend-1
cb3b885bb389ea33ef003c916bea7b03a36d86bb
[ "MIT" ]
null
null
null
caseworker/open_general_licences/enums.py
code-review-doctor/lite-frontend-1
cb3b885bb389ea33ef003c916bea7b03a36d86bb
[ "MIT" ]
null
null
null
from lite_content.lite_internal_frontend.open_general_licences import ( OGEL_DESCRIPTION, OGTCL_DESCRIPTION, OGTL_DESCRIPTION, ) from lite_forms.components import Option class OpenGeneralExportLicences: class OpenGeneralLicence: def __init__(self, id, name, description, acronym): self.id = id self.name = name self.description = description self.acronym = acronym open_general_export_licence = OpenGeneralLicence( "00000000-0000-0000-0000-000000000002", "Open General Export Licence", OGEL_DESCRIPTION, "OGEL", ) open_general_trade_control_licence = OpenGeneralLicence( "00000000-0000-0000-0000-000000000013", "Open General Trade Control Licence", OGTCL_DESCRIPTION, "OGTCL", ) open_general_transhipment_licence = OpenGeneralLicence( "00000000-0000-0000-0000-000000000014", "Open General Transhipment Licence", OGTL_DESCRIPTION, "OGTL", ) @classmethod def all(cls): return [ cls.open_general_export_licence, cls.open_general_trade_control_licence, cls.open_general_transhipment_licence, ] @classmethod def as_options(cls): return [ Option(key=ogl.id, value=f"{ogl.name} ({ogl.acronym})", description=ogl.description) for ogl in cls.all() ] @classmethod def get_by_id(cls, id): return next(ogl for ogl in cls.all() if ogl.id == id)
29.09434
117
0.647211
162
1,542
5.919753
0.314815
0.114703
0.05318
0.075078
0.256517
0.140772
0
0
0
0
0
0.085182
0.269131
1,542
52
118
29.653846
0.76575
0
0
0.23913
0
0
0.156291
0.070039
0
0
0
0
0
1
0.086957
false
0
0.043478
0.065217
0.304348
0
0
0
0
null
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
null
0
0
0
0
0
0
0
0
0
0
0
0
1
0
d49731577779af0d944350934f9656734de31c66
319
py
Python
sort.py
EYH0602/FP_Workshop
866b180b411c1ef439e1a2d039c6d6333e91cd39
[ "MIT" ]
1
2021-10-21T02:15:03.000Z
2021-10-21T02:15:03.000Z
sort.py
EYH0602/FP_Workshop
866b180b411c1ef439e1a2d039c6d6333e91cd39
[ "MIT" ]
null
null
null
sort.py
EYH0602/FP_Workshop
866b180b411c1ef439e1a2d039c6d6333e91cd39
[ "MIT" ]
null
null
null
def quicksort(xs): if len(xs) == 0: return [] pivot = xs[0] xs = xs[1:] left = [x for x in xs if x <= pivot] right = [x for x in xs if x > pivot] res = quicksort(left) res.append(pivot) res += quicksort(right) return res xs = [1, 3, 2, 4, 5, 2] sorted_xs = quicksort(xs)
17.722222
40
0.526646
54
319
3.092593
0.388889
0.071856
0.05988
0.083832
0.203593
0.203593
0.203593
0.203593
0
0
0
0.04186
0.326019
319
17
41
18.764706
0.734884
0
0
0
0
0
0
0
0
0
0
0
0
1
0.076923
false
0
0
0
0.230769
0
0
0
0
null
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
null
0
0
0
0
0
0
0
0
0
0
0
0
1
0
d49737aed7a2d03e7911f282302b8766a0010d5f
9,372
py
Python
bddtests/steps/bdd_test_util.py
TarantulaTechnology/fabric5
6da971177ab7d74f1e1cfa6f7fc73e75768e5686
[ "Apache-2.0" ]
4
2018-01-02T04:26:16.000Z
2018-10-25T08:51:06.000Z
bddtests/steps/bdd_test_util.py
TarantulaTechnology/fabric5
6da971177ab7d74f1e1cfa6f7fc73e75768e5686
[ "Apache-2.0" ]
null
null
null
bddtests/steps/bdd_test_util.py
TarantulaTechnology/fabric5
6da971177ab7d74f1e1cfa6f7fc73e75768e5686
[ "Apache-2.0" ]
9
2016-11-17T07:40:04.000Z
2020-03-16T16:11:39.000Z
# Copyright IBM Corp. 2016 All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # import os import re import subprocess import devops_pb2 import fabric_pb2 import chaincode_pb2 from grpc.beta import implementations def cli_call(context, arg_list, expect_success=True): """Executes a CLI command in a subprocess and return the results. @param context: the behave context @param arg_list: a list command arguments @param expect_success: use False to return even if an error occurred when executing the command @return: (string, string, int) output message, error message, return code """ #arg_list[0] = "update-" + arg_list[0] # We need to run the cli command by actually calling the python command # the update-cli.py script has a #!/bin/python as the first line # which calls the system python, not the virtual env python we # setup for running the update-cli p = subprocess.Popen(arg_list, stdout=subprocess.PIPE, stderr=subprocess.PIPE) output, error = p.communicate() if p.returncode != 0: if output is not None: print("Output:\n" + output) if error is not None: print("Error Message:\n" + error) if expect_success: raise subprocess.CalledProcessError(p.returncode, arg_list, output) return output, error, p.returncode class UserRegistration: def __init__(self, secretMsg, composeService): self.secretMsg = secretMsg self.composeService = composeService self.tags = {} self.lastResult = None def getUserName(self): return self.secretMsg['enrollId'] def getSecret(self): return devops_pb2.Secret(enrollId=self.secretMsg['enrollId'],enrollSecret=self.secretMsg['enrollSecret']) # Registerses a user on a specific composeService def registerUser(context, secretMsg, composeService): userName = secretMsg['enrollId'] if 'users' in context: pass else: context.users = {} if userName in context.users: raise Exception("User already registered: {0}".format(userName)) context.users[userName] = UserRegistration(secretMsg, composeService) # Registerses a user on a specific composeService def getUserRegistration(context, enrollId): userRegistration = None if 'users' in context: pass else: context.users = {} if enrollId in context.users: userRegistration = context.users[enrollId] else: raise Exception("User has not been registered: {0}".format(enrollId)) return userRegistration def ipFromContainerNamePart(namePart, containerDataList): """Returns the IPAddress based upon a name part of the full container name""" ip = None containerNamePrefix = os.path.basename(os.getcwd()) + "_" for containerData in containerDataList: if containerData.containerName.startswith(containerNamePrefix + namePart): ip = containerData.ipAddress if ip == None: raise Exception("Could not find container with namePart = {0}".format(namePart)) return ip def getTxResult(context, enrollId): '''Returns the TransactionResult using the enrollId supplied''' assert 'users' in context, "users not found in context. Did you register a user?" assert 'compose_containers' in context, "compose_containers not found in context" (channel, userRegistration) = getGRPCChannelAndUser(context, enrollId) stub = devops_pb2.beta_create_Devops_stub(channel) txRequest = devops_pb2.TransactionRequest(transactionUuid = context.transactionID) response = stub.GetTransactionResult(txRequest, 2) assert response.status == fabric_pb2.Response.SUCCESS, 'Failure getting Transaction Result from {0}, for user "{1}": {2}'.format(userRegistration.composeService,enrollId, response.msg) # Now grab the TransactionResult from the Msg bytes txResult = fabric_pb2.TransactionResult() txResult.ParseFromString(response.msg) return txResult def getGRPCChannel(ipAddress): channel = implementations.insecure_channel(ipAddress, 30303) print("Returning GRPC for address: {0}".format(ipAddress)) return channel def getGRPCChannelAndUser(context, enrollId): '''Returns a tuple of GRPC channel and UserRegistration instance. The channel is open to the composeService that the user registered with.''' userRegistration = getUserRegistration(context, enrollId) # Get the IP address of the server that the user registered on ipAddress = ipFromContainerNamePart(userRegistration.composeService, context.compose_containers) channel = getGRPCChannel(ipAddress) return (channel, userRegistration) def getDeployment(context, ccAlias): '''Return a deployment with chaincode alias from prior deployment, or None if not found''' deployment = None if 'deployments' in context: pass else: context.deployments = {} if ccAlias in context.deployments: deployment = context.deployments[ccAlias] # else: # raise Exception("Deployment alias not found: '{0}'. Are you sure you have deployed a chaincode with this alias?".format(ccAlias)) return deployment def deployChaincode(context, enrollId, chaincodePath, ccAlias, ctor): '''Deploy a chaincode with the specified alias for the specfied enrollId''' (channel, userRegistration) = getGRPCChannelAndUser(context, enrollId) stub = devops_pb2.beta_create_Devops_stub(channel) # Make sure deployment alias does NOT already exist assert getDeployment(context, ccAlias) == None, "Deployment alias already exists: '{0}'.".format(ccAlias) args = getArgsFromContextForUser(context, enrollId) ccSpec = chaincode_pb2.ChaincodeSpec(type = chaincode_pb2.ChaincodeSpec.GOLANG, chaincodeID = chaincode_pb2.ChaincodeID(name="",path=chaincodePath), ctorMsg = chaincode_pb2.ChaincodeInput(function = ctor, args = args)) ccSpec.secureContext = userRegistration.getUserName() if 'metadata' in context: ccSpec.metadata = context.metadata try: ccDeploymentSpec = stub.Deploy(ccSpec, 60) ccSpec.chaincodeID.name = ccDeploymentSpec.chaincodeSpec.chaincodeID.name context.grpcChaincodeSpec = ccSpec context.deployments[ccAlias] = ccSpec except: del stub raise def invokeChaincode(context, enrollId, ccAlias, functionName): # Get the deployment for the supplied chaincode alias deployedCcSpec = getDeployment(context, ccAlias) assert deployedCcSpec != None, "Deployment NOT found for chaincode alias '{0}'".format(ccAlias) # Create a new ChaincodeSpec by copying the deployed one newChaincodeSpec = chaincode_pb2.ChaincodeSpec() newChaincodeSpec.CopyFrom(deployedCcSpec) # Update hte chaincodeSpec ctorMsg for invoke args = getArgsFromContextForUser(context, enrollId) chaincodeInput = chaincode_pb2.ChaincodeInput(function = functionName, args = args ) newChaincodeSpec.ctorMsg.CopyFrom(chaincodeInput) ccInvocationSpec = chaincode_pb2.ChaincodeInvocationSpec(chaincodeSpec = newChaincodeSpec) (channel, userRegistration) = getGRPCChannelAndUser(context, enrollId) stub = devops_pb2.beta_create_Devops_stub(channel) response = stub.Invoke(ccInvocationSpec,2) return response def getArgsFromContextForUser(context, enrollId): # Update the chaincodeSpec ctorMsg for invoke args = [] if 'table' in context: # There are function arguments userRegistration = getUserRegistration(context, enrollId) # Allow the user to specify expressions referencing tags in the args list pattern = re.compile('\{(.*)\}$') for arg in context.table[0].cells: m = pattern.match(arg) if m: # tagName reference found in args list tagName = m.groups()[0] # make sure the tagName is found in the users tags assert tagName in userRegistration.tags, "TagName '{0}' not found for user '{1}'".format(tagName, userRegistration.getUserName()) args.append(userRegistration.tags[tagName]) else: #No tag referenced, pass the arg args.append(arg) return args def getContainerDataValuesFromContext(context, aliases, callback): """Returns the IPAddress based upon a name part of the full container name""" assert 'compose_containers' in context, "compose_containers not found in context" values = [] containerNamePrefix = os.path.basename(os.getcwd()) + "_" for namePart in aliases: for containerData in context.compose_containers: if containerData.containerName.startswith(containerNamePrefix + namePart): values.append(callback(containerData)) break return values
40.747826
189
0.714789
1,061
9,372
6.267672
0.282752
0.021654
0.014436
0.007669
0.153233
0.139699
0.12015
0.106917
0.093684
0.082256
0
0.006844
0.204866
9,372
229
190
40.925764
0.885534
0.26131
0
0.197183
0
0
0.088046
0
0
0
0
0
0.049296
1
0.105634
false
0.021127
0.049296
0.014085
0.246479
0.021127
0
0
0
null
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
null
0
0
0
0
0
0
0
0
0
0
0
0
1
0
d4973b8aa4822ac46365e7bcf3331ae6bf592f03
13,868
py
Python
1.0.0/hp/dict.py
cefect/SOFDA0
62c5566d0f388a5fd76a070ceb5ee3e38b0d7463
[ "MIT" ]
null
null
null
1.0.0/hp/dict.py
cefect/SOFDA0
62c5566d0f388a5fd76a070ceb5ee3e38b0d7463
[ "MIT" ]
null
null
null
1.0.0/hp/dict.py
cefect/SOFDA0
62c5566d0f388a5fd76a070ceb5ee3e38b0d7463
[ "MIT" ]
null
null
null
''' Created on Mar 6, 2018 @author: cef hp functions for workign with dictionaries ''' import logging, os, sys, math, copy, inspect from collections import OrderedDict from weakref import WeakValueDictionary as wdict import numpy as np import hp.basic mod_logger = logging.getLogger(__name__) #creates a child logger of the root def dict_2_logr(dict, logger= mod_logger): #log each value of the dictionary to fille logger = logger.getChild('dict_2_logr') msg = '\n' for key, value in dict.iteritems(): msg = msg + ' key: %s\n value: %s \n'%(key, value) logger.debug(msg) def key_list(d, #return the intersection of the dict.keys() and the key_list key_list, logger = mod_logger): logger = logger.getChild('key_list') #=========================================================================== # pre check #=========================================================================== bool_list = hp.basic.bool_list_in_list(d.keys(), key_list) if not bool_list.any(): raise IOError #check if any are not found #=========================================================================== # build the found values #=========================================================================== values_fnd_list = [] for key, value in d.iteritems(): if key in key_list: values_fnd_list.append(value) return values_fnd_list def build_nones_dict(key_list, logger=mod_logger): #add 'None' values to the passed keys val_list = np.full((1, len(key_list)), None) dict = dict(zip(key_list, val_list)) return dict def merge_two_dicts(x, y): if x is None: return y if y is None: return x z = x.copy() # start with x's keys and values z.update(y) # modifies z with y's keys and values & returns None return z def value_by_ksearch(ksearch_str, d, #get the entry that matches the search str logger=mod_logger, *search_args): #=========================================================================== # take a shot at a perfect match #=========================================================================== try: return d[ksearch_str] except: #find a match for this key k_fnd = hp.basic.list_search(d.keys(), ksearch_str, *search_args) if k_fnd is None: logger = logger.getChild('value_by_ksearch') logger.debug('could not find \'%s\' in %i dict keys. returning None'%(ksearch_str, len(d))) return None else: return d[k_fnd] def merge(dl, dr, #intelligent dictionary merging set_type = 'intersect', method = 'exact', container = dict(), logger = mod_logger, *search_args): if set_type == 'union': if method == 'exact': d_merge = merge_two_dicts(dl, dr, logger=logger) else: raise IOError #todo elif set_type == 'intersect': d_merge = subset(dl, dr.keys(), set_type = set_type, method=method, container=container, logger=logger, *search_args) else: raise IOError logger.debug('got d_merge %i'%len(d_merge)) return container(d_merge) def subset_pfx(d_big, prefix, logger=mod_logger): #=========================================================================== # shortcuts #=========================================================================== if len(d_big) == 0: return dict() #=========================================================================== # defaults #=========================================================================== logger = logger.getChild('subset_pfx') d = copy.copy(d_big) fnd_d = dict() for k, v in d.iteritems(): if k.startswith(prefix): fnd_d[k] = v logger.debug('found %i entries with prefix \'%s\' \n'%(len(fnd_d), prefix)) return fnd_d def subset(d_big, l, #get a dictionary subset using standard user inputs #ordered = False, using containers instead set_type = 'sub', method = 'exact', container = dict, logger = mod_logger, *search_args): """ #=========================================================================== # INPUTS #=========================================================================== l: list of keys (within d_big) on which to erturn the sutset set_type: how to treat the set intersect: returna dictionary with only the common keys sub: raise a flag if not every item in 'l' is found in d_big.keys() method: what type of key search to perform (re.function) search: look for a key in the dictionary that contains the list entry. returned d is keyed by the list """ logger = logger.getChild('subset') #=========================================================================== # setup[] #========================================================================== d = container() """ #dictionary setup if ordered: d = OrderedDict() else: d = dict()""" #input list setup if isinstance(l, list): pass elif isinstance(l, basestring): l = [l] elif l is None: return d else: raise IOError nofnd_l = [] #=========================================================================== # determine subset by kwarg #=========================================================================== for k in l: try: #attempt teh direct match d[k] = d_big[k] except: #=================================================================== # try again using search functions #=================================================================== try: if method == 'search': #search and return this value v = value_by_ksearch(k, d_big, logger=logger, *search_args) if not v is None: d[k] = v continue #not sure this is needed else: raise ValueError else: raise ValueError #=================================================================== # nothing found. proceed based on set_type #=================================================================== except: logger.debug('unable to find \'%s\' in the dict with method \'%s\''%(k, method)) if set_type == 'sub': boolar = hp.basic.bool_list_in_list(d_big.keys(), l) if not np.all(boolar): logger.error('%i entries in list not found in big_d'%(len(l) - boolar.sum())) raise IOError elif set_type == 'intersect': nofnd_l.append(k) else: raise IOError #=========================================================================== # wrap up #=========================================================================== if len(nofnd_l) >0: logger.debug('%i of %i list entries DO NOT intersect: %s'%(len(nofnd_l), len(l), nofnd_l)) if set_type == 'sub': raise IOError #=========================================================================== # check #=========================================================================== if len(d) == 0: logger.warning('0 common values between d(%i) and l(%i)'%(len(d), len(l))) logger.debug('returning d with %i entries: %s \n'%(len(d), d.keys())) return container(d) #=============================================================================== # def subset(d_big, l, #get a dictionary subset using standard user inputs # ordered = False, set_type = 'sub', search = 'search', # logger = mod_logger): # """ # #=========================================================================== # # INPUTS # #=========================================================================== # l: list of keys (within d_big) on which to erturn the sutset # # set_type: how to treat the set # intersect: returna dictionary with only the common keys # sub: raise a flag if not every item in 'l' is found in d_big.keys() # # search: what type of key search to perform (re.function) # """ # logger = logger.getChild('subset') # # #=========================================================================== # # setup[] # #========================================================================== # #dictionary setup # if ordered: d = OrderedDict() # else: d = dict() # # #input list setup # if isinstance(l, list): pass # elif isinstance(l, basestring): l = [l] # elif l is None: return None # else: raise IOError # # #=========================================================================== # # determine subset by kwarg # #=========================================================================== # if set_type == 'sub': # try: # for k in l: # d[k] = d_big[k] # # except: # boolar = hp.basic.bool_list_in_list(d_big.keys(), l) # # if not np.all(boolar): # logger.error('%i entries in list not found in big_d'%(len(l) - boolar.sum())) # # raise IOError # # if len(d) == 0: raise IOError # # elif set_type == 'intersect': # nofnd_l = [] # for k in l: # try: # d[k] = d_big[k] # except: # nofnd_l.append(k) # # if len(nofnd_l) >0: # logger.debug('%i of %i list entries DO NOT intersect: %s'%(len(nofnd_l), len(l), nofnd_l)) # # #=========================================================================== # # check # #=========================================================================== # if len(d) == 0: logger.warning('0 common values between d(%i) and l(%i)'% # (len(d), len(l))) # # return d #=============================================================================== class deepcopier(): tries = 0 #keep track of the loop def __init__(self,obj, logger=mod_logger): self.logger = logger.getChild('deepcopier') self.copy_o = obj def tryit(self, obj=None): #make as deep a copy as possible if obj is None: obj = self.copy_o #=========================================================================== # simple try #=========================================================================== try: copy_o = copy.deepcopy(obj) return copy_o except: self.logger.debug('failed first attempt') self.tries += 1 #======================================================================= # sophisiticated try #======================================================================= self.logger.debug('copy attempt %i'%self.tries) if self.tries > 10: return self.copy_o #try for each element of the dict if isinstance(obj, dict): new_d = dict() for key, value in obj.iteritems(): try: new_d[key] = self.tryit(obj = value) except: new_d[key] = copy.copy(obj) self.logger.debug('returning new_d with %i entries: %s'%(len(new_d), new_d.keys())) else: raise IOError return new_d from collections import OrderedDict class MyOrderedDict(OrderedDict): """ as there is no builtin method to add to the head of an ordered dict, here we add a method https://stackoverflow.com/questions/16664874/how-can-i-add-an-element-at-the-top-of-an-ordereddict-in-python """ def prepend(self, key, value, dict_setitem=dict.__setitem__): """add entry to the front of myself""" root = self._OrderedDict__root first = root[1] if key in self: link = self._OrderedDict__map[key] link_prev, link_next, _ = link link_prev[1] = link_next link_next[0] = link_prev link[0] = root link[1] = first root[1] = first[0] = link else: root[1] = first[0] = self._OrderedDict__map[key] = [root, first, key] dict_setitem(self, key, value)
36.687831
113
0.391477
1,319
13,868
3.992419
0.189538
0.019939
0.025636
0.010824
0.322446
0.288454
0.281048
0.27687
0.264717
0.231675
0
0.003969
0.327805
13,868
377
114
36.785146
0.560931
0.455509
0
0.178808
0
0
0.074901
0
0
0
0
0.002653
0
1
0.072848
false
0.006623
0.039735
0
0.205298
0
0
0
0
null
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
null
0
0
0
0
0
0
0
0
0
0
0
0
1
0
d49bc7fba6d65f4ec2d4a29ecf9e4f75e3ad24d1
10,163
py
Python
automatoes/authorize.py
candango/automatoes
fbfd01cfaa2c36e23a7251e333ef3fa86ef4bff9
[ "Apache-2.0" ]
13
2019-10-08T14:57:19.000Z
2022-01-12T10:01:30.000Z
automatoes/authorize.py
piraz/automatoes
fc6a20c317a8ac863bfb054c9541e310e0431e5f
[ "Apache-2.0" ]
125
2019-10-08T15:04:17.000Z
2022-03-29T19:27:12.000Z
automatoes/authorize.py
candango/automatoes
fbfd01cfaa2c36e23a7251e333ef3fa86ef4bff9
[ "Apache-2.0" ]
8
2019-10-14T15:18:57.000Z
2021-04-21T10:41:08.000Z
#!/usr/bin/env python # # Copyright 2019-2020 Flavio Garcia # Copyright 2016-2017 Veeti Paananen under MIT License # # 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. """ The domain authorization command. """ from . import get_version from .acme import AcmeV2 from .crypto import generate_jwk_thumbprint from .errors import AutomatoesError from .model import Order from cartola import fs, sysexits import hashlib import os import sys def create_order(acme, domains, method, order_file): order = acme.new_order(domains, method) update_order(order, order_file) return order def update_order(order, order_file): fs.write(order_file, order.serialize().decode()) def clean_http_challenges(files): # Clean up created files for path in files: try: os.remove(path) except: print("Couldn't delete http challenge file {}".format(path)) def clean_challenge_file(challenge_file): try: os.remove(challenge_file) except: print("Couldn't delete challenge file {}".format(challenge_file)) def authorize(server, paths, account, domains, method, verbose=False): print("Candango Automatoes {}. Manuale replacement.\n\n".format( get_version())) current_path = paths['current'] orders_path = paths['orders'] domains_hash = hashlib.sha256( "_".join(domains).encode('ascii')).hexdigest() order_path = os.path.join(orders_path, domains_hash) order_file = os.path.join(order_path, "order.json".format(domains_hash)) if not os.path.exists(orders_path): if verbose: print("Orders path not found creating it at {}." "".format(orders_path)) os.mkdir(orders_path) os.chmod(orders_path, 0o770) else: if verbose: print("Orders path found at {}.".format(orders_path)) if not os.path.exists(order_path): if verbose: print("Current order {} path not found creating it at orders " "path.\n".format(domains_hash)) os.mkdir(order_path) os.chmod(order_path, 0o770) else: if verbose: print("Current order {} path found at orders path.\n".format( domains_hash)) method = method acme = AcmeV2(server, account) try: print("Authorizing {}.\n".format(", ".join(domains))) # Creating orders for domains if not existent if not os.path.exists(order_file): if verbose: print(" Order file not found creating it.") order = create_order(acme, domains, method, order_file) else: if verbose: print(" Found order file. Querying ACME server for current " "status.") order = Order.deserialize(fs.read(order_file)) try: server_order = acme.query_order(order) order.contents = server_order.contents except: print(" WARNING: Old order. Setting it as expired.\n") order.contents['status'] = "expired" update_order(order, order_file) if not order.expired and not order.invalid: if order.contents['status'] == 'valid': print(" Order is valid and expires at {}. Please run " "the issue " "command.\n".format(order.contents['expires'])) print(" {} domain(s) authorized. Let's Encrypt!".format( len(domains))) sys.exit(sysexits.EX_OK) else: if verbose: print(" Order still pending and expires " "at {}.\n".format(order.contents['expires'])) else: if order.invalid: print(" WARNING: Invalid order, renewing it.\n Just " "continue with the authorization when all " "verifications are in place.\n") else: print(" WARNING: Expired order. Renewing order.\n") os.remove(order_file) order = create_order(acme, domains, method, order_file) update_order(order, order_file) pending_challenges = [] for challenge in acme.get_order_challenges(order): print(" Requesting challenge for {}.".format(challenge.domain)) if challenge.status == 'valid': print(" {} is already authorized until {}.".format( challenge.domain, challenge.expires)) continue else: challenge_file = os.path.join(order_path, challenge.file_name) if verbose: print(" Creating challenge file {}.\n".format( challenge.file_name)) fs.write(challenge_file, challenge.serialize().decode()) pending_challenges.append(challenge) # Quit if nothing to authorize if not pending_challenges: print("\nAll domains are already authorized, exiting.") sys.exit(sysexits.EX_OK) files = set() if method == 'dns': print("\n DNS verification required. Make sure these TXT records" " are in place:\n") for challenge in pending_challenges: print(" _acme-challenge.{}. IN TXT " "\"{}\"".format(challenge.domain, challenge.key)) elif method == 'http': print("\n HTTP verification required. Make sure these files are " "in place:\n") for challenge in pending_challenges: token = challenge.contents['token'] # path sanity check assert (token and os.path.sep not in token and '.' not in token) files.add(token) fs.write( os.path.join(current_path, token), "%s.%s" % (token, generate_jwk_thumbprint(account.key)) ) print(" http://{}/.well-known/acme-challenge/{}".format( challenge.domain, token)) print("\n The necessary files have been written to the current " "directory.\n") # Wait for the user to complete the challenges input("\nPress Enter to continue.\n") # Validate challenges done, failed, pending = set(), set(), set() for challenge in pending_challenges: print(" {}: waiting for verification. Checking in 5 " "seconds.".format(challenge.domain)) response = acme.verify_order_challenge(challenge, 5, 1) if response['status'] == "valid": print(" {}: OK! Authorization lasts until {}.".format( challenge.domain, challenge.expires)) done.add(challenge.domain) elif response['status'] == 'invalid': print(" {}: {} ({})".format( challenge.domain, response['error']['detail'], response['error']['type']) ) failed.add(challenge.domain) break else: print("{}: Pending!".format(challenge.domain)) pending.add(challenge.domain) break challenge_file = os.path.join(order_path, challenge.file_name) # Print results if failed: print(" {} domain(s) authorized, {} failed.".format( len(done), len(failed), )) print(" Authorized: {}".format(' '.join(done) or "N/A")) print(" Failed: {}".format(' '.join(failed))) print(" WARNING: The current order will be invalidated. " "Try again.") if verbose: print(" Deleting invalid challenge file {}.\n".format( challenge.file_name)) clean_challenge_file(challenge_file) os.remove(order_file) os.rmdir(order_path) if method == 'http': print(files) clean_http_challenges(files) sys.exit(sysexits.EX_FATAL_ERROR) else: if pending: print(" {} domain(s) authorized, {} pending.".format( len(done), len(pending))) print(" Authorized: {}".format(' '.join(done) or "N/A")) print(" Pending: {}".format(' '.join(pending))) print(" Try again.") sys.exit(sysexits.EX_CANNOT_EXECUTE) else: if verbose: print(" Deleting valid challenge file {}.".format( challenge.file_name)) clean_challenge_file(challenge_file) if verbose: print(" Querying ACME server for current status.\n") server_order = acme.query_order(order) order.contents = server_order.contents update_order(order, order_file) print(" {} domain(s) authorized. Let's Encrypt!".format( len(done))) if method == 'http': clean_http_challenges(files) sys.exit(sysexits.EX_OK) except IOError as e: print("A connection or service error occurred. Aborting.") raise AutomatoesError(e)
39.239382
79
0.546394
1,069
10,163
5.100094
0.237605
0.050073
0.028247
0.019259
0.320249
0.23661
0.162876
0.13573
0.105282
0.040719
0
0.005447
0.3497
10,163
258
80
39.391473
0.819489
0.084129
0
0.325243
0
0
0.206833
0
0
0
0
0
0.004854
1
0.024272
false
0
0.043689
0
0.072816
0.218447
0
0
0
null
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
null
0
0
0
0
0
0
0
0
0
0
0
0
1
0
d49c1e0bb83e7c39fdece7542b9e2c9d25d03288
5,832
py
Python
rllib/agents/dqn/simple_q_torch_policy.py
jamesliu/ray
11ab412db1fa3603a3006e8ed414e80dd1f11c0c
[ "Apache-2.0" ]
3
2020-12-12T05:10:44.000Z
2021-04-12T21:52:47.000Z
rllib/agents/dqn/simple_q_torch_policy.py
jamesliu/ray
11ab412db1fa3603a3006e8ed414e80dd1f11c0c
[ "Apache-2.0" ]
227
2021-10-01T08:00:01.000Z
2021-12-28T16:47:26.000Z
rllib/agents/dqn/simple_q_torch_policy.py
gramhagen/ray
c18caa4db36d466718bdbcb2229aa0b2dc03da1f
[ "Apache-2.0" ]
1
2020-12-02T06:26:20.000Z
2020-12-02T06:26:20.000Z
"""PyTorch policy class used for Simple Q-Learning""" import logging from typing import Dict, Tuple import gym import ray from ray.rllib.agents.dqn.simple_q_tf_policy import ( build_q_models, compute_q_values, get_distribution_inputs_and_class) from ray.rllib.models.modelv2 import ModelV2 from ray.rllib.models.torch.torch_action_dist import TorchCategorical, \ TorchDistributionWrapper from ray.rllib.policy import Policy from ray.rllib.policy.policy_template import build_policy_class from ray.rllib.policy.sample_batch import SampleBatch from ray.rllib.policy.torch_policy import TorchPolicy from ray.rllib.utils.annotations import override from ray.rllib.utils.framework import try_import_torch from ray.rllib.utils.torch_utils import concat_multi_gpu_td_errors, huber_loss from ray.rllib.utils.typing import TensorType, TrainerConfigDict torch, nn = try_import_torch() F = None if nn: F = nn.functional logger = logging.getLogger(__name__) class TargetNetworkMixin: """Assign the `update_target` method to the SimpleQTorchPolicy The function is called every `target_network_update_freq` steps by the master learner. """ def __init__(self): # Hard initial update from Q-net(s) to target Q-net(s). self.update_target() def update_target(self): # Update_target_fn will be called periodically to copy Q network to # target Q networks. state_dict = self.model.state_dict() for target in self.target_models.values(): target.load_state_dict(state_dict) @override(TorchPolicy) def set_weights(self, weights): # Makes sure that whenever we restore weights for this policy's # model, we sync the target network (from the main model) # at the same time. TorchPolicy.set_weights(self, weights) self.update_target() def build_q_model_and_distribution( policy: Policy, obs_space: gym.spaces.Space, action_space: gym.spaces.Space, config: TrainerConfigDict) -> Tuple[ModelV2, TorchDistributionWrapper]: return build_q_models(policy, obs_space, action_space, config), \ TorchCategorical def build_q_losses(policy: Policy, model, dist_class, train_batch: SampleBatch) -> TensorType: """Constructs the loss for SimpleQTorchPolicy. Args: policy (Policy): The Policy to calculate the loss for. model (ModelV2): The Model to calculate the loss for. dist_class (Type[ActionDistribution]): The action distribution class. train_batch (SampleBatch): The training data. Returns: TensorType: A single loss tensor. """ target_model = policy.target_models[model] # q network evaluation q_t = compute_q_values( policy, model, train_batch[SampleBatch.CUR_OBS], explore=False, is_training=True) # target q network evalution q_tp1 = compute_q_values( policy, target_model, train_batch[SampleBatch.NEXT_OBS], explore=False, is_training=True) # q scores for actions which we know were selected in the given state. one_hot_selection = F.one_hot(train_batch[SampleBatch.ACTIONS].long(), policy.action_space.n) q_t_selected = torch.sum(q_t * one_hot_selection, 1) # compute estimate of best possible value starting from state at t + 1 dones = train_batch[SampleBatch.DONES].float() q_tp1_best_one_hot_selection = F.one_hot( torch.argmax(q_tp1, 1), policy.action_space.n) q_tp1_best = torch.sum(q_tp1 * q_tp1_best_one_hot_selection, 1) q_tp1_best_masked = (1.0 - dones) * q_tp1_best # compute RHS of bellman equation q_t_selected_target = (train_batch[SampleBatch.REWARDS] + policy.config["gamma"] * q_tp1_best_masked) # Compute the error (Square/Huber). td_error = q_t_selected - q_t_selected_target.detach() loss = torch.mean(huber_loss(td_error)) # Store values for stats function in model (tower), such that for # multi-GPU, we do not override them during the parallel loss phase. model.tower_stats["loss"] = loss # TD-error tensor in final stats # will be concatenated and retrieved for each individual batch item. model.tower_stats["td_error"] = td_error return loss def stats_fn(policy: Policy, batch: SampleBatch) -> Dict[str, TensorType]: return {"loss": torch.mean(torch.stack(policy.get_tower_stats("loss")))} def extra_action_out_fn(policy: Policy, input_dict, state_batches, model, action_dist) -> Dict[str, TensorType]: """Adds q-values to the action out dict.""" return {"q_values": policy.q_values} def setup_late_mixins(policy: Policy, obs_space: gym.spaces.Space, action_space: gym.spaces.Space, config: TrainerConfigDict) -> None: """Call all mixin classes' constructors before SimpleQTorchPolicy initialization. Args: policy (Policy): The Policy object. obs_space (gym.spaces.Space): The Policy's observation space. action_space (gym.spaces.Space): The Policy's action space. config (TrainerConfigDict): The Policy's config. """ TargetNetworkMixin.__init__(policy) SimpleQTorchPolicy = build_policy_class( name="SimpleQPolicy", framework="torch", loss_fn=build_q_losses, get_default_config=lambda: ray.rllib.agents.dqn.simple_q.DEFAULT_CONFIG, stats_fn=stats_fn, extra_action_out_fn=extra_action_out_fn, after_init=setup_late_mixins, make_model_and_action_dist=build_q_model_and_distribution, mixins=[TargetNetworkMixin], action_distribution_fn=get_distribution_inputs_and_class, extra_learn_fetches_fn=concat_multi_gpu_td_errors, )
35.779141
79
0.710905
782
5,832
5.049872
0.272379
0.02431
0.033426
0.028868
0.186123
0.104837
0.056217
0.04153
0.04153
0.04153
0
0.004113
0.20799
5,832
162
80
36
0.850834
0.281036
0
0.10989
0
0
0.012509
0
0
0
0
0
0
1
0.087912
false
0
0.175824
0.021978
0.318681
0
0
0
0
null
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
null
0
0
0
0
0
0
0
0
0
0
0
0
1
0
d49f62cf4c67498959f387338aa3e5ee4e7a2d59
382
py
Python
blender/arm/logicnode/native/LN_detect_mobile_browser.py
niacdoial/armory
3f9b633fbf772017c576a3f77695a6c28d9956e1
[ "Zlib" ]
null
null
null
blender/arm/logicnode/native/LN_detect_mobile_browser.py
niacdoial/armory
3f9b633fbf772017c576a3f77695a6c28d9956e1
[ "Zlib" ]
null
null
null
blender/arm/logicnode/native/LN_detect_mobile_browser.py
niacdoial/armory
3f9b633fbf772017c576a3f77695a6c28d9956e1
[ "Zlib" ]
null
null
null
from arm.logicnode.arm_nodes import * class DetectMobileBrowserNode(ArmLogicTreeNode): """Determines the mobile browser or not (works only for web browsers).""" bl_idname = 'LNDetectMobileBrowserNode' bl_label = 'Detect Mobile Browser' arm_version = 1 def init(self, context): super(DetectMobileBrowserNode, self).init(context) self.add_output('NodeSocketBool', 'Mobile')
34.727273
74
0.777487
45
382
6.488889
0.755556
0.089041
0
0
0
0
0
0
0
0
0
0.002967
0.117801
382
11
75
34.727273
0.863501
0.175393
0
0
0
0
0.212903
0.080645
0
0
0
0
0
1
0.125
false
0
0.125
0
0.75
0
0
0
0
null
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
null
0
0
0
0
0
0
0
0
0
0
0
0
1
0
d4a074467479872c4d6bb6745cf590f7c740594e
29,959
py
Python
corehq/apps/dump_reload/tests/test_sql_dump_load.py
andyasne/commcare-hq
c59a24e57bdd4d2536493f9ecdcc9906f4ae1b88
[ "BSD-3-Clause" ]
471
2015-01-10T02:55:01.000Z
2022-03-29T18:07:18.000Z
corehq/apps/dump_reload/tests/test_sql_dump_load.py
andyasne/commcare-hq
c59a24e57bdd4d2536493f9ecdcc9906f4ae1b88
[ "BSD-3-Clause" ]
14,354
2015-01-01T07:38:23.000Z
2022-03-31T20:55:14.000Z
corehq/apps/dump_reload/tests/test_sql_dump_load.py
andyasne/commcare-hq
c59a24e57bdd4d2536493f9ecdcc9906f4ae1b88
[ "BSD-3-Clause" ]
175
2015-01-06T07:16:47.000Z
2022-03-29T13:27:01.000Z
import inspect import json import uuid from collections import Counter from datetime import datetime from io import StringIO import mock from django.contrib.admin.utils import NestedObjects from django.db import transaction, IntegrityError from django.db.models.signals import post_delete, post_save from django.test import SimpleTestCase, TestCase from nose.tools import nottest from casexml.apps.case.mock import CaseFactory, CaseIndex, CaseStructure from corehq.apps.commtrack.helpers import make_product from corehq.apps.commtrack.tests.util import get_single_balance_block from corehq.apps.domain.models import Domain from corehq.apps.dump_reload.sql import SqlDataDumper, SqlDataLoader from corehq.apps.dump_reload.sql.dump import ( get_model_iterator_builders_to_dump, get_objects_to_dump, ) from corehq.apps.dump_reload.sql.load import ( DefaultDictWithKey, constraint_checks_deferred, ) from corehq.apps.hqcase.utils import submit_case_blocks from corehq.apps.products.models import SQLProduct from corehq.apps.zapier.consts import EventTypes from corehq.apps.zapier.models import ZapierSubscription from corehq.apps.zapier.signals.receivers import ( zapier_subscription_post_delete, ) from corehq.blobs.models import BlobMeta from corehq.form_processor.backends.sql.dbaccessors import LedgerAccessorSQL from corehq.form_processor.interfaces.dbaccessors import ( CaseAccessors, FormAccessors, ) from corehq.form_processor.models import ( CaseTransaction, CommCareCaseIndexSQL, CommCareCaseSQL, LedgerTransaction, LedgerValue, XFormInstanceSQL, ) from corehq.form_processor.tests.utils import ( FormProcessorTestUtils, create_form_for_test, sharded, ) from corehq.messaging.scheduling.scheduling_partitioned.models import ( AlertScheduleInstance, ) class BaseDumpLoadTest(TestCase): @classmethod def setUpClass(cls): post_delete.disconnect(zapier_subscription_post_delete, sender=ZapierSubscription) super(BaseDumpLoadTest, cls).setUpClass() cls.domain_name = uuid.uuid4().hex cls.domain = Domain(name=cls.domain_name) cls.domain.save() cls.default_objects_counts = Counter({}) @classmethod def tearDownClass(cls): cls.domain.delete() super(BaseDumpLoadTest, cls).tearDownClass() post_delete.connect(zapier_subscription_post_delete, sender=ZapierSubscription) def delete_sql_data(self): delete_domain_sql_data_for_dump_load_test(self.domain_name) def tearDown(self): self.delete_sql_data() super(BaseDumpLoadTest, self).tearDown() def _dump_and_load(self, expected_dump_counts, load_filter=None, expected_load_counts=None, dumper_fn=None): expected_load_counts = expected_load_counts or expected_dump_counts expected_dump_counts.update(self.default_objects_counts) models = list(expected_dump_counts) self._check_signals_handle_raw(models) output_stream = StringIO() if dumper_fn: dumper_fn(output_stream) else: SqlDataDumper(self.domain_name, [], []).dump(output_stream) self.delete_sql_data() # make sure that there's no data left in the DB objects_remaining = list(get_objects_to_dump(self.domain_name, [], [])) object_classes = [obj.__class__.__name__ for obj in objects_remaining] counts = Counter(object_classes) self.assertEqual([], objects_remaining, 'Not all data deleted: {}'.format(counts)) # Dump actual_model_counts, dump_lines = self._parse_dump_output(output_stream) expected_model_counts = _normalize_object_counter(expected_dump_counts) self.assertDictEqual(dict(expected_model_counts), dict(actual_model_counts)) # Load loader = SqlDataLoader(object_filter=load_filter) loaded_model_counts = loader.load_objects(dump_lines) normalized_expected_loaded_counts = _normalize_object_counter(expected_load_counts, for_loaded=True) self.assertDictEqual(dict(normalized_expected_loaded_counts), dict(loaded_model_counts)) self.assertEqual(sum(expected_load_counts.values()), sum(loaded_model_counts.values())) return dump_lines def _parse_dump_output(self, output_stream): dump_output = output_stream.getvalue().split('\n') dump_lines = [line.strip() for line in dump_output if line.strip()] actual_model_counts = Counter([json.loads(line)['model'] for line in dump_lines]) return actual_model_counts, dump_lines def _check_signals_handle_raw(self, models): """Ensure that any post_save signal handlers have been updated to handle 'raw' calls.""" whitelist_receivers = [ 'django_digest.models._post_save_persist_partial_digests' ] for model in models: for receiver in post_save._live_receivers(model): receiver_path = receiver.__module__ + '.' + receiver.__name__ if receiver_path in whitelist_receivers: continue args = inspect.getargspec(receiver).args message = 'Signal handler "{}" for model "{}" missing raw arg'.format( receiver, model ) self.assertIn('raw', args, message) @nottest def delete_domain_sql_data_for_dump_load_test(domain_name): for model_class, builder in get_model_iterator_builders_to_dump(domain_name, [], []): for iterator in builder.querysets(): with transaction.atomic(using=iterator.db), \ constraint_checks_deferred(iterator.db): collector = NestedObjects(using=iterator.db) collector.collect(iterator) collector.delete() assert [] == list(get_objects_to_dump(domain_name, [], [])), "Not all SQL objects deleted" @sharded class TestSQLDumpLoadShardedModels(BaseDumpLoadTest): maxDiff = None @classmethod def setUpClass(cls): super(TestSQLDumpLoadShardedModels, cls).setUpClass() cls.factory = CaseFactory(domain=cls.domain_name) cls.form_accessors = FormAccessors(cls.domain_name) cls.case_accessors = CaseAccessors(cls.domain_name) cls.product = make_product(cls.domain_name, 'A Product', 'prodcode_a') cls.default_objects_counts.update({SQLProduct: 1}) @classmethod def tearDownClass(cls): FormProcessorTestUtils.delete_all_cases_forms_ledgers(cls.domain_name) super(TestSQLDumpLoadShardedModels, cls).tearDownClass() def test_dump_load_form(self): expected_object_counts = Counter({ XFormInstanceSQL: 2, BlobMeta: 2 }) pre_forms = [ create_form_for_test(self.domain_name), create_form_for_test(self.domain_name) ] self._dump_and_load(expected_object_counts) form_ids = self.form_accessors.get_all_form_ids_in_domain('XFormInstance') self.assertEqual(set(form_ids), set(form.form_id for form in pre_forms)) for pre_form in pre_forms: post_form = self.form_accessors.get_form(pre_form.form_id) self.assertDictEqual(pre_form.to_json(), post_form.to_json()) def test_sql_dump_load_case(self): expected_object_counts = Counter({ XFormInstanceSQL: 2, BlobMeta: 2, CommCareCaseSQL: 2, CaseTransaction: 3, CommCareCaseIndexSQL: 1 }) pre_cases = self.factory.create_or_update_case( CaseStructure( attrs={'case_name': 'child', 'update': {'age': 3, 'diabetic': False}, 'create': True}, indices=[ CaseIndex(CaseStructure(attrs={'case_name': 'parent', 'update': {'age': 42}, 'create': True})), ] ) ) pre_cases[0] = self.factory.create_or_update_case(CaseStructure( case_id=pre_cases[0].case_id, attrs={'external_id': 'billie jean', 'update': {'name': 'Billie Jean'}} ))[0] self._dump_and_load(expected_object_counts) case_ids = self.case_accessors.get_case_ids_in_domain() self.assertEqual(set(case_ids), set(case.case_id for case in pre_cases)) for pre_case in pre_cases: post_case = self.case_accessors.get_case(pre_case.case_id) self.assertDictEqual(pre_case.to_json(), post_case.to_json()) def test_ledgers(self): expected_object_counts = Counter({ XFormInstanceSQL: 3, BlobMeta: 3, CommCareCaseSQL: 1, CaseTransaction: 3, LedgerValue: 1, LedgerTransaction: 2 }) case = self.factory.create_case() submit_case_blocks([ get_single_balance_block(case.case_id, self.product._id, 10) ], self.domain_name) submit_case_blocks([ get_single_balance_block(case.case_id, self.product._id, 5) ], self.domain_name) pre_ledger_values = LedgerAccessorSQL.get_ledger_values_for_case(case.case_id) pre_ledger_transactions = LedgerAccessorSQL.get_ledger_transactions_for_case(case.case_id) self.assertEqual(1, len(pre_ledger_values)) self.assertEqual(2, len(pre_ledger_transactions)) self._dump_and_load(expected_object_counts) post_ledger_values = LedgerAccessorSQL.get_ledger_values_for_case(case.case_id) post_ledger_transactions = LedgerAccessorSQL.get_ledger_transactions_for_case(case.case_id) self.assertEqual(1, len(post_ledger_values)) self.assertEqual(2, len(post_ledger_transactions)) self.assertEqual(pre_ledger_values[0].ledger_reference, post_ledger_values[0].ledger_reference) self.assertDictEqual(pre_ledger_values[0].to_json(), post_ledger_values[0].to_json()) pre_ledger_transactions = sorted(pre_ledger_transactions, key=lambda t: t.pk) post_ledger_transactions = sorted(post_ledger_transactions, key=lambda t: t.pk) for pre, post in zip(pre_ledger_transactions, post_ledger_transactions): self.assertEqual(str(pre), str(post)) class TestSQLDumpLoad(BaseDumpLoadTest): def test_case_search_config(self): from corehq.apps.case_search.models import CaseSearchConfig, FuzzyProperties expected_object_counts = Counter({ CaseSearchConfig: 1, FuzzyProperties: 2, }) pre_config, created = CaseSearchConfig.objects.get_or_create(pk=self.domain_name) pre_config.enabled = True pre_fuzzies = [ FuzzyProperties(domain=self.domain, case_type='dog', properties=['breed', 'color']), FuzzyProperties(domain=self.domain, case_type='owner', properties=['name']), ] for fuzzy in pre_fuzzies: fuzzy.save() pre_config.fuzzy_properties.set(pre_fuzzies) pre_config.save() self._dump_and_load(expected_object_counts) post_config = CaseSearchConfig.objects.get(domain=self.domain_name) self.assertTrue(post_config.enabled) self.assertEqual(pre_config.fuzzy_properties, post_config.fuzzy_properties) post_fuzzies = FuzzyProperties.objects.filter(domain=self.domain_name) self.assertEqual(set(f.case_type for f in post_fuzzies), {'dog', 'owner'}) def test_users(self): from corehq.apps.users.models import CommCareUser from corehq.apps.users.models import WebUser from django.contrib.auth.models import User expected_object_counts = Counter({User: 3}) ccuser_1 = CommCareUser.create( domain=self.domain_name, username='user_1', password='secret', created_by=None, created_via=None, email='email@example.com', ) ccuser_2 = CommCareUser.create( domain=self.domain_name, username='user_2', password='secret', created_by=None, created_via=None, email='email1@example.com', ) web_user = WebUser.create( domain=self.domain_name, username='webuser_t1', password='secret', created_by=None, created_via=None, email='webuser@example.com', ) self.addCleanup(ccuser_1.delete, self.domain_name, deleted_by=None) self.addCleanup(ccuser_2.delete, self.domain_name, deleted_by=None) self.addCleanup(web_user.delete, self.domain_name, deleted_by=None) self._dump_and_load(expected_object_counts) def test_dump_roles(self): from corehq.apps.users.models import UserRole, Permissions, RoleAssignableBy, RolePermission expected_object_counts = Counter({ UserRole: 2, RolePermission: 11, RoleAssignableBy: 1 }) role1 = UserRole.create(self.domain_name, 'role1') role2 = UserRole.create( self.domain_name, 'role1', permissions=Permissions(edit_web_users=True), assignable_by=[role1.id] ) self.addCleanup(role1.delete) self.addCleanup(role2.delete) self._dump_and_load(expected_object_counts) role1_loaded = UserRole.objects.get(id=role1.id) role2_loaded = UserRole.objects.get(id=role2.id) self.assertEqual(role1_loaded.permissions.to_list(), Permissions().to_list()) self.assertEqual(role1_loaded.assignable_by, []) self.assertEqual(role2_loaded.permissions.to_list(), Permissions(edit_web_users=True).to_list()) self.assertEqual(role2_loaded.assignable_by, [role1_loaded.get_id]) def test_device_logs(self): from corehq.apps.receiverwrapper.util import submit_form_locally from phonelog.models import DeviceReportEntry, ForceCloseEntry, UserEntry, UserErrorEntry from corehq.apps.users.models import CommCareUser from django.contrib.auth.models import User expected_object_counts = Counter({ User: 1, DeviceReportEntry: 7, UserEntry: 1, UserErrorEntry: 2, ForceCloseEntry: 1 }) user = CommCareUser.create( domain=self.domain_name, username='user_1', password='secret', created_by=None, created_via=None, email='email@example.com', uuid='428d454aa9abc74e1964e16d3565d6b6' # match ID in devicelog.xml ) self.addCleanup(user.delete, self.domain_name, deleted_by=None) with open('corehq/ex-submodules/couchforms/tests/data/devicelogs/devicelog.xml', 'rb') as f: xml = f.read() submit_form_locally(xml, self.domain_name) self._dump_and_load(expected_object_counts) def test_demo_user_restore(self): from corehq.apps.users.models import CommCareUser from corehq.apps.ota.models import DemoUserRestore from django.contrib.auth.models import User expected_object_counts = Counter({ User: 1, DemoUserRestore: 1 }) user_id = uuid.uuid4().hex user = CommCareUser.create( domain=self.domain_name, username='user_1', password='secret', created_by=None, created_via=None, email='email@example.com', uuid=user_id ) self.addCleanup(user.delete, self.domain_name, deleted_by=None) DemoUserRestore( demo_user_id=user_id, restore_blob_id=uuid.uuid4().hex, content_length=1027, restore_comment="Test migrate demo user restore" ).save() self._dump_and_load(expected_object_counts) def test_products(self): from corehq.apps.products.models import SQLProduct expected_object_counts = Counter({SQLProduct: 3}) p1 = SQLProduct.objects.create(domain=self.domain_name, product_id='test1', name='test1') p2 = SQLProduct.objects.create(domain=self.domain_name, product_id='test2', name='test2') parchived = SQLProduct.objects.create(domain=self.domain_name, product_id='test3', name='test3', is_archived=True) self._dump_and_load(expected_object_counts) self.assertEqual(2, SQLProduct.active_objects.filter(domain=self.domain_name).count()) all_active = SQLProduct.active_objects.filter(domain=self.domain_name).all() self.assertTrue(p1 in all_active) self.assertTrue(p2 in all_active) self.assertTrue(parchived not in all_active) def test_location_type(self): from corehq.apps.locations.models import LocationType from corehq.apps.locations.tests.test_location_types import make_loc_type expected_object_counts = Counter({LocationType: 7}) state = make_loc_type('state', domain=self.domain_name) district = make_loc_type('district', state, domain=self.domain_name) section = make_loc_type('section', district, domain=self.domain_name) block = make_loc_type('block', district, domain=self.domain_name) center = make_loc_type('center', block, domain=self.domain_name) county = make_loc_type('county', state, domain=self.domain_name) city = make_loc_type('city', county, domain=self.domain_name) self._dump_and_load(expected_object_counts) hierarchy = LocationType.objects.full_hierarchy(self.domain_name) desired_hierarchy = { state.id: ( state, { district.id: ( district, { section.id: (section, {}), block.id: (block, { center.id: (center, {}), }), }, ), county.id: ( county, {city.id: (city, {})}, ), }, ), } self.assertEqual(hierarchy, desired_hierarchy) def test_location(self): from corehq.apps.locations.models import LocationType, SQLLocation from corehq.apps.locations.tests.util import setup_locations_and_types expected_object_counts = Counter({LocationType: 3, SQLLocation: 11}) location_type_names = ['province', 'district', 'city'] location_structure = [ ('Western Cape', [ ('Cape Winelands', [ ('Stellenbosch', []), ('Paarl', []), ]), ('Cape Town', [ ('Cape Town City', []), ]) ]), ('Gauteng', [ ('Ekurhuleni ', [ ('Alberton', []), ('Benoni', []), ('Springs', []), ]), ]), ] location_types, locations = setup_locations_and_types( self.domain_name, location_type_names, [], location_structure, ) self._dump_and_load(expected_object_counts) names = ['Cape Winelands', 'Paarl', 'Cape Town'] location_ids = [locations[name].location_id for name in names] result = SQLLocation.objects.get_locations_and_children(location_ids) self.assertItemsEqual( [loc.name for loc in result], ['Cape Winelands', 'Stellenbosch', 'Paarl', 'Cape Town', 'Cape Town City'] ) result = SQLLocation.objects.get_locations_and_children([locations['Gauteng'].location_id]) self.assertItemsEqual( [loc.name for loc in result], ['Gauteng', 'Ekurhuleni ', 'Alberton', 'Benoni', 'Springs'] ) def test_sms(self): from corehq.apps.sms.models import PhoneNumber, MessagingEvent, MessagingSubEvent expected_object_counts = Counter({PhoneNumber: 1, MessagingEvent: 1, MessagingSubEvent: 1}) phone_number = PhoneNumber( domain=self.domain_name, owner_doc_type='CommCareCase', owner_id='fake-owner-id1', phone_number='99912341234', backend_id=None, ivr_backend_id=None, verified=True, is_two_way=True, pending_verification=False, contact_last_modified=datetime.utcnow() ) phone_number.save() event = MessagingEvent.objects.create( domain=self.domain_name, date=datetime.utcnow(), source=MessagingEvent.SOURCE_REMINDER, content_type=MessagingEvent.CONTENT_SMS, status=MessagingEvent.STATUS_COMPLETED ) MessagingSubEvent.objects.create( parent=event, date=datetime.utcnow(), recipient_type=MessagingEvent.RECIPIENT_CASE, content_type=MessagingEvent.CONTENT_SMS, status=MessagingEvent.STATUS_COMPLETED ) self._dump_and_load(expected_object_counts) def test_message_scheduling(self): AlertScheduleInstance( schedule_instance_id=uuid.uuid4(), domain=self.domain_name, recipient_type='CommCareUser', recipient_id=uuid.uuid4().hex, current_event_num=0, schedule_iteration_num=1, next_event_due=datetime(2017, 3, 1), active=True, alert_schedule_id=uuid.uuid4(), ).save() self._dump_and_load({AlertScheduleInstance: 1}) def test_mobile_backend(self): from corehq.apps.sms.models import ( SQLMobileBackend, SQLMobileBackendMapping, ) domain_backend = SQLMobileBackend.objects.create( domain=self.domain_name, name='test-domain-mobile-backend', display_name='Test Domain Mobile Backend', hq_api_id='TDMB', inbound_api_key='test-domain-mobile-backend-inbound-api-key', supported_countries=["*"], backend_type=SQLMobileBackend.SMS, is_global=False, ) SQLMobileBackendMapping.objects.create( domain=self.domain_name, backend=domain_backend, backend_type=SQLMobileBackend.SMS, prefix='123', ) global_backend = SQLMobileBackend.objects.create( domain=None, name='test-global-mobile-backend', display_name='Test Global Mobile Backend', hq_api_id='TGMB', inbound_api_key='test-global-mobile-backend-inbound-api-key', supported_countries=["*"], backend_type=SQLMobileBackend.SMS, is_global=True, ) SQLMobileBackendMapping.objects.create( domain=self.domain_name, backend=global_backend, backend_type=SQLMobileBackend.SMS, prefix='*', ) self._dump_and_load({ SQLMobileBackendMapping: 1, SQLMobileBackend: 1, }) self.assertEqual(SQLMobileBackend.objects.first().domain, self.domain_name) self.assertEqual(SQLMobileBackendMapping.objects.first().domain, self.domain_name) def test_case_importer(self): from corehq.apps.case_importer.tracking.models import ( CaseUploadFileMeta, CaseUploadFormRecord, CaseUploadRecord, ) upload_file_meta = CaseUploadFileMeta.objects.create( identifier=uuid.uuid4().hex, filename='picture.jpg', length=1024, ) case_upload_record = CaseUploadRecord.objects.create( domain=self.domain_name, upload_id=uuid.uuid4(), task_id=uuid.uuid4(), couch_user_id=uuid.uuid4().hex, case_type='person', upload_file_meta=upload_file_meta, ) CaseUploadFormRecord.objects.create( case_upload_record=case_upload_record, form_id=uuid.uuid4().hex, ) self._dump_and_load(Counter({ CaseUploadFileMeta: 1, CaseUploadRecord: 1, CaseUploadFormRecord: 1, })) def test_transifex(self): from corehq.apps.translations.models import TransifexProject, TransifexOrganization org = TransifexOrganization.objects.create(slug='test', name='demo', api_token='123') TransifexProject.objects.create( organization=org, slug='testp', name='demop', domain=self.domain_name ) TransifexProject.objects.create( organization=org, slug='testp1', name='demop1', domain=self.domain_name ) self._dump_and_load(Counter({TransifexOrganization: 1, TransifexProject: 2})) def test_filtered_dump_load(self): from corehq.apps.locations.tests.test_location_types import make_loc_type from corehq.apps.products.models import SQLProduct from corehq.apps.locations.models import LocationType make_loc_type('state', domain=self.domain_name) SQLProduct.objects.create(domain=self.domain_name, product_id='test1', name='test1') expected_object_counts = Counter({LocationType: 1, SQLProduct: 1}) self._dump_and_load(expected_object_counts, load_filter='sqlproduct', expected_load_counts=Counter({SQLProduct: 1})) self.assertEqual(0, LocationType.objects.count()) def test_sms_content(self): from corehq.messaging.scheduling.models import AlertSchedule, SMSContent, AlertEvent from corehq.messaging.scheduling.scheduling_partitioned.dbaccessors import \ delete_alert_schedule_instances_for_schedule schedule = AlertSchedule.create_simple_alert(self.domain, SMSContent()) schedule.set_custom_alert( [ (AlertEvent(minutes_to_wait=5), SMSContent()), (AlertEvent(minutes_to_wait=15), SMSContent()), ] ) self.addCleanup(lambda: delete_alert_schedule_instances_for_schedule(AlertScheduleInstance, schedule.schedule_id)) self._dump_and_load(Counter({AlertSchedule: 1, AlertEvent: 2, SMSContent: 2})) def test_zapier_subscription(self): ZapierSubscription.objects.create( domain=self.domain_name, case_type='case_type', event_name=EventTypes.NEW_CASE, url='example.com', user_id='user_id', ) self._dump_and_load(Counter({ZapierSubscription: 1})) @mock.patch("corehq.apps.dump_reload.sql.load.ENQUEUE_TIMEOUT", 1) class TestSqlLoadWithError(BaseDumpLoadTest): def setUp(self): self.products = [ SQLProduct.objects.create(domain=self.domain_name, product_id='test1', name='test1'), SQLProduct.objects.create(domain=self.domain_name, product_id='test2', name='test2'), SQLProduct.objects.create(domain=self.domain_name, product_id='test3', name='test3'), ] def test_load_error_queue_full(self): """Blocks when sending 'test3'""" self._load_with_errors(chunk_size=1) def test_load_error_queue_full_on_terminate(self): """Blocks when sending ``None`` into the queue to 'terminate' it.""" self._load_with_errors(chunk_size=2) def _load_with_errors(self, chunk_size): output_stream = StringIO() SqlDataDumper(self.domain_name, [], []).dump(output_stream) self.delete_sql_data() # resave the product to force an error self.products[0].save() actual_model_counts, dump_lines = self._parse_dump_output(output_stream) self.assertEqual(actual_model_counts['products.sqlproduct'], 3) loader = SqlDataLoader() with self.assertRaises(IntegrityError),\ mock.patch("corehq.apps.dump_reload.sql.load.CHUNK_SIZE", chunk_size): # patch the chunk size so that the queue blocks loader.load_objects(dump_lines) class DefaultDictWithKeyTests(SimpleTestCase): def test_intended_use_case(self): def enlist(item): return [item] greasy_spoon = DefaultDictWithKey(enlist) self.assertEqual(greasy_spoon['spam'], ['spam']) greasy_spoon['spam'].append('spam') self.assertEqual(greasy_spoon['spam'], ['spam', 'spam']) def test_not_enough_params(self): def empty_list(): return [] greasy_spoon = DefaultDictWithKey(empty_list) with self.assertRaisesRegex( TypeError, r'empty_list\(\) takes 0 positional arguments but 1 was given' ): greasy_spoon['spam'] def test_too_many_params(self): def appender(item1, item2): return [item1, item2] greasy_spoon = DefaultDictWithKey(appender) with self.assertRaisesRegex( TypeError, r"appender\(\) missing 1 required positional argument: 'item2'" ): greasy_spoon['spam'] def test_no_factory(self): greasy_spoon = DefaultDictWithKey() with self.assertRaisesRegex( TypeError, "'NoneType' object is not callable" ): greasy_spoon['spam'] def _normalize_object_counter(counter, for_loaded=False): """Converts a <Model Class> keyed counter to an model label keyed counter""" def _model_class_to_label(model_class): label = '{}.{}'.format(model_class._meta.app_label, model_class.__name__) return label if for_loaded else label.lower() return Counter({ _model_class_to_label(model_class): count for model_class, count in counter.items() })
38.310742
124
0.647118
3,249
29,959
5.689751
0.158203
0.035703
0.041653
0.038948
0.406199
0.329547
0.251325
0.21665
0.169209
0.132803
0
0.008958
0.258487
29,959
781
125
38.359795
0.823183
0.013685
0
0.228178
0
0
0.055768
0.012909
0
0
0
0
0.062787
1
0.064319
false
0.007657
0.087289
0.004594
0.171516
0
0
0
0
null
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
null
0
0
0
0
0
0
0
0
0
0
0
0
1
0
d4a08e8d4977972540a2be8547db892cc6d2f3ab
4,561
py
Python
tests/keras/test_activations.py
the-moliver/keras
4fa7e5d454dd4f3f33f1d756a2a8659f2e789141
[ "MIT" ]
150
2017-01-15T15:32:23.000Z
2021-11-23T15:07:55.000Z
tests/keras/test_activations.py
wdw110/keras
4fa7e5d454dd4f3f33f1d756a2a8659f2e789141
[ "MIT" ]
40
2017-01-15T15:41:05.000Z
2020-11-16T13:15:50.000Z
tests/keras/test_activations.py
wdw110/keras
4fa7e5d454dd4f3f33f1d756a2a8659f2e789141
[ "MIT" ]
38
2017-01-15T22:04:06.000Z
2019-11-01T22:35:35.000Z
import pytest import numpy as np from numpy.testing import assert_allclose from keras import backend as K from keras import activations def get_standard_values(): ''' These are just a set of floats used for testing the activation functions, and are useful in multiple tests. ''' return np.array([[0, 0.1, 0.5, 0.9, 1.0]], dtype=K.floatx()) def test_softmax(): ''' Test using a reference implementation of softmax ''' def softmax(values): m = np.max(values) e = np.exp(values - m) return e / np.sum(e) x = K.placeholder(ndim=2) f = K.function([x], [activations.softmax(x)]) test_values = get_standard_values() result = f([test_values])[0] expected = softmax(test_values) assert_allclose(result, expected, rtol=1e-05) def test_time_distributed_softmax(): x = K.placeholder(shape=(1, 1, 5)) f = K.function([x], [activations.softmax(x)]) test_values = get_standard_values() test_values = np.reshape(test_values, (1, 1, np.size(test_values))) f([test_values])[0] def test_softplus(): ''' Test using a reference softplus implementation ''' def softplus(x): return np.log(np.ones_like(x) + np.exp(x)) x = K.placeholder(ndim=2) f = K.function([x], [activations.softplus(x)]) test_values = get_standard_values() result = f([test_values])[0] expected = softplus(test_values) assert_allclose(result, expected, rtol=1e-05) def test_softsign(): ''' Test using a reference softsign implementation ''' def softsign(x): return np.divide(x, np.ones_like(x) + np.absolute(x)) x = K.placeholder(ndim=2) f = K.function([x], [activations.softsign(x)]) test_values = get_standard_values() result = f([test_values])[0] expected = softsign(test_values) assert_allclose(result, expected, rtol=1e-05) def test_sigmoid(): ''' Test using a numerically stable reference sigmoid implementation ''' def ref_sigmoid(x): if x >= 0: return 1 / (1 + np.exp(-x)) else: z = np.exp(x) return z / (1 + z) sigmoid = np.vectorize(ref_sigmoid) x = K.placeholder(ndim=2) f = K.function([x], [activations.sigmoid(x)]) test_values = get_standard_values() result = f([test_values])[0] expected = sigmoid(test_values) assert_allclose(result, expected, rtol=1e-05) def test_hard_sigmoid(): ''' Test using a reference hard sigmoid implementation ''' def ref_hard_sigmoid(x): ''' Reference hard sigmoid with slope and shift values from theano, see https://github.com/Theano/Theano/blob/master/theano/tensor/nnet/sigm.py ''' x = (x * 0.2) + 0.5 z = 0.0 if x <= 0 else (1.0 if x >= 1 else x) return z hard_sigmoid = np.vectorize(ref_hard_sigmoid) x = K.placeholder(ndim=2) f = K.function([x], [activations.hard_sigmoid(x)]) test_values = get_standard_values() result = f([test_values])[0] expected = hard_sigmoid(test_values) assert_allclose(result, expected, rtol=1e-05) def test_relu(): ''' Relu implementation doesn't depend on the value being a theano variable. Testing ints, floats and theano tensors. ''' x = K.placeholder(ndim=2) f = K.function([x], [activations.relu(x)]) test_values = get_standard_values() result = f([test_values])[0] # because no negatives in test values assert_allclose(result, test_values, rtol=1e-05) def test_elu(): x = K.placeholder(ndim=2) f = K.function([x], [activations.elu(x, 0.5)]) test_values = get_standard_values() result = f([test_values])[0] # because no negatives in test values assert_allclose(result, test_values, rtol=1e-05) negative_values = np.array([[-1, -2]], dtype=K.floatx()) result = f([negative_values])[0] true_result = (np.exp(negative_values) - 1) / 2 assert_allclose(result, true_result) def test_tanh(): test_values = get_standard_values() x = K.placeholder(ndim=2) exp = activations.tanh(x) f = K.function([x], [exp]) result = f([test_values])[0] expected = np.tanh(test_values) assert_allclose(result, expected, rtol=1e-05) def test_linear(): ''' This function does no input validation, it just returns the thing that was passed in. ''' xs = [1, 5, True, None, 'foo'] for x in xs: assert(x == activations.linear(x)) if __name__ == '__main__': pytest.main([__file__])
26.062857
79
0.635825
648
4,561
4.320988
0.203704
0.110714
0.060714
0.035357
0.466786
0.438929
0.429643
0.429643
0.429643
0.429643
0
0.022197
0.229555
4,561
174
80
26.212644
0.774616
0.170796
0
0.357143
0
0
0.003041
0
0
0
0
0
0.112245
1
0.163265
false
0
0.05102
0.020408
0.285714
0
0
0
0
null
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
null
0
0
0
0
0
0
0
0
0
0
0
0
1
0
d4a19a6793c7b81c31ff51744f9dee445aa534f8
1,685
py
Python
tests/test_cli/test_generate/test_generate.py
lrahmani/agents-aea
9bd1d51530fc21bf41b5adea031cda19a94b048b
[ "Apache-2.0" ]
null
null
null
tests/test_cli/test_generate/test_generate.py
lrahmani/agents-aea
9bd1d51530fc21bf41b5adea031cda19a94b048b
[ "Apache-2.0" ]
null
null
null
tests/test_cli/test_generate/test_generate.py
lrahmani/agents-aea
9bd1d51530fc21bf41b5adea031cda19a94b048b
[ "Apache-2.0" ]
null
null
null
# -*- coding: utf-8 -*- # ------------------------------------------------------------------------------ # # Copyright 2018-2019 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.cli.generate sub-module.""" from unittest import TestCase, mock from aea.cli.generate import _generate_item from tests.test_cli.tools_for_testing import ContextMock def _raise_file_exists(self, *args, **kwargs): raise FileExistsError() @mock.patch("builtins.open", mock.mock_open()) @mock.patch("aea.cli.generate.ConfigLoader") @mock.patch("aea.cli.generate.os.path.join", return_value="joined-path") @mock.patch("aea.cli.generate.ProtocolGenerator.generate", _raise_file_exists) class GenerateItemTestCase(TestCase): """Test case for fetch_agent_locally method.""" def test__generate_item_file_exists(self, *mocks): """Test for fetch_agent_locally method positive result.""" ctx_mock = ContextMock() with self.assertRaises(SystemExit): _generate_item(ctx_mock, "protocol", "path")
37.444444
80
0.665282
212
1,685
5.165094
0.54717
0.054795
0.063927
0.041096
0.110502
0
0
0
0
0
0
0.00904
0.146588
1,685
44
81
38.295455
0.752434
0.550148
0
0
0
0
0.188966
0.13931
0
0
0
0
0.071429
1
0.142857
false
0
0.214286
0
0.428571
0
0
0
0
null
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
null
0
0
0
0
0
0
0
0
0
0
0
0
1
0
d4a21ef2eb21f79e91184165f8bb407caaf1dcb1
17,126
py
Python
sphinx/ext/napoleon/__init__.py
PeerHerholz/smobsc
db34d2bb96b80579bd4a3f4c198a6b524c5a134a
[ "BSD-2-Clause" ]
3
2019-06-11T09:42:08.000Z
2020-03-10T15:57:09.000Z
sphinx/ext/napoleon/__init__.py
PeerHerholz/smobsc
db34d2bb96b80579bd4a3f4c198a6b524c5a134a
[ "BSD-2-Clause" ]
12
2019-01-09T15:43:57.000Z
2020-01-21T10:46:30.000Z
sphinx/ext/napoleon/__init__.py
PeerHerholz/smobsc
db34d2bb96b80579bd4a3f4c198a6b524c5a134a
[ "BSD-2-Clause" ]
10
2019-02-04T11:49:35.000Z
2020-03-21T13:32:20.000Z
""" sphinx.ext.napoleon ~~~~~~~~~~~~~~~~~~~ Support for NumPy and Google style docstrings. :copyright: Copyright 2007-2018 by the Sphinx team, see AUTHORS. :license: BSD, see LICENSE for details. """ from sphinx import __display_version__ as __version__ from sphinx.application import Sphinx from sphinx.ext.napoleon.docstring import GoogleDocstring, NumpyDocstring if False: # For type annotation from typing import Any, Dict, List # NOQA class Config: """Sphinx napoleon extension settings in `conf.py`. Listed below are all the settings used by napoleon and their default values. These settings can be changed in the Sphinx `conf.py` file. Make sure that "sphinx.ext.napoleon" is enabled in `conf.py`:: # conf.py # Add any Sphinx extension module names here, as strings extensions = ['sphinx.ext.napoleon'] # Napoleon settings napoleon_google_docstring = True napoleon_numpy_docstring = True napoleon_include_init_with_doc = False napoleon_include_private_with_doc = False napoleon_include_special_with_doc = False napoleon_use_admonition_for_examples = False napoleon_use_admonition_for_notes = False napoleon_use_admonition_for_references = False napoleon_use_ivar = False napoleon_use_param = True napoleon_use_rtype = True napoleon_use_keyword = True napoleon_custom_sections = None .. _Google style: https://google.github.io/styleguide/pyguide.html .. _NumPy style: https://github.com/numpy/numpy/blob/master/doc/HOWTO_DOCUMENT.rst.txt Attributes ---------- napoleon_google_docstring : :obj:`bool` (Defaults to True) True to parse `Google style`_ docstrings. False to disable support for Google style docstrings. napoleon_numpy_docstring : :obj:`bool` (Defaults to True) True to parse `NumPy style`_ docstrings. False to disable support for NumPy style docstrings. napoleon_include_init_with_doc : :obj:`bool` (Defaults to False) True to list ``__init___`` docstrings separately from the class docstring. False to fall back to Sphinx's default behavior, which considers the ``__init___`` docstring as part of the class documentation. **If True**:: def __init__(self): \"\"\" This will be included in the docs because it has a docstring \"\"\" def __init__(self): # This will NOT be included in the docs napoleon_include_private_with_doc : :obj:`bool` (Defaults to False) True to include private members (like ``_membername``) with docstrings in the documentation. False to fall back to Sphinx's default behavior. **If True**:: def _included(self): \"\"\" This will be included in the docs because it has a docstring \"\"\" pass def _skipped(self): # This will NOT be included in the docs pass napoleon_include_special_with_doc : :obj:`bool` (Defaults to False) True to include special members (like ``__membername__``) with docstrings in the documentation. False to fall back to Sphinx's default behavior. **If True**:: def __str__(self): \"\"\" This will be included in the docs because it has a docstring \"\"\" return unicode(self).encode('utf-8') def __unicode__(self): # This will NOT be included in the docs return unicode(self.__class__.__name__) napoleon_use_admonition_for_examples : :obj:`bool` (Defaults to False) True to use the ``.. admonition::`` directive for the **Example** and **Examples** sections. False to use the ``.. rubric::`` directive instead. One may look better than the other depending on what HTML theme is used. This `NumPy style`_ snippet will be converted as follows:: Example ------- This is just a quick example **If True**:: .. admonition:: Example This is just a quick example **If False**:: .. rubric:: Example This is just a quick example napoleon_use_admonition_for_notes : :obj:`bool` (Defaults to False) True to use the ``.. admonition::`` directive for **Notes** sections. False to use the ``.. rubric::`` directive instead. Note ---- The singular **Note** section will always be converted to a ``.. note::`` directive. See Also -------- :attr:`napoleon_use_admonition_for_examples` napoleon_use_admonition_for_references : :obj:`bool` (Defaults to False) True to use the ``.. admonition::`` directive for **References** sections. False to use the ``.. rubric::`` directive instead. See Also -------- :attr:`napoleon_use_admonition_for_examples` napoleon_use_ivar : :obj:`bool` (Defaults to False) True to use the ``:ivar:`` role for instance variables. False to use the ``.. attribute::`` directive instead. This `NumPy style`_ snippet will be converted as follows:: Attributes ---------- attr1 : int Description of `attr1` **If True**:: :ivar attr1: Description of `attr1` :vartype attr1: int **If False**:: .. attribute:: attr1 Description of `attr1` :type: int napoleon_use_param : :obj:`bool` (Defaults to True) True to use a ``:param:`` role for each function parameter. False to use a single ``:parameters:`` role for all the parameters. This `NumPy style`_ snippet will be converted as follows:: Parameters ---------- arg1 : str Description of `arg1` arg2 : int, optional Description of `arg2`, defaults to 0 **If True**:: :param arg1: Description of `arg1` :type arg1: str :param arg2: Description of `arg2`, defaults to 0 :type arg2: int, optional **If False**:: :parameters: * **arg1** (*str*) -- Description of `arg1` * **arg2** (*int, optional*) -- Description of `arg2`, defaults to 0 napoleon_use_keyword : :obj:`bool` (Defaults to True) True to use a ``:keyword:`` role for each function keyword argument. False to use a single ``:keyword arguments:`` role for all the keywords. This behaves similarly to :attr:`napoleon_use_param`. Note unlike docutils, ``:keyword:`` and ``:param:`` will not be treated the same way - there will be a separate "Keyword Arguments" section, rendered in the same fashion as "Parameters" section (type links created if possible) See Also -------- :attr:`napoleon_use_param` napoleon_use_rtype : :obj:`bool` (Defaults to True) True to use the ``:rtype:`` role for the return type. False to output the return type inline with the description. This `NumPy style`_ snippet will be converted as follows:: Returns ------- bool True if successful, False otherwise **If True**:: :returns: True if successful, False otherwise :rtype: bool **If False**:: :returns: *bool* -- True if successful, False otherwise napoleon_custom_sections : :obj:`list` (Defaults to None) Add a list of custom sections to include, expanding the list of parsed sections. The entries can either be strings or tuples, depending on the intention: * To create a custom "generic" section, just pass a string. * To create an alias for an existing section, pass a tuple containing the alias name and the original, in that order. If an entry is just a string, it is interpreted as a header for a generic section. If the entry is a tuple/list/indexed container, the first entry is the name of the section, the second is the section key to emulate. """ _config_values = { 'napoleon_google_docstring': (True, 'env'), 'napoleon_numpy_docstring': (True, 'env'), 'napoleon_include_init_with_doc': (False, 'env'), 'napoleon_include_private_with_doc': (False, 'env'), 'napoleon_include_special_with_doc': (False, 'env'), 'napoleon_use_admonition_for_examples': (False, 'env'), 'napoleon_use_admonition_for_notes': (False, 'env'), 'napoleon_use_admonition_for_references': (False, 'env'), 'napoleon_use_ivar': (False, 'env'), 'napoleon_use_param': (True, 'env'), 'napoleon_use_rtype': (True, 'env'), 'napoleon_use_keyword': (True, 'env'), 'napoleon_custom_sections': (None, 'env') } def __init__(self, **settings): # type: (Any) -> None for name, (default, rebuild) in self._config_values.items(): setattr(self, name, default) for name, value in settings.items(): setattr(self, name, value) def setup(app): # type: (Sphinx) -> Dict[str, Any] """Sphinx extension setup function. When the extension is loaded, Sphinx imports this module and executes the ``setup()`` function, which in turn notifies Sphinx of everything the extension offers. Parameters ---------- app : sphinx.application.Sphinx Application object representing the Sphinx process See Also -------- `The Sphinx documentation on Extensions <http://sphinx-doc.org/extensions.html>`_ `The Extension Tutorial <http://sphinx-doc.org/extdev/tutorial.html>`_ `The Extension API <http://sphinx-doc.org/extdev/appapi.html>`_ """ if not isinstance(app, Sphinx): # probably called by tests return {'version': __version__, 'parallel_read_safe': True} _patch_python_domain() app.setup_extension('sphinx.ext.autodoc') app.connect('autodoc-process-docstring', _process_docstring) app.connect('autodoc-skip-member', _skip_member) for name, (default, rebuild) in Config._config_values.items(): app.add_config_value(name, default, rebuild) return {'version': __version__, 'parallel_read_safe': True} def _patch_python_domain(): # type: () -> None try: from sphinx.domains.python import PyTypedField except ImportError: pass else: import sphinx.domains.python from sphinx.locale import _ for doc_field in sphinx.domains.python.PyObject.doc_field_types: if doc_field.name == 'parameter': doc_field.names = ('param', 'parameter', 'arg', 'argument') break sphinx.domains.python.PyObject.doc_field_types.append( PyTypedField('keyword', label=_('Keyword Arguments'), names=('keyword', 'kwarg', 'kwparam'), typerolename='obj', typenames=('paramtype', 'kwtype'), can_collapse=True)) def _process_docstring(app, what, name, obj, options, lines): # type: (Sphinx, str, str, Any, Any, List[str]) -> None """Process the docstring for a given python object. Called when autodoc has read and processed a docstring. `lines` is a list of docstring lines that `_process_docstring` modifies in place to change what Sphinx outputs. The following settings in conf.py control what styles of docstrings will be parsed: * ``napoleon_google_docstring`` -- parse Google style docstrings * ``napoleon_numpy_docstring`` -- parse NumPy style docstrings Parameters ---------- app : sphinx.application.Sphinx Application object representing the Sphinx process. what : str A string specifying the type of the object to which the docstring belongs. Valid values: "module", "class", "exception", "function", "method", "attribute". name : str The fully qualified name of the object. obj : module, class, exception, function, method, or attribute The object to which the docstring belongs. options : sphinx.ext.autodoc.Options The options given to the directive: an object with attributes inherited_members, undoc_members, show_inheritance and noindex that are True if the flag option of same name was given to the auto directive. lines : list of str The lines of the docstring, see above. .. note:: `lines` is modified *in place* """ result_lines = lines docstring = None # type: GoogleDocstring if app.config.napoleon_numpy_docstring: docstring = NumpyDocstring(result_lines, app.config, app, what, name, obj, options) result_lines = docstring.lines() if app.config.napoleon_google_docstring: docstring = GoogleDocstring(result_lines, app.config, app, what, name, obj, options) result_lines = docstring.lines() lines[:] = result_lines[:] def _skip_member(app, what, name, obj, skip, options): # type: (Sphinx, str, str, Any, bool, Any) -> bool """Determine if private and special class members are included in docs. The following settings in conf.py determine if private and special class members or init methods are included in the generated documentation: * ``napoleon_include_init_with_doc`` -- include init methods if they have docstrings * ``napoleon_include_private_with_doc`` -- include private members if they have docstrings * ``napoleon_include_special_with_doc`` -- include special members if they have docstrings Parameters ---------- app : sphinx.application.Sphinx Application object representing the Sphinx process what : str A string specifying the type of the object to which the member belongs. Valid values: "module", "class", "exception", "function", "method", "attribute". name : str The name of the member. obj : module, class, exception, function, method, or attribute. For example, if the member is the __init__ method of class A, then `obj` will be `A.__init__`. skip : bool A boolean indicating if autodoc will skip this member if `_skip_member` does not override the decision options : sphinx.ext.autodoc.Options The options given to the directive: an object with attributes inherited_members, undoc_members, show_inheritance and noindex that are True if the flag option of same name was given to the auto directive. Returns ------- bool True if the member should be skipped during creation of the docs, False if it should be included in the docs. """ has_doc = getattr(obj, '__doc__', False) is_member = (what == 'class' or what == 'exception' or what == 'module') if name != '__weakref__' and has_doc and is_member: cls_is_owner = False if what == 'class' or what == 'exception': qualname = getattr(obj, '__qualname__', '') cls_path, _, _ = qualname.rpartition('.') if cls_path: try: if '.' in cls_path: import importlib import functools mod = importlib.import_module(obj.__module__) mod_path = cls_path.split('.') cls = functools.reduce(getattr, mod_path, mod) else: cls = obj.__globals__[cls_path] except Exception: cls_is_owner = False else: cls_is_owner = (cls and hasattr(cls, name) and # type: ignore name in cls.__dict__) else: cls_is_owner = False if what == 'module' or cls_is_owner: is_init = (name == '__init__') is_special = (not is_init and name.startswith('__') and name.endswith('__')) is_private = (not is_init and not is_special and name.startswith('_')) inc_init = app.config.napoleon_include_init_with_doc inc_special = app.config.napoleon_include_special_with_doc inc_private = app.config.napoleon_include_private_with_doc if ((is_special and inc_special) or (is_private and inc_private) or (is_init and inc_init)): return False return None
36.515991
88
0.608782
2,005
17,126
5.017955
0.17606
0.027333
0.017891
0.020276
0.453434
0.391711
0.321539
0.274426
0.242719
0.189643
0
0.00275
0.299428
17,126
468
89
36.594017
0.835806
0.648663
0
0.144231
0
0
0.137715
0.06087
0
0
0
0.008547
0
1
0.048077
false
0.009615
0.105769
0
0.211538
0
0
0
0
null
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
null
0
0
0
0
0
0
0
0
0
0
0
0
1
0
d4a24c39597d568e3ab31f3730cb741839a01aff
2,390
py
Python
plugins/similarity/rdkit/tanimoto/lbvs-entry.py
skodapetr/viset
87863ed6cde63392b2d503ceda53bb2cea367d69
[ "MIT" ]
1
2018-12-28T19:36:04.000Z
2018-12-28T19:36:04.000Z
plugins/similarity/rdkit/tanimoto/lbvs-entry.py
skodapetr/viset
87863ed6cde63392b2d503ceda53bb2cea367d69
[ "MIT" ]
14
2017-11-15T17:45:58.000Z
2018-12-10T17:52:23.000Z
plugins/similarity/rdkit/tanimoto/lbvs-entry.py
skodapetr/viset
87863ed6cde63392b2d503ceda53bb2cea367d69
[ "MIT" ]
null
null
null
#!/usr/bin/env python # -*- coding: utf-8 -*- import json from rdkit import DataStructs import plugin_api __license__ = "X11" class LbvsEntry(plugin_api.PluginInterface): """ Compute Tanimoto similarity. """ def __init__(self): self.stream = None self.counter = 0 self.first_entry = False def execute(self, files): query = LbvsEntry._load_file(files["query_file"]) database = LbvsEntry._load_file(files["database_file"]) with open(files["output_file"], "w") as stream: self.stream = stream self.write_output_header() self.compute_and_write_similarities_for_items(query, database) self.write_output_footer() def write_output_header(self): self.stream.write('{"data":[') def write_output_footer(self): self.stream.write(']}') def compute_and_write_similarities_for_items(self, query, database): self.first_entry = True for query_item in query: for database_item in database: self._write_separator_if_needed() self.first_entry = False self._compute_and_write_similarity(query_item, database_item) def _write_separator_if_needed(self): if not self.first_entry: self.stream.write(",") def _compute_and_write_similarity(self, query, item): similarity = LbvsEntry._compute_similarity( query["value"], item["value"]) json.dump({ "query": query["id"], "id": item["id"], "value": similarity }, self.stream) @staticmethod def _load_file(path): with open(path) as stream: return [{ "id": item["id"], "value": LbvsEntry._as_sparse_vector(item["value"]) } for item in json.load(stream)["data"]] @staticmethod def _as_sparse_vector(data): # Use max integer value as a size. vector = DataStructs.cDataStructs.IntSparseIntVect(8388608) for key in data: vector[(int)(key)] = (int)(data[key]) return vector @staticmethod def _compute_similarity(left, right): return DataStructs.TanimotoSimilarity(left, right) def get_metadata(self) -> object: return { "id": "rdkit/tanimoto" }
29.506173
77
0.599582
264
2,390
5.155303
0.310606
0.044085
0.041146
0.027921
0.127112
0.088905
0.048494
0
0
0
0
0.006494
0.291213
2,390
80
78
29.875
0.79693
0.043515
0
0.118644
0
0
0.048501
0
0
0
0
0
0
1
0.186441
false
0
0.050847
0.033898
0.322034
0
0
0
0
null
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
null
0
0
0
0
0
0
0
0
0
0
0
0
1
0
d4a3f90c44e54f8024d6bee8196a0b29bb2aed61
2,849
py
Python
mall_spider/spiders/actions/proxy_service.py
524243642/taobao_spider
9cdaed1c7a67fc1f35ee2af2e18313cedf3b1e5e
[ "Unlicense" ]
12
2019-06-06T12:23:08.000Z
2021-06-15T17:50:07.000Z
mall_spider/spiders/actions/proxy_service.py
524243642/mall_spider
9cdaed1c7a67fc1f35ee2af2e18313cedf3b1e5e
[ "Unlicense" ]
3
2021-03-31T19:02:47.000Z
2022-02-11T03:43:15.000Z
mall_spider/spiders/actions/proxy_service.py
524243642/taobao_spider
9cdaed1c7a67fc1f35ee2af2e18313cedf3b1e5e
[ "Unlicense" ]
5
2019-09-17T03:55:56.000Z
2020-12-18T03:34:03.000Z
# coding: utf-8 import time from config.config_loader import global_config from mall_spider.spiders.actions.context import Context from mall_spider.spiders.actions.direct_proxy_action import DirectProxyAction __proxy_service = None class ProxyService(object): proxies_set = set() proxies_list = ['https://' + item['ip'] + ':' + item['port'] for item in global_config.s_proxy] LOW_WATER_MARK = 5 proxy_fetch_url = "http://ip.11jsq.com/index.php/api/entry?method=proxyServer.generate_api_url&packid=1&fa=0&fetch_key=&qty=1&time=1&pro=&city=&port=1&format=json&ss=5&css=&dt=1&specialTxt=3&specialJson=" def __init__(self) -> None: super().__init__() self._counter = 0 def get_s_proxy(self, username): proxy = global_config.s_proxy_dict[username] url = 'https://' + proxy['ip'] + ':' + proxy['port'] return { 'https': url } def get_origin_s_proxy(self, username): return global_config.s_proxy_dict[username] def get_static_proxy(self, username): if not global_config.static_proxy: return None proxy = global_config.static_proxy_dict[username] if proxy['username'] and proxy['password']: url = 'https://' + proxy['username'] + ':' + proxy['password'] + '@' + proxy['ip'] + ':' + proxy['port'] else: url = 'https://' + proxy['ip'] + ':' + proxy['port'] return { 'https': url } def get_origin_static_proxy(self, username): if not global_config.static_proxy: return None return global_config.static_proxy_dict[username] def get_proxy(self): if len(self.proxies_list) < self.LOW_WATER_MARK: for i in range(0, int(self.LOW_WATER_MARK * 1) - len(self.proxies_list)): self.fetch_proxy() time.sleep(2) proxy = self.proxies_list[self._counter % len(self.proxies_list)] self._counter += 1 return { 'https': proxy } def fetch_proxy(self): context = Context() action = DirectProxyAction() action.execute(context=context) result = context.get(Context.KEY_PROXY_RESULT, []) if result: for item in result: ip = item['IP'] port = str(item['Port']) url = 'https://' + ip + ':' + port if url not in self.proxies_set: self.proxies_set.add(url) self.proxies_list.append(url) def remove_proxy(self, url, force=False): if force: self.proxies_set.remove(url) self.proxies_list.remove(url) def get_proxy_service(): global __proxy_service if not __proxy_service: __proxy_service = ProxyService() return __proxy_service
33.127907
208
0.601264
350
2,849
4.637143
0.271429
0.060998
0.055453
0.056685
0.319778
0.216882
0.136784
0.136784
0.136784
0.136784
0
0.008236
0.275535
2,849
85
209
33.517647
0.778101
0.004563
0
0.161765
0
0.014706
0.10868
0
0
0
0
0
0
1
0.132353
false
0.029412
0.058824
0.014706
0.382353
0
0
0
0
null
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
null
0
0
0
0
0
0
0
0
0
0
0
0
1
0
d4a46b8215ad96def234df7df255d9ac5c89bb08
965
py
Python
app/weather_tests.py
joedanz/flask-weather
fe35aa359da6f5d7f942d97837403e153b5c5ede
[ "Apache-2.0" ]
1
2017-08-25T18:55:11.000Z
2017-08-25T18:55:11.000Z
app/weather_tests.py
joedanz/flask-weather
fe35aa359da6f5d7f942d97837403e153b5c5ede
[ "Apache-2.0" ]
null
null
null
app/weather_tests.py
joedanz/flask-weather
fe35aa359da6f5d7f942d97837403e153b5c5ede
[ "Apache-2.0" ]
null
null
null
import os import weather import datetime import unittest import tempfile class WeatherTestCase(unittest.TestCase): def setUp(self): self.db_fd, weather.app.config['DATABASE'] = tempfile.mkstemp() weather.app.config['TESTING'] = True self.app = weather.app.test_client() weather.init_db() def tearDown(self): os.close(self.db_fd) os.unlink(weather.app.config['DATABASE']) def test_empty_db(self): """Test empty database with no entries.""" rv = self.app.get('/') assert 'Nothing logged yet.' in rv.data def test_report(self): """Test reporting weather""" rv = self.app.get('/report/11210/63/23', follow_redirects=True) assert b'11210' in rv.data def test_full_db(self): """Test reporting weather""" rv = self.app.get('/', follow_redirects=True) assert b'11210' in rv.data if __name__ == '__main__': unittest.main()
26.805556
71
0.631088
126
965
4.68254
0.396825
0.067797
0.081356
0.061017
0.291525
0.254237
0.254237
0.254237
0.132203
0
0
0.02578
0.236269
965
35
72
27.571429
0.774763
0.084974
0
0.08
0
0
0.093426
0
0
0
0
0
0.12
1
0.2
false
0
0.2
0
0.44
0
0
0
0
null
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
null
0
0
0
0
0
0
0
0
0
0
0
0
1
0
d4a58432909af220904a476edcdbf9bcba8bc8c1
984
py
Python
modules/sensors/Activator.py
memristor/mep2
bc5cddacba3d740f791f3454b8cb51bda83ce202
[ "MIT" ]
5
2018-11-27T15:15:00.000Z
2022-02-10T21:44:13.000Z
modules/sensors/Activator.py
memristor/mep2
bc5cddacba3d740f791f3454b8cb51bda83ce202
[ "MIT" ]
2
2018-10-20T15:48:40.000Z
2018-11-20T05:11:33.000Z
modules/sensors/Activator.py
memristor/mep2
bc5cddacba3d740f791f3454b8cb51bda83ce202
[ "MIT" ]
1
2020-02-07T12:44:47.000Z
2020-02-07T12:44:47.000Z
import asyncio class Activator: def __init__(self, name, packet_stream=None): self.ps = None self.name = name self.future = None self.data = 0 self.state = '' if packet_stream: self.set_packet_stream(packet_stream) @_core.module_cmd def wait_activator(self): pass @_core.module_cmd def check_activator(self): print('checking act') if self.data: self.future.set_result(1) else: self.state = 'check_chinch' print('checking for chinch') def export_cmds(self): _core.export_cmd('wait_activator', self.wait_activator) _core.export_cmd('check_activator', self.check_activator) def on_recv(self, pkt): if self.state == 'check_chinch' and self.future and pkt[0] == 1: self.future.set_result(1) self.state = 'chinch_ready' print('waiting for activator') if self.state == 'chinch_ready' and self.future and pkt[0] == 0: self.future.set_result(1) def set_packet_stream(self, ps): ps.recv = self.on_recv self.ps = ps
24
66
0.705285
150
984
4.393333
0.266667
0.091047
0.059181
0.086495
0.151745
0.060698
0
0
0
0
0
0.009828
0.172764
984
40
67
24.6
0.799754
0
0
0.147059
0
0
0.131098
0
0
0
0
0
0
1
0.176471
false
0.029412
0.029412
0
0.235294
0.088235
0
0
0
null
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
null
0
0
0
0
0
0
0
0
0
0
0
0
1
0
d4a5dfe986967f5b7fa8e3f7e5dcaa1ed0f98f18
7,779
py
Python
examples/retrieval/evaluation/sparse/evaluate_deepct.py
ArthurCamara/beir
2739990b719f2d4814d88473cf9965d92d4f4c18
[ "Apache-2.0" ]
24
2022-03-20T18:48:52.000Z
2022-03-31T08:28:42.000Z
examples/retrieval/evaluation/sparse/evaluate_deepct.py
ArthurCamara/beir
2739990b719f2d4814d88473cf9965d92d4f4c18
[ "Apache-2.0" ]
9
2022-03-19T14:50:30.000Z
2022-03-30T17:31:18.000Z
examples/retrieval/evaluation/sparse/evaluate_deepct.py
ArthurCamara/beir
2739990b719f2d4814d88473cf9965d92d4f4c18
[ "Apache-2.0" ]
3
2022-03-25T15:45:14.000Z
2022-03-25T17:51:23.000Z
""" This example shows how to evaluate DeepCT (using Anserini) in BEIR. For more details on DeepCT, refer here: https://arxiv.org/abs/1910.10687 The original DeepCT repository is not modularised and only works with Tensorflow 1.x (1.15). We modified the DeepCT repository to work with Tensorflow latest (2.x). We do not change the core-prediction code, only few input/output file format and structure to adapt to BEIR formats. For more details on changes, check: https://github.com/NThakur20/DeepCT and compare it with original repo! Please follow the steps below to install DeepCT: 1. git clone https://github.com/NThakur20/DeepCT.git Since Anserini uses Java-11, we would advise you to use docker for running Pyserini. To be able to run the code below you must have docker locally installed in your machine. To install docker on your local machine, please refer here: https://docs.docker.com/get-docker/ After docker installation, please follow the steps below to get docker container up and running: 1. docker pull docker pull beir/pyserini-fastapi 2. docker build -t pyserini-fastapi . 3. docker run -p 8000:8000 -it --rm pyserini-fastapi Usage: python evaluate_deepct.py """ from DeepCT.deepct import run_deepct # git clone https://github.com/NThakur20/DeepCT.git from beir import util, LoggingHandler from beir.datasets.data_loader import GenericDataLoader from beir.retrieval.evaluation import EvaluateRetrieval from beir.generation.models import QGenModel from tqdm.autonotebook import trange import pathlib, os, json import logging import requests import random #### Just some code to print debug information to stdout logging.basicConfig(format='%(asctime)s - %(message)s', datefmt='%Y-%m-%d %H:%M:%S', level=logging.INFO, handlers=[LoggingHandler()]) #### /print debug information to stdout #### Download scifact.zip dataset and unzip the dataset dataset = "scifact" url = "https://public.ukp.informatik.tu-darmstadt.de/thakur/BEIR/datasets/{}.zip".format(dataset) out_dir = os.path.join(pathlib.Path(__file__).parent.absolute(), "datasets") data_path = util.download_and_unzip(url, out_dir) corpus, queries, qrels = GenericDataLoader(data_path).load(split="test") #### 1. Download Google BERT-BASE, Uncased model #### # Ref: https://github.com/google-research/bert base_model_url = "https://storage.googleapis.com/bert_models/2018_10_18/uncased_L-12_H-768_A-12.zip" out_dir = os.path.join(pathlib.Path(__file__).parent.absolute(), "models") bert_base_dir = util.download_and_unzip(base_model_url, out_dir) #### 2. Download DeepCT MSMARCO Trained BERT checkpoint #### # Credits to DeepCT authors: Zhuyun Dai, Jamie Callan, (https://github.com/AdeDZY/DeepCT) model_url = "http://boston.lti.cs.cmu.edu/appendices/arXiv2019-DeepCT-Zhuyun-Dai/outputs/marco.zip" out_dir = os.path.join(pathlib.Path(__file__).parent.absolute(), "models") checkpoint_dir = util.download_and_unzip(model_url, out_dir) ################################################## #### 3. Configure Params for DeepCT inference #### ################################################## # We cannot use the original Repo (https://github.com/AdeDZY/DeepCT) as it only runs with TF 1.15. # We reformatted the code (https://github.com/NThakur20/DeepCT) and made it working with latest TF 2.X! if not os.path.isfile(os.path.join(data_path, "deepct.jsonl")): ################################ #### Command-Line Arugments #### ################################ run_deepct.FLAGS.task_name = "beir" # Defined a seperate BEIR task in DeepCT. Check out run_deepct. run_deepct.FLAGS.do_train = False # We only want to use the code for inference. run_deepct.FLAGS.do_eval = False # No evaluation. run_deepct.FLAGS.do_predict = True # True, as we would use DeepCT model for only prediction. run_deepct.FLAGS.data_dir = os.path.join(data_path, "corpus.jsonl") # Provide original path to corpus data, follow beir format. run_deepct.FLAGS.vocab_file = os.path.join(bert_base_dir, "vocab.txt") # Provide bert-base-uncased model vocabulary. run_deepct.FLAGS.bert_config_file = os.path.join(bert_base_dir, "bert_config.json") # Provide bert-base-uncased config.json file. run_deepct.FLAGS.init_checkpoint = os.path.join(checkpoint_dir, "model.ckpt-65816") # Provide DeepCT MSMARCO model (bert-base-uncased) checkpoint file. run_deepct.FLAGS.max_seq_length = 350 # Provide Max Sequence Length used for consideration. (Max: 512) run_deepct.FLAGS.train_batch_size = 128 # Inference batch size, Larger more Memory but faster! run_deepct.FLAGS.output_dir = data_path # Output directory, this will contain two files: deepct.jsonl (output-file) and predict.tf_record run_deepct.FLAGS.output_file = "deepct.jsonl" # Output file for storing final DeepCT produced corpus. run_deepct.FLAGS.m = 100 # Scaling parameter for DeepCT weights: scaling parameter > 0, recommend 100 run_deepct.FLAGS.smoothing = "sqrt" # Use sqrt to smooth weights. DeepCT Paper uses None. run_deepct.FLAGS.keep_all_terms = True # Do not allow DeepCT to delete terms. # Runs DeepCT model on the corpus.jsonl run_deepct.main() #### Download Docker Image beir/pyserini-fastapi #### #### Locally run the docker Image + FastAPI #### docker_beir_pyserini = "http://127.0.0.1:8000" #### Upload Multipart-encoded files #### with open(os.path.join(data_path, "deepct.jsonl"), "rb") as fIn: r = requests.post(docker_beir_pyserini + "/upload/", files={"file": fIn}, verify=False) #### Index documents to Pyserini ##### index_name = "beir/you-index-name" # beir/scifact r = requests.get(docker_beir_pyserini + "/index/", params={"index_name": index_name}) ###################################### #### 2. Pyserini-Retrieval (BM25) #### ###################################### #### Retrieve documents from Pyserini ##### retriever = EvaluateRetrieval() qids = list(queries) query_texts = [queries[qid] for qid in qids] payload = {"queries": query_texts, "qids": qids, "k": max(retriever.k_values), "fields": {"contents": 1.0}, "bm25": {"k1": 18, "b": 0.7}} #### Retrieve pyserini results (format of results is identical to qrels) results = json.loads(requests.post(docker_beir_pyserini + "/lexical/batch_search/", json=payload).text)["results"] #### Retrieve RM3 expanded pyserini results (format of results is identical to qrels) # results = json.loads(requests.post(docker_beir_pyserini + "/lexical/rm3/batch_search/", json=payload).text)["results"] #### Evaluate your retrieval using NDCG@k, MAP@K ... logging.info("Retriever evaluation for k in: {}".format(retriever.k_values)) ndcg, _map, recall, precision = retriever.evaluate(qrels, results, retriever.k_values) #### Retrieval Example #### query_id, scores_dict = random.choice(list(results.items())) logging.info("Query : %s\n" % queries[query_id]) scores = sorted(scores_dict.items(), key=lambda item: item[1], reverse=True) for rank in range(10): doc_id = scores[rank][0] logging.info("Doc %d: %s [%s] - %s\n" % (rank+1, doc_id, corpus[doc_id].get("title"), corpus[doc_id].get("text")))
56.781022
189
0.655354
1,032
7,779
4.825581
0.333333
0.03253
0.042169
0.018474
0.186948
0.145984
0.109036
0.087349
0.071285
0.071285
0
0.018059
0.202725
7,779
136
190
57.198529
0.784908
0.421391
0
0.032787
0
0.04918
0.150146
0.005345
0
0
0
0
0
1
0
false
0
0.163934
0
0.163934
0
0
0
0
null
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
null
0
0
0
0
0
0
0
0
0
0
0
0
1
0
d4a684609779826c5d7b8e2a668f0007ffd391fe
3,018
py
Python
Examples/Space Truss - Nodal Load.py
AmirHosseinNamadchi/PyNite
8cc1fe3262e1efe029c6860394d2436601272e33
[ "MIT" ]
2
2022-02-26T23:11:19.000Z
2022-02-26T23:11:21.000Z
Examples/Space Truss - Nodal Load.py
AmirHosseinNamadchi/PyNite
8cc1fe3262e1efe029c6860394d2436601272e33
[ "MIT" ]
null
null
null
Examples/Space Truss - Nodal Load.py
AmirHosseinNamadchi/PyNite
8cc1fe3262e1efe029c6860394d2436601272e33
[ "MIT" ]
2
2020-08-27T15:36:42.000Z
2020-10-02T00:29:22.000Z
# Engineering Mechanics: Statics, 4th Edition # Bedford and Fowler # Problem 6.64 # Units for this model are meters and kilonewtons # Import 'FEModel3D' and 'Visualization' from 'PyNite' from PyNite import FEModel3D from PyNite import Visualization # Create a new model truss = FEModel3D() # Define the nodes truss.AddNode('A', 1.1, -0.4, 0) truss.AddNode('B', 1, 0, 0) truss.AddNode('C', 0, 0, 0.6) truss.AddNode('D', 0, 0, -0.4) truss.AddNode('E', 0, 0.8, 0) # Define the supports truss.DefineSupport('C', True, True, True, True, True, True) truss.DefineSupport('D', True, True, True, True, True, True) truss.DefineSupport('E', True, True, True, True, True, True) # Create members # Member properties were not given for this problem, so assumed values will be used # To make all the members act rigid, the modulus of elasticity will be set to a very large value E = 99999999 truss.AddMember('AB', 'A', 'B', E, 100, 100, 100, 100, 100) truss.AddMember('AC', 'A', 'C', E, 100, 100, 100, 100, 100) truss.AddMember('AD', 'A', 'D', E, 100, 100, 100, 100, 100) truss.AddMember('BC', 'B', 'C', E, 100, 100, 100, 100, 100) truss.AddMember('BD', 'B', 'D', E, 100, 100, 100, 100, 100) truss.AddMember('BE', 'B', 'E', E, 100, 100, 100, 100, 100) # Release the moments at the ends of the members to make truss members truss.DefineReleases('AC', False, False, False, False, True, True, \ False, False, False, False, True, True) truss.DefineReleases('AD', False, False, False, False, True, True, \ False, False, False, False, True, True) truss.DefineReleases('BC', False, False, False, False, True, True, \ False, False, False, False, True, True) truss.DefineReleases('BD', False, False, False, False, True, True, \ False, False, False, False, True, True) truss.DefineReleases('BE', False, False, False, False, True, True, \ False, False, False, False, True, True) # Add nodal loads truss.AddNodeLoad('A', 'FX', 10) truss.AddNodeLoad('A', 'FY', 60) truss.AddNodeLoad('A', 'FZ', 20) # Analyze the model truss.Analyze() # Print results print('Member BC calculated axial force: ' + str(truss.GetMember('BC').MaxAxial())) print('Member BC expected axial force: 32.7 Tension') print('Member BD calculated axial force: ' + str(truss.GetMember('BD').MaxAxial())) print('Member BD expected axial force: 45.2 Tension') print('Member BE calculated axial force: ' + str(truss.GetMember('BE').MaxAxial())) print('Member BE expected axial force: 112.1 Compression') # Render the model for viewing. The text height will be set to 50 mm. # Because the members in this example are nearly rigid, there will be virtually no deformation. The deformed shape won't be rendered. # The program has created a default load case 'Case 1' and a default load combo 'Combo 1' since we didn't specify any. We'll display 'Case 1'. Visualization.RenderModel(truss, text_height=0.05, render_loads=True, case='Case 1')
44.382353
142
0.674619
460
3,018
4.421739
0.308696
0.147493
0.147493
0.070796
0.366273
0.366273
0.292035
0.292035
0.235988
0.175025
0
0.060852
0.183234
3,018
67
143
45.044776
0.7643
0.292247
0
0.128205
0
0
0.142655
0
0
0
0
0
0
1
0
false
0
0.051282
0
0.051282
0.153846
0
0
0
null
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
null
0
0
0
0
0
0
0
0
0
0
0
0
1
0
d4a6c416bd8a2d26fc2585b919cf37090ef128d8
322
py
Python
Using Yagmail to make sending emails easier.py
CodeMaster7000/Sending-Emails-in-Python
2ec44f6520a6b98508c8adf372a191f2577fbf98
[ "MIT" ]
1
2021-12-23T15:42:01.000Z
2021-12-23T15:42:01.000Z
Using Yagmail to make sending emails easier.py
CodeMaster7000/Sending-Emails-in-Python
2ec44f6520a6b98508c8adf372a191f2577fbf98
[ "MIT" ]
null
null
null
Using Yagmail to make sending emails easier.py
CodeMaster7000/Sending-Emails-in-Python
2ec44f6520a6b98508c8adf372a191f2577fbf98
[ "MIT" ]
null
null
null
import yagmail receiver = "your@gmail.com" #Receiver's gmail address body = "Hello there from Yagmail" filename = "document.pdf" yag = yagmail.SMTP("my@gmail.com")#Your gmail address yag.send( to=receiver, subject="Yagmail test (attachment included", contents=body, attachments=filename, )
23
54
0.689441
40
322
5.55
0.65
0.081081
0
0
0
0
0
0
0
0
0
0
0.195652
322
13
55
24.769231
0.857143
0.130435
0
0
0
0
0.358491
0
0
0
0
0
0
1
0
false
0
0.090909
0
0.090909
0
0
0
0
null
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
null
0
0
0
0
0
0
0
0
0
0
0
0
1
0
d4a6cec9904df1ff0e2230e88f7f8978eeccd5f8
5,064
py
Python
pycad/py_src/transformations.py
markendr/esys-escript.github.io
0023eab09cd71f830ab098cb3a468e6139191e8d
[ "Apache-2.0" ]
null
null
null
pycad/py_src/transformations.py
markendr/esys-escript.github.io
0023eab09cd71f830ab098cb3a468e6139191e8d
[ "Apache-2.0" ]
null
null
null
pycad/py_src/transformations.py
markendr/esys-escript.github.io
0023eab09cd71f830ab098cb3a468e6139191e8d
[ "Apache-2.0" ]
null
null
null
############################################################################## # # Copyright (c) 2003-2020 by The University of Queensland # http://www.uq.edu.au # # Primary Business: Queensland, Australia # Licensed under the Apache License, version 2.0 # http://www.apache.org/licenses/LICENSE-2.0 # # Development until 2012 by Earth Systems Science Computational Center (ESSCC) # Development 2012-2013 by School of Earth Sciences # Development from 2014 by Centre for Geoscience Computing (GeoComp) # Development from 2019 by School of Earth and Environmental Sciences # ############################################################################## from __future__ import print_function, division __copyright__="""Copyright (c) 2003-2020 by The University of Queensland http://www.uq.edu.au Primary Business: Queensland, Australia""" __license__="""Licensed under the Apache License, version 2.0 http://www.apache.org/licenses/LICENSE-2.0""" __url__="https://launchpad.net/escript-finley" """ transformations :var __author__: name of author :var __copyright__: copyrights :var __license__: licence agreement :var __url__: url entry point on documentation :var __version__: version :var __date__: date of the version :var DEG: unit of degree :var RAD: unit of radiant """ __author__="Lutz Gross, l.gross@uq.edu.au" import numpy import math _TYPE=numpy.float64 DEG=math.pi/180. RAD=1. class Transformation(object): """ General class to define an affine transformation *x->Ax+b*. """ def __init__(self): """ Creates a linear transformation. """ pass def __call__(self,x=numpy.zeros((3,))): """ Applies transformation to ``x``. """ raise NotImplementeError() class Translation(Transformation): """ Defines a translation *x->x+b*. """ def __init__(self,b=numpy.zeros((3,),dtype=_TYPE)): """ Creates the linear transformation *x->x+b*. """ super(Translation, self).__init__() self.__b=numpy.array(b,_TYPE) def __call__(self,x=numpy.zeros((3,))): """ Applies translation to ``x``. """ return numpy.array(x,_TYPE)+self.__b class Rotatation(Transformation): """ Defines a rotation. """ def __init__(self,axis=numpy.ones((3,),dtype=_TYPE),point=numpy.zeros((3,),dtype=_TYPE),angle=0.*RAD): """ Creates a rotation using an axis and a point on the axis. """ self.__axis=numpy.array(axis,dtype=_TYPE) self.__point=numpy.array(point,dtype=_TYPE) lax=numpy.dot(self.__axis,self.__axis) if not lax>0: raise ValueError("points must be distinct.") self.__axis/=math.sqrt(lax) self.__angle=float(angle) def __call__(self,x=numpy.zeros((3,))): """ Applies the rotation to ``x``. """ x=numpy.array(x,_TYPE) z=x-self.__point z0=numpy.dot(z,self.__axis) z_per=z-z0*self.__axis lz_per=numpy.dot(z_per,z_per) if lz_per>0: axis1=z_per/math.sqrt(lz_per) axis2=_cross(axis1,self.__axis) lax2=numpy.dot(axis2,axis2) if lax2>0: axis2/=math.sqrt(lax2) return z0*self.__axis+math.sqrt(lz_per)*(math.cos(self.__angle)*axis1-math.sin(self.__angle)*axis2)+self.__point else: return x else: return x def _cross(x, y): """ Returns the cross product of ``x`` and ``y``. """ return numpy.array([x[1] * y[2] - x[2] * y[1], x[2] * y[0] - x[0] * y[2], x[0] * y[1] - x[1] * y[0]], _TYPE) class Dilation(Transformation): """ Defines a dilation. """ def __init__(self,factor=1.,center=numpy.zeros((3,),dtype=_TYPE)): """ Creates a dilation with a center and a given expansion/contraction factor. """ if not abs(factor)>0: raise ValueError("factor must be non-zero.") self.__factor=factor self.__center=numpy.array(center,dtype=_TYPE) def __call__(self,x=numpy.zeros((3,))): """ Applies dilation to ``x``. """ x=numpy.array(x,_TYPE) return self.__factor*(x-self.__center)+self.__center class Reflection(Transformation): """ Defines a reflection on a plane. """ def __init__(self,normal=numpy.ones((3,),dtype=_TYPE),offset=0.): """ Defines a reflection on a plane defined in normal form. """ self.__normal=numpy.array(normal,dtype=_TYPE) ln=math.sqrt(numpy.dot(self.__normal,self.__normal)) if not ln>0.: raise ValueError("normal must have positive length.") self.__normal/=ln if isinstance(offset,float) or isinstance(offset,int): self.__offset=offset/ln else: self.__offset=numpy.dot(numpy.array(offset,dtype=_TYPE),self.__normal) def __call__(self,x=numpy.zeros((3,))): """ Applies reflection to ``x``. """ x=numpy.array(x,_TYPE) return x - 2*(numpy.dot(x,self.__normal)-self.__offset)*self.__normal
29.788235
124
0.610585
664
5,064
4.388554
0.256024
0.037749
0.030199
0.02059
0.24674
0.226836
0.19046
0.18394
0.135896
0.11256
0
0.024063
0.220379
5,064
169
125
29.964497
0.714032
0.21643
0
0.173333
0
0
0.109346
0
0
0
0
0
0
1
0.146667
false
0.013333
0.04
0
0.346667
0.013333
0
0
0
null
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
null
0
0
0
0
0
0
0
0
0
0
0
0
1
0
d4a6efea0d126676c34a41838cc4fe1e41395646
1,116
py
Python
example/complex_scalar_star_solver.py
ThomasHelfer/BosonStar
5442a6e6171122a3ba1d6b079e6483ab72aa7338
[ "MIT" ]
2
2021-04-07T13:20:11.000Z
2021-04-07T17:11:25.000Z
example/complex_scalar_star_solver.py
ThomasHelfer/BosonStar
5442a6e6171122a3ba1d6b079e6483ab72aa7338
[ "MIT" ]
1
2021-06-14T15:40:25.000Z
2021-06-14T15:40:25.000Z
example/complex_scalar_star_solver.py
ThomasHelfer/BosonStar
5442a6e6171122a3ba1d6b079e6483ab72aa7338
[ "MIT" ]
null
null
null
from bosonstar.ComplexBosonStar import Complex_Boson_Star # ===================== # All imporntnat definitions # ===================== # Physics defintions phi0 = 0.40 # centeral phi D = 5.0 # Dimension (total not only spacial) Lambda = -0.2 # Cosmological constant # Solver definitions Rstart = 3 Rend = 50.00 deltaR = 1 N = 100000 e_pow_minus_delta_guess = 0.4999 verbose = 2 eps = 1e-10 # Small epsilon to avoid r \neq 0 # ==================================== # Main routine # ==================================== pewpew = Complex_Boson_Star(e_pow_minus_delta_guess, phi0, D, Lambda, verbose) pewpew.print_parameters() alpha0 = pewpew.radial_walker(Rstart, Rend, deltaR, N, eps) # ===================================== # Output and plotting # ===================================== soldict = pewpew.get_solution() # Makes sure that lapse goes asymptotically to 1 # (Not an essential step, but recommended) pewpew.normalise_edelta() pewpew.check_Einstein_equation() # =============================== path = pewpew.get_path() pewpew.plot_solution() pewpew.print_solution()
24.26087
78
0.580645
125
1,116
5.016
0.688
0.038278
0.051037
0.044657
0.060606
0
0
0
0
0
0
0.034847
0.151434
1,116
45
79
24.8
0.627244
0.464158
0
0
0
0
0
0
0
0
0
0
0
1
0
false
0
0.05
0
0.05
0.1
0
0
0
null
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
null
0
0
0
0
0
0
0
0
0
0
0
0
1
0
d4a71c335f605cc7723cb3705f2699bfe1e1693b
796
py
Python
setup.py
ouyhlan/fastNLP
cac13311e28c1e8e3c866d50656173650eb5c7a1
[ "Apache-2.0" ]
2,693
2018-03-08T03:09:20.000Z
2022-03-30T07:38:42.000Z
setup.py
ouyhlan/fastNLP
cac13311e28c1e8e3c866d50656173650eb5c7a1
[ "Apache-2.0" ]
291
2018-07-21T07:43:17.000Z
2022-03-07T13:06:58.000Z
setup.py
ouyhlan/fastNLP
cac13311e28c1e8e3c866d50656173650eb5c7a1
[ "Apache-2.0" ]
514
2018-03-09T06:54:25.000Z
2022-03-26T20:11:44.000Z
#!/usr/bin/env python # coding=utf-8 from setuptools import setup, find_packages with open('README.md', encoding='utf-8') as f: readme = f.read() with open('LICENSE', encoding='utf-8') as f: license = f.read() with open('requirements.txt', encoding='utf-8') as f: reqs = f.read() pkgs = [p for p in find_packages() if p.startswith('fastNLP')] print(pkgs) setup( name='FastNLP', version='0.7.0', url='https://gitee.com/fastnlp/fastNLP', description='fastNLP: Deep Learning Toolkit for NLP, developed by Fudan FastNLP Team', long_description=readme, long_description_content_type='text/markdown', license='Apache License', author='Fudan FastNLP Team', python_requires='>=3.6', packages=pkgs, install_requires=reqs.strip().split('\n'), )
26.533333
90
0.675879
114
796
4.649123
0.561404
0.030189
0.067925
0.079245
0.084906
0
0
0
0
0
0
0.013514
0.163317
796
29
91
27.448276
0.782282
0.041457
0
0
0
0
0.291721
0
0
0
0
0
0
1
0
false
0
0.045455
0
0.045455
0.045455
0
0
0
null
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
null
0
0
0
0
0
0
0
0
0
0
0
0
1
0
d4a7f2382cdb35d8940e5dd478b2dac3b5b10bd0
752
py
Python
Module1/file3.py
modulo16/PfNE
9706afc42c44dcfd1490e5ac074156f41e5515a8
[ "Unlicense" ]
null
null
null
Module1/file3.py
modulo16/PfNE
9706afc42c44dcfd1490e5ac074156f41e5515a8
[ "Unlicense" ]
null
null
null
Module1/file3.py
modulo16/PfNE
9706afc42c44dcfd1490e5ac074156f41e5515a8
[ "Unlicense" ]
null
null
null
from __future__ import print_function, unicode_literals #Ensures Unicode is used for all strings. my_str = 'whatever' #Shows the String type, which should be unicode type(my_str) #declare string: ip_addr = '192.168.1.1' #check it with boolean:(True) ip_addr == '192.168.1.1' #(false) ip_addr == '10.1.1.1' #is this substring in this variable? '192.168' in ip_addr '1.1' in ip_addr '15.1' not in ip_addr #Strings also have indices starting at '0' #in the case below we get '1' which is the first character ip_addr[0] #we can also get the last using negative notation. The follow gets the last: ip_addr[-1] #second to last: ip_addr[-2] #show length of string: len(ip_addr) #Example string concatenation my_str = 'Hello' my_str + ' something'
18.8
76
0.731383
137
752
3.868613
0.525547
0.113208
0.045283
0.045283
0.05283
0.05283
0
0
0
0
0
0.05873
0.162234
752
39
77
19.282051
0.78254
0.543883
0
0
0
0
0.203647
0
0
0
0
0
0
1
0
false
0
0.066667
0
0.066667
0.066667
0
0
0
null
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
null
0
0
0
0
0
0
0
0
0
0
0
0
1
0
d4acef5631789f4b877955db52847e8e212a8725
10,411
py
Python
pp_io_plugins/pp_kbddriver_plus.py
arcticmatter/pipresents-beep
e5945f929b47249f19b0cb3433a138e874b592db
[ "CNRI-Python", "CECILL-B" ]
null
null
null
pp_io_plugins/pp_kbddriver_plus.py
arcticmatter/pipresents-beep
e5945f929b47249f19b0cb3433a138e874b592db
[ "CNRI-Python", "CECILL-B" ]
null
null
null
pp_io_plugins/pp_kbddriver_plus.py
arcticmatter/pipresents-beep
e5945f929b47249f19b0cb3433a138e874b592db
[ "CNRI-Python", "CECILL-B" ]
null
null
null
#enhanced keyboard driver import copy import os import configparser from pp_displaymanager import DisplayManager class pp_kbddriver_plus(object): # control list items NAME=0 # symbolic name for input and output DIRECTION = 1 # in/out MATCH = 2 # for input the character/string to match (no EOL) MODE= 3 # for input the match mode any-char,char,any-line,line TEMPLATE=['','','',''] # CLASS VARIABLES (pp_kbddriver_plus.) driver_active=False title='' # usd for error reporting and logging tick_interval='' # mS between polls of the serial input match_mode='' # char or line, whether input characters are matched for each character or a complete line inputs={} # executed by main program and by each object using the driver def __init__(self): self.dm=DisplayManager() # executed once from main program def init(self,filename,filepath,widget,pp_dir,pp_home,pp_profile,event_callback=None): # instantiate arguments self.widget=widget self.filename=filename self.filepath=filepath self.event_callback=event_callback pp_kbddriver_plus.driver_active = False # read pp_kbddriver_plus.cfg file. reason,message=self._read(self.filename,self.filepath) if reason =='error': return 'error',message if self.config.has_section('DRIVER') is False: return 'error','No DRIVER section in '+self.filepath # all the below are used by another instance of pp_kbddriver_plus so must reference class variables # read information from DRIVER section pp_kbddriver_plus.title=self.config.get('DRIVER','title') pp_kbddriver_plus.bind_printing = self.config.get('DRIVER','bind-printing') # construct the control list from the config file pp_kbddriver_plus.in_names=[] pp_kbddriver_plus.out_names=[] for section in self.config.sections(): if section == 'DRIVER': continue entry=copy.deepcopy(pp_kbddriver_plus.TEMPLATE) entry[pp_kbddriver_plus.NAME]=self.config.get(section,'name') entry[pp_kbddriver_plus.DIRECTION]=self.config.get(section,'direction') if entry[pp_kbddriver_plus.DIRECTION] == 'none': continue elif entry[pp_kbddriver_plus.DIRECTION] == 'in': entry[pp_kbddriver_plus.MODE]=self.config.get(section,'mode') if entry[pp_kbddriver_plus.MODE] in ('specific-character','specific-line'): entry[pp_kbddriver_plus.MATCH]=self.config.get(section,'match') pp_kbddriver_plus.in_names.append(copy.deepcopy(entry)) else: return 'error',pp_kbddriver_plus.title + ' direction not in or out' # print pp_kbddriver_plus.in_names # bind the keys self._bind_keys(widget,self._key_received) # all ok so indicate the driver is active pp_kbddriver_plus.driver_active=True # init must return two arguments return 'normal',pp_kbddriver_plus.title + ' active' # sets up tkinter keyboard events such that any key press # does a callback to _key_received() with the event object def _bind_keys(self,widget,callback): for display_name in DisplayManager.display_map: status,message,display_id,canvas=self.dm.id_of_canvas(display_name) if status !='normal': continue # bind all the normal keys that return a printing character such that x produces pp-key-x (but fileterd in _key_received) canvas.bind("<Key>", lambda event,match='<Key>',name='': self._key_received(event,match,name)) # print 'bind printing' # Bind <Return> so that eol detection works, <Return> cannot be used to trigger an input event # if you wnt that use keys.cfg canvas.bind("<Return>", lambda event,match='<Return>',name='': self._key_received(event,match,name)) # print 'bind Return to make eol work' # go through entries and bind all specific-character matches to _key_received for entry in pp_kbddriver_plus.in_names: if entry[pp_kbddriver_plus.MODE] == 'specific-character': match = entry[pp_kbddriver_plus.MATCH] name = entry[pp_kbddriver_plus.NAME] canvas.bind(match, lambda event, match=match,name=name: self._key_received(event,match,name)) # print 'bind specific-char', match,name # start method must be defined. If not using inputs just pass def start(self): pp_kbddriver_plus.inputs['current-character']='' pp_kbddriver_plus.inputs['current-line']='' pp_kbddriver_plus.inputs['previous-line']='' def _key_received(self,event,match,name): # generate the events with symbolic names if driver is active if pp_kbddriver_plus.driver_active is True: char=event.char # print 'received ',char,match,name # if char is eol then match the line and start a new line if match =='<Return>': # do match of line # print 'do match line',pp_kbddriver_plus.inputs['current-line'] self.match_line(pp_kbddriver_plus.inputs['current-line']) # shuffle and empty the buffer pp_kbddriver_plus.inputs['previous-line'] = pp_kbddriver_plus.inputs['current-line'] pp_kbddriver_plus.inputs['current-line']='' pp_kbddriver_plus.inputs['current-character']='' if name !='': # print 'bound <Return> key' if self.event_callback is not None: self.event_callback(name,pp_kbddriver_plus.title) else: # process a character if char == '' and match == '<Key>': # unbound special key # print 'unbound special key ', match pass else: # a character has been received pp_kbddriver_plus.inputs['current-character']=char pp_kbddriver_plus.inputs['current-line']+=char # print pp_kbddriver_plus.inputs['current-character'],pp_kbddriver_plus.inputs['current-line'] if match == '<Key>' and char != '' and self.bind_printing =='yes': # print 'printable key, bind-printing is yes',char,match # printable character without overiding section if self.event_callback is not None: self.event_callback('pp-key-'+ char,pp_kbddriver_plus.title) else: if name != '': # print 'bound non-printable character',char,name if self.event_callback is not None: self.event_callback(name,pp_kbddriver_plus.title) # look through entries for any-character for entry in pp_kbddriver_plus.in_names: if entry[pp_kbddriver_plus.MODE] == 'any-character': # print 'match any character', char, 'current line is ',pp_kbddriver_plus.inputs['current-line'] if self.event_callback is not None: self.event_callback(entry[pp_kbddriver_plus.NAME],pp_kbddriver_plus.title) def match_line(self,line): for entry in pp_kbddriver_plus.in_names: if entry[pp_kbddriver_plus.MODE] == 'any-line': # print 'match any line',line if self.event_callback is not None: self.event_callback(entry[pp_kbddriver_plus.NAME],pp_kbddriver_plus.title) if entry[pp_kbddriver_plus.MODE] == 'specific-line' and line == entry[pp_kbddriver_plus.MATCH]: # print 'match specific line', line if self.event_callback is not None: self.event_callback(entry[pp_kbddriver_plus.NAME],pp_kbddriver_plus.title) # allow track plugins (or anything else) to access analog input values def get_input(self,key): if key in pp_kbddriver_plus.inputs: return True, pp_kbddriver_plus.inputs[key] else: return False, None # allow querying of driver state def is_active(self): return pp_kbddriver_plus.driver_active # called by main program only. Called when PP is closed down def terminate(self): pp_kbddriver_plus.driver_active = False # ************************************************ # output interface method # this can be called from many objects so needs to operate on class variables # ************************************************ # execute an output event def handle_output_event(self,name,param_type,param_values,req_time): return 'normal','no output methods' # *********************************** # reading .cfg file # ************************************ def _read(self,filename,filepath): if os.path.exists(filepath): self.config = configparser.ConfigParser(inline_comment_prefixes = (';',)) self.config.read(filepath) return 'normal',filename+' read' else: return 'error',filename+' not found at: '+filepath if __name__ == '__main__': from tkinter import * def key_callback(symbol,source): print('callback',symbol,source,'\n') if symbol=='pp-stop': idd.terminate() exit() pass root = Tk() w = Label(root, text="pp_kbddriver_plus.py test harness") w.pack() idd=pp_kbddriver_plus() reason,message=idd.init('pp_kbddriver_plus.cfg','/home/pi/pipresents/pp_io_config/keys_plus.cfg',root,key_callback) print(reason,message) if reason != 'error': idd.start() root.mainloop()
41.979839
134
0.589761
1,220
10,411
4.853279
0.201639
0.117041
0.159601
0.057423
0.312954
0.250633
0.200135
0.187975
0.174126
0.152846
0
0.000555
0.307463
10,411
247
135
42.149798
0.820666
0.266449
0
0.240876
0
0
0.080913
0.008844
0
0
0
0
0
1
0.087591
false
0.014599
0.036496
0.014599
0.277372
0.029197
0
0
0
null
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
null
0
0
0
0
0
0
0
0
0
0
0
0
1
0
d4b0acbd3ae55e6638c516e22ca4f69932aebab2
27,844
py
Python
project2/marriage.py
filipefborba/MarriageNSFG
d550301fbb9d80ddabf391a6168d2c8636113ed9
[ "MIT" ]
null
null
null
project2/marriage.py
filipefborba/MarriageNSFG
d550301fbb9d80ddabf391a6168d2c8636113ed9
[ "MIT" ]
null
null
null
project2/marriage.py
filipefborba/MarriageNSFG
d550301fbb9d80ddabf391a6168d2c8636113ed9
[ "MIT" ]
null
null
null
"""This file contains code for use with "Think Stats", by Allen B. Downey, available from greenteapress.com Copyright 2014 Allen B. Downey License: GNU GPLv3 http://www.gnu.org/licenses/gpl.html """ from __future__ import print_function, division import bisect import numpy as np import pandas as pd import scipy.stats import gzip import matplotlib.pyplot as plt from collections import defaultdict from collections import OrderedDict from collections import Counter import thinkstats2 import thinkplot import survival def ResampleResps(resps, remove_missing=False, jitter=0): """Resamples each dataframe and then concats them. resps: list of DataFrame returns: DataFrame """ # we have to resample the data from each cycle separately samples = [ResampleRowsWeighted(resp) for resp in resps] # then join the cycles into one big sample sample = pd.concat(samples, ignore_index=True, sort=False) # remove married people with unknown marriage dates if remove_missing: sample = sample[~sample.missing] # jittering the ages reflects the idea that the resampled people # are not identical to the actual respondents if jitter: Jitter(sample, 'age', jitter=jitter) Jitter(sample, 'agemarry', jitter=jitter) DigitizeResp(resp) return sample def ResampleRowsWeighted(df, column='finalwgt'): """Resamples the rows in df in accordance with a weight column. df: DataFrame returns: DataFrame """ weights = df['finalwgt'].copy() weights /= sum(weights) indices = np.random.choice(df.index, len(df), replace=True, p=weights) return df.loc[indices] def Jitter(df, column, jitter=1): """Adds random noise to a column. df: DataFrame column: string column name jitter: standard deviation of noise """ df[column] += np.random.uniform(-jitter, jitter, size=len(df)) def EstimateSurvival(resp, cutoff=None): """Estimates the survival curve. resp: DataFrame of respondents cutoff: where to truncate the estimated functions returns: pair of HazardFunction, SurvivalFunction """ complete = resp.loc[resp.complete, 'complete_var'].dropna() ongoing = resp.loc[~resp.complete, 'ongoing_var'].dropna() hf = survival.EstimateHazardFunction(complete, ongoing) if cutoff: hf.Truncate(cutoff) sf = hf.MakeSurvival() return hf, sf def PropensityMatch(target, group, colname='agemarry'): """Choose a random subset of `group` to matches propensity with `target`. target: DataFrame group: DataFrame colname: string name of column with propensity scores returns: DataFrame with sample of rows from `group` """ rv = scipy.stats.norm(scale=1) values = group[colname].fillna(100) def ChooseIndex(value): weights = rv.pdf(values-value) weights /= sum(weights) return np.random.choice(group.index, 1, p=weights)[0] indices = [ChooseIndex(value) for value in target[colname]] return group.loc[indices] def EstimateSurvivalByCohort(resps, iters=101, cutoffs=None, predict_flag=False, prop_match=None, error_rate=0): """Makes survival curves for resampled data. resps: list of DataFrames iters: number of resamples to plot predict_flag: whether to also plot predictions cutoffs: map from cohort to the first unreliable age_index returns: map from group name to list of survival functions """ if cutoffs == None: cutoffs = {} sf_map = defaultdict(list) # iters is the number of resampling runs to make for i in range(iters): sample = ResampleResps(resps) # group by decade grouped = sample.groupby('birth_index') if prop_match: last = grouped.get_group(prop_match) # and estimate (hf, sf) for each group hf_map = OrderedDict() for name, group in iter(grouped): if prop_match: group = PropensityMatch(last, group) if error_rate: AddErrors(group, 'complete_missing', error_rate) AddErrors(group, 'ongoing_missing', error_rate) # the amount of missing data is small; I think it is better # to drop it than to fill with random data #FillMissingColumn(group, 'complete_var', 'complete_missing') #FillMissingColumn(group, 'ongoing_var', 'ongoing_missing') cutoff = cutoffs.get(name, 100) hf_map[name] = EstimateSurvival(group, cutoff) # make predictions if desired if predict_flag: MakePredictions(hf_map) # extract the sf from each pair and accumulate the results for name, (hf, sf) in hf_map.items(): sf_map[name].append(sf) return sf_map def AddErrors(group, colname, error_rate): """ NOTE: This will not work if there are actual missing values! """ group[colname] = np.random.random(len(group)) < error_rate def FillMissingColumn(group, colname, missing_colname): """Fills missing values of the given column. group: DataFrame colname: string """ null = group[group[missing_colname]] if len(null) == 0: return # print(len(null), len(group)) valid = group[colname].dropna() fill = valid.sample(len(null), replace=True) fill.index = null.index group[colname].fillna(fill, inplace=True) def PlotSurvivalFunctions(sf_map, predict_flag=False, colormap=None): """Plot estimated survival functions. sf_map: map from group name to sequence of survival functions predict_flag: whether the lines are predicted or actual colormap: map from group name to color """ for name, sf_seq in sorted(sf_map.items(), reverse=True): if len(sf_seq) == 0: continue sf = sf_seq[0] if len(sf) == 0: continue ts, rows = MakeSurvivalCI(sf_seq, [10, 50, 90]) thinkplot.FillBetween(ts, rows[0], rows[2], color='gray', alpha=0.2) if not predict_flag: if colormap: color = colormap[name] thinkplot.Plot(ts, rows[1], label='%ds'%name, color=color) else: thinkplot.Plot(ts, rows[1], label='%ds'%name) def MakePredictions(hf_map): """Extends a set of hazard functions and recomputes survival functions. For each group in hf_map, we extend hf and recompute sf. hf_map: map from group name to (HazardFunction, SurvivalFunction) """ names = list(hf_map.keys()) names.sort() hfs = [hf_map[name][0] for name in names] # extend each hazard function using data from the previous cohort, # and update the survival function for i, name in enumerate(names): hf, sf = hf_map[name] if i > 0: hf.Extend(hfs[i-1]) sf = hf.MakeSurvival() hf_map[name] = hf, sf def MakeSurvivalCI(sf_seq, percents): """Makes confidence intervals from a list of survival functions. sf_seq: list of SurvivalFunction percents: list of percentiles to select, like [5, 95] returns: (ts, rows) where ts is a sequence of times and rows contains one row of values for each percent """ # find the union of all ts where the sfs are evaluated ts = set() for sf in sf_seq: ts |= set(sf.ts) ts = list(ts) ts.sort() # evaluate each sf at all times ss_seq = [sf.Probs(ts) for sf in sf_seq if len(sf) > 0] # return the requested percentiles from each column rows = thinkstats2.PercentileRows(ss_seq, percents) return ts, rows def ReadFemResp1982(): """Reads respondent data from NSFG Cycle 3. returns: DataFrame """ dat_file = '1982NSFGData.dat.gz' names = ['finalwgt', 'ageint', 'mar2p', 'cmmarrhx', 'fmarital', 'cmintvw', 'cmbirth', 'f18m1', 'cmdivorcx', 'cmstphsbx', 'fmarno'] colspecs = [(976-1, 982), (1001-1, 1002), (1268-1, 1271), (1037-1, 1040), (1041-1, 1041), (841-1, 844), (12-1, 15), (606-1, 606), (619-1, 622), (625-1, 628), (1142-1, 1143), ] df = pd.read_fwf(dat_file, colspecs=colspecs, names=names, header=None, nrows=7969, compression='gzip') df.cmintvw.replace([9797, 9898, 9999], np.nan, inplace=True) df.cmbirth.replace([9797, 9898, 9999], np.nan, inplace=True) df.cmmarrhx.replace([9797, 9898, 9999], np.nan, inplace=True) df.cmdivorcx.replace([9797, 9898, 9999], np.nan, inplace=True) df.cmstphsbx.replace([9797, 9898, 9999], np.nan, inplace=True) df.f18m1.replace([7, 8, 9], np.nan, inplace=True) # CM values above 9000 indicate month unknown df.loc[df.cmintvw>9000, 'cmintvw'] -= 9000 df.loc[df.cmbirth>9000, 'cmbirth'] -= 9000 df.loc[df.cmmarrhx>9000, 'cmmarrhx'] -= 9000 df.loc[df.cmdivorcx>9000, 'cmdivorcx'] -= 9000 df.loc[df.cmstphsbx>9000, 'cmstphsbx'] -= 9000 df['evrmarry'] = (df.fmarno > 0) df['divorced'] = (df.f18m1 == 4) df['separated'] = (df.f18m1 == 5) df['widowed'] = (df.f18m1 == 3) df['stillma'] = (df.fmarno==1) & (df.fmarital==1) df['cycle'] = 3 CleanResp(df) return df def ReadFemResp1988(): """Reads respondent data from NSFG Cycle 4. Read as if were a standard ascii file returns: DataFrame """ filename = '1988FemRespDataLines.dat.gz' names = ['finalwgt', 'ageint', 'currentcm', 'firstcm', 'cmintvw', 'cmbirth', 'f23m1', 'cmdivorcx', 'cmstphsbx', 'fmarno'] colspecs = [(2568-1, 2574), (36-1, 37), (1521-1, 1525), (1538-1, 1542), (12-1, 16), (26-1, 30), (1554-1, 1554), (1565-1, 1569), (1570-1, 1574), (2441-1, 2442), ] df = pd.read_fwf(filename, colspecs=colspecs, names=names, header=None, compression='gzip') df.cmintvw.replace([0, 99999], np.nan, inplace=True) df.cmbirth.replace([0, 99999], np.nan, inplace=True) df.firstcm.replace([0, 99999], np.nan, inplace=True) df.currentcm.replace([0, 99999], np.nan, inplace=True) df.cmdivorcx.replace([0, 99999], np.nan, inplace=True) df.cmstphsbx.replace([0, 99999], np.nan, inplace=True) # CM values above 9000 indicate month unknown df.loc[df.cmintvw>90000, 'cmintvw'] -= 90000 df.loc[df.cmbirth>90000, 'cmbirth'] -= 90000 df.loc[df.firstcm>90000, 'firstcm'] -= 90000 df.loc[df.currentcm>90000, 'currentcm'] -= 90000 df.loc[df.cmdivorcx>90000, 'cmdivorcx'] -= 90000 df.loc[df.cmstphsbx>90000, 'cmstphsbx'] -= 90000 # combine current and first marriage df['cmmarrhx'] = df.firstcm df.cmmarrhx.fillna(df.currentcm, inplace=True) # define evrmarry if either currentcm or firstcm is non-zero df['evrmarry'] = (df.fmarno > 0) df['divorced'] = (df.f23m1==2) df['separated'] = (df.f23m1==3) df['widowed'] = (df.f23m1==1) df['stillma'] = (df.fmarno==1) & (df.f23m1.isnull()) df['cycle'] = 4 CleanResp(df) return df def ReadFemResp1995(): """Reads respondent data from NSFG Cycle 5. returns: DataFrame """ dat_file = '1995FemRespData.dat.gz' names = ['cmintvw', 'timesmar', 'cmmarrhx', 'cmbirth', 'finalwgt', 'marend01', 'cmdivorcx', 'cmstphsbx', 'marstat'] colspecs = [(12360-1, 12363), (4637-1, 4638), (11759-1, 11762), (14-1, 16), (12350-1, 12359), (4713-1, 4713), (4718-1, 4721), (4722-1, 4725), (17-1, 17)] df = pd.read_fwf(dat_file, compression='gzip', colspecs=colspecs, names=names) invalid = [9997, 9998, 9999] df.cmintvw.replace(invalid, np.nan, inplace=True) df.cmbirth.replace(invalid, np.nan, inplace=True) df.cmmarrhx.replace(invalid, np.nan, inplace=True) df.cmdivorcx.replace(invalid, np.nan, inplace=True) df.cmstphsbx.replace(invalid, np.nan, inplace=True) df.timesmar.replace([98, 99], np.nan, inplace=True) df['evrmarry'] = (df.timesmar > 0) df['divorced'] = (df.marend01==1) df['separated'] = (df.marend01==2) df['widowed'] = (df.marend01==3) df['stillma'] = (df.timesmar==1) & (df.marend01.isnull()) df['cycle'] = 5 CleanResp(df) return df def ReadFemResp2002(): """Reads respondent data from NSFG Cycle 6. returns: DataFrame """ usecols = ['caseid', 'cmmarrhx', 'cmdivorcx', 'cmbirth', 'cmintvw', 'evrmarry', 'parity', 'finalwgt', 'mardat01', 'marend01', 'mardis01', 'rmarital', 'fmarno', 'mar1diss'] df = ReadResp('2002FemResp.dct', '2002FemResp.dat.gz', usecols=usecols) invalid = [9997, 9998, 9999] df.cmintvw.replace(invalid, np.nan, inplace=True) df.cmbirth.replace(invalid, np.nan, inplace=True) df.cmmarrhx.replace(invalid, np.nan, inplace=True) df['evrmarry'] = (df.evrmarry==1) df['divorced'] = (df.marend01==1) df['separated'] = (df.marend01==2) df['widowed'] = (df.marend01==3) df['stillma'] = (df.fmarno == 1) & (df.rmarital==1) df['cycle'] = 6 CleanResp(df) return df def ReadFemResp2010(): """Reads respondent data from NSFG Cycle 7. returns: DataFrame """ usecols = ['caseid', 'cmmarrhx', 'cmdivorcx', 'cmbirth', 'cmintvw', 'evrmarry', 'parity', 'wgtq1q16', 'mardat01', 'marend01', 'mardis01', 'rmarital', 'fmarno', 'mar1diss'] df = ReadResp('2006_2010_FemRespSetup.dct', '2006_2010_FemResp.dat.gz', usecols=usecols) invalid = [9997, 9998, 9999] df.cmintvw.replace(invalid, np.nan, inplace=True) df.cmbirth.replace(invalid, np.nan, inplace=True) df.cmmarrhx.replace(invalid, np.nan, inplace=True) df['evrmarry'] = (df.evrmarry==1) df['divorced'] = (df.marend01==1) df['separated'] = (df.marend01==2) df['widowed'] = (df.marend01==3) df['stillma'] = (df.fmarno == 1) & (df.rmarital==1) df['finalwgt'] = df.wgtq1q16 df['cycle'] = 7 CleanResp(df) return df def ReadFemResp2013(): """Reads respondent data from NSFG Cycle 8. returns: DataFrame """ usecols = ['caseid', 'cmmarrhx', 'cmdivorcx', 'cmbirth', 'cmintvw', 'evrmarry', 'parity', 'wgt2011_2013', 'mardat01', 'marend01', 'mardis01', 'rmarital', 'fmarno', 'mar1diss'] df = ReadResp('2011_2013_FemRespSetup.dct', '2011_2013_FemRespData.dat.gz', usecols=usecols) invalid = [9997, 9998, 9999] df.cmintvw.replace(invalid, np.nan, inplace=True) df.cmbirth.replace(invalid, np.nan, inplace=True) df.cmmarrhx.replace(invalid, np.nan, inplace=True) df['evrmarry'] = (df.evrmarry==1) df['divorced'] = (df.marend01==1) df['separated'] = (df.marend01==2) df['widowed'] = (df.marend01==3) df['stillma'] = (df.fmarno == 1) & (df.rmarital==1) df['finalwgt'] = df.wgt2011_2013 df['cycle'] = 8 CleanResp(df) return df def ReadFemResp2015(): """Reads respondent data from NSFG Cycle 9. returns: DataFrame """ usecols = ['caseid', 'cmmarrhx', 'cmdivorcx', 'cmbirth', 'cmintvw', 'evrmarry', 'parity', 'wgt2013_2015', 'mardat01', 'marend01', 'mardis01', 'rmarital', 'fmarno', 'mar1diss'] df = ReadResp('2013_2015_FemRespSetup.dct', '2013_2015_FemRespData.dat.gz', usecols=usecols) invalid = [9997, 9998, 9999] df.cmintvw.replace(invalid, np.nan, inplace=True) df.cmbirth.replace(invalid, np.nan, inplace=True) df.cmmarrhx.replace(invalid, np.nan, inplace=True) df['evrmarry'] = (df.evrmarry==1) df['divorced'] = (df.marend01==1) df['separated'] = (df.marend01==2) df['widowed'] = (df.marend01==3) df['stillma'] = (df.fmarno == 1) & (df.rmarital==1) df['finalwgt'] = df.wgt2013_2015 df['cycle'] = 9 CleanResp(df) return df def ReadFemResp2017(): """Reads respondent data from NSFG Cycle 10. returns: DataFrame """ # removed 'cmmarrhx', 'cmdivorcx', 'cmbirth', usecols = ['caseid', 'cmintvw', 'ager', 'evrmarry', 'parity', 'wgt2015_2017', 'mardat01', 'marend01', 'mardis01', 'rmarital', 'fmarno', 'mar1diss'] df = ReadResp('2015_2017_FemRespSetup.dct', '2015_2017_FemRespData.dat.gz', usecols=usecols) invalid = [9997, 9998, 9999] df.cmintvw.replace(invalid, np.nan, inplace=True) #df.cmbirth.replace(invalid, np.nan, inplace=True) #df.cmmarrhx.replace(invalid, np.nan, inplace=True) # since cmbirth and cmmarrhx are no longer included, # we have to compute them based on other variables; # the result can be off by up to 12 months df['cmbirth'] = df.cmintvw - df.ager*12 df['cmmarrhx'] = (df.mardat01-1900) * 12 df['evrmarry'] = (df.evrmarry==1) df['divorced'] = (df.marend01==1) df['separated'] = (df.marend01==2) df['widowed'] = (df.marend01==3) df['stillma'] = (df.fmarno == 1) & (df.rmarital==1) df['finalwgt'] = df.wgt2015_2017 df['cycle'] = 10 # Instead of calling CleanResp, we have to customize #CleanResp(df) df['agemarry'] = (df.cmmarrhx - df.cmbirth) / 12.0 df['age'] = (df.cmintvw - df.cmbirth) / 12.0 # if married, we need agemarry; if not married, we need age df['missing'] = np.where(df.evrmarry, df.agemarry.isnull(), df.age.isnull()) month0 = pd.to_datetime('1899-12-15') dates = [month0 + pd.DateOffset(months=cm) for cm in df.cmbirth] df['year'] = (pd.DatetimeIndex(dates).year - 1900) DigitizeResp(df) return df def ReadResp(dct_file, dat_file, **options): """Reads the NSFG respondent data. dct_file: string file name dat_file: string file name returns: DataFrame """ dct = thinkstats2.ReadStataDct(dct_file, encoding='iso-8859-1') df = dct.ReadFixedWidth(dat_file, compression='gzip', **options) return df def CleanResp(resp): """Cleans a respondent DataFrame. resp: DataFrame of respondents Adds columns: agemarry, age, decade, fives """ resp['agemarry'] = (resp.cmmarrhx - resp.cmbirth) / 12.0 resp['age'] = (resp.cmintvw - resp.cmbirth) / 12.0 # if married, we need agemarry; if not married, we need age resp['missing'] = np.where(resp.evrmarry, resp.agemarry.isnull(), resp.age.isnull()) month0 = pd.to_datetime('1899-12-15') dates = [month0 + pd.DateOffset(months=cm) for cm in resp.cmbirth] resp['year'] = (pd.DatetimeIndex(dates).year - 1900) #resp['decade'] = resp.year // 10 #resp['fives'] = resp.year // 5 DigitizeResp(resp) def DigitizeResp(df): """Computes indices for age, agemarry, and birth year. Groups each of these variables into bins and then assigns an index to each bin. For example, anyone between 30 and 30.99 year old is assigned age_index 30. Anyone born in the 80s is given the year_index 80. This function allows me to run the analysis with different levels of granularity. df: DataFrame """ age_min = 10 age_max = 55 age_step = 1 age_bins = np.arange(age_min, age_max, age_step) year_min = 0 year_max = 120 year_step = 10 year_bins = np.arange(year_min, year_max, year_step) df['age_index'] = np.digitize(df.age, age_bins) * age_step df.age_index += age_min - age_step df.loc[df.age.isnull(), 'age_index'] = np.nan df['agemarry_index'] = np.digitize(df.agemarry, age_bins) * age_step df.agemarry_index += age_min - age_step df.loc[df.agemarry.isnull(), 'agemarry_index'] = np.nan df['birth_index'] = np.digitize(df.year, year_bins) * year_step df.birth_index += year_min - year_step def ReadCanadaCycle5(): """ """ #age at first marriage: CC232 #age of respondent at interview: C3 #final weight: C1 #marital status: C5 #Respondent every married: CC227 pass def ReadCanadaCycle6(): """ """ #age at first marriage: CC232 #age of respondent at interview: C3 #final weight: C1 #marital status: C5 #Respondent every married: CC227 pass def ReadMaleResp2002(): """Reads respondent data from NSFG Cycle 6. returns: DataFrame """ usecols = ['caseid', 'mardat01', 'cmdivw', 'cmbirth', 'cmintvw', 'evrmarry', 'finalwgt', 'fmarit', 'timesmar', 'marrend4', #'marrend', 'marrend2', 'marrend3', marrend5', 'marrend6', ] df = ReadResp('2002Male.dct', '2002Male.dat.gz', usecols=usecols) #df.marrend.replace([8,9], np.nan, inplace=True) #df.marrend2.replace([8,9], np.nan, inplace=True) #df.marrend3.replace([8,9], np.nan, inplace=True) df.marrend4.replace([8,9], np.nan, inplace=True) #df.marrend5.replace([8,9], np.nan, inplace=True) #df.marrend6.replace([8,9], np.nan, inplace=True) df.timesmar.replace([98,99], np.nan, inplace=True) # the way marriage ends are recorded is really confusing, # but it looks like marrend4 is the end of the first marriage. df['marend01'] = df.marrend4 df['cmmarrhx'] = df.mardat01 df['evrmarry'] = (df.timesmar > 0) df['divorced'] = (df.marend01==2) | (df.marend01==3) df['separated'] = (df.marend01==4) df['widowed'] = (df.marend01==1) df['stillma'] = (df.timesmar== 1) & (df.fmarit==1) df['cycle'] = 6 CleanResp(df) return df def ReadMaleResp2010(): """Reads respondent data from NSFG Cycle 7. returns: DataFrame """ usecols = ['caseid', 'mardat01', 'cmdivw', 'cmbirth', 'cmintvw', 'evrmarry', 'wgtq1q16', 'marend01', 'rmarital', 'fmarno', 'mar1diss'] df = ReadResp('2006_2010_MaleSetup.dct', '2006_2010_Male.dat.gz', usecols=usecols) df['cmmarrhx'] = df.mardat01 df['evrmarry'] = (df.evrmarry==1) df['divorced'] = (df.marend01==1) df['separated'] = (df.marend01==2) df['widowed'] = (df.marend01==3) df['stillma'] = (df.fmarno == 1) & (df.rmarital==1) df['finalwgt'] = df.wgtq1q16 df['cycle'] = 7 CleanResp(df) return df def ReadMaleResp2013(): """Reads respondent data from NSFG Cycle 8. returns: DataFrame """ usecols = ['caseid', 'mardat01', 'cmdivw', 'cmbirth', 'cmintvw', 'evrmarry', 'wgt2011_2013', 'marend01', 'rmarital', 'fmarno', 'mar1diss'] df = ReadResp('2011_2013_MaleSetup.dct', '2011_2013_MaleData.dat.gz', usecols=usecols) df['cmmarrhx'] = df.mardat01 df['evrmarry'] = (df.evrmarry==1) df['divorced'] = (df.marend01==1) df['separated'] = (df.marend01==2) df['widowed'] = (df.marend01==3) df['stillma'] = (df.fmarno == 1) & (df.rmarital==1) df['finalwgt'] = df.wgt2011_2013 df['cycle'] = 8 CleanResp(df) return df def ReadMaleResp2015(): """Reads respondent data from NSFG Cycle 9. returns: DataFrame """ usecols = ['caseid', 'mardat01', 'cmdivw', 'cmbirth', 'cmintvw', 'evrmarry', 'wgt2013_2015', 'marend01', 'rmarital', 'fmarno', 'mar1diss'] df = ReadResp('2013_2015_MaleSetup.dct', '2013_2015_MaleData.dat.gz', usecols=usecols) df['cmmarrhx'] = df.mardat01 df['evrmarry'] = (df.evrmarry==1) df['divorced'] = (df.marend01==1) df['separated'] = (df.marend01==2) df['widowed'] = (df.marend01==3) df['stillma'] = (df.fmarno == 1) & (df.rmarital==1) df['finalwgt'] = df.wgt2013_2015 df['cycle'] = 9 CleanResp(df) return df def ReadMaleResp2017(): """Reads respondent data from NSFG Cycle 10. returns: DataFrame """ usecols = ['caseid', 'mardat01', 'cmintvw', 'ager', 'evrmarry', 'wgt2015_2017', 'marend01', 'rmarital', 'fmarno', 'mar1diss'] df = ReadResp('2015_2017_MaleSetup.dct', '2015_2017_MaleData.dat.gz', usecols=usecols) # since cmbirth and cmmarrhx are no longer included, # we have to compute them based on other variables; # the result can be off by up to 12 months df['cmbirth'] = df.cmintvw - df.ager*12 df['cmmarrhx'] = (df.mardat01-1900) * 12 df['evrmarry'] = (df.evrmarry==1) df['divorced'] = (df.marend01==1) df['separated'] = (df.marend01==2) df['widowed'] = (df.marend01==3) df['stillma'] = (df.fmarno == 1) & (df.rmarital==1) df['finalwgt'] = df.wgt2015_2017 df['cycle'] = 10 # Instead of calling CleanResp, we have to customize #CleanResp(df) df['agemarry'] = (df.cmmarrhx - df.cmbirth) / 12.0 df['age'] = (df.cmintvw - df.cmbirth) / 12.0 # if married, we need agemarry; if not married, we need age df['missing'] = np.where(df.evrmarry, df.agemarry.isnull(), df.age.isnull()) month0 = pd.to_datetime('1899-12-15') dates = [month0 + pd.DateOffset(months=cm) for cm in df.cmbirth] df['year'] = (pd.DatetimeIndex(dates).year - 1900) DigitizeResp(df) return df def Validate1982(df): assert(len(df) == 7969) assert(len(df[df.evrmarry]) == 4651) assert(df.agemarry.value_counts().max() == 71) def Validate1988(df): assert(len(df) == 8450) assert(len(df[df.evrmarry]) == 5290) assert(df.agemarry.value_counts().max() == 73) def Validate1995(df): assert(len(df) == 10847) assert(len(df[df.evrmarry]) == 6841) assert(df.agemarry.value_counts().max() == 79) def Validate2002(df): assert(len(df) == 7643) assert(sum(df.evrmarry) == 4126) assert(df.agemarry.value_counts().max() == 45) def Validate2010(df): assert(len(df) == 12279) assert(sum(df.evrmarry) == 5534) assert(df.agemarry.value_counts().max() == 64) def Validate2013(df): assert(len(df) == 5601) assert(sum(df.evrmarry) == 2452) assert(df.agemarry.value_counts().max() == 33) def Validate2015(df): assert(len(df) == 5699) assert(sum(df.evrmarry) == 2401) assert(df.agemarry.value_counts().max() == 25) def Validate2017(df): assert(len(df) == 5554) assert(sum(df.evrmarry) == 2582) assert(df.agemarry.value_counts().max() == 29) def main(): print('Cycle 10') resp10 = ReadFemResp2017() Validate2017(resp10) print('Cycle 9') resp9 = ReadFemResp2015() Validate2015(resp9) print('Cycle 8') resp8 = ReadFemResp2013() Validate2013(resp8) print('Cycle 7') resp7 = ReadFemResp2010() Validate2010(resp7) print('Cycle 6') resp6 = ReadFemResp2002() Validate2002(resp6) print('Cycle 5') resp5 = ReadFemResp1995() Validate1995(resp5) print('Cycle 4') resp4 = ReadFemResp1988() Validate1988(resp4) print('Cycle 3') resp3 = ReadFemResp1982() Validate1982(resp3) if __name__ == '__main__': main()
29.064718
79
0.599196
3,438
27,844
4.801629
0.173066
0.00836
0.029077
0.038769
0.454022
0.43064
0.393991
0.371699
0.326084
0.292767
0
0.074426
0.258799
27,844
957
80
29.095089
0.725458
0.211895
0
0.378987
0
0
0.131929
0.021021
0
0
0
0
0.045028
1
0.073171
false
0.003752
0.02439
0
0.138837
0.016886
0
0
0
null
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
null
0
0
0
0
0
0
0
0
0
0
0
0
1
0
d4b13f250b052bca7bffe7a5880d063d7c169a7e
3,955
py
Python
xfel/merging/application/reflection_table_utils.py
ErwinP/cctbx_project
58f9fb5ed38c7391510e892f0ca9520467b692c1
[ "BSD-3-Clause-LBNL" ]
null
null
null
xfel/merging/application/reflection_table_utils.py
ErwinP/cctbx_project
58f9fb5ed38c7391510e892f0ca9520467b692c1
[ "BSD-3-Clause-LBNL" ]
null
null
null
xfel/merging/application/reflection_table_utils.py
ErwinP/cctbx_project
58f9fb5ed38c7391510e892f0ca9520467b692c1
[ "BSD-3-Clause-LBNL" ]
null
null
null
from __future__ import absolute_import, division, print_function from six.moves import range from dials.array_family import flex import math class reflection_table_utils(object): @staticmethod def get_next_hkl_reflection_table(reflections): '''Generate asu hkl slices from an asu hkl-sorted reflection table''' if reflections.size() == 0: yield reflections i_begin = 0 hkl_ref = reflections[0].get('miller_index_asymmetric') for i in range(reflections.size()): hkl = reflections[i].get('miller_index_asymmetric') if hkl == hkl_ref: continue else: yield reflections[i_begin:i] i_begin = i hkl_ref = hkl yield reflections[i_begin:i+1] @staticmethod def select_odd_experiment_reflections(reflections): 'Select reflections from experiments with odd ids. An experiment id must be a string representing a hexadecimal number' sel = flex.bool() for refl in reflections: sel.append(int(refl['exp_id'], 16)%2 != 0) return reflections.select(sel) @staticmethod def select_even_experiment_reflections(reflections): 'Select reflections from experiments with even ids. An experiment id must be a string representing a hexadecimal number' sel = flex.bool() for refl in reflections: sel.append(int(refl['exp_id'], 16)%2 == 0) return reflections.select(sel) @staticmethod def merged_reflection_table(): '''Create a reflection table for storing merged HKLs''' table = flex.reflection_table() table['miller_index'] = flex.miller_index() table['intensity'] = flex.double() table['sigma'] = flex.double() table['multiplicity'] = flex.int() return table @staticmethod def merge_reflections(reflections, min_multiplicity): '''Merge intensities of multiply-measured symmetry-reduced HKLs''' merged_reflections = reflection_table_utils.merged_reflection_table() for refls in reflection_table_utils.get_next_hkl_reflection_table(reflections=reflections): if refls.size() == 0: break # unless the input "reflections" list is empty, generated "refls" lists cannot be empty hkl = refls[0]['miller_index_asymmetric'] # This assert is timeconsuming when using a small number of cores #assert not (hkl in merged_reflections['miller_index']) # i.e. assert that the input reflection table came in sorted refls = refls.select(refls['intensity.sum.variance'] > 0.0) if refls.size() >= min_multiplicity: weighted_intensity_array = refls['intensity.sum.value'] / refls['intensity.sum.variance'] weights_array = flex.double(refls.size(), 1.0) / refls['intensity.sum.variance'] weighted_mean_intensity = flex.sum(weighted_intensity_array) / flex.sum(weights_array) standard_error_of_weighted_mean_intensity = 1.0/math.sqrt(flex.sum(weights_array)) merged_reflections.append( {'miller_index' : hkl, 'intensity' : weighted_mean_intensity, 'sigma' : standard_error_of_weighted_mean_intensity, 'multiplicity' : refls.size()}) return merged_reflections @staticmethod def prune_reflection_table_keys(reflections, keys_to_delete=None, keys_to_keep=None): '''Remove reflection table keys: either inclusive or exclusive''' if len(reflections) != 0: all_keys = list() for key in reflections[0]: all_keys.append(key) if keys_to_delete != None: for key in keys_to_delete: if key in all_keys: del reflections[key] elif keys_to_keep != None: for key in all_keys: #if not key in ['intensity.sum.value', 'intensity.sum.variance', 'miller_index', 'miller_index_asymmetric', 'exp_id', 'odd_frame', 's1']: if not key in keys_to_keep: del reflections[key] return reflections
40.357143
147
0.683439
501
3,955
5.189621
0.269461
0.075
0.032308
0.025385
0.246154
0.228462
0.173077
0.173077
0.120769
0.120769
0
0.007477
0.22225
3,955
97
148
40.773196
0.837776
0.22048
0
0.184211
0
0
0.144765
0.040971
0
0
0
0
0
1
0.078947
false
0
0.052632
0
0.210526
0.013158
0
0
0
null
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
null
0
0
0
0
0
0
0
0
0
0
0
0
1
0
d4b2a9a044269ea09a095573c7237e7f034915c1
5,359
py
Python
torchmetrics/retrieval/retrieval_fallout.py
rudaoshi/metrics
c018348619bd7e375cb86abf7dfcaddb7208a36d
[ "Apache-2.0" ]
null
null
null
torchmetrics/retrieval/retrieval_fallout.py
rudaoshi/metrics
c018348619bd7e375cb86abf7dfcaddb7208a36d
[ "Apache-2.0" ]
null
null
null
torchmetrics/retrieval/retrieval_fallout.py
rudaoshi/metrics
c018348619bd7e375cb86abf7dfcaddb7208a36d
[ "Apache-2.0" ]
null
null
null
# Copyright The PyTorch Lightning team. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. from typing import Any, Callable, Optional import pangu.core.backend as B from pangu.core.backend import Tensor, tensor from torchmetrics.functional.retrieval.fall_out import retrieval_fall_out from torchmetrics.retrieval.retrieval_metric import RetrievalMetric from torchmetrics.utilities.data import get_group_indexes class RetrievalFallOut(RetrievalMetric): """Computes `Fall-out`_. Works with binary target data. Accepts float predictions from a model output. Forward accepts: - ``preds`` (float tensor): ``(N, ...)`` - ``target`` (long or bool tensor): ``(N, ...)`` - ``indexes`` (long tensor): ``(N, ...)`` ``indexes``, ``preds`` and ``target`` must have the same dimension. ``indexes`` indicate to which query a prediction belongs. Predictions will be first grouped by ``indexes`` and then `Fall-out` will be computed as the mean of the `Fall-out` over each query. Args: empty_target_action: Specify what to do with queries that do not have at least a negative ``target``. Choose from: - ``'neg'``: those queries count as ``0.0`` (default) - ``'pos'``: those queries count as ``1.0`` - ``'skip'``: skip those queries; if all queries are skipped, ``0.0`` is returned - ``'error'``: raise a ``ValueError`` k: consider only the top k elements for each query (default: None, which considers them all) compute_on_step: Forward only calls ``update()`` and return None if this is set to False. default: True dist_sync_on_step: Synchronize metric state across processes at each ``forward()`` before returning the value at the step. default: False process_group: Specify the process group on which synchronization is called. default: None (which selects the entire world) dist_sync_fn: Callback that performs the allgather operation on the metric state. When `None`, DDP will be used to perform the allgather. default: None Raises: ValueError: If ``k`` parameter is not `None` or an integer larger than 0 Example: >>> from torchmetrics import RetrievalFallOut >>> indexes = tensor([0, 0, 0, 1, 1, 1, 1]) >>> preds = tensor([0.2, 0.3, 0.5, 0.1, 0.3, 0.5, 0.2]) >>> target = tensor([False, False, True, False, True, False, True]) >>> fo = RetrievalFallOut(k=2) >>> fo(preds, target, indexes=indexes) tensor(0.5000) """ higher_is_better = False def __init__( self, empty_target_action: str = "pos", k: int = None, compute_on_step: bool = True, dist_sync_on_step: bool = False, process_group: Optional[Any] = None, dist_sync_fn: Callable = None, ) -> None: super().__init__( empty_target_action=empty_target_action, compute_on_step=compute_on_step, dist_sync_on_step=dist_sync_on_step, process_group=process_group, dist_sync_fn=dist_sync_fn, ) if (k is not None) and not (isinstance(k, int) and k > 0): raise ValueError("`k` has to be a positive integer or None") self.k = k def compute(self) -> Tensor: """First concat state `indexes`, `preds` and `target` since they were stored as lists. After that, compute list of groups that will help in keeping together predictions about the same query. Finally, for each group compute the `_metric` if the number of negative targets is at least 1, otherwise behave as specified by `self.empty_target_action`. """ indexes = B.cat(self.indexes, dim=0) preds = B.cat(self.preds, dim=0) target = B.cat(self.target, dim=0) res = [] groups = get_group_indexes(indexes) for group in groups: mini_preds = preds[group] mini_target = target[group] if not (1 - mini_target).sum(): if self.empty_target_action == "error": raise ValueError("`compute` method was provided with a query with no negative target.") if self.empty_target_action == "pos": res.append(tensor(1.0)) elif self.empty_target_action == "neg": res.append(tensor(0.0)) else: # ensure list containt only float tensors res.append(self._metric(mini_preds, mini_target)) return B.stack([x.to(preds) for x in res]).mean() if res else tensor(0.0).to(preds) def _metric(self, preds: Tensor, target: Tensor) -> Tensor: return retrieval_fall_out(preds, target, k=self.k)
40.598485
120
0.630715
719
5,359
4.59388
0.336579
0.026642
0.041175
0.031789
0.038147
0.010294
0
0
0
0
0
0.012762
0.268893
5,359
131
121
40.908397
0.830271
0.552528
0
0
0
0
0.055505
0
0
0
0
0
0
1
0.0625
false
0
0.125
0.020833
0.270833
0
0
0
0
null
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
null
0
0
0
0
0
0
0
0
0
0
0
0
1
0
d4b523573d56f337047743520fa550fd29576318
13,961
py
Python
project/app/paste/controllers.py
An0nYm0u5101/Pastebin
aef35abee69ce7ce240d3a3f64bb19446468d30d
[ "MIT" ]
1
2020-08-08T06:07:47.000Z
2020-08-08T06:07:47.000Z
project/app/paste/controllers.py
An0nYm0u5101/Pastebin
aef35abee69ce7ce240d3a3f64bb19446468d30d
[ "MIT" ]
null
null
null
project/app/paste/controllers.py
An0nYm0u5101/Pastebin
aef35abee69ce7ce240d3a3f64bb19446468d30d
[ "MIT" ]
1
2020-08-08T06:07:50.000Z
2020-08-08T06:07:50.000Z
from flask import Blueprint, request, render_template, \ flash, g, session, redirect, url_for, jsonify from app import db, requires_auth from flask_cors import CORS from .models import Paste import uuid from datetime import datetime from app.user.models import User from pygments import highlight from pygments.lexers import get_lexer_by_name, guess_lexer from pygments.formatters import HtmlFormatter from functools import wraps from datetime import datetime from dateutil import parser def requires_admin(f): @wraps(f) def decorated(*args, **kwargs): if 'user_id' not in session: return jsonify(message="Unauthorized", success=False), 401 user_id = session['user_id'] user = User.query.filter(User.id == user_id).first() if(user.user_type != 2): return jsonify(message="Unauthorized", success=False), 401 return f(*args, **kwargs) return decorated mod_paste = Blueprint('paste', __name__) CORS(mod_paste) def is_active(paste): return parser.parse(paste.expire_time) > datetime.now() @mod_paste.route('/create_paste', methods=['GET']) @requires_auth def create_form(): curr_id = session['user_id'] user = User.query.filter(User.id == curr_id).first() return render_template('user.html', username=user.username) @mod_paste.route('/create_paste', methods=['POST']) def create_paste(): title = request.form['title'] text = request.form['text'] paste_type = request.form['type'] if 'user_id' in session: user_id = session['user_id'] else: user = User.query.filter(User.username == 'Guest').first() user_id = user.id lang = request.form['lang'] time_form = request.form['time'] expire_time = str(time_form) add_time = str(datetime.now()) url = str(uuid.uuid4()) report_count = 0 try: paste = Paste(title, text, lang, add_time, expire_time, user_id, url, report_count, paste_type) user = User.query.filter(User.id == user_id).first() x = user.paste_count user.paste_count = x + 1 db.session.add(paste) db.session.commit() # jsonify(success=True, paste=paste.to_dict()) return jsonify({'url': url}), 200 except: return jsonify({'error': 'Error while creating Paste, Please check if all fields are filled'}), 400 @mod_paste.route('/paste', methods=['GET']) @requires_auth def get_all_pastes(): # user_id = session['user_id'] # pastes = paste.query.filter(paste.user_id == user_id).all() if 'user_id' in session: curr_id = session['user_id'] user = User.query.filter(curr_id == User.id).first() if user.user_type == 2: return render_template('admin_mypaste.html') return render_template("mypaste.html") else: return jsonify({'error': 'Please Login to Continue'}), 400 # return jsonify(success=True, pastes=[paste.to_dict() for paste in # pastes]) @mod_paste.route('/api/paste', methods=['POST']) @requires_auth def get_all_pastes_object(): user_id = session['user_id'] user = User.query.filter(user_id == User.id).first() pastes = Paste.query.filter(Paste.user_id == user_id).all() active = [] for paste in pastes: if is_active(paste): active.append(paste.to_dict()) else: userid_to_red = paste.user_id user_to_red = User.query.filter(userid_to_red == User.id) user_to_red.paste_count = user_to_red.paste_count - 1 db.session.delete(paste) db.session.commit() return jsonify({'paste_list': active, 'username': user.username}), 200 @mod_paste.route('/<url>/embed', methods=['GET']) def embed_code_form(url): paste = Paste.query.filter(Paste.url == url).first() if is_active(paste): return render_template('embed.html', paste_text=paste.text, paste_link="http://127.0.0.1:8080/" + url) else: userid_to_red = paste.user_id user_to_red = User.query.filter(User.id == userid_to_red).first() user_to_red.paste_count = user_to_red.paste_count - 1 db.session.delete(paste) db.session.commit() return render_template("index.html"), 404 # @mod_paste.route('/<url>/embed', methods=['POST']) # def embed_code(url): # paste = Paste.query.filter(Paste.url == url).first() # return jsonify(paste_text = paste.text,paste_link = url) @mod_paste.route('/<url>/embed/output', methods=['GET']) def embed_code_disp(url): paste = Paste.query.filter(Paste.url == url).first() if is_active(paste): return render_template('embed_output.html') else: userid_to_red = paste.user_id user_to_red = User.query.filter(User.id == userid_to_red).first() user_to_red.paste_count = user_to_red.paste_count - 1 db.session.delete(paste) db.session.commit() return render_template("index.html"), 404 # @mod_paste.route('/paste', methods=['GET']) # @requires_auth # def get_all_pastes(): # # user_id = session['user_id'] # # pastes = paste.query.filter(paste.user_id == user_id).all() # curr_id = session['user_id'] # user = User.query.filter(User.id == curr_id).first() # paste_list = Paste.query.filter(curr_id == Paste.user_id).all() # url_pre = "/" # for paste in paste_list: # paste.url = url_pre + paste.url # if user.user_type == 1: # return render_template('mypaste.html', paste_list=paste_list) # return render_template('admin_mypaste.html',paste_list = paste_list) # # return jsonify(success=True, pastes=[paste.to_dict() for paste in # # pastes]) # # # @mod_paste.route('/api/paste', methods=['POST']) # @requires_auth # def get_all_pastes_object(): # user_id = session['user_id'] # user = User.query.filter(user_id == User.id).first() # pastes = Paste.query.filter(Paste.user_id == user_id).all() # active = [] # for paste in pastes: # temp_paste = {} # if paste.is_active(): # temp_paste['title'] = paste.title # temp_paste['add_time']=paste.add_time # temp_paste['expire_time']=paste.expire_time # temp_paste['lang']=paste.lang # temp_paste['url']=paste.url # active.append(temp_paste) # # return jsonify({'paste_list':active,'username':user.username}),200 # @mod_paste.route('/paste/<id>', methods=['GET']) # @requires_auth # def get_paste(id): # user_id = session['user_id'] # paste = paste.query.filter( # Paste.id == id, Paste.user_id == user_id).first() # if paste is None: # return render_template("index.html"),4044 # else: # return jsonify(success=True, paste=paste.to_dict()) # @mod_paste.route('/paste/<id>', methods=['POST']) # @requires_auth # def edit_paste(id): # user_id = session['user_id'] # paste = Paste.query.filter( # Paste.id == id, Paste.user_id == user_id).first() # if paste is None: # return render_template("index.html"),4044 # else: # paste.title = request.form['title'] # paste.text = request.form['text'] # paste.color = request.form['color'] # paste.lang = request.form['lang'] # db.session.commit() # return jsonify(success=True) @mod_paste.route('/<url>/delete', methods=['POST']) @requires_auth def delete_paste(url): user_id = session['user_id'] # print(user_id) paste = Paste.query.filter(Paste.url == url).first() user = User.query.filter(User.id == user_id).first() if paste is None: return render_template("index.html"), 404 if is_active(paste): if paste.user_id == user_id or user.user_type == 2: userid_to_red = paste.user_id user_to_red = User.query.filter(User.id == userid_to_red).first() user_to_red.paste_count = user_to_red.paste_count - 1 db.session.delete(paste) db.session.commit() return jsonify(success=True, user_type=user.user_type), 200 else: return jsonify(success=False), 400 else: userid_to_red = paste.user_id user_to_red = User.query.filter(User.id == userid_to_red).first() user_to_red.paste_count = user_to_red.paste_count - 1 db.session.delete(paste) db.session.commit() return render_template("index.html"), 404 # @mod_paste.route('/<url>', methods=['GET']) # def display_paste(url): # paste = Paste.query.filter(Paste.url == url).first() # style = HtmlFormatter().get_style_defs('.highlight') # lexer = get_lexer_by_name(paste.lang) # formatter = HtmlFormatter(linenos=True, cssclass="highlight") # result = highlight(paste.text, lexer, formatter) # return render_template("view_paste.html", paste_title=paste.title, # paste_lang=paste.lang, highlight_style=style, @mod_paste.route('/<url>', methods=['GET']) # paste_text=result,paste_rawdata = paste.text) def display_paste(url): paste = Paste.query.filter(Paste.url == url).first() if Paste.query.filter(Paste.url == url).first() != None: if is_active(paste): if 'user_id' in session: if(paste.paste_type == "1" and session['user_id'] != paste.user_id): return render_template("index.html"), 200 user_id = session['user_id'] user = User.query.filter(User.id == user_id).first() if user.user_type == 1: return render_template('view_paste.html') if user.user_type == 2: return render_template('view_paste_admin.html') return render_template("view_paste_guest.html") else: userid_to_red = paste.user_id user_to_red = User.query.filter(User.id == userid_to_red).first() user_to_red.paste_count = user_to_red.paste_count - 1 db.session.delete(paste) db.session.commit() return render_template("index.html"), 404 else: return render_template("index.html"), 404 @mod_paste.route('/api/<url>', methods=['POST']) def ret_paste(url): paste = Paste.query.filter(Paste.url == url).first() user = User.query.filter(paste.user_id == User.id).first() if is_active(paste): return jsonify({'paste_owner': user.username, 'paste_text': paste.text, 'paste_title': paste.title, 'paste_lang': paste.lang, 'paste_add': paste.add_time, 'paste_expire': paste.expire_time}), 200 else: userid_to_red = paste.user_id user_to_red = User.query.filter(User.id == userid_to_red).first() user_to_red.paste_count = user_to_red.paste_count - 1 db.session.delete(paste) db.session.commit() return render_template("index.html"), 404 # @mod_paste.route('/<url>/add_report', methods=['POST']) # @requires_auth # def to_delete(url): # paste_to_delete = Paste.query.filter(Paste.url == url).first() # if paste_to_delete.report_count > 5: # db.session.delete(paste_to_delete) # else: # paste_to_delete.report_count = paste_to_delete.report_count + 1 # db.session.commit() # curr_id = session['user_id'] # paste_list = Paste.query.filter(Paste.user_id == curr_id).all() # url_pre = "/" # for paste in paste_list: # paste.url = url_pre + paste.url # return render_template('mypaste.html', paste_list=paste_list) @mod_paste.route('/<url>/edit', methods=['GET']) @requires_auth def edit_form(url): if 'user_id' in session: user_id = session['user_id'] paste = Paste.query.filter(Paste.url == url).first() if is_active(paste): if paste.user_id == user_id: return render_template('editpaste.html') return jsonify(success=False, reply="Not Authorized"), 400 else: userid_to_red = paste.user_id user_to_red = User.query.filter(User.id == userid_to_red).first() user_to_red.paste_count = user_to_red.paste_count - 1 db.session.delete(paste) db.session.commit() return render_template("index.html"), 404 return jsonify(success=False, reply="Please Login"), 400 @mod_paste.route('/<url>/edit', methods=['POST']) @requires_auth def edit_paste(url): if 'user_id' in session: user_id = session['user_id'] paste = Paste.query.filter(Paste.url == url).first() if not is_active(paste): userid_to_red = paste.user_id user_to_red = User.query.filter(User.id == userid_to_red).first() user_to_red.paste_count = user_to_red.paste_count - 1 db.session.delete(paste) db.session.commit() return render_template('index.html'), 404 if paste.user_id != user_id: return jsonify(success=False, reply="Not Authorized"), 400 title = request.form['title'] text = request.form['text'] lang = request.form['lang'] time_form = request.form['time'] paste_type = request.form['type'] expire_time = str(time_form) paste.title = title paste.text = text paste.lang = lang paste.expire_time = expire_time paste.paste_type = paste_type db.session.commit() return jsonify(success=True, url=url) return jsonify(success=False, reply="Please Login") @mod_paste.route('/admin/pastes', methods=['GET']) @requires_admin def all_pastes(): paste_list = db.session.all() url_pre = "/" for paste in paste_list: if is_active(paste): paste.url = url_pre + paste.url else: userid_to_red = paste.user_id user_to_red = User.query.filter(User.id == userid_to_red).first() user_to_red.paste_count = user_to_red.paste_count - 1 db.session.delete(paste) db.session.commit() return render_template('allpaste.html', paste_list=paste_list) @mod_paste.route('/<username>/paste', methods=['GET']) @requires_admin def get_user_pastes(username): # user_id = session['user_id'] # pastes = paste.query.filter(paste.user_id == user_id).all() if 'user_id' in session: return render_template('user_paste.html') else: return jsonify({'error': 'Please Login to Continue'}), 400 # return jsonify(success=True, pastes=[paste.to_dict() for paste in # pastes]) @mod_paste.route('/<username>/api/paste', methods=['POST']) #@requires_admin def get_user_pastes_object(username): # admin_id = session['user_id'] # admin = User.query.filter(admin_id == User.id).first() user = User.query.filter(User.username == username).first() pastes = Paste.query.filter(Paste.user_id == user.id).all() active = [] for paste in pastes: if is_active(paste): active.append(paste.to_dict()) else: userid_to_red = paste.user_id user_to_red = User.query.filter(User.id == userid_to_red).first() user_to_red.paste_count = user_to_red.paste_count - 1 db.session.delete(paste) db.session.commit() return jsonify({'paste_list': active, 'username': user.username}), 200
34.302211
197
0.698016
2,077
13,961
4.46702
0.07222
0.069843
0.040957
0.037185
0.767299
0.692175
0.632141
0.577603
0.533844
0.492347
0
0.009761
0.148772
13,961
406
198
34.3867
0.770953
0.287658
0
0.580769
0
0
0.100539
0.006404
0
0
0
0
0
1
0.065385
false
0
0.05
0.003846
0.269231
0.007692
0
0
0
null
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
null
0
0
0
0
0
0
0
0
0
0
0
0
1
0
d4b56ca40567b39870ee94f1ef850a0b0b2f1d60
8,333
py
Python
control_drone/run_model_on_cam.py
Apiquet/DeepLearningFrameworkFromScratch
798ac42aa1a05286eb148576072e015fd94dbf94
[ "MIT" ]
1
2020-12-18T14:40:49.000Z
2020-12-18T14:40:49.000Z
control_drone/run_model_on_cam.py
Apiquet/DeepLearningFrameworkFromScratch
798ac42aa1a05286eb148576072e015fd94dbf94
[ "MIT" ]
null
null
null
control_drone/run_model_on_cam.py
Apiquet/DeepLearningFrameworkFromScratch
798ac42aa1a05286eb148576072e015fd94dbf94
[ "MIT" ]
null
null
null
#!/usr/bin/env python # -*- coding: utf-8 -*- """ This script run neural network model on a camera live stream """ import argparse import cv2 import numpy as np import os import time import sys COMMANDS = {0: "move_forward", 1: "go_down", 2: "rot_10_deg", 3: "go_up", 4: "take_off", 5: "land", 6: "idle"} def send_command(anafi, command_id): """ Function to send commands to an Anafi drone in function of the command id """ if command_id not in COMMANDS: raise f"Command id not in COMMANDS choices: {command_id}" print("The following command will be sent: ", COMMANDS[command_id]) if COMMANDS[command_id] == "move_forward": anafi.move_relative(dx=1, dy=0, dz=0, dradians=0) if COMMANDS[command_id] == "go_down": anafi.move_relative(dx=0, dy=0, dz=-0.5, dradians=0) if COMMANDS[command_id] == "rot_10_deg": anafi.move_relative(dx=0, dy=0, dz=0, dradians=0.785) if COMMANDS[command_id] == "go_up": anafi.move_relative(dx=0, dy=0, dz=0.5, dradians=0) if COMMANDS[command_id] == "take_off": anafi.safe_takeoff(5) if COMMANDS[command_id] == "land": anafi.safe_land(5) return def main(): parser = argparse.ArgumentParser() parser.add_argument( "-p", "--weight_path", required=True, type=str, help="Path to load weights for the model." ) parser.add_argument( "-a", "--pyparrot_path", required=True, type=str, help="Path to pyparrot module downloaded from amymcgovern on github." ) parser.add_argument( "-w", "--img_width", required=False, default=28, type=int, help="Image width." ) parser.add_argument( "-n", "--num_classes", required=False, default=7, type=int, help="Number of classes." ) parser.add_argument( "-c", "--crop", required=False, default=None, type=str, help="Crop image, format: MinWidth,MaxWidth,MinHeight,MaxHeight.\ Set -1 for the unchanged ones" ) parser.add_argument( "-r", "--resize", required=False, default=None, type=str, help="Resize shape, format: height,width" ) parser.add_argument( "-b", "--binarize", required=False, default=None, type=str, help="To binarize images, format for thresholding: min,max" ) parser.add_argument( "-g", "--gray", required=False, action="store_true", help="To save 1-channel images" ) parser.add_argument( "-e", "--erode", required=False, default=None, type=str, help="Erode option, format: kernel_size,iteration" ) parser.add_argument( "-d", "--dilate", required=False, default=None, type=str, help="Dilate option, format: kernel_size,iteration" ) parser.add_argument( "-m", "--camid", required=False, default=0, type=int, help="Camera ID, default is 0" ) parser.add_argument( "-t", "--tensorflow", required=False, action="store_true", help="To specify if Tensorflow model is used." ) parser.add_argument( "-z", "--number_of_confimation", required=False, default=3, type=int, help="Minimum number of identical commands before sending to drone." ) args = parser.parse_args() """ Drone connection """ sys.path.append(args.pyparrot_path) from pyparrot.Anafi import Anafi print("Connecting to drone...") anafi = Anafi(drone_type="Anafi", ip_address="192.168.42.1") success = anafi.connect(10) print(success) print("Sleeping few seconds...") anafi.smart_sleep(3) """ Load model """ print("Loading model...") input_size = args.img_width**2 num_class = args.num_classes hidden_size = 128 if args.tensorflow: import tensorflow as tf model = tf.keras.models.load_model(args.weight_path) else: script_path = os.path.realpath(__file__) sys.path.append(os.path.dirname(script_path) + "/../") from homemade_framework import framework as NN model = NN.Sequential([NN.Linear(input_size, hidden_size), NN.LeakyReLU(), NN.BatchNorm(), NN.Linear(hidden_size, hidden_size), NN.LeakyReLU(), NN.BatchNorm(), NN.Linear(hidden_size, num_class), NN.Softmax()], NN.LossMSE()) model.load(args.weight_path) """ Webcam process """ print("Start webcam...") cam = cv2.VideoCapture(args.camid) ret, frame = cam.read() min_height, max_height = 0, frame.shape[0] min_width, max_width = 0, frame.shape[1] print("Cam resolution: {}x{}".format(max_width, max_height)) if args.crop is not None: res = [int(x) for x in args.crop.split(',')] if res[0] != -1: min_width = res[0] if res[1] != -1: max_width = res[1] if res[2] != -1: min_height = res[2] if res[3] != -1: max_height = res[3] print("Image cropped to minWidth:maxWidth, minHeight:maxHeight: {}:{}\ , {},{}".format(min_width, max_width, min_height, max_height)) pause = False imgs = [] while True: ret, frame = cam.read() if not ret: print("failed to grab frame") break if args.crop is not None: frame = frame[min_height:max_height, min_width:max_width] cv2.imshow("Original image", frame) k = cv2.waitKey(1) if k % 256 == 27: # ESC pressed print("Escape hit, closing...") break elif k % 256 == ord('p'): # p pressed if pause: pause = False else: pause = True if not pause: if args.gray: frame = cv2.cvtColor(frame, cv2.COLOR_BGR2GRAY) if args.binarize: frame = cv2.medianBlur(frame, 5) min_thresh, max_thresh = [int(x) for x in args.binarize.split(',')] ret, frame = cv2.threshold(frame, min_thresh, max_thresh, cv2.THRESH_BINARY) if args.erode is not None: k_size, iteration = [int(x) for x in args.erode.split(',')] kernel = np.ones((k_size, k_size), np.uint8) frame = cv2.erode(frame, kernel, iterations=int(iteration)) if args.dilate is not None: k_size, iteration = [int(x) for x in args.dilate.split(',')] kernel = np.ones((k_size, k_size), np.uint8) frame = cv2.dilate(frame, kernel, iterations=int(iteration)) if args.resize: height, width = [int(size) for size in args.resize.split(',')] frame = cv2.resize(frame, (height, width), interpolation=cv2.INTER_AREA) image = np.asarray(frame)/255. cv2.imshow("Input image for the model", frame) image = image.reshape([np.prod(image.shape)]) if len(imgs) < args.number_of_confimation: imgs.append(image) else: if args.tensorflow: results = np.argmax(model(np.asarray(imgs)), axis=1) else: results = NN.get_inferences(model, np.asarray(imgs)) print("Model's output on buffer: ", results) if np.unique(results).size == 1 and\ COMMANDS[results[0]] != "idle": send_command(anafi, results[0]) imgs = [] imgs = imgs[1:] imgs.append(image) time.sleep(0.3) cam.release() cv2.destroyAllWindows() if __name__ == '__main__': main()
29.867384
78
0.531621
979
8,333
4.40143
0.266599
0.027152
0.051288
0.026456
0.245301
0.229752
0.204456
0.129961
0.092365
0.086331
0
0.020654
0.343454
8,333
278
79
29.97482
0.766953
0.023881
0
0.280851
0
0
0.131546
0.008105
0
0
0
0
0
1
0.008511
false
0
0.038298
0
0.051064
0.046809
0
0
0
null
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
null
0
0
0
0
0
0
0
0
0
0
0
0
1
0
d4bc84fe21a49ee4da04551b3e65cc3308167280
2,449
py
Python
app/request.py
vincentmuya/News-highlight
67f61bb0bea69ec004c11a2148c62cd892a19615
[ "CNRI-Python" ]
null
null
null
app/request.py
vincentmuya/News-highlight
67f61bb0bea69ec004c11a2148c62cd892a19615
[ "CNRI-Python" ]
null
null
null
app/request.py
vincentmuya/News-highlight
67f61bb0bea69ec004c11a2148c62cd892a19615
[ "CNRI-Python" ]
null
null
null
import urllib.request import json from .models import News # Getting api key api_key = None # Getting the movie base url base_url = None def configure_request(app): global api_key,base_url api_key = app.config['NEWS_API_KEY'] base_url = app.config['NEWS_API_BASE_URL'] def get_news_source(country,category): ''' Function that gets the json response to our url request ''' get_news_source_url = base_url.format(country,category,api_key) with urllib.request.urlopen(get_news_source_url)as url: get_news_source_data = url.read() get_news_source_response = json.loads(get_news_source_data) print(get_news_source_response) source_result = None if get_news_source_response['articles']: source_result_list = get_news_source_response['articles'] source_result = process_result(source_result_list) return source_result def process_result(source_list): ''' this function processes the results and converts them into a list the source list is a list of dictionaries containing news results ''' source_result= [] for source_item in source_list: source = source_item.get('source') author = source_item.get('author') title = source_item.get('title') description = source_item.get('description') url = source_item.get('url') urlToImage = source_item.get('urlToImage') publishedAt = source_item.get('publishedAt') if urlToImage: source_object = News(source,author,title,description,url,urlToImage,publishedAt) source_result.append(source_object) return source_result def get_news(source): get_news_details_url = base_url.format(source,api_key) with urllib.request.urlopen(get_news_details_url) as url: news_details_data = url.read() news_details_response = json.loads(news_details_data) news_object = None if news_details_response: source = news_details_response.get('source') author = news_details_response.get('original_author') title = news_details_response.get('title') description = news_details_response.get('description') url = news_details_response.get('url') urlToImage = news_details_response.get('urlToImage') news_object = news(source,author,title,description,url,urlToImage,publishedAt) return news_object
33.094595
91
0.703144
316
2,449
5.142405
0.21519
0.051692
0.08
0.081231
0.172308
0.172308
0.172308
0.121846
0.076308
0
0
0
0.213965
2,449
73
92
33.547945
0.844156
0.094733
0
0.040816
0
0
0.0674
0
0
0
0
0
0
1
0.081633
false
0
0.061224
0
0.204082
0.020408
0
0
0
null
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
null
0
0
0
0
0
0
0
0
0
0
0
0
1
0