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
978a831843efed4c9a546c08310214668dcc7a6e
7,009
py
Python
docs/database_tables.py
wdr-data/wdr-okr
71c9e6e8d3521b1bb67d30310a93584389de2127
[ "MIT" ]
2
2021-07-28T08:46:13.000Z
2022-01-19T17:05:48.000Z
docs/database_tables.py
wdr-data/wdr-okr
71c9e6e8d3521b1bb67d30310a93584389de2127
[ "MIT" ]
3
2020-11-10T23:34:17.000Z
2021-03-31T16:19:21.000Z
docs/database_tables.py
wdr-data/wdr-okr
71c9e6e8d3521b1bb67d30310a93584389de2127
[ "MIT" ]
null
null
null
"""Read database information from Django models and create a HTML table for the documentation. """ import collections import os import sys import django from loguru import logger DOCS_DIR = os.path.dirname(os.path.abspath(__file__)) BASE_DIR = os.path.dirname(DOCS_DIR) sys.path.insert(0, BASE_DIR) os.environ["DJANGO_SETTINGS_MODULE"] = "app.settings" django.setup() from django_extensions.management.modelviz import generate_graph_data # noqa: E402 from database_tables_config import ( # noqa: E402 APP_LABELS, HTML_TOP, HTML_BOTTOM, FILENAME, ) def tabulate(head, rows, head_classes=None, row_classes=None): head_classes = head_classes or {} row_classes = row_classes or {} th = [] for i, item in enumerate(head): attrs = [] if i in head_classes: attrs.append(f'class="{head_classes[i]}"') th.append(f"<th{' ' if attrs else ''}{' '.join(attrs)}>{item}</th>") tr = [] for row in rows: td = [] for i, item in enumerate(row): attrs = [] if i in row_classes: attrs.append(f'class="{row_classes[i]}"') td.append(f"<td{' ' if attrs else ''}{' '.join(attrs)}>{item}</td>") tr.append(f"<tr>{' '.join(td)}</tr>") head_html = f"<thead><tr>{' '.join(th)}</tr></thead>" body_html = "<tbody>" + "\n".join(tr) + "</tbody>" return f"<table>{head_html}\n{body_html}</table>" def build_html( # noqa: C901 app_labels: list = APP_LABELS, html_top: str = HTML_TOP, html_bottom: str = HTML_BOTTOM, ) -> str: """Create an HTML page with a series of html tables for each table in the database. Args: app_labels (list): List of Django apps to include in HTML page. Defaults to APP_LABELS. html_top (str): HTML code to insert above generated table. Defaults to HTML_TOP. html_bottom (str): HTML code to insert below generated table. Defaults to HTML_BOTTOM. Returns: str: HTML page. """ # generate a dict with the table names as keys output_table_dict = {} for label in app_labels: # read basic data with django_extensions.management.modelviz data = generate_graph_data([label]) for db_table in data["graphs"][0]["models"]: # generate data for each table (include help_text if present, if not use verbose_name) table_fields = [] for field in db_table["fields"]: if field["help_text"]: description = field["help_text"] else: description = field["verbose_name"] data_type = f'<code>{field["db_type"]}</code>' if field["relation"]: field_type = field["internal_type"] field_type = field_type.replace("ForeignKey", "FK") data_type = f"{data_type} (<b>{field_type}</b>)" # elif field["type"] == "AutoField": # data_type = f'{data_type}<br/><b>{field["type"]}</b>' nullable = "✅" if field["null"] else "❌" unique = "✅" if field["unique"] else "❌" table_fields.append( [ f"<code>{field['column_name']}</code>", data_type, unique, nullable, description, ] ) # only include tables that are stored in db if ( db_table["fields"][0]["name"] == "id" and db_table["fields"][0]["type"] == "AutoField" ): # create table info text from docstring docstring_html = db_table["docstring"].replace("\n\n", "<br />\n") info_text = f"<p>{docstring_html}</p>" # if table uses foreign keys: create a list of foreign keys with links if db_table["relations"]: relation_text = "" for relation in db_table["relations"]: if relation["type"] == "ForeignKey": relation_text += f'<li><a href="#{relation["target"]}"><code>{relation["target_table_name"]}</code></a> via <code>{relation["column_name"]}</code></li>' # elif relation["type"] == "ManyToManyField": # relation_text += f'<li><code>{relation["column_name"]}</code> aus der Tabelle <a href="#{relation["target"]}">{relation["target_table_name"]}</a> (ManyToMany)</li>' if relation_text: if db_table["is_m2m_table"]: info_text += "<p>Sie verbindet die folgenden Tabellen:</p>" else: info_text += "<p>Diese Tabelle hat folgende Relationen zu anderen Tabellen:</p>" info_text += "<ul>" info_text += relation_text info_text += "</ul>" if db_table["unique_together"]: info_text += "Für die Tabelle sind die folgenden <code>UNIQUE</code> Constraints definiert: <ul>" for tup in db_table["unique_together"]: info_text += f"<li>{', '.join(f'<code>{field}</code>' for field in tup)}</li>" info_text += "</ul>" # combine table name, table info text, table fields, and Django model name output_table_dict[db_table["db_table_name"]] = [ info_text, table_fields, db_table["name"], ] # sort dict of database tables alphabetically output_sorted = collections.OrderedDict(sorted(output_table_dict.items())) # collect HTML items in a string html_tables = "" for table_name, table_infos in output_sorted.items(): # convert output table to HTML html_tables += f"<a name='{table_infos[2]}'></a>" # For backwards compatibility html_tables += ( f"<h3><a name='{table_name}' href='#{table_name}'>{table_name}</a></h3>" + f"<div class='docstring'>{table_infos[0]}</div>" + "\n" + tabulate( ["Name", "Type", "UNIQUE", "NULL", "Beschreibung"], table_infos[1], head_classes={2: "mono", 3: "mono"}, row_classes={2: "hcenter vcenter", 3: "hcenter vcenter"}, ) + "\n" ) return str(html_top + html_tables + html_bottom) if __name__ == "__main__": # generate html page (based on constants from database_tables_config) html_page = build_html(APP_LABELS, HTML_TOP, HTML_BOTTOM) # write output to file filepath = os.path.join(DOCS_DIR, FILENAME) with open(filepath, "wt") as output_file: output_file.write(html_page) logger.success("Data written to {}", filepath)
38.092391
194
0.542017
826
7,009
4.417676
0.245763
0.024938
0.015073
0.017539
0.135928
0.067964
0
0
0
0
0
0.004869
0.326009
7,009
183
195
38.300546
0.766723
0.206449
0
0.066116
0
0.016529
0.238502
0.101073
0.008264
0
0
0
0
1
0.016529
false
0
0.057851
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
978c3f0eef7e90463917faf45f6b1c6c86a54b70
5,454
py
Python
LibraryManagementSystem/settings.py
TejasJogi/Library-Management-System-Django-MYSQL
f6dd1910d4270e42ac200b4eb47f2e76cb0c296d
[ "MIT" ]
2
2021-11-26T16:21:05.000Z
2022-02-25T16:02:48.000Z
LibraryManagementSystem/settings.py
TejasJogi/Library-Management-System-Django-MYSQL
f6dd1910d4270e42ac200b4eb47f2e76cb0c296d
[ "MIT" ]
null
null
null
LibraryManagementSystem/settings.py
TejasJogi/Library-Management-System-Django-MYSQL
f6dd1910d4270e42ac200b4eb47f2e76cb0c296d
[ "MIT" ]
null
null
null
""" Django settings for LibraryManagementSystem project. Generated by 'django-admin startproject' using Django 3.2.9. For more information on this file, see https://docs.djangoproject.com/en/3.2/topics/settings/ For the full list of settings and their values, see https://docs.djangoproject.com/en/3.2/ref/settings/ """ import os from pathlib import Path from decouple import config # Build paths inside the project like this: BASE_DIR / 'subdir'. BASE_DIR = Path(__file__).resolve().parent.parent # Quick-start development settings - unsuitable for production # See https://docs.djangoproject.com/en/3.2/howto/deployment/checklist/ # SECURITY WARNING: keep the secret key used in production secret! SECRET_KEY = config('SECRET_KEY') # SECURITY WARNING: don't run with debug turned on in production! DEBUG = config('DEBUG', cast=bool) ALLOWED_HOSTS = [] # Application definition INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', # My App 'library.apps.LibraryConfig', # Form widget tweaks 'widget_tweaks', # Django Social loigin 'django.contrib.sites', 'allauth', 'allauth.account', 'allauth.socialaccount', 'allauth.socialaccount.providers.google', # RESTFull API 'rest_framework', 'rest_framework_simplejwt' ] MIDDLEWARE = [ 'django.middleware.security.SecurityMiddleware', 'django.contrib.sessions.middleware.SessionMiddleware', 'django.middleware.common.CommonMiddleware', 'django.middleware.csrf.CsrfViewMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', 'django.middleware.clickjacking.XFrameOptionsMiddleware', ] # Added for Google auth SITE_ID = 2 ACCOUNT_AUTHENTICATION_METHOD = 'email' ACCOUNT_EMAIL_REQUIRED = True ACCOUNT_UNIQUE_EMAIL = True ACCOUNT_USERNAME_REQUIRED = False ACCOUNT_EMAIL_VERIFICATION = 'mandatory' ROOT_URLCONF = 'LibraryManagementSystem.urls' TEMPLATES = [ { 'BACKEND': 'django.template.backends.django.DjangoTemplates', 'DIRS': [os.path.join(BASE_DIR, 'templates'), os.path.join(BASE_DIR, 'templates', 'accounts')], 'APP_DIRS': True, 'OPTIONS': { 'context_processors': [ 'django.template.context_processors.debug', 'django.template.context_processors.request', 'django.contrib.auth.context_processors.auth', 'django.contrib.messages.context_processors.messages', ], }, }, ] LOGIN_REDIRECT_URL = '/dashboard' WSGI_APPLICATION = 'LibraryManagementSystem.wsgi.application' # Database # https://docs.djangoproject.com/en/3.2/ref/settings/#databases DATABASES = { 'default': { 'ENGINE': 'django.db.backends.mysql', 'NAME': config("DATABASE_NAME"), 'USER': config("DATABASE_USER"), 'PASSWORD': config("DATABASE_PASSWORD"), 'HOST': config("DATABASE_HOST"), 'PORT': config("DATABASE_PORT", cast=int), } } # Password validation # https://docs.djangoproject.com/en/3.2/ref/settings/#auth-password-validators AUTH_PASSWORD_VALIDATORS = [ { 'NAME': 'django.contrib.auth.password_validation.UserAttributeSimilarityValidator', }, { 'NAME': 'django.contrib.auth.password_validation.MinimumLengthValidator', }, { 'NAME': 'django.contrib.auth.password_validation.CommonPasswordValidator', }, { 'NAME': 'django.contrib.auth.password_validation.NumericPasswordValidator', }, ] # Internationalization # https://docs.djangoproject.com/en/3.2/topics/i18n/ LANGUAGE_CODE = 'en-in' TIME_ZONE = 'Asia/Kolkata' USE_I18N = True USE_L10N = True USE_TZ = True # Static files (CSS, JavaScript, Images) # https://docs.djangoproject.com/en/3.2/howto/static-files/ STATIC_URL = '/static/' # Default primary key field type # https://docs.djangoproject.com/en/3.2/ref/settings/#default-auto-field DEFAULT_AUTO_FIELD = 'django.db.models.BigAutoField' # added manually STATICFILES_DIRS = [ BASE_DIR / "static", ] AUTH_USER_MODEL = 'library.User' AUTHENTICATION_BACKENDS = [ 'django.contrib.auth.backends.ModelBackend', 'allauth.account.auth_backends.AuthenticationBackend', ] EMAIL_BACKEND = 'django.core.mail.backends.smtp.EmailBackend' EMAIL_HOST = config('EMAIL_HOST') EMAIL_USE_TLS = config('EMAIL_USE_TLS', cast=bool) EMAIL_PORT = config('EMAIL_PORT', cast=int) EMAIL_HOST_USER = config('EMAIL_HOST_USER') EMAIL_HOST_PASSWORD = config('EMAIL_HOST_PASSWORD') SOCIALACCOUNT_PROVIDERS = { 'google': { 'SCOPE': [ 'profile', 'email', ], 'AUTH_PARAMS': { 'access_type': 'online', } }, } SESSION_COOKIE_AGE = 1000 SESSION_SAVE_EVERY_REQUEST = False ACCOUNT_LOGOUT_ON_PASSWORD_CHANGE = True # django-allauth registraion settings ACCOUNT_EMAIL_CONFIRMATION_EXPIRE_DAYS = 1 ACCOUNT_LOGIN_ATTEMPTS_LIMIT = 5 # 1 day ACCOUNT_LOGIN_ATTEMPTS_TIMEOUT = 86400 # or any other page ACCOUNT_LOGOUT_REDIRECT_URL = '/accounts/login/' REST_FRAMEWORK = { 'DEFAULT_AUTHENTICATION_CLASSES': [ 'rest_framework_simplejwt.authentication.JWTAuthentication', ], 'DEFAULT_RENDERER_CLASSES': [ 'rest_framework.renderers.JSONRenderer' ], }
24.790909
103
0.706637
599
5,454
6.247078
0.383973
0.059059
0.047034
0.053447
0.137627
0.137627
0.082042
0.082042
0.042758
0
0
0.008407
0.17125
5,454
220
104
24.790909
0.819469
0.229923
0
0.03125
1
0
0.468555
0.344695
0
0
0
0
0
1
0
false
0.0625
0.023438
0
0.023438
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
1
0
0
0
null
0
0
0
0
0
0
0
1
0
0
0
0
0
2
978c454e2c28df828f082014fc81cd881d17aa27
2,497
py
Python
device/container/src/baseline_device/service/jobs/sample2.py
MartinMReed/aws-iot-baseline
61bdc51708e6f4480d0117a43f0adde5f6a63506
[ "MIT" ]
1
2021-12-31T05:05:30.000Z
2021-12-31T05:05:30.000Z
device/container/src/baseline_device/service/jobs/sample2.py
nelsestu/thing-expert
2e105d718c386258d8efdb329ea60da1072ffbe8
[ "MIT" ]
null
null
null
device/container/src/baseline_device/service/jobs/sample2.py
nelsestu/thing-expert
2e105d718c386258d8efdb329ea60da1072ffbe8
[ "MIT" ]
1
2021-04-05T23:44:12.000Z
2021-04-05T23:44:12.000Z
import json import logging import os import sys import threading import time import paho.mqtt.client as paho import paho.mqtt.publish as paho_publish from baseline_device.util.config import config from baseline_device.util.mqtt import MqttLoggingHandler logging.basicConfig(level=logging.INFO) logger = logging.getLogger(__file__) client_id = os.environ['BASELINE_CLIENT_ID'] program = 'sample2' connected = threading.Event() def on_connect(client: paho.Client, userdata: dict, flags: dict, rc: int) -> None: # The value of rc determines success or not: # 0: Connection successful # 1: Connection refused - incorrect protocol version # 2: Connection refused - invalid client identifier # 3: Connection refused - server unavailable # 4: Connection refused - bad username or password # 5: Connection refused - not authorised # 6-255: Currently unused. if rc == 0: connected.set() client = None job_id = None try: with open(f'/tmp/{config.app_name}/jobs/{program}', 'r') as f: execution = json.load(f) job_id = execution['jobId'] client = paho.Client(clean_session=True) client.on_connect = on_connect client.enable_logger(logger) logger.addHandler(MqttLoggingHandler(client, f'$aws/rules/{config.topic_prefix}/things/{client_id}/log')) client.connect_async('localhost') client.loop_start() while not connected.is_set(): time.sleep(1) logger.info('Job started!') time.sleep(30) logger.info('Job complete!') client.publish(f'$aws/things/{client_id}/jobs/{job_id}/update', qos=2, payload=json.dumps({ 'status': 'SUCCEEDED', 'expectedVersion': execution['versionNumber'], 'executionNumber': execution['executionNumber'] })) sys.exit(0) except SystemExit as e: raise e except: logger.critical('Fatal shutdown...', exc_info=True) if job_id: try: client_publish = client.publish if client.is_connected() else paho_publish.single client_publish(f'$aws/things/{client_id}/jobs/{job_id}/update', qos=2, payload=json.dumps({ 'status': 'FAILED', 'expectedVersion': execution['versionNumber'], 'executionNumber': execution['executionNumber'] })) except: logger.warning('Unable to send job status as FAILED', exc_info=True) sys.exit(1) finally: if client: client.loop_stop() client.disconnect()
26.284211
109
0.673208
308
2,497
5.344156
0.435065
0.024301
0.025516
0.026731
0.17983
0.17983
0.087485
0.087485
0.087485
0.087485
0
0.009635
0.210252
2,497
94
110
26.56383
0.825051
0.132559
0
0.169492
0
0
0.203987
0.083449
0
0
0
0
0
1
0.016949
false
0
0.169492
0
0.186441
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
978cde5321a929429de3c79977503bd4e3e5a2f0
12,183
py
Python
odoo-13.0/addons/sale/tests/test_onchange.py
VaibhavBhujade/Blockchain-ERP-interoperability
b5190a037fb6615386f7cbad024d51b0abd4ba03
[ "MIT" ]
12
2021-03-26T08:39:40.000Z
2022-03-16T02:20:10.000Z
odoo-13.0/addons/sale/tests/test_onchange.py
VaibhavBhujade/Blockchain-ERP-interoperability
b5190a037fb6615386f7cbad024d51b0abd4ba03
[ "MIT" ]
13
2020-12-20T16:00:21.000Z
2022-03-14T14:55:30.000Z
odoo-13.0/addons/sale/tests/test_onchange.py
VaibhavBhujade/Blockchain-ERP-interoperability
b5190a037fb6615386f7cbad024d51b0abd4ba03
[ "MIT" ]
17
2020-08-31T11:18:49.000Z
2022-02-09T05:57:31.000Z
# -*- coding: utf-8 -*- # Part of Odoo. See LICENSE file for full copyright and licensing details. from odoo.tests import Form from odoo.tests.common import TransactionCase class TestOnchangeProductId(TransactionCase): """Test that when an included tax is mapped by a fiscal position, the included tax must be subtracted to the price of the product. """ def setUp(self): super(TestOnchangeProductId, self).setUp() self.fiscal_position_model = self.env['account.fiscal.position'] self.fiscal_position_tax_model = self.env['account.fiscal.position.tax'] self.tax_model = self.env['account.tax'] self.so_model = self.env['sale.order'] self.po_line_model = self.env['sale.order.line'] self.res_partner_model = self.env['res.partner'] self.product_tmpl_model = self.env['product.template'] self.product_model = self.env['product.product'] self.product_uom_model = self.env['uom.uom'] self.supplierinfo_model = self.env["product.supplierinfo"] self.pricelist_model = self.env['product.pricelist'] def test_onchange_product_id(self): uom_id = self.product_uom_model.search([('name', '=', 'Units')])[0] pricelist = self.pricelist_model.search([('name', '=', 'Public Pricelist')])[0] partner_id = self.res_partner_model.create(dict(name="George")) tax_include_id = self.tax_model.create(dict(name="Include tax", amount='21.00', price_include=True, type_tax_use='sale')) tax_exclude_id = self.tax_model.create(dict(name="Exclude tax", amount='0.00', type_tax_use='sale')) product_tmpl_id = self.product_tmpl_model.create(dict(name="Voiture", list_price=121, taxes_id=[(6, 0, [tax_include_id.id])])) product_id = product_tmpl_id.product_variant_id fp_id = self.fiscal_position_model.create(dict(name="fiscal position", sequence=1)) fp_tax_id = self.fiscal_position_tax_model.create(dict(position_id=fp_id.id, tax_src_id=tax_include_id.id, tax_dest_id=tax_exclude_id.id)) # Create the SO with one SO line and apply a pricelist and fiscal position on it order_form = Form(self.env['sale.order'].with_context(tracking_disable=True)) order_form.partner_id = partner_id order_form.pricelist_id = pricelist order_form.fiscal_position_id = fp_id with order_form.order_line.new() as line: line.name = product_id.name line.product_id = product_id line.product_uom_qty = 1.0 line.product_uom = uom_id sale_order = order_form.save() # Check the unit price of SO line self.assertEquals(100, sale_order.order_line[0].price_unit, "The included tax must be subtracted to the price") def test_pricelist_application(self): """ Test different prices are correctly applied based on dates """ support_product = self.env.ref('product.product_product_2') support_product.list_price = 100 partner = self.res_partner_model.create(dict(name="George")) christmas_pricelist = self.env['product.pricelist'].create({ 'name': 'Christmas pricelist', 'item_ids': [(0, 0, { 'date_start': "2017-12-01", 'date_end': "2017-12-24", 'compute_price': 'percentage', 'base': 'list_price', 'percent_price': 20, 'applied_on': '3_global', 'name': 'Pre-Christmas discount' }), (0, 0, { 'date_start': "2017-12-25", 'date_end': "2017-12-31", 'compute_price': 'percentage', 'base': 'list_price', 'percent_price': 50, 'applied_on': '3_global', 'name': 'Post-Christmas super-discount' })] }) # Create the SO with pricelist based on date order_form = Form(self.env['sale.order'].with_context(tracking_disable=True)) order_form.partner_id = partner order_form.date_order = '2017-12-20' order_form.pricelist_id = christmas_pricelist with order_form.order_line.new() as line: line.product_id = support_product so = order_form.save() # Check the unit price and subtotal of SO line self.assertEqual(so.order_line[0].price_unit, 80, "First date pricelist rule not applied") self.assertEquals(so.order_line[0].price_subtotal, so.order_line[0].price_unit * so.order_line[0].product_uom_qty, 'Total of SO line should be a multiplication of unit price and ordered quantity') # Change order date of the SO and check the unit price and subtotal of SO line with Form(so) as order: order.date_order = '2017-12-30' with order.order_line.edit(0) as line: line.product_id = support_product self.assertEqual(so.order_line[0].price_unit, 50, "Second date pricelist rule not applied") self.assertEquals(so.order_line[0].price_subtotal, so.order_line[0].price_unit * so.order_line[0].product_uom_qty, 'Total of SO line should be a multiplication of unit price and ordered quantity') def test_pricelist_uom_discount(self): """ Test prices and discounts are correctly applied based on date and uom""" computer_case = self.env.ref('product.product_product_16') computer_case.list_price = 100 partner = self.res_partner_model.create(dict(name="George")) categ_unit_id = self.ref('uom.product_uom_categ_unit') goup_discount_id = self.ref('product.group_discount_per_so_line') self.env.user.write({'groups_id': [(4, goup_discount_id, 0)]}) new_uom = self.env['uom.uom'].create({ 'name': '10 units', 'factor_inv': 10, 'uom_type': 'bigger', 'rounding': 1.0, 'category_id': categ_unit_id }) christmas_pricelist = self.env['product.pricelist'].create({ 'name': 'Christmas pricelist', 'discount_policy': 'without_discount', 'item_ids': [(0, 0, { 'date_start': "2017-12-01", 'date_end': "2017-12-30", 'compute_price': 'percentage', 'base': 'list_price', 'percent_price': 10, 'applied_on': '3_global', 'name': 'Christmas discount' })] }) so = self.env['sale.order'].create({ 'partner_id': partner.id, 'date_order': '2017-12-20', 'pricelist_id': christmas_pricelist.id, }) order_line = self.env['sale.order.line'].new({ 'order_id': so.id, 'product_id': computer_case.id, }) # force compute uom and prices order_line.product_id_change() order_line.product_uom_change() order_line._onchange_discount() self.assertEqual(order_line.price_subtotal, 90, "Christmas discount pricelist rule not applied") self.assertEqual(order_line.discount, 10, "Christmas discount not equalt to 10%") order_line.product_uom = new_uom order_line.product_uom_change() order_line._onchange_discount() self.assertEqual(order_line.price_subtotal, 900, "Christmas discount pricelist rule not applied") self.assertEqual(order_line.discount, 10, "Christmas discount not equalt to 10%") def test_pricelist_based_on_other(self): """ Test price and discount are correctly applied with a pricelist based on an other one""" computer_case = self.env.ref('product.product_product_16') computer_case.list_price = 100 partner = self.res_partner_model.create(dict(name="George")) goup_discount_id = self.ref('product.group_discount_per_so_line') self.env.user.write({'groups_id': [(4, goup_discount_id, 0)]}) first_pricelist = self.env['product.pricelist'].create({ 'name': 'First pricelist', 'discount_policy': 'without_discount', 'item_ids': [(0, 0, { 'compute_price': 'percentage', 'base': 'list_price', 'percent_price': 10, 'applied_on': '3_global', 'name': 'First discount' })] }) second_pricelist = self.env['product.pricelist'].create({ 'name': 'Second pricelist', 'discount_policy': 'without_discount', 'item_ids': [(0, 0, { 'compute_price': 'formula', 'base': 'pricelist', 'base_pricelist_id': first_pricelist.id, 'price_discount': 10, 'applied_on': '3_global', 'name': 'Second discount' })] }) so = self.env['sale.order'].create({ 'partner_id': partner.id, 'date_order': '2018-07-11', 'pricelist_id': second_pricelist.id, }) order_line = self.env['sale.order.line'].new({ 'order_id': so.id, 'product_id': computer_case.id, }) # force compute uom and prices order_line.product_id_change() order_line._onchange_discount() self.assertEqual(order_line.price_subtotal, 81, "Second pricelist rule not applied") self.assertEqual(order_line.discount, 19, "Second discount not applied") def test_pricelist_with_other_currency(self): """ Test prices are correctly applied with a pricelist with an other currency""" computer_case = self.env.ref('product.product_product_16') computer_case.list_price = 100 partner = self.res_partner_model.create(dict(name="George")) categ_unit_id = self.ref('uom.product_uom_categ_unit') other_currency = self.env['res.currency'].create({'name': 'other currency', 'symbol': 'other'}) self.env['res.currency.rate'].create({'name': '2018-07-11', 'rate': 2.0, 'currency_id': other_currency.id, 'company_id': self.env.company.id}) self.env['res.currency.rate'].search( [('currency_id', '=', self.env.company.currency_id.id)] ).unlink() new_uom = self.env['uom.uom'].create({ 'name': '10 units', 'factor_inv': 10, 'uom_type': 'bigger', 'rounding': 1.0, 'category_id': categ_unit_id }) # This pricelist doesn't show the discount first_pricelist = self.env['product.pricelist'].create({ 'name': 'First pricelist', 'currency_id': other_currency.id, 'discount_policy': 'with_discount', 'item_ids': [(0, 0, { 'compute_price': 'percentage', 'base': 'list_price', 'percent_price': 10, 'applied_on': '3_global', 'name': 'First discount' })] }) so = self.env['sale.order'].create({ 'partner_id': partner.id, 'date_order': '2018-07-12', 'pricelist_id': first_pricelist.id, }) order_line = self.env['sale.order.line'].new({ 'order_id': so.id, 'product_id': computer_case.id, }) # force compute uom and prices order_line.product_id_change() self.assertEqual(order_line.price_unit, 180, "First pricelist rule not applied") order_line.product_uom = new_uom order_line.product_uom_change() self.assertEqual(order_line.price_unit, 1800, "First pricelist rule not applied")
44.790441
204
0.583682
1,442
12,183
4.690014
0.136616
0.050569
0.019518
0.023658
0.672926
0.607275
0.577406
0.538518
0.508206
0.46296
0
0.025983
0.298695
12,183
271
205
44.95572
0.765566
0.075187
0
0.568182
0
0
0.238723
0.024336
0
0
0
0
0.059091
1
0.027273
false
0
0.009091
0
0.040909
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
978e392b87cb419fb505337ab4cee06b350097b0
8,390
py
Python
IEX_29id/utils/folders.py
kellyjelly0904/macros_29id
573946d13eee7f85da049ac666b5dd2d18d19bb1
[ "MIT" ]
null
null
null
IEX_29id/utils/folders.py
kellyjelly0904/macros_29id
573946d13eee7f85da049ac666b5dd2d18d19bb1
[ "MIT" ]
1
2021-11-10T02:00:41.000Z
2021-11-11T03:02:23.000Z
IEX_29id/utils/folders.py
kellyjelly0904/macros_29id
573946d13eee7f85da049ac666b5dd2d18d19bb1
[ "MIT" ]
2
2021-09-28T21:19:47.000Z
2021-10-12T20:51:43.000Z
from epics import caput from IEX_29id.utils.exp import Check_run, BL_Mode_Set, BL_ioc from IEX_29id.mda.file import MDA_CurrentDirectory from IEX_29id.mda.file import MDA_CurrentRun import os import re def Make_DataFolder(run,folder,UserName,scanIOC,ftp): #JM was here ->print full crontab command and change permissions on kip -still needs work! """ Creates the User Folder on the dserv if ftp = True: creates the folders on kip (ftp server) and modifies the cronjob """ crontime={ 'mda2ascii':'0,30 * * * * ', 'chmod':'1,31 * * * * ', 'data_other':'2,32 * * * * ', 'notebook':'*/3 * * * * ', } if (folder == 'c'or folder == 'd'): if ftp: print('-------------------------------------------------------------') #mda2ascii MyPath_kip_run='/net/kip/sftp/pub/29id'+folder+'ftp/files/'+run+'/' MyPath_kip='/net/kip/sftp/pub/29id'+folder+'ftp/files/'+run+'/'+UserName+'/' cmd_mda2ascii=crontime['mda2ascii']+' /net/s29dserv/APSshare/bin/mda2ascii -d '+MyPath_kip+'ascii '+MyPath_kip+'mda/*.mda' print(cmd_mda2ascii) #chmode cmd_chmod=crontime['chmod']+' chmod 664 '+MyPath_kip+'ascii/*.asc' print(cmd_chmod) #notebooks cmd_notebook=crontime['notebook']+' /usr/bin/rsync -av --exclude=core /home/beams22/29IDUSER/Documents/User_Folders/'+UserName+'/* kip:'+MyPath_kip+'notebook > /home/beams22/29ID/cronfiles/cptoftp-currrun-d-User.log 2>&1' print(cmd_notebook) print('-------------------------------------------------------------\n\n') #making folders print("\n\n") print(MyPath_kip) print(MyPath_kip+"ascii") if not (os.path.exists(MyPath_kip_run)): os.mkdir(MyPath_kip_run) os.chmod(MyPath_kip_run, 0o775) if not (os.path.exists(MyPath_kip)): os.mkdir(MyPath_kip) os.chmod(MyPath_kip, 0o775) if not (os.path.exists(MyPath_kip+"ascii")): os.mkdir(MyPath_kip+'ascii') os.chmod(MyPath_kip+'ascii', 0o775) if not (os.path.exists(MyPath_kip+"notebook")): os.mkdir(MyPath_kip+"notebook") os.chmod(MyPath_kip+"notebook", 0o775) else: print("To create ftp folders & update contrab, you need to run the following as 29id:") print("\tFolder_"+str(scanIOC)+"('"+str(run)+"','"+str(UserName)+"',ftp=True)") MyPath_File='/home/beams/29IDUSER/Documents/User_Folders/'+UserName UserName = "/"+UserName if not (os.path.exists(MyPath_File)): os.mkdir(MyPath_File) #if folder == 'd': #MyPath_File_hkl='/home/beams/29IDUSER/Documents/User_Folders/'+UserName+'/hkl' #if not(os.path.exists(MyPath_File_hkl)): # os.mkdir(MyPath_File_hkl) if folder == 'b': UserName = '' #MyPath_run='/net/s29data/export/data_29id'+folder+'/'+run MyPath_run=os.path.dirname(_userDataFolder(UserName,scanIOC)) if not (os.path.exists(MyPath_run)): os.mkdir(MyPath_run) #MyPath_Data=MyPath_run+UserName MyPath_Data=_userDataFolder(UserName,scanIOC) if not (os.path.exists(MyPath_Data)): os.mkdir(MyPath_Data) def _userDataFolder(userName,scanIOC,**kwargs): """ Returns the path to a user folder dataFolder='/net/s29data/export/data_29id'+folder+'/'+run+'/'+userName kwargs: run: Check_run(); unless specified BLmode: Staff / User; based on userName unless specified folder: determined by UserName and scanIOC folder = b (Staff) folder = c (User and ARPES) folder = d (User and Kappa) """ kwargs.setdefault('run',Check_run()) folder="" run=kwargs['run'] if userName == 'Staff': folder="b" if "BLmode" in kwargs: BL_Mode_Set(kwargs["BLmode"]) else: BL_Mode_Set("Staff") else: BL_Mode_Set("User") if scanIOC=="ARPES": folder="c" if scanIOC=="Kappa": folder="d" dataFolder='/net/s29data/export/data_29id'+folder+'/'+run+'/'+userName return dataFolder def _filename_key(filename): return (len(filename), filename) def Folder_mda(run,folder,UserName,scanIOC): """ For Staff: folder='b', UserName='Staff' For ARPES: folder ='c' For Kappa or RSoXS: folder = 'd' """ FilePrefix=scanIOC if UserName == 'Staff': UserName="" else: UserName=UserName+"/" MyPath="/net/s29data/export/data_29id"+folder+"/"+run+"/"+UserName+"mda" print("\nMDA folder: " + MyPath) if not (os.path.exists(MyPath)): os.mkdir(MyPath) FileNumber=1 else: FileNumber=getNextFileNumber(MyPath,FilePrefix) if scanIOC=="Test" or scanIOC=="Kappa" or scanIOC=="ARPES" or scanIOC=="RSoXS": caput("29id"+scanIOC+":saveData_fileSystem","/net/s29data/export/data_29id"+folder+"/"+run) os.sleep(0.25) #needed so that it has time to write caput("29id"+scanIOC+":saveData_subDir","/"+UserName+"mda") else: caput("29id"+scanIOC+":saveData_fileSystem","//s29data/export/data_29id"+folder+"/"+run) os.sleep(0.25) caput("29id"+scanIOC+":saveData_subDir",UserName+"mda") caput("29id"+scanIOC+":saveData_baseName",FilePrefix+"_") caput("29id"+scanIOC+":saveData_scanNumber",FileNumber) def getNextFileNumber(data_dir, file_prefix,**kwargs): """ gets the next file number for the pattern data_dir/file_prefix_filenum kwargs: debug = False (default); if True then print lo q = True (default); if False then prints next file number """ kwargs.setdefault("debug",False) kwargs.setdefault("q",True) onlyfiles = [f for f in os.listdir(data_dir) if os.isfile(os.join(data_dir, f)) and f[:len(file_prefix)] == file_prefix] sortedfiles = sorted(onlyfiles, key=_filename_key) pattern = re.compile('(.*)_(.*)\.(.*)') try: lastFile = sortedfiles[-1] except IndexError as errObj: nextFileNumber = 1 if kwargs["debug"]: print("Data directory = ", data_dir) print("File prefix =", file_prefix) print("File number =", None) print("File extension =", "TBD") print("Next File number =", nextFileNumber) else: matchObj = pattern.match(lastFile) nextFileNumber = int(matchObj.group(2)) + 1 if kwargs["debug"]: print("Data directory = ", data_dir) print("File prefix =", matchObj.group(1)) print("File number =", matchObj.group(2)) print("File extension =", matchObj.group(3)) print("Next File number =", nextFileNumber) if kwargs["q"] == False: print("Next File Number: ",nextFileNumber) return nextFileNumber def Check_Staff_Directory(**kwargs): """ Switchs to the staff directory Uses Fold """ kwargs.setdefault("scanIOC",BL_ioc()) kwargs.setdefault("run",Check_run()) scanIOC=kwargs["scanIOC"] run= kwargs["run"] directory = MDA_CurrentDirectory(scanIOC) current_run = MDA_CurrentRun(scanIOC) if directory.find('data_29idb') < 1 or current_run != run: print('You are not currently saving in the Staff directory and/or the desired run - REPLY "yes" to switch folder.\nThis will only work if the run directory already exists.\nOtherwise, you must open ipython as 29id to create a new run directory using:\n\tFolder_'+scanIOC+'(run,\'Staff\')') foo=input('\nAre you ready to switch to the '+run+' Staff directory? >') if foo == 'Y' or foo == 'y' or foo == 'yes'or foo == 'YES': print('Switching directory...') if scanIOC=='ARPES': Folder_ARPES('Staff',mdaOnly=True,**kwargs) elif scanIOC=='Kappa': Folder_Kappa('Staff',create_only=False) else: print('\nFolder not set.') else: print('Staff directory OK.') directory = MDA_CurrentDirectory(scanIOC) print('\nCurrent directory: '+directory)
40.143541
297
0.590703
998
8,390
4.846693
0.229459
0.037213
0.013025
0.020467
0.251809
0.198677
0.193922
0.123217
0.095514
0.038867
0
0.018856
0.254112
8,390
208
298
40.336538
0.754075
0.148272
0
0.128378
0
0.02027
0.249498
0.066495
0
0
0
0
0
1
0.040541
false
0
0.040541
0.006757
0.101351
0.182432
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
978f1fcb3bef9348f27a0824ad9894eb219d2595
2,932
py
Python
sceance/set_watchlist.py
sjmignot/film-to-cal
82d5e96b65197ff96522324d6527fca6f18cc76b
[ "MIT" ]
6
2020-02-05T21:31:57.000Z
2020-03-08T00:35:16.000Z
sceance/set_watchlist.py
sjmignot/film-to-cal
82d5e96b65197ff96522324d6527fca6f18cc76b
[ "MIT" ]
null
null
null
sceance/set_watchlist.py
sjmignot/film-to-cal
82d5e96b65197ff96522324d6527fca6f18cc76b
[ "MIT" ]
null
null
null
# -*- coding: utf-8 -*- ''' Starts a Firfox headless brower to see if movies on your watchlist are playing at any of your favorite theaters. Favorite theaters are taken from a txt file (extracted from "theaters.txt"). These showtimes are compared to a watchlist (extracted from "watchlist.txt") -samuel mignot- ''' # ------------------- # # imports # # ------------------- # import configparser import os from os import listdir from os.path import isfile, join # internal import file_helpers # ------------------- # # constants # # ------------------- # THIS_DIRECTORY = os.path.abspath(os.path.dirname(__file__)) DATA_DIR = '/data' WATCHLIST_DIR = '/watchlists' OSCARS_WATCHLIST = 'oscar-winners-watchlist.txt' ERROR_MESSAGE = { "watchlist_select": "response must be an integer in the range 1-{max_show}", "yes_no": "response must be one of the following: 'yes', 'y', 'no', 'n'" } def robert_easter_eggers(original_choice): res = get_input( f"Are you sure you want to set your default watchlist to...the oscars..? [y/n]: ", {'y', 'yes', 'no', 'n'}, ERROR_MESSAGE['yes_no'] ) if res in {'y', 'yes'}: res = get_input( f"The awards that gave Best Picture to Forrest Gump over Pulp fiction..? [y/n]: ", {'y', 'yes', 'no', 'n'}, ERROR_MESSAGE['yes_no'] ) if res in {'y', 'yes'}: print('... Aight...') return original_choice if res in {'n', 'no'}: return set_watchlist(no_oscars=True) def get_watchlists(): mypath = THIS_DIRECTORY+DATA_DIR+WATCHLIST_DIR return [f for f in listdir(mypath) if isfile(join(mypath, f))] def get_input(question, response_format, error_message): ''' loops until a response that is in response_format is met''' while True: res = input(question) if res in response_format: return res print(error_message) def set_watchlist(no_oscars=False): '''for each movie left filtering, asks the user if they want to watch it and provides showtimes to pick from''' watchlist_files = get_watchlists() if(no_oscars): watchlist_files = list(filter(lambda x: x!=OSCARS_WATCHLIST, watchlist_files)) for i, watchlist in enumerate(watchlist_files, start=1): print(f"[{i}]: {watchlist}") res = get_input( f"select your watchlist [1-{len(watchlist_files)} or n to cancel]: ", set(map(str, range(1, len(watchlist_files)+1)))|{'n', 'no'}, ERROR_MESSAGE['watchlist_select'].format(max_show=str(len(watchlist_files))) ) print() if res in {'n', 'no'}: return None chosen_watchlist = watchlist_files[int(res)-1] if(not no_oscars): if chosen_watchlist == OSCARS_WATCHLIST: chosen_watchlist = robert_easter_eggers(chosen_watchlist) return chosen_watchlist if __name__ == "__main__": set_watchlist()
32.21978
115
0.62824
391
2,932
4.531969
0.365729
0.063205
0.019752
0.020316
0.059819
0.059819
0.041761
0.041761
0.041761
0.041761
0
0.00308
0.224761
2,932
90
116
32.577778
0.776507
0.206003
0
0.186441
0
0
0.216558
0.022658
0
0
0
0
0
1
0.067797
false
0
0.084746
0
0.254237
0.067797
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
978fc91e48a69b62fda28f8d703d52a062332e01
177
py
Python
app/routes/views.py
izconcept/Turnt
28d25ebfbd43aa6472aa1f0eec7e73ec1b8d15d3
[ "Apache-2.0" ]
4
2018-01-29T05:51:32.000Z
2018-02-08T05:18:47.000Z
app/routes/views.py
izconcept/Turnt
28d25ebfbd43aa6472aa1f0eec7e73ec1b8d15d3
[ "Apache-2.0" ]
3
2018-01-30T21:41:09.000Z
2018-01-31T18:20:01.000Z
app/routes/views.py
izconcept/Turnt
28d25ebfbd43aa6472aa1f0eec7e73ec1b8d15d3
[ "Apache-2.0" ]
1
2019-03-29T19:32:28.000Z
2019-03-29T19:32:28.000Z
from app import app, drinks from flask import render_template, session, redirect, request @app.route('/') def index(): return render_template('index.html', drinks=drinks)
22.125
61
0.745763
24
177
5.416667
0.625
0.215385
0
0
0
0
0
0
0
0
0
0
0.135593
177
7
62
25.285714
0.849673
0
0
0
0
0
0.062147
0
0
0
0
0
0
1
0.2
true
0
0.4
0.2
0.8
0
1
0
0
null
1
0
0
0
0
0
0
0
0
0
0
0
0
1
0
0
0
0
0
0
0
0
0
0
null
0
0
0
0
0
0
1
0
1
1
0
0
0
6
978fd61709e98a6a4163084a70975c96d6b7f512
21,143
py
Python
ARHMM-code/olfactory_search_xval.py
Smear-Lab/Olfactory_Search
92ea57cdd49b9c1d88ffe5d7b18a0be2cd73f0ff
[ "MIT" ]
null
null
null
ARHMM-code/olfactory_search_xval.py
Smear-Lab/Olfactory_Search
92ea57cdd49b9c1d88ffe5d7b18a0be2cd73f0ff
[ "MIT" ]
null
null
null
ARHMM-code/olfactory_search_xval.py
Smear-Lab/Olfactory_Search
92ea57cdd49b9c1d88ffe5d7b18a0be2cd73f0ff
[ "MIT" ]
null
null
null
#Misc import os, time, argparse import h5py, json import glob, fnmatch,pdb from tqdm import tqdm import multiprocessing #Base import numpy as np import pandas as pd import scipy.stats as st from sklearn.model_selection import StratifiedKFold #Plotting import matplotlib matplotlib.use('Agg') import seaborn as sns from matplotlib import pyplot as plt from matplotlib.backends.backend_pdf import PdfPages import matplotlib.gridspec as gridspec #State-Space Modeling #S.Linderman import ssm #M.Johnson from pyhsmm.util.text import progprint_xrange from pybasicbayes.distributions import Gaussian, AutoRegression import autoregressive.models as pyhmm #User Modules import utilities as util import plotting_YAA as plots_YAA ##===== Run Command =====## # OMP_NUM_THREADS=1 python olfactory_search_xval.py --model_type "ARHMM_MJ" --Kmin 12 --Kmax 20 ##===== ============================ =====## ##===== Parse Command Line Arguments =====## parser = argparse.ArgumentParser(description='ARHMM Mouse') parser.add_argument('--save',type=bool, default=1, help='Save Results?') parser.add_argument('--json_dir', type=str, help='Directory Path of model parameter json file; not required if using other arguments') ##===== Data Options =====## parser.add_argument('--mID',type=str, default='all_mice', help='mouse to fit model to') parser.add_argument('--condition', type=str, default='all_conds', help='trial condition type') parser.add_argument('--data_type', type=str, default='BHNx', help='BHNx vs BHNxv vs EgoAllo_xv') parser.add_argument('--HMM_inputs', type=str, default='BHNx', help='BHNx vs BHNxv') parser.add_argument('--x_units', type=str, default='pixels', help='pixels or arena_length') ##===== Model Type =====## parser.add_argument('--model_type', type=str, default='ARHMM_MJ', help='ARHMM_SL or ARHMM_MJ') parser.add_argument('--robust', type=bool, default=0, help='autoregressive(0) or robust_autoregressive(1)') parser.add_argument('--sticky', type=bool, default=0, help='standard(0) or sticky(1) ARHMM') parser.add_argument('--inputdriven', type=bool, default=0, help='HMM transitions dependent on some input in addition to previous HMM state') ##===== Model Parameters =====## parser.add_argument('--kappa', type=float, default=1e5, help='sticky arhmm kappa') parser.add_argument('--AR_lags', type=str, default=1, help='Autoregressive lags') parser.add_argument('--l2_penalty_A', type=float, default=0, help='AR l2_penalty_A') parser.add_argument('--l2_penalty_b', type=float, default=0, help='AR l2_penalty_b') parser.add_argument('--l2_penalty_V', type=float, default=0, help='AR l2_penalty_V') parser.add_argument('--MAP_threshold', type=float, default=0.80, help='MAP threshold') parser.add_argument('--nGibbs', type=int, default=200, help='number of iterations to run the Gibbs sampler') parser.add_argument('--burn_fraction', type=float, default=0.66, help='Calculate MAP sequence with the last 37.5% of samples; of nGibbs = 400, 250 samples are burned') ##===== Run Options =====## parser.add_argument('--Kmin', type=int, default=80, help='minimum number of HMM states') parser.add_argument('--Kmax', type=int, default=100, help='maximum number of HMM states') parser.add_argument('--kXval', type=int, default=5, help='number of kfold') parser.add_argument('--EM_tolerance', type=float, default=1e-5, help='SSM EM algorithm tolerance') parser.add_argument('--EM_iters', type=int, default=200, help='EM Iterations') parser.add_argument('--max_processes', type=int, default=18, help='max # of parallel processes to run') args = parser.parse_args() def set_arhmm_hyperparams(opt,K): D_obs = opt['D_obs'] Mobs = 0 #Autoregressive keyword arguments ar_kwargs = dict( # l2_penalty_A= args_dic['l2_penalty_A'], # l2_penalty_b= args_dic['l2_penalty_b'], # l2_penalty_V= args_dic['l2_penalty_V'], lags = opt['AR_lags'] ) #HMM Transition parameters trans_kwargs = dict( # alpha= args_dic['alpha'], ) #Gaussian or t-distribution if not opt['robust']: observation_type = "autoregressive" else: observation_type = "robust_autoregressive" #What model are we going to run? if not opt['inputdriven']: M = 0 if not opt['sticky']: if opt['model_type'] == 'ARHMM_MJ': print('Bayesian ARHMM') else: print('Vanilla ARHMM') transition_type = "standard" else: print('sticky ARHMM') transition_type = "sticky" trans_kwargs['kappa'] = opt['kappa'] else: M = D_obs # trans_kwargs['l2_penalty'] = args_dic['l2_penalty_W'] #coeff of l2-regul penalty on W (weights of logistic regression) transition_type = "inputdriven" if not opt['sticky']: print('input-driven ARHMM') else: print('input-driven sticky ARHMM') trans_kwargs['kappa'] = opt['kappa'] #If we're using matt Johnsons code, most of the above parameters don't matter #Initialize Observation distribution and set it to ar_kwargs if opt['model_type'] == 'ARHMM_MJ': affine = True dynamics_hypparams = \ dict(nu_0=D_obs + 2, S_0=np.eye(D_obs), M_0=np.hstack((np.eye(D_obs), np.zeros((D_obs,int(affine))))), K_0=np.eye(D_obs + affine), affine=affine) # Initialize a list of autorgressive objects given the size of the # observations and number of max discrete states ar_kwargs = [AutoRegression(A=np.column_stack((0.99 * np.eye(D_obs),\ np.zeros((D_obs, int(affine))))),sigma=np.eye(D_obs),\ **dynamics_hypparams) for _ in range(K)] return D_obs, M, Mobs, observation_type, ar_kwargs, transition_type, trans_kwargs def make_hyperparams_dic(opt, K, M, trans_kwargs, ar_kwargs): hyperparams = opt.copy() del hyperparams['Kmin'], hyperparams['Kmax'] hyperparams['K'] = K hyperparams['M'] = M # hyperparams['Mobs'] = Mobs hyperparams['trans_kwargs'] = trans_kwargs if opt['model_type'] == 'ARHMM_SL': hyperparams['ar_kwargs'] = ar_kwargs return hyperparams def arhmm_bayesian_fit(arhmm, data_train, data_test, opt, i_fold): # Add test data to ARHMM for data in data_train: # Add data per trial arhmm.add_data(data) #Create data structures to contain gibb samples nGibbs = opt['nGibbs'] nTrials = len(data_train) K = arhmm.num_states; D_obs = arhmm.D; stateseq_smpls = [[] for i in range(nTrials)] AB_smpls = np.zeros((nGibbs,K,D_obs,D_obs+1)) sqrt_sigmas_smpls = np.zeros((nGibbs,K,D_obs,D_obs)) trans_matrix_smpls = np.zeros((nGibbs,K,K)) GibbsLLs = np.zeros((nGibbs)) # Loop over samples for iSample in tqdm(range(nGibbs)): # Sample Model arhmm.resample_model() #keep track of model log_likelihood's as a check for "convergence" GibbsLLs[iSample] = arhmm.log_likelihood() # Append each Gibbs sample for each trial for iTrial in range(len(arhmm.states_list)): stateseq_smpls[iTrial].append(arhmm.states_list[iTrial].stateseq.copy()) # Append the ARHMM matrix A and transition matrix for this sample for state in range(K): AB_smpls[iSample,state] = arhmm.obs_distns[state].A.copy() sqrt_sigmas_smpls[iSample,state] = np.linalg.cholesky(arhmm.obs_distns[state].sigma) trans_matrix_smpls[iSample] = arhmm.trans_distn.trans_matrix.copy() # Calculate the mean A, B, and transition matrix for all burn = opt['burn_fraction'] ABs_mean = np.mean(AB_smpls[int(burn*nGibbs):],axis=0) As = ABs_mean[:,:,:D_obs]; Bs = ABs_mean[:,:,D_obs] sqrt_Sigmas = np.mean(sqrt_sigmas_smpls[int(burn*nGibbs):],axis=0) obs = {'ABs': ABs_mean, 'As': As,'Bs': Bs, 'sqrt_Sigmas': sqrt_Sigmas} log_mean_transition_matrix = np.log(np.mean(trans_matrix_smpls[int(burn*nGibbs):,:,:],axis=0)) trans = {'log_Ps': log_mean_transition_matrix} init = {'P0': arhmm.init_state_distn.pi_0} param_dict = {} param_dict['transitions'] = trans param_dict['observations'] = obs param_dict['init_state_distn'] = init #llhood of heldout ll_heldout = arhmm.log_likelihood(data=data_test) state_usage = arhmm.state_usages #Lists to contain import stuffff trMAPs = [] trPosteriors = [] trMasks = [] #Plot convergence here SaveDir, fname_sffx = util.make_sub_dir(K, opt, i_fold) plots_YAA.plot_model_convergence(stateseq_smpls, AB_smpls, trans_matrix_smpls, GibbsLLs, sorted(arhmm.used_states), SaveDir, fname='-'.join(('Model_convergence',fname_sffx))+'.pdf') #All of the data has been used to fit the model #All of the data is contained with the ARHMM object already if i_fold == -1: #Calculate the MAP estimate for iTrial in range(nTrials): # Take the gibbs samples after the burn fraction to construct MAP z_smpls = np.array(stateseq_smpls[iTrial][int(burn*nGibbs):]) state_probs_trial = [] for state in range(K): state_occurances = np.isin(z_smpls,state) state_probs_trial.append(np.sum(state_occurances,axis=0)/z_smpls.shape[0]) #Save the maximum posterior probability for each time step pprob = np.vstack((np.zeros((1,K)),np.array(state_probs_trial).T)) trPosteriors.append(pprob) mask = np.max(pprob,axis=1) < opt['MAP_threshold'] trMasks.append(mask) #Use the maximum posterior probability to determine a robust MAP State sequence MAP = np.hstack(([-1],np.ndarray.flatten(st.mode(z_smpls)[0]))) #Add MAP to list trMAPs.append(MAP) ll_heldout #Else this is a fold of the x-validation else: #Get the state sequences and state marginal distributions of the heldout data for data in data_test: #Get state marginals state_marginals = arhmm.heldout_state_marginals(data) trPosteriors.append(state_marginals) #Create mask mask = np.max(state_marginals,axis=1) < opt['MAP_threshold'] trMasks.append(mask) #Get the state sequence with the max probability stateseq = np.argmax(state_marginals,axis=1) trMAPs.append(stateseq) return trMAPs, trPosteriors, trMasks, state_usage, ll_heldout, param_dict, GibbsLLs def map_seq_n_usage(arhmm, data_test, opt, inputs=None): """ Compute the local MAP state (arg-max of marginal state probabilities at each time step) and overall state usages. thresh: if marginal probability of MAP state is below threshold, replace with np.nan (or rather output a mask array with nan's in those time steps) Also output average state usages and the marginal state probabilities """ T = 0; ll_heldout = 0 state_usage = np.zeros(arhmm.K) trMAPs = [] trPosteriors = [] trMasks = [] #Loop over data to obtain MAP sequence for each trial for index, data in enumerate(data_test): #Get state probabilities and log-likelihood if opt['inputdriven']: inputdata = inputs[index] Ez, _, ll = arhmm.expected_states(data,input=inputdata) else: Ez, _, ll = arhmm.expected_states(data) #Update number of data points, state usage, and llood of data T += Ez.shape[0] state_usage += Ez.sum(axis=0) ll_heldout += ll #maximum a posteriori probability estimate of states map_seq = np.argmax(Ez,axis=1) max_prob = Ez[np.r_[0:Ez.shape[0]],map_seq] #Save sequences trMAPs.append(map_seq) trPosteriors.append(Ez) trMasks.append(max_prob < opt['MAP_threshold']) #Normalize state_usage /= T #Get parameters from ARHMM object param_dict = util.params_to_dict(arhmm.params, HMM_INPUTS = opt['inputdriven'], ROBUST = opt['robust']) return trMAPs, trPosteriors, trMasks, state_usage, ll_heldout, param_dict def fit_arhmm_get_llhood(data_list, trsum, K, opt, train_inds=None, test_inds=None, i_fold=-1): #Go! startTime = time.time() #Separate the data into a training and test set based on the indices given if train_inds is not None and test_inds is not None: data_train = [data_list[ii] for ii in train_inds] data_test = [data_list[ii] for ii in test_inds] trsum_test = trsum.iloc[test_inds] else: #fit model on all data data_train = data_list data_test = data_list trsum_test = trsum #adding 10 so i_fold == -1 case doesn't give error np.random.seed(10+i_fold) # set hyperparameters D_obs, M, Mobs, observation_type, ar_kwargs, transition_type, trans_kwargs = set_arhmm_hyperparams(opt,K) ##===== Create the ARHMM object either from Scott's package =====## if opt['model_type'] == 'ARHMM_SL': arhmm = ssm.HMM(K, D_obs, M=M, observations=observation_type, observation_kwargs=ar_kwargs, transitions=transition_type, transition_kwargs=trans_kwargs) if opt['inputdriven']: #Separate inputs from the data_list into training and test sets raise Exception('TODO: Separate inputs from the data_list into training and test sets') else: inputs_train = None inputs_test = None ##===== Fit on training data =====## model_convergence = arhmm.fit(data_train, inputs=inputs_train, method="em", num_em_iters=opt['EM_iters'], tolerance=opt['EM_tolerance']) #Get MAP sequences for heldout data (or all of the data if this isn't part of the xval) trMAPs, trPosteriors, trMasks, state_usage, ll_heldout_old, param_dict = map_seq_n_usage(arhmm, data_test, opt, inputs_test) #Calculate loglikehood of the test and training data ll_heldout = arhmm.log_likelihood(data_test) ll_training = arhmm.log_likelihood(data_train, inputs=inputs_train) ##===== Or from Matt Johnson's packages =====## else: #Sticky or Standard ARHMM if opt['sticky']: # Create AR-HDP-HMM Object arhmm = pyhmm.ARWeakLimitStickyHDPHMM( init_state_distn='uniform', init_emission_distn=init_distn, obs_distns=ar_kwargs, alpha=1.0, kappa=opt['kappa'], gamma=3.0) else: #Vanilla ARHMM arhmm = pyhmm.ARHMM( alpha=4., init_state_distn='uniform', obs_distns=ar_kwargs) ##===== Fit on training data =====## trMAPs, trPosteriors, trMasks, state_usage, ll_heldout, param_dict, model_convergence = \ arhmm_bayesian_fit(arhmm, data_train, data_test, opt, i_fold) #Calculate loglikehood of training data ll_training = arhmm.log_likelihood() #Sort based on state-usage trMAPs, trPosteriors, state_usage, state_perm = util.sort_states_by_usage(state_usage, trMAPs, trPosteriors) ##===== Calculate Log-likelihood =====## #Count total number of time steps in data tTest = sum(map(len, data_test)) ll_heldout_perstep = ll_heldout/tTest #For Training tTrain = sum(map(len, data_train)) ll_training_perstep = ll_training/tTrain llhood_tuple = (ll_heldout,ll_heldout_perstep,ll_training,ll_training_perstep) ##===== Save & Plot =====## #Create subdirectory under base directory for kfold SaveDir, fname_sffx = util.make_sub_dir(K, opt, i_fold) #Convert hyperparameters into dictionary for save process hyperparams = make_hyperparams_dic(opt, K, M, trans_kwargs, ar_kwargs) RunTime = time.perf_counter() - startTime #Plot model parameters plots_YAA.save_plot_parameters(SaveDir, fname_sffx, llhood_tuple, state_usage, hyperparams, param_dict, state_perm, model_convergence, RunTime) #if this is fit on all data (which i_fold==-1 signifies) plot and save MAP seqs (and state-posteriors) # if i_fold == -1: # plots_YAA.save_plot_MAPseqs(SaveDir, fname_sffx, trsum, trMAPs, trPosteriors, trMasks, state_usage, opt, K, state_perm) return ll_training_perstep, ll_heldout_perstep, K ##===== ===== =====## ##===== Start =====## if __name__ == "__main__": #GO! startTime = time.time() #Convert arguments into dictionary; opt <-> options opt = args.__dict__ #Create base folder for saved results SaveDirRoot = util.make_base_dir(opt['model_type'],opt['data_type'],opt['mID']) #Save script options in JSON file opt['SaveDirRoot'] = SaveDirRoot opt['json_dir'] = SaveDirRoot js_fname = 'ARHMM_hyperparameters.json' if opt['save']: with open(os.path.join(SaveDirRoot, js_fname), 'w') as jsfile: json.dump(opt, jsfile, indent=4) ##====== ======================== ======## ##====== Read in Observation Data ======## data_list, trsum, angle_list = util.read_data(opt['mID'],opt['condition'],opt['data_type']) # Number of obserations per time step D_obs = data_list[0].shape[1] opt.update(D_obs = D_obs) # Total Trials nTrials = len(trsum) #Save which trials are being used to fit the ARHMM if opt['save']: trsum.to_csv(os.path.join(SaveDirRoot,'inputted_trials.txt'),header=False,index=False,sep='\t',float_format='%.4f') ##===== ==================== =====## ##===== Perform X-validation =====## k_fold = StratifiedKFold(n_splits=opt['kXval']) #Stratify data per mice and per condition for kfolds include = ['{}_C{}'.format(i,j) for i,j in zip(list(trsum['mID']),list(trsum['cond']))] # Creates parallel processes pool = multiprocessing.Pool(processes=opt['max_processes']) #Preallocate matrix for cross-validation llhood values Ks = np.arange(opt['Kmin'],opt['Kmax']+1,10) ll_heldout = np.zeros((len(Ks),opt['kXval']+1)) ll_training = np.zeros((len(Ks),opt['kXval']+1)) model_fullfit = [] process_outputs = [] #Loop over number of HMM states for index, K in enumerate(np.arange(opt['Kmin'],opt['Kmax']+1,20)): #Fit the model to all of the data, and then for each kfold of x-validation model_fullfit.append(pool.apply_async(fit_arhmm_get_llhood, args=(data_list,trsum,K,opt))) #Loop over kfolds kfold_outputs = [] for iK, (train_indices, test_indices) in enumerate(k_fold.split(data_list, include)): kfold_outputs.append(pool.apply_async(fit_arhmm_get_llhood, args= \ (data_list, trsum, K, opt, train_indices, test_indices, iK))) process_outputs.append(kfold_outputs) ##===== =========== =====## ##===== Get results =====## #Extract log_likelihood results from parallel kfold processing for index, results in enumerate(process_outputs): ll_training[index,:-1] = np.array([iFold.get()[0] for iFold in results]) ll_heldout[index,:-1] = np.array([iFold.get()[1] for iFold in results]) Ks[index] = results[0].get()[2] time #For full fit Ks_ff = Ks.copy() for index, results in enumerate(model_fullfit): ll_training[index,-1] = results.get()[0] ll_heldout[index,-1] = results.get()[1] Ks_ff = results.get()[2] #Close Parallel pool pool.close() #Total Run Time RunTime = time.perf_counter() - startTime opt.update(RunTime = RunTime) hrs=int(RunTime//3600); mins=int((RunTime%3600)//60); secs=int(RunTime - hrs*3600 - mins*60) print('\tTotal run time = {:02d}:{:02d}:{:02d} for {} total trials and {} K\'s\n'.format(hrs,mins,secs,nTrials,opt['Kmax']+1-opt['Kmin'])) # Save summary data of all x-validation results plots_YAA.save_plot_xval_lls(ll_training, ll_heldout, Ks,opt)
40.895551
185
0.62328
2,755
21,143
4.602541
0.189837
0.017744
0.033517
0.006703
0.188801
0.138722
0.108438
0.092666
0.074054
0.060252
0
0.00998
0.255924
21,143
516
186
40.974806
0.796021
0.21714
0
0.132686
0
0.003236
0.119868
0.006425
0
0
0
0
0
1
0.016181
false
0
0.064725
0
0.097087
0.022654
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
9793545d6d0e47925c766734e2f8f75b3b0595d3
1,402
py
Python
src/pyeff_io.py
pyflosic/pyeff
4b76fcc4a0bfb25f9f4106567d01b5ea02db6737
[ "Apache-2.0" ]
3
2019-06-24T08:04:25.000Z
2020-05-26T03:45:45.000Z
src/pyeff_io.py
pyflosic/pyeff
4b76fcc4a0bfb25f9f4106567d01b5ea02db6737
[ "Apache-2.0" ]
null
null
null
src/pyeff_io.py
pyflosic/pyeff
4b76fcc4a0bfb25f9f4106567d01b5ea02db6737
[ "Apache-2.0" ]
null
null
null
# Copyright 2019 PyEFF developers # # 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 def write_cfg(f_name,types,chemical_symbols,spins,x): # write a new cfg file based on the x vector o = open(f_name,'w') o.write('@params\n') o.write('calc = minimize\n') o.write('@nuclei\n') idx = 0 for p in range(len(types)): if types[p] == 'nuclei': o.write(str(x[idx+0])+' '+str(x[idx+1])+' '+str(x[idx+2])+' '+str(chemical_symbols[p])+'\n') idx = idx + 3 o.write('@electrons\n') for p in range(len(types)): if types[p] == 'electron': o.write(str(x[idx+0])+' '+str(x[idx+1])+' '+str(x[idx+2])+' '+str(spins[p])+' '+str(np.exp(x[idx+3]))+'\n') idx = idx +4 o.close()
40.057143
131
0.574893
209
1,402
3.832536
0.478469
0.034956
0.052434
0.03995
0.149813
0.149813
0.149813
0.149813
0.149813
0.082397
0
0.017893
0.282454
1,402
34
132
41.235294
0.77833
0.437946
0
0.117647
0
0
0.095052
0
0
0
0
0
0
1
0.058824
false
0
0.058824
0
0.117647
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
979375047a16643d63291a0d8aad8d8fc63735f2
22,196
py
Python
declarations_site/catalog/data/mapping_chesno.py
li-ar/declarations.com.ua
343cd86cc5a4bd895f2859ed896728f6416ac223
[ "MIT" ]
32
2015-04-01T15:17:35.000Z
2021-05-02T20:46:33.000Z
declarations_site/catalog/data/mapping_chesno.py
li-ar/declarations.com.ua
343cd86cc5a4bd895f2859ed896728f6416ac223
[ "MIT" ]
52
2015-03-23T21:37:04.000Z
2022-02-10T07:27:13.000Z
declarations_site/catalog/data/mapping_chesno.py
li-ar/declarations.com.ua
343cd86cc5a4bd895f2859ed896728f6416ac223
[ "MIT" ]
18
2015-03-16T22:10:44.000Z
2021-11-01T12:56:12.000Z
from collections import namedtuple SubDocument = namedtuple("SubDocument", ["path_prefix", "mapping"]) NumericOperation = namedtuple("NumericOperation", ["path_prefix", "field", "operation"]) JoinOperation = namedtuple("JoinOperation", ["paths", "separator"]) MAPPING = { "_id": "details/id", "intro": { "isnotdeclaration": "", "declaration_year": "details/year" }, "general": { "full_name": "full_name", "last_name": "last_name", "name": "first_name", "patronymic": "second_name", "name_hidden": "", "name_unclear": "", "last_name_hidden": "", "last_name_unclear": "", "patronymic_hidden": "", "patronymic_unclear": "", "inn": "", "addresses": [ { "place": "", "place_district": "", "place_city": "", "place_city_type": "", "place_address": "", "place_address_type": "" } ], "addresses_raw": "", "addresses_raw_hidden": "", "post": { "region": "office/region", "office": "office/office", "post": "office/position" }, "post_raw": "office/position", "family": SubDocument( "details/fields/4.0/items", { "relations": "", "family_name": "family_member", "inn": "" } ), "family_raw": "" }, "income": { "5": { "value": "details/fields/5.0/items/0/value", "comment": "", "family": "details/fields/5.1/items/0/value", "family_comment": "" }, "6": { "value": "details/fields/6.0/items/0/value", "comment": "", "family": "details/fields/6.1/items/0/value", "family_comment": "" }, "7": { "value": "details/fields/7.0/items/0/value", "comment": "", "family": "details/fields/7.1/items/0/value", "family_comment": "", "source_name": "details/fields/7.0/items/0/comment" }, "8": { "value": "details/fields/8.0/items/0/value", "comment": "", "family": "details/fields/8.1/items/0/value", "family_comment": "" }, "9": { "value": "details/fields/9.0/items/0/value", "comment": "", "family": "details/fields/9.1/items/0/value", "family_comment": "" }, "10": { "value": "details/fields/10.0/items/0/value", "comment": "", "family": "details/fields/10.1/items/0/value", "family_comment": "" }, "11": { "value": "details/fields/11.0/items/0/value", "comment": "", "family": "details/fields/11.1/items/0/value", "family_comment": "" }, "12": { "value": "details/fields/12.0/items/0/value", "comment": "", "family": "details/fields/12.1/items/0/value", "family_comment": "" }, "13": { "value": "details/fields/13.0/items/0/value", "comment": "", "family": "details/fields/13.1/items/0/value", "family_comment": "" }, "14": { "value": "details/fields/14.0/items/0/value", "comment": "", "family": "details/fields/14.1/items/0/value", "family_comment": "" }, "15": { "value": "details/fields/15.0/items/0/value", "comment": "", "family": "details/fields/15.1/items/0/value", "family_comment": "" }, "16": { "value": "details/fields/16.0/items/0/value", "comment": "", "family": "details/fields/16.1/items/0/value", "family_comment": "" }, "17": { "value": "details/fields/17.0/items/0/value", "comment": "", "family": "details/fields/17.1/items/0/value", "family_comment": "" }, "18": { "value": "details/fields/18.0/items/0/value", "comment": "", "family": "details/fields/18.1/items/0/value", "family_comment": "" }, "19": { "value": "details/fields/19.0/items/0/value", "comment": "", "family": "details/fields/19.1/items/0/value", "family_comment": "" }, "20": { "value": "details/fields/20.0/items/0/value", "comment": "", "family": "details/fields/20.1/items/0/value", "family_comment": "" }, "21": SubDocument( "details/fields/21.0/items", { "country": "", "country_comment": "", "cur": "", "uah_equal": "value" } ), "22": SubDocument( "details/fields/22.0/items", { "country": "", "country_comment": "", "cur": "", "uah_equal": "value" } ) }, "estate": { "23": SubDocument( "details/fields/23.0/items", { "location_raw": "comment", "region": "", "address": "", "space": "value", "space_units": "", "space_comment": "", "costs": "purchase", "costs_comment": "", "costs_rent": "rent", "costs_rent_comment": "" } ), "24": SubDocument( "details/fields/24.0/items", { "location_raw": "comment", "region": "", "address": "", "space": "value", "space_units": "", "space_comment": "", "costs": "purchase", "costs_comment": "", "costs_rent": "rent", "costs_rent_comment": "" } ), "25": SubDocument( "details/fields/25.0/items", { "location_raw": "comment", "region": "", "address": "", "space": "value", "space_units": "", "space_comment": "", "costs": "purchase", "costs_comment": "", "costs_rent": "rent", "costs_rent_comment": "" } ), "26": SubDocument( "details/fields/26.0/items", { "location_raw": "comment", "region": "", "address": "", "space": "value", "space_units": "", "space_comment": "", "costs": "purchase", "costs_comment": "", "costs_rent": "rent", "costs_rent_comment": "" } ), "27": SubDocument( "details/fields/27.0/items", { "location_raw": "comment", "region": "", "address": "", "space": "value", "space_units": "", "space_comment": "", "costs": "purchase", "costs_comment": "", "costs_rent": "rent", "costs_rent_comment": "" } ), "28": SubDocument( "details/fields/28.0/items", { "location_raw": "comment", "region": "", "address": "", "space": "value", "space_units": "", "space_comment": "", "costs": "purchase", "costs_comment": "", "costs_rent": "rent", "costs_rent_comment": "" } ), "29": SubDocument( "details/fields/29.0/items", { "location_raw": "comment", "region": "", "address": "", "space": "value", "space_units": "", "space_comment": "", "costs_property": "purchase", "costs_property_comment": "", "costs_rent": "rent", "costs_rent_comment": "" } ), "30": SubDocument( "details/fields/30.0/items", { "location_raw": "comment", "region": "", "address": "", "space": "value", "space_units": "", "space_comment": "", "costs_property": "purchase", "costs_property_comment": "", "costs_rent": "rent", "costs_rent_comment": "" } ), "31": SubDocument( "details/fields/31.0/items", { "location_raw": "comment", "region": "", "address": "", "space": "value", "space_units": "", "space_comment": "", "costs_property": "purchase", "costs_property_comment": "", "costs_rent": "rent", "costs_rent_comment": "" } ), "32": SubDocument( "details/fields/32.0/items", { "location_raw": "comment", "region": "", "address": "", "space": "value", "space_units": "", "space_comment": "", "costs_property": "purchase", "costs_property_comment": "", "costs_rent": "rent", "costs_rent_comment": "" } ), "33": SubDocument( "details/fields/33.0/items", { "location_raw": "comment", "region": "", "address": "", "space": "value", "space_units": "", "space_comment": "", "costs_property": "purchase", "costs_property_comment": "", "costs_rent": "rent", "costs_rent_comment": "" } ), "34": SubDocument( "details/fields/34.0/items", { "location_raw": "comment", "region": "", "address": "", "space": "value", "space_units": "", "space_comment": "", "costs_property": "purchase", "costs_property_comment": "", "costs_rent": "rent", "costs_rent_comment": "" } ) }, "vehicle": { "35": SubDocument( "details/fields/35.0/items", { "brand": JoinOperation(("mark", "model", "description"), ' '), "brand_info": "", "year": "year", "sum": "purchase", "sum_comment": "", "sum_rent": "rent", "sum_rent_comment": "", "brand_hidden": "" } ), "36": SubDocument( "details/fields/36.0/items", { "brand": JoinOperation(("mark", "model", "description"), ' '), "brand_info": "", "year": "year", "sum": "purchase", "sum_comment": "", "sum_rent": "rent", "sum_rent_comment": "", "brand_hidden": "" } ), "37": SubDocument( "details/fields/37.0/items", { "brand": JoinOperation(("mark", "model", "description"), ' '), "brand_info": "", "year": "year", "sum": "purchase", "sum_comment": "", "sum_rent": "rent", "sum_rent_comment": "", "brand_hidden": "" } ), "38": SubDocument( "details/fields/38.0/items", { "brand": JoinOperation(("mark", "model", "description"), ' '), "brand_info": "", "year": "year", "sum": "purchase", "sum_comment": "", "sum_rent": "rent", "sum_rent_comment": "", "brand_hidden": "" } ), "39": SubDocument( "details/fields/39.0/items", { "brand": JoinOperation(("mark", "model", "description"), ' '), "brand_info": "", "year": "year", "sum": "purchase", "sum_comment": "", "sum_rent": "rent", "sum_rent_comment": "", "brand_hidden": "" } ), "40": SubDocument( "details/fields/40.0/items", { "brand": JoinOperation(("mark", "model", "description"), ' '), "brand_info": "", "year": "year", "sum": "purchase", "sum_comment": "", "sum_rent": "rent", "sum_rent_comment": "", "brand_hidden": "" } ), "41": SubDocument( "details/fields/41.0/items", { "brand": JoinOperation(("mark", "model", "description"), ' '), "brand_info": "", "year": "year", "sum": "purchase", "sum_comment": "", "sum_rent": "rent", "sum_rent_comment": "", "brand_hidden": "" } ), "42": SubDocument( "details/fields/42.0/items", { "brand": JoinOperation(("mark", "model", "description"), ' '), "brand_info": "", "year": "year", "sum": "purchase", "sum_comment": "", "sum_rent": "rent", "sum_rent_comment": "", "brand_hidden": "" } ), "43": SubDocument( "details/fields/43.0/items", { "brand": JoinOperation(("mark", "model", "description"), ' '), "brand_info": "", "year": "year", "sum": "purchase", "sum_comment": "", "sum_rent": "rent", "sum_rent_comment": "", "brand_hidden": "" } ), "44": SubDocument( "details/fields/44.0/items", { "brand": JoinOperation(("mark", "model", "description"), ' '), "brand_info": "", "year": "year", "sum": "purchase", "sum_comment": "", "sum_rent": "rent", "sum_rent_comment": "", "brand_hidden": "" } ) }, "banks": { "45": [{ "sum": NumericOperation("details/fields/45.0/items", "value", sum), "sum_units": "details/fields/45.0/units", "sum_comment": "", "sum_foreign": NumericOperation("details/fields/45.1/items", "value", sum), "sum_foreign_units": "details/fields/45.1/units", "sum_foreign_comment": "" }], "46": [{ "sum": NumericOperation("details/fields/46.0/items", "value", sum), "sum_units": "details/fields/46.0/units", "sum_comment": "", "sum_foreign": NumericOperation("details/fields/46.1/items", "value", sum), "sum_foreign_units": "details/fields/46.1/units", "sum_foreign_comment": "" }], "47": [{ "sum": NumericOperation("details/fields/47.0/items", "value", sum), "sum_units": "details/fields/47.0/units", "sum_comment": "", "sum_foreign": NumericOperation("details/fields/47.1/items", "value", sum), "sum_foreign_units": "details/fields/47.1/units", "sum_foreign_comment": "" }], "48": [{ "sum": NumericOperation("details/fields/48.0/items", "value", sum), "sum_units": "details/fields/48.0/units", "sum_comment": "", "sum_foreign": NumericOperation("details/fields/48.1/items", "value", sum), "sum_foreign_units": "details/fields/48.1/units", "sum_foreign_comment": "" }], "49": [{ "sum": NumericOperation("details/fields/49.0/items", "value", sum), "sum_units": "details/fields/49.0/units", "sum_comment": "", "sum_foreign": NumericOperation("details/fields/49.1/items", "value", sum), "sum_foreign_units": "details/fields/49.1/units", "sum_foreign_comment": "" }], "50": [{ "sum": NumericOperation("details/fields/50.0/items", "value", sum), "sum_units": "details/fields/50.0/units", "sum_comment": "", "sum_foreign": NumericOperation("details/fields/50.1/items", "value", sum), "sum_foreign_units": "details/fields/50.1/units", "sum_foreign_comment": "" }], "51": [{ "sum": NumericOperation("details/fields/51.0/items", "value", sum), "sum_units": "details/fields/51.0/units", "sum_comment": "", "sum_foreign": NumericOperation("details/fields/51.1/items", "value", sum), "sum_foreign_units": "details/fields/51.1/units", "sum_foreign_comment": "" }], "52": [{ "sum": NumericOperation("details/fields/52.0/items", "value", sum), "sum_units": "details/fields/52.0/units", "sum_comment": "", "sum_foreign": NumericOperation("details/fields/52.1/items", "value", sum), "sum_foreign_units": "details/fields/52.1/units", "sum_foreign_comment": "" }], "53": [{ "sum": NumericOperation("details/fields/53.0/items", "value", sum), "sum_units": "details/fields/53.0/units", "sum_comment": "", "sum_foreign": NumericOperation("details/fields/53.1/items", "value", sum), "sum_foreign_units": "details/fields/53.1/units", "sum_foreign_comment": "" }] }, "liabilities": { "54": { "sum": NumericOperation("details/fields/54.0/items", "value", sum), "sum_comment": "", "sum_foreign": NumericOperation("details/fields/54.1/items", "value", sum), "sum_foreign_comment": "" }, "55": { "sum": NumericOperation("details/fields/55.0/items", "value", sum), "sum_comment": "", "sum_foreign": NumericOperation("details/fields/55.1/items", "value", sum), "sum_foreign_comment": "" }, "56": { "sum": NumericOperation("details/fields/56.0/items", "value", sum), "sum_comment": "", "sum_foreign": NumericOperation("details/fields/56.1/items", "value", sum), "sum_foreign_comment": "" }, "57": { "sum": NumericOperation("details/fields/57.0/items", "value", sum), "sum_comment": "", "sum_foreign": NumericOperation("details/fields/57.1/items", "value", sum), "sum_foreign_comment": "" }, "58": { "sum": NumericOperation("details/fields/58.0/items", "value", sum), "sum_comment": "", "sum_foreign": NumericOperation("details/fields/58.1/items", "value", sum), "sum_foreign_comment": "" }, "59": { "sum": NumericOperation("details/fields/59.0/items", "value", sum), "sum_comment": "", "sum_foreign": NumericOperation("details/fields/59.1/items", "value", sum), "sum_foreign_comment": "" }, "60": { "sum": NumericOperation("details/fields/60.0/items", "value", sum), "sum_comment": "", "sum_foreign": NumericOperation("details/fields/60.1/items", "value", sum), "sum_foreign_comment": "" }, "61": { "sum": NumericOperation("details/fields/61.0/items", "value", sum), "sum_comment": "", "sum_foreign": NumericOperation("details/fields/61.1/items", "value", sum), "sum_foreign_comment": "" }, "62": { "sum": NumericOperation("details/fields/62.0/items", "value", sum), "sum_comment": "", "sum_foreign": NumericOperation("details/fields/62.1/items", "value", sum), "sum_foreign_comment": "" }, "63": { "sum": NumericOperation("details/fields/63.0/items", "value", sum), "sum_comment": "", "sum_foreign": NumericOperation("details/fields/63.1/items", "value", sum), "sum_foreign_comment": "" }, "64": { "sum": NumericOperation("details/fields/64.0/items", "value", sum), "sum_comment": "", "sum_foreign": NumericOperation("details/fields/64.1/items", "value", sum), "sum_foreign_comment": "" } }, "declaration": { "date": "", "notfull": "", "notfull_lostpages": "", "additional_info": "details/comment", "additional_info_text": "details/comment", "needs_scancopy_check": "", "url": "details/url", "link": "details/link", "source": "%CHESNO%" } }
34.573209
88
0.421157
1,760
22,196
5.128409
0.082955
0.167073
0.128518
0.070906
0.699092
0.676158
0.627964
0.590184
0.487924
0.381675
0
0.03649
0.402415
22,196
641
89
34.627145
0.643999
0
0
0.486614
0
0
0.388674
0.148045
0
0
0
0
0
1
0
false
0
0.001575
0
0.001575
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
9793ec4954370ea87c1224757843713b7976c1e3
3,179
py
Python
common/threads/thread_pool.py
ziizhuwy/cify
627ae74f6a27d803521df213e8644366dbba183f
[ "Apache-2.0" ]
8
2018-10-11T16:05:14.000Z
2020-12-30T08:21:15.000Z
common/threads/thread_pool.py
keven1z/cify
627ae74f6a27d803521df213e8644366dbba183f
[ "Apache-2.0" ]
1
2020-04-22T03:36:59.000Z
2020-06-11T06:42:42.000Z
common/threads/thread_pool.py
ziizhuwy/cify
627ae74f6a27d803521df213e8644366dbba183f
[ "Apache-2.0" ]
4
2019-07-10T06:51:45.000Z
2020-04-19T09:52:09.000Z
# !/usr/bin/env python # -*- coding:utf-8 -*- import queue import threading import traceback from data.config import * from common.log.log_util import LogUtil as log logger = log.getLogger(__name__) class ThreadPool(object): def __init__(self): self.task_queue = queue.Queue() self.threads = [] self.__init_thread_pool(THREAD_NUMBER) def __init_thread_pool(self, thread_num): """ the number of workers means the number of parallel running threads """ for i in range(thread_num): worker = Worker(self.task_queue) worker.setDaemon(True) # comment this line to avoid the main thread was end before subthread worker.start() self.threads.append(worker) # logger.debug('constructed a thread pool with %d workers', len(self.threads)) def add_task(self, func, *args): """ add a task to task queue """ self.task_queue.put((func, args)) def wait_all_complete(self): """ this will block the thread until the task queue was empty """ self.task_queue.join() self._terminate_workers() def force_complete(self): self.clear_tasks() self._terminate_workers() def clear_tasks(self): # logger.info('there are %d tasks in the queue that will be removed' % self.task_queue.qsize()) while not self.task_queue.empty(): self.task_queue.get_nowait() self.task_queue.task_done() # logger.debug('removed a task and %d remains' % self.task_queue.qsize()) # logger.info('task queue was cleared and the size=%d' % self.task_queue.qsize()) def _terminate_workers(self): # logger.debug('will terminate %d workers in thread pool', len(self.threads)) for worker in self.threads: worker.terminate() class Worker(threading.Thread): def __init__(self, task_queue): super(Worker, self).__init__() self.task_queue = task_queue self.stop = False def run(self): max_len = 64 while not self.stop: try: do, args = self.task_queue.get(timeout=1) args_desc = str(args) if len(args_desc) > max_len: args_desc = '%s...' % args_desc[0:max_len] # logger.debug('get a task(function=%s, params=%s) and there are %d in queue' % # (do, args_desc, self.task_queue.qsize())) try: do(*args) except: logger.warn(traceback.format_exc()) # logger.debug('finish a task(function=%s, params=%s) and there are %d in queue' % # (do, args_desc, self.task_queue.qsize())) if self.stop: # logger.info('the worker in thread pool was terminated') pass self.task_queue.task_done() except: pass def terminate(self): self.stop = True
32.773196
113
0.557093
385
3,179
4.418182
0.314286
0.10582
0.122281
0.05291
0.104644
0.079953
0.079953
0.079953
0.079953
0.079953
0
0.002389
0.341617
3,179
96
114
33.114583
0.81032
0.334382
0
0.178571
0
0
0.002459
0
0
0
0
0
0
1
0.178571
false
0.035714
0.089286
0
0.303571
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
9794d489e11c9d85b61fcfda17b5fcf122b391c0
4,431
py
Python
whatsappy/group.py
YohananDiamond/whatsappy
2474839baf32295fea568c4dd30c59edace11e58
[ "MIT" ]
null
null
null
whatsappy/group.py
YohananDiamond/whatsappy
2474839baf32295fea568c4dd30c59edace11e58
[ "MIT" ]
null
null
null
whatsappy/group.py
YohananDiamond/whatsappy
2474839baf32295fea568c4dd30c59edace11e58
[ "MIT" ]
null
null
null
from time import sleep from selenium.webdriver.common.keys import Keys from os import path from .tool import * from .error import BadPathError import traceback def change_group_description(self, description: str): """Changes the group description Args: description (str): New group description """ try: # Abre as informações do grupo self.driver.find_element_by_xpath('//*[@id="main"]/header/div[2]').click() if not is_admin(self): print("You are not a group admin!") return self.driver.find_element_by_xpath( '//*[@id="app"]/div[1]/div[1]/div[2]/div[3]/span/div[1]/span/div[1]/div/section/div[2]/div[2]/div/div/span[2]/div' ).click() # Tenta clicar na caneta de edição da descrição description_dom = self.driver.find_element_by_xpath( '//*[@id="app"]/div[1]/div[1]/div[2]/div[3]/span/div[1]/span/div[1]/div/section/div[2]/div[2]/div/div[1]/div/div[2]' ) # Seleciona a descrição para editar description_dom.clear() # Limpa if description.find("\n"): # Escreve for line in description.split("\n"): description_dom.send_keys(line) description_dom.send_keys(Keys.SHIFT + Keys.ENTER) description_dom.send_keys(Keys.ENTER) else: description_dom.send_keys(description) except: error_log(traceback.format_exc()) try: # Fecha as informações do grupo self.driver.find_element_by_xpath( '//*[@id="app"]/div[1]/div[1]/div[2]/div[3]/span/div[1]/span/div[1]/header/div/div[1]/button' ).click() except: pass def change_group_name(self, name: str): """Changes the group name Args: name (str): New group name """ try: # Abre as informações do grupo self.driver.find_element_by_xpath('//*[@id="main"]/header/div[2]').click() if not is_admin(self): print("You are not a group admin!") return # Clica para editar o nome do grupo self.driver.find_element_by_xpath( '//*[@id="app"]/div[1]/div[1]/div[2]/div[3]/span/div[1]/span/div[1]/div/section/div[1]/div[2]/div[1]/span[2]/div' ).click() group_name_dom = self.driver.find_element_by_xpath( '//*[@id="app"]/div[1]/div[1]/div[2]/div[3]/span/div[1]/span/div[1]/div/section/div[1]/div[2]/div[1]/div/div[2]' ) # Seleciona o texto do nome do grupo group_name_dom.clear() # Limpa group_name_dom.send_keys(name + Keys.ENTER) # Escreve except: error_log(traceback.format_exc()) try: self.driver.find_element_by_xpath( '//*[@id="app"]/div[1]/div[1]/div[2]/div[3]/span/div[1]/span/div[1]/header/div/div[1]/button' ).click() # Fecha as informações do grupo except: pass def change_group_pfp(self, file_path: str): try: if not path.isabs(file_path): raise BadPathError("The file path is not absolute") # Abre as informações do grupo self.driver.find_element_by_xpath('//*[@id="main"]/header/div[2]').click() if not is_admin(self): print("You are not a group admin!") return self.driver.find_element_by_xpath( '//*[@id="app"]/div[1]/div[1]/div[2]/div[3]/span/div[1]/span/div[1]/div/section/div[1]/div[1]/div/input' ).send_keys(file_path) # Envia a foto sleep(1) self.driver.find_element_by_xpath( '//*[@id="app"]/div[1]/span[2]/div[1]/div/div/div/div/div/span/div[1]/div/div[2]/span/div' ).click() # Confima except: error_log(traceback.format_exc()) try: self.driver.find_element_by_xpath( '//*[@id="app"]/div[1]/div[1]/div[2]/div[3]/span/div[1]/span/div[1]/header/div/div[1]/button' ).click() # Fecha as informações do grupo except: pass def leave_group(self): """Leaves the group you are""" # Abre as informações do grupo self.driver.find_element_by_xpath('//*[@id="main"]/header/div[2]').click() self.driver.find_element_by_xpath( '//*[@id="app"]/div[1]/div[1]/div[2]/div[3]/span/div[1]/span/div[1]/div/section/div[6]/div' ).click() self.driver.find_element_by_xpath( '//*[@id="app"]/div[1]/span[2]/div[1]/div/div/div/div/div/div[2]/div[2]' ).click()
31.204225
128
0.594223
666
4,431
3.83033
0.154655
0.079969
0.090553
0.123481
0.670325
0.624069
0.611133
0.597413
0.597413
0.597413
0
0.026447
0.232002
4,431
141
129
31.425532
0.723185
0.129091
0
0.586207
0
0.126437
0.340963
0.31176
0
0
0
0
0
1
0.045977
false
0.034483
0.068966
0
0.149425
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
97959af172f3896c43a9153dc3a145cbbaa7178b
365
py
Python
Books/GodOfPython/P16_Networking/SimplehttpServer.py
Tim232/Python-Things
05f0f373a4cf298e70d9668c88a6e3a9d1cd8146
[ "MIT" ]
2
2020-12-05T07:42:55.000Z
2021-01-06T23:23:18.000Z
Books/GodOfPython/P16_Networking/SimplehttpServer.py
Tim232/Python-Things
05f0f373a4cf298e70d9668c88a6e3a9d1cd8146
[ "MIT" ]
null
null
null
Books/GodOfPython/P16_Networking/SimplehttpServer.py
Tim232/Python-Things
05f0f373a4cf298e70d9668c88a6e3a9d1cd8146
[ "MIT" ]
null
null
null
from http.server import HTTPServer, SimpleHTTPRequestHandler import sys ip = '127.0.0.1' port = 8000 addr = (ip, port) httpd = HTTPServer(addr, SimpleHTTPRequestHandler) Servip, Servport = httpd.socket.getsockname() try: httpd.serve_forever() except KeyboardInterrupt: print('Keyboard interrupt received, exiting.') httpd.server_close() sys.exit(0)
20.277778
60
0.750685
44
365
6.181818
0.704545
0
0
0
0
0
0
0
0
0
0
0.035032
0.139726
365
18
61
20.277778
0.83121
0
0
0
0
0
0.125683
0
0
0
0
0
0
1
0
false
0
0.153846
0
0.153846
0.076923
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
9796d5c78ed8b8b2d57b57dbb718992d6e9e2e56
935
py
Python
2020/day10.py
mbmackenzie/advent-of-code
66ef2723b67c84b9c03e05281106fb2811da17a1
[ "MIT" ]
null
null
null
2020/day10.py
mbmackenzie/advent-of-code
66ef2723b67c84b9c03e05281106fb2811da17a1
[ "MIT" ]
null
null
null
2020/day10.py
mbmackenzie/advent-of-code
66ef2723b67c84b9c03e05281106fb2811da17a1
[ "MIT" ]
null
null
null
"""Day 10: Adapter Array""" from collections import Counter from collections import defaultdict from aoc import Solution class Day10(Solution): """Solution to day 10 of the 2020 Advent of Code""" def __init__(self) -> None: super().__init__(2020, 10, "Adapter Array") @property def max_joltage(self) -> int: """The last element in the data plus 3""" return self.data[-1] + 3 def _part_one(self) -> int: counts = Counter( val - prev for val, prev in zip(self.data, [0, *self.data[:-1]]) ) return counts[1] * (counts[3] + 1) def _part_two(self) -> int: counts = defaultdict(int, {0: 1}) for value in self.data: counts[value] = counts[value - 1] + counts[value - 2] + counts[value - 3] return counts[self.max_joltage - 3] def _get_data(self) -> list[int]: return sorted(self.input.as_list(int))
25.972222
85
0.594652
129
935
4.178295
0.403101
0.059369
0.051948
0
0
0
0
0
0
0
0
0.044183
0.273797
935
35
86
26.714286
0.749632
0.11016
0
0
0
0
0.015931
0
0
0
0
0
0
1
0.238095
false
0
0.142857
0.047619
0.619048
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
1
0
0
0
0
1
0
0
2
97970c5a1a0f3349fb93a725c6270efcd0b82297
874
py
Python
train.py
groverkds/hand_sign_recognition
4ae05c43af869e990acc636b0a031f903709dfbc
[ "Apache-2.0" ]
3
2020-02-18T07:12:42.000Z
2022-01-07T14:35:42.000Z
train.py
polawarrushi/hand_sign_recognition
493b3568c462280533a33cab592008c91da1f999
[ "Apache-2.0" ]
null
null
null
train.py
polawarrushi/hand_sign_recognition
493b3568c462280533a33cab592008c91da1f999
[ "Apache-2.0" ]
8
2019-05-22T15:45:17.000Z
2021-09-15T17:28:50.000Z
import numpy as np import pickle from sklearn.model_selection import train_test_split from sklearn import svm from sklearn import metrics import pandas as pd with open('data/dataframe.pickle', 'rb') as handle: df = pickle.load(handle) data = df.copy() data.drop('alphabet', axis=1) target = df.alphabet X_train, X_test, y_train, y_test = train_test_split(data, target, test_size=0.4,random_state=109) # 70% training and 30% test #Create a svm Classifier clf = svm.SVC(kernel='linear') # Linear Kernel #Train the model using the training sets clf.fit(X_train, y_train) #Predict the response for test dataset y_pred = clf.predict(X_test) # Model Accuracy: how often is the classifier correct? print("Accuracy:",metrics.accuracy_score(y_test, y_pred)) with open('data/classifier_SVM.pickle', 'wb') as handle: pickle.dump(clf, handle, protocol=pickle.HIGHEST_PROTOCOL)
30.137931
125
0.771167
144
874
4.541667
0.479167
0.050459
0.042813
0
0
0
0
0
0
0
0
0.013055
0.12357
874
29
126
30.137931
0.840731
0.218535
0
0
0
0
0.109306
0.069424
0
0
0
0
0
1
0
false
0
0.333333
0
0.333333
0.055556
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
1
0
0
0
0
1
9797b5af874059d81d0e5f547824f391670ed073
56
py
Python
gnoll/actions/dispatch.py
gnoll-project/gnoll-python
cf2540d2220733ba2203d86ca939fa64f38d0af0
[ "MIT" ]
null
null
null
gnoll/actions/dispatch.py
gnoll-project/gnoll-python
cf2540d2220733ba2203d86ca939fa64f38d0af0
[ "MIT" ]
null
null
null
gnoll/actions/dispatch.py
gnoll-project/gnoll-python
cf2540d2220733ba2203d86ca939fa64f38d0af0
[ "MIT" ]
null
null
null
from pyee import EventEmitter dispatch = EventEmitter()
18.666667
29
0.821429
6
56
7.666667
0.833333
0
0
0
0
0
0
0
0
0
0
0
0.125
56
2
30
28
0.938776
0
0
0
0
0
0
0
0
0
0
0
0
1
0
false
0
0.5
0
0.5
0
1
0
0
null
0
0
0
0
0
0
0
0
0
0
0
0
0
1
0
0
0
0
0
0
0
0
0
0
null
0
0
0
0
0
0
0
0
1
0
0
0
0
3
979851dc526feb93a60dbe69c32893824847ba79
1,217
py
Python
dataclasses_serialization/serializer_base/dataclasses.py
blfoster/python-dataclasses-serialization
1a2d1fc15ca1800c2b4953fe5cb2557f37d1475d
[ "MIT" ]
19
2019-04-15T15:57:20.000Z
2021-07-09T07:01:12.000Z
dataclasses_serialization/serializer_base/dataclasses.py
blfoster/python-dataclasses-serialization
1a2d1fc15ca1800c2b4953fe5cb2557f37d1475d
[ "MIT" ]
14
2019-08-01T13:03:53.000Z
2021-04-20T13:26:54.000Z
dataclasses_serialization/serializer_base/dataclasses.py
blfoster/python-dataclasses-serialization
1a2d1fc15ca1800c2b4953fe5cb2557f37d1475d
[ "MIT" ]
11
2019-06-13T21:38:55.000Z
2022-02-28T08:53:20.000Z
from toolz import curry from dataclasses_serialization.serializer_base.errors import DeserializationError from dataclasses_serialization.serializer_base.noop import noop_deserialization from dataclasses_serialization.serializer_base.typing import ( dataclass_field_types, isinstance, ) __all__ = ["dict_to_dataclass"] @curry def dict_to_dataclass(cls, dct, deserialization_func=noop_deserialization): if not isinstance(dct, dict): raise DeserializationError( "Cannot deserialize {} {!r} using {}".format( type(dct), dct, dict_to_dataclass ) ) try: fld_types = dataclass_field_types(cls, require_bound=True) except TypeError: raise DeserializationError("Cannot deserialize unbound generic {}".format(cls)) try: return cls( **{ fld.name: deserialization_func(fld_type, dct[fld.name]) for fld, fld_type in fld_types if fld.name in dct } ) except TypeError: raise DeserializationError( "Missing one or more required fields to deserialize {!r} as {}".format( dct, cls ) )
29.682927
87
0.642564
126
1,217
5.97619
0.420635
0.059761
0.111554
0.151394
0.167331
0
0
0
0
0
0
0
0.282662
1,217
40
88
30.425
0.862543
0
0
0.176471
0
0
0.123254
0
0
0
0
0
0
1
0.029412
false
0
0.117647
0
0.176471
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
97992e047d22c07ba264c49af6fa5aef078bd341
905
py
Python
pydrift/decorators.py
sergiocalde94/pydrift
8d8968ca80895cc31e86bc55df57ad64712e36d8
[ "MIT" ]
18
2020-06-27T21:05:18.000Z
2021-12-20T15:14:57.000Z
pydrift/decorators.py
sergiocalde94/pydrift
8d8968ca80895cc31e86bc55df57ad64712e36d8
[ "MIT" ]
5
2021-02-03T17:53:53.000Z
2021-04-23T14:03:36.000Z
pydrift/decorators.py
sergiocalde94/pydrift
8d8968ca80895cc31e86bc55df57ad64712e36d8
[ "MIT" ]
7
2020-06-07T10:51:41.000Z
2021-06-13T20:23:28.000Z
from functools import wraps def check_optional_module(_func=None, *, has_module: bool, exception_message: str): def decorator_check_optional_module(func): @wraps(func) def wrapper_check_optional_module(*args, **kwargs): if not has_module: raise ModuleNotFoundError(exception_message) return func(*args, **kwargs) return wrapper_check_optional_module if _func is None: return decorator_check_optional_module else: return decorator_check_optional_module(_func) def track_calls(func): @wraps(func) def wrapper_track_calls(*args, **kwargs): wrapper_track_calls.has_been_called_ids.append(id(args[0])) return func(*args, **kwargs) wrapper_track_calls.has_been_called_ids = [] return wrapper_track_calls
31.206897
67
0.640884
102
905
5.303922
0.333333
0.144177
0.210721
0.127542
0.428835
0.158965
0.158965
0.158965
0.158965
0
0
0.001546
0.285083
905
28
68
32.321429
0.834621
0
0
0.173913
0
0
0
0
0
0
0
0
0
1
0.217391
false
0
0.043478
0
0.521739
0
0
0
0
null
0
1
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
1
0
0
0
0
1
0
0
3
979b32ffcbb69c325f9cc6f26076b4bf72ce74b8
93
py
Python
django-version/djversion/apps.py
sarath196/django-mptt-demo-re-version
d570aa8612c0bf838c191a7a8a1b3f57bf2be16f
[ "MIT" ]
null
null
null
django-version/djversion/apps.py
sarath196/django-mptt-demo-re-version
d570aa8612c0bf838c191a7a8a1b3f57bf2be16f
[ "MIT" ]
null
null
null
django-version/djversion/apps.py
sarath196/django-mptt-demo-re-version
d570aa8612c0bf838c191a7a8a1b3f57bf2be16f
[ "MIT" ]
null
null
null
from django.apps import AppConfig class DjversionConfig(AppConfig): name = 'djversion'
15.5
33
0.763441
10
93
7.1
0.9
0
0
0
0
0
0
0
0
0
0
0
0.16129
93
5
34
18.6
0.910256
0
0
0
0
0
0.096774
0
0
0
0
0
0
1
0
false
0
0.333333
0
1
0
1
0
0
null
0
0
0
0
0
0
0
0
0
0
0
0
0
1
0
0
0
0
0
0
0
0
0
0
null
0
0
0
0
0
0
0
0
1
0
1
0
0
4
979b57b2f520e53382dbdd26bd190261e6e49b86
9,359
py
Python
DQN_Qlearning/agent.py
WoShiDongZhiWu/Reinforcement-learning-Algorithm
59fdf29e7feb73048b9ddf3b4755b55f0459efcb
[ "Apache-2.0" ]
1
2019-12-23T02:59:13.000Z
2019-12-23T02:59:13.000Z
DQN_Qlearning/agent.py
WoShiDongZhiWu/reinforcement-learning-algorithm
59fdf29e7feb73048b9ddf3b4755b55f0459efcb
[ "Apache-2.0" ]
null
null
null
DQN_Qlearning/agent.py
WoShiDongZhiWu/reinforcement-learning-algorithm
59fdf29e7feb73048b9ddf3b4755b55f0459efcb
[ "Apache-2.0" ]
null
null
null
''' ################################################################################################# # author wudong # date 20190812 # 功能 # 实现各类算法,Srasa(0),Sarsa(λ),Q-learning,DQN ################################################################################################# ''' from random import random, choice from gym import Env, spaces import gym import numpy as np from core import Transition, Experience, Agent from utils import str_key, set_dict, get_dict from utils import epsilon_greedy_pi, epsilon_greedy_policy from utils import greedy_policy, learning_curve from approximator import NetApproximator class SarsaAgent(Agent): def __init__(self, env:Env, capacity:int = 20000): super(SarsaAgent, self).__init__(env, capacity) self.Q = {} #增加Q字典存储行为价值 def policy(self, A, s, Q, epsilon): #重写基类的policy函数 ''' 使用ε-greedy策略 return a 策略得到的行为 ''' return epsilon_greedy_policy(A, s, Q, epsilon) def learning_method(self, gamma = 0.9, alpha = 0.1, epsilon = 1e-5, display = False, lambda_ = None): '''重写基类的函数 遍历一个episode ''' self.state = self.env.reset() #个体当前的状态 s0 = self.state if display: self.env.render() a0 = self.perform_policy(s0, epsilon) #执行策略,生成动作 time_in_episode, total_reward = 0, 0 is_done = False while not is_done: # add code here s1, r1, is_done, info, total_reward = self.act(a0) if display: self.env.render() a1 = self.perform_policy(s1, epsilon) old_q = get_dict(self.Q, s0, a0) q_prime = get_dict(self.Q, s1, a1) td_target = r1 + gamma * q_prime new_q = old_q + alpha * (td_target - old_q) set_dict(self.Q, new_q, s0, a0) s0, a0 = s1, a1 time_in_episode += 1 if display: print(self.experience.last_episode) return time_in_episode, total_reward class SarsaLambdaAgent(Agent): def __init__(self, env:Env, capacity:int = 20000): super(SarsaLambdaAgent, self).__init__(env, capacity) self.Q = {} def policy(self, A, s, Q, epsilon): return epsilon_greedy_policy(A, s, Q, epsilon) def learning_method(self, lambda_ = 0.9, gamma = 0.9, alpha = 0.1, epsilon = 1e-5, display = False): self.state = self.env.reset() s0 = self.state if display: self.env.render() a0 = self.perform_policy(s0, epsilon) # print(self.action_t.name) time_in_episode, total_reward = 0, 0 is_done = False E = {} while not is_done: # add code here s1, r1, is_done, info, total_reward = self.act(a0) if display: self.env.render() a1 = self.perform_policy(s1, epsilon) q = get_dict(self.Q, s0, a0) q_prime = get_dict(self.Q, s1, a1) delta = r1 + gamma * q_prime - q e = get_dict(E, s0, a0) e += 1 set_dict(E, e, s0, a0) for s in self.S: for a in self.A: e_value = get_dict(E, s, a) old_q = get_dict(self.Q, s, a) new_q = old_q + alpha * delta * e_value new_e = gamma * lambda_ * e_value set_dict(self.Q, new_q, s, a) set_dict(E, new_e, s, a) s0, a0 = s1, a1 time_in_episode += 1 if display: print(self.experience.last_episode) return time_in_episode, total_reward class QAgent(Agent): def __init__(self, env:Env, capacity:int = 20000): super(QAgent, self).__init__(env, capacity) self.Q = {} def policy(self, A, s, Q, epsilon): return epsilon_greedy_policy(A, s, Q, epsilon) def learning_method(self, gamma = 0.9, alpha = 0.1, epsilon = 1e-5, display = False, lambda_ = None): self.state = self.env.reset() s0 = self.state if display: self.env.render() time_in_episode, total_reward = 0, 0 is_done = False while not is_done: # add code here a0 = self.perform_policy(s0, epsilon) #使用ε-greedy s1, r1, is_done, info, total_reward = self.act(a0) if display: self.env.render() self.policy = greedy_policy a1 = greedy_policy(self.A, s1, self.Q) #使用完全贪婪策略 old_q = get_dict(self.Q, s0, a0) q_prime = get_dict(self.Q, s1, a1) td_target = r1 + gamma * q_prime new_q = old_q + alpha * (td_target - old_q) set_dict(self.Q, new_q, s0, a0) s0 = s1 time_in_episode += 1 if display: print(self.experience.last_episode) return time_in_episode, total_reward class DQNAgent(Agent): '''使用近似的价值函数(全连接网络)实现的DQN ''' def __init__(self, env: Env = None, capacity = 20000, hidden_dim: int = 32, batch_size = 128, epochs = 2): if env is None: raise "agent should have an environment" super(DQNAgent, self).__init__(env, capacity) self.input_dim = env.observation_space.shape[0] # 状态连续,输入维度 self.output_dim = env.action_space.n # 行为离散,输出维度 self.hidden_dim = hidden_dim #隐藏层的维度 # 行为网络,该网络用来计算产生行为,以及对应的Q值,每次更新 self.behavior_Q = NetApproximator(input_dim = self.input_dim, output_dim = self.output_dim, hidden_dim = self.hidden_dim) self.target_Q = self.behavior_Q.clone() # 计算价值目标的Q,不定期更新 self.batch_size = batch_size # 批学习一次状态转换数量 self.epochs = epochs # 统一批状态转换学习的次数 return def _update_target_Q(self): '''将更新策略的Q网络(连带其参数)复制给输出目标Q值的网络 ''' self.target_Q = self.behavior_Q.clone() # 更新计算价值目标的Q网络 def policy(self, A, s, Q = None, epsilon = None): '''依据更新策略的价值函数(网络)产生一个行为,遵循greedy或ε-greedy ''' Q_s = self.behavior_Q(s) # 行为价值函数,预测得到Q rand_value = random() if epsilon is not None and rand_value < epsilon: return self.env.action_space.sample() else: return int(np.argmax(Q_s)) #返回得到最大Q值的动作a def _learn_from_memory(self, gamma, learning_rate): '''从记忆中进行学习,(experience-episode-transmition) ''' trans_pieces = self.sample(self.batch_size) # 随机获取记忆里的Transmition,取batch_size个 states_0 = np.vstack([x.s0 for x in trans_pieces]) actions_0 = np.array([x.a0 for x in trans_pieces]) reward_1 = np.array([x.reward for x in trans_pieces]) is_done = np.array([x.is_done for x in trans_pieces]) states_1 = np.vstack([x.s1 for x in trans_pieces]) X_batch = states_0 y_batch = self.target_Q(states_0) # 得到numpy格式的预测结果 Q_target = reward_1 + gamma * np.max(self.target_Q(states_1), axis=1)*\ (~ is_done) # is_done则Q_target==reward_1 # switch this on will make DQN to DDQN # 行为a'从行为价值网络中得到 #a_prime = np.argmax(self.behavior_Q(states_1), axis=1).reshape(-1) # (s',a')的价值从目标价值网络中得到 #Q_states_1 = self.target_Q(states_1) #temp_Q = Q_states_1[np.arange(len(Q_states_1)), a_prime] # (s,a)的目标价值根据贝尔曼方程得到 #Q_target = reward_1 + gamma * temp_Q * (~ is_done) # is_done则Q_target==reward_1 ## end of DDQN part y_batch[np.arange(len(X_batch)), actions_0] = Q_target #作为目标值、监督值 # 训练行为价值网络,更新其参数 loss = self.behavior_Q.fit(x = X_batch, #行为价值网络,利用X_batch生成预测值,与y_batch计算损失 y = y_batch, learning_rate = learning_rate, epochs = self.epochs) mean_loss = loss.sum() / self.batch_size # 可根据需要设定一定的目标价值网络参数的更新频率 self._update_target_Q() return mean_loss def learning_method(self, gamma = 0.9, alpha = 0.1, epsilon = 1e-5, display = False, lambda_ = None): '''遍历单个eposide ''' self.state = self.env.reset() s0 = self.state if display: self.env.render() time_in_episode, total_reward = 0, 0 is_done = False loss = 0 while not is_done: # add code here s0 = self.state a0 = self.perform_policy(s0, epsilon) #行为价值网络behavior产生动作a0 s1, r1, is_done, info, total_reward = self.act(a0) #执行动作,得到观测值 if display: self.env.render() # 当经历里有足够大小的transition时,开始启用基于experience的学习 if self.total_trans > self.batch_size: loss += self._learn_from_memory(gamma, alpha) # s0 = s1 time_in_episode += 1 loss /= time_in_episode if display: print("epsilon:{:3.2f},loss:{:3.2f},{}".format(epsilon,loss,self.experience.last_episode)) return time_in_episode, total_reward
35.316981
105
0.543862
1,172
9,359
4.116894
0.196246
0.024663
0.035026
0.026529
0.516269
0.459689
0.429016
0.395855
0.395855
0.395855
0
0.027433
0.337857
9,359
265
106
35.316981
0.75117
0.147452
0
0.517045
0
0
0.008036
0.003954
0
0
0
0
0
1
0.079545
false
0
0.051136
0.011364
0.215909
0.022727
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
979c4c7ab54f0e47ec7248d0082811b92e99c917
3,649
py
Python
DMProject/15.package/15.7.MNIST.py
gongjunhuang/Spider
c683137dafac9c7f4afd359baf9d0717d1a127e2
[ "Apache-2.0" ]
1
2018-02-26T15:45:17.000Z
2018-02-26T15:45:17.000Z
DMProject/15.package/15.7.MNIST.py
gongjunhuang/Spider
c683137dafac9c7f4afd359baf9d0717d1a127e2
[ "Apache-2.0" ]
null
null
null
DMProject/15.package/15.7.MNIST.py
gongjunhuang/Spider
c683137dafac9c7f4afd359baf9d0717d1a127e2
[ "Apache-2.0" ]
null
null
null
#!/usr/bin/python # -*- coding:utf-8 -*- import numpy as np from sklearn import svm import matplotlib.colors import matplotlib.pyplot as plt from PIL import Image from sklearn.metrics import accuracy_score import pandas as pd import os import csv from sklearn.model_selection import train_test_split from sklearn.model_selection import GridSearchCV from sklearn.ensemble import RandomForestClassifier from time import time from pprint import pprint def save_image(im, i): im = 255 - im.values.reshape(28, 28) a = im.astype(np.uint8) output_path = '.\\HandWritten' if not os.path.exists(output_path): os.mkdir(output_path) Image.fromarray(a).save(output_path + ('\\%d.png' % i)) def save_result(model): data_test_pred = model.predict(data_test) data_test['Label'] = data_test_pred data_test.to_csv('Prediction.csv', header=True, index=True, columns=['Label']) if __name__ == "__main__": classifier_type = 'RF' print('载入训练数据...') t = time() data = pd.read_csv('MNIST.train.csv', header=0, dtype=np.int) print('载入完成,耗时%f秒' % (time() - t)) x, y = data.iloc[:, 1:], data['label'] x_train, x_valid, y_train, y_valid = train_test_split(x, y, test_size=0.2, random_state=1) print(x.shape, x_valid.shape) print('图片个数:%d,图片像素数目:%d' % x.shape) print('载入测试数据...') t = time() data_test = pd.read_csv('MNIST.test.csv', header=0, dtype=np.int) print('载入完成,耗时%f秒' % (time() - t)) matplotlib.rcParams['font.sans-serif'] = ['SimHei'] matplotlib.rcParams['axes.unicode_minus'] = False plt.figure(figsize=(15, 9), facecolor='w') for index in range(16): image = x.iloc[index, :] plt.subplot(4, 8, index + 1) plt.imshow(image.values.reshape(28, 28), cmap=plt.cm.gray_r, interpolation='nearest') plt.title('训练图片: %i' % y[index]) for index in range(16): image = data_test.iloc[index, :] plt.subplot(4, 8, index + 17) plt.imshow(image.values.reshape(28, 28), cmap=plt.cm.gray_r, interpolation='nearest') save_image(image.copy(), index) plt.title('测试图片') plt.tight_layout(2) plt.show() if classifier_type == 'SVM': model = svm.SVC(C=1000, kernel='rbf', gamma=1e-10) print('SVM开始训练...') else: model = RandomForestClassifier(100, criterion='gini', min_samples_split=2, min_impurity_decrease=1e-10) print('随机森林开始训练...') t = time() model.fit(x_train, y_train) t = time() - t print('%s训练结束,耗时%d分钟%.3f秒' % (classifier_type, int(t/60), t - 60*int(t/60))) t = time() y_train_pred = model.predict(x_train) t = time() - t print('%s训练集准确率:%.3f%%,耗时%d分钟%.3f秒' % (classifier_type, accuracy_score(y_train, y_train_pred)*100, int(t/60), t - 60*int(t/60))) t = time() y_valid_pred = model.predict(x_valid) t = time() - t print('%s测试集准确率:%.3f%%,耗时%d分钟%.3f秒' % (classifier_type, accuracy_score(y_valid, y_valid_pred)*100, int(t/60), t - 60*int(t/60))) save_result(model) err = (y_valid != y_valid_pred) err_images = x_valid[err] err_y_hat = y_valid_pred[err] err_y = y_valid[err] print(err_y_hat) print(err_y) plt.figure(figsize=(10, 8), facecolor='w') for index in range(12): image = err_images.iloc[index, :] plt.subplot(3, 4, index + 1) plt.imshow(image.values.reshape(28, 28), cmap=plt.cm.gray_r, interpolation='nearest') plt.title('错分为:%i,真实值:%i' % (err_y_hat[index], err_y.values[index]), fontsize=12) plt.suptitle('数字图片手写体识别:分类器%s' % classifier_type, fontsize=15) plt.tight_layout(rect=(0, 0, 1, 0.95)) plt.show()
35.086538
132
0.64456
562
3,649
4.021352
0.307829
0.011947
0.015929
0.015487
0.316372
0.253097
0.218142
0.197345
0.197345
0.163717
0
0.03488
0.190737
3,649
103
133
35.427184
0.730444
0.01014
0
0.191011
0
0
0.096953
0.014958
0
0
0
0
0
1
0.022472
false
0
0.157303
0
0.179775
0.157303
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
979c80762641e4c8d009fdd05535ea43eb570cd2
4,122
py
Python
examples/collision-avoid/pyplot_staticplan.py
yinanl/rocs
bf2483903e39f4c0ea254a9ef56720a1259955ad
[ "BSD-3-Clause" ]
null
null
null
examples/collision-avoid/pyplot_staticplan.py
yinanl/rocs
bf2483903e39f4c0ea254a9ef56720a1259955ad
[ "BSD-3-Clause" ]
null
null
null
examples/collision-avoid/pyplot_staticplan.py
yinanl/rocs
bf2483903e39f4c0ea254a9ef56720a1259955ad
[ "BSD-3-Clause" ]
null
null
null
import matplotlib.pyplot as plt import matplotlib.patches as patches import matplotlib.animation as animation import matplotlib.colors as mcolors from scipy.interpolate import interp1d from scipy.integrate import solve_ivp import os import re import numpy as np import h5py import sys from os.path import dirname, realpath pypath = dirname(dirname(dirname(realpath(__file__)))) + '/python/' sys.path.insert(1, pypath) import utils from odes import car2 dirpath = dirname(realpath(__file__)) transfile = '/abstfull_0.2-0.2-0.2.h5' labelfile = '/labels_dba1_abstfull_0.2-0.2-0.2.h5' ctlrfile = '/controller_dba1_0.2-0.2-0.2.h5' specfile = '/dba1.txt' # # Simulation of static motion planning tau, X, eta, _, winids, controller = \ utils.read_controller_abst_from_h5(dirpath+ctlrfile) # # Compute the percentage of winning set on the state space winset = controller.xgrid[winids, :] print("\nWinning set coverage:") winper = "{:.2%}".format(winids.size/controller.xgrid.shape[0]) print(winper) # # Load specification dba = utils.read_spec_from_txt(dirpath+specfile) # # Simulation Tsim = 50 num_acc = 3 x0 = np.array([1.0, 1.0, np.pi/3.]) i0 = utils.index_in_grid(x0, controller.xgrid) if(not np.any(winids == i0)): sys.exit("The initial condition is not in the winning set.\n") xsim, usim, qsim, tsim = utils.simulate_abstbased_dba_control( tau, Tsim, num_acc, x0, car2, dba, controller) # # Display workspace fig = plt.figure() ax = plt.axes() ax.set_xlim(0,10) ax.set_ylim(0,10) xgrid = np.array([]) eta = np.array([]) labels = np.array([]) obs = np.array([]) with h5py.File(dirpath+transfile, 'r') as ft,\ h5py.File(dirpath+labelfile, 'r') as fl: eta = ft['eta'][...] xgrid = ft['xgrid'][...] obs = ft['obs'][...] labels = fl['labels'][...] oset = xgrid[obs, :] ax.add_collection( utils.polycoll_grid_array(oset, eta, True, 'gray', 0.7) ) gset = xgrid[np.where(labels>0),:].squeeze() ax.add_collection( utils.polycoll_grid_array(gset, eta, True, 'palegreen', 0.7) ) obstacles = [[0.0, 0.5, 5.0, 6.0], [2.4, 2.6, 0.0, 3.2], [3.9, 4.1, 9.0, 10.0], #[3.9, 4.1, 8.0, 10.0] [5.9, 6.1, 0.0, 0.6], [5.9, 6.1, 3.8, 5.1], # [5.9, 6.1, 3.8, 6.1], [6.1, 10.0, 4.9, 5.1]] # [6.1, 10.0, 5.9, 6.1] rects_obs = [patches.Rectangle((obstacles[i][0], obstacles[i][2]), obstacles[i][1]-obstacles[i][0], obstacles[i][3]-obstacles[i][2], linewidth=1,edgecolor='k',facecolor='k') for i in range(len(obstacles))] goals = [[0.5, 2.0, 7.5, 9.5], # a [7.5, 9.5, 0.8, 3.0]] # d rects_gs = [patches.Rectangle((goals[i][0], goals[i][2]), goals[i][1]-goals[i][0], goals[i][3]-goals[i][2], linewidth=1,edgecolor='y',fill=False) for i in range(len(goals))] circ_gs = patches.Circle([8.0, 8.0], radius=0.8, linewidth=1, edgecolor='y', fill=False) for rect in rects_obs: ax.add_patch(rect) for rect in rects_gs: ax.add_patch(rect) ax.add_patch(circ_gs) ax.text((goals[0][0]+goals[0][1])/2.0-0.5, (goals[0][2]+goals[0][3])/2.0, "pickup") ax.text((goals[1][0]+goals[1][1])/2.0-0.5, (goals[1][2]+goals[1][3])/2.0, "drop") ax.text(7.8, 7.8, "count") # # # Plot winning set in 2D plane # ax.add_collection( # utils.polycoll_grid_array(winset, eta, True, 'palegoldenrod', 0.7) # ) # # Plot closed-loop trajectoryies colors = list(mcolors.TABLEAU_COLORS.keys()) qdiff = np.diff(np.insert(qsim, 0, dba.q0)) qchks = np.argwhere(qdiff != 0).squeeze() qchks = np.insert(qchks, 0, 0) qchks = np.append(qchks, qsim.size) q = dba.q0 for k in range(qchks.size-1): q = q + qdiff[qchks[k]] xs = xsim[qchks[k]:qchks[k+1]+1, :] ax.plot(xs[:, 0], xs[:, 1], color=colors[q]) ax.plot(xsim[0, 0], xsim[0, 1], marker='^', markerfacecolor='r', markeredgecolor='r') ax.plot(xsim[-1, 0], xsim[-1, 1], marker='v', markerfacecolor='g', markeredgecolor='g') plt.show()
30.761194
83
0.607472
679
4,122
3.612666
0.273932
0.008969
0.007338
0.009784
0.157358
0.1064
0.087648
0.013045
0
0
0
0.068285
0.200631
4,122
133
84
30.992481
0.676176
0.08952
0
0.039604
0
0
0.065451
0.02441
0
0
0
0
0
1
0
false
0
0.138614
0
0.138614
0.019802
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
979eeaea89fd74c57893ede5d89f60a48b582ae8
2,394
py
Python
source/script/FASelector_SRC/Type/.JPG.py
onsoim/FuzzBuilderEx
d0e8bada27677a0f676e92dc48aaa764ba679508
[ "Apache-2.0" ]
6
2021-03-27T06:07:01.000Z
2022-03-29T04:54:03.000Z
source/script/FASelector_SRC/Type/.JPG.py
onsoim/FuzzBuilderEx
d0e8bada27677a0f676e92dc48aaa764ba679508
[ "Apache-2.0" ]
4
2021-03-24T00:10:59.000Z
2022-03-28T13:41:28.000Z
source/script/FASelector_SRC/Type/.JPG.py
onsoim/FuzzBuilderEx
d0e8bada27677a0f676e92dc48aaa764ba679508
[ "Apache-2.0" ]
2
2021-04-05T06:22:20.000Z
2021-10-01T21:07:18.000Z
#-*- coding:utf-8 -*- import os import re class folder(): def __init__(self,path): self.path = path if path[-1] != '/': self.path += '/' self.filelist = [] self.get_filelist() def get_filelist(self): tmp = os.listdir(self.path) for test in tmp: test = self.path + test if os.path.isfile(test): self.filelist.append(test) print 'There are %d files in "%s" folder.' %(len(self.filelist), self.path) class file(): def __init__(self,filename): self.filename = filename with open(filename,'r') as f: self.raw_data = f.read() self.hex_data = self.raw_data.encode('hex') self.SOIMARKER = self.get_OIMARKER('\xff\xd8') self.EOIMARKER = self.get_OIMARKER('\xff\xd9') def check_OI(self): len_SOI = len(re.findall('\xff\xd8',self.raw_data)) len_EOI = len(re.findall('\xff\xd9',self.raw_data)) print "=" * 0x34 print "'%s' has %d SOIMARKER & %d EOIMARKER" %(self.filename, len_SOI, len_EOI) return len_SOI def get_OIMARKER(self,sig): markers = [] OIMARKER = re.finditer(sig,self.raw_data) for i in OIMARKER: markers.append(i.start()) return markers if __name__ == "__main__": import sys #path = './pictures/' #folder = folder(path) folder = folder(sys.argv[1]) path, filelist = folder.path, folder.filelist markers = ['ffc','ffd','ffe','fff'] JPG = [] if not os.path.isdir('output'): os.makedirs('output/') for filename in filelist: pic = file(filename) output = filename.split('/')[-1].split('.')[0] if pic.check_OI(): with open('output/%s.txt' % output,'w') as txt: fd = pic.SOIMARKER[0] txt.write("%s => %s\n" %(pic.raw_data[fd:fd+2].encode('hex'), hex(fd))) start, end = fd * 2 + 4, fd * 2 + 8 while pic.hex_data[start:end-1] in markers: marker = pic.hex_data[start:end] txt.write("%s => %s\n" %(marker, hex(start/2))) start, end = start + 4, end + 4 index = int(pic.hex_data[start:end],16) start, end = start + index * 2, end + index * 2 if marker == "ffda": marker = pic.EOIMARKER[0] if marker < end: marker = pic.EOIMARKER[1] txt.write("%s => %s\n" %('ffd9', hex(marker))) print "'%s' is JPG" % filename JPG.append(filename) with open('output/%s.jpg' % output, 'w') as restore: restore.write(pic.raw_data[fd:marker]) else: print "'%s' is JPG but broken" else: print "'%s' is not JPG" % filename print "\n",JPG
27.837209
81
0.621554
370
2,394
3.916216
0.264865
0.033816
0.037957
0.020704
0.060041
0
0
0
0
0
0
0.015003
0.192565
2,394
85
82
28.164706
0.734609
0.02548
0
0
0
0
0.112876
0
0
0
0.001717
0
0
0
null
null
0
0.044118
null
null
0.102941
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
1
0
0
0
0
0
0
0
0
1
979f6be94ead98ea08a3e58188d707e4861320f7
3,656
py
Python
Constants.py
unmonk/Project-Infinity
63c22fcf4086adf868967cb172434e3ceba4bac5
[ "CC0-1.0" ]
null
null
null
Constants.py
unmonk/Project-Infinity
63c22fcf4086adf868967cb172434e3ceba4bac5
[ "CC0-1.0" ]
null
null
null
Constants.py
unmonk/Project-Infinity
63c22fcf4086adf868967cb172434e3ceba4bac5
[ "CC0-1.0" ]
null
null
null
__author__ = 'Scott' import os import pygame SCREEN_WIDTH = 1280 SCREEN_HEIGHT = 720 GAME_TITLE = "Project Infinity" MAP_COLLISION_LAYER = 2 MAP_DEATH_LAYER = 3 MAP_BACKGROUND_LAYER = 0 MAP_FORGROUND_LAYER = 1 MAP_ENDOFLEVEL_LAYER = 5 MAP_ITEM_LAYER = 4 BACKGROUND_COLOR = (20, 20, 20) screen = pygame.display.set_mode([SCREEN_WIDTH, SCREEN_HEIGHT]) LAST_LEVEL = 1 #Main Character Licensed to Scott Weaver #Platform tiles CC0 #background music CC0 #Jump Sounds Credit: dklon pygame.mixer.init() jump1 = pygame.mixer.Sound('data/audio/jump_01.wav') jump2 = pygame.mixer.Sound('data/audio/jump_03.wav') heart = pygame.mixer.Sound('data/audio/upshort.wav') PLAYERPATH = 'data/ninja/' IMAGE_PATH =\ { 'playerIdle': [], 'playerDie': [], 'playerFlip': [], 'playerJump': [], 'playerRun': [], 'playerSlide': [], 'playerStun': [], 'playerWallGrab': [], 'playerProjectile': [], 'playerLives': [] } for i in range(1, 6): IMAGE_PATH['playerIdle'].append(os.path.join(PLAYERPATH, "idle_0%d.png" %i)) for i in range(1, 5): IMAGE_PATH['playerDie'].append(os.path.join(PLAYERPATH, "die_0%d.png" %i)) for i in range(1, 7): IMAGE_PATH['playerFlip'].append(os.path.join(PLAYERPATH, "flip_0%d.png" %i)) for i in range(1, 8): IMAGE_PATH['playerRun'].append(os.path.join(PLAYERPATH, "run_0%d.png" %i)) for i in range(1, 4): IMAGE_PATH['playerStun'].append(os.path.join(PLAYERPATH, "stunned_0%d.png" %i)) IMAGE_PATH['playerJump'].append(os.path.join(PLAYERPATH, "jumpDown.png")) IMAGE_PATH['playerJump'].append(os.path.join(PLAYERPATH, "jumpUp.png")) IMAGE_PATH['playerWallGrab'].append(os.path.join(PLAYERPATH, "wallGrab.png")) IMAGE_PATH['playerSlide'].append(os.path.join(PLAYERPATH, "slideDuck.png")) IMAGE_PATH['playerProjectile'].append(os.path.join(PLAYERPATH, "knife.png")) IMAGE_PATH['playerLives'].append(os.path.join(PLAYERPATH, "heart.png")) DATA = \ { 'playerIdle': [], 'playerDie': [], 'playerFlip': [], 'playerJump': [], 'playerRun': [], 'playerSlide':[], 'playerStun':[], 'playerWallGrab':[], 'playerProjectile':[], 'playerLives': [] } def load_images(): for i in range(0, 5): DATA['playerIdle'].append(pygame.image.load(IMAGE_PATH['playerIdle'][i]).convert_alpha()) for i in range(0, 4): DATA['playerDie'].append(pygame.image.load(IMAGE_PATH['playerDie'][i]).convert_alpha()) for i in range(0, 6): DATA['playerFlip'].append(pygame.image.load(IMAGE_PATH['playerFlip'][i]).convert_alpha()) for i in range(0, 7): DATA['playerRun'].append(pygame.image.load(IMAGE_PATH['playerRun'][i]).convert_alpha()) for i in range(0, 3): DATA['playerStun'].append(pygame.image.load(IMAGE_PATH['playerStun'][i]).convert_alpha()) DATA['playerJump'].append(pygame.image.load(IMAGE_PATH['playerJump'][0]).convert_alpha()) DATA['playerJump'].append(pygame.image.load(IMAGE_PATH['playerJump'][1]).convert_alpha()) DATA['playerWallGrab'].append(pygame.image.load(IMAGE_PATH['playerWallGrab'][0]).convert_alpha()) DATA['playerSlide'].append(pygame.image.load(IMAGE_PATH['playerSlide'][0]).convert_alpha()) DATA['playerProjectile'].append(pygame.image.load(IMAGE_PATH['playerProjectile'][0]).convert_alpha()) DATA['playerProjectile'].append(pygame.transform.flip(DATA['playerProjectile'][0], True, False)) DATA['playerLives'].append(pygame.image.load(IMAGE_PATH['playerLives'][0]).convert_alpha()) print "DEBUG IMAGES:", DATA def get_image(name, frame): return DATA[name][frame]
34.490566
105
0.671772
472
3,656
5.061441
0.230932
0.086647
0.055253
0.073671
0.545416
0.426957
0.294684
0.257011
0.17748
0.147342
0
0.019212
0.145788
3,656
106
106
34.490566
0.745757
0.027899
0
0.240964
0
0
0.239088
0.018586
0
0
0
0
0
0
null
null
0
0.024096
null
null
0.012048
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
1
0
0
0
0
0
0
0
0
1
97a1ff60f08e5d9b17054c1f2b8239c0c712ac7b
17,655
py
Python
vol3/vol3-python-examples/lib/aifh/som.py
Sun-Joong/aifh
1b6363d26f54b77348020ce88ced0670568ed736
[ "Apache-2.0" ]
777
2015-01-17T22:48:26.000Z
2022-03-31T01:10:07.000Z
vol3/vol3-python-examples/lib/aifh/som.py
Sun-Joong/aifh
1b6363d26f54b77348020ce88ced0670568ed736
[ "Apache-2.0" ]
17
2015-01-02T14:41:24.000Z
2017-09-02T02:57:09.000Z
vol3/vol3-python-examples/lib/aifh/som.py
Sun-Joong/aifh
1b6363d26f54b77348020ce88ced0670568ed736
[ "Apache-2.0" ]
445
2015-01-26T17:01:49.000Z
2022-03-24T07:16:58.000Z
#!/usr/bin/env python """ Artificial Intelligence for Humans Volume 3: Deep Learning and Neural Networks Python Version http://www.aifh.org http://www.jeffheaton.com Code repository: https://github.com/jeffheaton/aifh Copyright 2015 by Jeff Heaton 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. For more information on Heaton Research copyrights, licenses and trademarks visit: http://www.heatonresearch.com/copyright """ import scipy.spatial import numpy as np import scipy as sp import sys class SelfOrganizingMap: """ The weights of the output neurons base on the input from the input neurons. """ def __init__(self, input_count, output_count): """ The constructor. :param input_count: Number of input neurons :param output_count: Number of output neurons :return: """ self.input_count = input_count self.output_count = output_count self.weights = np.zeros([self.output_count, self.input_count]) self.distance = sp.spatial.distance.euclidean def calculate_error(self, data): bmu = BestMatchingUnit(self) bmu.reset() # Determine the BMU for each training element. for input in data: bmu.calculate_bmu(input) # update the error return bmu.worst_distance / 100.0 def classify(self, input): if len(input) > self.input_count: raise Exception("Can't classify SOM with input size of {} " "with input data of count {}".format(self.input_count, len(input))) min_dist = sys.maxfloat result = -1 for i in range(self.output_count): dist = self.distance.calculate(input, self.weights[i]) if dist < min_dist: min_dist = dist result = i return result def reset(self): self.weights = (np.random.rand(self.weights.shape[0], self.weights.shape[1]) * 2.0) - 1 class BestMatchingUnit: """ The "Best Matching Unit" or BMU is a very important concept in the training for a SOM. The BMU is the output neuron that has weight connections to the input neurons that most closely match the current input vector. This neuron (and its "neighborhood") are the neurons that will receive training. This class also tracks the worst distance (of all BMU's). This gives some indication of how well the network is trained, and thus becomes the "error" of the entire network. """ def __init__(self, som): """ Construct a BestMatchingUnit class. The training class must be provided. :param som: The SOM to evaluate. """ # The owner of this class. self.som = som # What is the worst BMU distance so far, this becomes the error for the # entire SOM. self.worst_distance = 0 def calculate_bmu(self, input): """ Calculate the best matching unit (BMU). This is the output neuron that has the lowest Euclidean distance to the input vector. :param input: The input vector. :return: The output neuron number that is the BMU. """ result = 0 if len(input) > self.som.input_count: raise Exception( "Can't train SOM with input size of {} with input data of count {}.".format(self.som.input_count, len(input))) # Track the lowest distance so far. lowest_distance = float("inf") for i in range(self.som.output_count): distance = self.calculate_euclidean_distance(self.som.weights, input, i) # Track the lowest distance, this is the BMU. if distance < lowest_distance: lowest_distance = distance result = i # Track the worst distance, this is the error for the entire network. if lowest_distance > self.worst_distance: self.worst_distance = lowest_distance return result def calculate_euclidean_distance(self, matrix, input, output_neuron): """ Calculate the Euclidean distance for the specified output neuron and the input vector. This is the square root of the squares of the differences between the weight and input vectors. :param matrix: The matrix to get the weights from. :param input: The input vector. :param outputNeuron: The neuron we are calculating the distance for. :return: The Euclidean distance. """ result = 0 # Loop over all input data. diff = input - matrix[output_neuron] return np.sqrt(sum(diff*diff)) class BasicTrainSOM: """ This class implements competitive training, which would be used in a winner-take-all neural network, such as the self organizing map (SOM). This is an unsupervised training method, no ideal data is needed on the training set. If ideal data is provided, it will be ignored. Training is done by looping over all of the training elements and calculating a "best matching unit" (BMU). This BMU output neuron is then adjusted to better "learn" this pattern. Additionally, this training may be applied to other "nearby" output neurons. The degree to which nearby neurons are update is defined by the neighborhood function. A neighborhood function is required to determine the degree to which neighboring neurons (to the winning neuron) are updated by each training iteration. Because this is unsupervised training, calculating an error to measure progress by is difficult. The error is defined to be the "worst", or longest, Euclidean distance of any of the BMU's. This value should be minimized, as learning progresses. Because only the BMU neuron and its close neighbors are updated, you can end up with some output neurons that learn nothing. By default these neurons are not forced to win patterns that are not represented well. This spreads out the workload among all output neurons. This feature is not used by default, but can be enabled by setting the "forceWinner" property. """ def __init__(self, network, learning_rate, training, neighborhood): # The neighborhood function to use to determine to what degree a neuron # should be "trained". self.neighborhood = neighborhood # The learning rate. To what degree should changes be applied. self.learning_rate = learning_rate # The network being trained. self.network = network # How many neurons in the input layer. self.input_neuron_count = network.input_count # How many neurons in the output layer. self.output_neuron_count = network.output_count # Utility class used to determine the BMU. self.bmu_util = BestMatchingUnit(network) # Correction matrix. self.correction_matrix = np.zeros([network.output_count, network.input_count]) # True is a winner is to be forced, see class description, or forceWinners # method. By default, this is true. self.force_winner = False # When used with autodecay, this is the starting learning rate. self.start_rate = 0 # When used with autodecay, this is the ending learning rate. self.end_rate = 0 # When used with autodecay, this is the starting radius. self.start_radius = 0 # When used with autodecay, this is the ending radius. self.end_radius = 0 # This is the current autodecay learning rate. self.auto_decay_rate = 0 # This is the current autodecay radius. self.auto_decay_radius = 0 # The current radius. self.radius = 0 # Training data. self.training = training def _apply_correction(self): """ Loop over the synapses to be trained and apply any corrections that were determined by this training iteration. """ np.copyto(self.network.weights, self.correction_matrix) def auto_decay(self): """ Should be called each iteration if autodecay is desired. """ if self.radius > self.end_radius: self.radius += self.auto_decay_radius if self.learning_rate > self.end_rate: self.learning_rate += self.auto_decay_rate self.neighborhood.radius = self.radius def copy_input_pattern(self, matrix, output_neuron, input): """ Copy the specified input pattern to the weight matrix. This causes an output neuron to learn this pattern "exactly". This is useful when a winner is to be forced. :param matrix: The matrix that is the target of the copy. :param output_neuron: The output neuron to set. :param input: The input pattern to copy. """ matrix[output_neuron, :] = input def decay(self, decay_rate, decay_radius): """ Decay the learning rate and radius by the specified amount. :param decay_rate: The percent to decay the learning rate by. :param decay_radius: The percent to decay the radius by. """ self.radius *= (1.0 - decay_radius) self.learning_rate *= (1.0 - decay_rate) self.neighborhood.radius = self.radius def _determine_new_weight(self, weight, input, currentNeuron, bmu): """ Determine the weight adjustment for a single neuron during a training iteration. :param weight: The starting weight. :param input: The input to this neuron. :param currentNeuron: The neuron who's weight is being updated. :param bmu: The neuron that "won", the best matching unit. :return: The new weight value. """ return weight \ + (self.neighborhood.fn(currentNeuron, bmu) \ * self.learning_rate * (input - weight)) def _force_winners(self, matrix, won, least_represented): """ Force any neurons that did not win to off-load patterns from overworked neurons. :param matrix: An array that specifies how many times each output neuron has "won". :param won: The training pattern that is the least represented by this neural network. :param least_represented: The synapse to modify. :return: True if a winner was forced. """ max_activation = float("-inf") max_activation_neuron = -1 output = self.compute(self.network, self.least_represented) # Loop over all of the output neurons. Consider any neurons that were # not the BMU (winner) for any pattern. Track which of these # non-winning neurons had the highest activation. for output_neuron in range(len(won)): # Only consider neurons that did not "win". if won[output_neuron] == 0: if (max_activation_neuron == -1) \ or (output[output_neuron] > max_activation): max_activation = output[output_neuron] max_activation_neuron = output_neuron # If a neurons was found that did not activate for any patterns, then # force it to "win" the least represented pattern. if max_activation_neuron != -1: self.copy_input_pattern(matrix, max_activation_neuron, least_represented) return True else: return False def iteration(self): """ Perform one training iteration. """ # Reset the BMU and begin this iteration. self.bmu_util.reset() won = [0] * self.output_neuron_count least_represented_activation = float("inf") least_represented = None # Reset the correction matrix for this synapse and iteration. self.correctionMatrix.clear() # Determine the BMU for each training element. for input in self.training: bmu = self.bmu_util.calculate_bmu(input) won[bmu] += 1 # If we are to force a winner each time, then track how many # times each output neuron becomes the BMU (winner). if self.force_winner: # Get the "output" from the network for this pattern. This # gets the activation level of the BMU. output = self.compute(self.network, input) # Track which training entry produces the least BMU. This # pattern is the least represented by the network. if output[bmu] < least_represented_activation: least_represented_activation = output[bmu] least_represented = input.getInput() self.train(bmu, self.network.getWeights(), input.getInput()) if self.force_winner: # force any non-winning neurons to share the burden somewhat if not self.force_winners(self.network.weights, won, least_represented): self.apply_correction() else: self.apply_correction() def set_auto_decay(self, planned_iterations, start_rate, end_rate, start_radius, end_radius): """ Setup autodecay. This will decrease the radius and learning rate from the start values to the end values. :param planned_iterations: The number of iterations that are planned. This allows the decay rate to be determined. :param start_rate: The starting learning rate. :param end_rate: The ending learning rate. :param start_radius: The starting radius. :param end_radius: The ending radius. """ self.start_rate = start_rate self.end_rate = end_rate self.start_radius = start_radius self.end_radius = end_radius self.auto_decay_radius = (end_radius - start_radius) / planned_iterations self.auto_decay_rate = (end_rate - start_rate) / planned_iterations self.set_params(self.start_rate, self.start_radius) def set_params(self, rate, radius): """ Set the learning rate and radius. :param rate: The new learning rate. :param radius: :return: The new radius. """ self.radius = radius self.learning_rate = rate self.neighborhood.radius = radius def get_status(self): """ :return: A string display of the status. """ result = "Rate=" result += str(self.learning_rate) result += ", Radius=" result += str(self.radius) return result def _train(self, bmu, matrix, input): """ Train for the specified synapse and BMU. :param bmu: The best matching unit for this input. :param matrix: The synapse to train. :param input: The input to train for. :return: """ # adjust the weight for the BMU and its neighborhood for output_neuron in range(self.output_neuron_count): self._train_pattern(matrix, input, output_neuron, bmu) def _train_pattern(self, matrix, input, current, bmu): """ Train for the specified pattern. :param matrix: The synapse to train. :param input: The input pattern to train for. :param current: The current output neuron being trained. :param bmu: The best matching unit, or winning output neuron. """ for input_neuron in range(self.input_neuron_count): current_weight = matrix[current][input_neuron] input_value = input[input_neuron] new_weight = self._determine_new_weight(current_weight, input_value, current, bmu) self.correction_matrix[current][input_neuron] = new_weight def train_single_pattern(self, pattern): """ Train the specified pattern. Find a winning neuron and adjust all neurons according to the neighborhood function. :param pattern: The pattern to train. """ bmu = self.bmu_util.calculate_bmu(pattern) self._train(bmu, self.network.weights, pattern) self._apply_correction() def compute(self, som, input): """ Calculate the output of the SOM, for each output neuron. Typically, you will use the classify method instead of calling this method. :param som: The input pattern. :param input: The output activation of each output neuron. :return: """ result = np.zeros(som.output_count) for i in range(som.output_count): optr = som.weights[i] matrix_a = np.zeros([input.length,1]) for j in range(len(input)): matrix_a[0][j] = input[j] matrix_b = np.zeros(1,input.length) for j in range(len(optr)): matrix_b[0][j] = optr[j] result[i] = np.dot(matrix_a, matrix_b) return result
37.886266
114
0.63625
2,265
17,655
4.86181
0.170861
0.030512
0.008173
0.009807
0.162368
0.088086
0.048039
0.048039
0.03587
0.025608
0
0.003458
0.295667
17,655
465
115
37.967742
0.882107
0.470292
0
0.095238
0
0
0.019378
0
0
0
0
0
0
1
0.130952
false
0
0.02381
0
0.22619
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
97a29197dc50e799d9651b87306ebbcdd023348a
458
py
Python
loader.py
AmaRocket/TMDBMovieBotTelegram
07d248da0ee5c20e788612814f964917748474ba
[ "MIT" ]
null
null
null
loader.py
AmaRocket/TMDBMovieBotTelegram
07d248da0ee5c20e788612814f964917748474ba
[ "MIT" ]
null
null
null
loader.py
AmaRocket/TMDBMovieBotTelegram
07d248da0ee5c20e788612814f964917748474ba
[ "MIT" ]
null
null
null
import logging import asyncio from aiogram import Bot, Dispatcher from aiogram.contrib.fsm_storage.memory import MemoryStorage import config loop = asyncio.get_event_loop() bot = Bot(token=config.token, parse_mode='HTML') storage = MemoryStorage() dp = Dispatcher(bot, storage=storage) logging.basicConfig(format=u'%(filename)s [LINE:%(lineno)d] #%(levelname)-8s [%(asctime)s] %(message)s', level=logging.INFO, )
26.941176
105
0.69869
57
458
5.54386
0.614035
0.06962
0
0
0
0
0
0
0
0
0
0.002653
0.176856
458
16
106
28.625
0.835544
0
0
0
0
0.083333
0.170306
0
0
0
0
0
0
1
0
false
0
0.416667
0
0.416667
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
1
0
0
0
0
1
97a4368e398e0b9f09d0d9196d816ae5a12f9c17
4,729
py
Python
animator/entity/basic_shape.py
sherlockdoyle/Animator
5c1bec50e7e120db36a8a333fa7ddcdaf10dda3b
[ "MIT" ]
null
null
null
animator/entity/basic_shape.py
sherlockdoyle/Animator
5c1bec50e7e120db36a8a333fa7ddcdaf10dda3b
[ "MIT" ]
null
null
null
animator/entity/basic_shape.py
sherlockdoyle/Animator
5c1bec50e7e120db36a8a333fa7ddcdaf10dda3b
[ "MIT" ]
null
null
null
import math from animator.entity import Entity from animator.constant import * __all__ = ["Circle", "Ellipse", "Rect", "Square", "Poly"] class Circle(Entity): """ Draws a circle on the scene. :param r: The radius of the circle. Default is 0 """ def __init__(self, r=UNIT, **kwargs): super(Circle, self).__init__(**kwargs) self.r = r def on_draw(self): self.scene.ctx.arc(0, 0, self.r, 0, TWO_PI) # TODO: How to handle transformation? def _get_bounding_box(self, transformed=True): r = self.r return super()._get_bounding_box() if transformed else (r, r, r, r) def _get_length(self): return TWO_PI * self.r class Ellipse(Entity): def __init__(self, rx=UNIT, ry=None, **kwargs): super(Ellipse, self).__init__(**kwargs) if ry is None: ry = rx self.rx, self.ry = rx, ry def on_draw(self): self.scene.ctx.save() self.scene.ctx.scale(1, self.ry / self.rx) self.scene.ctx.arc(0, 0, self.rx, 0, TWO_PI) self.scene.ctx.restore() # TODO: How to handle transformation? def _get_bounding_box(self, transformed=True): rx, ry = self.rx, self.ry return super()._get_bounding_box() if transformed else (rx, ry, rx, ry) def _get_length(self): a, b = self.rx, self.ry h = 3 * ((a - b) / (a + b)) ** 2 return PI * (a + b) * (1 + h / (10 + math.sqrt(4 - h))) class Rect(Entity): def __init__(self, w=2 * UNIT, h=None, **kwargs): super(Rect, self).__init__(**kwargs) if h is None: h = w self.w = w self.h = h def on_draw(self): self.scene.ctx.rectangle(-self.w / 2, -self.h / 2, self.w, self.h) # TODO: How to handle transformation? def _get_bounding_box(self, transformed=True): w, h = self.w / 2, self.h / 2 return super()._get_bounding_box() if transformed else (w, h, w, h) def _get_length(self): return 2 * (self.w + self.h) class Square(Rect): def __init__(self, s=2 * UNIT, **kwargs): super(Square, self).__init__(s, s, **kwargs) class Poly(Entity): def __init__(self, n=3, r=UNIT, inradius=False, **kwargs): super(Poly, self).__init__(**kwargs) if inradius: r /= math.cos(PI / n) self.n, self.r = n, r self.points = [] max_x, max_y = 0, 0 dt = -PI * (1 / n + 0.5 - (n % 2) / n) for i in range(n): x, y = math.cos(TWO_PI / n * i + dt) * r, math.sin(TWO_PI / n * i + dt) * r max_x, max_y = max(max_x, x), max(max_y, y) self.points.append([x, y]) self.mx, self.my = max_x, max_y def on_draw(self): self.scene.ctx.move_to(*self.points[0]) for i in range(1, self.n): self.scene.ctx.line_to(*self.points[i]) self.scene.ctx.close_path() # TODO: How to handle transformation? def _get_bounding_box(self, transformed=True): return super()._get_bounding_box() if transformed else (self.mx, self.my, self.mx, self.my) def _get_length(self): return 2 * self.n * self.r * math.sin(PI / self.n) # TODO: Implement Star? # class Star(Entity): # def __init__(self, n=5, outradius=UNIT, inradius=None, **kwargs): # super(Star, self).__init__(**kwargs) # if inradius is None: # ct = math.cos(HALF_PI / n * ((n - 1) // 2)) # inradius = outradius * (2 * ct - 1 / ct) # self.n, self.out_r, self.in_r = n, outradius, inradius # self.points = [] # max_x, max_y = 0, 0 # dt = -PI * (1 / n + 0.5 - (n % 2) / n) # for i in range(n): # x, y = math.cos(TWO_PI / n * i + dt) * outradius, math.sin(TWO_PI / n * i + dt) * outradius # max_x, max_y = max(max_x, x), max(max_y, y) # self.points.append([x, y]) # x, y = math.cos(TWO_PI / n * (i + .5) + dt) * inradius, math.sin(TWO_PI / n * (i + .5) + dt) * inradius # self.points.append([x, y]) # self.mx, self.my = max_x, max_y # # def on_draw(self): # self.scene.ctx.move_to(*self.points[0]) # for i in range(1, 2 * self.n): # self.scene.ctx.line_to(*self.points[i]) # self.scene.ctx.close_path() # # # TODO: How to handle transformation? # def _get_bounding_box(self, transformed=True): # return super()._get_bounding_box() if transformed else (self.mx, self.my, self.mx, self.my) # # def _get_length(self): # return 2 * self.n * math.sqrt(self.in_r ** 2 + self.out_r ** 2 - # 2 * self.in_r * self.out_r * math.cos(PI / self.n))
33.778571
117
0.550011
728
4,729
3.387363
0.130495
0.043796
0.058394
0.019465
0.609489
0.560016
0.539335
0.461071
0.403487
0.403487
0
0.015292
0.294777
4,729
139
118
34.021583
0.724138
0.356524
0
0.164384
0
0
0.009051
0
0
0
0
0.007194
0
1
0.232877
false
0
0.041096
0.054795
0.452055
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
1
0
0
0
0
0
0
0
1
97a57543f9dc26b5f9e4368297bf82071ccf16c7
1,855
py
Python
src/GUI/custom_widgets.py
QWERTSKIHACK/peniot
8b5c5c4dddb5adf53977c3e2e99e645a086f1f0b
[ "MIT" ]
143
2019-12-31T08:12:36.000Z
2022-03-31T15:59:51.000Z
src/GUI/custom_widgets.py
QWERTSKIHACK/peniot
8b5c5c4dddb5adf53977c3e2e99e645a086f1f0b
[ "MIT" ]
5
2020-01-28T15:47:23.000Z
2022-02-23T11:18:55.000Z
src/GUI/custom_widgets.py
QWERTSKIHACK/peniot
8b5c5c4dddb5adf53977c3e2e99e645a086f1f0b
[ "MIT" ]
39
2019-12-30T22:19:38.000Z
2022-03-17T10:24:37.000Z
from Tkinter import * from hard_coded_texts import get_project_name class Header(Frame): """ Generic header template class which is used for construction of different screens """ def __init__(self, parent_window): Frame.__init__(self, parent_window) # Configure the window self.configure(background="white") # Create the header header = Label(self, text=get_project_name(), width=55, font=("Arial", 20), height=5) header.grid() header.configure(background="white") class CustomButton(Button): """ Generic button template to use them throughout the screens """ def __init__(self, parent_window, text, _function, row, columnspan=None, sticky=None, column=None, height=2, foreground="black"): Button.__init__(self, parent_window, command=_function, text=text, font=("Arial", 15), borderwidth=0, height=height, highlightthickness=0, background="white", foreground=foreground) self.grid(row=row, columnspan=columnspan, sticky=sticky, column=column) class CustomLabel(Label): """ Generic label template to use them throughout the screens """ def __init__(self, parent_window, text, row, column, rowspan=None, columnspan=None, sticky=None): Label.__init__(self, parent_window, text=text, font=("Arial", 15)) self.grid(row=row, column=column, rowspan=rowspan, columnspan=columnspan, sticky=sticky) class CustomRadiobutton(Radiobutton): """ Generic radio button template to use them throughout the screens """ def __init__(self, parent_window, text, row, column, sticky, variable, value): Radiobutton.__init__(self, parent_window, text=text, font=("Arial", 13), variable=variable, value=value) self.grid(row=row, column=column, sticky=sticky)
37.1
112
0.686253
222
1,855
5.518018
0.315315
0.052245
0.091429
0.130612
0.325714
0.308571
0.241633
0.241633
0.181224
0.181224
0
0.009447
0.201078
1,855
49
113
37.857143
0.817139
0.163342
0
0
0
0
0.026846
0
0
0
0
0
0
1
0.173913
false
0
0.086957
0
0.434783
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
97a757d0e58b59160fb7713ada622222e925c521
4,479
py
Python
Code/search.py
Keyology/cs-1.3-2020
7b6f02c76dc16f1abafc613ebe6088d51b36b3be
[ "MIT" ]
null
null
null
Code/search.py
Keyology/cs-1.3-2020
7b6f02c76dc16f1abafc613ebe6088d51b36b3be
[ "MIT" ]
4
2020-02-17T23:27:06.000Z
2020-03-10T20:21:22.000Z
Code/search.py
Keyology/cs-1.3-2020
7b6f02c76dc16f1abafc613ebe6088d51b36b3be
[ "MIT" ]
null
null
null
#!python def linear_search(array, item): """return the first index of item in array or None if item is not found""" # implement linear_search_iterative and linear_search_recursive below, then # change this to call your implementation to verify it passes all tests # return linear_search_iterative(array, item) return linear_search_recursive(array, item) def linear_search_iterative(array, item): # loop over all array values until item is found for index, value in enumerate(array): if item == value: return index # found return None # not found def linear_search_recursive(array, item, index=0): # TODO: implement linear search recursively here ''' Time complexity is O(n) ''' # check if item is in array if array[index] == item: return index # if item is not in array retun NONE if index == len(array) -1 and array[index] != item: return None index += 1 return linear_search_recursive(array, item, index) # save the index to a variable # create a condition to check if array[index] == item # if yes return index #otherwise call the function again and update the index # create another condition to check if the index is at the last item in the list # once implemented, change linear_search to call linear_search_recursive # to verify that your recursive implementation passes all tests def binary_search(array, item): """return the index of item in sorted array or None if item is not found""" # # implement binary_search_iterative and binary_search_recursive below, then # # change this to call your implementation to verify it passes all tests # return binary_search_iterative(array, item) return binary_search_recursive(array, item) def binary_search_iterative(array, item): # TODO: implement binary search iteratively here ''' Time complexity is O(log n) ''' # Sort the array array = sorted(array) # set the left value to the first index of the list which is zero left = 0 # set the right to the last index in the array right = len(array) - 1 while left <= right: # get the middle index of the array middle_value = (left + right) // 2 # if the middle value is less than item than move to the left index to the right once if array[middle_value] < item: left = middle_value + 1 # if the item is greater than the middle index move the right to the left once if array[middle_value] > item: right = middle_value - 1 # if the middle value == the target value return the middle value index if array[middle_value] == item: return middle_value # if the item is not in the array return NONE return None # reasign array to sorted array # only sort once # create a variable named median and set it to int(len(array) / 2) # once implemented, change binary_search to call binary_search_iterative # to verify that your iterative implementation passes all tests def binary_search_recursive(array, item, left=None, right=None): # TODO: implement binary search recursively here ''' Time complexity is O(log n) ''' # Sort the array array = sorted(array) # get the middle index of the array if left == None and right == None: left = 0 right = len(array) -1 middle_value = (left + right) // 2 print('MIDDLE VALUE', middle_value) if left > right: return None # if the middle value == the target value return the middle value index if array[middle_value] == item: print('---MIDDLE Value ---',middle_value) return middle_value # if the middle value is less than item than move to the left index to the right once if array[middle_value] < item: left = middle_value + 1 print('---LEFT----', left) return binary_search_recursive(array, item, left, right) # if the item is greater than the middle index move the right to the left once if array[middle_value] > item: right = middle_value - 1 print('----RIGHT 1----', right) return binary_search_recursive(array, item, left, right) # once implemented, change binary_search to call binary_search_recursive # to verify that your recursive implementation passes all tests
31.542254
95
0.663764
636
4,479
4.584906
0.150943
0.090535
0.048011
0.057613
0.644033
0.540123
0.481824
0.424554
0.39369
0.336077
0
0.00459
0.270373
4,479
141
96
31.765957
0.887699
0.523778
0
0.571429
0
0
0.027683
0
0
0
0
0.007092
0
1
0.122449
false
0
0
0
0.387755
0.081633
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
97aa46050ee4e69349797e69e7c1131f9730f6f8
5,155
py
Python
panoptes_aggregation/tests/reducer_tests/test_survey_reducer.py
CKrawczyk/python-reducers-for-caesar
9c5d9e072906d3fde2497fa61a66e4c8c0113ec2
[ "Apache-2.0" ]
1
2018-11-27T16:43:37.000Z
2018-11-27T16:43:37.000Z
panoptes_aggregation/tests/reducer_tests/test_survey_reducer.py
CKrawczyk/python-reducers-for-caesar
9c5d9e072906d3fde2497fa61a66e4c8c0113ec2
[ "Apache-2.0" ]
2
2017-07-27T09:05:03.000Z
2019-04-03T20:28:31.000Z
panoptes_aggregation/tests/reducer_tests/test_survey_reducer.py
CKrawczyk/python-reducers-for-caesar
9c5d9e072906d3fde2497fa61a66e4c8c0113ec2
[ "Apache-2.0" ]
2
2017-07-26T17:30:17.000Z
2017-07-27T09:14:51.000Z
import unittest from collections import Counter import copy import flask import json from panoptes_aggregation.reducers.survey_reducer import process_data, survey_reducer from panoptes_aggregation.reducers.test_utils import extract_in_data extracted_data = [ {'answers_howmanyanimalsdoyousee': {'1': 1.0}, 'answers_whatistheanimalsdoing': {'grooming': 1.0}, 'choice': 'raccoon'}, {'answers_howmanyanimalsdoyousee': {'1': 1.0}, 'answers_whatistheanimalsdoing': {'standing': 1.0}, 'choice': 'raccoon'}, {'answers_howmanyanimalsdoyousee': {'1': 1.0}, 'answers_whatistheanimalsdoing': {'standing': 1.0}, 'answers_clickwowifthisasanespeciallyawesomephoto': {'wow': 1.0}, 'choice': 'raccoon'}, {'answers_howmanyanimalsdoyousee': {'1': 1.0}, 'answers_whatistheanimalsdoing': {'standing': 1.0}, 'choice': 'raccoon'}, {'answers_howmanyanimalsdoyousee': {'1': 1.0}, 'answers_whatistheanimalsdoing': {'interacting': 1.0, 'grooming': 1.0}, 'answers_clickwowifthisasanespeciallyawesomephoto': {'wow': 1.0}, 'choice': 'blackbear'}, {'answers_howmanyanimalsdoyousee': {'1': 1.0}, 'answers_whatistheanimalsdoing': {'standing': 1.0}, 'choice': 'blackbear'}, {'answers_howmanyanimalsdoyousee': {'1': 1.0}, 'answers_whatistheanimalsdoing': {'standing': 1.0}, 'answers_clickwowifthisasanespeciallyawesomephoto': {'wow': 1.0}, 'choice': 'blackbear'}, {'answers_howmanyanimalsdoyousee': {'1': 1.0}, 'answers_whatistheanimalsdoing': {'grooming': 1.0}, 'choice': 'blackbear'} ] processed_data = { 'blackbear': [ { 'answers_clickwowifthisasanespeciallyawesomephoto': Counter({'wow': 1}), 'answers_howmanyanimalsdoyousee': Counter({'1': 1}), 'answers_whatistheanimalsdoing': Counter({'interacting': 1, 'grooming': 1}) }, { 'answers_howmanyanimalsdoyousee': Counter({'1': 1}), 'answers_whatistheanimalsdoing': Counter({'standing': 1}) }, { 'answers_clickwowifthisasanespeciallyawesomephoto': Counter({'wow': 1}), 'answers_howmanyanimalsdoyousee': Counter({'1': 1}), 'answers_whatistheanimalsdoing': Counter({'standing': 1}) }, { 'answers_howmanyanimalsdoyousee': Counter({'1': 1}), 'answers_whatistheanimalsdoing': Counter({'grooming': 1}) } ], 'raccoon': [ { 'answers_howmanyanimalsdoyousee': Counter({'1': 1}), 'answers_whatistheanimalsdoing': Counter({'grooming': 1}) }, { 'answers_howmanyanimalsdoyousee': Counter({'1': 1}), 'answers_whatistheanimalsdoing': Counter({'standing': 1}) }, { 'answers_clickwowifthisasanespeciallyawesomephoto': Counter({'wow': 1}), 'answers_howmanyanimalsdoyousee': Counter({'1': 1}), 'answers_whatistheanimalsdoing': Counter({'standing': 1}) }, { 'answers_howmanyanimalsdoyousee': Counter({'1': 1}), 'answers_whatistheanimalsdoing': Counter({'standing': 1}) } ] } reduced_data = [ { 'choice': 'raccoon', 'total_vote_count': 8, 'choice_count': 4, 'answers_howmanyanimalsdoyousee': { '1': 4 }, 'answers_whatistheanimalsdoing': { 'standing': 3, 'grooming': 1 }, 'answers_clickwowifthisasanespeciallyawesomephoto': { 'wow': 1 } }, { 'choice': 'blackbear', 'total_vote_count': 8, 'choice_count': 4, 'answers_howmanyanimalsdoyousee': { '1': 4 }, 'answers_whatistheanimalsdoing': { 'standing': 2, 'grooming': 2, 'interacting': 1 }, 'answers_clickwowifthisasanespeciallyawesomephoto': { 'wow': 2 } } ] class TestCountSurvey(unittest.TestCase): def setUp(self): self.maxDiff = None self.extracted_data = copy.deepcopy(extracted_data) self.processed_data = copy.deepcopy(processed_data) self.reduced_data = copy.deepcopy(reduced_data) def test_process_data(self): result_data, result_count = process_data(self.extracted_data) self.assertEqual(result_count, len(self.extracted_data)) self.assertDictEqual(result_data, self.processed_data) def test_count_vote(self): result = survey_reducer._original((self.processed_data, len(self.extracted_data))) self.assertCountEqual(result, self.reduced_data) def test_survey_reducer(self): result = survey_reducer(self.extracted_data) self.assertCountEqual(result, self.reduced_data) def test_survey_reducer_request(self): app = flask.Flask(__name__) request_kwargs = { 'data': json.dumps(extract_in_data(self.extracted_data)), 'content_type': 'application/json' } with app.test_request_context(**request_kwargs): result = survey_reducer(flask.request) self.assertCountEqual(result, self.reduced_data) if __name__ == '__main__': unittest.main()
39.653846
212
0.628904
447
5,155
6.997763
0.154362
0.012788
0.03165
0.079284
0.65633
0.647698
0.634591
0.634591
0.634591
0.634591
0
0.022905
0.229292
5,155
129
213
39.96124
0.76441
0
0
0.29661
0
0
0.374976
0.280504
0
0
0
0
0.042373
1
0.042373
false
0
0.059322
0
0.110169
0
0
0
0
null
0
0
0
0
0
0
0
0
1
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
0
1
97affcf5430ea542d75da78b8065ecc199a3cc76
1,898
py
Python
PyMess/FIPS/ANN/ConvertData.py
mattkjames7/PyMess
f2c68285a7845a24d98284e20ed4292ed5e58138
[ "MIT" ]
null
null
null
PyMess/FIPS/ANN/ConvertData.py
mattkjames7/PyMess
f2c68285a7845a24d98284e20ed4292ed5e58138
[ "MIT" ]
null
null
null
PyMess/FIPS/ANN/ConvertData.py
mattkjames7/PyMess
f2c68285a7845a24d98284e20ed4292ed5e58138
[ "MIT" ]
null
null
null
import numpy as np from ... import Globals from .ReadData import ReadData import os import RecarrayTools as RT def _DateStrToDateUT(s): ''' convert date on the format YYYY-MM-DDThh:mm:ss.sss to an integer date and a floating point time. ''' Y = np.array([np.int32(x[0:4]) for x in s]) M = np.array([np.int32(x[5:7]) for x in s]) D = np.array([np.int32(x[8:10]) for x in s]) h = np.array([np.float32(x[11:13]) for x in s]) m = np.array([np.float32(x[14:16]) for x in s]) s = np.array([np.float32(x[17:]) for x in s]) Date = (Y*10000 + M*100 + D).astype('int32') ut = (h + m/60.0 + s/3600.0).astype('float32') return Date,ut def ConvertData(): ''' Convert the James et al 2020 data to binaries ''' #create the output dtype dtype = [ ('Date','int32'), ('ut','float32'), ('nk','float32'), ('tk','float32'), ('K','float32'), ('SplitProb','float32',(8,)), ('Prob','float32'), ('SplitClass','int8',(8,)), ('Class','int8')] #read in the data file data = ReadData() #create a recarray out = np.recarray(data.size,dtype=dtype) #convert dates and times out.Date,out.ut = _DateStrToDateUT(data.UT) #copy the other fields across out.nk = data.Density out.tk = data.Temperature out.K = data.Kappa for i in range(0,8): out.SplitProb[:,i] = data['P{:d}'.format(i)].astype('float32') out.SplitClass[:,i] = data['Class{:d}'.format(i)].astype('int8') out.Prob = data.P out.Class = data.Class #find the unique dates ud = np.unique(out.Date) #create the output directory outdir = Globals.MessPath + 'FIPS/ANN/bin/' if not os.path.isdir(outdir): os.system('mkdir -pv '+outdir) #file name format fnfmt = outdir + '{:08d}.bin' #loop through dates, saving a recarray file for each one for i in range(ud.size): use = np.where(out.Date == ud[i])[0] fname = fnfmt.format(ud[i]) RT.SaveRecarray(out[use],fname)
24.025316
70
0.630664
318
1,898
3.757862
0.383648
0.035146
0.045188
0.035146
0.093724
0.028452
0.028452
0.028452
0
0
0
0.050837
0.181243
1,898
78
71
24.333333
0.718147
0.19705
0
0
0
0
0.109772
0
0
0
0
0
0
1
0.044444
false
0
0.111111
0
0.177778
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
97b17d951641a10dde5adb0978a509ff02ff1d9c
812
py
Python
libapp/migrations/0010_notification.py
Nyagah-Tech/library
2ae1df4e89257c9c7d7f2328ab6c5f6352867997
[ "MIT" ]
null
null
null
libapp/migrations/0010_notification.py
Nyagah-Tech/library
2ae1df4e89257c9c7d7f2328ab6c5f6352867997
[ "MIT" ]
8
2020-06-06T01:24:32.000Z
2022-02-10T12:26:48.000Z
libapp/migrations/0010_notification.py
Nyagah-Tech/library
2ae1df4e89257c9c7d7f2328ab6c5f6352867997
[ "MIT" ]
null
null
null
# Generated by Django 2.2.8 on 2020-01-23 06:58 from django.conf import settings from django.db import migrations, models import tinymce.models class Migration(migrations.Migration): dependencies = [ migrations.swappable_dependency(settings.AUTH_USER_MODEL), ('libapp', '0009_comment'), ] operations = [ migrations.CreateModel( name='Notification', fields=[ ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')), ('name', models.CharField(max_length=200)), ('notification', tinymce.models.HTMLField()), ('user', models.ManyToManyField(blank=True, related_name='notification', to=settings.AUTH_USER_MODEL)), ], ), ]
31.230769
119
0.626847
84
812
5.928571
0.642857
0.040161
0.064257
0.084337
0
0
0
0
0
0
0
0.036125
0.25
812
25
120
32.48
0.781609
0.055419
0
0
1
0
0.086275
0
0
0
0
0
0
1
0
false
0
0.157895
0
0.315789
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
1
0
0
0
null
0
0
0
0
0
0
0
0
0
0
0
0
0
1
97b281cd2e09060653c37e8623382835d9e1206e
3,891
py
Python
2_data_files/plotter.py
Abhipanda4/RQs_in_Regex_Graphs
80b86b5b3f92ef28102ac0f5049bb495b5cc07f9
[ "Apache-2.0" ]
2
2018-10-09T09:59:45.000Z
2021-11-21T17:01:47.000Z
2_data_files/plotter.py
Abhipanda4/RQs_in_Regex_Graphs
80b86b5b3f92ef28102ac0f5049bb495b5cc07f9
[ "Apache-2.0" ]
null
null
null
2_data_files/plotter.py
Abhipanda4/RQs_in_Regex_Graphs
80b86b5b3f92ef28102ac0f5049bb495b5cc07f9
[ "Apache-2.0" ]
null
null
null
import csv import matplotlib.pyplot as plt import numpy as np def index_sizes(): fp = open("./index_size.csv") x = csv.reader(fp, delimiter='\t') sizes = [] for line in x: size = float(line[0].strip()[:-1]) sizes.append(size) temp = sorted(sizes[:-1]) nodes = [i for i in range(100, 5001, 100)] f = plt.figure() plt.xlabel("Number of node-color pairs stored") plt.ylabel("Size of partial index(in MBs)") plt.plot(nodes, temp) plt.show() f.savefig("../figures/index_sizes.pdf", bbox_inches='tight') def MC_size_dependence(): fp = open("./MC_analysis.csv", 'r') x = csv.reader(fp) times = [int(i[1]) for i in x] p = [] for i in range(0, len(times), 100): p.append(np.mean(times[i:i + 100])) parts = [i for i in range(10, 501, 10)] print(p) plt.plot(parts, p) plt.xlabel("Number of pairs stored") plt.ylabel("Average time in ms") plt.title("Variation of query times with size of index stored") plt.show() def pre_process_time(): fp1 = open("./TC_pre_pro.txt", 'r') fp2 = open("./MC_pre_pro.txt", 'r') nodes = [i for i in range(10, 21, 2)] f1 = csv.reader(fp1) f2 = csv.reader(fp2) p2 = [[]] * 5 p1 = [int(i[0]) for i in f1] p2_temp = [int(i[0]) for i in f2] print(p2_temp) for i in range(5): p2[i] = [p2_temp[j] / 20 for j in range(i, len(p2_temp), 5)] f = plt.figure() plt.plot(nodes, p1, label="Complete transitive closure") for i in range(5): plt.plot(nodes, p2[i], label=str((i + 1) * 10) + "% pairs computed") plt.xlabel("|V|(in thousands)") plt.ylabel("Time taken to build table(in ms)") plt.title("Comparision of pre-processing times for Algorithm 1 & 3") plt.legend() plt.show() f.savefig("../figures/pre_pro_10iter_MC.pdf", bbox_inches='tight') def hits_vs_miss(): fp = csv.reader(open("./MC_size_dependence.csv", 'r')) tmp = list(fp) lines = [i for i in tmp if i[0].find("Time") == -1] T = [] H = [] M = [] for i in range(0, len(lines), 5): times = [int(lines[i + j][1]) for j in range(5)] T.append(sum(times) / 5) hits = [int(lines[i + j][2]) for j in range(5)] H.append(sum(hits) / 5) misses = [int(lines[i + j][3]) for j in range(5)] M.append(sum(misses) / 5) # print(T) # print(H) # print(M) X = [6000, 12000, 18000, 24000, 30000] plt.subplot(1, 2, 1) plt.plot(X, H, label="Hits") plt.plot(X, M, label="Misses") plt.xlabel("Number of node-color pairs stored") plt.ylabel("Number of hits/misses") plt.legend() plt.subplot(1, 2, 2) plt.plot(X, T, label="Query Times") plt.xlabel("Number of node-color pairs stored") plt.ylabel("Time in ms") plt.title("Query times") plt.show() def f(r): timings = [] x = [] count = 0 for line in r: x.append(int(line[1])) count += 1 if count == 20: timings.append(sum(x) / 20) x = [] count = 0 return timings def edge_size(): f1 = open("./data_algo1.csv", 'r') f2 = open("./data_algo2.csv", 'r') f3 = open("./data_algo3.csv", 'r') r1 = csv.reader(f1) r2 = csv.reader(f2) r3 = csv.reader(f3) x1 = f(r1) x2 = f(r2) x3 = f(r3) x1[3] = x1[3] / 100 print(x1) print(x2) print(x3) x = [2, 3, 4, 5, 6] fig = plt.figure() plt.plot(x, x1, label="Full Transitive Closure") plt.plot(x, x2, label="Partial Transitive Closure") plt.plot(x[:3], x3[:3], label="BFS") plt.legend() plt.xlabel("Edge-Node Ratio") plt.ylabel("Average Time taken for query in milliseconds") plt.show() fig.savefig("../figures/edge_variation.pdf") # pre_process_time() # hits_vs_miss() # MC_size_dependence() # edge_size() index_sizes()
25.431373
76
0.561809
627
3,891
3.425837
0.23445
0.020484
0.030726
0.035847
0.217877
0.111732
0.064246
0.064246
0.064246
0.064246
0
0.053472
0.25983
3,891
152
77
25.598684
0.692361
0.023901
0
0.161017
0
0
0.207388
0.029288
0
0
0
0
0
1
0.050847
false
0
0.025424
0
0.084746
0.042373
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
97b47597bcd7e262415d73a5d1a8d5d991bcfe66
3,022
py
Python
generic_editor.py
jcooper-korg/talon_user
ef086f9890448f7d633a4f02b36a18de853581a8
[ "0BSD" ]
1
2018-09-22T22:34:35.000Z
2018-09-22T22:34:35.000Z
generic_editor.py
jcooper-korg/talon_user
ef086f9890448f7d633a4f02b36a18de853581a8
[ "0BSD" ]
null
null
null
generic_editor.py
jcooper-korg/talon_user
ef086f9890448f7d633a4f02b36a18de853581a8
[ "0BSD" ]
null
null
null
# https://github.com/JonathanNickerson/talon_voice_user_scripts # jsc added indent/outdent and simplified jolt from talon.voice import Key, press, Str, Context ctx = Context('generic_editor') # , bundle='com.microsoft.VSCode') numeral_map = dict((str(n), n) for n in range(0, 20)) for n in [20, 30, 40, 50, 60, 70, 80, 90]: numeral_map[str(n)] = n numeral_map["oh"] = 0 # synonym for zero numerals = ' (' + ' | '.join(sorted(numeral_map.keys())) + ')+' optional_numerals = ' (' + ' | '.join(sorted(numeral_map.keys())) + ')*' def text_to_number(words): tmp = [str(s).lower() for s in words] words = [parse_word(word) for word in tmp] result = 0 factor = 1 for word in reversed(words): if word not in numerals: raise Exception('not a number') result = result + factor * int(numeral_map[word]) factor = 10 * factor return result def parse_word(word): word = word.lstrip('\\').split('\\', 1)[0] return word def jump_to_bol(m): line = text_to_number(m) press('cmd-l') Str(str(line))(None) press('enter') def jump_to_end_of_line(): press('cmd-right') def jump_to_beginning_of_text(): press('cmd-left') def jump_to_nearly_end_of_line(): press('left') def jump_to_bol_and(then): def fn(m): if len(m._words) > 1: jump_to_bol(m._words[1:]) else: press('ctrl-a') press('cmd-left') then() return fn def jump_to_eol_and(then): def fn(m): if len(m._words) > 1: jump_to_bol(m._words[1:]) press('cmd-right') then() return fn def toggle_comments(): # works in VSCode with Finnish keyboard layout # press('cmd-shift-7') # does not work in VSCode, see https://github.com/talonvoice/talon/issues/3 press('cmd-/') def snipline(): press('shift-cmd-right') press('delete') press('delete') press('ctrl-a') press('cmd-left') keymap = { 'sprinkle' + optional_numerals: jump_to_bol, 'spring' + optional_numerals: jump_to_eol_and(jump_to_beginning_of_text), 'dear' + optional_numerals: jump_to_eol_and(lambda: None), 'smear' + optional_numerals: jump_to_eol_and(jump_to_nearly_end_of_line), 'trundle' + optional_numerals: jump_to_bol_and(toggle_comments), 'jolt': Key('ctrl-a cmd-left shift-down cmd-c down cmd-v' ), # jsc simplified 'snipline' + optional_numerals: jump_to_bol_and(snipline), # NB these do not work properly if there is a selection 'snipple': Key('shift-cmd-left delete'), 'snipper': Key('shift-cmd-right delete'), 'shackle': Key('cmd-right shift-cmd-left'), 'bracken': [Key('cmd-shift-ctrl-right')], 'shockey': Key('ctrl-a cmd-left enter up'), 'shockoon': Key('cmd-right enter'), 'sprinkoon' + numerals: jump_to_eol_and(lambda: press('enter')), 'olly': Key('cmd-a'), # jsc added '(indent | shabble)': Key('cmd-['), '(outdent | shabber)': Key('cmd-]'), } ctx.keymap(keymap)
26.743363
82
0.625745
438
3,022
4.127854
0.319635
0.056416
0.034845
0.073009
0.277102
0.22677
0.082965
0.082965
0.045354
0.045354
0
0.013491
0.215089
3,022
112
83
26.982143
0.748735
0.12409
0
0.246753
0
0
0.1783
0
0.025974
0
0
0
0
1
0.155844
false
0
0.012987
0
0.220779
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
97b62ed540d6ffc6ab71d19b389a5534151aeb3d
4,260
py
Python
setup.py
blschatz/pyHDT
9553fd49e1e89a89d248e5d75b3a49ad3b3e124f
[ "MIT" ]
null
null
null
setup.py
blschatz/pyHDT
9553fd49e1e89a89d248e5d75b3a49ad3b3e124f
[ "MIT" ]
null
null
null
setup.py
blschatz/pyHDT
9553fd49e1e89a89d248e5d75b3a49ad3b3e124f
[ "MIT" ]
null
null
null
# setup.py # Author: Thomas MINIER - MIT License 2017-2018 from setuptools import setup, Extension from os import listdir import pybind11 import distutils import platform __pyhdt_version__ = "1.2.1" with open('README.rst') as file: long_description = file.read() def list_files(path, extension=".cpp", exclude="S.cpp"): """List paths to all files that ends with a given extension""" return ["%s/%s" % (path, f) for f in listdir(path) if f.endswith(extension) and (not f.endswith(exclude))] # pyHDT source files sources = [ "src/hdt.cpp", "src/hdt_document.cpp", "src/triple_iterator.cpp", "src/tripleid_iterator.cpp", "src/join_iterator.cpp" ] # HDT source files sources += list_files("serd-0.30.0/src/", extension=".c") sources += list_files("hdt-cpp-1.3.2/libcds/src/static/bitsequence") sources += list_files("hdt-cpp-1.3.2/libcds/src/static/coders") sources += list_files("hdt-cpp-1.3.2/libcds/src/static/mapper") sources += list_files("hdt-cpp-1.3.2/libcds/src/static/sequence") sources += list_files("hdt-cpp-1.3.2/libcds/src/static/permutation") sources += list_files("hdt-cpp-1.3.2/libcds/src/utils") sources += list_files("hdt-cpp-1.3.2/libhdt/src/bitsequence") sources += list_files("hdt-cpp-1.3.2/libhdt/src/dictionary") sources += list_files("hdt-cpp-1.3.2/libhdt/src/hdt") sources += list_files("hdt-cpp-1.3.2/libhdt/src/header") sources += list_files("hdt-cpp-1.3.2/libhdt/src/huffman") sources += list_files("hdt-cpp-1.3.2/libhdt/src/libdcs") sources += list_files("hdt-cpp-1.3.2/libhdt/src/libdcs/fmindex") sources += list_files("hdt-cpp-1.3.2/libhdt/src/rdf") sources += list_files("hdt-cpp-1.3.2/libhdt/src/sequence") sources += list_files("hdt-cpp-1.3.2/libhdt/src/triples") sources += list_files("hdt-cpp-1.3.2/libhdt/src/util") sources += list_files("hdt-cpp-1.3.2/libhdt/src/sparql") # pybind11 + pyHDT + libcds + HDT-lib headers include_dirs = [ pybind11.get_include(), pybind11.get_include(True), "include/", "hdt-cpp-1.3.2/libhdt/include/", "hdt-cpp-1.3.2/libhdt/src/dictionary/", "hdt-cpp-1.3.2/libhdt/src/sparql/", "hdt-cpp-1.3.2/libcds/include/", "hdt-cpp-1.3.2/libcds/src/static/bitsequence", "hdt-cpp-1.3.2/libcds/src/static/coders", "hdt-cpp-1.3.2/libcds/src/static/mapper", "hdt-cpp-1.3.2/libcds/src/static/permutation", "hdt-cpp-1.3.2/libcds/src/static/sequence", "hdt-cpp-1.3.2/libcds/src/utils", "serd-0.30.0" ] # Need to build in c++11 minimum # TODO add a check to use c++14 or c++17 if available extra_compile_args_macos = ["-std=c++11", "-DHAVE_SERD", "-DHAVE_POSIX_MEMALIGN"] extra_compile_args_win = ["-DHAVE_SERD", "-DWIN32", "-D_AMD64_", "-DUNICODE"] plaf = platform.system() if plaf == "Windows": extra_compile_args = extra_compile_args_win elif plaf == "Darwin": extra_compile_args = extra_compile_args_macos else: extra_compile_args = ["-std=c++11", "-DHAVE_SERD", "-DHAVE_POSIX_MEMALIGN"] # build HDT extension hdt_extension = Extension("hdt", sources=sources, include_dirs=include_dirs, extra_compile_args=extra_compile_args, language='c++') # monkey patch the distutils compiler to enable compilation of the Serd parser source # it is C, and the C++11 compile argument is incompatible c = distutils.ccompiler.new_compiler def wrapped_new_compiler_fn(*args, **kwargs): compiler = c(*args, **kwargs) c_c = compiler._compile def wrapped_compiler_compile(obj, src, ext, cc_args, extra_postargs, pp_opts): if ext == ".c": return c_c(obj, src, ext, cc_args, [ "-DHAVE_SERD", "-std=c99" ], pp_opts) else: return c_c(obj, src, ext, cc_args, extra_postargs, pp_opts) compiler._compile = wrapped_compiler_compile return compiler distutils.ccompiler.new_compiler = wrapped_new_compiler_fn setup( name="hdt", version=__pyhdt_version__, author="Thomas Minier", author_email="thomas.minier@univ-nantes.fr", url="https://github.com/Callidon/pyHDT", description="Read and query HDT document with ease in Python", long_description=long_description, keywords=["hdt", "rdf", "semantic web", "search"], license="MIT", install_requires=['pybind11==2.2.4'], ext_modules=[hdt_extension] )
37.368421
110
0.698122
675
4,260
4.251852
0.248889
0.060627
0.068293
0.078049
0.447735
0.447735
0.40662
0.396516
0.329268
0.227875
0
0.036374
0.135211
4,260
113
111
37.699115
0.742671
0.102347
0
0.022727
0
0
0.38514
0.292465
0
0
0
0.00885
0
1
0.034091
false
0
0.056818
0
0.136364
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
97ba1bc69fa28bb340ca97364cb86adfcaf60e62
2,880
py
Python
src/rest_api/mir_coords_to_csv.py
jonathanleinola/radiohead-master
f0854441c07aba0ccf51bf9ec8904b860eefd683
[ "MIT" ]
null
null
null
src/rest_api/mir_coords_to_csv.py
jonathanleinola/radiohead-master
f0854441c07aba0ccf51bf9ec8904b860eefd683
[ "MIT" ]
null
null
null
src/rest_api/mir_coords_to_csv.py
jonathanleinola/radiohead-master
f0854441c07aba0ccf51bf9ec8904b860eefd683
[ "MIT" ]
null
null
null
import time import sys import urllib3 from time import sleep import json import csv import datetime import requests from datetime import datetime import subprocess # just for changing file ownership at the end of script http = urllib3.PoolManager() ############################################################################### DURATION = 2000 # How many timestamps you want? it 100 takes 10s TIMES = 10 # How many times per sec you want the timestamp ############################################################################### ### define filename to save timestamps (coords3.csv) with open('coords.csv', mode='w') as csvfile: # open the csv file writer = csv.writer(csvfile, delimiter=',', quoting=csv.QUOTE_MINIMAL) writer.writerow(["X", "Y", "orientation","timestamp"]) print ("Coord queries running, wait"), print(DURATION/TIMES), print ("s") def main(): ####################################################################### ### change the url localhost to match actual addrest for REST API calls ####################################################################### url = 'http://192.168.12.20/api/v2.0.0/status' # url where to call the rest api error=0 response = http.request('GET', url) # response values from REST API ### get the values from response jason object x,y,orientation ### try: x = json.loads(response.data)['position']['x'] y = json.loads(response.data)['position']['y'] orientation = json.loads(response.data)['position']['orientation'] except KeyError as error: error=1 ### get the timestamp %f')[:-3] gives second with 3 digits ### timestamp = datetime.now().strftime('%Y/%m/%d %H:%M:%S.%f')[:-3] ### write the REST API values into csv file if error != 1: writer.writerow([x,y,orientation,timestamp]) else: error=0 if __name__ == '__main__': time_start = time.time() i = 1 while True: time_current = time.time() if time_current > time_start + i / float(TIMES): # print('{}: {}'.format(i, time_current)) main() # execute main function after every 100ms i += 1 if i > DURATION: # break the prog when duration reached break print ("Coord queries done, have a nice day!") ################################################################################ ### If issues with ownership of the file u can use subprocess.call function to ### execute shell commands such as: ### subprocess.call(['chown', '[user]:root','/home/user/Documents/coords3.csv']) ### change [user] to match username and the file path to correct folder ################################################################################
39.452055
87
0.518056
323
2,880
4.575851
0.473684
0.005413
0.026387
0.042625
0.107578
0.048714
0
0
0
0
0
0.017849
0.221875
2,880
72
88
40
0.641678
0.301042
0
0.044444
0
0
0.135099
0
0
0
0
0
0
1
0.022222
false
0
0.222222
0
0.244444
0.088889
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
97bb0bfb2e83efd2bcd29357e37506cc837d9359
2,704
py
Python
arraycw.py
cs-fullstack-2019-spring/python-arraycollections-cw-MelaatiJ
1337dacf9568e8e5249ce6aa13bd0e425b31e940
[ "Apache-2.0" ]
null
null
null
arraycw.py
cs-fullstack-2019-spring/python-arraycollections-cw-MelaatiJ
1337dacf9568e8e5249ce6aa13bd0e425b31e940
[ "Apache-2.0" ]
null
null
null
arraycw.py
cs-fullstack-2019-spring/python-arraycollections-cw-MelaatiJ
1337dacf9568e8e5249ce6aa13bd0e425b31e940
[ "Apache-2.0" ]
null
null
null
def main(): # problem1() # problem2() # problem3() # problem4() # problem5() def problem1(): awesomePeeps = ["kenn", "Kevin", "Erin", "Meka"] #made an array print(awesomePeeps[2]) #printing the second element print(len(awesomePeeps)) #printing the length and how many inside awesomePeeps.remove("Kevin") #removing kevin print(awesomePeeps[2]) # # Create a function with the variable below. After you create the variable do the instructions below that. # ``` # arrayForProblem2 = ["Kenn", "Kevin", "Erin", "Meka"] # ``` # a) Print the 3rd element of the numberList. # # b) Print the size of the array # # c) Delete the second element. # # d) Print the 3rd element. def problem2(): userInput = "" #making a blank input while(userInput != 'q'): #if its not equal to q it will continue to ask userInput = input("Enter something") def problem3(): nickNames = { #this is my dictionary "johnathan" : "John", "Micheal":"Mike", "William":"Bill", "RObert":"Rob" } print(nickNames) #printing all the objects print(nickNames["William"]) #printing william nick name # Create a function that contains a collection of information for the following. After you create the collection do the instructions below that. # ``` # Jonathan/John # Michael/Mike # William/Bill # Robert/Rob # ``` # a) Print the collection # # b) Print William's nickname def problem4(): rando = [23,34,45,7,89] #my rando arrAay for elements in range(len(rando)-1,-1,-1): #making it go backwards print(rando[elements]) #printing the elements # Create an array of 5 numbers. # <strong>Using a loop</strong>, print the elements in the array reverse order. # <strong>Do not use a function</strong> # # # # def problem5(): higher = 0 lower = 0 #setting my variables to zero equal = 0 pickaNumber = [2,4,5,7,8] #made my array userinput=int(input("Enter a number")) for eachEl in range(0,len(pickaNumber)-1,1): #calling each number in the array if(userinput>pickaNumber[eachEl]): lower+=1 elif(userinput==pickaNumber[eachEl]): #comparing them to if its lkarger or maller equal+=1 elif(userinput<pickaNumber[eachEl]): higher+=1 print(higher) print(lower) #printing each function print(equal) # # Create a function that will have a hard coded array then ask the user for a number. # Use the userInput to state how many numbers in an array are higher, lower, or equal to it. # # if __name__ == '__main__': main()
23.719298
144
0.628698
354
2,704
4.779661
0.39548
0.023641
0.026596
0.020095
0.095745
0
0
0
0
0
0
0.020906
0.257027
2,704
114
145
23.719298
0.821304
0.504068
0
0.047619
0
0
0.086381
0
0
0
0
0
0
0
null
null
0
0
null
null
0.214286
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
1
0
0
0
0
0
0
0
0
1
97be40091dbb9d0bd5f45ca454971f59e1fb204d
3,511
py
Python
timeeval_experiments/algorithms/mscred.py
HPI-Information-Systems/TimeEval
9b2717b89decd57dd09e04ad94c120f13132d7b8
[ "MIT" ]
2
2022-01-29T03:46:31.000Z
2022-02-14T14:06:35.000Z
timeeval_experiments/algorithms/mscred.py
HPI-Information-Systems/TimeEval
9b2717b89decd57dd09e04ad94c120f13132d7b8
[ "MIT" ]
null
null
null
timeeval_experiments/algorithms/mscred.py
HPI-Information-Systems/TimeEval
9b2717b89decd57dd09e04ad94c120f13132d7b8
[ "MIT" ]
null
null
null
from durations import Duration from typing import Any, Dict, Optional from timeeval import Algorithm, TrainingType, InputDimensionality from timeeval.adapters import DockerAdapter from timeeval.params import ParameterConfig import numpy as np import numpy as np from timeeval.utils.window import ReverseWindowing # post-processing for MSCRED def post_mscred(scores: np.ndarray, args: dict) -> np.ndarray: ds_length = args.get("dataset_details").length # type: ignore gap_time = args.get("hyper_params", {}).get("gap_time", 10) window_size = args.get("hyper_params", {}).get("window_size", 5) max_window_size = max(args.get("hyper_params", {}).get("windows", [10, 30, 60])) offset = (ds_length - (max_window_size - 1)) % gap_time image_scores = ReverseWindowing(window_size=window_size).fit_transform(scores) return np.concatenate([np.repeat(image_scores[:-offset], gap_time), image_scores[-offset:]]) _mscred_parameters: Dict[str, Dict[str, Any]] = { "batch_size": { "defaultValue": 32, "description": "Number of instances trained at the same time", "name": "batch_size", "type": "int" }, "early_stopping_delta": { "defaultValue": 0.05, "description": "If 1 - (loss / last_loss) is less than `delta` for `patience` epochs, stop", "name": "early_stopping_delta", "type": "float" }, "early_stopping_patience": { "defaultValue": 10, "description": "If 1 - (loss / last_loss) is less than `delta` for `patience` epochs, stop", "name": "early_stopping_patience", "type": "int" }, "epochs": { "defaultValue": 1, "description": "Number of training iterations over entire dataset", "name": "epochs", "type": "int" }, "gap_time": { "defaultValue": 10, "description": "Number of points to skip over between the generation of signature matrices", "name": "gap_time", "type": "int" }, "learning_rate": { "defaultValue": 0.001, "description": "Learning rate for Adam optimizer", "name": "learning_rate", "type": "float" }, "random_state": { "defaultValue": 42, "description": "Seed for the random number generator", "name": "random_state", "type": "int" }, "split": { "defaultValue": 0.8, "description": "Train-validation split for early stopping", "name": "split", "type": "float" }, "test_batch_size": { "defaultValue": 256, "description": "Number of instances used for validation and testing at the same time", "name": "test_batch_size", "type": "int" }, "window_size": { "defaultValue": 5, "description": "Size of the sliding windows", "name": "window_size", "type": "int" }, "windows": { "defaultValue": [ 10, 30, 60 ], "description": "Number and size of different signature matrices (correlation matrices) to compute as a preprocessing step", "name": "windows", "type": "List[int]" } } def mscred(params: ParameterConfig = None, skip_pull: bool = False, timeout: Optional[Duration] = None) -> Algorithm: return Algorithm( name="MSCRED", main=DockerAdapter( image_name="registry.gitlab.hpi.de/akita/i/mscred", skip_pull=skip_pull, timeout=timeout, group_privileges="akita", ), preprocess=None, postprocess=post_mscred, param_schema=_mscred_parameters, param_config=params or ParameterConfig.defaults(), data_as_file=True, training_type=TrainingType.SEMI_SUPERVISED, input_dimensionality=InputDimensionality("multivariate") )
30.530435
125
0.672173
419
3,511
5.479714
0.362769
0.034843
0.033101
0.023519
0.111063
0.068815
0.068815
0.068815
0.068815
0.068815
0
0.013923
0.181715
3,511
114
126
30.798246
0.785242
0.011108
0
0.152381
0
0.019048
0.405592
0.023926
0
0
0
0
0
1
0.019048
false
0
0.07619
0.009524
0.114286
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
97bf1504b82eb929f132872535cb5630bd14f3ad
7,470
py
Python
fedot/core/operations/evaluation/operation_implementations/data_operations/sklearn_selectors.py
vishalbelsare/FEDOT
3a6f06b29cf2f173008d119f7cb5dc705a45f695
[ "BSD-3-Clause" ]
null
null
null
fedot/core/operations/evaluation/operation_implementations/data_operations/sklearn_selectors.py
vishalbelsare/FEDOT
3a6f06b29cf2f173008d119f7cb5dc705a45f695
[ "BSD-3-Clause" ]
null
null
null
fedot/core/operations/evaluation/operation_implementations/data_operations/sklearn_selectors.py
vishalbelsare/FEDOT
3a6f06b29cf2f173008d119f7cb5dc705a45f695
[ "BSD-3-Clause" ]
null
null
null
from typing import Optional import numpy as np from sklearn.feature_selection import RFE from sklearn.linear_model import LinearRegression, LogisticRegression from sklearn.tree import DecisionTreeClassifier, DecisionTreeRegressor from fedot.core.data.data import OutputData from fedot.core.operations.evaluation.operation_implementations.implementation_interfaces import \ DataOperationImplementation class FeatureSelectionImplementation(DataOperationImplementation): """ Class for applying feature selection operations on tabular data """ def __init__(self, **params: Optional[dict]): super().__init__() self.inner_model = None self.operation = None self.is_not_fitted = None # Number of columns in features table self.features_columns_number = None # Bool mask where True - remain column and False - drop it self.remain_features_mask = None def fit(self, input_data): """ Method for fit feature selection :param input_data: data with features, target and ids to process :return operation: trained operation (optional output) """ features = input_data.features target = input_data.target # Define number of columns in the features table if len(features.shape) == 1: self.features_columns_number = 1 else: self.features_columns_number = features.shape[1] if self.features_columns_number > 1: if self._is_input_data_one_dimensional(features): self.is_not_fitted = True return self.operation try: self.operation.fit(features, target) except ValueError: # For time series forecasting not available multi-targets self.operation.fit(features, target[:, 0]) else: self.is_not_fitted = True return self.operation def transform(self, input_data, is_fit_pipeline_stage: Optional[bool]): """ Method for making prediction :param input_data: data with features, target and ids to process :param is_fit_pipeline_stage: is this fit or predict stage for pipeline :return output_data: filtered input data by columns """ if self.is_not_fitted: return self._convert_to_output(input_data, input_data.features) features = input_data.features source_features_shape = features.shape transformed_features = self._make_new_table(features) # Update features output_data = self._convert_to_output(input_data, transformed_features) self._update_column_types(source_features_shape, output_data) return output_data def get_params(self): return self.operation.get_params() def _update_column_types(self, source_features_shape, output_data: OutputData): """ Update column types after applying feature selection operations """ if len(source_features_shape) < 2: return output_data else: if self.features_columns_number > 1: cols_number_removed = source_features_shape[1] - output_data.predict.shape[1] if cols_number_removed > 0: # There are several columns, which were dropped col_types = output_data.supplementary_data.column_types['features'] # Calculate remained_column_types = np.array(col_types)[self.remain_features_mask] output_data.supplementary_data.column_types['features'] = list(remained_column_types) def _make_new_table(self, features): """ The method creates a table based on transformed data and source boolean features :param features: tabular data for processing :return transformed_features: transformed features table """ # Bool vector - mask for columns self.remain_features_mask = self.operation.support_ transformed_features = features[:, self.remain_features_mask] return transformed_features @staticmethod def _is_input_data_one_dimensional(features_to_process: np.array): """ Check if features table contain only one column """ return features_to_process.shape[1] == 1 class LinearRegFSImplementation(FeatureSelectionImplementation): """ Class for feature selection based on Recursive Feature Elimination (RFE) and LinearRegression as core model Task type - regression """ def __init__(self, **params: Optional[dict]): super().__init__() self.inner_model = LinearRegression(normalize=True) if not params: # Default parameters self.operation = RFE(estimator=self.inner_model) else: # Checking the appropriate params are using or not rfe_params = {k: params[k] for k in ['n_features_to_select', 'step']} self.operation = RFE(estimator=self.inner_model, **rfe_params) self.params = params class NonLinearRegFSImplementation(FeatureSelectionImplementation): """ Class for feature selection based on Recursive Feature Elimination (RFE) and DecisionTreeRegressor as core model Task type - regression """ def __init__(self, **params: Optional[dict]): super().__init__() self.inner_model = DecisionTreeRegressor() if not params: # Default parameters self.operation = RFE(estimator=self.inner_model) else: # Checking the appropriate params are using or not rfe_params = {k: params[k] for k in ['n_features_to_select', 'step']} self.operation = RFE(estimator=self.inner_model, **rfe_params) self.params = params class LinearClassFSImplementation(FeatureSelectionImplementation): """ Class for feature selection based on Recursive Feature Elimination (RFE) and LogisticRegression as core model Task type - classification """ def __init__(self, **params: Optional[dict]): super().__init__() self.inner_model = LogisticRegression() if not params: # Default parameters self.operation = RFE(estimator=self.inner_model) else: # Checking the appropriate params are using or not rfe_params = {k: params[k] for k in ['n_features_to_select', 'step']} self.operation = RFE(estimator=self.inner_model, **rfe_params) self.params = params class NonLinearClassFSImplementation(FeatureSelectionImplementation): """ Class for feature selection based on Recursive Feature Elimination (RFE) and DecisionTreeClassifier as core model Task type - classification """ def __init__(self, **params: Optional[dict]): super().__init__() self.inner_model = DecisionTreeClassifier() if not params: # Default parameters self.operation = RFE(estimator=self.inner_model) else: # Checking the appropriate params are using or not rfe_params = {k: params[k] for k in ['n_features_to_select', 'step']} self.operation = RFE(estimator=self.inner_model, **rfe_params) self.params = params
37.35
105
0.654485
817
7,470
5.749082
0.194614
0.041516
0.038748
0.04258
0.47839
0.447733
0.409836
0.390249
0.374069
0.374069
0
0.002215
0.274833
7,470
199
106
37.537688
0.86487
0.247925
0
0.476636
0
0
0.020837
0
0
0
0
0
0
1
0.102804
false
0
0.065421
0.009346
0.28972
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
97c09d6d0c463e1a6cbc1d5065aab627ff77af00
18,595
py
Python
budou/budou.py
aodag/budou
97be13eb87745d5ac78e9c42eda97ac923226259
[ "Apache-2.0" ]
null
null
null
budou/budou.py
aodag/budou
97be13eb87745d5ac78e9c42eda97ac923226259
[ "Apache-2.0" ]
null
null
null
budou/budou.py
aodag/budou
97be13eb87745d5ac78e9c42eda97ac923226259
[ "Apache-2.0" ]
null
null
null
# -*- coding: utf-8 -*- # # Copyright 2017 Google Inc. All rights reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. """Budou, an automatic CJK line break organizer.""" from __future__ import print_function from .cachefactory import load_cache import collections from xml.etree import ElementTree as ET import html5lib import re import six import unicodedata cache = load_cache() class Chunk(object): """Chunk object. This represents a unit for word segmentation. Attributes: word: Surface word of the chunk. (str) pos: Part of speech. (str) label: Label information. (str) dependency: Dependency to neighbor words. None for no dependency, True for dependency to the following word, and False for the dependency to the previous word. (bool or None) """ SPACE_POS = 'SPACE' BREAK_POS = 'BREAK' DEPENDENT_LABEL = ( 'P', 'SNUM', 'PRT', 'AUX', 'SUFF', 'AUXPASS', 'RDROP', 'NUMBER', 'NUM', 'PREF') def __init__(self, word, pos=None, label=None, dependency=None): self.word = word self.pos = pos self.label = label self.dependency = dependency self._add_dependency_if_punct() def __repr__(self): return 'Chunk(%s, %s, %s, %s)' % ( repr(self.word), self.pos, self.label, self.dependency) @classmethod def space(cls): """Creates space Chunk.""" chunk = cls(u' ', cls.SPACE_POS) return chunk @classmethod def breakline(cls): """Creates breakline Chunk.""" chunk = cls(u'\n', cls.BREAK_POS) return chunk def is_space(self): """Checks if this is space Chunk.""" return self.pos == self.SPACE_POS def has_cjk(self): """Checks if the word of the chunk contains CJK characters Using range from https://github.com/nltk/nltk/blob/develop/nltk/tokenize/util.py#L149 """ for char in self.word: if any([start <= ord(char) <= end for start, end in [(4352, 4607), (11904, 42191), (43072, 43135), (44032, 55215), (63744, 64255), (65072, 65103), (65381, 65500), (131072, 196607)] ]): return True return False def update_word(self, word): """Updates the word of the chunk.""" self.word = word def serialize(self): """Returns serialized chunk data in dictionary.""" return { 'word': self.word, 'pos': self.pos, 'label': self.label, 'dependency': self.dependency, 'has_cjk': self.has_cjk(), } def maybe_add_dependency(self, default_dependency_direction): """Adds dependency if any dependency is not assigned yet.""" if self.dependency is None and self.label in self.DEPENDENT_LABEL: self.dependency = default_dependency_direction def _add_dependency_if_punct(self): """Adds dependency if the chunk is punctuation.""" if self.pos == 'PUNCT': try: # Getting unicode category to determine the direction. # Concatenates to the following if it belongs to Ps or Pi category. # Ps: Punctuation, open (e.g. opening bracket characters) # Pi: Punctuation, initial quote (e.g. opening quotation mark) # Otherwise, concatenates to the previous word. # See also https://en.wikipedia.org/wiki/Unicode_character_property category = unicodedata.category(self.word) self.dependency = category in ('Ps', 'Pi') except: pass class ChunkList(list): """Chunk list. """ def get_overlaps(self, offset, length): """Returns chunks overlapped with the given range. Args: offset: Begin offset of the range. (int) length: Length of the range. (int) Returns: Overlapped chunks. (list of Chunk) """ # In case entity's offset points to a space just before the entity. if ''.join([chunk.word for chunk in self])[offset] == ' ': offset += 1 index = 0 result = [] for chunk in self: if offset < index + len(chunk.word) and index < offset + length: result.append(chunk) index += len(chunk.word) return result def swap(self, old_chunks, new_chunk): """Swaps old consecutive chunks with new chunk. Args: old_chunks: List of consecutive Chunks to be removed. (list of Chunk) new_chunk: A Chunk to be inserted. (Chunk) """ indexes = [self.index(chunk) for chunk in old_chunks] del self[indexes[0]:indexes[-1] + 1] self.insert(indexes[0], new_chunk) class Budou(object): """A parser for CJK line break organizer. Attributes: service: A Resource object with methods for interacting with the service. (googleapiclient.discovery.Resource) """ DEFAULT_CLASS_NAME = 'ww' def __init__(self, service): self.service = service @classmethod def authenticate(cls, json_path=None): """Authenticates for Cloud Natural Language API and returns a parser. If a service account private key file is not given, it tries to authenticate with default credentials. Args: json_path: A file path to a service account's JSON private keyfile. (str, optional) Returns: Budou parser. (Budou) """ import google_auth_httplib2 from googleapiclient import discovery scope = ['https://www.googleapis.com/auth/cloud-platform'] if json_path: try: from google.oauth2 import service_account credentials = service_account.Credentials.from_service_account_file( json_path) scoped_credentials = credentials.with_scopes(scope) except ImportError: print('''Failed to load google.oauth2.service_account module. If you are running this script in Google App Engine environment, please call `authenticate` method with empty argument to authenticate with default credentials.''') else: import google.auth scoped_credentials, project = google.auth.default(scope) authed_http = google_auth_httplib2.AuthorizedHttp(scoped_credentials) service = discovery.build('language', 'v1beta2', http=authed_http) return cls(service) def parse(self, source, attributes=None, use_cache=True, language=None, max_length=None, use_entity=False, classname=None): """Parses input HTML code into word chunks and organized code. Args: source: Text to be processed. (str) attributes: A key-value mapping for attributes of output elements. (dictionary, optional) **This argument used to accept a string or a list of strings to specify class names of the output chunks, but this designation method is now deprecated. Please use a dictionary to designate attributes.** use_cache: Whether to use caching. (bool, optional) language: A language used to parse text. (str, optional) max_length: Maximum length of span enclosed chunk. (int, optional) use_entity: Whether to use entities Entity Analysis results. Note that it makes additional request to API, which may incur additional cost. (bool, optional) classname: A class name of output elements. (str, optional) **This argument is deprecated. Please use attributes argument instead.** Returns: A dictionary with the list of word chunks and organized HTML code. For example: { 'chunks': [ {'dependency': None, 'label': 'NSUBJ', 'pos': 'NOUN', 'word': '今日も'}, {'dependency': None, 'label': 'ROOT', 'pos': 'VERB', 'word': '食べる'} ], 'html_code': '<span class="ww">今日も</span><span class="ww">食べる</span>' } """ if use_cache: result_value = cache.get(source, language) if result_value: return result_value input_text = self._preprocess(source) if language == 'ko': # Korean has spaces between words, so this simply parses words by space # and wrap them as chunks. chunks = self._get_chunks_per_space(input_text) else: chunks, tokens, language = self._get_chunks_with_api( input_text, language, use_entity) attributes = self._get_attribute_dict(attributes, classname) html_code = self._html_serialize(chunks, attributes, max_length) result_value = { 'chunks': [chunk.serialize() for chunk in chunks], 'html_code': html_code, 'language': language, 'tokens': tokens, } if use_cache: cache.set(source, language, result_value) return result_value def _get_chunks_per_space(self, input_text): """Returns a chunk list by separating words by spaces. Args: input_text: String to parse. (str) Returns: A chunk list. (ChunkList) """ chunks = ChunkList() words = input_text.split() for i, word in enumerate(words): chunks.append(Chunk(word)) if i < len(words) - 1: # Add no space after the last word. chunks.append(Chunk.space()) return chunks def _get_chunks_with_api(self, input_text, language=None, use_entity=False): """Returns a chunk list by using Google Cloud Natural Language API. Args: input_text: String to parse. (str) language: A language code. 'ja' and 'ko' are supported. (str, optional) use_entity: Whether to use entities in Natural Language API response. (bool, optional) Returns: A chunk list. (ChunkList) """ chunks, tokens, language = self._get_source_chunks(input_text, language) if use_entity: entities = self._get_entities(input_text, language) chunks = self._group_chunks_by_entities(chunks, entities) chunks = self._resolve_dependency(chunks) chunks = self._insert_breakline(chunks) return chunks, tokens, language def _get_attribute_dict(self, attributes, classname=None): """Returns a dictionary of HTML element attributes. Args: attributes: If a dictionary, it should be a map of name-value pairs for attributes of output elements. If a string, it should be a class name of output elements. (dict or str) classname: Optional class name. (str, optional) Returns: An attribute dictionary. (dict of (str, str)) """ if attributes and isinstance(attributes, six.string_types): return { 'class': attributes } if not attributes: attributes = {} if not classname: classname = self.DEFAULT_CLASS_NAME attributes.setdefault('class', classname) return attributes def _preprocess(self, source): """Removes unnecessary break lines and white spaces. Args: source: HTML code to be processed. (str) Returns: Preprocessed HTML code. (str) """ doc = html5lib.parseFragment(source) source = ET.tostring(doc, encoding='utf-8', method='text').decode('utf-8') source = source.replace(u'\n', u'').strip() source = re.sub(r'\s\s+', u' ', source) return source def _get_source_chunks(self, input_text, language=None): """Returns a chunk list retrieved from Syntax Analysis results. Args: input_text: Text to annotate. (str) language: Language of the text. 'ja' and 'ko' are supported. (str, optional) Returns: A chunk list. (ChunkList) """ chunks = ChunkList() sentence_length = 0 tokens, language = self._get_annotations(input_text, language) for i, token in enumerate(tokens): word = token['text']['content'] begin_offset = token['text']['beginOffset'] label = token['dependencyEdge']['label'] pos = token['partOfSpeech']['tag'] if begin_offset > sentence_length: chunks.append(Chunk.space()) sentence_length = begin_offset chunk = Chunk(word, pos, label) # Determining default concatenating direction based on syntax dependency. chunk.maybe_add_dependency( i < token['dependencyEdge']['headTokenIndex']) chunks.append(chunk) sentence_length += len(word) return chunks, tokens, language def _group_chunks_by_entities(self, chunks, entities): """Groups chunks by entities retrieved from NL API Entity Analysis. Args: chunks: The list of chunks to be processed. (ChunkList) entities: List of entities. (list of dict) Returns: A chunk list. (ChunkList) """ for entity in entities: chunks_to_concat = chunks.get_overlaps( entity['beginOffset'], len(entity['content'])) if not chunks_to_concat: continue new_chunk_word = u''.join([chunk.word for chunk in chunks_to_concat]) new_chunk = Chunk(new_chunk_word) chunks.swap(chunks_to_concat, new_chunk) return chunks def _html_serialize(self, chunks, attributes, max_length): """Returns concatenated HTML code with SPAN tag. Args: chunks: The list of chunks to be processed. (ChunkList) attributes: If a dictionary, it should be a map of name-value pairs for attributes of output SPAN tags. If a string, it should be a class name of output SPAN tags. If an array, it should be a list of class names of output SPAN tags. (str or dict or list of str) max_length: Maximum length of span enclosed chunk. (int, optional) Returns: The organized HTML code. (str) """ doc = ET.Element('span') for chunk in chunks: if chunk.is_space(): if doc.getchildren(): if doc.getchildren()[-1].tail is None: doc.getchildren()[-1].tail = ' ' else: doc.getchildren()[-1].tail += ' ' else: if doc.text is not None: # We want to preserve space in cases like "Hello 你好" # But the space in " 你好" can be discarded. doc.text += ' ' else: if chunk.has_cjk() and not (max_length and len(chunk.word) > max_length): ele = ET.Element('span') ele.text = chunk.word for k, v in attributes.items(): ele.attrib[k] = v doc.append(ele) else: # add word without span tag for non-CJK text (e.g. English) # by appending it after the last element if doc.getchildren(): if doc.getchildren()[-1].tail is None: doc.getchildren()[-1].tail = chunk.word else: doc.getchildren()[-1].tail += chunk.word else: if doc.text is None: doc.text = chunk.word else: doc.text += chunk.word result = ET.tostring(doc, encoding='utf-8').decode('utf-8') result = html5lib.serialize( html5lib.parseFragment(result), sanitize=True, quote_attr_values="always") return result def _resolve_dependency(self, chunks): """Resolves chunk dependency by concatenating them. Args: chunks: a chink list. (ChunkList) Returns: A chunk list. (ChunkList) """ chunks = self._concatenate_inner(chunks, True) chunks = self._concatenate_inner(chunks, False) return chunks def _concatenate_inner(self, chunks, direction): """Concatenates chunks based on each chunk's dependency. Args: direction: Direction of concatenation process. True for forward. (bool) Returns: A chunk list. (ChunkList) """ tmp_bucket = [] source_chunks = chunks if direction else chunks[::-1] target_chunks = ChunkList() for chunk in source_chunks: if ( # if the chunk has matched dependency, do concatenation. chunk.dependency == direction or # if the chunk is SPACE, concatenate to the previous chunk. (direction == False and chunk.is_space()) ): tmp_bucket.append(chunk) continue tmp_bucket.append(chunk) if not direction: tmp_bucket = tmp_bucket[::-1] new_word = ''.join([tmp_chunk.word for tmp_chunk in tmp_bucket]) chunk.update_word(new_word) target_chunks.append(chunk) tmp_bucket = [] if tmp_bucket: target_chunks += tmp_bucket return target_chunks if direction else target_chunks[::-1] def _insert_breakline(self, chunks): """Inserts a breakline instead of a trailing space if the chunk is in CJK. Args: chunks: a chunk list. (ChunkList) Returns: A chunk list. (ChunkList) """ target_chunks = ChunkList() for chunk in chunks: if chunk.word[-1] == ' ' and chunk.has_cjk(): chunk_to_add = Chunk( chunk.word[:-1], chunk.pos, chunk.label, chunk.dependency) target_chunks.append(chunk_to_add) target_chunks.append(chunk.breakline()) else: target_chunks.append(chunk) return target_chunks def _get_annotations(self, text, language='', encoding='UTF32'): """Returns the list of annotations from the given text.""" body = { 'document': { 'type': 'PLAIN_TEXT', 'content': text, }, 'features': { 'extract_syntax': True, }, 'encodingType': encoding, } if language: body['document']['language'] = language request = self.service.documents().annotateText(body=body) response = request.execute() tokens = response.get('tokens', []) language = response.get('language') return tokens, language def _get_entities(self, text, language='', encoding='UTF32'): """Returns the list of annotations from the given text.""" body = { 'document': { 'type': 'PLAIN_TEXT', 'content': text, }, 'encodingType': encoding, } if language: body['document']['language'] = language request = self.service.documents().analyzeEntities(body=body) response = request.execute() result = [] for entity in response.get('entities', []): mentions = entity.get('mentions', []) if not mentions: continue entity_text = mentions[0]['text'] offset = entity_text['beginOffset'] for word in entity_text['content'].split(): result.append({'content': word, 'beginOffset': offset}) offset += len(word) return result
33.625678
81
0.645012
2,348
18,595
5.002129
0.202726
0.013027
0.009366
0.014474
0.192337
0.134951
0.115028
0.079183
0.079183
0.079183
0
0.009344
0.251788
18,595
552
82
33.686594
0.834831
0.370046
0
0.227119
0
0
0.076359
0.002624
0
0
0
0
0
1
0.091525
false
0.00678
0.044068
0.00339
0.237288
0.00678
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
97c0da1f40fc823b2243e9c93e971592b96efa4c
318
py
Python
backend/api/admin.py
steviemsiy/FindTheGame
f4a86a38c8133089778735f34b04f9ce6b084c48
[ "MIT" ]
null
null
null
backend/api/admin.py
steviemsiy/FindTheGame
f4a86a38c8133089778735f34b04f9ce6b084c48
[ "MIT" ]
null
null
null
backend/api/admin.py
steviemsiy/FindTheGame
f4a86a38c8133089778735f34b04f9ce6b084c48
[ "MIT" ]
null
null
null
from django.contrib import admin #if ENVIRONMENT == 'PROD': # from api.models import * #else: from api.models import * # Register your models here. admin.site.register(Event, EventAdmin) admin.site.register(ApiKey, ApiKeyAdmin) admin.site.register(PlayerProfile) admin.site.register(Group) admin.site.register(Game)
22.714286
40
0.779874
43
318
5.767442
0.511628
0.181452
0.342742
0.153226
0
0
0
0
0
0
0
0
0.100629
318
13
41
24.461538
0.867133
0.257862
0
0
0
0
0
0
0
0
0
0
0
1
0
true
0
0.285714
0
0.285714
0
0
0
0
null
0
1
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
1
0
0
0
0
0
0
2
97c0f0316a610972e2430f4b0813c029c750b789
1,456
py
Python
lpd/callbacks/collect_outputs.py
RoySadaka/lpd
921454d9730d8228f4b0ca5349b0558ebd123c65
[ "MIT" ]
4
2020-10-02T10:04:19.000Z
2022-01-19T12:45:02.000Z
lpd/callbacks/collect_outputs.py
RoySadaka/lpd
921454d9730d8228f4b0ca5349b0558ebd123c65
[ "MIT" ]
1
2020-10-06T17:43:57.000Z
2020-10-06T17:47:43.000Z
lpd/callbacks/collect_outputs.py
RoySadaka/lpd
921454d9730d8228f4b0ca5349b0558ebd123c65
[ "MIT" ]
1
2020-10-03T17:21:32.000Z
2020-10-03T17:21:32.000Z
from lpd.enums import Phase, State from lpd.callbacks.callback_base import CallbackBase from lpd.callbacks.callback_context import CallbackContext from typing import Union, List class CollectOutputs(CallbackBase): """ This callback will collect outputs per each state, (it is currently used in trainer.predict() method.) It will collect the numpy outputs in the defined states to a dictionary (state->outputs) Methods: get_outputs_for_state - for a given state, returns the collected outputs Args: apply_on_phase - see in CallbackBase apply_on_states - see in CallbackBase """ def __init__(self, apply_on_phase: Phase, apply_on_states: Union[State, List[State]]): super(CollectOutputs, self).__init__(apply_on_phase, apply_on_states) self.state_to_outputs = {} def get_outputs_for_state(self, state: State): return [data.cpu().numpy() for data in self.state_to_outputs[state]] def __call__(self, callback_context: CallbackContext): c = callback_context #READABILITY DOWN THE ROAD state = c.trainer_state if self.should_apply_on_state(c): if state not in self.state_to_outputs: self.state_to_outputs[state] = [] last_outputs = c.trainer._last_data[state].outputs.data self.state_to_outputs[state].append(last_outputs)
37.333333
110
0.677885
187
1,456
5
0.347594
0.052406
0.058824
0.096257
0.097326
0
0
0
0
0
0
0
0.249313
1,456
38
111
38.315789
0.855444
0.270604
0
0
0
0
0
0
0
0
0
0
0
1
0.15
false
0
0.2
0.05
0.45
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
97c13a11e20c33272886d8a9d47cf19a001f5c55
107
py
Python
api/constants.py
python-discord/code-jam-management
b6b91357f0afa69f875336917a72ea771eb13556
[ "MIT" ]
6
2021-06-07T17:29:23.000Z
2022-02-25T23:36:16.000Z
api/constants.py
python-discord/code-jam-management
b6b91357f0afa69f875336917a72ea771eb13556
[ "MIT" ]
4
2021-09-04T13:53:40.000Z
2021-12-30T23:13:59.000Z
api/constants.py
python-discord/code-jam-management
b6b91357f0afa69f875336917a72ea771eb13556
[ "MIT" ]
2
2021-06-07T17:18:15.000Z
2021-06-14T19:32:33.000Z
from decouple import config DATABASE_URL = config("DATABASE_URL") LOG_LEVEL = config("LOG_LEVEL", "INFO")
21.4
39
0.766355
15
107
5.2
0.6
0.358974
0.435897
0
0
0
0
0
0
0
0
0
0.11215
107
4
40
26.75
0.821053
0
0
0
0
0
0.233645
0
0
0
0
0
0
1
0
false
0
0.333333
0
0.333333
0
1
0
0
null
1
1
0
0
0
0
0
0
0
0
0
0
0
1
0
0
0
0
0
0
0
0
0
0
null
0
0
0
0
0
0
0
0
1
0
0
0
0
5
97c42e24a090f424ea4838812d93847accbf8363
15,022
py
Python
snakebot.py
paulolima18/Snake_Python
f872f374c573963b4347333e4a2099a8956c9de4
[ "MIT" ]
null
null
null
snakebot.py
paulolima18/Snake_Python
f872f374c573963b4347333e4a2099a8956c9de4
[ "MIT" ]
null
null
null
snakebot.py
paulolima18/Snake_Python
f872f374c573963b4347333e4a2099a8956c9de4
[ "MIT" ]
null
null
null
'Game1' ''' x.type são os seguintes (Tudo em Capslock) quit atctiveevent keydown keyup mousemotion mousebuttonup mousebuttondown videioresize ''' #40pygame import pygame_textinput import pygame import random width=800 height=600 bsize=20 thick=20 fps=60 direction = 270 wall = 10 pygame.init() gdisplay=pygame.display.set_mode((width,height)) pygame.display.update() pygame.display.set_caption('SNAKE PL') colors={'red':(128,0,0),'black':(0,0,0),'white':(255,255,255),'green':(0,155,0),'blue':(0,0,155),'yellow':(255,170,0),'darkblue':(51,102,204),'darkgreen':(51,102,0), 'violet':(102,0,102),'brown':(77,38,0),'pink':(255,204,255)} 'music = pygame.mixer.Sound('')' def music1(): pygame.mixer.music.stop() pygame.mixer.music.load('assets/music/reloaded.ogg') pygame.mixer.music.play(-1) def music2(): pygame.mixer.music.stop() pygame.mixer.music.load('assets/music/lionel.ogg') pygame.mixer.music.play(-1) def music3(): pygame.mixer.music.stop() pygame.mixer.music.load('assets/music/lana.ogg') pygame.mixer.music.play() def music4(): pygame.mixer.music.stop() pygame.mixer.music.load('assets/music/george.ogg') pygame.mixer.music.play() icon = pygame.image.load('assets/img/s32.png') snakepng = pygame.image.load('assets/img/snakehead20.png') applepng = pygame.image.load('assets/img/apple20.png') pygame.display.set_icon(icon) textinput = pygame_textinput.TextInput() clock=pygame.time.Clock() smallfont = pygame.font.SysFont('impact', 30) medfont = pygame.font.SysFont('impact', 60) largefont = pygame.font.SysFont('impact', 90) introfont = pygame.font.SysFont('Impact', 150) def snake(bsize,snakelist,x): head = pygame.transform.rotate(snakepng,direction) gdisplay.blit(head, (snakelist[-1][0], snakelist[-1][1])) for xy in snakelist[:-1]: pygame.draw.rect(gdisplay,colors['green'],[xy[0],xy[1],bsize,bsize]) def text_objetcts(text,color,size): textsurface = size.render(text, True,color) return textsurface, textsurface.get_rect() def msm(msg,color,change=0,size=medfont): text1,text2 = text_objetcts(msg,color,size) text2.center = (width/2),((height/2)+change) gdisplay.blit(text1,text2) def score(score): text = smallfont.render('Score: ' + str(score), True, colors['black']) gdisplay.blit(text,(bsize,bsize)) def pause(): pause = True pygame.mixer.music.pause() gdisplay.fill(colors['darkblue']) msm('PAUSE',colors['black'],-100,largefont) msm('(C) to Continue (Q) to Quit',colors['black'],0,smallfont) msm('New music press from (1 to 4)',colors['black'],50,smallfont) pygame.display.update() while pause: for event in pygame.event.get(): if event.type == pygame.QUIT: pygame.quit() quit() if event.type == pygame.KEYDOWN: if event.key == pygame.K_q: pygame.quit() quit() if event.key == pygame.K_c: pygame.mixer.music.unpause() pause = False if event.key == pygame.K_1: music1() if event.key == pygame.K_2: music2() if event.key == pygame.K_3: music3() if event.key == pygame.K_4: music4() clock.tick(5) def introg(): music1() pygame.display.update() intro = True while intro: gdisplay.fill(colors['darkgreen']) msm("SNAKE PL",colors['violet'],-100,introfont) msm('Simple Snake Game', colors['black'],0,smallfont) msm('Press (S) to Start (P) to Pause (Q) to Quit',colors['blue'],height/2-100,smallfont) pygame.display.update() clock.tick(fps) for event in pygame.event.get(): if event.type == pygame.KEYDOWN: if event.key == pygame.K_s: intro = False gameloop() if event.key == pygame.QUIT: pygame.quit() quit() if event.key == pygame.K_q: pygame.quit() quit() def inputed(): inpute = True while inpute: gdisplay.fill(colors['darkblue']) msm('|Place Player Name|',colors['yellow'],0,largefont) events = pygame.event.get() for event in events: if event.type == pygame.QUIT: pygame.quit() quit() if event.type == pygame.KEYDOWN: if event.key == pygame.K_RETURN: return textinput.get_text() inpute = False # Feed it with events every frame textinput.update(events) # Blit its surface onto the screen gdisplay.blit(textinput.get_surface(), (10, 10)) pygame.display.update() clock.tick(30) def topscore(score,name): eva = True pre = ["?","meh"] pos = ["crazy","veryStack"] listz = [] while eva: with open('db/topscore.txt','r') as fd: lines = [x.split() for x in fd.readlines()] check = False for line in lines: if (score > int(line[1]) ) and (not check): #Save current value pre[0] = line[0] pre[1] = line[1] #Insert New score line[1] = score line[0] = name listz.append(line) check = True elif check: #Position Value pos[0] = line[0] pos[1] = line[1] #Player that got downgraded line[1] = pre[1] line[0] = pre[0] #Player that will get downgraded pre[0] = pos[0] pre[1] = pos[1] listz.append(line) else: listz.append(line) x = [x for x in listz] with open('db/topscore.txt','w') as fd: for i in range(len(x)): if i == 0: fd.write('%s %s\n'%(x[i][0],x[i][1])) elif 0<i<9: fd.write('%s %s\n'%(x[i][0],x[i][1])) elif i == 9: fd.write('%s %s'%(x[i][0],x[i][1])) eva = False '''fd = open('top10.txt',a) 'Nome de Jogador | score ' fd.close() ''' def final(): fin = True while fin: with open('db/topscore.txt','r') as fd: lines = [line.split() for line in fd.readlines()] gdisplay.fill(colors['darkblue']) msm('TOP SCORES',colors['yellow'],-250,medfont) msm(str('%s:%s'%(lines[0][0],lines[0][1])),colors['black'],-200,smallfont) msm(str('%s:%s'%(lines[1][0],lines[1][1])),colors['black'],-150,smallfont) msm(str('%s:%s'%(lines[2][0],lines[2][1])),colors['black'],-100,smallfont) msm(str('%s:%s'%(lines[3][0],lines[3][1])),colors['black'],-50,smallfont) msm(str('%s:%s'%(lines[4][0],lines[4][1])),colors['black'],0,smallfont) msm(str('%s:%s'%(lines[5][0],lines[5][1])),colors['black'],50,smallfont) msm(str('%s:%s'%(lines[6][0],lines[6][1])),colors['black'],100,smallfont) msm(str('%s:%s'%(lines[7][0],lines[7][1])),colors['black'],150,smallfont) msm(str('%s:%s'%(lines[8][0],lines[8][1])),colors['black'],200,smallfont) msm(str('%s:%s'%(lines[9][0],lines[9][1])),colors['black'],250,smallfont) text = smallfont.render('Q (Quit) B (Start Screen)', True, colors['black']) gdisplay.blit(text,(width-300,height-50)) pygame.display.update() for event in pygame.event.get(): if event.type == pygame.QUIT: pygame.quit() quit() if event.type == pygame.KEYDOWN: if event.key == pygame.K_q: pygame.quit() quit() fin == False if event.key == pygame.K_b: introg() def walls(): left = pygame.draw.rect(gdisplay,colors['pink'],[0,0,wall,height]) right = pygame.draw.rect(gdisplay,colors['pink'],[width-wall,0,wall,height]) up = pygame.draw.rect(gdisplay,colors['pink'],[0,0,width,wall]) down = pygame.draw.rect(gdisplay,colors['pink'],[0,height-wall,width,wall]) def butt(snakelist,snakehead,direction): for i in snakelist[:-1]: if direction == 270: if [snakehead[0]+10.0,snakehead[1]] == i: return True if direction == 90: if [snakehead[0]-10.0,snakehead[1]] == i: return True if direction == 0: if [snakehead[0],snakehead[1]-10.0] == i: return True if direction == 180: if [snakehead[0],snakehead[1]+10.0] == i: return True return False def gameloop(): global direction exitg = False overg = False x_lead=width/2 #incio y_lead=height/2 xclead,yclead=bsize,0 snakehead = [] snakelist = [] snakelen = 1 xapple = int(random.randrange(bsize,width-thick,bsize)) yapple = int(random.randrange(bsize,height-thick,bsize)) while not exitg: while overg == True: gdisplay.fill(colors['darkblue']) msm('GAME OVER',colors['red'],-100,largefont) msm('Press C (Repeat) Q (Quit) B (Music Selection) T (Scores)',colors['yellow'],height/2-100,smallfont) msm('Your score is %d'%(snakelen-1), colors['black'], 50) pygame.display.update() for event in pygame.event.get(): if event.type == pygame.QUIT: exitg = True overg = False if event.type == pygame.KEYDOWN: if event.key == pygame.K_c: gameloop() if event.key == pygame.K_q: exitg = True overg = False if event.key == pygame.K_b: introg() if event.key == pygame.K_t: playername = inputed() topscore(snakelen-1,playername) final() '''if event.key == pygame.K_t: topscore(snakelen-1,playername) ''' if (x_lead > xapple): if direction == 270 and (not butt(snakelist,snakehead,270)):#(right) if (y_lead < yapple) and (not butt(snakelist,snakehead,180)): direction = 180 yclead = bsize xclead = 0 #faker if (y_lead < yapple) and (not butt(snakelist,snakehead,0)): direction = 0 yclead = -bsize xclead = 0 if (y_lead > yapple) and (not butt(snakelist,snakehead,0)): direction = 0 yclead = -bsize xclead = 0 #faker if (y_lead > yapple)and (not butt(snakelist,snakehead,180)): direction = 180 yclead = bsize xclead = 0 elif (not butt(snakelist,snakehead,90)): direction = 90 xclead = -bsize yclead = 0 print(not butt(snakelist,snakehead,90)) if (x_lead < xapple): if direction == 90 and (not butt(snakelist,snakehead,90)):#(left) if (y_lead < yapple) and (not butt(snakelist,snakehead,180)): direction = 180 yclead = bsize xclead = 0 #faker if (y_lead < yapple) and (not butt(snakelist,snakehead,0)): direction = 0 yclead = -bsize xclead = 0 if (y_lead > yapple)and (not butt(snakelist,snakehead,0)): direction = 0 yclead = -bsize xclead = 0 #faker if (y_lead > yapple)and (not butt(snakelist,snakehead,180)): direction = 180 yclead = bsize xclead = 0 elif (not butt(snakelist,snakehead,270)): direction = 270 xclead = bsize yclead = 0 if (x_lead == xapple): if (not butt(snakelist,snakehead,180)) and (y_lead < yapple):#(left) direction = 180 yclead = bsize xclead = 0 elif (not butt(snakelist,snakehead,0)) and (y_lead > yapple): direction = 0 yclead = -bsize xclead = 0 elif (not butt(snakelist,snakehead,90)): direction = 90 yclead = 0 xclead = -bsize elif (not butt(snakelist,snakehead,270)): direction = 270 yclead = 0 xclead = bsize if x_lead > width-wall-bsize or x_lead < wall or y_lead < wall or y_lead > height-wall-bsize: overg = True '''if event.type == pygame.KEYUP: #só move quando pressionado o butão if event.key == pygame.K_RIGHT or event.key == pygame.K_LEFT: xclead = 0 elif event.key == pygame.K_UP or event.key == pygame.K_DOWN: yclear=0 ''' dt = clock.tick(fps) x_lead+=xclead /2 y_lead+=yclead /2 if x_lead+bsize > xapple and x_lead < xapple+thick: if y_lead+bsize > yapple and y_lead < yapple+thick: xapple = int(random.randrange(bsize,width-bsize,bsize)) yapple = int(random.randrange(bsize,height-bsize,bsize)) snakelen+=1 '''for i in colors: gdisplay.fill(colors[i]) pygame.display.update() ''' gdisplay.fill(colors['brown']) gdisplay.blit(applepng,(xapple,yapple)) snakehead = [] snakehead.append(x_lead) snakehead.append(y_lead) snakelist.append(snakehead) if len(snakelist) > snakelen: del snakelist[0] for i in snakelist[:-1]: if snakehead == i: overg = True snake(bsize,snakelist,direction) walls() #gdisplay.fill(colors[''], rect=[x,y,w,h]) score(snakelen-1) pygame.display.update() #pygame.draw.rect(local,cor,[x,y,w,h]) clock.tick(fps) pygame.quit() quit() introg() gameloop()
34.853828
165
0.503462
1,756
15,022
4.274487
0.159453
0.026112
0.039169
0.039968
0.478684
0.384226
0.329869
0.306288
0.277511
0.264988
0
0.042361
0.357276
15,022
430
166
34.934884
0.73506
0.02037
0
0.419825
0
0
0.062491
0.010033
0
0
0
0
0
1
0.046647
false
0
0.008746
0
0.075802
0.002915
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
97c4ceb646afbf2252dacae9ae06cb0ea8c68412
327
py
Python
simplemap/html_render.py
patrick--/simplemap
1c0a9de1a9c2e35b73f3068511b9c17bc389ba50
[ "MIT" ]
126
2015-12-31T17:31:40.000Z
2020-01-21T19:45:27.000Z
simplemap/html_render.py
ptrks/simplemap
1c0a9de1a9c2e35b73f3068511b9c17bc389ba50
[ "MIT" ]
7
2016-01-01T17:10:02.000Z
2018-08-09T08:16:19.000Z
simplemap/html_render.py
ptrks/simplemap
1c0a9de1a9c2e35b73f3068511b9c17bc389ba50
[ "MIT" ]
14
2015-12-31T21:49:29.000Z
2017-09-13T06:19:32.000Z
""" simplemap.html_render ~~~~~~~~~~~~~~~~~~~~~ This module contains everything related to Jinja2 HTML rendering. """ from jinja2 import Undefined class SilentUndefined(Undefined): """ Allow Jinja2 to continue rendering if undefined tag is parsed """ def _fail_with_undefined_error(self, *args, **kwargs): return None
20.4375
70
0.718654
39
327
5.897436
0.794872
0
0
0
0
0
0
0
0
0
0
0.010676
0.140673
327
16
71
20.4375
0.807829
0.529052
0
0
0
0
0
0
0
0
0
0
0
1
0.25
false
0
0.25
0.25
1
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
1
0
0
0
1
1
0
0
3
97c5657c514435f5241d15a78f30c3d6d353de51
487
py
Python
P2.2-Intro Data Science/exercises/lesson_5/aadhaar_generated_quiz/aadhaar_generated_reducer.py
lucasosouza/udacity-data-analysis
2603565cede0c5269ce643584475929f8f2053ce
[ "MIT" ]
null
null
null
P2.2-Intro Data Science/exercises/lesson_5/aadhaar_generated_quiz/aadhaar_generated_reducer.py
lucasosouza/udacity-data-analysis
2603565cede0c5269ce643584475929f8f2053ce
[ "MIT" ]
null
null
null
P2.2-Intro Data Science/exercises/lesson_5/aadhaar_generated_quiz/aadhaar_generated_reducer.py
lucasosouza/udacity-data-analysis
2603565cede0c5269ce643584475929f8f2053ce
[ "MIT" ]
null
null
null
import sys def reducer(): aadhaar_generated = 0 old_key = None #Cycle through the list of key-value pairs emitted #by your mapper, and print out each key once, #along with the total number of Aadhaar generated, #separated by a tab. Assume that the list of key- #value pairs will be ordered by key. Make sure #each key-value pair is formatted correctly! #Here's a sample final key-value pair: "Gujarat\t5.0" # your code here reducer()
28.647059
57
0.679671
77
487
4.272727
0.662338
0.097264
0.054711
0.072948
0.133739
0.133739
0
0
0
0
0
0.008287
0.256674
487
17
58
28.647059
0.900552
0.712526
0
0
1
0
0
0
0
0
0
0.058824
0
1
0.2
false
0
0.2
0
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
1
0
0
0
null
0
0
1
0
0
0
0
0
0
0
0
0
0
2
97c69078a7ae6ebe2e0737e89806854c5deb0cda
3,999
py
Python
src/genie/libs/parser/nxos/tests/ShowIpv6RipRouteVrfAll/cli/equal/golden_output_2_expected.py
balmasea/genieparser
d1e71a96dfb081e0a8591707b9d4872decd5d9d3
[ "Apache-2.0" ]
204
2018-06-27T00:55:27.000Z
2022-03-06T21:12:18.000Z
src/genie/libs/parser/nxos/tests/ShowIpv6RipRouteVrfAll/cli/equal/golden_output_2_expected.py
balmasea/genieparser
d1e71a96dfb081e0a8591707b9d4872decd5d9d3
[ "Apache-2.0" ]
468
2018-06-19T00:33:18.000Z
2022-03-31T23:23:35.000Z
src/genie/libs/parser/nxos/tests/ShowIpv6RipRouteVrfAll/cli/equal/golden_output_2_expected.py
balmasea/genieparser
d1e71a96dfb081e0a8591707b9d4872decd5d9d3
[ "Apache-2.0" ]
309
2019-01-16T20:21:07.000Z
2022-03-30T12:56:41.000Z
expected_output = { 'vrf': { 'default': { 'address_family': { 'ipv4': { 'instance': { 'rip-1': { 'routes': { '2001:10:12:120::/64': { 'best_route': False, 'index': { 1: { 'expire_time': '00:02:58', 'interface': 'Ethernet1/2.120', 'metric': 2, 'next_hop': 'fe80::f816:3eff:fe8f:fbd9', 'tag': 0, }, }, 'next_hops': 1, }, '2001:10:13:120::/64': { 'best_route': True, 'index': { 1: { 'interface': 'Ethernet1/2.120', 'metric': 1, 'next_hop': '2001:10:13:120::3', 'route_type': 'connected', 'tag': 0, }, }, 'next_hops': 0, }, '2001:10:23:120::/64': { 'best_route': True, 'index': { 1: { 'interface': 'Ethernet1/1.120', 'metric': 1, 'next_hop': '2001:10:23:120::3', 'route_type': 'connected', 'tag': 0, }, }, 'next_hops': 0, }, '2001:1:1:1::1/128': { 'best_route': False, 'index': { 1: { 'expire_time': '00:02:58', 'interface': 'Ethernet1/2.120', 'metric': 2, 'next_hop': 'fe80::f816:3eff:fe8f:fbd9', 'tag': 0, }, }, 'next_hops': 1, }, '2001:3:3:3::3/128': { 'best_route': True, 'index': { 1: { 'interface': 'loopback0', 'metric': 1, 'next_hop': '2001:3:3:3::3', 'route_type': 'connected', 'tag': 0, }, }, 'next_hops': 0, }, }, }, }, }, }, }, }, }
47.607143
84
0.15954
170
3,999
3.623529
0.276471
0.019481
0.064935
0.097403
0.831169
0.788961
0.743506
0.668831
0.668831
0.480519
0
0.163836
0.749687
3,999
83
85
48.180723
0.451548
0
0
0.493827
0
0
0.162372
0.012509
0
0
0
0
0
1
0
false
0
0
0
0
0
0
0
0
null
0
0
0
1
1
1
0
0
0
0
0
1
0
0
0
0
1
0
0
0
0
0
0
0
null
0
0
0
0
0
0
0
0
0
0
0
0
0
5
97c76c081c460323a55942e3974a52a93f0623d4
804
py
Python
run_tests.py
scottwittenburg/vcs
5b9f17fb78f7ab186fc0132ab81ada043a7ba348
[ "BSD-3-Clause" ]
11
2018-10-10T03:14:33.000Z
2022-01-05T14:18:15.000Z
run_tests.py
scottwittenburg/vcs
5b9f17fb78f7ab186fc0132ab81ada043a7ba348
[ "BSD-3-Clause" ]
196
2018-03-21T19:44:56.000Z
2021-12-21T21:56:24.000Z
run_tests.py
scottwittenburg/vcs
5b9f17fb78f7ab186fc0132ab81ada043a7ba348
[ "BSD-3-Clause" ]
5
2019-12-09T21:54:45.000Z
2022-03-20T04:22:14.000Z
#!/usr/bin/env python import os import sys import cdat_info class VCSTestRunner(cdat_info.TestRunnerBase): def _prep_nose_options(self): opt = super(VCSTestRunner, self)._prep_nose_options() if self.args.no_vtk_ui: opt += ["-A", "not vtk_ui"] if self.args.vtk is not None: cdat_info.run_command( "conda install -f -y -c {} vtk-cdat".format(self.args.vtk)) return opt test_suite_name = 'vcs' workdir = os.getcwd() runner = VCSTestRunner(test_suite_name, options=["--no-vtk-ui", "--vtk"], options_files=["tests/vcs_runtests.json"], get_sample_data=True, test_data_files_info="share/test_data_files.txt") ret_code = runner.run(workdir) sys.exit(ret_code)
28.714286
75
0.618159
108
804
4.342593
0.527778
0.051173
0.063966
0
0
0
0
0
0
0
0
0
0.258706
804
27
76
29.777778
0.786913
0.024876
0
0
0
0
0.144317
0.061303
0
0
0
0
0
1
0.05
false
0
0.15
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
97c77c550cf0c53433815e5c8467ef4ace730897
1,007
py
Python
pyrl/cli/util.py
jponf/pyrl
1353d59deee2731c509991a6cca90a7b991779bc
[ "Apache-2.0" ]
2
2021-01-25T15:04:45.000Z
2021-11-05T06:15:40.000Z
pyrl/cli/util.py
jponf/pyrl
1353d59deee2731c509991a6cca90a7b991779bc
[ "Apache-2.0" ]
null
null
null
pyrl/cli/util.py
jponf/pyrl
1353d59deee2731c509991a6cca90a7b991779bc
[ "Apache-2.0" ]
null
null
null
# -*- coding: utf-8 -*- import random import six # SciPy Stack import numpy as np # Torch import torch ############################################################################### def initialize_seed(seed): """Initializes the seed of different PRNGs. :param seed: Value to initialize the PRNGs. """ np.random.seed(seed) random.seed(seed) torch.manual_seed(seed) def evaluate(agent, env, max_steps, render): """Evaluates the given agent on an environment. :return: A numpy array with the reward of each step taken by the agent. """ rewards = [] infos = [] done = False state = env.reset() for _ in six.moves.range(max_steps): action = agent.compute_action(state) next_state, reward, done, info = env.step(action) if render: env.render() state = next_state rewards.append(reward) infos.append(info) if done: break return np.array(rewards), infos, done
20.55102
79
0.569017
121
1,007
4.669421
0.504132
0.056637
0.049558
0
0
0
0
0
0
0
0
0.00134
0.259186
1,007
48
80
20.979167
0.756032
0.242304
0
0
0
0
0
0
0
0
0
0
0
1
0.083333
false
0
0.166667
0
0.291667
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
97c97448c31c9699860a83ac252dd71c1be4c6a6
1,522
py
Python
code/src/main/python/mos/blocks/contest_meta_block.py
anonfse/COSAL_Anonymized
709906294fd775131f3e019862bbdd554d83773d
[ "Unlicense" ]
null
null
null
code/src/main/python/mos/blocks/contest_meta_block.py
anonfse/COSAL_Anonymized
709906294fd775131f3e019862bbdd554d83773d
[ "Unlicense" ]
1
2021-11-03T08:28:31.000Z
2021-11-03T08:28:31.000Z
code/src/main/python/mos/blocks/contest_meta_block.py
anonfse/COSAL_Anonymized
709906294fd775131f3e019862bbdd554d83773d
[ "Unlicense" ]
1
2022-03-22T14:24:13.000Z
2022-03-22T14:24:13.000Z
import sys import os sys.path.append(os.path.abspath(".")) sys.dont_write_bytecode = True __author__ = "COSAL" from utils.lib import O class ContestMeta(O): def __init__(self, **kwargs): O.__init__(self, **kwargs) self.submission_id = None self.contest_type = None self.contest_id = None self.problem_id = None self.exec_time = None self.code_size = None def to_bson(self): bson = { "submissionId": self.submission_id } if self.contest_type is not None: bson["contestType"] = self.contest_type if self.contest_id is not None: bson["contestId"] = self.contest_id if self.problem_id is not None: bson["problemId"] = self.problem_id if self.code_size is not None: bson["codeSize"] = self.code_size if self.exec_time is not None: bson["execTime"] = self.exec_time return bson @staticmethod def from_bson(bson): block = ContestMeta() block.submission_id = bson["submissionId"] if "contestType" in bson: block.contest_type = bson["contestType"] if "contestId" in bson: block.contest_id = bson["contestId"] else: block.contest_id = 0 if "problemId" in bson: block.problem_id = bson["problemId"] else: block.problem_id = 0 if "codeSize" in bson: block.code_size = bson["codeSize"] if "execTime" in bson: block.exec_time = bson["execTime"] return block def make_key(self): return "C:%d-P:%d" % (self.contest_id, self.problem_id)
24.548387
59
0.653745
212
1,522
4.485849
0.254717
0.080967
0.047319
0.068349
0.031546
0
0
0
0
0
0
0.001711
0.231932
1,522
61
60
24.95082
0.811805
0
0
0.039216
0
0
0.114398
0
0
0
0
0
0
1
0.078431
false
0
0.058824
0.019608
0.215686
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
97ca9e6d4a2bc51de1e8a75b509fdde60fa6a362
1,312
py
Python
app/Product.py
krishotte/web_sperky
fec2e150c146c69d3b002085407c2cd2d749ec6a
[ "MIT" ]
null
null
null
app/Product.py
krishotte/web_sperky
fec2e150c146c69d3b002085407c2cd2d749ec6a
[ "MIT" ]
null
null
null
app/Product.py
krishotte/web_sperky
fec2e150c146c69d3b002085407c2cd2d749ec6a
[ "MIT" ]
null
null
null
"""Product Model.""" from config.database import Model from orator.orm import belongs_to, belongs_to_many, has_many, has_one class Product(Model): """Product Model.""" __fillable__ = ['name', 'category_id', 'price', 'description', 'image_folder', 'detail', 'note'] @belongs_to('category_id', 'id') def category(self): from app.Product_category import Product_category return Product_category @belongs_to_many() def materials(self): from app.Material import Material return Material @belongs_to_many('products_related', 'product_id', 'related_id') # this somehow magically works - stores Product.id into product_id and related_products[Product].id into related_id def related_products(self): # referenced products from app.Product import Product return Product @belongs_to_many def orders(self): from app.Order import Order return Order @belongs_to def availability(self): from app.Availability import Availability return Availability @has_many def variants(self): from app.Variant import Variant return Variant.order_by('id') @has_one def top_product(self): from app.TopProduct import TopProduct return TopProduct
27.914894
119
0.681402
159
1,312
5.408805
0.301887
0.073256
0.076744
0.037209
0
0
0
0
0
0
0
0
0.233994
1,312
46
120
28.521739
0.855721
0.125
0
0
0
0
0.091549
0
0
0
0
0
0
1
0.21875
false
0
0.28125
0
0.78125
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
1
0
0
0
0
0
0
0
1
97cc531294afb11301fe771674b2ba6517514180
562
py
Python
data/coco_korean/coco_load_image.py
Pixir/Pixir
63a6fc0728403af92eadf188f532f9f41cd9f912
[ "MIT" ]
null
null
null
data/coco_korean/coco_load_image.py
Pixir/Pixir
63a6fc0728403af92eadf188f532f9f41cd9f912
[ "MIT" ]
1
2020-02-10T08:11:23.000Z
2020-02-10T08:11:23.000Z
data/coco_korean/coco_load_image.py
Pixir/Pixir
63a6fc0728403af92eadf188f532f9f41cd9f912
[ "MIT" ]
3
2020-02-09T11:14:33.000Z
2020-04-11T16:10:17.000Z
from PIL import Image import json import numpy as np from tqdm import tqdm with open('../../../coco/MSCOCO_train_val_Korean.json', 'r', encoding='utf-8') as f: info = json.load(f) # print(info[0]['file_path']) img_path = '../../../coco/' img_size = 64 images = np.empty((len(info), img_size, img_size, 3), dtype=np.uint8) for i in tqdm(range(len(info))): img = Image.open(img_path + info[i]['file_path']).convert('RGB') img = img.resize((img_size, img_size)) img_arr = np.array(img) images[i] = img_arr np.save('coco_images.npy', images)
26.761905
84
0.658363
96
562
3.697917
0.489583
0.098592
0.084507
0.078873
0
0
0
0
0
0
0
0.012526
0.147687
562
20
85
28.1
0.728601
0.048043
0
0
0
0
0.166979
0.078799
0
0
0
0
0
1
0
false
0
0.266667
0
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
97ccf40733199c207a29b866cea4353f6edc523b
630
py
Python
programming/udemy/SLLCycle.py
vamsitallapudi/Coderefer-Python-Projects
a7acc682251661e296c64533f4a85d47e6eedda2
[ "Apache-2.0" ]
1
2021-01-03T06:42:58.000Z
2021-01-03T06:42:58.000Z
programming/udemy/SLLCycle.py
vamsitallapudi/Coderefer-Python-Projects
a7acc682251661e296c64533f4a85d47e6eedda2
[ "Apache-2.0" ]
null
null
null
programming/udemy/SLLCycle.py
vamsitallapudi/Coderefer-Python-Projects
a7acc682251661e296c64533f4a85d47e6eedda2
[ "Apache-2.0" ]
null
null
null
class Node: def __init__(self, value): self.value = value self.nextnode = None def cycle_check(node): if not node: return False head = node node = node.nextnode while node: if node == head: return True node = node.nextnode return False if __name__ == '__main__': # CREATE CYCLE LIST a = Node(1) b = Node(2) c = Node(3) a.nextnode = b b.nextnode = c c.nextnode = a # Cycle Here! # CREATE NON CYCLE LIST x = Node(1) y = Node(2) z = Node(3) x.nextnode = y y.nextnode = z print(cycle_check(a))
17.027027
33
0.539683
87
630
3.747126
0.37931
0.07362
0.09816
0
0
0
0
0
0
0
0
0.014888
0.360317
630
36
34
17.5
0.794045
0.080952
0
0.148148
0
0
0.013913
0
0
0
0
0
0
1
0.074074
false
0
0
0
0.222222
0.037037
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
97cea0095c84b4a1f87650614e47111614016fd2
3,619
py
Python
awesome/plugins/other_xsh/__init__.py
Lparksi/bot
8a38953d09436b60e8edff4ebe86bf19fe3b7046
[ "MIT" ]
3
2020-03-31T10:36:31.000Z
2020-04-23T12:01:10.000Z
awesome/plugins/other_xsh/__init__.py
Lparksi/bot
8a38953d09436b60e8edff4ebe86bf19fe3b7046
[ "MIT" ]
1
2020-07-16T14:51:26.000Z
2020-07-30T12:46:55.000Z
awesome/plugins/other_xsh/__init__.py
Lparksi/bot
8a38953d09436b60e8edff4ebe86bf19fe3b7046
[ "MIT" ]
null
null
null
from nonebot import on_command, CommandSession from nonebot import on_natural_language, NLPSession, IntentCommand from jieba import posseg @on_command("sushe", aliases=("宿舍", "寝室"), only_to_me=False) async def sushe(session: CommandSession): if session.event.group_id == 818278353: await session.send("""一般都是6人间,上下铺,桌子一侧排,有空调,另外租(租比较贵,就这两年,跟舍友商量好要不要租)。 男生一般都是十里铺,也就是校外宿舍,当然还有三里屯之类的,就认准在十里铺就好)""") @on_command("sushe_img", aliases=("宿舍照片", "寝室照片"), only_to_me=False) async def suzheimg(session: CommandSession): if session.event.group_id == 818278353: await session.send("""[CQ:image,file=https://s1.ax1x.com/2020/07/27/aPVaff.jpg]""") @on_natural_language(keywords={"宿舍", "寝室"}, only_to_me=False) async def _(session: NLPSession): stripped_msg = session.msg_text.strip() words = posseg.lcut(stripped_msg) for word in words: if word.word == "照片": return IntentCommand(60.0, 'sushe_img') if word.word == "洗澡": return IntentCommand(60.0, 'xizao') return IntentCommand(61.0, 'sushe') @on_command('xizao', aliases="洗澡", only_to_me=False) async def xizao(session: CommandSession): if session.event.group_id == 818278353: await session.send("""男生宿舍有洗澡间,女生在校内澡堂,不过只有2楼可以洗热水澡,需要刷单独洗澡卡,可以好几个人同时洗有问题请联系:[CQ:at,qq=331456218]""") @on_natural_language(keywords="洗澡", only_to_me=False) async def _(session: NLPSession): return IntentCommand(60.0, 'xizao') @on_command("kaixue", only_to_me=False, aliases="开学") async def kaixue(session: CommandSession): if session.event.group_id == 818278353: await session.send("""具体开学时候还未确定,一般9月份,咱学校有病例,估计9月份开不了学,会延期或不开学。 有问题请联系:[CQ:at,qq=331456218]""") @on_natural_language(keywords={"开学"}, only_to_me=False) async def _(session: NLPSession): return IntentCommand(60.0, 'kaixue') @on_command("zuidifen", aliases="最低分", only_to_me=False) async def zuidifen(session: CommandSession): if session.event.group_id == 818278353: await session.send("""按最低分是不能考虑能不能上的,应该以你的专业招生的院校排名和人数拉一个单子,依次累加,根据你的排名来算,你可以问我如何算排名。 有问题请联系:[CQ:at,qq=331456218]""") @on_natural_language(keywords={"最低分", "多少分"}, only_to_me=False) async def _(session: NLPSession): return IntentCommand(60.0, "zuidifen") @on_command("whoisgood", aliases="哪个好", only_to_me=False) async def whoisgood(session: CommandSession): if session.event.group_id == 818278353: await session.send("""河南省近几年大量扩招专升本的学生,说明对专升本学生更加重视,也说明确实对省内本科教育越来越看中,同时也为河南学子争取本科权益。 当然,河南省内本科都差不多,如果考虑普通高考中的普通二本来对比专升本哪个学校好,其实省内院校都一样的,无需纠结,因为都是省内,又不是郑大那种特别好的学校,出门人家看的是学历 有问题请联系:[CQ:at,qq=331456218]""") @on_natural_language(keywords={"哪个好"}, only_to_me=False) async def _(session: NLPSession): return IntentCommand(60.0, "whoisgood") @on_command("yonon", aliases="能不能上", only_to_me=False) async def yonon(session: CommandSession): if session.event.group_id == 818278353: await session.send("[CQ:image,file=https://s1.ax1x.com/2020/07/27/aPnGgf.jpg]") @on_natural_language(keywords={"能不能", "能"}, only_to_me=False) async def _(session: NLPSession): stripped_msg = session.msg_text.strip() words = posseg.lcut(stripped_msg) for word in words: if word.word == "上": return IntentCommand(60.0, "yonon") @on_command("spm", aliases="算排名", only_to_me=False) async def spm(session: CommandSession): if session.event.group_id == 818278353: await session.send("[CQ:image,file=https://s1.ax1x.com/2020/07/27/aPQAde.jpg]") @on_natural_language(keywords={"算排名", "排名"}, only_to_me=False) async def _(session: NLPSession): return IntentCommand(60.0, "spm")
35.480392
109
0.721194
482
3,619
5.253112
0.255187
0.035545
0.047393
0.077014
0.64376
0.597946
0.564771
0.544234
0.516983
0.46248
0
0.053583
0.128489
3,619
102
110
35.480392
0.749207
0
0
0.361111
0
0.041667
0.231492
0.137293
0
0
0
0
0
1
0
false
0
0.041667
0
0.166667
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
97cf3240bc800a83f7619e974f4e80d78228793e
500
py
Python
calculatorapi/calculatorapi_client.py
sufyankhanrao/assignment_7_3_1
4bcf99c3e56f1ef5ae77990f59691f85b0307ff3
[ "MIT" ]
null
null
null
calculatorapi/calculatorapi_client.py
sufyankhanrao/assignment_7_3_1
4bcf99c3e56f1ef5ae77990f59691f85b0307ff3
[ "MIT" ]
null
null
null
calculatorapi/calculatorapi_client.py
sufyankhanrao/assignment_7_3_1
4bcf99c3e56f1ef5ae77990f59691f85b0307ff3
[ "MIT" ]
null
null
null
# -*- coding: utf-8 -*- """ calculatorapi This file was automatically generated by APIMATIC v2.0 ( https://apimatic.io ). """ from calculatorapi.decorators import lazy_property from calculatorapi.configuration import Configuration from calculatorapi.controllers.simple_calculator_controller import SimpleCalculatorController class CalculatorapiClient(object): config = Configuration @lazy_property def simple_calculator(self): return SimpleCalculatorController()
21.73913
93
0.77
48
500
7.916667
0.6875
0.134211
0
0
0
0
0
0
0
0
0
0.007109
0.156
500
22
94
22.727273
0.893365
0.234
0
0
1
0
0
0
0
0
0
0
0
1
0.125
false
0
0.375
0.125
0.875
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
1
0
0
0
null
0
0
0
0
0
0
0
0
1
1
1
0
0
4
97cf4d5a480c01da483d0f38460e002acb1f26fe
3,387
py
Python
fabric_cf/broker/core/broker_kernel.py
fabric-testbed/ActorBase
3c7dd040ee79fef0759e66996c93eeec57c790b2
[ "MIT" ]
null
null
null
fabric_cf/broker/core/broker_kernel.py
fabric-testbed/ActorBase
3c7dd040ee79fef0759e66996c93eeec57c790b2
[ "MIT" ]
null
null
null
fabric_cf/broker/core/broker_kernel.py
fabric-testbed/ActorBase
3c7dd040ee79fef0759e66996c93eeec57c790b2
[ "MIT" ]
null
null
null
#!/usr/bin/env python3 # MIT License # # Copyright (c) 2020 FABRIC Testbed # # Permission is hereby granted, free of charge, to any person obtaining a copy # of this software and associated documentation files (the "Software"), to deal # in the Software without restriction, including without limitation the rights # to use, copy, modify, merge, publish, distribute, sublicense, and/or sell # copies of the Software, and to permit persons to whom the Software is # furnished to do so, subject to the following conditions: # # The above copyright notice and this permission notice shall be included in all # copies or substantial portions of the Software. # # THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR # IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, # FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE # AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER # LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, # OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE # SOFTWARE. # # # Author: Komal Thareja (kthare10@renci.org) from datetime import datetime, timezone from fabric_cf.actor.core.common.constants import Constants from fabric_cf.actor.core.common.exceptions import BrokerException from fabric_cf.actor.core.kernel.broker_query_model_publisher import BrokerQueryModelPublisher from fabric_cf.actor.core.manage.management_utils import ManagementUtils class BrokerKernel: """ Class responsible for starting Broker Periodic; also holds Management Actor """ def __init__(self): from fabric_cf.actor.core.container.globals import GlobalsSingleton self.logger = GlobalsSingleton.get().get_logger() self.broker = GlobalsSingleton.get().get_container().get_actor() self.producer = GlobalsSingleton.get().get_simple_kafka_producer() self.kafka_topic = GlobalsSingleton.get().get_config().get_global_config().get_bqm_config().get( Constants.KAFKA_TOPIC, None) self.publish_interval = GlobalsSingleton.get().get_config().get_global_config().get_bqm_config().get( Constants.PUBLISH_INTERVAL, None) self.last_query_time = None def do_periodic(self): """ Periodically publish BQM to a Kafka Topic to be consumed by Portal """ if self.kafka_topic is not None and self.publish_interval is not None and self.producer is not None: current_time = datetime.now(timezone.utc) if self.last_query_time is None or (current_time - self.last_query_time).seconds > self.publish_interval: bqm = BrokerQueryModelPublisher(broker=self.broker, logger=self.logger, kafka_topic=self.kafka_topic, producer=self.producer) bqm.execute() self.last_query_time = datetime.now(timezone.utc) class BrokerKernelSingleton: __instance = None def __init__(self): if self.__instance is not None: raise BrokerException(msg="Singleton can't be created twice !") def get(self): """ Actually create an instance """ if self.__instance is None: self.__instance = BrokerKernel() return self.__instance get = classmethod(get)
43.423077
117
0.71804
441
3,387
5.371882
0.399093
0.037146
0.025327
0.03588
0.14141
0.079358
0.056564
0.056564
0.056564
0.056564
0
0.002609
0.207854
3,387
78
118
43.423077
0.880358
0.384411
0
0.058824
0
0
0.017
0
0
0
0
0
0
1
0.117647
false
0
0.176471
0
0.441176
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
97d09a3a5d1f3d145292ae525c74f813c38634ca
1,539
py
Python
app/account/migrations/0002_alter_user_options_alter_user_managers_and_more.py
NhatHox23/nhat-inventory-backend
d494d91c9b68a1a441e72d94018be86f07d2141e
[ "MIT" ]
1
2021-12-25T06:54:48.000Z
2021-12-25T06:54:48.000Z
app/account/migrations/0002_alter_user_options_alter_user_managers_and_more.py
NhatHox23/nhat-inventory-backend
d494d91c9b68a1a441e72d94018be86f07d2141e
[ "MIT" ]
null
null
null
app/account/migrations/0002_alter_user_options_alter_user_managers_and_more.py
NhatHox23/nhat-inventory-backend
d494d91c9b68a1a441e72d94018be86f07d2141e
[ "MIT" ]
null
null
null
# Generated by Django 4.0 on 2021-12-17 08:04 from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('account', '0001_initial'), ] operations = [ migrations.AlterModelOptions( name='user', options={}, ), migrations.AlterModelManagers( name='user', managers=[ ], ), migrations.RemoveField( model_name='user', name='date_joined', ), migrations.RemoveField( model_name='user', name='first_name', ), migrations.RemoveField( model_name='user', name='groups', ), migrations.RemoveField( model_name='user', name='is_active', ), migrations.RemoveField( model_name='user', name='is_staff', ), migrations.RemoveField( model_name='user', name='is_superuser', ), migrations.RemoveField( model_name='user', name='last_name', ), migrations.RemoveField( model_name='user', name='user_permissions', ), migrations.RemoveField( model_name='user', name='username', ), migrations.AlterField( model_name='user', name='email', field=models.CharField(max_length=255, unique=True), ), ]
24.046875
64
0.489279
121
1,539
6.066116
0.421488
0.141689
0.177112
0.231608
0.485014
0.485014
0.277929
0
0
0
0
0.022581
0.395712
1,539
63
65
24.428571
0.766667
0.02794
0
0.578947
1
0
0.107764
0
0
0
0
0
0
1
0
false
0
0.017544
0
0.070175
0
0
0
0
null
0
0
1
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
1
0
0
0
null
0
0
0
0
0
0
0
0
0
0
0
0
0
2
8ad8e73f0765a04eca466c875d8845aef87a9bad
372
py
Python
tests/lib/bes/hardware/test_Ftdi.py
reconstruir/bes
82ff54b2dadcaef6849d7de424787f1dedace85c
[ "Apache-2.0" ]
null
null
null
tests/lib/bes/hardware/test_Ftdi.py
reconstruir/bes
82ff54b2dadcaef6849d7de424787f1dedace85c
[ "Apache-2.0" ]
null
null
null
tests/lib/bes/hardware/test_Ftdi.py
reconstruir/bes
82ff54b2dadcaef6849d7de424787f1dedace85c
[ "Apache-2.0" ]
null
null
null
#!/usr/bin/env python #-*- coding:utf-8; mode:python; indent-tabs-mode: nil; c-basic-offset: 2; tab-width: 2 -*- import unittest from bes.hardware.Ftdi import Ftdi class TestFtdi(unittest.TestCase): def test_find_devices(self): devices = Ftdi.find_devices() for device in devices: print('DEVICE: ', device) if __name__ == "__main__": unittest.main()
23.25
90
0.693548
53
372
4.660377
0.716981
0.089069
0
0
0
0
0
0
0
0
0
0.009585
0.158602
372
15
91
24.8
0.779553
0.293011
0
0
0
0
0.061303
0
0
0
0
0
0
1
0.111111
false
0
0.222222
0
0.444444
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
8ad9c64ca58eeecc2c0887b2257ecd48066ce9be
6,097
py
Python
task3.py
Anchorboy/PR_FinalProject
e744723c9c9dd55e6995ae5929eb45f90c70819b
[ "MIT" ]
null
null
null
task3.py
Anchorboy/PR_FinalProject
e744723c9c9dd55e6995ae5929eb45f90c70819b
[ "MIT" ]
null
null
null
task3.py
Anchorboy/PR_FinalProject
e744723c9c9dd55e6995ae5929eb45f90c70819b
[ "MIT" ]
null
null
null
import os import random from itertools import cycle import cv2 import matplotlib.pyplot as plt import numpy as np from scipy import interp from skimage import exposure from skimage.feature import hog from sklearn import metrics from sklearn.decomposition import PCA from sklearn.preprocessing import label_binarize from sklearn.svm import SVC def read_data(): img_size = (200, 200) train_all = [] test_all = [] current_base = os.path.abspath('.') train_path = os.path.join(current_base, "train") test_path = os.path.join(current_base, "test") # read train for dir_name in os.listdir(train_path): dir_path = os.path.join(train_path, dir_name) class_id = int(dir_name) for img_name in os.listdir(dir_path): img_path = os.path.join(dir_path, img_name) img_vec = cv2.imread(img_path, flags=1) # print img_vec.shape # res = cv2.resize(img_vec, (int(img_vec.shape[0]*0.5), int(img_vec.shape[1]*0.5)), interpolation=cv2.INTER_CUBIC) res = cv2.resize(img_vec, img_size, interpolation=cv2.INTER_CUBIC) nor_res = np.zeros_like(res) nor_res = cv2.normalize(src=res, dst=nor_res, alpha=0, beta=1, norm_type=cv2.NORM_MINMAX, dtype=cv2.CV_32F) # print nor_res.shape nor_res = nor_res.reshape(nor_res.shape[0] * nor_res.shape[1] * nor_res.shape[2], ) train_all.append((class_id, nor_res)) # read test for dir_name in os.listdir(test_path): dir_path = os.path.join(test_path, dir_name) class_id = int(dir_name) for img_name in os.listdir(dir_path): img_path = os.path.join(dir_path, img_name) img_vec = cv2.imread(img_path, flags=1) # print img_vec.shape # res = cv2.resize(img_vec, (int(img_vec.shape[0]*0.5), int(img_vec.shape[1]*0.5)), interpolation=cv2.INTER_CUBIC) res = cv2.resize(img_vec, img_size, interpolation=cv2.INTER_CUBIC) nor_res = np.zeros_like(res) nor_res = cv2.normalize(src=res, dst=nor_res, alpha=0, beta=1, norm_type=cv2.NORM_MINMAX, dtype=cv2.CV_32F) nor_res = nor_res.reshape(nor_res.shape[0] * nor_res.shape[1] * nor_res.shape[2], ) test_all.append((class_id, nor_res)) return train_all, test_all def show_hog(img): fd, hog_img = hog(img, orientations=9, pixels_per_cell=(8, 8), cells_per_block=(1, 1), feature_vector=True, visualise=True) h = hog(img, orientations=9, pixels_per_cell=(16, 16), cells_per_block=(3, 3), feature_vector=True, visualise=False) print fd.shape print hog_img.shape print h.shape print hog_img hog_image_rescaled = exposure.rescale_intensity(hog_img, in_range=(0, 0.02)) print hog_image_rescaled cv2.imshow("ori", img) cv2.imshow("hog", hog_image_rescaled) cv2.waitKey() def draw_multi_ROC(y_test, decf, score): y_test_bin = label_binarize(y_test, classes=[(i+1) for i in xrange(n_classes)]) # Compute macro-average ROC curve and ROC area fpr = dict() tpr = dict() roc_auc = dict() for i in range(n_classes): fpr[i], tpr[i], _ = metrics.roc_curve(y_test_bin[:, i], decf[:, i]) roc_auc[i] = metrics.auc(fpr[i], tpr[i]) # Compute micro-average ROC curve and ROC area fpr["micro"], tpr["micro"], _ = metrics.roc_curve(y_test_bin.ravel(), decf.ravel()) roc_auc["micro"] = metrics.auc(fpr["micro"], tpr["micro"]) # First aggregate all false positive rates all_fpr = np.unique(np.concatenate([fpr[i] for i in range(n_classes)])) # Then interpolate all ROC curves at this points mean_tpr = np.zeros_like(all_fpr) # print mean_tpr for i in range(n_classes): # print interp(all_fpr, fpr[i], tpr[i]) mean_tpr += interp(all_fpr, fpr[i], tpr[i]) # Finally average it and compute AUC mean_tpr /= n_classes fpr["macro"] = all_fpr tpr["macro"] = mean_tpr roc_auc["macro"] = metrics.auc(fpr["macro"], tpr["macro"]) # Plot all ROC curves plt.figure(figsize=(20,10)) plt.title("Score: " + str(score)) plt.plot(fpr["micro"], tpr["micro"], label='micro-average ROC curve (area = {0:0.2f})' ''.format(roc_auc["micro"]), color='deeppink', linestyle=':', linewidth=4) plt.plot(fpr["macro"], tpr["macro"], label='macro-average ROC curve (area = {0:0.2f})' ''.format(roc_auc["macro"]), color='navy', linestyle=':', linewidth=4) lw = 2 colors = cycle([ ((round(random.uniform(0.0, 1.0), 2)), (round(random.uniform(0.0, 1.0), 2)), (round(random.uniform(0.0, 1.0), 2))) for i in xrange(n_classes) ]) for i, color in zip(range(n_classes), colors): plt.plot(fpr[i], tpr[i], color=color, lw=lw, label='ROC curve of class {0} (area = {1:0.2f})' ''.format(i, roc_auc[i])) plt.plot([0, 1], [0, 1], 'k--', lw=lw) plt.xlim([0.0, 1.0]) plt.ylim([0.0, 1.05]) plt.xlabel('False Positive Rate') plt.ylabel('True Positive Rate') # plt.title('Some extension of Receiver operating characteristic to multi-class') plt.legend(loc='lower right') if os.path.exists("task3"): os.mkdir("task3") plt.savefig("task3/"+'pca_svm.png') plt.show() # plt.close() if __name__ == "__main__": train_all, test_all = read_data() X_train = [ i[1] for i in train_all ] y_train = [ i[0] for i in train_all ] X_test = [ i[1] for i in test_all ] y_test = [ i[0] for i in test_all ] pca = PCA(n_components=0.95) pca.fit(X_train) X_pca_train = pca.transform(X_train) X_pca_test = pca.transform(X_test) n_classes = len(set(y_train)) svm = SVC() svm.fit(X_pca_train, y_train) predict = svm.predict(X_pca_test) score = svm.score(X_pca_test, y_test) svm.decision_function_shape = "ovr" decf = svm.decision_function(X_pca_test) draw_multi_ROC(y_test, decf, score) # pix_cell += 1
36.951515
135
0.626866
959
6,097
3.779979
0.211679
0.031448
0.014897
0.023172
0.430897
0.413241
0.32469
0.266207
0.266207
0.266207
0
0.027114
0.231753
6,097
165
136
36.951515
0.746798
0.114483
0
0.15
0
0
0.060955
0
0
0
0
0
0
0
null
null
0
0.108333
null
null
0.041667
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
1
0
0
0
0
0
0
0
0
1
8adba14d1116a00200adf306c8aff70161525c2c
6,504
py
Python
pyhdx/fitting_torch.py
sebaztiano/PyHDX
12fc2b5f67200885706226823bd8e1f46e3b5db1
[ "MIT" ]
null
null
null
pyhdx/fitting_torch.py
sebaztiano/PyHDX
12fc2b5f67200885706226823bd8e1f46e3b5db1
[ "MIT" ]
null
null
null
pyhdx/fitting_torch.py
sebaztiano/PyHDX
12fc2b5f67200885706226823bd8e1f46e3b5db1
[ "MIT" ]
null
null
null
import torch.nn as nn import torch.nn.functional as F from torch.optim import SGD import torch as t from scipy import constants import numpy as np import pandas as pd from pyhdx.models import Protein class DeltaGFit(nn.Module): def __init__(self, deltaG): super(DeltaGFit, self).__init__() self.deltaG = deltaG def forward(self, temperature, X, k_int, timepoints): """ # inputs, list of: temperatures: scalar (1,) X (N_peptides, N_residues) k_int: (N_peptides, 1) """ pfact = t.exp(self.deltaG / (constants.R * temperature)) uptake = 1 - t.exp(-t.matmul((k_int / (1 + pfact)), timepoints)) return t.matmul(X, uptake) def estimate_errors(series, deltaG): #todo refactor to data_obj # boolean array to select residues which are exchanging (ie no nterminal resiudes, no prolines, no regions without coverage) bools = series.coverage['exchanges'].to_numpy() r_number = series.coverage.r_number[bools] # Residue number which exchange deltaG = t.tensor(deltaG[bools], dtype=t.float64) tensors = series.get_tensors(exchanges=True) def calc_loss(deltaG_input): criterion = t.nn.MSELoss(reduction='sum') pfact = t.exp(deltaG_input.unsqueeze(-1) / (constants.R * tensors['temperature'])) uptake = 1 - t.exp(-t.matmul((tensors['k_int'] / (1 + pfact)), tensors['timepoints'])) output = t.matmul(tensors['X'], uptake) loss = criterion(output, tensors['uptake']) return loss hessian = t.autograd.functional.hessian(calc_loss, deltaG) hessian_inverse = t.inverse(-hessian) covariance = np.sqrt(np.abs(np.diagonal(hessian_inverse))) #todo return pd series? return Protein({'covariance': covariance, 'r_number': r_number}, index='r_number') class TorchFitResult(object): def __init__(self, fit_object, model, **metadata): self.fit_object = fit_object self.model = model self.metadata = metadata @property def mse_loss(self): """obj:`float`: Losses from mean squared error part of Lagrangian""" mse_loss = self.metadata['mse_loss'][-1] return mse_loss @property def total_loss(self): """obj:`float`: Total loss value of the Lagrangian""" total_loss = self.metadata['total_loss'][-1] return total_loss @property def reg_loss(self): """obj:`float`: Losses from regularization part of Lagrangian""" return self.total_loss - self.mse_loss @property def regularization_percentage(self): """obj:`float`: Percentage part of the total loss that is regularization loss""" return (self.reg_loss / self.total_loss) * 100 @property def deltaG(self): return self.model.deltaG.detach().numpy().squeeze() class TorchSingleFitResult(TorchFitResult): #todo perhaps pass KineticsFitting object (which includes temperature) (yes do then it can also have methods which return inputs) def __init__(self, *args, **kwargs): super(TorchSingleFitResult, self).__init__(*args, **kwargs) #todo refactor series @property def series(self): return self.fit_object @property def temperature(self): return self.series.temperature @property def output(self): out_dict = {} out_dict['r_number'] = self.series.coverage.r_number out_dict['sequence'] = self.series.coverage['sequence'].to_numpy() out_dict['_deltaG'] = self.deltaG out_dict['deltaG'] = out_dict['_deltaG'].copy() out_dict['deltaG'][~self.series.coverage['exchanges']] = np.nan if self.temperature is not None: pfact = np.exp(out_dict['deltaG'] / (constants.R * self.temperature)) out_dict['pfact'] = pfact #todo add possibility to add append series to protein? #todo update order of columns protein = Protein(out_dict, index='r_number') protein_cov = estimate_errors(self.fit_object, self.deltaG) protein = protein.join(protein_cov) return protein def __call__(self, timepoints): """output: Np x Nt array""" #todo fix and tests with t.no_grad(): #tensors = self.series.get_tensors() temperature = t.Tensor([self.temperature]) X = t.Tensor(self.series.coverage.X) # Np x Nr k_int = t.Tensor(self.series.coverage['k_int'].to_numpy()).unsqueeze(-1) # Nr x 1 timepoints = t.Tensor(timepoints).unsqueeze(0) # 1 x Nt inputs = [temperature, X, k_int, timepoints] output = self.model(*inputs) return output.detach().numpy() class TorchBatchFitResult(TorchFitResult): def __init__(self, *args, **kwargs): super(TorchBatchFitResult, self).__init__(*args, **kwargs) @property def output(self): #todo directly create dataframe quantities = ['_deltaG', 'deltaG', 'covariance', 'pfact'] names = [data_obj.name or data_obj.state for data_obj in self.fit_object.data_objs] iterables = [names, quantities] col_index = pd.MultiIndex.from_product(iterables, names=['State', 'Quantity']) output_data = np.zeros((self.fit_object.Nr, self.fit_object.Ns * len(quantities))) g_values = self.deltaG g_values_nan = g_values.copy() g_values_nan[~self.fit_object.exchanges] = np.nan pfact = np.exp(g_values / (constants.R * self.fit_object.temperature[:, np.newaxis])) output_data[:, 0::len(quantities)] = g_values.T output_data[:, 1::len(quantities)] = g_values_nan.T for i, data_obj in enumerate(self.fit_object.data_objs): #todo this could use some pandas i0 = data_obj.coverage.interval[0] - self.fit_object.interval[0] i1 = data_obj.coverage.interval[1] - self.fit_object.interval[0] cov = estimate_errors(data_obj, g_values[i, i0:i1]) # returns a protein? should be series pd_series = cov['covariance'] pd_series = pd_series.reindex(self.fit_object.r_number) output_data[:, 2+i*len(quantities)] = pd_series.to_numpy() output_data[:, 3::len(quantities)] = pfact.T df = pd.DataFrame(output_data, index=self.fit_object.r_number, columns=col_index) return Protein(df) # use multi index df: https://stackoverflow.com/questions/24290495/constructing-3d-pandas-dataframe
36.745763
133
0.64837
835
6,504
4.875449
0.252695
0.033161
0.044706
0.011791
0.0958
0.039794
0.014247
0
0
0
0
0.0078
0.231242
6,504
177
134
36.745763
0.8064
0.164975
0
0.115044
0
0
0.041745
0
0
0
0
0.00565
0
1
0.150442
false
0
0.070796
0.026549
0.371681
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
8adcaaa5e04f3df5fcea316f738bf758a8c1621e
665
py
Python
backend/models.py
FoamyGuy/PyPortal_Signage_System
46515841bdb413b25e97604697901c2ad6ad471e
[ "MIT" ]
1
2022-03-27T20:51:28.000Z
2022-03-27T20:51:28.000Z
backend/models.py
FoamyGuy/PyPortal_Signage_System
46515841bdb413b25e97604697901c2ad6ad471e
[ "MIT" ]
null
null
null
backend/models.py
FoamyGuy/PyPortal_Signage_System
46515841bdb413b25e97604697901c2ad6ad471e
[ "MIT" ]
null
null
null
from django.contrib.auth.models import User from django.db import models import uuid # Create your models here. from django.db.models import CASCADE class Plan(models.Model): name = models.CharField(max_length=128) content_image = models.FileField(upload_to="content", blank=True, default='') content_json = models.JSONField(blank=True, default=dict) user = models.ForeignKey(User, on_delete=CASCADE, null=True, blank=True) uuid = models.UUIDField(default=uuid.uuid4, editable=False) def __str__(self): if self.user: return "{} - {}".format(self.user.username, self.name) else: return self.name
30.227273
81
0.697744
88
665
5.170455
0.545455
0.065934
0.052747
0
0
0
0
0
0
0
0
0.007407
0.18797
665
22
82
30.227273
0.835185
0.03609
0
0
0
0
0.021875
0
0
0
0
0
0
1
0.066667
false
0
0.266667
0
0.866667
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
1
0
0
1
8adf4e176f915ff5864e25390bfbffbbd957feee
179
py
Python
jinja2_error/__init__.py
mumubin/jiaja2_error
f2f2df42ec60a99442f61d480ffbf8c67071a737
[ "MIT" ]
2
2020-06-12T09:50:09.000Z
2021-06-25T16:06:11.000Z
jinja2_error/__init__.py
mumubin/jiaja2_error
f2f2df42ec60a99442f61d480ffbf8c67071a737
[ "MIT" ]
null
null
null
jinja2_error/__init__.py
mumubin/jiaja2_error
f2f2df42ec60a99442f61d480ffbf8c67071a737
[ "MIT" ]
null
null
null
# -*- coding: utf-8 -*- from .jinja2_error import ErrorExtension __author__ = 'Robin Hu' __email__ = 'given.hubin@gmail.com' __version__ = '0.1.0' __all__ = ['ErrorExtension']
17.9
40
0.698324
22
179
4.909091
0.909091
0
0
0
0
0
0
0
0
0
0
0.032468
0.139665
179
10
41
17.9
0.668831
0.117318
0
0
0
0
0.305732
0.133758
0
0
0
0
0
1
0
false
0
0.2
0
0.2
0
1
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
0
1
8ae079fb5cc787087019878ddc15a079fc9ed4df
2,165
py
Python
elements/python/9/14/soln.py
mmcloughlin/problems
6095842ffe007a12ec8c2093850515aa4e046616
[ "MIT" ]
11
2019-02-08T06:54:34.000Z
2021-08-07T18:57:39.000Z
elements/python/9/14/soln.py
mmcloughlin/problems
6095842ffe007a12ec8c2093850515aa4e046616
[ "MIT" ]
1
2019-05-21T08:14:10.000Z
2019-05-21T08:14:10.000Z
elements/python/9/14/soln.py
mmcloughlin/problems
6095842ffe007a12ec8c2093850515aa4e046616
[ "MIT" ]
null
null
null
import collections class MaxQueue(object): """ MaxQueue provides a base queue API and tracks the largest item contained in the queue. """ def __init__(self): self.items = [] self.peaks = [] def enqueue(self, x): self.items.append(x) while len(self.peaks) > 0 and self.peaks[-1] < x: self.peaks.pop(-1) self.peaks.append(x) def dequeue(self): if self.empty(): return None x = self.items.pop(0) if x == self.peaks[0]: self.peaks.pop(0) return x def max(self): return self.peaks[0] if not self.empty() else None def empty(self): return len(self.items) == 0 TimestampValue = collections.namedtuple('TimestampValue', ['timestamp', 'value']) def max_rolling_window(points, window_length): q = MaxQueue() maxima = [] t = 0 tail = 0 head = 0 while t <= points[-1].timestamp: while head < len(points) and points[head].timestamp <= t: q.enqueue(points[head].value) head += 1 while points[tail].timestamp < t - window_length: q.dequeue() tail += 1 maxima.append(TimestampValue( timestamp=t, value=q.max(), )) t += 1 return maxima def test(): """ test example from figure 9.4 """ points = [ 1.3, None, 2.5, 3.7, None, 1.4, 2.6, None, 2.2, 1.7, None, None, None, None, 1.7 ] maxima = [ 1.3, 1.3, 2.5, 3.7, 3.7, 3.7, 3.7, 2.6, 2.6, 2.6, 2.2, 2.2, 1.7, None, 1.7, ] timestamped_points = [] for t, p in enumerate(points): if p is not None: timestamped_points.append(TimestampValue( timestamp=t, value=p, )) results = max_rolling_window(timestamped_points, 3) for t, r in enumerate(results): assert r.timestamp == t assert maxima[t] == r.value print 'pass' def main(): test() if __name__ == '__main__': main()
23.031915
81
0.50485
278
2,165
3.856115
0.266187
0.067164
0.027985
0.011194
0.094216
0.007463
0
0
0
0
0
0.045255
0.367206
2,165
93
82
23.27957
0.737226
0
0
0.057143
0
0
0.019851
0
0
0
0
0
0.028571
0
null
null
0.014286
0.014286
null
null
0.014286
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
1
0
0
0
0
0
0
0
0
1
8ae1bf6090dd889c0f197f2b8a758940dc94c4c9
992
py
Python
migrations/versions/035e7209663c_tags_and_base_with_unique.py
microservice-experiment-flask-0hsn/pocket-ws-flask
e7582a6ebe4b554070f183e43042c87762633085
[ "MIT" ]
null
null
null
migrations/versions/035e7209663c_tags_and_base_with_unique.py
microservice-experiment-flask-0hsn/pocket-ws-flask
e7582a6ebe4b554070f183e43042c87762633085
[ "MIT" ]
null
null
null
migrations/versions/035e7209663c_tags_and_base_with_unique.py
microservice-experiment-flask-0hsn/pocket-ws-flask
e7582a6ebe4b554070f183e43042c87762633085
[ "MIT" ]
null
null
null
"""tags and base with unique Revision ID: 035e7209663c Revises: Create Date: 2022-04-16 11:22:34.040818 """ from alembic import op import sqlalchemy as sa # revision identifiers, used by Alembic. revision = '035e7209663c' down_revision = None branch_labels = None depends_on = None def upgrade(): # ### commands auto generated by Alembic - please adjust! ### op.create_table('tags', sa.Column('id', sa.BigInteger(), nullable=False), sa.Column('created_at', sa.DateTime(), nullable=True), sa.Column('updated_at', sa.DateTime(), nullable=True), sa.Column('user_rel', sa.String(length=64), nullable=True), sa.Column('title', sa.String(length=128), nullable=False), sa.PrimaryKeyConstraint('id'), sa.UniqueConstraint('title', 'user_rel', name='uniq_title_user_rel') ) # ### end Alembic commands ### def downgrade(): # ### commands auto generated by Alembic - please adjust! ### op.drop_table('tags') # ### end Alembic commands ###
26.810811
72
0.680444
129
992
5.139535
0.503876
0.060332
0.063348
0.090498
0.229261
0.229261
0.229261
0.13273
0
0
0
0.054414
0.166331
992
36
73
27.555556
0.747279
0.297379
0
0
0
0
0.134848
0
0
0
0
0
0
1
0.111111
false
0
0.111111
0
0.222222
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
8ae23495524de5ac2aff79dd30996961f889e7e8
486
py
Python
bot/plugins/bongo.py
JastLucy/twitch-chat-bot
df7cde7e4f78d4789c69e63d0920063bf493d1ca
[ "MIT" ]
null
null
null
bot/plugins/bongo.py
JastLucy/twitch-chat-bot
df7cde7e4f78d4789c69e63d0920063bf493d1ca
[ "MIT" ]
null
null
null
bot/plugins/bongo.py
JastLucy/twitch-chat-bot
df7cde7e4f78d4789c69e63d0920063bf493d1ca
[ "MIT" ]
null
null
null
from __future__ import annotations from bot.config import Config from bot.data import command from bot.data import esc from bot.data import format_msg from bot.message import Message @command('!bongo') async def cmd_bongo(config: Config, msg: Message) -> str: _, _, rest = msg.msg.partition(' ') rest = rest.strip() if rest: rest = f'{rest} ' return format_msg( msg, f'awcBongo awcBongo awcBongo {esc(rest)}awcBongo awcBongo awcBongo', )
23.142857
76
0.683128
66
486
4.893939
0.363636
0.108359
0.102167
0.157895
0
0
0
0
0
0
0
0
0.218107
486
20
77
24.3
0.85
0
0
0
0
0
0.160494
0
0
0
0
0
0
1
0
false
0
0.375
0
0.4375
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
1
0
0
0
0
1
8ae264be6fcb91ac2eb22ef29be6e415fafa0087
6,079
py
Python
recline/commands/man_utils.py
NetApp/recline
065d9d90b6f5b63b535a091f14552e4790c26ecc
[ "BSD-3-Clause" ]
4
2020-05-29T22:54:41.000Z
2021-10-03T07:59:07.000Z
recline/commands/man_utils.py
NetApp/recline
065d9d90b6f5b63b535a091f14552e4790c26ecc
[ "BSD-3-Clause" ]
2
2020-08-28T07:39:43.000Z
2021-04-05T12:45:39.000Z
recline/commands/man_utils.py
NetApp/recline
065d9d90b6f5b63b535a091f14552e4790c26ecc
[ "BSD-3-Clause" ]
null
null
null
""" This module holds some utility functions used as part of the man command to format text from CLI commands into consistent man pages that respond to the terminal width. """ import curses from recline.arg_types.positional import Positional from recline.arg_types.remainder import Remainder from recline.commands.cli_command import get_annotation_type def wrapped_string(text, screen_width, prefix=0): """This function will take a string and make sure it can fit within the given screen_width. If the string is too long to fit, it will be broken on word boundaries (specifically the ' ' character) if it can or the word will be split with a '-' character and the second half moved to the next line. If a prefix is given, the line(s) will be prefixed with that many ' ' characters, including any wrapped lines. If the given string includes embeded newline characters, then each line will be evaluated according to the rules above including breaking on word boundaries and injecting a prefix. """ if not text: return '' new_text = '' # if we have multiple paragraphs, then wrap each one as if it were a single line lines = text.split('\n') if len(lines) > 1: for index, line in enumerate(lines): if index > 0: new_text += ' ' * prefix new_text += wrapped_string(line, screen_width, prefix=prefix) + '\n' return new_text.rstrip() if len(text) + prefix < screen_width: return text words = text.split(' ') current_line = '' for word in words: if prefix + len(current_line) + len(word) + 1 < screen_width: # if word fits on line, just add it current_line += word + ' ' else: space_left = screen_width - (prefix + len(current_line)) if space_left < 3 or len(word) - space_left < 3: # if not much room, move whole word to the next line new_text += '%s\n' % current_line.rstrip() current_line = '%s%s ' % (' ' * prefix, word) else: # split the word across lines with a hyphen current_line += word[:space_left - 1] + '-' new_text += current_line.rstrip() + "\n" current_line = ' ' * prefix + word[space_left - 1:] + ' ' new_text += current_line.rstrip() return new_text def generate_help_text(screen_width, command_class): """Generates lines of help text which are formatted using the curses library. The final document resembles a typical Linux-style manpage. See here: https://www.tldp.org/HOWTO/Man-Page/q3.html """ # generate styled man page, one section at a time help_text = [] indent = ' ' # command name and short description help_text.append(('NAME\n', curses.A_BOLD)) help_text.append((indent,)) help_text.append((command_class.name, curses.A_BOLD)) help_text.append((' -- ',)) description = wrapped_string( command_class.docstring.short_description, screen_width, prefix=(len(command_class.name) + len(indent) + 4), ) for line in description.split('\n'): help_text.append(('%s\n' % line,)) help_text.append(('\n',)) # command usage details help_text.append(('SYNOPSIS\n', curses.A_BOLD)) help_text.append((indent,)) description = wrapped_string( command_class.get_command_usage(), screen_width, prefix=len(indent), ) for line in description.split('\n'): help_text.append(('%s\n' % line,)) help_text.append(('\n',)) # command detailed description if command_class.docstring.long_description: help_text.append(('DESCRIPTION\n', curses.A_BOLD)) help_text.append((indent,)) description = wrapped_string( command_class.docstring.long_description, screen_width, prefix=len(indent), ) for line in description.split('\n'): help_text.append(('%s\n' % line,)) help_text.append(('\n',)) # each command parameter with description, constraints, and defaults if command_class.docstring.params: def print_arg(arg): meta = command_class.get_arg_metavar(arg) description = command_class.get_arg_description(arg, indent=None) annotation_type = get_annotation_type(arg) positional = '' if issubclass(annotation_type, (Remainder, Positional)) else '-' arg_name = '' if issubclass(annotation_type, Positional) else '%s ' % arg.name prefix = '%s %s%s%s ' % (indent, positional, arg_name, meta) help_text.append((prefix,)) description = wrapped_string( description, screen_width, prefix=len(prefix) ) for line in description.split('\n'): help_text.append(('%s\n' % line,)) help_text.append(('\n'),) help_text.append(('OPTIONS\n', curses.A_BOLD)) if command_class.required_args: help_text.append((indent,)) help_text.append(('Required:\n', curses.A_UNDERLINE)) for arg in command_class.required_args: print_arg(arg) if command_class.optional_args: help_text.append((indent,)) help_text.append(('Optional:\n', curses.A_UNDERLINE)) for arg in command_class.optional_args: print_arg(arg) # each command example if command_class.docstring.examples: help_text.append(('EXAMPLES\n', curses.A_BOLD)) for example in command_class.docstring.examples: prefix = indent + ' ' help_text.append((indent,)) help_text.append(('%s:' % (example.name), curses.A_UNDERLINE)) help_text.append(('\n%s' % prefix,)) description = wrapped_string( example.description, screen_width, prefix=len(prefix), ) for line in description.split('\n'): help_text.append(('%s\n' % line,)) return help_text
39.474026
92
0.623787
775
6,079
4.730323
0.236129
0.067649
0.10311
0.032733
0.281779
0.259411
0.237861
0.224768
0.195308
0.154392
0
0.002248
0.268136
6,079
153
93
39.732026
0.821758
0.226024
0
0.269231
0
0
0.035251
0
0
0
0
0
0
1
0.028846
false
0
0.038462
0
0.115385
0.028846
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
8ae39804dc5f4ef4b01469e35dccf93770837275
1,759
py
Python
bigml/tests/compare_forecasts_steps.py
pertinkoira/python
c486060f7f7c79ef9f48ced567f118ac7aae3f84
[ "Apache-2.0" ]
null
null
null
bigml/tests/compare_forecasts_steps.py
pertinkoira/python
c486060f7f7c79ef9f48ced567f118ac7aae3f84
[ "Apache-2.0" ]
3
2022-03-29T17:54:19.000Z
2022-03-29T17:54:42.000Z
bigml/tests/compare_forecasts_steps.py
pertinkoira/python
c486060f7f7c79ef9f48ced567f118ac7aae3f84
[ "Apache-2.0" ]
null
null
null
# -*- coding: utf-8 -*- # # Copyright 2017-2022 BigML # # 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 json import os from nose.tools import eq_, assert_almost_equal from .world import world, res_filename #@step(r'I create a local forecast for "(.*)"') def i_create_a_local_forecast(step, input_data): input_data = json.loads(input_data) world.local_forecast = world.local_time_series.forecast(input_data) #@step(r'the local forecast is "(.*)"') def the_local_forecast_is(step, local_forecasts): local_forecasts = json.loads(local_forecasts) attrs = ["point_forecast", "model"] for field_id in local_forecasts: forecast = world.local_forecast[field_id] local_forecast = local_forecasts[field_id] eq_(len(forecast), len(local_forecast), "forecast: %s" % forecast) for index in range(len(forecast)): for attr in attrs: if isinstance(forecast[index][attr], list): for pos, item in enumerate(forecast[index][attr]): assert_almost_equal(local_forecast[index][attr][pos], item, places=5) else: eq_(forecast[index][attr], local_forecast[index][attr])
37.425532
77
0.675952
239
1,759
4.824268
0.464435
0.112749
0.073721
0.027754
0.036427
0
0
0
0
0
0
0.010287
0.226265
1,759
46
78
38.23913
0.836885
0.371234
0
0
0
0
0.028493
0
0
0
0
0
0.090909
1
0.090909
false
0
0.181818
0
0.272727
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
8ae58acf089690caafb8cdb5422fc701ad32f66a
2,749
py
Python
application.py
roupenminassian/UTS-DSI-x-Disability-Research-Network
e08378594f09560a477521f22f62a47622e07cdd
[ "MIT" ]
null
null
null
application.py
roupenminassian/UTS-DSI-x-Disability-Research-Network
e08378594f09560a477521f22f62a47622e07cdd
[ "MIT" ]
null
null
null
application.py
roupenminassian/UTS-DSI-x-Disability-Research-Network
e08378594f09560a477521f22f62a47622e07cdd
[ "MIT" ]
null
null
null
import pandas as pd import streamlit as st import openai import os import jsonlines import pickle from rank_bm25 import BM25Okapi openai.organization = "org-eiJyreiRZUtpiu8pm6LIIA8B" openai.api_key = st.secrets['API_KEY'] """ # Data Science Institute x Disability Research Network: A UTS HASS-DSI Research Project The project involves preprocessing textual data from the Royal Commission into "Aged Care Quality and Safety", and "Violence, Abuse, Neglect and Exploitation of People with Disability" and utilising natural language processing (NLP) techniques to improve document search functionality. Initial attempts were made to create a document-fetching algorithm designed to minimise the amount of time a user may spend searching relevant information. Please upload a file in the correct data format below; otherwise you may use an existing, preprocessed file by selecting the below box. """ #Load documents input = st.file_uploader('') if input is None: st.write("Or use sample dataset to try the application") sample = st.checkbox("Download sample data from GitHub") try: if sample: st.markdown("""[download_link](https://gist.github.com/roupenminassian/0a17d0bf8a6410dbb1b9d3f42462c063)""") except: pass else: with open("test_final.txt","rb") as fp:# Unpickling contents = pickle.load(fp) #Preparing model tokenized_corpus = [doc.split(" ") for doc in contents] bm25 = BM25Okapi(tokenized_corpus) user_input = st.text_input('Please Enter a Query:') corpus_selected = st.slider("Select the number of relevant documents to present:", min_value=0, max_value=5, step=1) temperature_selected = st.slider("Set the temperature (controls how much randomness is in the output):", min_value=0.0, max_value=1.0, step=0.05) if user_input is None: st.write('Please enter a query above.') else: tokenized_query = user_input.split(" ") doc_scores = bm25.get_scores(tokenized_query) if st.button('Generate Text'): generated_text = bm25.get_top_n(tokenized_query, contents, n=corpus_selected) for i in range(corpus_selected): st.write(generated_text[i]) GPT_text = openai.Answer.create( search_model="davinci", model="davinci", question=user_input, documents=["test.jsonl"], #file = "file-nYWFf5V4zKtZMv82WyakRZme", examples_context="In 2017, U.S. life expectancy was 78.6 years.", examples=[["What is human life expectancy in the United States?","78 years."]], max_tokens=50, temperature = temperature_selected, stop=["\n", "<|endoftext|>"], ) st.write('GPT-3 Answer: ' + GPT_text['answers'][0])
36.171053
441
0.706075
370
2,749
5.148649
0.52973
0.014698
0.011549
0.013648
0.018898
0
0
0
0
0
0
0.028118
0.19789
2,749
75
442
36.653333
0.835828
0.028738
0
0.042553
0
0
0.282915
0.01407
0
0
0
0
0
1
0
false
0.021277
0.148936
0
0.148936
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
8ae5d110cb00dff54458d2c48b5bb3d0525b7694
2,468
py
Python
examples/tour_examples/bootstrap_xkcd_tour.py
chau11ece/GitStudy
d2f1130d529ec99e3a08878dba7af41f2a08e27d
[ "MIT" ]
null
null
null
examples/tour_examples/bootstrap_xkcd_tour.py
chau11ece/GitStudy
d2f1130d529ec99e3a08878dba7af41f2a08e27d
[ "MIT" ]
null
null
null
examples/tour_examples/bootstrap_xkcd_tour.py
chau11ece/GitStudy
d2f1130d529ec99e3a08878dba7af41f2a08e27d
[ "MIT" ]
null
null
null
from seleniumbase import BaseCase class MyTestClass(BaseCase): def test_bootstrap_tour(self): self.open("https://xkcd.com/1117/") self.assert_element('img[alt="My Sky"]') self.create_bootstrap_tour() self.add_tour_step("Welcome to XKCD!") self.add_tour_step("This is the XKCD logo.", "#masthead img") self.add_tour_step("Here's the daily webcomic.", "#comic img") self.add_tour_step("This is the title.", "#ctitle", alignment="top") self.add_tour_step("Click here for the next comic.", 'a[rel="next"]') self.add_tour_step("Click here for the previous one.", 'a[rel="prev"]') self.add_tour_step("Learn about the author here.", 'a[rel="author"]') self.add_tour_step("Click for a random comic.", 'a[href*="/random/"]') self.add_tour_step("Thanks for taking this tour!") self.export_tour(filename="bootstrap_xkcd_tour.js") # Exports the tour self.play_tour() # Plays the tour @pytest.fixture def default_context(self): return {"extra_context": {}} @pytest.fixture( params=[ {"author": "alice"}, {"project_slug": "helloworld"}, {"author": "bob", "project_slug": "foobar"}, ] ) def extra_context(request): return {"extra_context": request.param} @pytest.fixture(params=["default", "extra"]) def context(request): if request.param == "default": return request.getfuncargvalue("default_context") else: return request.getfuncargvalue("extra_context") def test_generate_project(cookies, context): """Call the cookiecutter API to generate a new project from a template. """ result = cookies.bake(extra_context=context) assert result.exit_code == 0 assert result.exception is None assert result.project.isdir() @pytest.mark.parametrize( "test_input,expected", [ ("3+5", 8), pytest.param("1+7", 8, marks=pytest.mark.basic), pytest.param("2+4", 6, marks=pytest.mark.basic, id="basic_2+4"), pytest.param( "6*9", 42, marks=[pytest.mark.basic, pytest.mark.xfail], id="basic_6*9" ), ], ) def test_eval(self, test_input, expected): assert eval(test_input) == expected # studying git branching & merging # chautran: git checkout v1.0.24
36.294118
87
0.603728
306
2,468
4.722222
0.398693
0.043599
0.068512
0.093426
0.1391
0.07474
0.07474
0.041522
0
0
0
0.014154
0.255673
2,468
67
88
36.835821
0.772455
0.066856
0
0
0
0
0.246377
0.009662
0
0
0
0
0.09434
1
0.113208
false
0
0.018868
0.037736
0.226415
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
8ae89e6b4029a557bbcd06a8ce74401ad918eb08
899
py
Python
tests/strawpoll_api_reader_tests.py
vaibhav-y/py-strawpoll
d725beb9a0e42ced84f9ae648bdf8a7216bd6e55
[ "MIT" ]
null
null
null
tests/strawpoll_api_reader_tests.py
vaibhav-y/py-strawpoll
d725beb9a0e42ced84f9ae648bdf8a7216bd6e55
[ "MIT" ]
1
2016-05-12T21:25:09.000Z
2016-07-20T08:58:57.000Z
tests/strawpoll_api_reader_tests.py
vaibhav-y/py-strawpoll
d725beb9a0e42ced84f9ae648bdf8a7216bd6e55
[ "MIT" ]
null
null
null
from strawpoll import StrawpollAPIReader from random import randrange import requests # Setup test fixtures for poll id `id` id = randrange(1, 1000) BASE_URL = 'https://strawpoll.me' API_PATH = 'api/v2/polls' json = requests.get('/'.join([BASE_URL, API_PATH, str(id)])) sp = dict(json=json.text, api=StrawpollAPIReader.from_apiv2(id), url=StrawpollAPIReader.from_url('/'.join([BASE_URL, str(id)]))) # I feel these are redundant since we only need to test URL vs JSON # to actually verify if everything is working due to how this is layered def test_json_and_api_return_same_data(): assert(StrawpollAPIReader.from_json(sp['json']) == sp['api']) # @with_setup(setup, teardown) def test_api_and_url_return_same_data(): assert(sp['api'] == sp['url']) # @with_setup(setup, teardown) def test_json_and_url_return_same_data(): assert(StrawpollAPIReader.from_json(sp['json']) == sp['url'])
35.96
128
0.74416
140
899
4.571429
0.428571
0.171875
0.065625
0.09375
0.309375
0.309375
0.16875
0.16875
0.16875
0.16875
0
0.008827
0.117909
899
24
129
37.458333
0.798235
0.256952
0
0
0
0
0.081571
0
0
0
0
0
0.214286
1
0.214286
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
1
0
0
0
0
0
0
0
1
8ae9058fefadf30c0326f4f63c43379b31ae9689
9,267
py
Python
src/tests/functional/test_entry_data_endpoint.py
jroberts07/fpl-stats-api
3a7b5faacec5f83643a16143000b46bea70b5364
[ "MIT" ]
null
null
null
src/tests/functional/test_entry_data_endpoint.py
jroberts07/fpl-stats-api
3a7b5faacec5f83643a16143000b46bea70b5364
[ "MIT" ]
7
2019-09-08T21:46:14.000Z
2019-12-23T15:06:53.000Z
src/tests/functional/test_entry_data_endpoint.py
jroberts07/fpl_stats_api
3a7b5faacec5f83643a16143000b46bea70b5364
[ "MIT" ]
null
null
null
from aioresponses import aioresponses from server import app as sanic_app async def test_success_multiple_classics(test_cli): """Test entry data with an array of classic leagues. Args: test_cli (obj): The test event loop. """ with aioresponses(passthrough=['http://127.0.0.1:']) as m: with open( 'tests/functional/data/' 'entry_response_multiple_classic_leagues.json' ) as f: entry_data = f.read() with open( 'tests/functional/data/' 'league_response_less_than_fifty.json' ) as f: league_data = f.read() m.get( sanic_app.config.FPL_URL + sanic_app.config.ENTRY_DATA.format( entry_id=123 ), status=200, body=entry_data ) m.get( sanic_app.config.FPL_URL + sanic_app.config.LEAGUE_DATA.format( league_id=1 ), status=200, body=league_data ) m.get( sanic_app.config.FPL_URL + sanic_app.config.LEAGUE_DATA.format( league_id=2 ), status=200, body=league_data ) resp = await test_cli.get( '/entry_data/123?player_cookie=456' ) assert resp.status == 200 resp_json = await resp.json() assert resp_json == { "name": "TEAM A", "leagues": [ { "id": 1, "name": "LEAGUE A", }, { "id": 2, "name": "LEAGUE B", } ] } async def test_success_multiple_classics_some_more_than_fifty(test_cli): """Test entry data with an array of classic leagues some with more than fifty entries. Args: test_cli (obj): The test event loop. """ with aioresponses(passthrough=['http://127.0.0.1:']) as m: with open( 'tests/functional/data/' 'entry_response_multiple_classic_leagues.json' ) as f: entry_data = f.read() with open( 'tests/functional/data/' 'league_response_less_than_fifty.json' ) as f: league_data_less_than_fifty = f.read() with open( 'tests/functional/data/' 'league_response_more_than_fifty.json' ) as f: league_data_more_than_fifty = f.read() m.get( sanic_app.config.FPL_URL + sanic_app.config.ENTRY_DATA.format( entry_id=123 ), status=200, body=entry_data ) m.get( sanic_app.config.FPL_URL + sanic_app.config.LEAGUE_DATA.format( league_id=1 ), status=200, body=league_data_less_than_fifty ) m.get( sanic_app.config.FPL_URL + sanic_app.config.LEAGUE_DATA.format( league_id=2 ), status=200, body=league_data_more_than_fifty ) resp = await test_cli.get( '/entry_data/123?player_cookie=456' ) assert resp.status == 200 resp_json = await resp.json() assert resp_json == { "name": "TEAM A", "leagues": [ { "id": 1, "name": "LEAGUE A", } ] } async def test_league_api_bad_response(test_cli): """Test entry data with a bad response from league API. Args: test_cli (obj): The test event loop. """ with aioresponses(passthrough=['http://127.0.0.1:']) as m: with open( 'tests/functional/data/' 'entry_response_single_classic_league.json' ) as f: entry_data = f.read() with open( 'tests/functional/data/' 'bad_response.json' ) as f: league_data = f.read() m.get( sanic_app.config.FPL_URL + sanic_app.config.ENTRY_DATA.format( entry_id=123 ), status=200, body=entry_data ) m.get( sanic_app.config.FPL_URL + sanic_app.config.LEAGUE_DATA.format( league_id=1 ), status=200, body=league_data ) resp = await test_cli.get( '/entry_data/123?player_cookie=456' ) assert resp.status == 500 resp_json = await resp.json() assert resp_json == { "error": "THERE WAS A PROBLEM WITH THE DATA RETURNED FROM FPL" } async def test_success_single_classics(test_cli): """Test entry data with a single classic league. Args: test_cli (obj): The test event loop. """ with aioresponses(passthrough=['http://127.0.0.1:']) as m: with open( 'tests/functional/data/' 'entry_response_single_classic_league.json' ) as f: entry_data = f.read() with open( 'tests/functional/data/' 'league_response_less_than_fifty.json' ) as f: league_data = f.read() m.get( sanic_app.config.FPL_URL + sanic_app.config.ENTRY_DATA.format( entry_id=123 ), status=200, body=entry_data ) m.get( sanic_app.config.FPL_URL + sanic_app.config.LEAGUE_DATA.format( league_id=1 ), status=200, body=league_data ) resp = await test_cli.get( '/entry_data/123?player_cookie=456' ) assert resp.status == 200 resp_json = await resp.json() assert resp_json == { "name": "TEAM A", "leagues": [ { "id": 1, "name": "LEAGUE A", } ] } async def test_no_leagues(test_cli): """Test entry data with no leagues. Args: test_cli (obj): The test event loop. """ with aioresponses(passthrough=['http://127.0.0.1:']) as m: with open( 'tests/functional/data/entry_response_no_leagues.json' ) as f: fpl_data = f.read() m.get( sanic_app.config.FPL_URL + sanic_app.config.ENTRY_DATA.format( entry_id=123 ), status=200, body=fpl_data ) resp = await test_cli.get( '/entry_data/123?player_cookie=456' ) assert resp.status == 200 resp_json = await resp.json() assert resp_json == { "name": "TEAM A", "leagues": [] } async def test_no_name(test_cli): """Test entry data with no name. Args: test_cli (obj): The test event loop. """ with aioresponses(passthrough=['http://127.0.0.1:']) as m: with open( 'tests/functional/data/entry_response_no_name.json' ) as f: entry_data = f.read() with open( 'tests/functional/data/' 'league_response_less_than_fifty.json' ) as f: league_data = f.read() m.get( sanic_app.config.FPL_URL + sanic_app.config.ENTRY_DATA.format( entry_id=123 ), status=200, body=entry_data ) m.get( sanic_app.config.FPL_URL + sanic_app.config.LEAGUE_DATA.format( league_id=1 ), status=200, body=league_data ) resp = await test_cli.get( '/entry_data/123?player_cookie=456' ) assert resp.status == 200 resp_json = await resp.json() assert resp_json == { "name": None, "leagues": [ { "id": 1, "name": "LEAGUE A", } ] } async def test_no_player_cookie(test_cli): """Test entry data with no player_cookie. Args: test_cli (obj): The test event loop. """ resp = await test_cli.get( '/entry_data/123?player_cookie=' ) assert resp.status == 400 resp_json = await resp.json() assert resp_json == { "error": "PARAMETERS REQUIRED: player_cookie" } async def test_fpl_error_response(test_cli): """Test entry data with an error response from FPL. Args: test_cli (obj): The test event loop. """ with aioresponses(passthrough=['http://127.0.0.1:']) as m: m.get( sanic_app.config.FPL_URL + sanic_app.config.ENTRY_DATA.format( entry_id=123 ), status=500, body=None ) resp = await test_cli.get( '/entry_data/123?player_cookie=456' ) assert resp.status == 500 resp_json = await resp.json() assert resp_json == { "error": "ERROR CONNECTING TO THE FANTASY API" }
28.601852
75
0.499838
1,036
9,267
4.243243
0.082046
0.067561
0.089172
0.038217
0.893085
0.881256
0.867152
0.818926
0.812102
0.792539
0
0.033483
0.400561
9,267
323
76
28.690402
0.757876
0
0
0.718045
0
0
0.161897
0.111603
0
0
0
0
0.06015
1
0
false
0.026316
0.007519
0
0.007519
0
0
0
0
null
0
0
0
1
1
1
1
1
1
0
0
0
0
0
0
0
0
0
0
1
0
0
0
0
null
0
0
0
0
0
0
0
0
0
0
0
0
0
7
8aec45c46dd80ffcb2b3b4c997ad5691276264a2
916
py
Python
option/asian.py
Michany/pycing
761c3cd1a887d6a168909abc107c6ea0d80992d3
[ "MIT" ]
null
null
null
option/asian.py
Michany/pycing
761c3cd1a887d6a168909abc107c6ea0d80992d3
[ "MIT" ]
1
2020-02-12T15:12:41.000Z
2020-02-12T15:13:34.000Z
option/asian.py
Michany/pycing
761c3cd1a887d6a168909abc107c6ea0d80992d3
[ "MIT" ]
null
null
null
import numpy as np from ..core.derivative import Derivative class AsianCallOption(Derivative): def __init__(self, S, K, T, r, sigma, steps, **kwargs): super().__init__(S_0=S, T=T, r=r, sigma=sigma, steps=steps, **kwargs) self.S = S self.K = K self.T = T self.r = r self.sigma = sigma def payoff(self, underlyingAssetPath, **kwargs): return max(underlyingAssetPath.mean() - self.K, 0) * np.exp(-self.r * self.T) class AsianPutOption(Derivative): def __init__(self, S, K, T, r, sigma, steps, **kwargs): super().__init__(S_0=S, T=T, r=r, sigma=sigma, steps=steps, **kwargs) self.S = S self.K = K self.T = T self.r = r self.sigma = sigma def payoff(self, underlyingAssetPath, **kwargs): return max(self.K - underlyingAssetPath.mean(), 0) * np.exp(-self.r * self.T)
26.941176
85
0.578603
129
916
3.968992
0.217054
0.039063
0.066406
0.082031
0.71875
0.71875
0.71875
0.65625
0.65625
0.65625
0
0.006033
0.276201
916
33
86
27.757576
0.766214
0
0
0.727273
0
0
0
0
0
0
0
0
0
1
0.181818
false
0
0.090909
0.090909
0.454545
0
0
0
0
null
0
0
0
0
1
1
0
0
1
0
0
0
0
0
0
0
0
0
0
1
0
0
0
0
null
0
0
0
0
0
0
0
0
0
0
0
0
0
4
8aed0fd9be816c87487500edc230255c399c0ca8
8,283
py
Python
PyReQTL/annotate.py
nalomran/PyReQTL
020535e69dfd7ab3c074a3e28cda6cca465672e8
[ "MIT" ]
14
2020-09-23T18:51:41.000Z
2020-10-10T11:22:58.000Z
PyReQTL/annotate.py
nalomran/PyReQTL
020535e69dfd7ab3c074a3e28cda6cca465672e8
[ "MIT" ]
null
null
null
PyReQTL/annotate.py
nalomran/PyReQTL
020535e69dfd7ab3c074a3e28cda6cca465672e8
[ "MIT" ]
null
null
null
#!/usr/bin/env python3 """Annotate the output of ReQTL as cis or trans Created on Aug, 29 2020 @author: Nawaf Alomran This module annotates the output of ReQTL as cis or trans based on whether the SNVs resides within its paired gene. Input + Options ---------------- + -r: the path to the ReQTL analysis result file + -ga: the path to the file gene location annotations + -o: the prefix for the output annotated result Output ------ + a file with the ReQTLs annotated as cis or trans How to Run ---------- python -m PyReQTL.annotate \ -r output/ReQTL_test_all_ReQTLs.txt \ -ga data/gene_locations_hg38.txt \ -o ReQTL_test \ -c True * Python runtime via time command 8.19s user 0.61s system 112% cpu 7.838 total * R time command line 3.15s user 0.22s system 99% cpu 3.383 total * Note that the speed after the importr statements Python is faster than than R """ import argparse import sys from datetime import datetime import numpy as np # type: ignore import pandas as pd # type: ignore import rpy2.robjects.packages as rpackages # type: ignore from rpy2.robjects import pandas2ri # type: ignore from rpy2.robjects.packages import importr # type: ignore try: from common import (create_output_dir, output_filename_generator, bool_conv_args) except ModuleNotFoundError: from PyReQTL.common import (create_output_dir, output_filename_generator, bool_conv_args) # install the R package GenomicFeatures from within Python if not rpackages.isinstalled('GenomicFeatures'): print("installing GenomicFeatures package ...") bioc_manager = rpackages.importr('BiocManager') bioc_manager.install('GenomicFeatures') print("Done installing the package.") # importing the following required R packages to be used within Python print("Kindly wait for the required R packages to be imported into Python...") g_ranges = importr('GenomicRanges') print("GenomicRanges package is imported.") g_alignments = importr('GenomicAlignments') print("GenomicAlignments package is imported.") iranges = importr('IRanges') print("IRanges package is imported.") print("Done importing.") # This needs to be activated in order to perform pandas conversion pandas2ri.activate() def cis_trans_annotator(rqt_rst: str, gene_ann: str, out_prefx: str, cli: bool = False) -> None: """Annotate the output of ReQTL as cis or trans based on whether the SNVs resides within its paired gene Parameter --------- rqt_rst: the path to the ReQTL analysis result file gene_ann: the path to the file gene location annotation out_prefx: the prefix for the output annotated result cli: Whether the function is been executed with the command line. Default is False. Return ------ reqtl_reslt_arranged: dataframe ReQTLs annotated as cis or trans Output ------ - file with the ReQTLs annotated as cis or trans """ start_time = datetime.now() # reading the ReQTL result file from run_matrix_ReQTL reqtl_result = pd.read_table(rqt_rst, sep="\t") # ------------------------------------------------------------------------# # ------------------------------------------------------------------------# # -----------------annotate which gene harbors the snp--------------------# # classify ReQTLs in which the two members of the pair are in the same----# # gene as cis and classify all others as trans----------------------------# # ------------------------------------------------------------------------# # ------------------------------------------------------------------------# reqtl_reslt_arranged = reqtl_result.assign(new_SNP=reqtl_result.SNP) # split them into four columns based on the pattern "[:_>]" reqtl_reslt_arranged = reqtl_reslt_arranged.new_SNP.str.split('[:_>]', expand=True) reqtl_reslt_arranged.columns = ['chrom', 'start', 'ref', 'alt'] # concatenating the re-arranged dataframe with the original dataframe reqtl_reslt_arranged = pd.concat([reqtl_result, reqtl_reslt_arranged], axis=1) # making the new end column the same as the start column reqtl_reslt_arranged = reqtl_reslt_arranged.assign( end=reqtl_reslt_arranged.start) # convert Python Pandas DataFrame to R-dataframe reqtl_result_df_r = pandas2ri.py2rpy(reqtl_reslt_arranged) # read gene location file and then convert to R dataframe gene_locs_py_df = pd.read_table(gene_ann, sep="\t") gene_locs_df_r = pandas2ri.py2rpy(gene_locs_py_df) # storing the location of genomic features for both R dataframes reqtl_reslt_granges_r = g_ranges.GRanges(reqtl_result_df_r) gene_loc_granges_r = g_ranges.GRanges(gene_locs_df_r) # finding the overlap between the ranges overlaps = iranges.findOverlaps(reqtl_reslt_granges_r, gene_loc_granges_r, select="last", type="within") # ignore the Pycharm warning later overlaps = np.where(overlaps == -2147483648, None, overlaps) overlaps = overlaps.tolist() # reindex the gene_locs dataframe by the overlaps genes_snp = gene_locs_py_df.ensembl_gene.reindex(overlaps) reqtl_reslt_arranged['genes_snp'] = pd.Series(genes_snp.values.tolist()) # if genes_snp == gene in reqtl_reslt_arranged dataframe then it cis # otherwise it will be trans reqtl_reslt_arranged['class'] = np.where( reqtl_reslt_arranged.genes_snp == reqtl_reslt_arranged.gene, 'cis', 'trans') reqtl_reslt_arranged.loc[reqtl_reslt_arranged['genes_snp'].isna(), 'class'] = reqtl_reslt_arranged['genes_snp'] # drop the unneeded columns reqtl_reslt_arranged.drop( ['chrom', 'end', 'ref', 'alt', 'start'], axis=1, inplace=True) out_dir = create_output_dir("output") annotated_file = output_filename_generator(out_dir, out_prefx, "_ReQTLs_cistrans_ann.txt") reqtl_reslt_arranged.to_csv(annotated_file, sep="\t", index=False, na_rep='NULL') print(f"\nCis/trans annotated ReQTLs saved in {annotated_file}\n") if cli: print(f"Analysis took after importing the required packages " f"{(datetime.now() - start_time).total_seconds()} sec") else: return reqtl_reslt_arranged def main() -> None: """Parses the command line arguments entered by the user Parameters --------- None Return ------- None """ USAGE = """Annotate the output of ReQTL as cis or trans based on whether the SNV resides within its paired gene""" parser = argparse.ArgumentParser(description=USAGE) parser.add_argument('-r', dest="rqt_rst", required=True, help="the path to the ReQTL analysis result file") parser.add_argument('-ga', dest='gene_ann', required=True, help="the path to the file gene location annotations") parser.add_argument('-o', dest="out_prefx", required=True, help="the prefix for the output annotated result") parser.add_argument("-c", dest="cli", default=False, type=bool_conv_args, help="""Whether the function is been executed with the command line. Default is False!""") args = parser.parse_args() rqt_rst = args.rqt_rst gene_ann = args.gene_ann out_prefx = args.out_prefx cli = args.cli try: cis_trans_annotator(rqt_rst, gene_ann, out_prefx, cli) except KeyboardInterrupt: sys.exit('\nthe user ends the program') if __name__ == '__main__': main()
33
79
0.608234
1,000
8,283
4.859
0.289
0.049393
0.081498
0.017288
0.28051
0.210949
0.190574
0.155999
0.118337
0.095287
0
0.009085
0.269105
8,283
250
80
33.132
0.793525
0.354219
0
0.0625
0
0
0.198422
0.010008
0
0
0
0
0
1
0.017857
false
0
0.178571
0
0.205357
0.080357
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
8aef1e6b611dba02218b5cc706c486dafbea639a
940
py
Python
fx_bmark_extract.py
kiike/scripts
c58386288ff889dd14c91db4487734b294ba3a81
[ "ISC" ]
null
null
null
fx_bmark_extract.py
kiike/scripts
c58386288ff889dd14c91db4487734b294ba3a81
[ "ISC" ]
null
null
null
fx_bmark_extract.py
kiike/scripts
c58386288ff889dd14c91db4487734b294ba3a81
[ "ISC" ]
null
null
null
#!/usr/bin/env python """ Import a Firefox bookmarks file into a single json list """ import json import pprint def walk(struct, depth=0): children = struct.get('children') if children: for child in children: if child.get('type') == 'text/x-moz-place': title = child.get('title') uri = child.get('uri') tags = child.get('tags') if tags: tag_l = [tag for tag in tags.split(',')] else: tag_l = [] out_dict = {'title': title, 'uri': uri, 'tags': tag_l } if out_dict not in my_marks: my_marks.append(out_dict) walk(child) with open("bmarks") as f: my_marks = [] j = json.load(f) walk(j) print(json.dumps(my_marks, indent=2))
24.736842
60
0.453191
109
940
3.816514
0.495413
0.076923
0.038462
0
0
0
0
0
0
0
0
0.003731
0.429787
940
37
61
25.405405
0.772388
0.080851
0
0
0
0
0.068925
0
0
0
0
0
0
1
0.038462
false
0
0.076923
0
0.115385
0.076923
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
8af06ba56b9d9246907fcee08895d969c1f3947a
429
py
Python
hostel/devices/migrations/0003_device_photos.py
phylocko/hostel
ff9fb7eb2d38e8cbe4feb096a07f0c5cea1a5365
[ "Apache-2.0" ]
null
null
null
hostel/devices/migrations/0003_device_photos.py
phylocko/hostel
ff9fb7eb2d38e8cbe4feb096a07f0c5cea1a5365
[ "Apache-2.0" ]
null
null
null
hostel/devices/migrations/0003_device_photos.py
phylocko/hostel
ff9fb7eb2d38e8cbe4feb096a07f0c5cea1a5365
[ "Apache-2.0" ]
1
2020-10-31T17:33:52.000Z
2020-10-31T17:33:52.000Z
# Generated by Django 2.0.5 on 2021-10-05 00:52 from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('common', '0004_photos'), ('devices', '0002_auto_20201017_2132'), ] operations = [ migrations.AddField( model_name='device', name='photos', field=models.ManyToManyField(to='common.Photo'), ), ]
21.45
60
0.589744
45
429
5.511111
0.822222
0
0
0
0
0
0
0
0
0
0
0.113636
0.282051
429
19
61
22.578947
0.691558
0.104895
0
0
1
0
0.185864
0.060209
0
0
0
0
0
1
0
false
0
0.076923
0
0.307692
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
1
0
0
0
null
0
0
0
0
0
0
0
0
0
0
0
0
0
1
8af62ad39d558e0d5a5806871f1e4a6b7a8df43e
194,948
py
Python
src/lib/tracker/multitracker.py
DerryHub/FairMOT-attack
2678cebe939eb8e14106c1e9e07f0c44b5ba975f
[ "MIT" ]
18
2021-11-18T15:38:46.000Z
2022-03-22T07:24:27.000Z
src/lib/tracker/multitracker.py
DerryHub/FairMOT-attack
2678cebe939eb8e14106c1e9e07f0c44b5ba975f
[ "MIT" ]
null
null
null
src/lib/tracker/multitracker.py
DerryHub/FairMOT-attack
2678cebe939eb8e14106c1e9e07f0c44b5ba975f
[ "MIT" ]
1
2021-11-25T03:14:37.000Z
2021-11-25T03:14:37.000Z
# ------------------------------------------------------------------------------ # Copyright (c) Microsoft Corporation. All rights reserved. # Licensed under the MIT License. # ------------------------------------------------------------------------------ from collections import deque import cv2 import numpy as np import torch import torch.nn as nn import torch.nn.functional as F from models import * from models.decode import mot_decode from models.model import create_model, load_model from models.utils import _tranpose_and_gather_feat, _tranpose_and_gather_feat_expand from tracker import matching from tracking_utils.kalman_filter import KalmanFilter from tracking_utils.log import logger from tracking_utils.utils import * from utils.post_process import ctdet_post_process from cython_bbox import bbox_overlaps as bbox_ious from .basetrack import BaseTrack, TrackState from scipy.optimize import linear_sum_assignment import random import pickle import copy class GaussianBlurConv(nn.Module): def __init__(self, channels=3): super(GaussianBlurConv, self).__init__() self.channels = channels kernel = [[0.00078633, 0.00655965, 0.01330373, 0.00655965, 0.00078633], [0.00655965, 0.05472157, 0.11098164, 0.05472157, 0.00655965], [0.01330373, 0.11098164, 0.22508352, 0.11098164, 0.01330373], [0.00655965, 0.05472157, 0.11098164, 0.05472157, 0.00655965], [0.00078633, 0.00655965, 0.01330373, 0.00655965, 0.00078633]] kernel = torch.FloatTensor(kernel).unsqueeze(0).unsqueeze(0) kernel = np.repeat(kernel, self.channels, axis=0) self.weight = nn.Parameter(data=kernel, requires_grad=False) def __call__(self, x): x = F.conv2d(x, self.weight, padding=2, groups=self.channels) return x gaussianBlurConv = GaussianBlurConv().cuda() seed = 0 random.seed(seed) np.random.seed(seed) if torch.cuda.is_available(): torch.cuda.manual_seed_all(seed) torch.manual_seed(seed) torch.cuda.manual_seed(seed) torch.cuda.manual_seed_all(seed) # Remove randomness (may be slower on Tesla GPUs) # https://pytorch.org/docs/stable/notes/randomness.html if seed == 0: torch.backends.cudnn.deterministic = True torch.backends.cudnn.benchmark = False smoothL1 = torch.nn.SmoothL1Loss() mse = torch.nn.MSELoss() td_ = {} def bbox_dis(bbox1, bbox2): center1 = (bbox1[:, :2] + bbox1[:, 2:]) / 2 center2 = (bbox2[:, :2] + bbox2[:, 2:]) / 2 center1 = np.repeat(center1.reshape(-1, 1, 2), len(bbox2), axis=1) center2 = np.repeat(center2.reshape(1, -1, 2), len(bbox1), axis=0) dis = np.sqrt(np.sum((center1 - center2) ** 2, axis=-1)) return dis class STrack(BaseTrack): shared_kalman = KalmanFilter() shared_kalman_ = KalmanFilter() def __init__(self, tlwh, score, temp_feat, buffer_size=30): # wait activate self._tlwh = np.asarray(tlwh, dtype=np.float) self.kalman_filter = None self.mean, self.covariance = None, None self.is_activated = False self.score = score self.tracklet_len = 0 self.exist_len = 1 self.smooth_feat = None self.smooth_feat_ad = None self.update_features(temp_feat) self.features = deque([], maxlen=buffer_size) self.alpha = 0.9 self.curr_tlbr = self.tlwh_to_tlbr(self._tlwh) self.det_dict = {} def get_v(self): return self.mean[4:6] if self.mean is not None else None def update_features_ad(self, feat): feat /= np.linalg.norm(feat) if self.smooth_feat_ad is None: self.smooth_feat_ad = feat else: self.smooth_feat_ad = self.alpha * self.smooth_feat_ad + (1 - self.alpha) * feat self.smooth_feat_ad /= np.linalg.norm(self.smooth_feat_ad) def update_features(self, feat): feat /= np.linalg.norm(feat) self.curr_feat = feat if self.smooth_feat is None: self.smooth_feat = feat else: self.smooth_feat = self.alpha * self.smooth_feat + (1 - self.alpha) * feat self.features.append(feat) self.smooth_feat /= np.linalg.norm(self.smooth_feat) def predict(self): mean_state = self.mean.copy() if self.state != TrackState.Tracked: mean_state[7] = 0 self.mean, self.covariance = self.kalman_filter.predict(mean_state, self.covariance) @staticmethod def multi_predict(stracks): if len(stracks) > 0: multi_mean = np.asarray([st.mean.copy() for st in stracks]) multi_covariance = np.asarray([st.covariance for st in stracks]) for i, st in enumerate(stracks): if st.state != TrackState.Tracked: multi_mean[i][7] = 0 multi_mean, multi_covariance = STrack.shared_kalman.multi_predict(multi_mean, multi_covariance) for i, (mean, cov) in enumerate(zip(multi_mean, multi_covariance)): stracks[i].mean = mean stracks[i].covariance = cov @staticmethod def multi_predict_(stracks): if len(stracks) > 0: multi_mean = np.asarray([st.mean.copy() for st in stracks]) multi_covariance = np.asarray([st.covariance for st in stracks]) for i, st in enumerate(stracks): if st.state != TrackState.Tracked: multi_mean[i][7] = 0 multi_mean, multi_covariance = STrack.shared_kalman_.multi_predict(multi_mean, multi_covariance) for i, (mean, cov) in enumerate(zip(multi_mean, multi_covariance)): stracks[i].mean = mean stracks[i].covariance = cov def activate(self, kalman_filter, frame_id, track_id=None): """Start a new tracklet""" self.kalman_filter = kalman_filter if track_id: self.track_id = track_id['track_id'] track_id['track_id'] += 1 else: self.track_id = self.next_id() self.mean, self.covariance = self.kalman_filter.initiate(self.tlwh_to_xyah(self._tlwh)) self.tracklet_len = 0 self.state = TrackState.Tracked self.is_activated = True self.frame_id = frame_id self.start_frame = frame_id def activate_(self, kalman_filter, frame_id, track_id=None): """Start a new tracklet""" self.kalman_filter = kalman_filter if track_id: self.track_id = track_id['track_id'] track_id['track_id'] += 1 else: self.track_id = self.next_id_() self.mean, self.covariance = self.kalman_filter.initiate(self.tlwh_to_xyah(self._tlwh)) self.tracklet_len = 0 self.state = TrackState.Tracked self.is_activated = True self.frame_id = frame_id self.start_frame = frame_id def re_activate(self, new_track, frame_id, new_id=False): self.curr_tlbr = self.tlwh_to_tlbr(new_track.tlwh) self.mean, self.covariance = self.kalman_filter.update( self.mean, self.covariance, self.tlwh_to_xyah(new_track.tlwh) ) self.update_features(new_track.curr_feat) self.tracklet_len = 0 self.exist_len += 1 self.state = TrackState.Tracked self.is_activated = True self.frame_id = frame_id if new_id: self.track_id = self.next_id() def re_activate_(self, new_track, frame_id, new_id=False): self.curr_tlbr = self.tlwh_to_tlbr(new_track.tlwh) self.mean, self.covariance = self.kalman_filter.update( self.mean, self.covariance, self.tlwh_to_xyah(new_track.tlwh) ) self.update_features(new_track.curr_feat) self.tracklet_len = 0 self.exist_len += 1 self.state = TrackState.Tracked self.is_activated = True self.frame_id = frame_id if new_id: self.track_id = self.next_id_() def update(self, new_track, frame_id, update_feature=True): """ Update a matched track :type new_track: STrack :type frame_id: int :type update_feature: bool :return: """ self.frame_id = frame_id self.tracklet_len += 1 self.exist_len += 1 self.curr_tlbr = self.tlwh_to_tlbr(new_track.tlwh) new_tlwh = new_track.tlwh self.mean, self.covariance = self.kalman_filter.update( self.mean, self.covariance, self.tlwh_to_xyah(new_tlwh)) self.state = TrackState.Tracked self.is_activated = True self.score = new_track.score if update_feature: self.update_features(new_track.curr_feat) @property # @jit(nopython=True) def tlwh(self): """Get current position in bounding box format `(top left x, top left y, width, height)`. """ if self.mean is None: return self._tlwh.copy() ret = self.mean[:4].copy() ret[2] *= ret[3] ret[:2] -= ret[2:] / 2 return ret @property # @jit(nopython=True) def tlbr(self): """Convert bounding box to format `(min x, min y, max x, max y)`, i.e., `(top left, bottom right)`. """ ret = self.tlwh.copy() ret[2:] += ret[:2] return ret @staticmethod # @jit(nopython=True) def tlwh_to_xyah(tlwh): """Convert bounding box to format `(center x, center y, aspect ratio, height)`, where the aspect ratio is `width / height`. """ ret = np.asarray(tlwh).copy() ret[:2] += ret[2:] / 2 ret[2] /= ret[3] return ret def to_xyah(self): return self.tlwh_to_xyah(self.tlwh) @staticmethod # @jit(nopython=True) def tlbr_to_tlwh(tlbr): ret = np.asarray(tlbr).copy() ret[2:] -= ret[:2] return ret @staticmethod # @jit(nopython=True) def tlwh_to_tlbr(tlwh): ret = np.asarray(tlwh).copy() ret[2:] += ret[:2] return ret def __repr__(self): return 'OT_{}_({}-{})'.format(self.track_id, self.start_frame, self.end_frame) class JDETracker(object): def __init__( self, opt, frame_rate=30, tracked_stracks=[], lost_stracks=[], removed_stracks=[], frame_id=0, ad_last_info={}, model=None ): self.opt = opt print('Creating model...') if model: self.model = model else: self.model = create_model(opt.arch, opt.heads, opt.head_conv) self.model = load_model(self.model, opt.load_model).cuda() self.model.eval() self.log_index = [] self.unconfirmed_ad_iou = None self.tracked_stracks_ad_iou = None self.strack_pool_ad_iou = None self.tracked_stracks = copy.deepcopy(tracked_stracks) # type: list[STrack] self.lost_stracks = copy.deepcopy(lost_stracks) # type: list[STrack] self.removed_stracks = copy.deepcopy(removed_stracks) # type: list[STrack] self.tracked_stracks_ad = copy.deepcopy(tracked_stracks) # type: list[STrack] self.lost_stracks_ad = copy.deepcopy(lost_stracks) # type: list[STrack] self.removed_stracks_ad = copy.deepcopy(removed_stracks) # type: list[STrack] self.tracked_stracks_ = copy.deepcopy(tracked_stracks) # type: list[STrack] self.lost_stracks_ = copy.deepcopy(lost_stracks) # type: list[STrack] self.removed_stracks_ = copy.deepcopy(removed_stracks) # type: list[STrack] self.frame_id = frame_id self.frame_id_ = frame_id self.frame_id_ad = frame_id self.det_thresh = opt.conf_thres self.buffer_size = int(frame_rate / 30.0 * opt.track_buffer) self.max_time_lost = self.buffer_size self.max_per_image = 128 self.kalman_filter = KalmanFilter() self.kalman_filter_ad = KalmanFilter() self.kalman_filter_ = KalmanFilter() self.attacked_ids = set([]) self.low_iou_ids = set([]) self.ATTACK_IOU_THR = opt.iou_thr self.attack_iou_thr = self.ATTACK_IOU_THR self.ad_last_info = copy.deepcopy(ad_last_info) self.FRAME_THR = 10 self.temp_i = 0 self.multiple_ori_ids = {} self.multiple_att_ids = {} self.multiple_ori2att = {} self.multiple_att_freq = {} # hijacking attack self.ad_bbox = True self.ad_ids = set([]) def post_process(self, dets, meta): dets = dets.detach().cpu().numpy() dets = dets.reshape(1, -1, dets.shape[2]) dets = ctdet_post_process( dets.copy(), [meta['c']], [meta['s']], meta['out_height'], meta['out_width'], self.opt.num_classes) for j in range(1, self.opt.num_classes + 1): dets[0][j] = np.array(dets[0][j], dtype=np.float32).reshape(-1, 5) return dets[0] def merge_outputs(self, detections): results = {} for j in range(1, self.opt.num_classes + 1): results[j] = np.concatenate( [detection[j] for detection in detections], axis=0).astype(np.float32) scores = np.hstack( [results[j][:, 4] for j in range(1, self.opt.num_classes + 1)]) if len(scores) > self.max_per_image: kth = len(scores) - self.max_per_image thresh = np.partition(scores, kth)[kth] for j in range(1, self.opt.num_classes + 1): keep_inds = (results[j][:, 4] >= thresh) results[j] = results[j][keep_inds] return results @staticmethod def recoverImg(im_blob, img0): height = 608 width = 1088 im_blob = im_blob.cpu() * 255.0 shape = img0.shape[:2] # shape = [height, width] ratio = min(float(height) / shape[0], float(width) / shape[1]) new_shape = (round(shape[1] * ratio), round(shape[0] * ratio)) # new_shape = [width, height] dw = (width - new_shape[0]) / 2 # width padding dh = (height - new_shape[1]) / 2 # height padding top, bottom = round(dh - 0.1), round(dh + 0.1) left, right = round(dw - 0.1), round(dw + 0.1) im_blob = im_blob.squeeze().permute(1, 2, 0)[top:height - bottom, left:width - right, :].numpy().astype( np.uint8) im_blob = cv2.cvtColor(im_blob, cv2.COLOR_RGB2BGR) h, w, _ = img0.shape im_blob = cv2.resize(im_blob, (w, h)) return im_blob def recoverNoise(self, noise, img0): height = 608 width = 1088 shape = img0.shape[:2] # shape = [height, width] ratio = min(float(height) / shape[0], float(width) / shape[1]) new_shape = (round(shape[1] * ratio), round(shape[0] * ratio)) # new_shape = [width, height] dw = (width - new_shape[0]) / 2 # width padding dh = (height - new_shape[1]) / 2 # height padding top, bottom = round(dh - 0.1), round(dh + 0.1) left, right = round(dw - 0.1), round(dw + 0.1) noise = noise[:, :, top:height - bottom, left:width - right] h, w, _ = img0.shape # noise = self.resizeTensor(noise, h, w).cpu().squeeze().permute(1, 2, 0).numpy() noise = noise.cpu().squeeze().permute(1, 2, 0).numpy() noise = (noise[:, :, ::-1] * 255).astype(np.int) return noise @staticmethod def resizeTensor(tensor, height, width): h = torch.linspace(-1, 1, height).view(-1, 1).repeat(1, width).to(tensor.device) w = torch.linspace(-1, 1, width).repeat(height, 1).to(tensor.device) grid = torch.cat((h.unsqueeze(2), w.unsqueeze(2)), dim=2) grid = grid.unsqueeze(0) output = F.grid_sample(tensor, grid=grid, mode='bilinear', align_corners=True) return output @staticmethod def processIoUs(ious): h, w = ious.shape assert h == w ious = np.tril(ious, -1) index = np.argsort(-ious.reshape(-1)) indSet = set([]) for ind in index: i = ind // h j = ind % w if ious[i, j] == 0: break if i in indSet or j in indSet: ious[i, j] = 0 else: indSet.add(i) indSet.add(j) return ious def attack_sg_hj( self, im_blob, img0, dets, inds, remain_inds, last_info, outputs_ori, attack_id, attack_ind, ad_bbox, track_v ): noise = torch.zeros_like(im_blob) im_blob_ori = im_blob.clone().data outputs = outputs_ori H, W = outputs_ori['hm'].size()[2:] hm_index = inds[0][remain_inds] hm_index_att = hm_index[attack_ind].item() index = list(range(hm_index.size(0))) index.pop(attack_ind) wh_ori = outputs['wh'].clone().data reg_ori = outputs['reg'].clone().data i = 0 while True: i += 1 loss = 0 hm_index_att_lst = [hm_index_att] loss -= ((outputs['hm'].view(-1)[hm_index_att_lst].sigmoid()) ** 2).mean() if ad_bbox: assert track_v is not None hm_index_gen = hm_index_att_lst[0] hm_index_gen += -(np.sign(track_v[0]) + W * np.sign(track_v[1])) loss -= ((1 - outputs['hm'].view(-1)[[hm_index_gen]].sigmoid()) ** 2).mean() loss -= smoothL1(outputs['wh'].view(2, -1)[:, [hm_index_gen]].T, wh_ori.view(2, -1)[:, hm_index_att_lst].T) loss -= smoothL1(outputs['reg'].view(2, -1)[:, [hm_index_gen]].T, reg_ori.view(2, -1)[:, hm_index_att_lst].T) loss.backward() grad = im_blob.grad grad /= (grad ** 2).sum().sqrt() + 1e-8 noise += grad * 2 im_blob = torch.clip(im_blob_ori + noise, min=0, max=1).data outputs, suc, _ = self.forwardFeatureDet( im_blob, img0, dets, [attack_ind], thr=1 if ad_bbox else 0, vs=[track_v] if ad_bbox else [] ) if suc: break if i > 60: break return noise, i, suc def attack_sg_det( self, im_blob, img0, dets, inds, remain_inds, last_info, outputs_ori, attack_id, attack_ind ): noise = torch.zeros_like(im_blob) im_blob_ori = im_blob.clone().data outputs = outputs_ori H, W = outputs_ori['hm'].size()[2:] hm_index = inds[0][remain_inds] hm_index_att = hm_index[attack_ind].item() index = list(range(hm_index.size(0))) index.pop(attack_ind) i = 0 while True: i += 1 loss = 0 hm_index_att_lst = [hm_index_att] # for n_i in range(3): # for n_j in range(3): # hm_index_att_ = hm_index_att + (n_i - 1) * W + (n_j - 1) # hm_index_att_ = max(0, min(H * W - 1, hm_index_att_)) # hm_index_att_lst.append(hm_index_att_) loss -= ((outputs['hm'].view(-1)[hm_index_att_lst].sigmoid()) ** 2).mean() # loss += ((outputs['hm'].view(-1)[hm_index_att_lst].sigmoid()) ** 2 * # torch.log(1 - outputs['hm'].view(-1)[hm_index_att_lst].sigmoid())).mean() loss.backward() grad = im_blob.grad grad /= (grad ** 2).sum().sqrt() + 1e-8 noise += grad * 2 im_blob = torch.clip(im_blob_ori + noise, min=0, max=1).data outputs, suc, _ = self.forwardFeatureDet( im_blob, img0, dets, [attack_ind] ) if suc: break if i > 60: break return noise, i, suc def attack_mt_hj( self, im_blob, img0, dets, inds, remain_inds, last_info, outputs_ori, attack_ids, attack_inds, ad_ids, track_vs ): img0_h, img0_w = img0.shape[:2] H, W = outputs_ori['hm'].size()[2:] r_w, r_h = img0_w / W, img0_h / H r_max = max(r_w, r_h) noise = torch.zeros_like(im_blob) im_blob_ori = im_blob.clone().data outputs = outputs_ori wh_ori = outputs['wh'].clone().data reg_ori = outputs['reg'].clone().data i = 0 hm_index = inds[0][remain_inds] hm_index_att_lst = hm_index[attack_inds].cpu().numpy().tolist() best_i = None best_noise = None best_fail = np.inf while True: i += 1 loss = 0 loss -= ((outputs['hm'].view(-1)[hm_index_att_lst].sigmoid()) ** 2).mean() hm_index_att_lst_ = [hm_index_att_lst[j] for j in range(len(hm_index_att_lst)) if attack_ids[j] not in ad_ids] if len(hm_index_att_lst_): assert len(track_vs) == len(hm_index_att_lst_) hm_index_gen_lst = [] for index in range(len(hm_index_att_lst_)): track_v = track_vs[index] hm_index_gen = hm_index_att_lst_[index] hm_index_gen += -(np.sign(track_v[0]) + W * np.sign(track_v[1])) hm_index_gen_lst.append(hm_index_gen) loss -= ((1 - outputs['hm'].view(-1)[hm_index_gen_lst].sigmoid()) ** 2).mean() loss -= smoothL1(outputs['wh'].view(2, -1)[:, hm_index_gen_lst].T, wh_ori.view(2, -1)[:, hm_index_att_lst_].T) loss -= smoothL1(outputs['reg'].view(2, -1)[:, hm_index_gen_lst].T, reg_ori.view(2, -1)[:, hm_index_att_lst_].T) loss.backward() grad = im_blob.grad grad /= (grad ** 2).sum().sqrt() + 1e-8 noise += grad thrs = [0 for j in range(len(attack_inds))] for j in range(len(thrs)): if attack_ids[j] not in ad_ids: thrs[j] = 0.9 im_blob = torch.clip(im_blob_ori + noise, min=0, max=1).data outputs, suc, fail_ids = self.forwardFeatureDet( im_blob, img0, dets, attack_inds.tolist(), thr=thrs ) if fail_ids is not None: if fail_ids == 0: break elif fail_ids <= best_fail: best_fail = fail_ids best_i = i best_noise = noise.clone() if i > 60: if self.opt.no_f_noise: return None, i, False else: if best_i is not None: noise = best_noise i = best_i return noise, i, False return noise, i, True def attack_mt_det( self, im_blob, img0, dets, inds, remain_inds, last_info, outputs_ori, attack_ids, attack_inds ): img0_h, img0_w = img0.shape[:2] H, W = outputs_ori['hm'].size()[2:] r_w, r_h = img0_w / W, img0_h / H r_max = max(r_w, r_h) noise = torch.zeros_like(im_blob) im_blob_ori = im_blob.clone().data outputs = outputs_ori wh_ori = outputs['wh'].clone().data reg_ori = outputs['reg'].clone().data i = 0 hm_index = inds[0][remain_inds] hm_index_att_lst = hm_index[attack_inds].cpu().numpy().tolist() best_i = None best_noise = None best_fail = np.inf while True: i += 1 loss = 0 loss -= ((outputs['hm'].view(-1)[hm_index_att_lst].sigmoid()) ** 2).mean() loss.backward() grad = im_blob.grad grad /= (grad ** 2).sum().sqrt() + 1e-8 noise += grad im_blob = torch.clip(im_blob_ori + noise, min=0, max=1).data outputs, suc, fail_ids = self.forwardFeatureDet( im_blob, img0, dets, attack_inds.tolist() ) if fail_ids is not None: if fail_ids == 0: break elif fail_ids <= best_fail: best_fail = fail_ids best_i = i best_noise = noise.clone() if i > 60: if self.opt.no_f_noise: return None, i, False else: if best_i is not None: noise = best_noise i = best_i return noise, i, False return noise, i, True def attack_sg_feat( self, im_blob, img0, id_features, dets, inds, remain_inds, last_info, outputs_ori, attack_id, attack_ind, target_id, target_ind ): noise = torch.zeros_like(im_blob) im_blob_ori = im_blob.clone().data last_ad_id_features = [None for _ in range(len(id_features[0]))] for i in range(len(id_features)): id_features[i] = id_features[i][[attack_ind, target_ind]] i = 0 suc = True while True: i += 1 loss = 0 loss_feat = 0 for id_i, id_feature in enumerate(id_features): if last_ad_id_features[attack_ind] is not None: last_ad_id_feature = torch.from_numpy(last_ad_id_features[attack_ind]).unsqueeze(0).cuda() sim_1 = torch.mm(id_feature[0:0 + 1], last_ad_id_feature.T).squeeze() sim_2 = torch.mm(id_feature[1:1 + 1], last_ad_id_feature.T).squeeze() loss_feat += sim_2 - sim_1 if last_ad_id_features[target_ind] is not None: last_ad_id_feature = torch.from_numpy(last_ad_id_features[target_ind]).unsqueeze(0).cuda() sim_1 = torch.mm(id_feature[1:1 + 1], last_ad_id_feature.T).squeeze() sim_2 = torch.mm(id_feature[0:0 + 1], last_ad_id_feature.T).squeeze() loss_feat += sim_2 - sim_1 if last_ad_id_features[attack_ind] is None and last_ad_id_features[target_ind] is None: loss_feat += torch.mm(id_feature[0:0 + 1], id_feature[1:1 + 1].T).squeeze() loss += loss_feat / len(id_features) loss.backward() grad = im_blob.grad grad /= (grad ** 2).sum().sqrt() + 1e-8 noise += grad im_blob = torch.clip(im_blob_ori + noise, min=0, max=1).data id_features_, outputs_, ae_attack_id, ae_target_id, hm_index_ = self.forwardFeatureSg( im_blob, img0, dets, inds, remain_inds, attack_id, attack_ind, target_id, target_ind, last_info ) if id_features_ is not None: id_features = id_features_ if ae_attack_id != attack_id and ae_attack_id is not None: break if i > 60: suc = False break return noise, i, suc def attack_sg_cl( self, im_blob, img0, id_features, dets, inds, remain_inds, last_info, outputs_ori, attack_id, attack_ind, target_id, target_ind ): img0_h, img0_w = img0.shape[:2] H, W = outputs_ori['hm'].size()[2:] r_w, r_h = img0_w / W, img0_h / H r_max = max(r_w, r_h) noise = torch.zeros_like(im_blob) im_blob_ori = im_blob.clone().data outputs = outputs_ori wh_ori = outputs['wh'].clone().data reg_ori = outputs['reg'].clone().data last_ad_id_features = [None for _ in range(len(id_features[0]))] strack_pool = copy.deepcopy(last_info['last_strack_pool']) last_attack_det = None last_target_det = None STrack.multi_predict(strack_pool) for strack in strack_pool: if strack.track_id == attack_id: last_ad_id_features[attack_ind] = strack.smooth_feat last_attack_det = torch.from_numpy(strack.tlbr).cuda().float() last_attack_det[[0, 2]] = (last_attack_det[[0, 2]] - 0.5 * W * (r_w - r_max)) / r_max last_attack_det[[1, 3]] = (last_attack_det[[1, 3]] - 0.5 * H * (r_h - r_max)) / r_max elif strack.track_id == target_id: last_ad_id_features[target_ind] = strack.smooth_feat last_target_det = torch.from_numpy(strack.tlbr).cuda().float() last_target_det[[0, 2]] = (last_target_det[[0, 2]] - 0.5 * W * (r_w - r_max)) / r_max last_target_det[[1, 3]] = (last_target_det[[1, 3]] - 0.5 * H * (r_h - r_max)) / r_max last_attack_det_center = torch.round( (last_attack_det[:2] + last_attack_det[2:]) / 2) if last_attack_det is not None else None last_target_det_center = torch.round( (last_target_det[:2] + last_target_det[2:]) / 2) if last_target_det is not None else None hm_index = inds[0][remain_inds] for i in range(len(id_features)): id_features[i] = id_features[i][[attack_ind, target_ind]] i = 0 j = -1 suc = True ori_hm_index = hm_index[[attack_ind, target_ind]].clone() ori_hm_index_re = hm_index[[target_ind, attack_ind]].clone() att_hm_index = None noise_0 = None i_0 = None noise_1 = None i_1 = None while True: i += 1 loss = 0 loss_feat = 0 # for id_i, id_feature in enumerate(id_features): # if last_ad_id_features[attack_ind] is not None: # last_ad_id_feature = torch.from_numpy(last_ad_id_features[attack_ind]).unsqueeze(0).cuda() # sim_1 = torch.mm(id_feature[0:0 + 1], last_ad_id_feature.T).squeeze() # sim_2 = torch.mm(id_feature[1:1 + 1], last_ad_id_feature.T).squeeze() # loss_feat += sim_2 - sim_1 # if last_ad_id_features[target_ind] is not None: # last_ad_id_feature = torch.from_numpy(last_ad_id_features[target_ind]).unsqueeze(0).cuda() # sim_1 = torch.mm(id_feature[1:1 + 1], last_ad_id_feature.T).squeeze() # sim_2 = torch.mm(id_feature[0:0 + 1], last_ad_id_feature.T).squeeze() # loss_feat += sim_2 - sim_1 # if last_ad_id_features[attack_ind] is None and last_ad_id_features[target_ind] is None: # loss_feat += torch.mm(id_feature[0:0 + 1], id_feature[1:1 + 1].T).squeeze() # loss += loss_feat / len(id_features) if i in [1, 10, 20, 30, 35, 40, 45, 50, 55]: attack_det_center = torch.stack([hm_index[attack_ind] % W, hm_index[attack_ind] // W]).float() target_det_center = torch.stack([hm_index[target_ind] % W, hm_index[target_ind] // W]).float() if last_target_det_center is not None: attack_center_delta = attack_det_center - last_target_det_center if torch.max(torch.abs(attack_center_delta)) > 1: attack_center_delta /= torch.max(torch.abs(attack_center_delta)) attack_det_center = torch.round(attack_det_center - attack_center_delta).int() hm_index[attack_ind] = attack_det_center[0] + attack_det_center[1] * W if last_attack_det_center is not None: target_center_delta = target_det_center - last_attack_det_center if torch.max(torch.abs(target_center_delta)) > 1: target_center_delta /= torch.max(torch.abs(target_center_delta)) target_det_center = torch.round(target_det_center - target_center_delta).int() hm_index[target_ind] = target_det_center[0] + target_det_center[1] * W att_hm_index = hm_index[[attack_ind, target_ind]].clone() if att_hm_index is not None: n_att_hm_index = [] n_ori_hm_index_re = [] for hm_ind in range(len(att_hm_index)): for n_i in range(3): for n_j in range(3): att_hm_ind = att_hm_index[hm_ind].item() att_hm_ind = att_hm_ind + (n_i - 1) * W + (n_j - 1) att_hm_ind = max(0, min(H*W-1, att_hm_ind)) n_att_hm_index.append(att_hm_ind) ori_hm_ind = ori_hm_index_re[hm_ind].item() ori_hm_ind = ori_hm_ind + (n_i - 1) * W + (n_j - 1) ori_hm_ind = max(0, min(H * W - 1, ori_hm_ind)) n_ori_hm_index_re.append(ori_hm_ind) # print(n_att_hm_index, n_ori_hm_index_re) loss += ((1 - outputs['hm'].view(-1).sigmoid()[n_att_hm_index]) ** 2 * torch.log(outputs['hm'].view(-1).sigmoid()[n_att_hm_index])).mean() loss += ((outputs['hm'].view(-1).sigmoid()[n_ori_hm_index_re]) ** 2 * torch.log(1 - outputs['hm'].view(-1).sigmoid()[n_ori_hm_index_re])).mean() loss -= smoothL1(outputs['wh'].view(2, -1)[:, n_att_hm_index].T, wh_ori.view(2, -1)[:, n_ori_hm_index_re].T) loss -= smoothL1(outputs['reg'].view(2, -1)[:, n_att_hm_index].T, reg_ori.view(2, -1)[:, n_ori_hm_index_re].T) loss.backward() grad = im_blob.grad grad /= (grad ** 2).sum().sqrt() + 1e-8 noise += grad im_blob = torch.clip(im_blob_ori + noise, min=0, max=1).data id_features_, outputs_, ae_attack_id, ae_target_id, hm_index_ = self.forwardFeatureSg( im_blob, img0, dets, inds, remain_inds, attack_id, attack_ind, target_id, target_ind, last_info ) if id_features_ is not None: id_features = id_features_ if outputs_ is not None: outputs = outputs_ # if hm_index_ is not None: # hm_index = hm_index_ if ae_attack_id != attack_id and ae_attack_id is not None: break if i > 60: if noise_0 is not None: return noise_0, i_0, suc elif noise_1 is not None: return noise_1, i_1, suc if self.opt.no_f_noise: return None, i, False else: suc = False break return noise, i, suc def attack_sg_random( self, im_blob, img0, id_features, dets, inds, remain_inds, last_info, outputs_ori, attack_id, attack_ind, target_id, target_ind ): im_blob_ori = im_blob.clone().data suc = False noise = torch.rand(im_blob_ori.size()).to(im_blob_ori.device) noise /= (noise**2).sum().sqrt() noise *= random.uniform(2, 8) im_blob = torch.clip(im_blob_ori + noise, min=0, max=1).data id_features_, outputs_, ae_attack_id, ae_target_id, hm_index_ = self.forwardFeatureSg( im_blob, img0, dets, inds, remain_inds, attack_id, attack_ind, target_id, target_ind, last_info, grad=False ) if ae_attack_id != attack_id and ae_attack_id is not None: suc = True return noise, 1, suc def attack_mt_random( self, im_blob, img0, id_features, dets, inds, remain_inds, last_info, outputs_ori, attack_ids, attack_inds, target_ids, target_inds ): im_blob_ori = im_blob.clone().data suc = False noise = torch.rand(im_blob_ori.size()).to(im_blob_ori.device) noise /= (noise ** 2).sum().sqrt() noise *= random.uniform(2, 8) im_blob = torch.clip(im_blob_ori + noise, min=0, max=1).data id_features, outputs, fail_ids = self.forwardFeatureMt( im_blob, img0, dets, inds, remain_inds, attack_ids, attack_inds, target_ids, target_inds, last_info, grad=False ) if fail_ids == 0: suc = True return noise, 1, suc def attack_sg( self, im_blob, img0, id_features, dets, inds, remain_inds, last_info, outputs_ori, attack_id, attack_ind, target_id, target_ind ): img0_h, img0_w = img0.shape[:2] H, W = outputs_ori['hm'].size()[2:] r_w, r_h = img0_w / W, img0_h / H r_max = max(r_w, r_h) noise = torch.zeros_like(im_blob) im_blob_ori = im_blob.clone().data outputs = outputs_ori wh_ori = outputs['wh'].clone().data reg_ori = outputs['reg'].clone().data last_ad_id_features = [None for _ in range(len(id_features[0]))] strack_pool = copy.deepcopy(last_info['last_strack_pool']) last_attack_det = None last_target_det = None STrack.multi_predict(strack_pool) for strack in strack_pool: if strack.track_id == attack_id: last_ad_id_features[attack_ind] = strack.smooth_feat last_attack_det = torch.from_numpy(strack.tlbr).cuda().float() last_attack_det[[0, 2]] = (last_attack_det[[0, 2]] - 0.5 * W * (r_w - r_max)) / r_max last_attack_det[[1, 3]] = (last_attack_det[[1, 3]] - 0.5 * H * (r_h - r_max)) / r_max elif strack.track_id == target_id: last_ad_id_features[target_ind] = strack.smooth_feat last_target_det = torch.from_numpy(strack.tlbr).cuda().float() last_target_det[[0, 2]] = (last_target_det[[0, 2]] - 0.5 * W * (r_w - r_max)) / r_max last_target_det[[1, 3]] = (last_target_det[[1, 3]] - 0.5 * H * (r_h - r_max)) / r_max last_attack_det_center = torch.round( (last_attack_det[:2] + last_attack_det[2:]) / 2) if last_attack_det is not None else None last_target_det_center = torch.round( (last_target_det[:2] + last_target_det[2:]) / 2) if last_target_det is not None else None hm_index = inds[0][remain_inds] for i in range(len(id_features)): id_features[i] = id_features[i][[attack_ind, target_ind]] i = 0 j = -1 suc = True ori_hm_index = hm_index[[attack_ind, target_ind]].clone() ori_hm_index_re = hm_index[[target_ind, attack_ind]].clone() att_hm_index = None noise_0 = None i_0 = None noise_1 = None i_1 = None while True: i += 1 loss = 0 loss_feat = 0 for id_i, id_feature in enumerate(id_features): if last_ad_id_features[attack_ind] is not None: last_ad_id_feature = torch.from_numpy(last_ad_id_features[attack_ind]).unsqueeze(0).cuda() sim_1 = torch.mm(id_feature[0:0 + 1], last_ad_id_feature.T).squeeze() sim_2 = torch.mm(id_feature[1:1 + 1], last_ad_id_feature.T).squeeze() loss_feat += sim_2 - sim_1 if last_ad_id_features[target_ind] is not None: last_ad_id_feature = torch.from_numpy(last_ad_id_features[target_ind]).unsqueeze(0).cuda() sim_1 = torch.mm(id_feature[1:1 + 1], last_ad_id_feature.T).squeeze() sim_2 = torch.mm(id_feature[0:0 + 1], last_ad_id_feature.T).squeeze() loss_feat += sim_2 - sim_1 if last_ad_id_features[attack_ind] is None and last_ad_id_features[target_ind] is None: loss_feat += torch.mm(id_feature[0:0 + 1], id_feature[1:1 + 1].T).squeeze() loss += loss_feat / len(id_features) if i in [10, 20, 30, 35, 40, 45, 50, 55]: attack_det_center = torch.stack([hm_index[attack_ind] % W, hm_index[attack_ind] // W]).float() target_det_center = torch.stack([hm_index[target_ind] % W, hm_index[target_ind] // W]).float() if last_target_det_center is not None: attack_center_delta = attack_det_center - last_target_det_center if torch.max(torch.abs(attack_center_delta)) > 1: attack_center_delta /= torch.max(torch.abs(attack_center_delta)) attack_det_center = torch.round(attack_det_center - attack_center_delta).int() hm_index[attack_ind] = attack_det_center[0] + attack_det_center[1] * W if last_attack_det_center is not None: target_center_delta = target_det_center - last_attack_det_center if torch.max(torch.abs(target_center_delta)) > 1: target_center_delta /= torch.max(torch.abs(target_center_delta)) target_det_center = torch.round(target_det_center - target_center_delta).int() hm_index[target_ind] = target_det_center[0] + target_det_center[1] * W att_hm_index = hm_index[[attack_ind, target_ind]].clone() if att_hm_index is not None: n_att_hm_index = [] n_ori_hm_index_re = [] for hm_ind in range(len(att_hm_index)): for n_i in range(3): for n_j in range(3): att_hm_ind = att_hm_index[hm_ind].item() att_hm_ind = att_hm_ind + (n_i - 1) * W + (n_j - 1) att_hm_ind = max(0, min(H*W-1, att_hm_ind)) n_att_hm_index.append(att_hm_ind) ori_hm_ind = ori_hm_index_re[hm_ind].item() ori_hm_ind = ori_hm_ind + (n_i - 1) * W + (n_j - 1) ori_hm_ind = max(0, min(H * W - 1, ori_hm_ind)) n_ori_hm_index_re.append(ori_hm_ind) # print(n_att_hm_index, n_ori_hm_index_re) loss += ((1 - outputs['hm'].view(-1).sigmoid()[n_att_hm_index]) ** 2 * torch.log(outputs['hm'].view(-1).sigmoid()[n_att_hm_index])).mean() loss += ((outputs['hm'].view(-1).sigmoid()[n_ori_hm_index_re]) ** 2 * torch.log(1 - outputs['hm'].view(-1).sigmoid()[n_ori_hm_index_re])).mean() loss -= smoothL1(outputs['wh'].view(2, -1)[:, n_att_hm_index].T, wh_ori.view(2, -1)[:, n_ori_hm_index_re].T) loss -= smoothL1(outputs['reg'].view(2, -1)[:, n_att_hm_index].T, reg_ori.view(2, -1)[:, n_ori_hm_index_re].T) loss.backward() grad = im_blob.grad grad /= (grad ** 2).sum().sqrt() + 1e-8 noise += grad im_blob = torch.clip(im_blob_ori + noise, min=0, max=1).data id_features_, outputs_, ae_attack_id, ae_target_id, hm_index_ = self.forwardFeatureSg( im_blob, img0, dets, inds, remain_inds, attack_id, attack_ind, target_id, target_ind, last_info ) if id_features_ is not None: id_features = id_features_ if outputs_ is not None: outputs = outputs_ # if hm_index_ is not None: # hm_index = hm_index_ if ae_attack_id != attack_id and ae_attack_id is not None: break if i > 60: if noise_0 is not None: return noise_0, i_0, suc elif noise_1 is not None: return noise_1, i_1, suc if self.opt.no_f_noise: return None, i, False else: suc = False break return noise, i, suc def attack_mt( self, im_blob, img0, id_features, dets, inds, remain_inds, last_info, outputs_ori, attack_ids, attack_inds, target_ids, target_inds ): img0_h, img0_w = img0.shape[:2] H, W = outputs_ori['hm'].size()[2:] r_w, r_h = img0_w / W, img0_h / H r_max = max(r_w, r_h) noise = torch.zeros_like(im_blob) im_blob_ori = im_blob.clone().data outputs = outputs_ori wh_ori = outputs['wh'].clone().data reg_ori = outputs['reg'].clone().data i = 0 j = -1 last_ad_id_features = [None for _ in range(len(id_features[0]))] strack_pool = copy.deepcopy(last_info['last_strack_pool']) ad_attack_ids = [self.multiple_ori2att[attack_id] for attack_id in attack_ids] ad_target_ids = [self.multiple_ori2att[target_id] for target_id in target_ids] last_attack_dets = [None] * len(ad_attack_ids) last_target_dets = [None] * len(ad_target_ids) STrack.multi_predict(strack_pool) for strack in strack_pool: if strack.track_id in ad_attack_ids: index = ad_attack_ids.index(strack.track_id) last_ad_id_features[attack_inds[index]] = strack.smooth_feat last_attack_dets[index] = torch.from_numpy(strack.tlbr).cuda().float() last_attack_dets[index][[0, 2]] = (last_attack_dets[index][[0, 2]] - 0.5 * W * (r_w - r_max)) / r_max last_attack_dets[index][[1, 3]] = (last_attack_dets[index][[1, 3]] - 0.5 * H * (r_h - r_max)) / r_max if strack.track_id in ad_target_ids: index = ad_target_ids.index(strack.track_id) last_ad_id_features[target_inds[index]] = strack.smooth_feat last_target_dets[index] = torch.from_numpy(strack.tlbr).cuda().float() last_target_dets[index][[0, 2]] = (last_target_dets[index][[0, 2]] - 0.5 * W * (r_w - r_max)) / r_max last_target_dets[index][[1, 3]] = (last_target_dets[index][[1, 3]] - 0.5 * H * (r_h - r_max)) / r_max last_attack_dets_center = [] for det in last_attack_dets: if det is None: last_attack_dets_center.append(None) else: last_attack_dets_center.append((det[:2] + det[2:]) / 2) last_target_dets_center = [] for det in last_target_dets: if det is None: last_target_dets_center.append(None) else: last_target_dets_center.append((det[:2] + det[2:]) / 2) hm_index = inds[0][remain_inds] ori_hm_index_re_lst = [] for ind in range(len(attack_ids)): attack_ind = attack_inds[ind] target_ind = target_inds[ind] ori_hm_index_re_lst.append(hm_index[[target_ind, attack_ind]].clone()) att_hm_index_lst = [] best_i = None best_noise = None best_fail = np.inf while True: i += 1 loss = 0 loss_feat = 0 for index, attack_id in enumerate(attack_ids): target_id = target_ids[index] attack_ind = attack_inds[index] target_ind = target_inds[index] for id_i, id_feature in enumerate(id_features): if last_ad_id_features[attack_ind] is not None: last_ad_id_feature = torch.from_numpy(last_ad_id_features[attack_ind]).unsqueeze(0).cuda() sim_1 = torch.mm(id_feature[attack_ind:attack_ind + 1], last_ad_id_feature.T).squeeze() sim_2 = torch.mm(id_feature[target_ind:target_ind + 1], last_ad_id_feature.T).squeeze() if self.opt.hard_sample > 0: loss_feat += torch.clamp(sim_2 - sim_1, max=self.opt.hard_sample) else: loss_feat += sim_2 - sim_1 if last_ad_id_features[target_ind] is not None: last_ad_id_feature = torch.from_numpy(last_ad_id_features[target_ind]).unsqueeze(0).cuda() sim_1 = torch.mm(id_feature[target_ind:target_ind + 1], last_ad_id_feature.T).squeeze() sim_2 = torch.mm(id_feature[attack_ind:attack_ind + 1], last_ad_id_feature.T).squeeze() if self.opt.hard_sample > 0: loss_feat += torch.clamp(sim_2 - sim_1, max=self.opt.hard_sample) else: loss_feat += sim_2 - sim_1 if last_ad_id_features[attack_ind] is None and last_ad_id_features[target_ind] is None: loss_feat += torch.mm(id_feature[attack_ind:attack_ind + 1], id_feature[target_ind:target_ind + 1].T).squeeze() if i in [10, 20, 30, 35, 40, 45, 50, 55]: attack_det_center = torch.stack([hm_index[attack_ind] % W, hm_index[attack_ind] // W]).float() target_det_center = torch.stack([hm_index[target_ind] % W, hm_index[target_ind] // W]).float() if last_target_dets_center[index] is not None: attack_center_delta = attack_det_center - last_target_dets_center[index] if torch.max(torch.abs(attack_center_delta)) > 1: attack_center_delta /= torch.max(torch.abs(attack_center_delta)) attack_det_center = torch.round(attack_det_center - attack_center_delta).int() hm_index[attack_ind] = attack_det_center[0] + attack_det_center[1] * W if last_attack_dets_center[index] is not None: target_center_delta = target_det_center - last_attack_dets_center[index] if torch.max(torch.abs(target_center_delta)) > 1: target_center_delta /= torch.max(torch.abs(target_center_delta)) target_det_center = torch.round(target_det_center - target_center_delta).int() hm_index[target_ind] = target_det_center[0] + target_det_center[1] * W if index == 0: att_hm_index_lst = [] att_hm_index_lst.append(hm_index[[attack_ind, target_ind]].clone()) loss += loss_feat / len(id_features) if len(att_hm_index_lst): assert len(att_hm_index_lst) == len(ori_hm_index_re_lst) n_att_hm_index_lst = [] n_ori_hm_index_re_lst = [] for lst_ind in range(len(att_hm_index_lst)): for hm_ind in range(len(att_hm_index_lst[lst_ind])): for n_i in range(3): for n_j in range(3): att_hm_ind = att_hm_index_lst[lst_ind][hm_ind].item() att_hm_ind = att_hm_ind + (n_i - 1) * W + (n_j - 1) att_hm_ind = max(0, min(H*W-1, att_hm_ind)) n_att_hm_index_lst.append(att_hm_ind) ori_hm_ind = ori_hm_index_re_lst[lst_ind][hm_ind].item() ori_hm_ind = ori_hm_ind + (n_i - 1) * W + (n_j - 1) ori_hm_ind = max(0, min(H * W - 1, ori_hm_ind)) n_ori_hm_index_re_lst.append(ori_hm_ind) # print(n_att_hm_index, n_ori_hm_index_re) loss += ((1 - outputs['hm'].view(-1).sigmoid()[n_att_hm_index_lst]) ** 2 * torch.log(outputs['hm'].view(-1).sigmoid()[n_att_hm_index_lst])).mean() loss += ((outputs['hm'].view(-1).sigmoid()[n_ori_hm_index_re_lst]) ** 2 * torch.log(1 - outputs['hm'].view(-1).sigmoid()[n_ori_hm_index_re_lst])).mean() loss -= smoothL1(outputs['wh'].view(2, -1)[:, n_att_hm_index_lst].T, wh_ori.view(2, -1)[:, n_ori_hm_index_re_lst].T) loss -= smoothL1(outputs['reg'].view(2, -1)[:, n_att_hm_index_lst].T, reg_ori.view(2, -1)[:, n_ori_hm_index_re_lst].T) loss.backward() grad = im_blob.grad grad /= (grad ** 2).sum().sqrt() + 1e-8 noise += grad im_blob = torch.clip(im_blob_ori + noise, min=0, max=1).data id_features, outputs, fail_ids = self.forwardFeatureMt( im_blob, img0, dets, inds, remain_inds, attack_ids, attack_inds, target_ids, target_inds, last_info ) if fail_ids is not None: if fail_ids == 0: break elif fail_ids <= best_fail: best_fail = fail_ids best_i = i best_noise = noise.clone() if i > 60: if self.opt.no_f_noise: return None, i, False else: if best_i is not None: noise = best_noise i = best_i return noise, i, False return noise, i, True def forwardFeatureDet(self, im_blob, img0, dets_, attack_inds, thr=0, vs=[]): width = img0.shape[1] height = img0.shape[0] inp_height = im_blob.shape[2] inp_width = im_blob.shape[3] c = np.array([width / 2., height / 2.], dtype=np.float32) s = max(float(inp_width) / float(inp_height) * height, width) * 1.0 meta = {'c': c, 's': s, 'out_height': inp_height // self.opt.down_ratio, 'out_width': inp_width // self.opt.down_ratio} im_blob.requires_grad = True self.model.zero_grad() output = self.model(im_blob)[-1] hm = output['hm'].sigmoid() wh = output['wh'] reg = output['reg'] if self.opt.reg_offset else None dets_raw, inds = mot_decode(hm, wh, reg=reg, cat_spec_wh=self.opt.cat_spec_wh, K=self.opt.K) dets = self.post_process(dets_raw.clone(), meta) dets = self.merge_outputs([dets])[1] remain_inds = dets[:, 4] > self.opt.conf_thres dets = dets[remain_inds] ious = bbox_ious(np.ascontiguousarray(dets_[:, :4], dtype=np.float), np.ascontiguousarray(dets[:, :4], dtype=np.float)) row_inds, col_inds = linear_sum_assignment(-ious) if not isinstance(thr, list): thr = [thr for _ in range(len(attack_inds))] fail_n = 0 for i in range(len(row_inds)): if row_inds[i] in attack_inds: if ious[row_inds[i], col_inds[i]] > thr[attack_inds.index(row_inds[i])]: fail_n += 1 elif len(vs): d_o = dets_[row_inds[i], :4] d_a = dets[col_inds[i], :4] c_o = (d_o[[0, 1]] + d_o[[2, 3]]) / 2 c_a = (d_a[[0, 1]] + d_a[[2, 3]]) / 2 c_d = ((c_a - c_o) / 4).astype(np.int) * vs[0] if c_d[0] >= 0 or c_d[1] >= 0: fail_n += 1 return output, fail_n == 0, fail_n def forwardFeatureSg(self, im_blob, img0, dets_, inds_, remain_inds_, attack_id, attack_ind, target_id, target_ind, last_info, grad=True): width = img0.shape[1] height = img0.shape[0] inp_height = im_blob.shape[2] inp_width = im_blob.shape[3] c = np.array([width / 2., height / 2.], dtype=np.float32) s = max(float(inp_width) / float(inp_height) * height, width) * 1.0 meta = {'c': c, 's': s, 'out_height': inp_height // self.opt.down_ratio, 'out_width': inp_width // self.opt.down_ratio} im_blob.requires_grad = True self.model.zero_grad() if grad: output = self.model(im_blob)[-1] else: with torch.no_grad(): output = self.model(im_blob)[-1] hm = output['hm'].sigmoid() wh = output['wh'] id_feature = output['id'] id_feature = F.normalize(id_feature, dim=1) reg = output['reg'] if self.opt.reg_offset else None dets_raw, inds = mot_decode(hm, wh, reg=reg, cat_spec_wh=self.opt.cat_spec_wh, K=self.opt.K) dets = self.post_process(dets_raw.clone(), meta) dets = self.merge_outputs([dets])[1] remain_inds = dets[:, 4] > self.opt.conf_thres dets = dets[remain_inds] if target_ind is None: ious = bbox_ious(np.ascontiguousarray(dets_[[attack_ind], :4], dtype=np.float), np.ascontiguousarray(dets[:, :4], dtype=np.float)) else: ious = bbox_ious(np.ascontiguousarray(dets_[[attack_ind, target_ind], :4], dtype=np.float), np.ascontiguousarray(dets[:, :4], dtype=np.float)) # det_ind = np.argmax(ious, axis=1) row_inds, col_inds = linear_sum_assignment(-ious) match = True if target_ind is None: if ious[row_inds[0], col_inds[0]] < 0.8: dets = dets_ inds = inds_ remain_inds = remain_inds_ match = False else: if len(col_inds) < 2 or ious[row_inds[0], col_inds[0]] < 0.6 or ious[row_inds[1], col_inds[1]] < 0.6: dets = dets_ inds = inds_ remain_inds = remain_inds_ match = False # assert match id_features = [] for i in range(3): for j in range(3): id_feature_exp = _tranpose_and_gather_feat_expand(id_feature, inds, bias=(i - 1, j - 1)).squeeze(0) id_features.append(id_feature_exp) for i in range(len(id_features)): id_features[i] = id_features[i][remain_inds] ae_attack_id = None ae_target_id = None if not match: for i in range(len(id_features)): if target_ind is not None: id_features[i] = id_features[i][[attack_ind, target_ind]] else: id_features[i] = id_features[i][[attack_ind]] return id_features, output, ae_attack_id, ae_target_id, None if row_inds[0] == 0: ae_attack_ind = col_inds[0] ae_target_ind = col_inds[1] if target_ind is not None else None else: ae_attack_ind = col_inds[1] ae_target_ind = col_inds[0] if target_ind is not None else None # ae_attack_ind = det_ind[0] # ae_target_ind = det_ind[1] if target_ind is not None else None hm_index = None # if target_ind is not None: # hm_index[[attack_ind, target_ind]] = hm_index[[ae_attack_ind, ae_target_ind]] id_features_ = [None for _ in range(len(id_features))] for i in range(len(id_features)): if target_ind is None: id_features_[i] = id_features[i][[ae_attack_ind]] else: try: id_features_[i] = id_features[i][[ae_attack_ind, ae_target_ind]] except: import pdb; pdb.set_trace() id_feature = _tranpose_and_gather_feat_expand(id_feature, inds) id_feature = id_feature.squeeze(0) id_feature = id_feature[remain_inds] id_feature = id_feature.detach().cpu().numpy() if len(dets) > 0: '''Detections''' detections = [STrack(STrack.tlbr_to_tlwh(tlbrs[:4]), tlbrs[4], f, 30) for (tlbrs, f) in zip(dets[:, :5], id_feature)] else: detections = [] unconfirmed = copy.deepcopy(last_info['last_unconfirmed']) strack_pool = copy.deepcopy(last_info['last_strack_pool']) kalman_filter = copy.deepcopy(last_info['kalman_filter']) STrack.multi_predict(strack_pool) dists = matching.embedding_distance(strack_pool, detections) dists = matching.fuse_motion(kalman_filter, dists, strack_pool, detections) matches, u_track, u_detection = matching.linear_assignment(dists, thresh=0.7) for itracked, idet in matches: track = strack_pool[itracked] det = detections[idet] if idet == ae_attack_ind: ae_attack_id = track.track_id elif idet == ae_target_ind: ae_target_id = track.track_id # if ae_attack_id is not None and ae_target_id is not None: # return id_features_, output, ae_attack_id, ae_target_id ''' Step 3: Second association, with IOU''' for i, idet in enumerate(u_detection): if idet == ae_attack_ind: ae_attack_ind = i elif idet == ae_target_ind: ae_target_ind = i detections = [detections[i] for i in u_detection] r_tracked_stracks = [strack_pool[i] for i in u_track if strack_pool[i].state == TrackState.Tracked] dists = matching.iou_distance(r_tracked_stracks, detections) matches, u_track, u_detection = matching.linear_assignment(dists, thresh=0.5) for itracked, idet in matches: track = r_tracked_stracks[itracked] det = detections[idet] if idet == ae_attack_ind: ae_attack_id = track.track_id elif idet == ae_target_ind: ae_target_id = track.track_id # if ae_attack_id is not None and ae_target_id is not None: # return id_features_, output, ae_attack_id, ae_target_id '''Deal with unconfirmed tracks, usually tracks with only one beginning frame''' for i, idet in enumerate(u_detection): if idet == ae_attack_ind: ae_attack_ind = i elif idet == ae_target_ind: ae_target_ind = i detections = [detections[i] for i in u_detection] dists = matching.iou_distance(unconfirmed, detections) matches, u_unconfirmed, u_detection = matching.linear_assignment(dists, thresh=0.7) for itracked, idet in matches: track = unconfirmed[itracked] if idet == ae_attack_ind: ae_attack_id = track.track_id elif idet == ae_target_ind: ae_target_id = track.track_id return id_features_, output, ae_attack_id, ae_target_id, hm_index def forwardFeatureMt(self, im_blob, img0, dets_, inds_, remain_inds_, attack_ids, attack_inds, target_ids, target_inds, last_info, grad=True): width = img0.shape[1] height = img0.shape[0] inp_height = im_blob.shape[2] inp_width = im_blob.shape[3] c = np.array([width / 2., height / 2.], dtype=np.float32) s = max(float(inp_width) / float(inp_height) * height, width) * 1.0 meta = {'c': c, 's': s, 'out_height': inp_height // self.opt.down_ratio, 'out_width': inp_width // self.opt.down_ratio} im_blob.requires_grad = True self.model.zero_grad() if grad: output = self.model(im_blob)[-1] else: with torch.no_grad(): output = self.model(im_blob)[-1] hm = output['hm'].sigmoid() wh = output['wh'] id_feature = output['id'] id_feature = F.normalize(id_feature, dim=1) reg = output['reg'] if self.opt.reg_offset else None dets_raw, inds = mot_decode(hm, wh, reg=reg, cat_spec_wh=self.opt.cat_spec_wh, K=self.opt.K) dets = self.post_process(dets_raw.clone(), meta) dets = self.merge_outputs([dets])[1] dets_index = [i for i in range(len(dets))] remain_inds = dets[:, 4] > self.opt.conf_thres dets = dets[remain_inds] ious = bbox_ious(np.ascontiguousarray(dets_[:, :4], dtype=np.float64), np.ascontiguousarray(dets[:, :4], dtype=np.float64)) row_inds, col_inds = linear_sum_assignment(-ious) match = True if target_inds is not None: for index, attack_ind in enumerate(attack_inds): target_ind = target_inds[index] if attack_ind not in row_inds or target_ind not in row_inds: match = False break att_index = row_inds.tolist().index(attack_ind) tar_index = row_inds.tolist().index(target_ind) if ious[attack_ind, col_inds[att_index]] < 0.6 or ious[target_ind, col_inds[tar_index]] < 0.6: match = False break else: for index, attack_ind in enumerate(attack_inds): if attack_ind not in row_inds: match = False break att_index = row_inds.tolist().index(attack_ind) if ious[attack_ind, col_inds[att_index]] < 0.8: match = False break if not match: dets = dets_ inds = inds_ remain_inds = remain_inds_ # assert match id_features = [] for i in range(3): for j in range(3): id_feature_exp = _tranpose_and_gather_feat_expand(id_feature, inds, bias=(i - 1, j - 1)).squeeze(0) id_features.append(id_feature_exp) for i in range(len(id_features)): id_features[i] = id_features[i][remain_inds] fail_ids = 0 if not match: return id_features, output, None ae_attack_inds = [] ae_attack_ids = [] for i in range(len(row_inds)): if ious[row_inds[i], col_inds[i]] > 0.6: if row_inds[i] in attack_inds: ae_attack_inds.append(col_inds[i]) index = attack_inds.tolist().index(row_inds[i]) ae_attack_ids.append(self.multiple_ori2att[attack_ids[index]]) # ae_attack_inds = [col_inds[row_inds == attack_ind] for attack_ind in attack_inds] # ae_attack_inds = np.concatenate(ae_attack_inds) id_features_ = [torch.zeros([len(dets_), id_features[0].size(1)]).to(id_features[0].device) for _ in range(len(id_features))] for i in range(9): id_features_[i][row_inds] = id_features[i][col_inds] id_feature = _tranpose_and_gather_feat_expand(id_feature, inds) id_feature = id_feature.squeeze(0) id_feature = id_feature[remain_inds] id_feature = id_feature.detach().cpu().numpy() if len(dets) > 0: '''Detections''' detections = [STrack(STrack.tlbr_to_tlwh(tlbrs[:4]), tlbrs[4], f, 30) for (tlbrs, f) in zip(dets[:, :5], id_feature)] else: detections = [] unconfirmed = copy.deepcopy(last_info['last_unconfirmed']) strack_pool = copy.deepcopy(last_info['last_strack_pool']) kalman_filter = copy.deepcopy(last_info['kalman_filter']) STrack.multi_predict(strack_pool) dists = matching.embedding_distance(strack_pool, detections) dists = matching.fuse_motion(kalman_filter, dists, strack_pool, detections) matches, u_track, u_detection = matching.linear_assignment(dists, thresh=0.7) for itracked, idet in matches: track = strack_pool[itracked] det = detections[idet] if dets_index[idet] in ae_attack_inds: index = ae_attack_inds.index(dets_index[idet]) if track.track_id == ae_attack_ids[index]: fail_ids += 1 ''' Step 3: Second association, with IOU''' dets_index = [dets_index[i] for i in u_detection] detections = [detections[i] for i in u_detection] r_tracked_stracks = [strack_pool[i] for i in u_track if strack_pool[i].state == TrackState.Tracked] dists = matching.iou_distance(r_tracked_stracks, detections) matches, u_track, u_detection = matching.linear_assignment(dists, thresh=0.5) for itracked, idet in matches: track = r_tracked_stracks[itracked] det = detections[idet] if dets_index[idet] in ae_attack_inds: index = ae_attack_inds.index(dets_index[idet]) if track.track_id == ae_attack_ids[index]: fail_ids += 1 '''Deal with unconfirmed tracks, usually tracks with only one beginning frame''' dets_index = [dets_index[i] for i in u_detection] detections = [detections[i] for i in u_detection] dists = matching.iou_distance(unconfirmed, detections) matches, u_unconfirmed, u_detection = matching.linear_assignment(dists, thresh=0.7) for itracked, idet in matches: track = unconfirmed[itracked] if dets_index[idet] in ae_attack_inds: index = ae_attack_inds.index(dets_index[idet]) if track.track_id == ae_attack_ids[index]: fail_ids += 1 return id_features_, output, fail_ids def CheckFit(self, dets, id_feature, attack_ids, attack_inds): ad_attack_ids_ = [self.multiple_ori2att[attack_id] for attack_id in attack_ids] \ if self.opt.attack == 'multiple' else attack_ids attack_dets = dets[attack_inds, :4] ad_attack_dets = [] ad_attack_ids = [] if len(dets) > 0: '''Detections''' detections = [STrack(STrack.tlbr_to_tlwh(tlbrs[:4]), tlbrs[4], f, 30) for (tlbrs, f) in zip(dets[:, :5], id_feature)] else: detections = [] unconfirmed = copy.deepcopy(self.ad_last_info['last_unconfirmed']) strack_pool = copy.deepcopy(self.ad_last_info['last_strack_pool']) kalman_filter = copy.deepcopy(self.ad_last_info['kalman_filter']) STrack.multi_predict(strack_pool) dists = matching.embedding_distance(strack_pool, detections) dists = matching.fuse_motion(kalman_filter, dists, strack_pool, detections) matches, u_track, u_detection = matching.linear_assignment(dists, thresh=0.7) for itracked, idet in matches: track = strack_pool[itracked] det = detections[idet] if track.track_id in ad_attack_ids_: ad_attack_dets.append(det.tlbr) ad_attack_ids.append(track.track_id) ''' Step 3: Second association, with IOU''' detections = [detections[i] for i in u_detection] r_tracked_stracks = [strack_pool[i] for i in u_track if strack_pool[i].state == TrackState.Tracked] dists = matching.iou_distance(r_tracked_stracks, detections) matches, u_track, u_detection = matching.linear_assignment(dists, thresh=0.5) for itracked, idet in matches: track = r_tracked_stracks[itracked] det = detections[idet] if track.track_id in ad_attack_ids_: ad_attack_dets.append(det.tlbr) ad_attack_ids.append(track.track_id) '''Deal with unconfirmed tracks, usually tracks with only one beginning frame''' detections = [detections[i] for i in u_detection] dists = matching.iou_distance(unconfirmed, detections) matches, u_unconfirmed, u_detection = matching.linear_assignment(dists, thresh=0.7) for itracked, idet in matches: track = unconfirmed[itracked] det = detections[idet] if track.track_id in ad_attack_ids_: ad_attack_dets.append(det.tlbr) ad_attack_ids.append(track.track_id) if len(ad_attack_dets) == 0: return [] ori_dets = np.array(attack_dets) ad_dets = np.array(ad_attack_dets) ious = bbox_ious(ori_dets.astype(np.float64), ad_dets.astype(np.float64)) row_ind, col_ind = linear_sum_assignment(-ious) attack_index = [] for i in range(len(row_ind)): if self.opt.attack == 'multiple': if ious[row_ind[i], col_ind[i]] > 0.9 and self.multiple_ori2att[attack_ids[row_ind[i]]] == ad_attack_ids[col_ind[i]]: attack_index.append(row_ind[i]) else: if ious[row_ind[i], col_ind[i]] > 0.9: attack_index.append(row_ind[i]) return attack_index def update_attack_sg(self, im_blob, img0, **kwargs): self.frame_id_ += 1 attack_id = kwargs['attack_id'] self_track_id_ori = kwargs.get('track_id', {}).get('origin', None) self_track_id_att = kwargs.get('track_id', {}).get('attack', None) activated_starcks = [] refind_stracks = [] lost_stracks = [] removed_stracks = [] width = img0.shape[1] height = img0.shape[0] inp_height = im_blob.shape[2] inp_width = im_blob.shape[3] c = np.array([width / 2., height / 2.], dtype=np.float32) s = max(float(inp_width) / float(inp_height) * height, width) * 1.0 meta = {'c': c, 's': s, 'out_height': inp_height // self.opt.down_ratio, 'out_width': inp_width // self.opt.down_ratio} ''' Step 1: Network forward, get detections & embeddings''' # with torch.no_grad(): im_blob.requires_grad = True self.model.zero_grad() output = self.model(im_blob)[-1] hm = output['hm'].sigmoid() wh = output['wh'] id_feature = output['id'] id_feature = F.normalize(id_feature, dim=1) reg = output['reg'] if self.opt.reg_offset else None dets_raw, inds = mot_decode(hm, wh, reg=reg, cat_spec_wh=self.opt.cat_spec_wh, K=self.opt.K) id_features = [] for i in range(3): for j in range(3): id_feature_exp = _tranpose_and_gather_feat_expand(id_feature, inds, bias=(i - 1, j - 1)).squeeze(0) id_features.append(id_feature_exp) id_feature = _tranpose_and_gather_feat_expand(id_feature, inds) id_feature = id_feature.squeeze(0) dets = self.post_process(dets_raw.clone(), meta) dets = self.merge_outputs([dets])[1] remain_inds = dets[:, 4] > self.opt.conf_thres dets = dets[remain_inds] id_feature = id_feature[remain_inds] for i in range(len(id_features)): id_features[i] = id_features[i][remain_inds] id_feature = id_feature.detach().cpu().numpy() last_id_features = [None for _ in range(len(dets))] last_ad_id_features = [None for _ in range(len(dets))] dets_index = [i for i in range(len(dets))] dets_ids = [None for _ in range(len(dets))] tracks_ad = [] # import pdb; pdb.set_trace() # vis ''' for i in range(0, dets.shape[0]): bbox = dets[i][0:4] cv2.rectangle(img0, (bbox[0], bbox[1]), (bbox[2], bbox[3]), (0, 255, 0), 2) cv2.imshow('dets', img0) cv2.waitKey(0) id0 = id0-1 ''' if len(dets) > 0: '''Detections''' detections = [STrack(STrack.tlbr_to_tlwh(tlbrs[:4]), tlbrs[4], f, 30) for (tlbrs, f) in zip(dets[:, :5], id_feature)] else: detections = [] ''' Add newly detected tracklets to tracked_stracks''' unconfirmed = [] tracked_stracks = [] # type: list[STrack] for track in self.tracked_stracks_: if not track.is_activated: unconfirmed.append(track) else: tracked_stracks.append(track) ''' Step 2: First association, with embedding''' strack_pool = joint_stracks(tracked_stracks, self.lost_stracks_) STrack.multi_predict(strack_pool) dists = matching.embedding_distance(strack_pool, detections) # dists = matching.gate_cost_matrix(self.kalman_filter, dists, strack_pool, detections) dists = matching.fuse_motion(self.kalman_filter_, dists, strack_pool, detections) matches, u_track, u_detection = matching.linear_assignment(dists, thresh=0.7) # import pdb; pdb.set_trace() for itracked, idet in matches: track = strack_pool[itracked] det = detections[idet] assert last_id_features[dets_index[idet]] is None assert last_ad_id_features[dets_index[idet]] is None last_id_features[dets_index[idet]] = track.smooth_feat last_ad_id_features[dets_index[idet]] = track.smooth_feat_ad tracks_ad.append((track, dets_index[idet])) if track.state == TrackState.Tracked: track.update(detections[idet], self.frame_id_) activated_starcks.append(track) else: track.re_activate_(det, self.frame_id_, new_id=False) refind_stracks.append(track) dets_ids[dets_index[idet]] = track.track_id ''' Step 3: Second association, with IOU''' dets_index = [dets_index[i] for i in u_detection] detections = [detections[i] for i in u_detection] r_tracked_stracks = [strack_pool[i] for i in u_track if strack_pool[i].state == TrackState.Tracked] dists = matching.iou_distance(r_tracked_stracks, detections) matches, u_track, u_detection = matching.linear_assignment(dists, thresh=0.5) for itracked, idet in matches: track = r_tracked_stracks[itracked] det = detections[idet] assert last_id_features[dets_index[idet]] is None assert last_ad_id_features[dets_index[idet]] is None last_id_features[dets_index[idet]] = track.smooth_feat last_ad_id_features[dets_index[idet]] = track.smooth_feat_ad tracks_ad.append((track, dets_index[idet])) if track.state == TrackState.Tracked: track.update(det, self.frame_id_) activated_starcks.append(track) else: track.re_activate_(det, self.frame_id_, new_id=False) refind_stracks.append(track) dets_ids[dets_index[idet]] = track.track_id for it in u_track: track = r_tracked_stracks[it] if not track.state == TrackState.Lost: track.mark_lost() lost_stracks.append(track) '''Deal with unconfirmed tracks, usually tracks with only one beginning frame''' dets_index = [dets_index[i] for i in u_detection] detections = [detections[i] for i in u_detection] dists = matching.iou_distance(unconfirmed, detections) matches, u_unconfirmed, u_detection = matching.linear_assignment(dists, thresh=0.7) for itracked, idet in matches: assert last_id_features[dets_index[idet]] is None assert last_ad_id_features[dets_index[idet]] is None last_id_features[dets_index[idet]] = unconfirmed[itracked].smooth_feat last_ad_id_features[dets_index[idet]] = unconfirmed[itracked].smooth_feat_ad tracks_ad.append((unconfirmed[itracked], dets_index[idet])) unconfirmed[itracked].update(detections[idet], self.frame_id_) activated_starcks.append(unconfirmed[itracked]) dets_ids[dets_index[idet]] = unconfirmed[itracked].track_id for it in u_unconfirmed: track = unconfirmed[it] track.mark_removed() removed_stracks.append(track) """ Step 4: Init new stracks""" for inew in u_detection: track = detections[inew] if track.score < self.det_thresh: continue track.activate_(self.kalman_filter_, self.frame_id_, track_id=self_track_id_ori) activated_starcks.append(track) dets_ids[dets_index[inew]] = track.track_id """ Step 5: Update state""" for track in self.lost_stracks_: if self.frame_id_ - track.end_frame > self.max_time_lost: track.mark_removed() removed_stracks.append(track) # print('Ramained match {} s'.format(t4-t3)) self.tracked_stracks_ = [t for t in self.tracked_stracks_ if t.state == TrackState.Tracked] self.tracked_stracks_ = joint_stracks(self.tracked_stracks_, activated_starcks) self.tracked_stracks_ = joint_stracks(self.tracked_stracks_, refind_stracks) self.lost_stracks_ = sub_stracks(self.lost_stracks_, self.tracked_stracks_) self.lost_stracks_.extend(lost_stracks) self.lost_stracks_ = sub_stracks(self.lost_stracks_, self.removed_stracks_) self.removed_stracks_.extend(removed_stracks) self.tracked_stracks_, self.lost_stracks_ = remove_duplicate_stracks(self.tracked_stracks_, self.lost_stracks_) # get scores of lost tracks output_stracks_ori = [track for track in self.tracked_stracks_ if track.is_activated] logger.debug('===========Frame {}=========='.format(self.frame_id_)) logger.debug('Activated: {}'.format([track.track_id for track in activated_starcks])) logger.debug('Refind: {}'.format([track.track_id for track in refind_stracks])) logger.debug('Lost: {}'.format([track.track_id for track in lost_stracks])) logger.debug('Removed: {}'.format([track.track_id for track in removed_stracks])) noise = None suc = 0 for attack_ind, track_id in enumerate(dets_ids): if track_id == attack_id: if self.opt.attack_id > 0: if not hasattr(self, f'frames_{attack_id}'): setattr(self, f'frames_{attack_id}', 0) if getattr(self, f'frames_{attack_id}') < self.FRAME_THR: setattr(self, f'frames_{attack_id}', getattr(self, f'frames_{attack_id}') + 1) break fit = self.CheckFit(dets, id_feature, [attack_id], [attack_ind]) ious = bbox_ious(np.ascontiguousarray(dets[:, :4], dtype=np.float64), np.ascontiguousarray(dets[:, :4], dtype=np.float64)) ious[range(len(dets)), range(len(dets))] = 0 dis = bbox_dis(np.ascontiguousarray(dets[:, :4], dtype=np.float64), np.ascontiguousarray(dets[:, :4], dtype=np.float64)) dis[range(len(dets)), range(len(dets))] = np.inf target_ind = np.argmax(ious[attack_ind]) if ious[attack_ind][target_ind] >= self.attack_iou_thr: if ious[attack_ind][target_ind] == 0: target_ind = np.argmin(dis[attack_ind]) target_id = dets_ids[target_ind] if fit: if self.opt.rand: noise, attack_iter, suc = self.attack_sg_random( im_blob, img0, id_features, dets, inds, remain_inds, last_info=self.ad_last_info, outputs_ori=output, attack_id=attack_id, attack_ind=attack_ind, target_id=target_id, target_ind=target_ind ) else: noise, attack_iter, suc = self.attack_sg( im_blob, img0, id_features, dets, inds, remain_inds, last_info=self.ad_last_info, outputs_ori=output, attack_id=attack_id, attack_ind=attack_ind, target_id=target_id, target_ind=target_ind ) self.attack_iou_thr = 0 if suc: suc = 1 print( f'attack id: {attack_id}\tattack frame {self.frame_id_}: SUCCESS\tl2 distance: {(noise ** 2).sum().sqrt().item()}\titeration: {attack_iter}') else: suc = 2 print( f'attack id: {attack_id}\tattack frame {self.frame_id_}: FAIL\tl2 distance: {(noise ** 2).sum().sqrt().item() if noise is not None else None}\titeration: {attack_iter}') else: suc = 3 if ious[attack_ind][target_ind] == 0: self.temp_i += 1 if self.temp_i >= 10: self.attack_iou_thr = self.ATTACK_IOU_THR else: self.temp_i = 0 else: self.attack_iou_thr = self.ATTACK_IOU_THR if fit: suc = 2 if noise is not None: l2_dis = (noise ** 2).sum().sqrt().item() adImg = torch.clip(im_blob + noise, min=0, max=1) noise = self.recoverNoise(noise, img0) # adImg = np.clip(img0 + noise, a_min=0, a_max=255) # noise = adImg - img0 noise = (noise - np.min(noise)) / (np.max(noise) - np.min(noise)) noise = (noise * 255).astype(np.uint8) else: l2_dis = None adImg = im_blob output_stracks_att = self.update(adImg, img0, track_id=self_track_id_att) adImg = self.recoverNoise(adImg.detach(), img0) return output_stracks_ori, output_stracks_att, adImg, noise, l2_dis, suc def update_attack_mt(self, im_blob, img0, **kwargs): self.frame_id_ += 1 activated_starcks = [] refind_stracks = [] lost_stracks = [] removed_stracks = [] width = img0.shape[1] height = img0.shape[0] inp_height = im_blob.shape[2] inp_width = im_blob.shape[3] c = np.array([width / 2., height / 2.], dtype=np.float32) s = max(float(inp_width) / float(inp_height) * height, width) * 1.0 meta = {'c': c, 's': s, 'out_height': inp_height // self.opt.down_ratio, 'out_width': inp_width // self.opt.down_ratio} ''' Step 1: Network forward, get detections & embeddings''' # with torch.no_grad(): im_blob.requires_grad = True self.model.zero_grad() output = self.model(im_blob)[-1] hm = output['hm'].sigmoid() wh = output['wh'] id_feature = output['id'] id_feature = F.normalize(id_feature, dim=1) reg = output['reg'] if self.opt.reg_offset else None dets_raw, inds = mot_decode(hm, wh, reg=reg, cat_spec_wh=self.opt.cat_spec_wh, K=self.opt.K) id_features = [] for i in range(3): for j in range(3): id_feature_exp = _tranpose_and_gather_feat_expand(id_feature, inds, bias=(i - 1, j - 1)).squeeze(0) id_features.append(id_feature_exp) id_feature = _tranpose_and_gather_feat_expand(id_feature, inds) id_feature = id_feature.squeeze(0) dets = self.post_process(dets_raw.clone(), meta) dets = self.merge_outputs([dets])[1] remain_inds = dets[:, 4] > self.opt.conf_thres dets = dets[remain_inds] id_feature = id_feature[remain_inds] for i in range(len(id_features)): id_features[i] = id_features[i][remain_inds] id_feature = id_feature.detach().cpu().numpy() last_id_features = [None for _ in range(len(dets))] last_ad_id_features = [None for _ in range(len(dets))] dets_index = [i for i in range(len(dets))] dets_ids = [None for _ in range(len(dets))] tracks_ad = [] # import pdb; pdb.set_trace() # vis ''' for i in range(0, dets.shape[0]): bbox = dets[i][0:4] cv2.rectangle(img0, (bbox[0], bbox[1]), (bbox[2], bbox[3]), (0, 255, 0), 2) cv2.imshow('dets', img0) cv2.waitKey(0) id0 = id0-1 ''' if len(dets) > 0: '''Detections''' detections = [STrack(STrack.tlbr_to_tlwh(tlbrs[:4]), tlbrs[4], f, 30) for (tlbrs, f) in zip(dets[:, :5], id_feature)] else: detections = [] ''' Add newly detected tracklets to tracked_stracks''' unconfirmed = [] tracked_stracks = [] # type: list[STrack] for track in self.tracked_stracks_: if not track.is_activated: unconfirmed.append(track) else: tracked_stracks.append(track) ''' Step 2: First association, with embedding''' strack_pool = joint_stracks(tracked_stracks, self.lost_stracks_) STrack.multi_predict(strack_pool) dists = matching.embedding_distance(strack_pool, detections) dists = matching.fuse_motion(self.kalman_filter_, dists, strack_pool, detections) matches, u_track, u_detection = matching.linear_assignment(dists, thresh=0.7) # import pdb; pdb.set_trace() for itracked, idet in matches: track = strack_pool[itracked] det = detections[idet] assert last_id_features[dets_index[idet]] is None assert last_ad_id_features[dets_index[idet]] is None last_id_features[dets_index[idet]] = track.smooth_feat last_ad_id_features[dets_index[idet]] = track.smooth_feat_ad tracks_ad.append((track, dets_index[idet])) if track.state == TrackState.Tracked: track.update(detections[idet], self.frame_id_) activated_starcks.append(track) else: track.re_activate_(det, self.frame_id_, new_id=False) refind_stracks.append(track) dets_ids[dets_index[idet]] = track.track_id ''' Step 3: Second association, with IOU''' dets_index = [dets_index[i] for i in u_detection] detections = [detections[i] for i in u_detection] r_tracked_stracks = [strack_pool[i] for i in u_track if strack_pool[i].state == TrackState.Tracked] dists = matching.iou_distance(r_tracked_stracks, detections) matches, u_track, u_detection = matching.linear_assignment(dists, thresh=0.5) for itracked, idet in matches: track = r_tracked_stracks[itracked] det = detections[idet] assert last_id_features[dets_index[idet]] is None assert last_ad_id_features[dets_index[idet]] is None last_id_features[dets_index[idet]] = track.smooth_feat last_ad_id_features[dets_index[idet]] = track.smooth_feat_ad tracks_ad.append((track, dets_index[idet])) if track.state == TrackState.Tracked: track.update(det, self.frame_id_) activated_starcks.append(track) else: track.re_activate_(det, self.frame_id_, new_id=False) refind_stracks.append(track) dets_ids[dets_index[idet]] = track.track_id for it in u_track: track = r_tracked_stracks[it] if not track.state == TrackState.Lost: track.mark_lost() lost_stracks.append(track) '''Deal with unconfirmed tracks, usually tracks with only one beginning frame''' dets_index = [dets_index[i] for i in u_detection] detections = [detections[i] for i in u_detection] dists = matching.iou_distance(unconfirmed, detections) matches, u_unconfirmed, u_detection = matching.linear_assignment(dists, thresh=0.7) for itracked, idet in matches: assert last_id_features[dets_index[idet]] is None assert last_ad_id_features[dets_index[idet]] is None last_id_features[dets_index[idet]] = unconfirmed[itracked].smooth_feat last_ad_id_features[dets_index[idet]] = unconfirmed[itracked].smooth_feat_ad tracks_ad.append((unconfirmed[itracked], dets_index[idet])) unconfirmed[itracked].update(detections[idet], self.frame_id_) activated_starcks.append(unconfirmed[itracked]) dets_ids[dets_index[idet]] = unconfirmed[itracked].track_id for it in u_unconfirmed: track = unconfirmed[it] track.mark_removed() removed_stracks.append(track) """ Step 4: Init new stracks""" for inew in u_detection: track = detections[inew] if track.score < self.det_thresh: continue track.activate_(self.kalman_filter_, self.frame_id_) activated_starcks.append(track) dets_ids[dets_index[inew]] = track.track_id """ Step 5: Update state""" for track in self.lost_stracks_: if self.frame_id_ - track.end_frame > self.max_time_lost: track.mark_removed() removed_stracks.append(track) # print('Ramained match {} s'.format(t4-t3)) self.tracked_stracks_ = [t for t in self.tracked_stracks_ if t.state == TrackState.Tracked] self.tracked_stracks_ = joint_stracks(self.tracked_stracks_, activated_starcks) self.tracked_stracks_ = joint_stracks(self.tracked_stracks_, refind_stracks) self.lost_stracks_ = sub_stracks(self.lost_stracks_, self.tracked_stracks_) self.lost_stracks_.extend(lost_stracks) self.lost_stracks_ = sub_stracks(self.lost_stracks_, self.removed_stracks_) self.removed_stracks_.extend(removed_stracks) self.tracked_stracks_, self.lost_stracks_ = remove_duplicate_stracks(self.tracked_stracks_, self.lost_stracks_) # get scores of lost tracks output_stracks_ori = [track for track in self.tracked_stracks_ if track.is_activated] id_set = set([track.track_id for track in output_stracks_ori]) for i in range(len(dets_ids)): if dets_ids[i] is not None and dets_ids[i] not in id_set: dets_ids[i] = None output_stracks_ori_ind = [] for ind, track in enumerate(output_stracks_ori): if track.track_id not in self.multiple_ori_ids: self.multiple_ori_ids[track.track_id] = 0 self.multiple_ori_ids[track.track_id] += 1 if self.multiple_ori_ids[track.track_id] <= self.FRAME_THR: output_stracks_ori_ind.append(ind) logger.debug('===========Frame {}=========='.format(self.frame_id_)) logger.debug('Activated: {}'.format([track.track_id for track in activated_starcks])) logger.debug('Refind: {}'.format([track.track_id for track in refind_stracks])) logger.debug('Lost: {}'.format([track.track_id for track in lost_stracks])) logger.debug('Removed: {}'.format([track.track_id for track in removed_stracks])) attack_ids = [] target_ids = [] attack_inds = [] target_inds = [] noise = None if len(dets) > 0: ious = bbox_ious(np.ascontiguousarray(dets[:, :4], dtype=np.float64), np.ascontiguousarray(dets[:, :4], dtype=np.float64)) ious[range(len(dets)), range(len(dets))] = 0 ious_inds = np.argmax(ious, axis=1) dis = bbox_dis(np.ascontiguousarray(dets[:, :4], dtype=np.float64), np.ascontiguousarray(dets[:, :4], dtype=np.float64)) dis[range(len(dets)), range(len(dets))] = np.inf dis_inds = np.argmin(dis, axis=1) for attack_ind, track_id in enumerate(dets_ids): if track_id is None or self.multiple_ori_ids[track_id] <= self.FRAME_THR \ or dets_ids[ious_inds[attack_ind]] not in self.multiple_ori2att \ or track_id not in self.multiple_ori2att: continue if ious[attack_ind, ious_inds[attack_ind]] > self.ATTACK_IOU_THR or ( track_id in self.low_iou_ids and ious[attack_ind, ious_inds[attack_ind]] > 0 ): attack_ids.append(track_id) target_ids.append(dets_ids[ious_inds[attack_ind]]) attack_inds.append(attack_ind) target_inds.append(ious_inds[attack_ind]) if hasattr(self, f'temp_i_{track_id}'): self.__setattr__(f'temp_i_{track_id}', 0) elif ious[attack_ind, ious_inds[attack_ind]] == 0 and track_id in self.low_iou_ids: if hasattr(self, f'temp_i_{track_id}'): self.__setattr__(f'temp_i_{track_id}', self.__getattribute__(f'temp_i_{track_id}') + 1) else: self.__setattr__(f'temp_i_{track_id}', 1) if self.__getattribute__(f'temp_i_{track_id}') > 10: self.low_iou_ids.remove(track_id) elif dets_ids[dis_inds[attack_ind]] in self.multiple_ori2att: attack_ids.append(track_id) target_ids.append(dets_ids[dis_inds[attack_ind]]) attack_inds.append(attack_ind) target_inds.append(dis_inds[attack_ind]) fit_index = self.CheckFit(dets, id_feature, attack_ids, attack_inds) if len(attack_ids) else [] if fit_index: attack_ids = np.array(attack_ids)[fit_index] target_ids = np.array(target_ids)[fit_index] attack_inds = np.array(attack_inds)[fit_index] target_inds = np.array(target_inds)[fit_index] if self.opt.rand: noise, attack_iter, suc = self.attack_mt_random( im_blob, img0, id_features, dets, inds, remain_inds, last_info=self.ad_last_info, outputs_ori=output, attack_ids=attack_ids, attack_inds=attack_inds, target_ids=target_ids, target_inds=target_inds ) else: noise, attack_iter, suc = self.attack_mt( im_blob, img0, id_features, dets, inds, remain_inds, last_info=self.ad_last_info, outputs_ori=output, attack_ids=attack_ids, attack_inds=attack_inds, target_ids=target_ids, target_inds=target_inds ) self.low_iou_ids.update(set(attack_ids)) if suc: self.attacked_ids.update(set(attack_ids)) print( f'attack ids: {attack_ids}\tattack frame {self.frame_id_}: SUCCESS\tl2 distance: {(noise ** 2).sum().sqrt().item()}\titeration: {attack_iter}') else: print(f'attack ids: {attack_ids}\tattack frame {self.frame_id_}: FAIL\tl2 distance: {(noise ** 2).sum().sqrt().item() if noise is not None else None}\titeration: {attack_iter}') if noise is not None: l2_dis = (noise ** 2).sum().sqrt().item() adImg = torch.clip(im_blob + noise, min=0, max=1) noise = self.recoverNoise(noise, img0) noise = (noise - np.min(noise)) / (np.max(noise) - np.min(noise)) noise = (noise * 255).astype(np.uint8) else: l2_dis = None adImg = im_blob output_stracks_att = self.update(adImg, img0) adImg = self.recoverNoise(adImg.detach(), img0) output_stracks_att_ind = [] for ind, track in enumerate(output_stracks_att): if track.track_id not in self.multiple_att_ids: self.multiple_att_ids[track.track_id] = 0 self.multiple_att_ids[track.track_id] += 1 if self.multiple_att_ids[track.track_id] <= self.FRAME_THR: output_stracks_att_ind.append(ind) if len(output_stracks_ori_ind) and len(output_stracks_att_ind): ori_dets = [track.curr_tlbr for i, track in enumerate(output_stracks_ori) if i in output_stracks_ori_ind] att_dets = [track.curr_tlbr for i, track in enumerate(output_stracks_att) if i in output_stracks_att_ind] ori_dets = np.stack(ori_dets).astype(np.float64) att_dets = np.stack(att_dets).astype(np.float64) ious = bbox_ious(ori_dets, att_dets) row_ind, col_ind = linear_sum_assignment(-ious) for i in range(len(row_ind)): if ious[row_ind[i], col_ind[i]] > 0.9: ori_id = output_stracks_ori[output_stracks_ori_ind[row_ind[i]]].track_id att_id = output_stracks_att[output_stracks_att_ind[col_ind[i]]].track_id self.multiple_ori2att[ori_id] = att_id return output_stracks_ori, output_stracks_att, adImg, noise, l2_dis def update_attack_sg_feat(self, im_blob, img0, **kwargs): self.frame_id_ += 1 attack_id = kwargs['attack_id'] self_track_id_ori = kwargs.get('track_id', {}).get('origin', None) self_track_id_att = kwargs.get('track_id', {}).get('attack', None) activated_starcks = [] refind_stracks = [] lost_stracks = [] removed_stracks = [] width = img0.shape[1] height = img0.shape[0] inp_height = im_blob.shape[2] inp_width = im_blob.shape[3] c = np.array([width / 2., height / 2.], dtype=np.float32) s = max(float(inp_width) / float(inp_height) * height, width) * 1.0 meta = {'c': c, 's': s, 'out_height': inp_height // self.opt.down_ratio, 'out_width': inp_width // self.opt.down_ratio} ''' Step 1: Network forward, get detections & embeddings''' # with torch.no_grad(): im_blob.requires_grad = True self.model.zero_grad() output = self.model(im_blob)[-1] hm = output['hm'].sigmoid() wh = output['wh'] id_feature = output['id'] id_feature = F.normalize(id_feature, dim=1) reg = output['reg'] if self.opt.reg_offset else None dets_raw, inds = mot_decode(hm, wh, reg=reg, cat_spec_wh=self.opt.cat_spec_wh, K=self.opt.K) id_features = [] for i in range(3): for j in range(3): id_feature_exp = _tranpose_and_gather_feat_expand(id_feature, inds, bias=(i - 1, j - 1)).squeeze(0) id_features.append(id_feature_exp) id_feature = _tranpose_and_gather_feat_expand(id_feature, inds) id_feature = id_feature.squeeze(0) dets = self.post_process(dets_raw.clone(), meta) dets = self.merge_outputs([dets])[1] remain_inds = dets[:, 4] > self.opt.conf_thres dets = dets[remain_inds] id_feature = id_feature[remain_inds] for i in range(len(id_features)): id_features[i] = id_features[i][remain_inds] id_feature = id_feature.detach().cpu().numpy() last_id_features = [None for _ in range(len(dets))] last_ad_id_features = [None for _ in range(len(dets))] dets_index = [i for i in range(len(dets))] dets_ids = [None for _ in range(len(dets))] tracks_ad = [] # import pdb; pdb.set_trace() # vis ''' for i in range(0, dets.shape[0]): bbox = dets[i][0:4] cv2.rectangle(img0, (bbox[0], bbox[1]), (bbox[2], bbox[3]), (0, 255, 0), 2) cv2.imshow('dets', img0) cv2.waitKey(0) id0 = id0-1 ''' if len(dets) > 0: '''Detections''' detections = [STrack(STrack.tlbr_to_tlwh(tlbrs[:4]), tlbrs[4], f, 30) for (tlbrs, f) in zip(dets[:, :5], id_feature)] else: detections = [] ''' Add newly detected tracklets to tracked_stracks''' unconfirmed = [] tracked_stracks = [] # type: list[STrack] for track in self.tracked_stracks_: if not track.is_activated: unconfirmed.append(track) else: tracked_stracks.append(track) ''' Step 2: First association, with embedding''' strack_pool = joint_stracks(tracked_stracks, self.lost_stracks_) STrack.multi_predict(strack_pool) dists = matching.embedding_distance(strack_pool, detections) # dists = matching.gate_cost_matrix(self.kalman_filter, dists, strack_pool, detections) dists = matching.fuse_motion(self.kalman_filter_, dists, strack_pool, detections) matches, u_track, u_detection = matching.linear_assignment(dists, thresh=0.7) # import pdb; pdb.set_trace() for itracked, idet in matches: track = strack_pool[itracked] det = detections[idet] assert last_id_features[dets_index[idet]] is None assert last_ad_id_features[dets_index[idet]] is None last_id_features[dets_index[idet]] = track.smooth_feat last_ad_id_features[dets_index[idet]] = track.smooth_feat_ad tracks_ad.append((track, dets_index[idet])) if track.state == TrackState.Tracked: track.update(detections[idet], self.frame_id_) activated_starcks.append(track) else: track.re_activate_(det, self.frame_id_, new_id=False) refind_stracks.append(track) dets_ids[dets_index[idet]] = track.track_id ''' Step 3: Second association, with IOU''' dets_index = [dets_index[i] for i in u_detection] detections = [detections[i] for i in u_detection] r_tracked_stracks = [strack_pool[i] for i in u_track if strack_pool[i].state == TrackState.Tracked] dists = matching.iou_distance(r_tracked_stracks, detections) matches, u_track, u_detection = matching.linear_assignment(dists, thresh=0.5) for itracked, idet in matches: track = r_tracked_stracks[itracked] det = detections[idet] assert last_id_features[dets_index[idet]] is None assert last_ad_id_features[dets_index[idet]] is None last_id_features[dets_index[idet]] = track.smooth_feat last_ad_id_features[dets_index[idet]] = track.smooth_feat_ad tracks_ad.append((track, dets_index[idet])) if track.state == TrackState.Tracked: track.update(det, self.frame_id_) activated_starcks.append(track) else: track.re_activate_(det, self.frame_id_, new_id=False) refind_stracks.append(track) dets_ids[dets_index[idet]] = track.track_id for it in u_track: track = r_tracked_stracks[it] if not track.state == TrackState.Lost: track.mark_lost() lost_stracks.append(track) '''Deal with unconfirmed tracks, usually tracks with only one beginning frame''' dets_index = [dets_index[i] for i in u_detection] detections = [detections[i] for i in u_detection] dists = matching.iou_distance(unconfirmed, detections) matches, u_unconfirmed, u_detection = matching.linear_assignment(dists, thresh=0.7) for itracked, idet in matches: assert last_id_features[dets_index[idet]] is None assert last_ad_id_features[dets_index[idet]] is None last_id_features[dets_index[idet]] = unconfirmed[itracked].smooth_feat last_ad_id_features[dets_index[idet]] = unconfirmed[itracked].smooth_feat_ad tracks_ad.append((unconfirmed[itracked], dets_index[idet])) unconfirmed[itracked].update(detections[idet], self.frame_id_) activated_starcks.append(unconfirmed[itracked]) dets_ids[dets_index[idet]] = unconfirmed[itracked].track_id for it in u_unconfirmed: track = unconfirmed[it] track.mark_removed() removed_stracks.append(track) """ Step 4: Init new stracks""" for inew in u_detection: track = detections[inew] if track.score < self.det_thresh: continue track.activate_(self.kalman_filter_, self.frame_id_, track_id=self_track_id_ori) activated_starcks.append(track) dets_ids[dets_index[inew]] = track.track_id """ Step 5: Update state""" for track in self.lost_stracks_: if self.frame_id_ - track.end_frame > self.max_time_lost: track.mark_removed() removed_stracks.append(track) # print('Ramained match {} s'.format(t4-t3)) self.tracked_stracks_ = [t for t in self.tracked_stracks_ if t.state == TrackState.Tracked] self.tracked_stracks_ = joint_stracks(self.tracked_stracks_, activated_starcks) self.tracked_stracks_ = joint_stracks(self.tracked_stracks_, refind_stracks) self.lost_stracks_ = sub_stracks(self.lost_stracks_, self.tracked_stracks_) self.lost_stracks_.extend(lost_stracks) self.lost_stracks_ = sub_stracks(self.lost_stracks_, self.removed_stracks_) self.removed_stracks_.extend(removed_stracks) self.tracked_stracks_, self.lost_stracks_ = remove_duplicate_stracks(self.tracked_stracks_, self.lost_stracks_) # get scores of lost tracks output_stracks_ori = [track for track in self.tracked_stracks_ if track.is_activated] logger.debug('===========Frame {}=========='.format(self.frame_id_)) logger.debug('Activated: {}'.format([track.track_id for track in activated_starcks])) logger.debug('Refind: {}'.format([track.track_id for track in refind_stracks])) logger.debug('Lost: {}'.format([track.track_id for track in lost_stracks])) logger.debug('Removed: {}'.format([track.track_id for track in removed_stracks])) noise = None suc = 0 for attack_ind, track_id in enumerate(dets_ids): if track_id == attack_id: if self.opt.attack_id > 0: if not hasattr(self, f'frames_{attack_id}'): setattr(self, f'frames_{attack_id}', 0) if getattr(self, f'frames_{attack_id}') < self.FRAME_THR: setattr(self, f'frames_{attack_id}', getattr(self, f'frames_{attack_id}') + 1) break fit = self.CheckFit(dets, id_feature, [attack_id], [attack_ind]) ious = bbox_ious(np.ascontiguousarray(dets[:, :4], dtype=np.float64), np.ascontiguousarray(dets[:, :4], dtype=np.float64)) ious[range(len(dets)), range(len(dets))] = 0 dis = bbox_dis(np.ascontiguousarray(dets[:, :4], dtype=np.float64), np.ascontiguousarray(dets[:, :4], dtype=np.float64)) dis[range(len(dets)), range(len(dets))] = np.inf target_ind = np.argmax(ious[attack_ind]) if ious[attack_ind][target_ind] >= self.attack_iou_thr: if ious[attack_ind][target_ind] == 0: target_ind = np.argmin(dis[attack_ind]) target_id = dets_ids[target_ind] if fit: noise, attack_iter, suc = self.attack_sg_feat( im_blob, img0, id_features, dets, inds, remain_inds, last_info=self.ad_last_info, outputs_ori=output, attack_id=attack_id, attack_ind=attack_ind, target_id=target_id, target_ind=target_ind ) self.attack_iou_thr = 0 if suc: suc = 1 print( f'attack id: {attack_id}\tattack frame {self.frame_id_}: SUCCESS\tl2 distance: {(noise ** 2).sum().sqrt().item()}\titeration: {attack_iter}') else: suc = 2 print( f'attack id: {attack_id}\tattack frame {self.frame_id_}: FAIL\tl2 distance: {(noise ** 2).sum().sqrt().item()}\titeration: {attack_iter}') else: suc = 3 if ious[attack_ind][target_ind] == 0: self.temp_i += 1 if self.temp_i >= 10: self.attack_iou_thr = self.ATTACK_IOU_THR else: self.temp_i = 0 else: self.attack_iou_thr = self.ATTACK_IOU_THR if fit: suc = 2 if noise is not None: l2_dis = (noise ** 2).sum().sqrt().item() adImg = torch.clip(im_blob + noise, min=0, max=1) noise = self.recoverNoise(noise, img0) noise = (noise - np.min(noise)) / (np.max(noise) - np.min(noise)) noise = (noise * 255).astype(np.uint8) else: l2_dis = None adImg = im_blob output_stracks_att = self.update(adImg, img0, track_id=self_track_id_att) adImg = self.recoverNoise(adImg.detach(), img0) return output_stracks_ori, output_stracks_att, adImg, noise, l2_dis, suc def update_attack_sg_cl(self, im_blob, img0, **kwargs): self.frame_id_ += 1 attack_id = kwargs['attack_id'] self_track_id_ori = kwargs.get('track_id', {}).get('origin', None) self_track_id_att = kwargs.get('track_id', {}).get('attack', None) activated_starcks = [] refind_stracks = [] lost_stracks = [] removed_stracks = [] width = img0.shape[1] height = img0.shape[0] inp_height = im_blob.shape[2] inp_width = im_blob.shape[3] c = np.array([width / 2., height / 2.], dtype=np.float32) s = max(float(inp_width) / float(inp_height) * height, width) * 1.0 meta = {'c': c, 's': s, 'out_height': inp_height // self.opt.down_ratio, 'out_width': inp_width // self.opt.down_ratio} ''' Step 1: Network forward, get detections & embeddings''' # with torch.no_grad(): im_blob.requires_grad = True self.model.zero_grad() output = self.model(im_blob)[-1] hm = output['hm'].sigmoid() wh = output['wh'] id_feature = output['id'] id_feature = F.normalize(id_feature, dim=1) reg = output['reg'] if self.opt.reg_offset else None dets_raw, inds = mot_decode(hm, wh, reg=reg, cat_spec_wh=self.opt.cat_spec_wh, K=self.opt.K) id_features = [] for i in range(3): for j in range(3): id_feature_exp = _tranpose_and_gather_feat_expand(id_feature, inds, bias=(i - 1, j - 1)).squeeze(0) id_features.append(id_feature_exp) id_feature = _tranpose_and_gather_feat_expand(id_feature, inds) id_feature = id_feature.squeeze(0) dets = self.post_process(dets_raw.clone(), meta) dets = self.merge_outputs([dets])[1] remain_inds = dets[:, 4] > self.opt.conf_thres dets = dets[remain_inds] id_feature = id_feature[remain_inds] for i in range(len(id_features)): id_features[i] = id_features[i][remain_inds] id_feature = id_feature.detach().cpu().numpy() last_id_features = [None for _ in range(len(dets))] last_ad_id_features = [None for _ in range(len(dets))] dets_index = [i for i in range(len(dets))] dets_ids = [None for _ in range(len(dets))] tracks_ad = [] # import pdb; pdb.set_trace() # vis ''' for i in range(0, dets.shape[0]): bbox = dets[i][0:4] cv2.rectangle(img0, (bbox[0], bbox[1]), (bbox[2], bbox[3]), (0, 255, 0), 2) cv2.imshow('dets', img0) cv2.waitKey(0) id0 = id0-1 ''' if len(dets) > 0: '''Detections''' detections = [STrack(STrack.tlbr_to_tlwh(tlbrs[:4]), tlbrs[4], f, 30) for (tlbrs, f) in zip(dets[:, :5], id_feature)] else: detections = [] ''' Add newly detected tracklets to tracked_stracks''' unconfirmed = [] tracked_stracks = [] # type: list[STrack] for track in self.tracked_stracks_: if not track.is_activated: unconfirmed.append(track) else: tracked_stracks.append(track) ''' Step 2: First association, with embedding''' strack_pool = joint_stracks(tracked_stracks, self.lost_stracks_) STrack.multi_predict(strack_pool) dists = matching.embedding_distance(strack_pool, detections) # dists = matching.gate_cost_matrix(self.kalman_filter, dists, strack_pool, detections) dists = matching.fuse_motion(self.kalman_filter_, dists, strack_pool, detections) matches, u_track, u_detection = matching.linear_assignment(dists, thresh=0.7) # import pdb; pdb.set_trace() for itracked, idet in matches: track = strack_pool[itracked] det = detections[idet] assert last_id_features[dets_index[idet]] is None assert last_ad_id_features[dets_index[idet]] is None last_id_features[dets_index[idet]] = track.smooth_feat last_ad_id_features[dets_index[idet]] = track.smooth_feat_ad tracks_ad.append((track, dets_index[idet])) if track.state == TrackState.Tracked: track.update(detections[idet], self.frame_id_) activated_starcks.append(track) else: track.re_activate_(det, self.frame_id_, new_id=False) refind_stracks.append(track) dets_ids[dets_index[idet]] = track.track_id ''' Step 3: Second association, with IOU''' dets_index = [dets_index[i] for i in u_detection] detections = [detections[i] for i in u_detection] r_tracked_stracks = [strack_pool[i] for i in u_track if strack_pool[i].state == TrackState.Tracked] dists = matching.iou_distance(r_tracked_stracks, detections) matches, u_track, u_detection = matching.linear_assignment(dists, thresh=0.5) for itracked, idet in matches: track = r_tracked_stracks[itracked] det = detections[idet] assert last_id_features[dets_index[idet]] is None assert last_ad_id_features[dets_index[idet]] is None last_id_features[dets_index[idet]] = track.smooth_feat last_ad_id_features[dets_index[idet]] = track.smooth_feat_ad tracks_ad.append((track, dets_index[idet])) if track.state == TrackState.Tracked: track.update(det, self.frame_id_) activated_starcks.append(track) else: track.re_activate_(det, self.frame_id_, new_id=False) refind_stracks.append(track) dets_ids[dets_index[idet]] = track.track_id for it in u_track: track = r_tracked_stracks[it] if not track.state == TrackState.Lost: track.mark_lost() lost_stracks.append(track) '''Deal with unconfirmed tracks, usually tracks with only one beginning frame''' dets_index = [dets_index[i] for i in u_detection] detections = [detections[i] for i in u_detection] dists = matching.iou_distance(unconfirmed, detections) matches, u_unconfirmed, u_detection = matching.linear_assignment(dists, thresh=0.7) for itracked, idet in matches: assert last_id_features[dets_index[idet]] is None assert last_ad_id_features[dets_index[idet]] is None last_id_features[dets_index[idet]] = unconfirmed[itracked].smooth_feat last_ad_id_features[dets_index[idet]] = unconfirmed[itracked].smooth_feat_ad tracks_ad.append((unconfirmed[itracked], dets_index[idet])) unconfirmed[itracked].update(detections[idet], self.frame_id_) activated_starcks.append(unconfirmed[itracked]) dets_ids[dets_index[idet]] = unconfirmed[itracked].track_id for it in u_unconfirmed: track = unconfirmed[it] track.mark_removed() removed_stracks.append(track) """ Step 4: Init new stracks""" for inew in u_detection: track = detections[inew] if track.score < self.det_thresh: continue track.activate_(self.kalman_filter_, self.frame_id_, track_id=self_track_id_ori) activated_starcks.append(track) dets_ids[dets_index[inew]] = track.track_id """ Step 5: Update state""" for track in self.lost_stracks_: if self.frame_id_ - track.end_frame > self.max_time_lost: track.mark_removed() removed_stracks.append(track) # print('Ramained match {} s'.format(t4-t3)) self.tracked_stracks_ = [t for t in self.tracked_stracks_ if t.state == TrackState.Tracked] self.tracked_stracks_ = joint_stracks(self.tracked_stracks_, activated_starcks) self.tracked_stracks_ = joint_stracks(self.tracked_stracks_, refind_stracks) self.lost_stracks_ = sub_stracks(self.lost_stracks_, self.tracked_stracks_) self.lost_stracks_.extend(lost_stracks) self.lost_stracks_ = sub_stracks(self.lost_stracks_, self.removed_stracks_) self.removed_stracks_.extend(removed_stracks) self.tracked_stracks_, self.lost_stracks_ = remove_duplicate_stracks(self.tracked_stracks_, self.lost_stracks_) # get scores of lost tracks output_stracks_ori = [track for track in self.tracked_stracks_ if track.is_activated] logger.debug('===========Frame {}=========='.format(self.frame_id_)) logger.debug('Activated: {}'.format([track.track_id for track in activated_starcks])) logger.debug('Refind: {}'.format([track.track_id for track in refind_stracks])) logger.debug('Lost: {}'.format([track.track_id for track in lost_stracks])) logger.debug('Removed: {}'.format([track.track_id for track in removed_stracks])) noise = None suc = 0 for attack_ind, track_id in enumerate(dets_ids): if track_id == attack_id: if self.opt.attack_id > 0: if not hasattr(self, f'frames_{attack_id}'): setattr(self, f'frames_{attack_id}', 0) if getattr(self, f'frames_{attack_id}') < self.FRAME_THR: setattr(self, f'frames_{attack_id}', getattr(self, f'frames_{attack_id}') + 1) break fit = self.CheckFit(dets, id_feature, [attack_id], [attack_ind]) ious = bbox_ious(np.ascontiguousarray(dets[:, :4], dtype=np.float64), np.ascontiguousarray(dets[:, :4], dtype=np.float64)) ious[range(len(dets)), range(len(dets))] = 0 dis = bbox_dis(np.ascontiguousarray(dets[:, :4], dtype=np.float64), np.ascontiguousarray(dets[:, :4], dtype=np.float64)) dis[range(len(dets)), range(len(dets))] = np.inf target_ind = np.argmax(ious[attack_ind]) if ious[attack_ind][target_ind] >= self.attack_iou_thr: if ious[attack_ind][target_ind] == 0: target_ind = np.argmin(dis[attack_ind]) target_id = dets_ids[target_ind] if fit: noise, attack_iter, suc = self.attack_sg_cl( im_blob, img0, id_features, dets, inds, remain_inds, last_info=self.ad_last_info, outputs_ori=output, attack_id=attack_id, attack_ind=attack_ind, target_id=target_id, target_ind=target_ind ) self.attack_iou_thr = 0 if suc: suc = 1 print( f'attack id: {attack_id}\tattack frame {self.frame_id_}: SUCCESS\tl2 distance: {(noise ** 2).sum().sqrt().item()}\titeration: {attack_iter}') else: suc = 2 print( f'attack id: {attack_id}\tattack frame {self.frame_id_}: FAIL\tl2 distance: {(noise ** 2).sum().sqrt().item() if noise is not None else None}\titeration: {attack_iter}') else: suc = 3 if ious[attack_ind][target_ind] == 0: self.temp_i += 1 if self.temp_i >= 10: self.attack_iou_thr = self.ATTACK_IOU_THR else: self.temp_i = 0 else: self.attack_iou_thr = self.ATTACK_IOU_THR if fit: suc = 2 if noise is not None: l2_dis = (noise ** 2).sum().sqrt().item() adImg = torch.clip(im_blob + noise, min=0, max=1) noise = self.recoverNoise(noise, img0) # adImg = np.clip(img0 + noise, a_min=0, a_max=255) # noise = adImg - img0 noise = (noise - np.min(noise)) / (np.max(noise) - np.min(noise)) noise = (noise * 255).astype(np.uint8) else: l2_dis = None adImg = im_blob output_stracks_att = self.update(adImg, img0, track_id=self_track_id_att) adImg = self.recoverNoise(adImg.detach(), img0) return output_stracks_ori, output_stracks_att, adImg, noise, l2_dis, suc def update_attack_sg_det(self, im_blob, img0, **kwargs): self.frame_id_ += 1 attack_id = kwargs['attack_id'] self_track_id_ori = kwargs.get('track_id', {}).get('origin', None) self_track_id_att = kwargs.get('track_id', {}).get('attack', None) activated_starcks = [] refind_stracks = [] lost_stracks = [] removed_stracks = [] width = img0.shape[1] height = img0.shape[0] inp_height = im_blob.shape[2] inp_width = im_blob.shape[3] c = np.array([width / 2., height / 2.], dtype=np.float32) s = max(float(inp_width) / float(inp_height) * height, width) * 1.0 meta = {'c': c, 's': s, 'out_height': inp_height // self.opt.down_ratio, 'out_width': inp_width // self.opt.down_ratio} ''' Step 1: Network forward, get detections & embeddings''' # with torch.no_grad(): im_blob.requires_grad = True self.model.zero_grad() output = self.model(im_blob)[-1] hm = output['hm'].sigmoid() wh = output['wh'] id_feature = output['id'] id_feature = F.normalize(id_feature, dim=1) reg = output['reg'] if self.opt.reg_offset else None dets_raw, inds = mot_decode(hm, wh, reg=reg, cat_spec_wh=self.opt.cat_spec_wh, K=self.opt.K) id_features = [] for i in range(3): for j in range(3): id_feature_exp = _tranpose_and_gather_feat_expand(id_feature, inds, bias=(i - 1, j - 1)).squeeze(0) id_features.append(id_feature_exp) id_feature = _tranpose_and_gather_feat_expand(id_feature, inds) id_feature = id_feature.squeeze(0) dets = self.post_process(dets_raw.clone(), meta) dets = self.merge_outputs([dets])[1] remain_inds = dets[:, 4] > self.opt.conf_thres dets = dets[remain_inds] id_feature = id_feature[remain_inds] for i in range(len(id_features)): id_features[i] = id_features[i][remain_inds] id_feature = id_feature.detach().cpu().numpy() last_id_features = [None for _ in range(len(dets))] last_ad_id_features = [None for _ in range(len(dets))] dets_index = [i for i in range(len(dets))] dets_ids = [None for _ in range(len(dets))] tracks_ad = [] # import pdb; pdb.set_trace() # vis ''' for i in range(0, dets.shape[0]): bbox = dets[i][0:4] cv2.rectangle(img0, (bbox[0], bbox[1]), (bbox[2], bbox[3]), (0, 255, 0), 2) cv2.imshow('dets', img0) cv2.waitKey(0) id0 = id0-1 ''' if len(dets) > 0: '''Detections''' detections = [STrack(STrack.tlbr_to_tlwh(tlbrs[:4]), tlbrs[4], f, 30) for (tlbrs, f) in zip(dets[:, :5], id_feature)] else: detections = [] ''' Add newly detected tracklets to tracked_stracks''' unconfirmed = [] tracked_stracks = [] # type: list[STrack] for track in self.tracked_stracks_: if not track.is_activated: unconfirmed.append(track) else: tracked_stracks.append(track) ''' Step 2: First association, with embedding''' strack_pool = joint_stracks(tracked_stracks, self.lost_stracks_) STrack.multi_predict(strack_pool) dists = matching.embedding_distance(strack_pool, detections) # dists = matching.gate_cost_matrix(self.kalman_filter, dists, strack_pool, detections) dists = matching.fuse_motion(self.kalman_filter_, dists, strack_pool, detections) matches, u_track, u_detection = matching.linear_assignment(dists, thresh=0.7) # import pdb; pdb.set_trace() for itracked, idet in matches: track = strack_pool[itracked] det = detections[idet] assert last_id_features[dets_index[idet]] is None assert last_ad_id_features[dets_index[idet]] is None last_id_features[dets_index[idet]] = track.smooth_feat last_ad_id_features[dets_index[idet]] = track.smooth_feat_ad tracks_ad.append((track, dets_index[idet])) if track.state == TrackState.Tracked: track.update(detections[idet], self.frame_id_) activated_starcks.append(track) else: track.re_activate_(det, self.frame_id_, new_id=False) refind_stracks.append(track) dets_ids[dets_index[idet]] = track.track_id ''' Step 3: Second association, with IOU''' dets_index = [dets_index[i] for i in u_detection] detections = [detections[i] for i in u_detection] r_tracked_stracks = [strack_pool[i] for i in u_track if strack_pool[i].state == TrackState.Tracked] dists = matching.iou_distance(r_tracked_stracks, detections) matches, u_track, u_detection = matching.linear_assignment(dists, thresh=0.5) for itracked, idet in matches: track = r_tracked_stracks[itracked] det = detections[idet] assert last_id_features[dets_index[idet]] is None assert last_ad_id_features[dets_index[idet]] is None last_id_features[dets_index[idet]] = track.smooth_feat last_ad_id_features[dets_index[idet]] = track.smooth_feat_ad tracks_ad.append((track, dets_index[idet])) if track.state == TrackState.Tracked: track.update(det, self.frame_id_) activated_starcks.append(track) else: track.re_activate_(det, self.frame_id_, new_id=False) refind_stracks.append(track) dets_ids[dets_index[idet]] = track.track_id for it in u_track: track = r_tracked_stracks[it] if not track.state == TrackState.Lost: track.mark_lost() lost_stracks.append(track) '''Deal with unconfirmed tracks, usually tracks with only one beginning frame''' dets_index = [dets_index[i] for i in u_detection] detections = [detections[i] for i in u_detection] dists = matching.iou_distance(unconfirmed, detections) matches, u_unconfirmed, u_detection = matching.linear_assignment(dists, thresh=0.7) for itracked, idet in matches: assert last_id_features[dets_index[idet]] is None assert last_ad_id_features[dets_index[idet]] is None last_id_features[dets_index[idet]] = unconfirmed[itracked].smooth_feat last_ad_id_features[dets_index[idet]] = unconfirmed[itracked].smooth_feat_ad tracks_ad.append((unconfirmed[itracked], dets_index[idet])) unconfirmed[itracked].update(detections[idet], self.frame_id_) activated_starcks.append(unconfirmed[itracked]) dets_ids[dets_index[idet]] = unconfirmed[itracked].track_id for it in u_unconfirmed: track = unconfirmed[it] track.mark_removed() removed_stracks.append(track) """ Step 4: Init new stracks""" for inew in u_detection: track = detections[inew] if track.score < self.det_thresh: continue track.activate_(self.kalman_filter_, self.frame_id_, track_id=self_track_id_ori) activated_starcks.append(track) dets_ids[dets_index[inew]] = track.track_id """ Step 5: Update state""" for track in self.lost_stracks_: if self.frame_id_ - track.end_frame > self.max_time_lost: track.mark_removed() removed_stracks.append(track) # print('Ramained match {} s'.format(t4-t3)) self.tracked_stracks_ = [t for t in self.tracked_stracks_ if t.state == TrackState.Tracked] self.tracked_stracks_ = joint_stracks(self.tracked_stracks_, activated_starcks) self.tracked_stracks_ = joint_stracks(self.tracked_stracks_, refind_stracks) self.lost_stracks_ = sub_stracks(self.lost_stracks_, self.tracked_stracks_) self.lost_stracks_.extend(lost_stracks) self.lost_stracks_ = sub_stracks(self.lost_stracks_, self.removed_stracks_) self.removed_stracks_.extend(removed_stracks) self.tracked_stracks_, self.lost_stracks_ = remove_duplicate_stracks(self.tracked_stracks_, self.lost_stracks_) # get scores of lost tracks output_stracks_ori = [track for track in self.tracked_stracks_ if track.is_activated] logger.debug('===========Frame {}=========='.format(self.frame_id_)) logger.debug('Activated: {}'.format([track.track_id for track in activated_starcks])) logger.debug('Refind: {}'.format([track.track_id for track in refind_stracks])) logger.debug('Lost: {}'.format([track.track_id for track in lost_stracks])) logger.debug('Removed: {}'.format([track.track_id for track in removed_stracks])) noise = None suc = 0 for attack_ind, track_id in enumerate(dets_ids): if track_id == attack_id: if self.opt.attack_id > 0: if not hasattr(self, f'frames_{attack_id}'): setattr(self, f'frames_{attack_id}', 0) if getattr(self, f'frames_{attack_id}') < self.FRAME_THR: setattr(self, f'frames_{attack_id}', getattr(self, f'frames_{attack_id}') + 1) break ious = bbox_ious(np.ascontiguousarray(dets[:, :4], dtype=np.float64), np.ascontiguousarray(dets[:, :4], dtype=np.float64)) ious = self.processIoUs(ious) ious = ious + ious.T target_ind = np.argmax(ious[attack_ind]) if ious[attack_ind][target_ind] >= self.attack_iou_thr: fit = self.CheckFit(dets, id_feature, [attack_id], [attack_ind]) if fit: noise, attack_iter, suc = self.attack_sg_det( im_blob, img0, dets, inds, remain_inds, last_info=self.ad_last_info, outputs_ori=output, attack_id=attack_id, attack_ind=attack_ind ) self.attack_iou_thr = 0 if suc: suc = 1 print( f'attack id: {attack_id}\tattack frame {self.frame_id_}: SUCCESS\tl2 distance: {(noise ** 2).sum().sqrt().item()}\titeration: {attack_iter}') else: suc = 2 print( f'attack id: {attack_id}\tattack frame {self.frame_id_}: FAIL\tl2 distance: {(noise ** 2).sum().sqrt().item()}\titeration: {attack_iter}') else: suc = 3 if ious[attack_ind][target_ind] == 0: self.temp_i += 1 if self.temp_i >= 10: self.attack_iou_thr = self.ATTACK_IOU_THR else: self.temp_i = 0 else: self.attack_iou_thr = self.ATTACK_IOU_THR break if noise is not None: l2_dis = (noise ** 2).sum().sqrt().item() adImg = torch.clip(im_blob + noise, min=0, max=1) noise = self.recoverNoise(noise, img0) noise = (noise - np.min(noise)) / (np.max(noise) - np.min(noise)) noise = (noise * 255).astype(np.uint8) else: l2_dis = None adImg = im_blob output_stracks_att = self.update(adImg, img0, track_id=self_track_id_att) adImg = self.recoverNoise(adImg.detach(), img0) return output_stracks_ori, output_stracks_att, adImg, noise, l2_dis, suc def update_attack_sg_hj(self, im_blob, img0, **kwargs): self.frame_id_ += 1 attack_id = kwargs['attack_id'] self_track_id_ori = kwargs.get('track_id', {}).get('origin', None) self_track_id_att = kwargs.get('track_id', {}).get('attack', None) activated_starcks = [] refind_stracks = [] lost_stracks = [] removed_stracks = [] width = img0.shape[1] height = img0.shape[0] inp_height = im_blob.shape[2] inp_width = im_blob.shape[3] c = np.array([width / 2., height / 2.], dtype=np.float32) s = max(float(inp_width) / float(inp_height) * height, width) * 1.0 meta = {'c': c, 's': s, 'out_height': inp_height // self.opt.down_ratio, 'out_width': inp_width // self.opt.down_ratio} ''' Step 1: Network forward, get detections & embeddings''' # with torch.no_grad(): im_blob.requires_grad = True self.model.zero_grad() output = self.model(im_blob)[-1] hm = output['hm'].sigmoid() wh = output['wh'] id_feature = output['id'] id_feature = F.normalize(id_feature, dim=1) reg = output['reg'] if self.opt.reg_offset else None dets_raw, inds = mot_decode(hm, wh, reg=reg, cat_spec_wh=self.opt.cat_spec_wh, K=self.opt.K) id_features = [] for i in range(3): for j in range(3): id_feature_exp = _tranpose_and_gather_feat_expand(id_feature, inds, bias=(i - 1, j - 1)).squeeze(0) id_features.append(id_feature_exp) id_feature = _tranpose_and_gather_feat_expand(id_feature, inds) id_feature = id_feature.squeeze(0) dets = self.post_process(dets_raw.clone(), meta) dets = self.merge_outputs([dets])[1] remain_inds = dets[:, 4] > self.opt.conf_thres dets = dets[remain_inds] id_feature = id_feature[remain_inds] for i in range(len(id_features)): id_features[i] = id_features[i][remain_inds] id_feature = id_feature.detach().cpu().numpy() last_id_features = [None for _ in range(len(dets))] last_ad_id_features = [None for _ in range(len(dets))] dets_index = [i for i in range(len(dets))] dets_ids = [None for _ in range(len(dets))] tracks_ad = [] # import pdb; pdb.set_trace() # vis ''' for i in range(0, dets.shape[0]): bbox = dets[i][0:4] cv2.rectangle(img0, (bbox[0], bbox[1]), (bbox[2], bbox[3]), (0, 255, 0), 2) cv2.imshow('dets', img0) cv2.waitKey(0) id0 = id0-1 ''' if len(dets) > 0: '''Detections''' detections = [STrack(STrack.tlbr_to_tlwh(tlbrs[:4]), tlbrs[4], f, 30) for (tlbrs, f) in zip(dets[:, :5], id_feature)] else: detections = [] ''' Add newly detected tracklets to tracked_stracks''' unconfirmed = [] tracked_stracks = [] # type: list[STrack] for track in self.tracked_stracks_: if not track.is_activated: unconfirmed.append(track) else: tracked_stracks.append(track) ''' Step 2: First association, with embedding''' strack_pool = joint_stracks(tracked_stracks, self.lost_stracks_) STrack.multi_predict(strack_pool) dists = matching.embedding_distance(strack_pool, detections) # dists = matching.gate_cost_matrix(self.kalman_filter, dists, strack_pool, detections) dists = matching.fuse_motion(self.kalman_filter_, dists, strack_pool, detections) matches, u_track, u_detection = matching.linear_assignment(dists, thresh=0.7) # import pdb; pdb.set_trace() for itracked, idet in matches: track = strack_pool[itracked] det = detections[idet] assert last_id_features[dets_index[idet]] is None assert last_ad_id_features[dets_index[idet]] is None last_id_features[dets_index[idet]] = track.smooth_feat last_ad_id_features[dets_index[idet]] = track.smooth_feat_ad tracks_ad.append((track, dets_index[idet])) if track.state == TrackState.Tracked: track.update(detections[idet], self.frame_id_) activated_starcks.append(track) else: track.re_activate_(det, self.frame_id_, new_id=False) refind_stracks.append(track) dets_ids[dets_index[idet]] = track.track_id ''' Step 3: Second association, with IOU''' dets_index = [dets_index[i] for i in u_detection] detections = [detections[i] for i in u_detection] r_tracked_stracks = [strack_pool[i] for i in u_track if strack_pool[i].state == TrackState.Tracked] dists = matching.iou_distance(r_tracked_stracks, detections) matches, u_track, u_detection = matching.linear_assignment(dists, thresh=0.5) for itracked, idet in matches: track = r_tracked_stracks[itracked] det = detections[idet] assert last_id_features[dets_index[idet]] is None assert last_ad_id_features[dets_index[idet]] is None last_id_features[dets_index[idet]] = track.smooth_feat last_ad_id_features[dets_index[idet]] = track.smooth_feat_ad tracks_ad.append((track, dets_index[idet])) if track.state == TrackState.Tracked: track.update(det, self.frame_id_) activated_starcks.append(track) else: track.re_activate_(det, self.frame_id_, new_id=False) refind_stracks.append(track) dets_ids[dets_index[idet]] = track.track_id for it in u_track: track = r_tracked_stracks[it] if not track.state == TrackState.Lost: track.mark_lost() lost_stracks.append(track) '''Deal with unconfirmed tracks, usually tracks with only one beginning frame''' dets_index = [dets_index[i] for i in u_detection] detections = [detections[i] for i in u_detection] dists = matching.iou_distance(unconfirmed, detections) matches, u_unconfirmed, u_detection = matching.linear_assignment(dists, thresh=0.7) for itracked, idet in matches: assert last_id_features[dets_index[idet]] is None assert last_ad_id_features[dets_index[idet]] is None last_id_features[dets_index[idet]] = unconfirmed[itracked].smooth_feat last_ad_id_features[dets_index[idet]] = unconfirmed[itracked].smooth_feat_ad tracks_ad.append((unconfirmed[itracked], dets_index[idet])) unconfirmed[itracked].update(detections[idet], self.frame_id_) activated_starcks.append(unconfirmed[itracked]) dets_ids[dets_index[idet]] = unconfirmed[itracked].track_id for it in u_unconfirmed: track = unconfirmed[it] track.mark_removed() removed_stracks.append(track) """ Step 4: Init new stracks""" for inew in u_detection: track = detections[inew] if track.score < self.det_thresh: continue track.activate_(self.kalman_filter_, self.frame_id_, track_id=self_track_id_ori) activated_starcks.append(track) dets_ids[dets_index[inew]] = track.track_id """ Step 5: Update state""" for track in self.lost_stracks_: if self.frame_id_ - track.end_frame > self.max_time_lost: track.mark_removed() removed_stracks.append(track) # print('Ramained match {} s'.format(t4-t3)) self.tracked_stracks_ = [t for t in self.tracked_stracks_ if t.state == TrackState.Tracked] self.tracked_stracks_ = joint_stracks(self.tracked_stracks_, activated_starcks) self.tracked_stracks_ = joint_stracks(self.tracked_stracks_, refind_stracks) self.lost_stracks_ = sub_stracks(self.lost_stracks_, self.tracked_stracks_) self.lost_stracks_.extend(lost_stracks) self.lost_stracks_ = sub_stracks(self.lost_stracks_, self.removed_stracks_) self.removed_stracks_.extend(removed_stracks) self.tracked_stracks_, self.lost_stracks_ = remove_duplicate_stracks(self.tracked_stracks_, self.lost_stracks_) # get scores of lost tracks output_stracks_ori = [track for track in self.tracked_stracks_ if track.is_activated] logger.debug('===========Frame {}=========='.format(self.frame_id_)) logger.debug('Activated: {}'.format([track.track_id for track in activated_starcks])) logger.debug('Refind: {}'.format([track.track_id for track in refind_stracks])) logger.debug('Lost: {}'.format([track.track_id for track in lost_stracks])) logger.debug('Removed: {}'.format([track.track_id for track in removed_stracks])) noise = None suc = 0 att_tracker = None if self.ad_bbox: for t in output_stracks_ori: if t.track_id == attack_id: att_tracker = t for attack_ind, track_id in enumerate(dets_ids): if track_id == attack_id: if self.opt.attack_id > 0: if not hasattr(self, f'frames_{attack_id}'): setattr(self, f'frames_{attack_id}', 0) if getattr(self, f'frames_{attack_id}') < self.FRAME_THR: setattr(self, f'frames_{attack_id}', getattr(self, f'frames_{attack_id}') + 1) break ious = bbox_ious(np.ascontiguousarray(dets[:, :4], dtype=np.float64), np.ascontiguousarray(dets[:, :4], dtype=np.float64)) ious = self.processIoUs(ious) ious = ious + ious.T target_ind = np.argmax(ious[attack_ind]) if ious[attack_ind][target_ind] >= self.attack_iou_thr: fit = self.CheckFit(dets, id_feature, [attack_id], [attack_ind]) if fit: noise, attack_iter, suc = self.attack_sg_hj( im_blob, img0, dets, inds, remain_inds, last_info=self.ad_last_info, outputs_ori=output, attack_id=attack_id, attack_ind=attack_ind, ad_bbox=self.ad_bbox, track_v=att_tracker.get_v() if att_tracker is not None else None ) self.attack_iou_thr = 0 if suc: suc = 1 print( f'attack id: {attack_id}\tattack frame {self.frame_id_}: SUCCESS\tl2 distance: {(noise ** 2).sum().sqrt().item()}\titeration: {attack_iter}') else: suc = 2 print( f'attack id: {attack_id}\tattack frame {self.frame_id_}: FAIL\tl2 distance: {(noise ** 2).sum().sqrt().item()}\titeration: {attack_iter}') else: suc = 3 if ious[attack_ind][target_ind] == 0: self.temp_i += 1 if self.temp_i >= 10: self.attack_iou_thr = self.ATTACK_IOU_THR else: self.temp_i = 0 else: self.attack_iou_thr = self.ATTACK_IOU_THR break if noise is not None: self.ad_bbox = False l2_dis = (noise ** 2).sum().sqrt().item() adImg = torch.clip(im_blob + noise, min=0, max=1) noise = self.recoverNoise(noise, img0) noise = (noise - np.min(noise)) / (np.max(noise) - np.min(noise)) noise = (noise * 255).astype(np.uint8) else: l2_dis = None adImg = im_blob output_stracks_att = self.update(adImg, img0, track_id=self_track_id_att) adImg = self.recoverNoise(adImg.detach(), img0) return output_stracks_ori, output_stracks_att, adImg, noise, l2_dis, suc def update_attack_mt_det(self, im_blob, img0, **kwargs): self.frame_id_ += 1 activated_starcks = [] refind_stracks = [] lost_stracks = [] removed_stracks = [] width = img0.shape[1] height = img0.shape[0] inp_height = im_blob.shape[2] inp_width = im_blob.shape[3] c = np.array([width / 2., height / 2.], dtype=np.float32) s = max(float(inp_width) / float(inp_height) * height, width) * 1.0 meta = {'c': c, 's': s, 'out_height': inp_height // self.opt.down_ratio, 'out_width': inp_width // self.opt.down_ratio} ''' Step 1: Network forward, get detections & embeddings''' # with torch.no_grad(): im_blob.requires_grad = True self.model.zero_grad() output = self.model(im_blob)[-1] hm = output['hm'].sigmoid() wh = output['wh'] id_feature = output['id'] id_feature = F.normalize(id_feature, dim=1) reg = output['reg'] if self.opt.reg_offset else None dets_raw, inds = mot_decode(hm, wh, reg=reg, cat_spec_wh=self.opt.cat_spec_wh, K=self.opt.K) id_features = [] for i in range(3): for j in range(3): id_feature_exp = _tranpose_and_gather_feat_expand(id_feature, inds, bias=(i - 1, j - 1)).squeeze(0) id_features.append(id_feature_exp) id_feature = _tranpose_and_gather_feat_expand(id_feature, inds) id_feature = id_feature.squeeze(0) dets = self.post_process(dets_raw.clone(), meta) dets = self.merge_outputs([dets])[1] remain_inds = dets[:, 4] > self.opt.conf_thres dets = dets[remain_inds] id_feature = id_feature[remain_inds] for i in range(len(id_features)): id_features[i] = id_features[i][remain_inds] id_feature = id_feature.detach().cpu().numpy() last_id_features = [None for _ in range(len(dets))] last_ad_id_features = [None for _ in range(len(dets))] dets_index = [i for i in range(len(dets))] dets_ids = [None for _ in range(len(dets))] tracks_ad = [] # import pdb; pdb.set_trace() # vis ''' for i in range(0, dets.shape[0]): bbox = dets[i][0:4] cv2.rectangle(img0, (bbox[0], bbox[1]), (bbox[2], bbox[3]), (0, 255, 0), 2) cv2.imshow('dets', img0) cv2.waitKey(0) id0 = id0-1 ''' if len(dets) > 0: '''Detections''' detections = [STrack(STrack.tlbr_to_tlwh(tlbrs[:4]), tlbrs[4], f, 30) for (tlbrs, f) in zip(dets[:, :5], id_feature)] else: detections = [] ''' Add newly detected tracklets to tracked_stracks''' unconfirmed = [] tracked_stracks = [] # type: list[STrack] for track in self.tracked_stracks_: if not track.is_activated: unconfirmed.append(track) else: tracked_stracks.append(track) ''' Step 2: First association, with embedding''' strack_pool = joint_stracks(tracked_stracks, self.lost_stracks_) STrack.multi_predict(strack_pool) dists = matching.embedding_distance(strack_pool, detections) dists = matching.fuse_motion(self.kalman_filter_, dists, strack_pool, detections) matches, u_track, u_detection = matching.linear_assignment(dists, thresh=0.7) # import pdb; pdb.set_trace() for itracked, idet in matches: track = strack_pool[itracked] det = detections[idet] assert last_id_features[dets_index[idet]] is None assert last_ad_id_features[dets_index[idet]] is None last_id_features[dets_index[idet]] = track.smooth_feat last_ad_id_features[dets_index[idet]] = track.smooth_feat_ad tracks_ad.append((track, dets_index[idet])) if track.state == TrackState.Tracked: track.update(detections[idet], self.frame_id_) activated_starcks.append(track) else: track.re_activate_(det, self.frame_id_, new_id=False) refind_stracks.append(track) dets_ids[dets_index[idet]] = track.track_id ''' Step 3: Second association, with IOU''' dets_index = [dets_index[i] for i in u_detection] detections = [detections[i] for i in u_detection] r_tracked_stracks = [strack_pool[i] for i in u_track if strack_pool[i].state == TrackState.Tracked] dists = matching.iou_distance(r_tracked_stracks, detections) matches, u_track, u_detection = matching.linear_assignment(dists, thresh=0.5) for itracked, idet in matches: track = r_tracked_stracks[itracked] det = detections[idet] assert last_id_features[dets_index[idet]] is None assert last_ad_id_features[dets_index[idet]] is None last_id_features[dets_index[idet]] = track.smooth_feat last_ad_id_features[dets_index[idet]] = track.smooth_feat_ad tracks_ad.append((track, dets_index[idet])) if track.state == TrackState.Tracked: track.update(det, self.frame_id_) activated_starcks.append(track) else: track.re_activate_(det, self.frame_id_, new_id=False) refind_stracks.append(track) dets_ids[dets_index[idet]] = track.track_id for it in u_track: track = r_tracked_stracks[it] if not track.state == TrackState.Lost: track.mark_lost() lost_stracks.append(track) '''Deal with unconfirmed tracks, usually tracks with only one beginning frame''' dets_index = [dets_index[i] for i in u_detection] detections = [detections[i] for i in u_detection] dists = matching.iou_distance(unconfirmed, detections) matches, u_unconfirmed, u_detection = matching.linear_assignment(dists, thresh=0.7) for itracked, idet in matches: assert last_id_features[dets_index[idet]] is None assert last_ad_id_features[dets_index[idet]] is None last_id_features[dets_index[idet]] = unconfirmed[itracked].smooth_feat last_ad_id_features[dets_index[idet]] = unconfirmed[itracked].smooth_feat_ad tracks_ad.append((unconfirmed[itracked], dets_index[idet])) unconfirmed[itracked].update(detections[idet], self.frame_id_) activated_starcks.append(unconfirmed[itracked]) dets_ids[dets_index[idet]] = unconfirmed[itracked].track_id for it in u_unconfirmed: track = unconfirmed[it] track.mark_removed() removed_stracks.append(track) """ Step 4: Init new stracks""" for inew in u_detection: track = detections[inew] if track.score < self.det_thresh: continue track.activate_(self.kalman_filter_, self.frame_id_) activated_starcks.append(track) dets_ids[dets_index[inew]] = track.track_id """ Step 5: Update state""" for track in self.lost_stracks_: if self.frame_id_ - track.end_frame > self.max_time_lost: track.mark_removed() removed_stracks.append(track) # print('Ramained match {} s'.format(t4-t3)) self.tracked_stracks_ = [t for t in self.tracked_stracks_ if t.state == TrackState.Tracked] self.tracked_stracks_ = joint_stracks(self.tracked_stracks_, activated_starcks) self.tracked_stracks_ = joint_stracks(self.tracked_stracks_, refind_stracks) self.lost_stracks_ = sub_stracks(self.lost_stracks_, self.tracked_stracks_) self.lost_stracks_.extend(lost_stracks) self.lost_stracks_ = sub_stracks(self.lost_stracks_, self.removed_stracks_) self.removed_stracks_.extend(removed_stracks) self.tracked_stracks_, self.lost_stracks_ = remove_duplicate_stracks(self.tracked_stracks_, self.lost_stracks_) # get scores of lost tracks output_stracks_ori = [track for track in self.tracked_stracks_ if track.is_activated] id_set = set([track.track_id for track in output_stracks_ori]) for i in range(len(dets_ids)): if dets_ids[i] is not None and dets_ids[i] not in id_set: dets_ids[i] = None output_stracks_ori_ind = [] for ind, track in enumerate(output_stracks_ori): if track.track_id not in self.multiple_ori_ids: self.multiple_ori_ids[track.track_id] = 0 self.multiple_ori_ids[track.track_id] += 1 if self.multiple_ori_ids[track.track_id] <= self.FRAME_THR: output_stracks_ori_ind.append(ind) logger.debug('===========Frame {}=========='.format(self.frame_id_)) logger.debug('Activated: {}'.format([track.track_id for track in activated_starcks])) logger.debug('Refind: {}'.format([track.track_id for track in refind_stracks])) logger.debug('Lost: {}'.format([track.track_id for track in lost_stracks])) logger.debug('Removed: {}'.format([track.track_id for track in removed_stracks])) attack_ids = [] target_ids = [] attack_inds = [] target_inds = [] noise = None if len(dets) > 0: ious = bbox_ious(np.ascontiguousarray(dets[:, :4], dtype=np.float64), np.ascontiguousarray(dets[:, :4], dtype=np.float64)) ious[range(len(dets)), range(len(dets))] = 0 ious_inds = np.argmax(ious, axis=1) dis = bbox_dis(np.ascontiguousarray(dets[:, :4], dtype=np.float64), np.ascontiguousarray(dets[:, :4], dtype=np.float64)) dis[range(len(dets)), range(len(dets))] = np.inf dis_inds = np.argmin(dis, axis=1) for attack_ind, track_id in enumerate(dets_ids): if track_id is None or self.multiple_ori_ids[track_id] <= self.FRAME_THR \ or dets_ids[ious_inds[attack_ind]] not in self.multiple_ori2att \ or track_id not in self.multiple_ori2att: continue if ious[attack_ind, ious_inds[attack_ind]] > self.ATTACK_IOU_THR or ( track_id in self.low_iou_ids and ious[attack_ind, ious_inds[attack_ind]] > 0 ): attack_ids.append(track_id) target_ids.append(dets_ids[ious_inds[attack_ind]]) attack_inds.append(attack_ind) target_inds.append(ious_inds[attack_ind]) if hasattr(self, f'temp_i_{track_id}'): self.__setattr__(f'temp_i_{track_id}', 0) elif ious[attack_ind, ious_inds[attack_ind]] == 0 and track_id in self.low_iou_ids: if hasattr(self, f'temp_i_{track_id}'): self.__setattr__(f'temp_i_{track_id}', self.__getattribute__(f'temp_i_{track_id}') + 1) else: self.__setattr__(f'temp_i_{track_id}', 1) if self.__getattribute__(f'temp_i_{track_id}') > 10: self.low_iou_ids.remove(track_id) elif dets_ids[dis_inds[attack_ind]] in self.multiple_ori2att: attack_ids.append(track_id) target_ids.append(dets_ids[dis_inds[attack_ind]]) attack_inds.append(attack_ind) target_inds.append(dis_inds[attack_ind]) fit_index = self.CheckFit(dets, id_feature, attack_ids, attack_inds) if len(attack_ids) else [] if fit_index: attack_ids = np.array(attack_ids)[fit_index] target_ids = np.array(target_ids)[fit_index] attack_inds = np.array(attack_inds)[fit_index] target_inds = np.array(target_inds)[fit_index] noise, attack_iter, suc = self.attack_mt_det( im_blob, img0, dets, inds, remain_inds, last_info=self.ad_last_info, outputs_ori=output, attack_ids=attack_ids, attack_inds=attack_inds ) self.low_iou_ids.update(set(attack_ids)) if suc: self.attacked_ids.update(set(attack_ids)) print( f'attack ids: {attack_ids}\tattack frame {self.frame_id_}: SUCCESS\tl2 distance: {(noise ** 2).sum().sqrt().item()}\titeration: {attack_iter}') else: print(f'attack ids: {attack_ids}\tattack frame {self.frame_id_}: FAIL\tl2 distance: {(noise ** 2).sum().sqrt().item() if noise is not None else None}\titeration: {attack_iter}') if noise is not None: l2_dis = (noise ** 2).sum().sqrt().item() adImg = torch.clip(im_blob + noise, min=0, max=1) noise = self.recoverNoise(noise, img0) noise = (noise - np.min(noise)) / (np.max(noise) - np.min(noise)) noise = (noise * 255).astype(np.uint8) else: l2_dis = None adImg = im_blob output_stracks_att = self.update(adImg, img0) adImg = self.recoverNoise(adImg.detach(), img0) output_stracks_att_ind = [] for ind, track in enumerate(output_stracks_att): if track.track_id not in self.multiple_att_ids: self.multiple_att_ids[track.track_id] = 0 self.multiple_att_ids[track.track_id] += 1 if self.multiple_att_ids[track.track_id] <= self.FRAME_THR: output_stracks_att_ind.append(ind) if len(output_stracks_ori_ind) and len(output_stracks_att_ind): ori_dets = [track.curr_tlbr for i, track in enumerate(output_stracks_ori) if i in output_stracks_ori_ind] att_dets = [track.curr_tlbr for i, track in enumerate(output_stracks_att) if i in output_stracks_att_ind] ori_dets = np.stack(ori_dets).astype(np.float64) att_dets = np.stack(att_dets).astype(np.float64) ious = bbox_ious(ori_dets, att_dets) row_ind, col_ind = linear_sum_assignment(-ious) for i in range(len(row_ind)): if ious[row_ind[i], col_ind[i]] > 0.9: ori_id = output_stracks_ori[output_stracks_ori_ind[row_ind[i]]].track_id att_id = output_stracks_att[output_stracks_att_ind[col_ind[i]]].track_id self.multiple_ori2att[ori_id] = att_id return output_stracks_ori, output_stracks_att, adImg, noise, l2_dis def update_attack_mt_hj(self, im_blob, img0, **kwargs): self.frame_id_ += 1 activated_starcks = [] refind_stracks = [] lost_stracks = [] removed_stracks = [] width = img0.shape[1] height = img0.shape[0] inp_height = im_blob.shape[2] inp_width = im_blob.shape[3] c = np.array([width / 2., height / 2.], dtype=np.float32) s = max(float(inp_width) / float(inp_height) * height, width) * 1.0 meta = {'c': c, 's': s, 'out_height': inp_height // self.opt.down_ratio, 'out_width': inp_width // self.opt.down_ratio} ''' Step 1: Network forward, get detections & embeddings''' # with torch.no_grad(): im_blob.requires_grad = True self.model.zero_grad() output = self.model(im_blob)[-1] hm = output['hm'].sigmoid() wh = output['wh'] id_feature = output['id'] id_feature = F.normalize(id_feature, dim=1) reg = output['reg'] if self.opt.reg_offset else None dets_raw, inds = mot_decode(hm, wh, reg=reg, cat_spec_wh=self.opt.cat_spec_wh, K=self.opt.K) id_features = [] for i in range(3): for j in range(3): id_feature_exp = _tranpose_and_gather_feat_expand(id_feature, inds, bias=(i - 1, j - 1)).squeeze(0) id_features.append(id_feature_exp) id_feature = _tranpose_and_gather_feat_expand(id_feature, inds) id_feature = id_feature.squeeze(0) dets = self.post_process(dets_raw.clone(), meta) dets = self.merge_outputs([dets])[1] remain_inds = dets[:, 4] > self.opt.conf_thres dets = dets[remain_inds] id_feature = id_feature[remain_inds] for i in range(len(id_features)): id_features[i] = id_features[i][remain_inds] id_feature = id_feature.detach().cpu().numpy() last_id_features = [None for _ in range(len(dets))] last_ad_id_features = [None for _ in range(len(dets))] dets_index = [i for i in range(len(dets))] dets_ids = [None for _ in range(len(dets))] tracks_ad = [] # import pdb; pdb.set_trace() # vis ''' for i in range(0, dets.shape[0]): bbox = dets[i][0:4] cv2.rectangle(img0, (bbox[0], bbox[1]), (bbox[2], bbox[3]), (0, 255, 0), 2) cv2.imshow('dets', img0) cv2.waitKey(0) id0 = id0-1 ''' if len(dets) > 0: '''Detections''' detections = [STrack(STrack.tlbr_to_tlwh(tlbrs[:4]), tlbrs[4], f, 30) for (tlbrs, f) in zip(dets[:, :5], id_feature)] else: detections = [] ''' Add newly detected tracklets to tracked_stracks''' unconfirmed = [] tracked_stracks = [] # type: list[STrack] for track in self.tracked_stracks_: if not track.is_activated: unconfirmed.append(track) else: tracked_stracks.append(track) ''' Step 2: First association, with embedding''' strack_pool = joint_stracks(tracked_stracks, self.lost_stracks_) STrack.multi_predict(strack_pool) dists = matching.embedding_distance(strack_pool, detections) dists = matching.fuse_motion(self.kalman_filter_, dists, strack_pool, detections) matches, u_track, u_detection = matching.linear_assignment(dists, thresh=0.7) # import pdb; pdb.set_trace() for itracked, idet in matches: track = strack_pool[itracked] det = detections[idet] assert last_id_features[dets_index[idet]] is None assert last_ad_id_features[dets_index[idet]] is None last_id_features[dets_index[idet]] = track.smooth_feat last_ad_id_features[dets_index[idet]] = track.smooth_feat_ad tracks_ad.append((track, dets_index[idet])) if track.state == TrackState.Tracked: track.update(detections[idet], self.frame_id_) activated_starcks.append(track) else: track.re_activate_(det, self.frame_id_, new_id=False) refind_stracks.append(track) dets_ids[dets_index[idet]] = track.track_id ''' Step 3: Second association, with IOU''' dets_index = [dets_index[i] for i in u_detection] detections = [detections[i] for i in u_detection] r_tracked_stracks = [strack_pool[i] for i in u_track if strack_pool[i].state == TrackState.Tracked] dists = matching.iou_distance(r_tracked_stracks, detections) matches, u_track, u_detection = matching.linear_assignment(dists, thresh=0.5) for itracked, idet in matches: track = r_tracked_stracks[itracked] det = detections[idet] assert last_id_features[dets_index[idet]] is None assert last_ad_id_features[dets_index[idet]] is None last_id_features[dets_index[idet]] = track.smooth_feat last_ad_id_features[dets_index[idet]] = track.smooth_feat_ad tracks_ad.append((track, dets_index[idet])) if track.state == TrackState.Tracked: track.update(det, self.frame_id_) activated_starcks.append(track) else: track.re_activate_(det, self.frame_id_, new_id=False) refind_stracks.append(track) dets_ids[dets_index[idet]] = track.track_id for it in u_track: track = r_tracked_stracks[it] if not track.state == TrackState.Lost: track.mark_lost() lost_stracks.append(track) '''Deal with unconfirmed tracks, usually tracks with only one beginning frame''' dets_index = [dets_index[i] for i in u_detection] detections = [detections[i] for i in u_detection] dists = matching.iou_distance(unconfirmed, detections) matches, u_unconfirmed, u_detection = matching.linear_assignment(dists, thresh=0.7) for itracked, idet in matches: assert last_id_features[dets_index[idet]] is None assert last_ad_id_features[dets_index[idet]] is None last_id_features[dets_index[idet]] = unconfirmed[itracked].smooth_feat last_ad_id_features[dets_index[idet]] = unconfirmed[itracked].smooth_feat_ad tracks_ad.append((unconfirmed[itracked], dets_index[idet])) unconfirmed[itracked].update(detections[idet], self.frame_id_) activated_starcks.append(unconfirmed[itracked]) dets_ids[dets_index[idet]] = unconfirmed[itracked].track_id for it in u_unconfirmed: track = unconfirmed[it] track.mark_removed() removed_stracks.append(track) """ Step 4: Init new stracks""" for inew in u_detection: track = detections[inew] if track.score < self.det_thresh: continue track.activate_(self.kalman_filter_, self.frame_id_) activated_starcks.append(track) dets_ids[dets_index[inew]] = track.track_id """ Step 5: Update state""" for track in self.lost_stracks_: if self.frame_id_ - track.end_frame > self.max_time_lost: track.mark_removed() removed_stracks.append(track) # print('Ramained match {} s'.format(t4-t3)) self.tracked_stracks_ = [t for t in self.tracked_stracks_ if t.state == TrackState.Tracked] self.tracked_stracks_ = joint_stracks(self.tracked_stracks_, activated_starcks) self.tracked_stracks_ = joint_stracks(self.tracked_stracks_, refind_stracks) self.lost_stracks_ = sub_stracks(self.lost_stracks_, self.tracked_stracks_) self.lost_stracks_.extend(lost_stracks) self.lost_stracks_ = sub_stracks(self.lost_stracks_, self.removed_stracks_) self.removed_stracks_.extend(removed_stracks) self.tracked_stracks_, self.lost_stracks_ = remove_duplicate_stracks(self.tracked_stracks_, self.lost_stracks_) # get scores of lost tracks output_stracks_ori = [track for track in self.tracked_stracks_ if track.is_activated] id_set = set([track.track_id for track in output_stracks_ori]) for i in range(len(dets_ids)): if dets_ids[i] is not None and dets_ids[i] not in id_set: dets_ids[i] = None output_stracks_ori_ind = [] for ind, track in enumerate(output_stracks_ori): if track.track_id not in self.multiple_ori_ids: self.multiple_ori_ids[track.track_id] = 0 self.multiple_ori_ids[track.track_id] += 1 if self.multiple_ori_ids[track.track_id] <= self.FRAME_THR: output_stracks_ori_ind.append(ind) logger.debug('===========Frame {}=========='.format(self.frame_id_)) logger.debug('Activated: {}'.format([track.track_id for track in activated_starcks])) logger.debug('Refind: {}'.format([track.track_id for track in refind_stracks])) logger.debug('Lost: {}'.format([track.track_id for track in lost_stracks])) logger.debug('Removed: {}'.format([track.track_id for track in removed_stracks])) attack_ids = [] target_ids = [] attack_inds = [] target_inds = [] noise = None if len(dets) > 0: ious = bbox_ious(np.ascontiguousarray(dets[:, :4], dtype=np.float64), np.ascontiguousarray(dets[:, :4], dtype=np.float64)) ious[range(len(dets)), range(len(dets))] = 0 ious_inds = np.argmax(ious, axis=1) dis = bbox_dis(np.ascontiguousarray(dets[:, :4], dtype=np.float64), np.ascontiguousarray(dets[:, :4], dtype=np.float64)) dis[range(len(dets)), range(len(dets))] = np.inf dis_inds = np.argmin(dis, axis=1) for attack_ind, track_id in enumerate(dets_ids): if track_id is None or self.multiple_ori_ids[track_id] <= self.FRAME_THR \ or dets_ids[ious_inds[attack_ind]] not in self.multiple_ori2att \ or track_id not in self.multiple_ori2att: continue if ious[attack_ind, ious_inds[attack_ind]] > self.ATTACK_IOU_THR or ( track_id in self.low_iou_ids and ious[attack_ind, ious_inds[attack_ind]] > 0 ): attack_ids.append(track_id) target_ids.append(dets_ids[ious_inds[attack_ind]]) attack_inds.append(attack_ind) target_inds.append(ious_inds[attack_ind]) if hasattr(self, f'temp_i_{track_id}'): self.__setattr__(f'temp_i_{track_id}', 0) elif ious[attack_ind, ious_inds[attack_ind]] == 0 and track_id in self.low_iou_ids: if hasattr(self, f'temp_i_{track_id}'): self.__setattr__(f'temp_i_{track_id}', self.__getattribute__(f'temp_i_{track_id}') + 1) else: self.__setattr__(f'temp_i_{track_id}', 1) if self.__getattribute__(f'temp_i_{track_id}') > 10: self.low_iou_ids.remove(track_id) elif dets_ids[dis_inds[attack_ind]] in self.multiple_ori2att: attack_ids.append(track_id) target_ids.append(dets_ids[dis_inds[attack_ind]]) attack_inds.append(attack_ind) target_inds.append(dis_inds[attack_ind]) fit_index = self.CheckFit(dets, id_feature, attack_ids, attack_inds) if len(attack_ids) else [] if fit_index: attack_ids = np.array(attack_ids)[fit_index] target_ids = np.array(target_ids)[fit_index] attack_inds = np.array(attack_inds)[fit_index] target_inds = np.array(target_inds)[fit_index] att_trackers = [] for attack_id in attack_ids: if attack_id not in self.ad_ids: for t in output_stracks_ori: if t.track_id == attack_id: att_trackers.append(t) noise, attack_iter, suc = self.attack_mt_hj( im_blob, img0, dets, inds, remain_inds, last_info=self.ad_last_info, outputs_ori=output, attack_ids=attack_ids, attack_inds=attack_inds, ad_ids=self.ad_ids, track_vs=[t.get_v() for t in att_trackers] ) self.ad_ids.update(attack_ids) self.low_iou_ids.update(set(attack_ids)) if suc: self.attacked_ids.update(set(attack_ids)) print( f'attack ids: {attack_ids}\tattack frame {self.frame_id_}: SUCCESS\tl2 distance: {(noise ** 2).sum().sqrt().item()}\titeration: {attack_iter}') else: print(f'attack ids: {attack_ids}\tattack frame {self.frame_id_}: FAIL\tl2 distance: {(noise ** 2).sum().sqrt().item() if noise is not None else None}\titeration: {attack_iter}') if noise is not None: l2_dis = (noise ** 2).sum().sqrt().item() adImg = torch.clip(im_blob + noise, min=0, max=1) noise = self.recoverNoise(noise, img0) noise = (noise - np.min(noise)) / (np.max(noise) - np.min(noise)) noise = (noise * 255).astype(np.uint8) else: l2_dis = None adImg = im_blob output_stracks_att = self.update(adImg, img0) adImg = self.recoverNoise(adImg.detach(), img0) output_stracks_att_ind = [] for ind, track in enumerate(output_stracks_att): if track.track_id not in self.multiple_att_ids: self.multiple_att_ids[track.track_id] = 0 self.multiple_att_ids[track.track_id] += 1 if self.multiple_att_ids[track.track_id] <= self.FRAME_THR: output_stracks_att_ind.append(ind) if len(output_stracks_ori_ind) and len(output_stracks_att_ind): ori_dets = [track.curr_tlbr for i, track in enumerate(output_stracks_ori) if i in output_stracks_ori_ind] att_dets = [track.curr_tlbr for i, track in enumerate(output_stracks_att) if i in output_stracks_att_ind] ori_dets = np.stack(ori_dets).astype(np.float64) att_dets = np.stack(att_dets).astype(np.float64) ious = bbox_ious(ori_dets, att_dets) row_ind, col_ind = linear_sum_assignment(-ious) for i in range(len(row_ind)): if ious[row_ind[i], col_ind[i]] > 0.9: ori_id = output_stracks_ori[output_stracks_ori_ind[row_ind[i]]].track_id att_id = output_stracks_att[output_stracks_att_ind[col_ind[i]]].track_id self.multiple_ori2att[ori_id] = att_id return output_stracks_ori, output_stracks_att, adImg, noise, l2_dis def update(self, im_blob, img0, **kwargs): self.frame_id += 1 self_track_id = kwargs.get('track_id', None) activated_starcks = [] refind_stracks = [] lost_stracks = [] removed_stracks = [] width = img0.shape[1] height = img0.shape[0] inp_height = im_blob.shape[2] inp_width = im_blob.shape[3] c = np.array([width / 2., height / 2.], dtype=np.float32) s = max(float(inp_width) / float(inp_height) * height, width) * 1.0 meta = {'c': c, 's': s, 'out_height': inp_height // self.opt.down_ratio, 'out_width': inp_width // self.opt.down_ratio} ''' Step 1: Network forward, get detections & embeddings''' with torch.no_grad(): output = self.model(im_blob)[-1] hm = output['hm'].sigmoid_() wh = output['wh'] id_feature = output['id'] id_feature = F.normalize(id_feature, dim=1) reg = output['reg'] if self.opt.reg_offset else None dets, inds = mot_decode(hm, wh, reg=reg, cat_spec_wh=self.opt.cat_spec_wh, K=self.opt.K) id_feature_ = id_feature.permute(0, 2, 3, 1).view(-1, 512) id_feature = _tranpose_and_gather_feat(id_feature, inds) id_feature = id_feature.squeeze(0) id_feature = id_feature.detach().cpu().numpy() dets = self.post_process(dets, meta) dets = self.merge_outputs([dets])[1] remain_inds = dets[:, 4] > self.opt.conf_thres dets = dets[remain_inds] id_feature = id_feature[remain_inds] # import pdb; pdb.set_trace() dets_index = inds[0][remain_inds].tolist() # vis ''' for i in range(0, dets.shape[0]): bbox = dets[i][0:4] cv2.rectangle(img0, (bbox[0], bbox[1]), (bbox[2], bbox[3]), (0, 255, 0), 2) cv2.imshow('dets', img0) cv2.waitKey(0) id0 = id0-1 ''' if len(dets) > 0: '''Detections''' detections = [STrack(STrack.tlbr_to_tlwh(tlbrs[:4]), tlbrs[4], f, 30) for (tlbrs, f) in zip(dets[:, :5], id_feature)] else: detections = [] ''' Add newly detected tracklets to tracked_stracks''' unconfirmed = [] tracked_stracks = [] # type: list[STrack] for track in self.tracked_stracks: if not track.is_activated: unconfirmed.append(track) else: tracked_stracks.append(track) ''' Step 2: First association, with embedding''' strack_pool = joint_stracks(tracked_stracks, self.lost_stracks) # Predict the current location with KF # for strack in strack_pool: # strack.predict() STrack.multi_predict(strack_pool) dists = matching.embedding_distance(strack_pool, detections) dists = matching.fuse_motion(self.kalman_filter, dists, strack_pool, detections) matches, u_track, u_detection = matching.linear_assignment(dists, thresh=0.7) for itracked, idet in matches: track = strack_pool[itracked] det = detections[idet] if track.state == TrackState.Tracked: track.update(detections[idet], self.frame_id) activated_starcks.append(track) else: track.re_activate(det, self.frame_id, new_id=False) refind_stracks.append(track) ''' Step 3: Second association, with IOU''' dets_index = [dets_index[i] for i in u_detection] detections = [detections[i] for i in u_detection] r_tracked_stracks = [strack_pool[i] for i in u_track if strack_pool[i].state == TrackState.Tracked] dists = matching.iou_distance(r_tracked_stracks, detections) matches, u_track, u_detection = matching.linear_assignment(dists, thresh=0.5) for itracked, idet in matches: track = r_tracked_stracks[itracked] det = detections[idet] if track.state == TrackState.Tracked: track.update(det, self.frame_id) activated_starcks.append(track) else: track.re_activate(det, self.frame_id, new_id=False) refind_stracks.append(track) for it in u_track: track = r_tracked_stracks[it] if not track.state == TrackState.Lost: track.mark_lost() lost_stracks.append(track) '''Deal with unconfirmed tracks, usually tracks with only one beginning frame''' dets_index = [dets_index[i] for i in u_detection] detections = [detections[i] for i in u_detection] dists = matching.iou_distance(unconfirmed, detections) matches, u_unconfirmed, u_detection = matching.linear_assignment(dists, thresh=0.7) for itracked, idet in matches: unconfirmed[itracked].update(detections[idet], self.frame_id) activated_starcks.append(unconfirmed[itracked]) for it in u_unconfirmed: track = unconfirmed[it] track.mark_removed() removed_stracks.append(track) """ Step 4: Init new stracks""" for inew in u_detection: track = detections[inew] if track.score < self.det_thresh: continue track.activate(self.kalman_filter, self.frame_id, track_id=self_track_id) activated_starcks.append(track) """ Step 5: Update state""" for track in self.lost_stracks: if self.frame_id - track.end_frame > self.max_time_lost: track.mark_removed() removed_stracks.append(track) # print('Ramained match {} s'.format(t4-t3)) self.tracked_stracks = [t for t in self.tracked_stracks if t.state == TrackState.Tracked] self.tracked_stracks = joint_stracks(self.tracked_stracks, activated_starcks) self.tracked_stracks = joint_stracks(self.tracked_stracks, refind_stracks) self.lost_stracks = sub_stracks(self.lost_stracks, self.tracked_stracks) self.lost_stracks.extend(lost_stracks) self.lost_stracks = sub_stracks(self.lost_stracks, self.removed_stracks) self.removed_stracks.extend(removed_stracks) self.tracked_stracks, self.lost_stracks = remove_duplicate_stracks(self.tracked_stracks, self.lost_stracks) # get scores of lost tracks output_stracks = [track for track in self.tracked_stracks if track.is_activated] logger.debug('===========Frame {}=========='.format(self.frame_id)) logger.debug('Activated: {}'.format([track.track_id for track in activated_starcks])) logger.debug('Refind: {}'.format([track.track_id for track in refind_stracks])) logger.debug('Lost: {}'.format([track.track_id for track in lost_stracks])) logger.debug('Removed: {}'.format([track.track_id for track in removed_stracks])) unconfirmed = [] tracked_stracks = [] # type: list[STrack] for track in self.tracked_stracks: if not track.is_activated: unconfirmed.append(track) else: tracked_stracks.append(track) ''' Step 2: First association, with embedding''' strack_pool = joint_stracks(tracked_stracks, self.lost_stracks) self.ad_last_info = { 'last_strack_pool': copy.deepcopy(strack_pool), 'last_unconfirmed': copy.deepcopy(unconfirmed), 'kalman_filter': copy.deepcopy(self.kalman_filter_) } return output_stracks def _nms(self, heat, kernel=3): pad = (kernel - 1) // 2 hmax = nn.functional.max_pool2d( heat, (kernel, kernel), stride=1, padding=pad) keep = (hmax == heat).float return keep def computer_targets(self, boxes, gt_box): an_ws = boxes[:, 2] an_hs = boxes[:, 3] ctr_x = boxes[:, 0] ctr_y = boxes[:, 1] gt_ws = gt_box[:, 2] gt_hs = gt_box[:, 3] gt_ctr_x = gt_box[:, 0] gt_ctr_y = gt_box[:, 1] targets_dx = (gt_ctr_x - ctr_x) / an_ws targets_dy = (gt_ctr_y - ctr_y) / an_hs targets_dw = np.log(gt_ws / an_ws) targets_dh = np.log(gt_hs / an_hs) targets = np.vstack((targets_dx, targets_dy, targets_dw, targets_dh)).T return targets def joint_stracks(tlista, tlistb): exists = {} res = [] for t in tlista: exists[t.track_id] = 1 res.append(t) for t in tlistb: tid = t.track_id if not exists.get(tid, 0): exists[tid] = 1 res.append(t) return res def sub_stracks(tlista, tlistb): stracks = {} for t in tlista: stracks[t.track_id] = t for t in tlistb: tid = t.track_id if stracks.get(tid, 0): del stracks[tid] return list(stracks.values()) def remove_duplicate_stracks(stracksa, stracksb): pdist = matching.iou_distance(stracksa, stracksb) pairs = np.where(pdist < 0.15) dupa, dupb = list(), list() for p, q in zip(*pairs): timep = stracksa[p].frame_id - stracksa[p].start_frame timeq = stracksb[q].frame_id - stracksb[q].start_frame if timep > timeq: dupb.append(q) else: dupa.append(p) resa = [t for i, t in enumerate(stracksa) if not i in dupa] resb = [t for i, t in enumerate(stracksb) if not i in dupb] return resa, resb def save(obj, name): with open(f'/home/derry/Desktop/{name}.pth', 'wb') as f: pickle.dump(obj, f) def load(name): with open(f'/home/derry/Desktop/{name}.pth', 'rb') as f: obj = pickle.load(f) return obj
43.986462
201
0.56671
24,775
194,948
4.172714
0.021877
0.025924
0.018863
0.017644
0.928041
0.914315
0.903743
0.895598
0.887782
0.879618
0
0.017038
0.325907
194,948
4,431
202
43.996389
0.769635
0.029049
0
0.845361
0
0.004458
0.026489
0.00304
0
0
0
0
0.014489
1
0.016439
false
0
0.00613
0.000836
0.040958
0.004737
0
0
0
null
0
0
0
1
1
1
1
1
1
0
0
0
0
0
0
0
0
0
0
1
0
0
0
0
null
0
0
0
0
0
0
0
0
0
0
0
0
0
7
8af66fdc8a9ee446bc7b0332263e370019166959
2,130
py
Python
t_system/db_fetching.py
sevgiun/T_System
2664e38843c36578bfb6c61e2642b56bd537352a
[ "MIT" ]
7
2019-11-06T10:00:39.000Z
2021-06-29T20:31:54.000Z
imline/db_fetching.py
MCYBA/ImLine
0d1bde9d196432905f3ed00b41cb048c97cf1b44
[ "MIT" ]
741
2019-11-01T11:23:33.000Z
2022-03-31T13:49:17.000Z
imline/db_fetching.py
MCYBA/ImLine
0d1bde9d196432905f3ed00b41cb048c97cf1b44
[ "MIT" ]
6
2019-11-01T11:49:27.000Z
2022-03-18T03:04:16.000Z
#!/usr/bin/python3 # -*- coding: utf-8 -*- """ .. module:: database :platform: Unix :synopsis: the top-level submodule of T_System that contains the functions and classes related to T_System's database and table creation ability. Powered by TinyDB. .. moduleauthor:: Cem Baybars GÜÇLÜ <cem.baybars@gmail.com> """ from tinydb import TinyDB # TinyDB is a lightweight document oriented database class DBFetcher: """Class to define an database handler with given folder and table name. It's only job creating databases or tables and returning them. This class provides necessary initiations and functions named :func:`t_system.database.Database.get` for return TinyDB database object. """ def __init__(self, folder, name, table=None, cache_size=None): """Initialization method of :class:`t_system.database.Database` class. Args: folder (str) Folder that contains database. name (str) Name of the database. table (str): Current working table name. cache_size (int): TinyDB caches query result for performance. """ self.folder = folder self.name = name self.table = table self.cache_size = cache_size def fetch(self): """Method to return database. If there is a table name method creates a table and returns that. Otherwise returns all db. Returns: TinyDB: database object. """ db = TinyDB(f'{self.folder}/{self.name}.json') if self.table: return self.__set_table(db, self.table, self.cache_size) return db @staticmethod def __set_table(db, table_name, cache_size=None): """Method to set database by table name. Args: db (TinyDB): TinyDB object. table_name (str): Current working table name. cache_size (int): TinyDB caches query result for performance. """ return db.table(table_name, cache_size=cache_size)
34.354839
168
0.615493
259
2,130
4.96139
0.393822
0.063035
0.04358
0.056031
0.116732
0.116732
0.116732
0.116732
0.116732
0.116732
0
0.001347
0.302817
2,130
61
169
34.918033
0.863973
0.646948
0
0
0
0
0.050505
0.050505
0
0
0
0
0
1
0.2
false
0
0.066667
0
0.533333
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
1
0
0
1
8af9408c776206126f843ee9b5587d4d0acab636
5,153
py
Python
xcltk/utils/pileup_regions.py
Rongtingting/xcltk
2e86207c45a1caa7f905a89e1c121c3c203eab2d
[ "Apache-2.0" ]
null
null
null
xcltk/utils/pileup_regions.py
Rongtingting/xcltk
2e86207c45a1caa7f905a89e1c121c3c203eab2d
[ "Apache-2.0" ]
null
null
null
xcltk/utils/pileup_regions.py
Rongtingting/xcltk
2e86207c45a1caa7f905a89e1c121c3c203eab2d
[ "Apache-2.0" ]
2
2021-01-26T02:07:32.000Z
2021-02-03T03:56:55.000Z
# Copied from cellSNP, https://github.com/single-cell-genetics/cellSNP/blob/purePython/cellSNP/utils/pileup_regions.py # Utilility functions for pileup SNPs across regions # originally in from pileup_utils.py # Author: Yuanhua Huang # Date: 21/05/2018 # Modified by: Xianjie Huang from .pileup import * from .sam import get_query_bases, get_query_qualities ## ealier high error in pileup whole genome might come from ## using _read.query_sequence, which has only partially aligned ## pileupread.query_position is based on the full length of the reads ## _read.qqual is based on aligned reads segment # def pileup_bases(pileupColumn): # """ pileup all reads mapped to the genome position. # """ # base_list, read_list, qual_list = [], [], [] # for pileupread in pileupColumn.pileups: # # query position is None if is_del or is_refskip is set. # if pileupread.is_del or pileupread.is_refskip: # continue # #query_POS = pileupread.query_position # query_POS = pileupread.query_position # _read = pileupread.alignment # try: # _base = _read.query_sequence[query_POS - 1].upper() # _qual = _read.qqual[query_POS - 1] # except: # print("warnings: a read fails to give _base or _qual.", # query_POS, len(_read.qqual), len(_read.qual), len(_read.query_sequence)) # print(_read.qqual) # continue # #_qual = "J" # read_list.append(_read) # base_list.append(_base) # qual_list.append(_qual) # return base_list, qual_list, read_list def pileup_bases(pileupColumn, real_POS, cell_tag, UMI_tag, min_MAPQ, max_FLAG, min_LEN): """ Pileup all reads mapped to the genome position. Filtering is also applied, including cell and UMI tags and read mapping quality. """ base_list, qual_list, UMIs_list, cell_list = [], [], [], [] for pileupread in pileupColumn.pileups: # query position is None if is_del or is_refskip is set. if pileupread.is_del or pileupread.is_refskip: continue _read = pileupread.alignment if real_POS is not None: try: idx = _read.positions.index(real_POS-1) except: continue _qual = get_query_qualities(_read)[idx] _base = get_query_bases(_read)[idx].upper() else: query_POS = pileupread.query_position _qual = _read.query_qualities[query_POS - 1] _base = _read.query_sequence[query_POS - 1].upper() ## filtering reads if (_read.mapq < min_MAPQ or _read.flag > max_FLAG or len(_read.positions) < min_LEN): continue if cell_tag is not None and _read.has_tag(cell_tag) == False: continue if UMI_tag is not None and _read.has_tag(UMI_tag) == False: continue if UMI_tag is not None: UMIs_list.append(fmt_umi_tag(_read, cell_tag, UMI_tag)) if cell_tag is not None: cell_list.append(_read.get_tag(cell_tag)) base_list.append(_base) qual_list.append(_qual) return base_list, qual_list, UMIs_list, cell_list def pileup_regions(samFile, barcodes, out_file=None, chrom=None, cell_tag="CR", UMI_tag="UR", min_COUNT=20, min_MAF=0.1, min_MAPQ=20, max_FLAG=255, min_LEN=30, doublet_GL=False, verbose=True): """Pileup allelic specific expression for a whole chromosome in sam file. TODO: 1) multiple sam files, e.g., bulk samples; 2) optional cell barcode """ samFile, chrom = check_pysam_chrom(samFile, chrom) if out_file is not None: fid = open(out_file, "w") fid.writelines(VCF_HEADER + CONTIG) if barcodes is not None: fid.writelines("\t".join(VCF_COLUMN + barcodes) + "\n") else: fid.writelines("\t".join(VCF_COLUMN + ["sample0"]) + "\n") POS_CNT = 0 vcf_lines_all = [] for pileupcolumn in samFile.pileup(contig=chrom): POS_CNT += 1 if verbose and POS_CNT % 1000000 == 0: print("%s: %dM positions processed." %(chrom, POS_CNT/1000000)) if pileupcolumn.n < min_COUNT: continue base_list, qual_list, UMIs_list, cell_list = pileup_bases(pileupcolumn, pileupcolumn.pos + 1, cell_tag, UMI_tag, min_MAPQ, max_FLAG, min_LEN) if len(base_list) < min_COUNT: continue base_merge, base_cells, qual_cells = map_barcodes(base_list, qual_list, cell_list, UMIs_list, barcodes) vcf_line = get_vcf_line(base_merge, base_cells, qual_cells, pileupcolumn.reference_name, pileupcolumn.pos + 1, min_COUNT, min_MAF, doublet_GL = doublet_GL) if vcf_line is not None: if out_file is None: vcf_lines_all.append(vcf_line) else: fid.writelines(vcf_line) if out_file is not None: fid.close() return vcf_lines_all
38.744361
118
0.622938
682
5,153
4.438416
0.259531
0.023786
0.026759
0.026429
0.339941
0.309217
0.26561
0.251734
0.16518
0.143376
0
0.01252
0.287017
5,153
132
119
39.037879
0.811377
0.352222
0
0.171429
0
0
0.014747
0
0
0
0
0.007576
0
1
0.028571
false
0
0.028571
0
0.085714
0.014286
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
8af96d0df5555eb37bb2040db58c0c8a963553d0
374
py
Python
scrapy_framework/demotest.py
savor007/scrapy_framework
9f1266eb2d4bb7e181d1c5352b05298e77040980
[ "MIT" ]
null
null
null
scrapy_framework/demotest.py
savor007/scrapy_framework
9f1266eb2d4bb7e181d1c5352b05298e77040980
[ "MIT" ]
null
null
null
scrapy_framework/demotest.py
savor007/scrapy_framework
9f1266eb2d4bb7e181d1c5352b05298e77040980
[ "MIT" ]
null
null
null
import importlib # from scrapy_framework.config.settings import SPIDERS # # # for data in SPIDERS: # print(data) # path=data.rsplit(".",1)[0] # cls_name=data.rsplit(".",1)[1] # module=importlib.import_module(path) # cls=getattr(module, cls_name) # print(cls) d = {'a':1,'b':4,'c':2} c=sorted(d.items(), key=lambda x: x[1], reverse=False) print(c)
20.777778
54
0.63369
58
374
4.017241
0.568966
0.085837
0.094421
0
0
0
0
0
0
0
0
0.025723
0.168449
374
18
55
20.777778
0.723473
0.65508
0
0
0
0
0.02521
0
0
0
0
0
0
1
0
false
0
0.25
0
0.25
0.25
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
8afad3555501f5f26b1ee0d4bb4ad784ace7da70
812
py
Python
imagersite/imager_images/urls.py
katcosgrove/django-imager
409081e6fa2933c7247fd8a9de49ec1cb053b778
[ "MIT" ]
null
null
null
imagersite/imager_images/urls.py
katcosgrove/django-imager
409081e6fa2933c7247fd8a9de49ec1cb053b778
[ "MIT" ]
2
2018-05-10T21:53:27.000Z
2018-05-15T17:37:20.000Z
imagersite/imager_images/urls.py
katcosgrove/django-imager
409081e6fa2933c7247fd8a9de49ec1cb053b778
[ "MIT" ]
null
null
null
from django.urls import path from .views import LibraryView, PhotosView, AlbumsView, PhotoView, AlbumView from .views import PhotoCreateView, AlbumCreateView, PhotoEditView, AlbumEditView urlpatterns = [ path('library/', LibraryView.as_view(), name='library'), path('photos/', PhotosView.as_view(), name='photos'), path('photos/<int:pk>', PhotoView.as_view(), name='photo'), path('photos/<int:pk>/edit', PhotoEditView.as_view(), name='photo_edit'), path('albums/', AlbumsView.as_view(), name='albums'), path('albums/<int:pk>', AlbumView.as_view(), name='album'), path('albums/<int:pk>/edit', AlbumEditView.as_view(), name='album_edit'), path('photos/add', PhotoCreateView.as_view(), name='photo_create'), path('albums/add', AlbumCreateView.as_view(), name='album_create') ]
47.764706
81
0.704433
100
812
5.59
0.29
0.096601
0.161002
0.080501
0
0
0
0
0
0
0
0
0.108374
812
16
82
50.75
0.772099
0
0
0
0
0
0.227833
0
0
0
0
0
0
1
0
false
0
0.214286
0
0.214286
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
8afb51114e53c381340def1b8d3f0d6726b17916
310
py
Python
Python/049group_anagrams.py
Apocrypse/LeetCode
3ada2605ce8c8f6dadebf37a30c9c00a0d1ede39
[ "MIT" ]
4
2020-03-17T03:08:51.000Z
2022-03-14T17:33:28.000Z
Python/049group_anagrams.py
Apocrypse/LeetCode
3ada2605ce8c8f6dadebf37a30c9c00a0d1ede39
[ "MIT" ]
null
null
null
Python/049group_anagrams.py
Apocrypse/LeetCode
3ada2605ce8c8f6dadebf37a30c9c00a0d1ede39
[ "MIT" ]
3
2021-04-29T16:51:02.000Z
2022-03-19T17:37:56.000Z
class Solution: def groupAnagrams(self, strs): """ :type strs: List[str] :rtype: List[List[str]] """ result = collections.defaultdict(list) for s in strs: key = "".join(sorted(s)) result[key].append(s) return result.values()
25.833333
46
0.509677
33
310
4.787879
0.666667
0.088608
0
0
0
0
0
0
0
0
0
0
0.354839
310
11
47
28.181818
0.79
0.145161
0
0
0
0
0
0
0
0
0
0
0
1
0.142857
false
0
0
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
8afb97d50c56a425188ed738b021e57471f05003
758
py
Python
app/urls.py
jhabarsingh/polling_app
8e9d6f8489576170cacb47be76e5bc4ec6378d06
[ "MIT" ]
1
2021-05-03T14:55:20.000Z
2021-05-03T14:55:20.000Z
app/urls.py
jhabarsingh/polling_app
8e9d6f8489576170cacb47be76e5bc4ec6378d06
[ "MIT" ]
2
2021-03-01T16:37:30.000Z
2021-05-03T20:37:56.000Z
app/urls.py
jhabarsingh/polling_app
8e9d6f8489576170cacb47be76e5bc4ec6378d06
[ "MIT" ]
null
null
null
from django.urls import path from app import views app_name = 'poll' urlpatterns = [ path('', views.home, name='home'), path('register', views.register, name='register'), path('login', views.admin_login, name='login'), path('create_poll/', views.create_poll, name='create_poll'), path('show_polls/', views.show_poll, name='show_polls'), path('show_polls/<slug:username>/', views.show_polls, name='show_polls'), path('save_poll/', views.save_poll, name='save_poll'), path('polling/<uuid:id>/', views.polling, name='polling'), path('logout/', views.admin_logout, name='logout'), path('poll_result/<uuid:id>/', views.poll_result, name='poll_result'), path('get_data/<uuid:id>/', views.get_data, name='get_data'), ]
39.894737
77
0.675462
106
758
4.632075
0.254717
0.09165
0.06721
0.069246
0
0
0
0
0
0
0
0
0.124011
758
18
78
42.111111
0.739458
0
0
0
0
0
0.306069
0.064644
0
0
0
0
0
1
0
false
0
0.125
0
0.125
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
8afe34ceebaf6f7db1a23f0d092b72c7df8780de
501
py
Python
1200-minimum-absolute-difference/1200-minimum-absolute-difference.py
marzy-bn/Leetcode_2022
07d6b9050279e82f610ed4a54209b33db3e3f8f9
[ "MIT" ]
null
null
null
1200-minimum-absolute-difference/1200-minimum-absolute-difference.py
marzy-bn/Leetcode_2022
07d6b9050279e82f610ed4a54209b33db3e3f8f9
[ "MIT" ]
null
null
null
1200-minimum-absolute-difference/1200-minimum-absolute-difference.py
marzy-bn/Leetcode_2022
07d6b9050279e82f610ed4a54209b33db3e3f8f9
[ "MIT" ]
null
null
null
class Solution: def minimumAbsDifference(self, arr: List[int]) -> List[List[int]]: results = [] mini = 1000000000 arr.sort() for a,b in zip(arr,arr[1:]): diff = abs(a-b) if diff == mini: results.append([a,b]) #print("ppp",results) elif diff < mini: mini = diff results = [(a,b)] #print("sss",results) return results
29.470588
70
0.423154
51
501
4.156863
0.529412
0.037736
0.066038
0
0
0
0
0
0
0
0
0.04
0.451098
501
17
71
29.470588
0.730909
0.07984
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
8aff4d08b156fe05c3178ca97948dcab05b52a18
1,588
py
Python
famous_block/SENet.py
dongqifong/learning
a36453e82802f92c6fb4b03cd8e09938a763bac7
[ "MIT" ]
null
null
null
famous_block/SENet.py
dongqifong/learning
a36453e82802f92c6fb4b03cd8e09938a763bac7
[ "MIT" ]
null
null
null
famous_block/SENet.py
dongqifong/learning
a36453e82802f92c6fb4b03cd8e09938a763bac7
[ "MIT" ]
null
null
null
import torch import torch.nn as nn class SEBlock(nn.Module): def __init__(self, in_c, kernel_size, r, dummy_x) -> None: super().__init__() self.in_c = in_c self.conv1 = nn.Conv1d(in_channels=self.in_c, out_channels=self.in_c, kernel_size=kernel_size, padding=int(kernel_size//2)) self.fc1 = nn.Linear(in_features=self.in_c, out_features=int(self.in_c/r)) self.fc2 = nn.Linear(in_features=int( self.in_c/r), out_features=self.in_c) self.relu = nn.ReLU() self.sigmoid = nn.Sigmoid() dumm_y = self.conv1(dummy_x) self.L = dumm_y.shape[-1] def forward(self, x_in): x_res = self.conv1(x_in) # (-1,C,L) x = self.global_avg_pooling(x_res) # (-1,C,1) x = x.view(-1, self.in_c) # (-1,C) x = self.fc1(x) # (-1,C/r) x = self.relu(x) # (-1,C/r) x = self.fc2(x) # (-1,C) x = self.sigmoid(x) # (-1,C) x = x.view(-1, self.in_c, 1) # (-1,C,1) x = self.scale(x_res, x) # (-1,C,L) x = x_in + x # (-1,C,L) return x # (-1,C,L) def global_avg_pooling(self, x): net = nn.AvgPool1d(kernel_size=self.L) return net(x) # (-1,c,1) def scale(self, x_res, x): return torch.mul(x_res, x) if __name__ == "__main__": in_c = 5 r = 4 kernel_size = 7 dummy_x = torch.randn((2, in_c, 128)) senet = SEBlock(in_c=in_c, r=r, kernel_size=kernel_size, dummy_x=dummy_x) out = senet(dummy_x) print(out.shape)
30.538462
108
0.537783
268
1,588
2.94403
0.216418
0.057034
0.08872
0.015209
0.152091
0.108999
0.038023
0.038023
0
0
0
0.032403
0.300378
1,588
51
109
31.137255
0.677768
0.063602
0
0
0
0
0.005427
0
0
0
0
0
0
1
0.097561
false
0
0.04878
0.02439
0.243902
0.02439
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
8aff5ab7850fa3bfa7318217948a0adf3698bd28
532
py
Python
otk/test/test_rii.py
draustin/otk
c6e91423ec79b85b380ee9385f6d27c91f92503d
[ "MIT" ]
7
2020-05-17T14:26:42.000Z
2022-02-14T04:52:54.000Z
otk/test/test_rii.py
uamhforever/otk
c6e91423ec79b85b380ee9385f6d27c91f92503d
[ "MIT" ]
17
2020-04-10T22:50:00.000Z
2020-06-18T04:54:19.000Z
otk/test/test_rii.py
uamhforever/otk
c6e91423ec79b85b380ee9385f6d27c91f92503d
[ "MIT" ]
1
2022-02-14T04:52:45.000Z
2022-02-14T04:52:45.000Z
import numpy as np from otk import rii def test_rii(): pages = rii.search('Eimerl-o', 'BaB2O4') assert len(pages) == 1 entry = rii.load_page(pages[0]) index = rii.parse_entry(entry) assert (abs(index(220e-9) - 1.8284) < 1e-3) def test_lookup_index(): assert (abs(rii.lookup_index('Malitson', 'SiO2')(800e-9) - 1.4533) < 1e-3) assert np.isclose(rii.lookup_index('Li-293K', 'Si')(1.3e-6), 3.5016, atol=1e-4) assert np.isclose(rii.lookup_index('Vuye-250C', 'Si')(0.5e-6), 4.4021 + 0.04j, atol=1e-4)
31.294118
93
0.640977
94
532
3.542553
0.510638
0.132132
0.126126
0.108108
0.174174
0.174174
0
0
0
0
0
0.125843
0.163534
532
16
94
33.25
0.622472
0
0
0
0
0
0.086466
0
0
0
0
0
0.416667
1
0.166667
false
0
0.166667
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
1
0
0
0
0
0
0
0
0
0
1
c1019da9fdbebdeb2177f41e024ec8a2375bfc50
355
py
Python
corehq/motech/migrations/0002_requestlog_payload_id.py
dimagilg/commcare-hq
ea1786238eae556bb7f1cbd8d2460171af1b619c
[ "BSD-3-Clause" ]
471
2015-01-10T02:55:01.000Z
2022-03-29T18:07:18.000Z
corehq/motech/migrations/0002_requestlog_payload_id.py
dimagilg/commcare-hq
ea1786238eae556bb7f1cbd8d2460171af1b619c
[ "BSD-3-Clause" ]
14,354
2015-01-01T07:38:23.000Z
2022-03-31T20:55:14.000Z
corehq/motech/migrations/0002_requestlog_payload_id.py
dimagilg/commcare-hq
ea1786238eae556bb7f1cbd8d2460171af1b619c
[ "BSD-3-Clause" ]
175
2015-01-06T07:16:47.000Z
2022-03-29T13:27:01.000Z
from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('motech', '0001_initial'), ] operations = [ migrations.AddField( model_name='requestlog', name='payload_id', field=models.CharField(blank=True, max_length=126, null=True), ), ]
20.882353
74
0.588732
33
355
6.212121
0.818182
0
0
0
0
0
0
0
0
0
0
0.027888
0.292958
355
16
75
22.1875
0.788845
0
0
0
0
0
0.107042
0
0
0
0
0
0
1
0
false
0
0.083333
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
c10256e1a56feb6756445ccac8a450d8e5c12102
754
py
Python
revibe/_errors/data.py
Revibe-Music/core-services
6b11cf16ad2c35d948f3a5c0e7a161e5b7cfc1b2
[ "MIT" ]
2
2022-01-24T23:30:18.000Z
2022-01-26T00:21:22.000Z
revibe/_errors/data.py
Revibe-Music/core-services
6b11cf16ad2c35d948f3a5c0e7a161e5b7cfc1b2
[ "MIT" ]
null
null
null
revibe/_errors/data.py
Revibe-Music/core-services
6b11cf16ad2c35d948f3a5c0e7a161e5b7cfc1b2
[ "MIT" ]
null
null
null
from . import base from revibe._helpers import const, status # ----------------------------------------------------------------------------- class ParameterMissingError(base.ExpectationFailedError): default_detail = "missing paramter, please check the docs for request requirements" class SerializerValidationError(base.ExpectationFailedError): default_detail = "misc. serializer error, please try again" class TooManyObjectsReturnedError(base.ProgramError): default_detail = "Too many objects found, please try again" class ObjectAlreadyExists(base.AlreadyReportedError): default_detail = "The request object already exists" class NoKeysError(base.ServiceUnavailableError): default_detail = "Could not find any valid keys"
31.416667
87
0.71618
72
754
7.416667
0.638889
0.121723
0.123596
0.146067
0
0
0
0
0
0
0
0
0.124668
754
23
88
32.782609
0.809091
0.102122
0
0
0
0
0.305185
0
0
0
0
0
0
1
0
false
0
0.166667
0
1
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
c1041af258749524bc55eafa1ab81f6db8f7fd21
1,188
py
Python
erhsh/utils/file_util.py
erhsh/erhsh-python
aeb04352948a2e1f8125a2681b80104b5146bff8
[ "Apache-2.0" ]
3
2021-04-20T11:23:58.000Z
2022-01-17T02:57:33.000Z
erhsh/utils/file_util.py
erhsh/erhsh-python
aeb04352948a2e1f8125a2681b80104b5146bff8
[ "Apache-2.0" ]
null
null
null
erhsh/utils/file_util.py
erhsh/erhsh-python
aeb04352948a2e1f8125a2681b80104b5146bff8
[ "Apache-2.0" ]
null
null
null
import os from datetime import datetime def list_sub_dirs(dir_path): if not os.path.exists(dir_path): raise RuntimeError("invalid dir path.") if not os.path.isdir(dir_path): raise RuntimeError("invalid dir path.") sub_dirs = [] sub_files = os.listdir(dir_path) for sub_file_name in sub_files: sub_file_path = os.path.join(dir_path, sub_file_name) if not os.path.isdir(sub_file_path): continue sub_dirs.append(sub_file_path) return sub_dirs def flatten_dir_path(dir_path): sub_dirs = list_sub_dirs(dir_path) for sub_dir_path in sub_dirs: sub_sub_dirs = list_sub_dirs(sub_dir_path) for sub_sub_dir_path in sub_sub_dirs: sub_sub_dir_name = os.path.basename(sub_sub_dir_path) target_dir_path = '_'.join([sub_dir_path, sub_sub_dir_name]) print(f"move: {sub_sub_dir_path} -> {target_dir_path}") os.renames(sub_sub_dir_path, target_dir_path) def create_dir(dir_path): if not os.path.exists(dir_path): os.makedirs(dir_path) return dir_path return create_dir(dir_path + "." + datetime.now().strftime("%Y%m%d%H%M%S"))
31.263158
79
0.677609
192
1,188
3.807292
0.223958
0.239398
0.095759
0.060192
0.444596
0.300958
0.28591
0.084815
0.084815
0
0
0
0.223906
1,188
37
80
32.108108
0.792842
0
0
0.137931
0
0
0.078283
0
0
0
0
0
0
1
0.103448
false
0
0.068966
0
0.275862
0.034483
0
0
0
null
1
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
0
1
c1099cb2a2632c598917595fb2f7f6e6745f4161
3,885
py
Python
reddit_IG_FB.py
Wanatux/Reddit-to-FB-Page
9f70b4cff72aecc34bad047078d77b534a1abfb4
[ "MIT" ]
null
null
null
reddit_IG_FB.py
Wanatux/Reddit-to-FB-Page
9f70b4cff72aecc34bad047078d77b534a1abfb4
[ "MIT" ]
null
null
null
reddit_IG_FB.py
Wanatux/Reddit-to-FB-Page
9f70b4cff72aecc34bad047078d77b534a1abfb4
[ "MIT" ]
null
null
null
#Clean Code for Picture uploader for social media platform import praw import random import pandas as pd import config from openpyxl import load_workbook import requests import json #Reddit Creds r = praw.Reddit( client_id= "Enter Info Here", client_secret= "Enter Info Here", user_agent= "Enter Info Here", username= "Enter Info Here", password= "Enter Info Here", ) #SubReddit List reddit_list = config.subreddit_list #Praw Scrape pics = [] Reddit_Scrapper = True while Reddit_Scrapper: subreddit = r.subreddit(random.choice(reddit_list)) for submission in subreddit.hot(limit=10): try: if 'jpg' not in submission.url: continue if submission.stickied: continue pic_tittle = submission.title url = submission.url un_id = submission.id pics.append((pic_tittle, url, un_id)) except: pass #Check if post was already posted #If it doesnt exist in Excel then continue df = pd.read_excel(r'subrreddit_history.xlsx') checker = True while checker: if len(pics) == 0: checker = False if pics[0][2] in df.values: pics.pop(0) if len(pics) == 0: checker = False else: checker = False if len(pics) > 1: Reddit_Scrapper = False # If data doesnt exist then append row df = pd.DataFrame({'un_id': [pics[0][2]], 'pic_tittle': [pics[0][0]]}) writer = pd.ExcelWriter('subrreddit_history.xlsx', engine='openpyxl') # try to open an existing workbook writer.book = load_workbook('subrreddit_history.xlsx') # copy existing sheets writer.sheets = dict((ws.title, ws) for ws in writer.book.worksheets) # read existing file reader = pd.read_excel(r'subrreddit_history.xlsx') # write out the new sheet df.to_excel(writer,index=False,header=False,startrow=len(reader)+1) writer.close() #this will get the Tittle of the post split it and add #s ad the beggining of each word for Tags. def fb_descript(): tags = [] s = ' ' for x in pics[0][0].split(): tags.append('#' + x) s = s.join(tags) return ''' {a} {c} {c} {c} {c} {c} {c} {c} {c} {c} {c} {b}'''.format(a=pics[0][0], b=s, c='.' *5) #FB Credits and Photo Post #INstagram Post Def def postInstagramPic(): #Post the Image image_location_1 = pics[0][1] post_url = 'https://graph.facebook.com/v10.0/{}/media'.format(config.inst_id) payload = { 'image_url': image_location_1, 'caption': fb_descript(), 'access_token': config.inst_acc_token, } r = requests.post(post_url, data=payload) print(r.text) #Instagram for some reason will need to convert the responde ID to a publish request. result = json.loads(r.text) if 'id' in result: creation_id = result['id'] second_url = 'https://graph.facebook.com/v10.0/{}/media_publish'.format(config.inst_id) second_payload = { 'creation_id': creation_id, 'access_token': config.inst_acc_token, } r = requests.post(second_url, data=second_payload) print('--------Just posted to instagram--------') print(r.text) else: pass postInstagramPic() #Facebook Picture Def def post_FBpage(): image_url = 'https://graph.facebook.com/{}/photos'.format(config.fb_page_id) image_location = pics[0][1] msg = fb_descript() img_payload = { 'message': msg, 'url': image_location, 'access_token': config.fb_acc_token } #Send the POST request r = requests.post(image_url, data=img_payload) print('--------Just posted to Facebook--------') print(r.text) post_FBpage()
28.566176
97
0.605405
515
3,885
4.44466
0.337864
0.019659
0.010485
0.012232
0.14941
0.117955
0.098733
0.0699
0.041066
0
0
0.010623
0.273102
3,885
136
98
28.566176
0.799929
0.149807
0
0.242991
0
0
0.175038
0.028006
0
0
0
0
0
1
0.028037
false
0.028037
0.065421
0
0.102804
0.046729
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
c10abea2f9bc648d3729f1ca476f5d8723fdfb12
3,914
py
Python
eph/interface.py
bluePhlavio/eph
9ad8d753ba70d7ed147a591c4181edd56b9533cc
[ "MIT" ]
1
2021-05-07T23:35:32.000Z
2021-05-07T23:35:32.000Z
eph/interface.py
bluePhlavio/eph
9ad8d753ba70d7ed147a591c4181edd56b9533cc
[ "MIT" ]
8
2019-11-02T01:04:26.000Z
2021-06-02T00:01:37.000Z
eph/interface.py
bluePhlavio/eph
9ad8d753ba70d7ed147a591c4181edd56b9533cc
[ "MIT" ]
1
2019-03-20T13:55:52.000Z
2019-03-20T13:55:52.000Z
""" Contains classes and functions useful to interact with the `Jpl Horizons service`_ from NASA. .. _`Jpl Horizons service`: https://ssd.jpl.nasa.gov/?horizons """ import requests from astropy.table import QTable from .util import addparams2url, wrap from .config import read_config from .models import BaseMap from .horizons import JPL_ENDPOINT, transform_key, transform from .parsers import parse, get_sections class JplReq(BaseMap): """ A requests to Jpl Horizons service. It can be thought as a :class:`dict` where key-value pairs represents Jpl Horizons parameters. Jpl parameters can be also set as attributes of the :class:`JplReq` instance. Furthermore, keys and values are adjusted to match Jpl Horizons interface in order to enhance readability and usability. """ def __getattr__(self, key): key = transform_key(key) return super(self.__class__, self).__getattr__(key) def __setattr__(self, key, value): k, v = transform(key, value) super(self.__class__, self).__setattr__(k, v) def __delattr__(self, key): key = transform_key(key) super(self.__class__, self).__delattr__(key) def read(self, filename, section='DEFAULT'): """ Reads configurations parameters from an ini file. Reads the `section` section of the ini config file `filename` and set all parameters for the Jpl request. Args: filename (str): the config file to be read. section (str): the section of the ini config file to be read. Returns: :class:`JplReq`: the object itself. """ params = read_config(filename, section) return self.set(params) def url(self): """ Calculate the Jpl Horizons url corresponding to the :class:`JplReq` object. Returns: str: the url with the Jpl parameters encoded in the query string. """ return addparams2url(JPL_ENDPOINT, {k: wrap(str(v)) for k, v in self.items()}) def query(self): """ Performs the query to the Jpl Horizons service. Returns: :class:`JplRes`: the response from Jpl Horizons service. Raises: :class:`ConnectionError` """ try: http_response = requests.get(self.url()) except requests.exceptions.ConnectionError as e: raise ConnectionError(e.__str__()) return JplRes(http_response) class JplRes(object): """A response from the Jpl Horizons service.""" def __init__(self, http_response): """ Initialize a :class:`JplRes` object from a `requests`_ http response object. Args: http_response: the http response from Jpl Horizons service. .. _`requests`: http://docs.python-requests.org/en/master/ """ self.http_response = http_response def raw(self): """Returns the content of the Jpl Horizons http response as is.""" return self.http_response.text def get_header(self): header, ephem, footer = get_sections(self.raw()) return header def get_data(self): header, data, footer = get_sections(self.raw()) return data def get_footer(self): header, ephemeris, footer = get_sections(self.raw()) return footer def parse(self, target=QTable): """ Parse the http response from Jpl Horizons and return, according to target. * an `astropy.table.Table`_ object. * an `astropy.table.QTable`_ object. .. _`astropy.table.Table`: http://docs.astropy.org/en/stable/table/ .. _`astropy.table.QTable`: http://docs.astropy.org/en/stable/table/ """ return parse(self.raw(), target=target) def __str__(self): return self.raw()
28.992593
92
0.628258
478
3,914
4.983264
0.271967
0.055416
0.052897
0.026448
0.157431
0.130982
0.026029
0
0
0
0
0.000705
0.275677
3,914
134
93
29.208955
0.839506
0.441748
0
0.042553
0
0
0.003819
0
0
0
0
0
0
1
0.276596
false
0
0.148936
0.021277
0.680851
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
1
0
0
0
0
1
0
0
2
c10b7e02be55b3e42b50607092409d07c6db24f8
64
py
Python
phanpy/pokedex/admin.py
wengole/phanpy
17392d3770af16a35198f35a7b2bfa24ff18a1be
[ "BSD-3-Clause" ]
null
null
null
phanpy/pokedex/admin.py
wengole/phanpy
17392d3770af16a35198f35a7b2bfa24ff18a1be
[ "BSD-3-Clause" ]
1
2016-02-03T00:07:34.000Z
2016-02-03T00:07:34.000Z
phanpy/pokedex/admin.py
wengole/phanpy
17392d3770af16a35198f35a7b2bfa24ff18a1be
[ "BSD-3-Clause" ]
null
null
null
from .autoregister import autoregister autoregister('pokedex')
16
38
0.828125
6
64
8.833333
0.666667
0
0
0
0
0
0
0
0
0
0
0
0.09375
64
3
39
21.333333
0.913793
0
0
0
0
0
0.109375
0
0
0
0
0
0
1
0
true
0
0.5
0
0.5
0
1
0
0
null
0
0
0
0
0
0
0
0
0
0
0
0
0
1
0
0
0
0
0
0
0
0
0
0
null
0
0
0
0
0
0
1
0
1
0
0
0
0
4
c10de940ca61195f3abd45d17f60bcb7de5621f4
3,834
py
Python
uil/core/templatetags/transformat.py
UiL-OTS-labs/django-shared-core
702ca346f1be861108ec70ceed2ed3b99623f0a3
[ "Apache-2.0" ]
null
null
null
uil/core/templatetags/transformat.py
UiL-OTS-labs/django-shared-core
702ca346f1be861108ec70ceed2ed3b99623f0a3
[ "Apache-2.0" ]
13
2019-06-25T13:23:30.000Z
2022-02-10T07:00:39.000Z
uil/core/templatetags/transformat.py
UiL-OTS-labs/django-shared-core
702ca346f1be861108ec70ceed2ed3b99623f0a3
[ "Apache-2.0" ]
null
null
null
from django.template import Library, Node, TemplateSyntaxError, Variable, VariableDoesNotExist from django.template.base import render_value_in_context from django.utils.safestring import SafeData, mark_safe register = Library() class FormattedTranslateNode(Node): def __init__(self, filter_expression, noop, formatvalues, asvar=None, message_context=None): self.noop = noop self.formatvalues = formatvalues self.asvar = asvar self.message_context = message_context self.filter_expression = filter_expression if isinstance(self.filter_expression.var, str): self.filter_expression.var = Variable("'%s'" % self.filter_expression.var) def render(self, context): self.filter_expression.var.translate = not self.noop if self.message_context: self.filter_expression.var.message_context = ( self.message_context.resolve(context)) output = self.filter_expression.resolve(context) value = render_value_in_context(output, context) # Restore percent signs. Percent signs in template text are doubled # so they are not interpreted as string format flags. is_safe = isinstance(value, SafeData) value = value.replace('%%', '%') formatvalues = [] for formatvalue in self.formatvalues: try: variable = Variable(formatvalue) formatvalues.append(variable.resolve(context)) except VariableDoesNotExist: formatvalues.append(formatvalue) value = value.format(*formatvalues) value = mark_safe(value) if is_safe else value if self.asvar: context[self.asvar] = value return '' else: return value @register.tag('transformat') def do_translate_format(parser, token): """ This tag is a modified version of the trans tag. In addition to doing all the things the trans tag does, it also performs a str.format() on the translation. The values for the format call can be added to the tag as additional parameters. """ bits = token.split_contents() if len(bits) < 2: raise TemplateSyntaxError("'%s' takes at least one argument" % bits[0]) message_string = parser.compile_filter(bits[1]) remaining = bits[2:] noop = False asvar = None message_context = None seen = set() invalid_context = {'as', 'noop'} formatvalues = [] while remaining: option = remaining.pop(0) if option in seen: raise TemplateSyntaxError( "The '%s' option was specified more than once." % option, ) elif option == 'noop': noop = True elif option == 'context': try: value = remaining.pop(0) except IndexError: raise TemplateSyntaxError( "No argument provided to the '%s' tag for the context option." % bits[0] ) if value in invalid_context: raise TemplateSyntaxError( "Invalid argument '%s' provided to the '%s' tag for the context option" % (value, bits[0]), ) message_context = parser.compile_filter(value) elif option == 'as': try: value = remaining.pop(0) except IndexError: raise TemplateSyntaxError( "No argument provided to the '%s' tag for the as option." % bits[0] ) asvar = value else: formatvalues.append(option) seen.add(option) return FormattedTranslateNode(message_string, noop, formatvalues, asvar, message_context)
36.865385
116
0.603286
408
3,834
5.568627
0.308824
0.06338
0.070423
0.050616
0.172535
0.104313
0.104313
0.104313
0.104313
0.082746
0
0.003811
0.315597
3,834
103
117
37.223301
0.862043
0.092853
0
0.180723
0
0
0.086302
0
0
0
0
0
0
1
0.036145
false
0
0.036145
0
0.120482
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
c10e02e2fe07318224fa852f647944dd03346223
422
py
Python
omnipark/api/v1/login/views.py
ryanpineo/omnipark-back
2b8fa6a4e576a6c187c3ad1ce42a95d7accbe29f
[ "Apache-2.0" ]
null
null
null
omnipark/api/v1/login/views.py
ryanpineo/omnipark-back
2b8fa6a4e576a6c187c3ad1ce42a95d7accbe29f
[ "Apache-2.0" ]
null
null
null
omnipark/api/v1/login/views.py
ryanpineo/omnipark-back
2b8fa6a4e576a6c187c3ad1ce42a95d7accbe29f
[ "Apache-2.0" ]
null
null
null
from rest_framework import response, viewsets from .serializers import LoginSerializer class LoginViewSet(viewsets.GenericViewSet): serializer_class = LoginSerializer def create(self, request, *args, **kwargs): serializer = self.get_serializer(data=request.data) serializer.is_valid(raise_exception=True) token = serializer.save() return response.Response({'token': token.key})
30.142857
59
0.734597
45
422
6.777778
0.644444
0
0
0
0
0
0
0
0
0
0
0
0.172986
422
13
60
32.461538
0.873926
0
0
0
0
0
0.011848
0
0
0
0
0
0
1
0.111111
false
0
0.222222
0
0.666667
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
1
0
0
1
c1151c01209f2be4a1e7c4a0edc5ad3a63d4466c
3,425
py
Python
generate_text/generate_tensorflow.py
renjunxiang/Text_Generate
209f2fcf58aed7661de71f34549d555e33feae53
[ "MIT" ]
101
2018-07-31T16:02:57.000Z
2022-03-20T22:50:33.000Z
generate_text/generate_tensorflow.py
renjunxiang/generate_text
209f2fcf58aed7661de71f34549d555e33feae53
[ "MIT" ]
1
2020-12-07T04:32:38.000Z
2021-08-18T04:47:49.000Z
generate_text/generate_tensorflow.py
Jiaogh/Text_Generate
209f2fcf58aed7661de71f34549d555e33feae53
[ "MIT" ]
26
2019-01-21T06:36:00.000Z
2022-03-15T06:29:45.000Z
import os import numpy as np import tensorflow as tf from .rnn import model_tensorflow import re import pickle DIR = os.path.dirname(os.path.abspath(__file__)) def generate_tensorflow(process_path=DIR + '/model/poem/poem.pkl', model_path=DIR + '/model/poem/train', maxlen=80, newline=True ): ''' :param process_path: 训预处理模型路径 :param model_path: 网络参数路径 :param maxlen: maxlen创作最大长度 :return: ''' with open(process_path, mode='rb') as f: data_process = pickle.load(f) word_index = data_process.word_index input_data = tf.placeholder(tf.int32, [None, None]) output_targets = tf.placeholder(tf.int32, [None, None]) tensors = model_tensorflow(input_data=input_data, output_targets=output_targets, num_words=data_process.num_words, num_units=data_process.num_units, num_layers=data_process.num_layers, batchsize=1) saver = tf.train.Saver(tf.global_variables()) initializer = tf.global_variables_initializer() with tf.Session() as sess: sess.run(initializer) checkpoint = tf.train.latest_checkpoint(model_path) saver.restore(sess, checkpoint) while True: print('创作前请确保有模型。输入开头,quit=离开;\n请输入命令:') start_word = input() if start_word == 'quit': print('\n再见!') break if start_word == '': words = list(word_index.keys()) # 随机初始不能是标点和终止符 for i in ['。', '?', '!', 'E']: words.remove(i) start_word = np.random.choice(words, 1) try: print('开始创作') input_index = [] for i in start_word: index_next = word_index[i] input_index.append(index_next) input_index = input_index[:-1] # 原则上不会出现0,保险起见还是加上去 while index_next not in [0, word_index['E']]: input_index.append(index_next) y_predict = sess.run(tensors['prediction'], feed_dict={input_data: np.array([input_index])}) y_predict = y_predict[-1] index_next = np.random.choice(np.arange(len(y_predict)), p=y_predict) if len(input_index) > maxlen: break index_word = {word_index[i]: i for i in word_index} text = [index_word[i] for i in input_index] text = ''.join(text) except Exception as e: print(e) text = '不能识别%s' % start_word finally: print('创作完成:\n') if newline: text_list = re.findall(pattern='[^。?!]*[。?!]', string=text) for i in text_list: print(i) else: print(text) print('\n------------我是分隔符------------\n') if __name__ == '__main__': generate_tensorflow(process_path=DIR + '/model/poem/poem.pkl', model_path=DIR + '/model/poem/train', maxlen=100)
36.052632
89
0.494891
357
3,425
4.518207
0.333333
0.044637
0.018599
0.039678
0.16491
0.133912
0.099194
0.099194
0.099194
0.099194
0
0.007257
0.396496
3,425
94
90
36.43617
0.773101
0.036788
0
0.081081
1
0
0.061487
0.019578
0
0
0
0
0
1
0.013514
false
0
0.081081
0
0.094595
0.108108
0
0
0
null
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
1
0
0
0
null
0
0
0
0
0
0
0
0
0
0
0
0
0
1
c1162fbd326c2f2b744b4495ef4678ed8f97bd59
1,042
py
Python
ymir/backend/src/ymir-app/app/models/model.py
elliotmessi/ymir
3ec8145a1f894778116eb5218de223f6dd805b70
[ "Apache-2.0" ]
null
null
null
ymir/backend/src/ymir-app/app/models/model.py
elliotmessi/ymir
3ec8145a1f894778116eb5218de223f6dd805b70
[ "Apache-2.0" ]
null
null
null
ymir/backend/src/ymir-app/app/models/model.py
elliotmessi/ymir
3ec8145a1f894778116eb5218de223f6dd805b70
[ "Apache-2.0" ]
null
null
null
from datetime import datetime from sqlalchemy import ( Boolean, Column, DateTime, Float, Integer, String, Text, UniqueConstraint, ) from app.config import settings from app.db.base_class import Base class Model(Base): __tablename__ = "model" id = Column(Integer, primary_key=True, index=True, autoincrement=True) hash = Column(String(settings.HASH_LEN_LIMIT), index=True) name = Column(String(settings.NAME_LEN_LIMIT), index=True) state = Column(Integer, index=True) map = Column(Float) parameters = Column(Text(settings.PARA_LEN_LIMIT)) task_id = Column(Integer, index=True) user_id = Column(Integer, index=True) is_deleted = Column(Boolean, default=False) create_datetime = Column(DateTime, default=datetime.utcnow, nullable=False) update_datetime = Column( DateTime, default=datetime.utcnow, onupdate=datetime.utcnow, nullable=False, ) __table_args__ = (UniqueConstraint("user_id", "hash", name="uniq_user_hash"),)
28.162162
82
0.696737
124
1,042
5.653226
0.379032
0.077033
0.064194
0.094151
0.191155
0.122682
0
0
0
0
0
0
0.199616
1,042
36
83
28.944444
0.840528
0
0
0.0625
0
0
0.028791
0
0
0
0
0
0
1
0
false
0
0.125
0
0.5625
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
1
0
0
1
c117e2d8b5f1b909c31dcd1e8e67fe7c83ac1b66
2,348
py
Python
apps/checkout/views.py
amyhoo/django-oscar-alipay
eacad65416428c6e09974219487a206577d34312
[ "BSD-3-Clause" ]
59
2015-08-29T10:51:34.000Z
2021-11-03T10:00:25.000Z
apps/checkout/views.py
amyhoo/django-oscar-alipay
eacad65416428c6e09974219487a206577d34312
[ "BSD-3-Clause" ]
4
2015-09-02T08:55:42.000Z
2017-05-15T10:33:00.000Z
apps/checkout/views.py
amyhoo/django-oscar-alipay
eacad65416428c6e09974219487a206577d34312
[ "BSD-3-Clause" ]
22
2015-08-10T10:46:18.000Z
2020-04-04T07:11:55.000Z
####################################################################################### # 重写 PaymentMethodView 提供多种支付方法的选择, # 重写 PaymentDetailsView 支付细节在具体支付方法包(例如alipay)中实现 ####################################################################################### from oscar.apps.checkout.views import PaymentMethodView,PaymentDetailsView as OscarPaymentDetailsView from alipay.warrant.views import AlipayHandle from django.http import HttpResponseRedirect from .mixins import RedirectSessionMixin from oscar.core.loading import get_class, get_classes, get_model OrderPlacementMixin = get_class('checkout.mixins', 'OrderPlacementMixin') class MultiPaymentMethodView(PaymentMethodView): template_name = 'oscar/checkout/payment_method.html' def get(self, request, *args, **kwargs): # By default we redirect straight onto the payment details view. Shops # that require a choice of payment method may want to override this # method to implement their specific logic. context = self.get_context_data(**kwargs) return self.render_to_response(context) class MultiPaymentDetailsView(RedirectSessionMixin,OscarPaymentDetailsView): template_name = 'oscar/checkout/payment_details.html' template_name_preview = 'oscar/checkout/preview.html' paymentsource_name={ 'alipay_warrant':"支付宝担保", } paymentsource_method={ 'alipay_warrant':AlipayHandle } def get_context_data(self, **kwargs): context=super(PaymentDetailsView,self).get_context_data(**kwargs) context['paymethod']=self.paymentsource_name[self.get_paymethod()] return context def get(self, request, *args, **kwargs): if kwargs.get('paymethod'): self.save_paymethod(kwargs.get('paymethod')) return HttpResponseRedirect('/checkout/preview') return super(PaymentDetailsView,self).get(self,request, *args, **kwargs) def handle_payment(self, order_number, order_total, **kwargs): ''' 处理支付请求 :param order_number: :param total_incl_tax: :param kwargs: :return: ''' self.set_order_number(order_number) self.set_info() paymethod=self.paymentsource_method[self.get_paymethod()] paymethod(self,order_number, **kwargs) from oscar.apps.checkout.views import *
44.301887
101
0.668654
235
2,348
6.519149
0.374468
0.022846
0.027415
0.035248
0.165796
0.077024
0
0
0
0
0
0
0.171635
2,348
53
102
44.301887
0.787661
0.142249
0
0.057143
0
0
0.116227
0.053902
0
0
0
0
0
1
0.114286
false
0
0.171429
0
0.6
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
1
0
0
1
c1186e20834312aecb510b36bdf673c14a6fdea9
553
py
Python
studzie/keras_tutor/keras_cifar100.py
amozie/amozie
fb7c16ce537bc5567f9c87cfc22c564a4dffc4ef
[ "Apache-2.0" ]
null
null
null
studzie/keras_tutor/keras_cifar100.py
amozie/amozie
fb7c16ce537bc5567f9c87cfc22c564a4dffc4ef
[ "Apache-2.0" ]
null
null
null
studzie/keras_tutor/keras_cifar100.py
amozie/amozie
fb7c16ce537bc5567f9c87cfc22c564a4dffc4ef
[ "Apache-2.0" ]
null
null
null
import numpy as np import matplotlib.pyplot as plt from keras.models import Sequential, Model from keras.layers import Dense, Activation, Input, Dropout, Flatten, Reshape, \ Conv2D, MaxPooling2D, concatenate, GlobalMaxPooling2D from keras.datasets import cifar100 from keras.callbacks import EarlyStopping from keras.utils import to_categorical, plot_model from keras.optimizers import Adam from keras.applications.vgg16 import VGG16 from skimage import transform, color (X_train, y_train), (X_test, y_test) = cifar100.load_data(label_mode='fine')
39.5
79
0.819168
77
553
5.779221
0.61039
0.141573
0.062921
0
0
0
0
0
0
0
0
0.026585
0.115732
553
13
80
42.538462
0.883436
0
0
0
0
0
0.007233
0
0
0
0
0
0
1
0
true
0
0.833333
0
0.833333
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
1
0
1
0
0
0
0
2
c11b5bc00c820d2149831a6a5219b716f80b5da6
497
py
Python
evaluate.py
QData/DeepDiff
2aef9c5520595b14da265578c2c04c3d65a4ad01
[ "Apache-2.0" ]
6
2021-04-28T22:46:11.000Z
2022-02-06T05:02:57.000Z
evaluate.py
QData/DeepDiff
2aef9c5520595b14da265578c2c04c3d65a4ad01
[ "Apache-2.0" ]
null
null
null
evaluate.py
QData/DeepDiff
2aef9c5520595b14da265578c2c04c3d65a4ad01
[ "Apache-2.0" ]
1
2022-03-11T01:41:49.000Z
2022-03-11T01:41:49.000Z
import numpy import torch import scipy import scipy.sparse as sp import logging from six.moves import xrange from collections import OrderedDict import sys import pdb from sklearn import metrics import torch.nn.functional as F from torch.autograd import Variable def compute_metrics(predictions, targets): pred=predictions.numpy() targets=targets.numpy() R2,p=scipy.stats.pearsonr(numpy.squeeze(targets),numpy.squeeze(pred)) MSE=metrics.mean_squared_error(targets, pred) return MSE, R2
20.708333
70
0.810865
73
497
5.479452
0.520548
0.055
0
0
0
0
0
0
0
0
0
0.004556
0.1167
497
23
71
21.608696
0.906606
0
0
0
0
0
0
0
0
0
0
0
0
1
0.055556
false
0
0.666667
0
0.777778
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
1
0
1
0
0
2
c11bc2c07ea4c7d0324366918fff40bddd73b06c
1,585
py
Python
crawler/scrapy_ffxiv/spiders/gathering_spider.py
shengzhc/sc-ff14-scrapy
2d5b74980e47ec140a4b8d506079fcc94dde54a2
[ "MIT" ]
null
null
null
crawler/scrapy_ffxiv/spiders/gathering_spider.py
shengzhc/sc-ff14-scrapy
2d5b74980e47ec140a4b8d506079fcc94dde54a2
[ "MIT" ]
null
null
null
crawler/scrapy_ffxiv/spiders/gathering_spider.py
shengzhc/sc-ff14-scrapy
2d5b74980e47ec140a4b8d506079fcc94dde54a2
[ "MIT" ]
null
null
null
import scrapy from scrapy.spiders import CrawlSpider, Rule from scrapy.linkextractors import LinkExtractor from scrapy_ffxiv.items import FfxivGatheringNode """ Spider to gather info from `www.ffxiv-gathering.com` """ class GatheringSpider(CrawlSpider): name = 'ff14-gathering' allowed_domains = [ 'ffxiv-gathering.com', ] start_urls = [ 'https://www.ffxiv-gathering.com/all.php', ] rules = ( Rule(LinkExtractor(allow=('ff14fish.carbuncleplushy.com/index.html')), callback='parse_fishing_nodes'), ) def parse_start_url(self, response): nodes = response.selector.xpath("//table[contains(@id, 'myTable')]/tbody/tr") for node in nodes: yield FfxivGatheringNode(name=node.xpath(".//td[1]/text()").get(), location=node.xpath(".//td[4]/text()").get(), time=node.xpath(".//td[6]/text()").get(), gclass=node.xpath(".//td[7]/text()").get()) def parse_fishing_node(self, response): nodes = response.selector.xpath("//table[@id='fishes/tbody/tr[contains(@class, 'fish-entry')]") for node in nodes: yield { 'item': node.xpath(".//td//a[@class='fish-name']/text()").get(), 'level': '1', 'location': node.xpath(".//td//a[@class='location-name']/text()").get() + ' - ' + node.xpath(".//td//span[@class='zone-name']/text()").get(), 'time': 'Anytime', 'class': 'Fishing', }
35.222222
157
0.55142
170
1,585
5.088235
0.435294
0.072832
0.089017
0.046243
0.182659
0.099422
0.099422
0
0
0
0
0.007712
0.263722
1,585
44
158
36.022727
0.733505
0
0
0.0625
0
0
0.294156
0.142482
0
0
0
0
0
1
0.0625
false
0
0.125
0
0.34375
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
c11c4e38953d87d8740e1177783eb8eb9e19cef3
927
py
Python
horizon/test_horizon-controller-node.py
cyberxml/testinfra-openstack-tests
8b57ff2901463deeaa4d58486bb6d14f65ba3d24
[ "MIT" ]
null
null
null
horizon/test_horizon-controller-node.py
cyberxml/testinfra-openstack-tests
8b57ff2901463deeaa4d58486bb6d14f65ba3d24
[ "MIT" ]
null
null
null
horizon/test_horizon-controller-node.py
cyberxml/testinfra-openstack-tests
8b57ff2901463deeaa4d58486bb6d14f65ba3d24
[ "MIT" ]
null
null
null
import pytest @pytest.mark.parametrize("name", [ ("openstack-dashboard"), ("httpd"), ("memcached"), ]) def test_packages(host, name): pkg = host.package(name) assert pkg.is_installed @pytest.mark.parametrize("name,port", [ ("httpd","80"), ("httpd-ssl","443"), ("memcached","11211"), ]) def test_listening_interfaces(host, name, port): sckt = host.socket("tcp://0.0.0.0:" + port) assert sckt.is_listening @pytest.mark.parametrize("process,enabled", [ ("httpd", True), ("memcached", True), ]) def test_services(host, process, enabled): svc = host.service(process) assert svc.is_running if enabled: assert svc.is_enabled @pytest.mark.parametrize("service,conf_file", [ ("openstack-dashboard", "local_settings"), ]) def test_main_services_files(host, service, conf_file): _file = host.file("/etc/" + service + "/" + conf_file) assert _file.exists
25.054054
58
0.651564
113
927
5.19469
0.39823
0.068143
0.143101
0.085179
0
0
0
0
0
0
0
0.018182
0.169364
927
36
59
25.75
0.744156
0
0
0.125
0
0
0.192017
0
0
0
0
0
0.15625
1
0.125
false
0
0.03125
0
0.15625
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