max_stars_repo_path
stringlengths
4
182
max_stars_repo_name
stringlengths
6
116
max_stars_count
int64
0
191k
id
stringlengths
7
7
content
stringlengths
100
10k
size
int64
100
10k
setup.py
MrManlu/dorna
39
2023279
import setuptools with open("README.md", "r") as fh: readme = fh.read() setuptools.setup( name="dorna", version="1.4.2", author="<NAME>", author_email="<EMAIL>", description="Dorna Python API", long_description=readme, long_description_content_type='text/markdown', url="https://dorna.ai/", project_urls={ 'Latest release': 'https://github.com/dorna-robotics/dorna/releases/', }, packages=setuptools.find_packages(), classifiers=[ 'Intended Audience :: Developers', 'Programming Language :: Python :: 3.7', "Operating System :: OS Independent", 'Topic :: Software Development :: Libraries :: Python Modules', ], install_requires=[ "setuptools", "PyYAML", "numpy", "pyserial", ], license="MIT", include_package_data=True, zip_safe = False, )
929
tests/test_match_result.py
julianirwin/predthread
0
2023275
from predthread import MatchResult from pytest import fixture equal_scores = ( ((0, 0), (0, 0)), ((1, 0), (1, 0)), ((0, 1), (0, 1)), ((1, 1), (1, 1)), ((5, 5), (5, 5)), ) @fixture(params=equal_scores) def exactly_equal_match_results(request): return MatchResult(*request.param[0]), MatchResult(*request.param[1]) unequal_scores = ( ((0, 0), (0, 1)), ((1, 0), (0, 0)), ((1, 1), (0, 0)), ((1, 1), (3, 1)), ((5, 5), (0, 5)), ) @fixture(params=unequal_scores) def not_exactly_equal_match_results(request): return MatchResult(*request.param[0]), MatchResult(*request.param[1]) same_result_scores = ( ((0, 0), (1, 1)), ((1, 0), (3, 0)), ((2, 2), (0, 0)), ((1, 3), (2, 4)), ) @fixture(params=same_result_scores) def same_result_match_results(request): return MatchResult(*request.param[0]), MatchResult(*request.param[1]) not_same_result_scores = ( ((0, 0), (2, 1)), ((1, 1), (3, 0)), ((2, 0), (0, 2)), ((1, 3), (4, 4)), ) @fixture(params=not_same_result_scores) def not_same_result_match_results(request): return MatchResult(*request.param[0]), MatchResult(*request.param[1]) class TestMatchResult: def test_init(self): match_result = MatchResult(0, 0) def test_exactly_equal(self, exactly_equal_match_results): mr1, mr2 = exactly_equal_match_results assert mr1.exactly_equals(mr2) def test_not_exactly_equal(self, not_exactly_equal_match_results): mr1, mr2 = not_exactly_equal_match_results assert not mr1.exactly_equals(mr2) def test_same_result_as(self, same_result_match_results): mr1, mr2 = same_result_match_results assert mr1.same_result_as(mr2) def test_not_same_result_as(self, not_same_result_match_results): mr1, mr2 = not_same_result_match_results assert not mr1.same_result_as(mr2)
1,877
cocpit/predictions.py
vprzybylo/vprzybylo.github.io
2
2024487
"""holds methods regarding making model predictions for confusion matrices and running the model on new data""" import itertools import os import numpy as np import torch import torch.nn.functional as F import cocpit.config as config from cocpit.auto_str import auto_str @auto_str class LoaderPredictions: """setup methods for predictions across batches""" def __init__(self): self.all_labels = [] self.all_paths = [] self.all_topk_probs = [] self.all_topk_classes = [] self.all_max_preds = [] self.wrong_trunc = [] def concat(self, var): return np.asarray(list(itertools.chain(*var))) def concatenate_loader_vars( self, ): """ flatten arrays from appending in batches """ if self.labels is None: pred_list = [ self.all_paths, self.all_topk_probs, self.all_topk_classes, self.all_max_preds, ] ( self.all_paths, self.all_topk_probs, self.all_topk_classes, self.all_max_preds, ) = map(self.concat, pred_list) else: pred_list = [ self.all_labels, self.all_paths, self.all_topk_probs, self.all_topk_classes, self.all_max_preds, ] # print(pred_list) ( self.all_labels, self.all_paths, self.all_topk_probs, self.all_topk_classes, self.all_max_preds, ) = map(self.concat, pred_list) def hone_incorrect_predictions(self, label_list, human_label, model_label): """ find indices where human labeled as one thing and model labeled as another """ idx_human = np.where(self.all_labels == human_label) [ self.wrong_trunc.append(i) for i in idx_human[0] if self.all_max_preds[i] == model_label ] cat1 = list(label_list.keys())[list(label_list.values()).index(human_label)] cat2 = list(label_list.keys())[list(label_list.values()).index(model_label)] print(f"{len(self.wrong_trunc)} wrong predictions between {cat1} and {cat2}") def find_wrong_indices(self): """ """ self.wrong_idx = [ index for index, elem in enumerate(self.all_max_preds) if elem != self.all_labels[index] ] # and # labels[index]==actual and elem == model_label] @auto_str class BatchPredictions(LoaderPredictions): """finds predictions for a given batch of test data (no label)""" def __init__( self, imgs, paths, model, labels=None, ): super().__init__() self.imgs = imgs.to(config.DEVICE) self.paths = paths self.model = model.to(config.DEVICE) self.labels = labels self.max_preds = None self.probs = None self.classes = None def find_logits(self): return self.model(self.imgs) def find_max_preds(self): """find the class with the highest probability across all images in the batch""" _, max_preds = torch.max(self.find_logits(), dim=1) # convert back to lists from being on gpus self.max_preds = max_preds.cpu().tolist() def preds_softmax(self): return F.softmax(self.find_logits(), dim=1) def top_k_preds(self, top_k_preds=9): '''get top k predictions for each index in the batch for bar chart''' topk = self.preds_softmax().cpu().topk(top_k_preds) self.probs, self.classes = [e.data.numpy().squeeze().tolist() for e in topk] def append_preds(self): """create a list of paths, top k predicted probabilities/classes and the class with the highest probability across batches. Stored in LoaderPredictions.""" self.all_paths.append(self.paths) self.all_topk_probs.append(self.probs) self.all_topk_classes.append(self.classes) self.all_max_preds.append(self.max_preds) self.all_labels.append(self.labels)
4,262
py_integration.py
RLuR/py-integration
1
2023531
import argparse import random import numpy as np import math MONTE_CARLO = 0 RIEMANN = 1 random.seed(1) def integrate_string(functionstring, lower_boundry, upper_boundry, method=1, iterations=10000): function = _parse_Function(functionstring) if method == 0: return monte_carlo_integrate(function, lower_boundry, upper_boundry, iterations) if method == 1: return riemann_integrate(function, lower_boundry, upper_boundry, iterations) def riemann_integrate(function, lower_boundry, upper_boundry, iterations=10000): step_size = (upper_boundry - lower_boundry)/iterations steps = np.arange(lower_boundry, upper_boundry, step_size) function_array = np.vectorize(function) results = function_array(steps) return np.mean(results) * (upper_boundry - lower_boundry) def monte_carlo_integrate(function, lower_boundry, upper_boundry, iterations=10000, min_height = None, max_height= None): if min_height is None or max_height is None: min_height, max_height = _generate_y_boundries(function, lower_boundry, upper_boundry, iterations) results = 0 for step in range(1, iterations): random_point = _generate_random_point(lower_boundry, upper_boundry, min_height, max_height) stepresult = _monte_Carlostep(function, random_point) if stepresult: results += 1 minresult = (upper_boundry - lower_boundry) * (min_height) return minresult + (upper_boundry - lower_boundry) * (max_height - min_height) * results / iterations def _generate_random_point(lower_boundry, upper_boundry, min_height, max_height): return [random.uniform(lower_boundry,upper_boundry), random.uniform(min_height, max_height)] def _parse_Function(expression): funcstr= '''\ def f(x): return {e}'''.format(e=expression) exec(funcstr, globals()) return f def _generate_y_boundries(function, lower_x_boundry, upper_x_boundry, iterations=1000): step_size = (upper_x_boundry - lower_x_boundry) / iterations steps = np.arange(lower_x_boundry, upper_x_boundry, step_size) function_array = np.vectorize(function) results = function_array(steps) return np.min(results), np.max(results) def _monte_Carlostep(function, point): if point[1] < function(point[0]): return True else: return False if __name__ == '__main__': argumentparser = argparse.ArgumentParser() argumentparser.add_argument("function", type=str) argumentparser.add_argument("lower_boundry", type=float) argumentparser.add_argument("upper_boundry", type=float) argumentparser.add_argument('-i', help='number of iterations (10000 default)', type=int, default=10000) argumentparser.add_argument("-m", type=int, choices=[0, 1, 2], default=2, help="which approximation method used: 0 = Monte Carlo, 1 = Riemann sum, 2 = both (default)") args=argumentparser.parse_args() iterations = 10000 if args.m in [0,2]: print(f"Monte Carlo approximation: {integrate_string(args.function, args.lower_boundry, args.upper_boundry, MONTE_CARLO, args.i)}") if args.m in [1,2]: print(f"Riemann approximation: {integrate_string(args.function, args.lower_boundry, args.upper_boundry, RIEMANN, args.i)}")
3,261
openDAM/plot/plot_bids.py
bcornelusse/openDAM
15
2024513
from datetime import datetime, timedelta import matplotlib.pyplot as plt import os plt.style.use('bmh') FONT_SIZE = 9 class BidPlotter: def __init__(self, dam, path, case): self.dam = dam self.case_ = case self.plots_folder = "%s/plots_%s_%s" % ( path, case, datetime.now().strftime('%Y%m%d_%H%M%S')) if not os.path.isdir(self.plots_folder): os.mkdir(self.plots_folder) def plot(self, locations=None): if locations is None: locations = self.dam.zones.keys() n_subplots = len(locations) fig = plt.figure(1, figsize=(8, 5 * n_subplots)) curves = self.dam.curves pun_orders = self.dam.punOrders l = 1 for location in locations: ax1 = plt.subplot(n_subplots, 1, l) # plot PUN pun_curve = [] last_volume = 0.0 for po in pun_orders: if po.location == location: pun_curve.append((last_volume, po.price)) pun_curve.append((last_volume + po.volume, po.price)) last_volume += po.volume pun_curve.append((last_volume, 0.0)) ax1.plot([x[0] for x in pun_curve], [x[1] for x in pun_curve], label="PUN curve") maxPrice = pun_curve[0][1] # Plot supply supply_curve_points = [] last_volume = 0.0 for curve in curves: if curve.location == location: for bid in curve.bids: if bid.volume > 0: # Supply supply_curve_points.append((last_volume, bid.price)) supply_curve_points.append((last_volume + bid.volume, bid.price)) last_volume += bid.volume if supply_curve_points: maxPrice = max(maxPrice, supply_curve_points[-1][1]) supply_curve_points.append((last_volume, maxPrice)) ax1.plot([x[0] for x in supply_curve_points], [x[1] for x in supply_curve_points], label="Supply") # Plot demand demand_curve_points = [] last_volume = 0.0 for curve in curves: if curve.location == location: for bid in curve.bids: if bid.volume < 0: # Demand demand_curve_points.append((last_volume, bid.price)) last_volume -= bid.volume demand_curve_points.append((last_volume, bid.price)) if demand_curve_points: demand_curve_points.append((last_volume, 0)) ax1.plot([x[0] for x in demand_curve_points], [x[1] for x in demand_curve_points], label="Demand") ax1.legend(fontsize=FONT_SIZE) ax1.set_xlabel('MWh', fontsize=FONT_SIZE) ax1.set_ylabel('EUR/MWh', fontsize=FONT_SIZE) ax1.set_title("Zone %d" % l) l += 1 fig.savefig("%s/bids.pdf" % self.plots_folder)
3,145
src/tenants/migrations/0001_initial.py
litedesk/litedesk-webserver-provision
1
2023410
# -*- coding: utf-8 -*- from __future__ import unicode_literals from django.db import models, migrations import django.utils.timezone from django.conf import settings import model_utils.fields class Migration(migrations.Migration): dependencies = [ migrations.swappable_dependency(settings.AUTH_USER_MODEL), ('contenttypes', '0001_initial'), ] operations = [ migrations.CreateModel( name='ActiveDirectory', fields=[ ('id', models.AutoField(verbose_name='ID', serialize=False, auto_created=True, primary_key=True)), ('url', models.CharField(max_length=300)), ('domain', models.CharField(max_length=200)), ('ou', models.CharField(max_length=200)), ('username', models.CharField(max_length=80)), ('password', models.CharField(max_length=1000)), ], options={ }, bases=(models.Model,), ), migrations.CreateModel( name='Tenant', fields=[ ('id', models.AutoField(verbose_name='ID', serialize=False, auto_created=True, primary_key=True)), ('created', model_utils.fields.AutoCreatedField(default=django.utils.timezone.now, verbose_name='created', editable=False)), ('modified', model_utils.fields.AutoLastModifiedField(default=django.utils.timezone.now, verbose_name='modified', editable=False)), ('name', models.CharField(unique=True, max_length=1000, db_index=True)), ('active', models.BooleanField(default=True)), ('email_domain', models.CharField(default=b'onmicrosoft.com', max_length=300)), ('active_directory', models.OneToOneField(null=True, blank=True, to='tenants.ActiveDirectory')), ], options={ 'abstract': False, }, bases=(models.Model,), ), migrations.CreateModel( name='TenantItem', fields=[ ('id', models.AutoField(verbose_name='ID', serialize=False, auto_created=True, primary_key=True)), ('object_id', models.PositiveIntegerField()), ('content_type', models.ForeignKey(to='contenttypes.ContentType')), ('tenant', models.ForeignKey(to='tenants.Tenant')), ], options={ }, bases=(models.Model,), ), migrations.CreateModel( name='TenantService', fields=[ ('id', models.AutoField(verbose_name='ID', serialize=False, auto_created=True, primary_key=True)), ('is_active', models.BooleanField(default=True)), ('api_token', models.CharField(max_length=128)), ('tenant', models.ForeignKey(to='tenants.Tenant')), ], options={ }, bases=(models.Model,), ), migrations.CreateModel( name='User', fields=[ ('id', models.AutoField(verbose_name='ID', serialize=False, auto_created=True, primary_key=True)), ('created', model_utils.fields.AutoCreatedField(default=django.utils.timezone.now, verbose_name='created', editable=False)), ('modified', model_utils.fields.AutoLastModifiedField(default=django.utils.timezone.now, verbose_name='modified', editable=False)), ('last_remote_read', models.DateTimeField(null=True, editable=False)), ('last_remote_save', models.DateTimeField(null=True, editable=False)), ('last_modified', models.DateTimeField(auto_now=True)), ('first_name', models.CharField(max_length=100, null=True)), ('last_name', models.CharField(max_length=100, null=True)), ('display_name', models.CharField(max_length=200, null=True)), ('mobile_phone_number', models.CharField(max_length=16, null=True, blank=True)), ('username', models.CharField(max_length=100, editable=False)), ('email', models.EmailField(max_length=75, null=True)), ('status', model_utils.fields.StatusField(default=b'staged', max_length=100, no_check_for_status=True, choices=[(b'staged', b'staged'), (b'pending', b'pending'), (b'active', b'active'), (b'suspended', b'suspended'), (b'disabled', b'disabled')])), ('services', models.ManyToManyField(to='tenants.TenantService')), ('tenant', models.ForeignKey(to='tenants.Tenant')), ], options={ }, bases=(models.Model,), ), migrations.CreateModel( name='UserGroup', fields=[ ('id', models.AutoField(verbose_name='ID', serialize=False, auto_created=True, primary_key=True)), ('name', models.CharField(max_length=80)), ('members', models.ManyToManyField(to='tenants.User', blank=True)), ('tenant', models.ForeignKey(to='tenants.Tenant')), ], options={ }, bases=(models.Model,), ), migrations.AlterUniqueTogether( name='usergroup', unique_together=set([('name', 'tenant')]), ), migrations.AlterUniqueTogether( name='user', unique_together=set([('tenant', 'username')]), ), migrations.AddField( model_name='tenant', name='members', field=models.ManyToManyField(related_name='peers', to=settings.AUTH_USER_MODEL, blank=True), preserve_default=True, ), migrations.AddField( model_name='tenant', name='primary_contact', field=models.OneToOneField(related_name='tenant', to=settings.AUTH_USER_MODEL), preserve_default=True, ), ]
5,970
uri.py
Kondziowy/PythonBasicTraining
1
2023471
import requests HTTP = "http" FILE = "file" class UriHandler: def __init__(self, uri): self.protocol = uri.split(":")[0].lower() self.resource = uri.split("/")[2] self.uri = uri print("URI handler initialized") def get(self): raise NotImplementedError() def get_contents(self): if self.protocol == HTTP: return HttpHandler(self.uri).get() if self.protocol == FILE: return FileHandler(self.uri).get() def __eq__(self, right): return super(UriHandler, self).__eq__(right) class HttpHandler(UriHandler): def __init__(self, uri): super(HttpHandler, self).__init__(uri) print("HTTP handler initialized") def get(self): return requests.get(self.uri).text class FileHandler(UriHandler): pass print(UriHandler("http://wp.pl").get_contents()) print(50 * "=") print(HttpHandler("http://wp.pl") == HttpHandler("http://wp.pl"))
998
main.py
jamesnoria/el_comercio_scraper
2
2022745
import pandas as pd from comercio_scraper import Scraper from options import UserOptions from helpers import Helper import os import json class ElComercio: """ Un scraper de las paginas del diario peruano El Comercio. Se extrae el titulo, breve descripción y el enlace de referencia. """ def __init__(self, main_url, news_number): self.main_url = main_url self.news_number = news_number def export(self, output): """ Funcion que exporta datos en diferentes formatos, format_option: 1: CSV , 2:JSON. """ if output == 1: self._export_to_csv() elif output == 2: self._export_to_json() def _export_to_csv(self): """ Haciendo el data-frame y exportandolo a un archivo .csv """ news = Scraper(self.main_url, self.news_number) news_scraper = pd.DataFrame({ 'TITULAR': news.header_scraper(), 'DESCRIPCIÓN': news.description_scraper(), 'LINKS': news.link_scraper() }) news_scraper.to_csv(f"./csv_files/{Helper.filename_generator(1)}") def _export_to_json(self): """ Haciendo el json y exportandolo a un archivo .json: """ news = Scraper(self.main_url, self.news_number) keys = ['title', 'description', 'link'] news_array = [{keys[n]: value for n, value in enumerate(new)} for new in zip( news.header_scraper(), news.description_scraper(), news.link_scraper())] json_object = json.dumps(news_array, indent=4) filename = f"./json_files/{Helper.filename_generator(2)}" if os.path.exists(filename): os.remove(filename) with open(filename, 'x') as output_file: output_file.write(json_object) if __name__ == "__main__": name = UserOptions(input('¿Cual es tu nombre: ')) name.greeting() try: p_number = int( input('¿Cuantas noticias deseas investigar? (max. 50): ')) if p_number > 50 or p_number < 0: raise ValueError( 'Por favor inserte un número de página valido (valor entero)') output = int(input( '¿En que formato quieres recibir las noticias?\n1. CSV\n2. JSON\n\nEleccion: ')) if output < 1 or output > 2: raise ValueError( 'Por favor inserte un número de opción valido (1 o 2)') elcomercio = ElComercio('https://elcomercio.pe/noticias/coronavirus/', p_number) elcomercio.export(output) name.progress_bar() print( f'¡LISTO!, puedes revisar el archivo: "{Helper.filename_generator(output)}" dentro de la carpeta: "{Helper.folder_generator(output)}"') except ValueError as ex: print(ex)
2,770
ext/opentelemetry-ext-system-metrics/src/opentelemetry/ext/system_metrics/__init__.py
cnnradams/opentelemetry-python
2
2023108
# Copyright The OpenTelemetry Authors # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. """ Instrument to report system (CPU, memory, network) and process (CPU, memory, garbage collection) metrics. By default, the following metrics are configured: "system_memory": ["total", "available", "used", "free"], "system_cpu": ["user", "system", "idle"], "network_bytes": ["bytes_recv", "bytes_sent"], "runtime_memory": ["rss", "vms"], "runtime_cpu": ["user", "system"], Usage ----- .. code:: python from opentelemetry import metrics from opentelemetry.ext.system_metrics import SystemMetrics from opentelemetry.sdk.metrics import MeterProvider, from opentelemetry.sdk.metrics.export import ConsoleMetricsExporter metrics.set_meter_provider(MeterProvider()) exporter = ConsoleMetricsExporter() SystemMetrics(exporter) # metrics are collected asynchronously input("...") # to configure custom metrics configuration = { "system_memory": ["total", "available", "used", "free", "active", "inactive", "wired"], "system_cpu": ["user", "nice", "system", "idle"], "network_bytes": ["bytes_recv", "bytes_sent"], "runtime_memory": ["rss", "vms"], "runtime_cpu": ["user", "system"], } SystemMetrics(exporter, config=configuration) API --- """ import gc import os import typing import psutil from opentelemetry import metrics from opentelemetry.sdk.metrics import ValueObserver from opentelemetry.sdk.metrics.export import MetricsExporter from opentelemetry.sdk.metrics.export.controller import PushController class SystemMetrics: def __init__( self, exporter: MetricsExporter, interval: int = 30, labels: typing.Optional[typing.Dict[str, str]] = None, config: typing.Optional[typing.Dict[str, typing.List[str]]] = None, ): self._labels = {} if labels is None else labels self.meter = metrics.get_meter(__name__) self.controller = PushController( meter=self.meter, exporter=exporter, interval=interval ) if config is None: self._config = { "system_memory": ["total", "available", "used", "free"], "system_cpu": ["user", "system", "idle"], "network_bytes": ["bytes_recv", "bytes_sent"], "runtime_memory": ["rss", "vms"], "runtime_cpu": ["user", "system"], } else: self._config = config self._proc = psutil.Process(os.getpid()) self._system_memory_labels = {} self._system_cpu_labels = {} self._network_bytes_labels = {} self._runtime_memory_labels = {} self._runtime_cpu_labels = {} self._runtime_gc_labels = {} # create the label set for each observer once for key, value in self._labels.items(): self._system_memory_labels[key] = value self._system_cpu_labels[key] = value self._network_bytes_labels[key] = value self._runtime_memory_labels[key] = value self._runtime_gc_labels[key] = value self.meter.register_observer( callback=self._get_system_memory, name="system.mem", description="System memory", unit="bytes", value_type=int, observer_type=ValueObserver, ) self.meter.register_observer( callback=self._get_system_cpu, name="system.cpu", description="System CPU", unit="seconds", value_type=float, observer_type=ValueObserver, ) self.meter.register_observer( callback=self._get_network_bytes, name="system.net.bytes", description="System network bytes", unit="bytes", value_type=int, observer_type=ValueObserver, ) self.meter.register_observer( callback=self._get_runtime_memory, name="runtime.python.mem", description="Runtime memory", unit="bytes", value_type=int, observer_type=ValueObserver, ) self.meter.register_observer( callback=self._get_runtime_cpu, name="runtime.python.cpu", description="Runtime CPU", unit="seconds", value_type=float, observer_type=ValueObserver, ) self.meter.register_observer( callback=self._get_runtime_gc_count, name="runtime.python.gc.count", description="Runtime: gc objects", unit="objects", value_type=int, observer_type=ValueObserver, ) def _get_system_memory(self, observer: metrics.ValueObserver) -> None: """Observer callback for memory available Args: observer: the observer to update """ system_memory = psutil.virtual_memory() for metric in self._config["system_memory"]: self._system_memory_labels["type"] = metric observer.observe( getattr(system_memory, metric), self._system_memory_labels ) def _get_system_cpu(self, observer: metrics.ValueObserver) -> None: """Observer callback for system cpu Args: observer: the observer to update """ cpu_times = psutil.cpu_times() for _type in self._config["system_cpu"]: self._system_cpu_labels["type"] = _type observer.observe( getattr(cpu_times, _type), self._system_cpu_labels ) def _get_network_bytes(self, observer: metrics.ValueObserver) -> None: """Observer callback for network bytes Args: observer: the observer to update """ net_io = psutil.net_io_counters() for _type in self._config["network_bytes"]: self._network_bytes_labels["type"] = _type observer.observe( getattr(net_io, _type), self._network_bytes_labels ) def _get_runtime_memory(self, observer: metrics.ValueObserver) -> None: """Observer callback for runtime memory Args: observer: the observer to update """ proc_memory = self._proc.memory_info() for _type in self._config["runtime_memory"]: self._runtime_memory_labels["type"] = _type observer.observe( getattr(proc_memory, _type), self._runtime_memory_labels ) def _get_runtime_cpu(self, observer: metrics.ValueObserver) -> None: """Observer callback for runtime CPU Args: observer: the observer to update """ proc_cpu = self._proc.cpu_times() for _type in self._config["runtime_cpu"]: self._runtime_cpu_labels["type"] = _type observer.observe( getattr(proc_cpu, _type), self._runtime_cpu_labels ) def _get_runtime_gc_count(self, observer: metrics.ValueObserver) -> None: """Observer callback for garbage collection Args: observer: the observer to update """ gc_count = gc.get_count() for index, count in enumerate(gc_count): self._runtime_gc_labels["count"] = str(index) observer.observe(count, self._runtime_gc_labels)
7,946
10-advanced-python-dev/1-args-kargs-expm.py
saidulislam/Python-Experiment
0
2022698
def mul(*args): print("args[0] : ", args[0]) print("args[1] : ", args[1]) return (args[0]*args[1]) num = mul(3, 9, 7) print(num) def multigreet(*args): for item in args: print(f"Hello {item}!") multigreet("John", "Conner", "Ryan", "Tim") print("\n\n") # *args has to be the last argument def multigreet2(msg, *args): for item in args: print(f"{msg} {item}!") multigreet2("Hey", "John", "Conner", "Ryan", "Tim") def print_family_info(**kwargs): family = {} for key, value in kwargs.items(): family[key] = value print(family) print("\n\n") print_family_info(mom="Jane", dad="John", child1="Rick", child2="Ellie") print("\n\n") # more use of *args def print_movie(*args): for value in args: print(value) movie = { "title": "The Matrix", "director": "Wachowski", "year": 1999 } print_movie(*movie.values()) print("\n\n") # more use of **kwargs def print_movie(**kwargs): for key, value in kwargs.items(): print(f"{key}: {value}") movie = { "title": "The Matrix", "director": "Wachowski", "year": 1999 } print_movie(**movie) print("\n\n") # **kwargs can give us more flexibility # when it comes to collecting unassigned keyword arguments, # and not only those coming from a dictionary. # For example, we could do this: def print_movie(**kwargs): for key, value in kwargs.items(): print(f"{key}: {value}") movie = { "title": "The Matrix", "director": "Wachowski", "year": 1999 } print_movie(studio="<NAME>", **movie) print("\n\n") # There are plenty more uses for a technique like this, including merging dictionaries, # and saving us a lot of typing when using format # for example, instead of the following def show_books(books): # Adds an empty line before the output print() for book in books: print(f"{book['title']}, by {book['author']} ({book['year']})") print() # you can do something like the following def show_books(books): # Adds an empty line before the output print() for book in books: print("{title}, by {author} ({year})".format(**book)) print() # One of the nice things about this approach is that # we can define the template elsewhere, which also means # we can refer to it in multiple places in our code. book_template = "{title}, by {author} ({year})" def show_books(books): # Adds an empty line before the output print() for book in books: print(book_template.format(**book)) print()
2,575
fibonacci/trampolinely.py
csuriano23/pycombinator
0
2024565
from __future__ import absolute_import from structure.trampoline import Trampoline class Fibonacci(Trampoline): def __init__(self, create_fn, original, current, prev2, prev1): self.create_fn = create_fn self.original = original self.current = current self.prev1 = prev1 self.prev2 = prev2 def value(self): return self.prev2 + self.prev1 def next(self): return self.create_fn(self.original, self.current + 1, self.prev1, self.value()) def calculate(value): def _inner(n, current, fibt2, fibt1): if current == n or n < 2: return Fibonacci(lambda *args: None, n, current, fibt2, fibt1) return Fibonacci(_inner, n, current, fibt2, fibt1) return _inner(value, 2, 0, 1 if value else 0).compute()
803
Oxenfree/oxenfree_binary_unpack_resources.py
Lenferd/TranslationTools
1
2024735
#!/usr/bin/python3 # -*- coding: utf-8 -*- # Программа: OxenfreeUnpacker # Назначение: Вытаскиваем текст из файлов # Версия: 3.1 # Дата: 8.04.17 # Модифик: 21.04.17 # Автор: Lenferd (<EMAIL>) import os import sys sys.path.insert(0, os.path.pardir) from Modules.BinaryParser import binary_parser as bparser from Modules.FilesOperation import find as ffind from Modules.FilesOperation import readFile as freader from Modules.FilesOperation import writeFile as fwriter from Modules.TextOperations import text_filter # file_patch = "/mnt/sda3/TT/TT_OF4/Unity_Assets_Files/resources" # filepatch = "/mnt/sda3/TT/TT_OF4/test" dir_path = r"../Oxenfree_data/test2" dir_resources = r"../Oxenfree_data/test2/input_resources" # filepatch = "./examples" # out path prefix = "result_resources" # folder in the result postfix = "fileinfo" # underfolder in the prefix folder (for file info) if __name__ == "__main__": """ Block 0 """ if len(sys.argv) < 2: pass else: dir_path = sys.argv[1] dir_resources = sys.argv[1] + "/input_resources" """ Block 1 open & read На выходе получаем list из листов соответствующих поданных на вход файлов (file_list) + данные внутри преобразованы в UTF8 из бинарного вида """ # Construct list of files (full route) # TODO можно добавить возможность указывать маску, по которой будут искаться файлы (т.е. разрешение) file_list = ffind.construct_file_three(dir_resources) # get all file data binary_data = freader.read_binary_files(file_list) # get strings strings = bparser.parse_binary_list(binary_data) """ Block 2 Использование фильтра для отсеивания лишних строг (грубая обработка) Фильтр настраивается """ # now we can use filtres result, removed = text_filter.oxenfree_filter_resources(strings) """ Block 3 Упорядочивание массивов данных по типу файлов """ # ordering result, ordering_result = text_filter.ordering_by_filetype(result, file_list) removed, ordering_removed = text_filter.ordering_by_filetype(removed, file_list) fwriter.write_data_only_one_writted_type_sorted(result, ordering_result, "result_all", prefix=prefix, path=dir_path) fwriter.write_data_to_many_file_witch_sorting_ordering(result, ordering_result, "result", prefix=prefix, path=dir_path) fwriter.write_data_with_filename_wo_empty(removed, ordering_removed, "removed", prefix=prefix, path=dir_path) # print filetype fwriter.write_list(ffind.find_all_type(ordering_result), "filetype", prefix=prefix, postfix=postfix, path=dir_path) empty_files_list = ffind.find_empty_files(result, ordering_result) fwriter.write_list(empty_files_list, 'empty', prefix=prefix, postfix=postfix, path=dir_path)
3,027
src/main/python/geeksforgeeks/dp/path-in-matrix.py
sonymoon/algorithm
0
2023839
def pathInMatrix(result, matrix, i, j, m, n): if i >= 0 and j >= 0: result.append(matrix[i][j]) if 0 <= i - 1 < m and 0 <= j < n and matrix[i - 1][j] - matrix[i][j] == 1: pathInMatrix(result, matrix, i - 1, j, m, n) if 0 <= i < m and 0 <= j + 1 < n and matrix[i][j + 1] - matrix[i][j] == 1: pathInMatrix(result, matrix, i, j + 1, m, n) if 0 <= i + 1 < m and 0 <= j < n and matrix[i + 1][j] - matrix[i][j] == 1: pathInMatrix(result, matrix, i + 1, j, m, n) if 0 <= i - 1 < m and 0 <= j - 1 < n and matrix[i - 1][j - 1] - matrix[i][j] == 1: pathInMatrix(result, matrix, i - 1, j - 1, m, n) return result def main(matrix): m = len(matrix) if m == 0: return n = len(matrix[0]) result = [] for i in range(m): for j in range(n): result.append(pathInMatrix([], matrix, i, j, m, n)) max0 = 0 maxLength = 0 for x in range(len(result)): if len(result[x]) > maxLength: maxLength = len(result[x]) max0 = x if result: print(result[max0]) return len(result[max0]) return 0 matrix = [ [1, 2, 9], [5, 3, 8], [4, 6, 7] ] print main(matrix)
1,222
pylayers/measures/test/test_switch.py
usmanwardag/pylayers
143
2024789
import pylayers.measures.switch.ni_usb_6501 as sw import time switch = sw.get_adapter() #reattach=False if not switch: print("No device found") # #very important : to use at the beginning of the initialization of the switch #for each measurements, set up the NI USB 6501 mode : bit 1 means write and bit 0 read # switch.set_io_mode(0b11111111, 0b11111111, 0b00000000) # #SISO case # #example for use the switch 1 to 4 #switch 1 to 4 : port 1 is allowed #switch.write_port(1, 1) #select output 2 of the switch 1-4 #switch.write_port(1, 2) #select output 3 of the switch 1-4 #example for use the switch 1 to 8 #switch 1 to 8 : port 0 is allowed #for each measurements, set up the NI USB 6501 mode : bit 1 means write and bit 0 read #switch.set_io_mode(0b11111111, 0b11111111, 0b00000000) #switch.write_port(1, 1) #select output 2 of the switch 1-4 #switch.write_port(1, 2) #select output 3 of the switch 1-4 #switch.write_port(0, 4) #select channel 5 of the switch 1-8 #switch.write_port(0, 5) #select channel 6 of the switch 1-8 # #MIMO case # tic = time.time() for k in range(8): print " Transmiter : select output number ",k switch.write_port(0,k) for l in range(4): print "Receiver : select output number ",l switch.write_port(1,l) time.sleep(1) #time waiting of the switch between antennas toc = time.time() t = toc - tic print "Measurement time (s) with switching :",t # tic = time.time() # for k in range(8): # print " Transmiter side (ULA 8) : output selected ",k # switch.write_port(0,k) # for l in range(4): # print "Receiver side (ULA 4) : output selected ",l # switch.write_port(1,l) # time.sleep(1) #time waiting of the switch between antennas # toc = time.time() # t = toc - tic # print "time switch (s):",t
1,821
actions/ceph_ops.py
johnsca/charm-ceph-mon
0
2024050
# Copyright 2016 Canonical Ltd # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. from subprocess import CalledProcessError, check_output import sys sys.path.append('hooks') from charmhelpers.core.hookenv import action_get, action_fail from charmhelpers.contrib.storage.linux.ceph import pool_set, \ set_pool_quota, snapshot_pool, remove_pool_snapshot def list_pools(): """Return a list of all Ceph pools.""" try: pool_list = check_output(['ceph', 'osd', 'pool', 'ls']).decode('UTF-8') return pool_list except CalledProcessError as e: action_fail(str(e)) def get_health(): """ Returns the output of 'ceph health'. On error, 'unknown' is returned. """ try: value = check_output(['ceph', 'health']).decode('UTF-8') return value except CalledProcessError as e: action_fail(str(e)) return 'Getting health failed, health unknown' def pool_get(): """ Returns a key from a pool using 'ceph osd pool get'. The key is provided via the 'key' action parameter and the pool provided by the 'pool_name' parameter. These are used when running 'ceph osd pool get <pool_name> <key>', the result of which is returned. On failure, 'unknown' will be returned. """ key = action_get("key") pool_name = action_get("pool_name") try: value = (check_output(['ceph', 'osd', 'pool', 'get', pool_name, key]) .decode('UTF-8')) return value except CalledProcessError as e: action_fail(str(e)) return 'unknown' def set_pool(): """ Sets an arbitrary key key in a Ceph pool. Sets the key specified by the action parameter 'key' to the value specified in the action parameter 'value' for the pool specified by the action parameter 'pool_name' using the charmhelpers 'pool_set' function. """ key = action_get("key") value = action_get("value") pool_name = action_get("pool_name") pool_set(service='ceph', pool_name=pool_name, key=key, value=value) def pool_stats(): """ Returns statistics for a pool. The pool name is provided by the action parameter 'name'. """ try: pool_name = action_get("name") stats = ( check_output(['ceph', 'osd', 'pool', 'stats', pool_name]) .decode('UTF-8') ) return stats except CalledProcessError as e: action_fail(str(e)) def delete_pool_snapshot(): """ Delete a pool snapshot. Deletes a snapshot from the pool provided by the action parameter 'name', with the snapshot name provided by action parameter 'snapshot-name' """ pool_name = action_get("name") snapshot_name = action_get("snapshot-name") remove_pool_snapshot(service='ceph', pool_name=pool_name, snapshot_name=snapshot_name) # Note only one or the other can be set def set_pool_max_bytes(): """ Sets the max bytes quota for a pool. Sets the pool quota maximum bytes for the pool specified by the action parameter 'name' to the value specified by the action parameter 'max' """ pool_name = action_get("name") max_bytes = action_get("max") set_pool_quota(service='ceph', pool_name=pool_name, max_bytes=max_bytes) def snapshot_ceph_pool(): """ Snapshots a Ceph pool. Snapshots the pool provided in action parameter 'name' and uses the parameter provided in the action parameter 'snapshot-name' as the name for the snapshot. """ pool_name = action_get("name") snapshot_name = action_get("snapshot-name") snapshot_pool(service='ceph', pool_name=pool_name, snapshot_name=snapshot_name)
4,311
tests/unit/opera/parser/tosca/v_1_3/test_event_filter_definition.py
abitrolly/xopera-opera
31
2023768
from opera.parser.tosca.v_1_3.event_filter_definition import EventFilterDefinition class TestParse: def test_full(self, yaml_ast): EventFilterDefinition.parse(yaml_ast( # language=yaml """ node: node_type_name requirement: requirement_name capability: capability_name """ )) def test_minimal(self, yaml_ast): EventFilterDefinition.parse(yaml_ast( # language=yaml """ node: node_template_name """ ))
562
WebMirror/OutputFilters/ScribbleHub/SHSeriesUpdateFilter.py
fake-name/ReadableWebProxy
193
2022730
import re import WebRequest import common.util.urlFuncs import WebMirror.OutputFilters.FilterBase class SHSeriesUpdateFilter(WebMirror.OutputFilters.FilterBase.FilterBase): wanted_mimetypes = [ 'text/html', ] want_priority = 50 loggerPath = "Main.Filter.ScribbleHub.Series" match_re = re.compile(r"^^https://www\.scribblehub\.com/(?:series-ranking|latest-series)/.*$", flags=re.IGNORECASE) @classmethod def wantsUrl(cls, url): if cls.match_re.search(url): print("SHSeriesUpdateFilter Wants url: '%s'" % url) return True # else: print("SHSeriesUpdateFilter doesn't want url: '%s'" % url) return False def __init__(self, **kwargs): self.kwargs = kwargs self.pageUrl = kwargs['pageUrl'] self.content = kwargs['pgContent'] self.type = kwargs['type'] self.db_sess = kwargs['db_sess'] self.log.info("Processing ScribbleHub SeriesUpdate Item") super().__init__(**kwargs) ################################################################################################################################## ################################################################################################################################## ################################################################################################################################## def extractSeriesReleases(self, seriesPageUrl, soup): containers = soup.find_all('div', class_='search_main_box') # print(soup) # print("container: ", containers) if not containers: return [] urls = [] for item in containers: div = item.find('div', class_='search_title') a = div.find("a") if a: url = common.util.urlFuncs.rebaseUrl(url=a['href'], base=seriesPageUrl) urls.append(url) else: self.log.error("No series in container: %s", item) return set(urls) def retrigger_pages(self, releases): self.log.info("Total releases found on page: %s. Forcing retrigger of item pages.", len(releases)) for release_url in releases: self.retrigger_page(release_url) def processPage(self, url, content): print("processPage() call") soup = WebRequest.as_soup(self.content) releases = self.extractSeriesReleases(self.pageUrl, soup) if releases: self.retrigger_pages(releases) ################################################################################################################################## ################################################################################################################################## ################################################################################################################################## def extractContent(self): # print("Call to extract!") # print(self.amqpint) self.processPage(self.pageUrl, self.content) def test(): print("Test mode!") import logSetup from WebMirror.Engine import SiteArchiver import common.database as db logSetup.initLogging() def fetch(url): with db.session_context() as sess: archiver = SiteArchiver( cookie_lock = None, db_interface = sess, new_job_queue = None ) archiver.synchronousJobRequest(url, ignore_cache=True, debug=True) # engine.dispatchRequest(testJobFromUrl('http://www.ScribbleHub.com/fiction/3021')) # engine.dispatchRequest(testJobFromUrl('http://www.ScribbleHub.com/fictions/latest-updates/')) # engine.dispatchRequest(testJobFromUrl('http://www.ScribbleHub.com/fictions/best-rated/')) # fetch('https://www.scribblehub.com/series-ranking/') fetch('https://www.scribblehub.com/series-ranking/?sort=3&order=1') # fetch('https://www.scribblehub.com/latest-series/') if __name__ == "__main__": test()
3,708
crawler/alice crawler.py
xiepeiheng/xiepeiheng
0
2024188
import urllib.request from bs4 import BeautifulSoup import re result = urllib.request.urlopen('http://1172.16.58.3:5000/alice') html = result.read().decode('utf-8') soup = BeautifulSoup(html, 'html.parser') print(soup)
220
desktop_simple/ebuilds/v1.12.0-noetic/libqicore-1.12.0-noetic/xarconverter/converter/node/bitmap_v2.py
Maelic/ros_overlay_on_gentoo_prefix_32b
0
2023370
#!/usr/bin/env python ## Copyright (c) 2012 Aldebaran Robotics. All rights reserved. ## Use of this source code is governed by a BSD-style license that can be ## found in the COPYING file. """ Contains a class that holds diagram informations .. module:: node """ import converter.node as node class BitmapV2(node.Node): """ Stores informations about bitmap in the box interface format """ def __init__(self, attrs): super(BitmapV2, self).__init__("BitmapV2") # Elements self.path = attrs.getValue("path") def beacon(self): return "Bitmap"
595
src/django/pfb_analysis/management/commands/analysis_batch_cancel.py
PeopleForBikes/pfb-network-connectivity
35
2023602
from django.core.management.base import BaseCommand from pfb_analysis.models import AnalysisBatch class Command(BaseCommand): help = """ Cancel all jobs in an AnalysisBatch """ def add_arguments(self, parser): parser.add_argument('batch_uuid', type=str) def handle(self, *args, **options): batch_uuid = options['batch_uuid'] batch = AnalysisBatch.objects.get(uuid=batch_uuid) self.stdout.write('Cancelling {}'.format(batch)) batch.cancel()
498
morphine/unigram_model.py
kmike/morphine
11
2024124
# -*- coding: utf-8 -*- from __future__ import absolute_import from pymorphy2 import MorphAnalyzer from pymorphy2.tokenizers import simple_word_tokenize class Tagger(object): def __init__(self, morph=None): if morph is None: morph = MorphAnalyzer() self.morph = morph def predict(self, tokens): if not isinstance(tokens, (list, tuple)): tokens = simple_word_tokenize(tokens) return [self.morph.parse(token)[0] for token in tokens]
498
scripts/price_feed_scripts/deploy_price_consumer_v3.py
coozebra/chainlink-mix
9
2023068
#!/usr/bin/python3 import os from brownie import PriceFeed, accounts, network, config # mainnet_eth_usd_address = '0x5f4eC3Df9cbd43714FE2740f5E3616155c5b8419' # kovan_eth_usd_address = '0x9326BFA02ADD2366b30bacB125260Af641031331' def main(): if network.show_active() in ['mainnet-fork', 'binance-fork', 'matic-fork']: price_feed = PriceFeed.deploy(config['networks'][network.show_active( )]['eth_usd_price_feed'], {'from': accounts[0]}) print("The current price of ETH is " + str(price_feed.getLatestPrice({'from': accounts[0]}))) return price_feed elif network.show_active() in ['kovan', 'rinkeby', 'mainnet']: dev = accounts.add(os.getenv(config['wallets']['from_key'])) return PriceFeed.deploy(config['networks'][network.show_active()]['eth_usd_price_feed'], {'from': dev}) else: print('Please pick a supported network, or fork a chain')
926
src/marshmallow3_annotations/_compat.py
dkunitsk/marshmallow3-annotations
48
2024132
import sys IS_PY36 = sys.version_info[:2] == (3, 6) if IS_PY36: def _is_class_var(typehint): from typing import _ClassVar # type: ignore try: return isinstance(typehint, _ClassVar) except TypeError: # pragma: no branch return False def _get_base(typehint): return typehint.__base__ else: def _is_class_var(typehint): # follow the lead of stdlib's dataclass implementation from typing import ClassVar, _GenericAlias # type: ignore return typehint is ClassVar or ( type(typehint) is _GenericAlias and typehint.__origin__ is ClassVar ) def _get_base(typehint): return typehint.__origin__
722
main.py
c3systems/sdk-python-example-eyescream
3
2024229
from lib.c3_sdk_python_0_0_2 import sdk from lib.eyescream.dataset import generate_dataset as gd from PIL import Image import io import os import subprocess c3 = None PillowImageRequired = Exception("pillow image is required") InvalidImage = Exception("invalid image") C3Required = Exception("c3 cannot be None") TrainingFailed = Exception("model training failed") SubprocessFailed = Exception("subprocess failed") standardImgFormat = "JPEG" tmpDir = "tmp" libDir = "lib" inputRelPath = tmpDir + os.path.sep + "input" augRelPath = tmpDir + os.path.sep + "aug_64x64" unaugRelPath = tmpDir + os.path.sep + "unaug_64x64" networkRelPath = tmpDir + os.path.sep + "network" scriptFileRelPath = libDir + os.path.sep + "eyescream" + os.path.sep + "train.lua" inputAbsPath = os.path.dirname(os.path.abspath(__file__)) + os.path.sep + inputRelPath augAbsPath = os.path.dirname(os.path.abspath(__file__)) + os.path.sep + augRelPath unaugAbsPath = os.path.dirname(os.path.abspath(__file__)) + os.path.sep + unaugRelPath networkAbsPath = os.path.dirname(os.path.abspath(__file__)) + os.path.sep + networkRelPath oldNetworkAbsPath = networkAbsPath + os.path.sep + "old.net" newNetworkAbsPath = networkAbsPath + os.path.sep + "adversarial.net" scriptFileAbsPath = os.path.dirname(os.path.abspath(__file__)) + os.path.sep + scriptFileRelPath augImagesKey = "aug_images" networkKey = "network" def main(): global c3 c3 = sdk.NewC3() c3.registerMethod("acceptImage", acceptImage) initState() c3.serve() def initState(): global c3 if c3 == None: print("c3 is none") raise C3Required if not os.path.exists(inputAbsPath): os.makedirs(inputAbsPath) if not os.path.exists(augAbsPath): os.makedirs(augAbsPath) if not os.path.exists(unaugAbsPath): os.makedirs(unaugAbsPath) if not os.path.exists(networkAbsPath): os.makedirs(networkAbsPath) if augImagesKey in c3.state: for idx in range(len(c3.state[augImagesKey])): b = c3.state[augImagesKey][idx] im = imageFromBytes(b) im.save(augAbsPath + os.path.sep + idx + standardImgFormat) network = bytearray() if networkKey in c3.state: network = c3.state[networkKey] writeBytesToFile(network, oldNetworkAbsPath) def writeBytesToFile(b, fileName): with open(fileName, 'wb+') as f: f.write(b) f.close() # http://www.codecodex.com/wiki/Read_a_file_into_a_byte_array#Python def readBytesFromFile(filename): with open(filename, "rb+") as file: return file.read() def imageFromBytes(b): im = Image.open(b) return im def imageToBytes(name, ext, img): b = io.BytesIO() img.save(b, format=ext) b.name = name + "." + ext b.seek(0) return b def acceptImage(img): if img == None: print("pillow image is required") raise PillowImageRequired imgCP = img.copy() try: imgCP.verify() except Exception as err: print("invalid img", err) raise InvalidImage img.save(inputAbsPath + os.path.sep + "input.jpg", format=standardImgFormat) # augment the input image and save it to disk gd.gen(inputAbsPath, augAbsPath, unaugAbsPath) # run an epoch of the model and save the weights # note: it's not ideal to run an epoch after each image is added \ # but this code is for example purposes, only... result = None try: cmd = ["th", scriptFileAbsPath] if os.stat(oldNetworkAbsPath).st_size != 0: cmd.extend(["--network", oldNetworkAbsPath]) cmd.extend(["--save", networkAbsPath, "--dataDir", augAbsPath]) result = subprocess.run(cmd) except Exception as err: print("subprocess errored", err) raise SubprocessFailed if result.returncode != 0: print("Preprocess failed: ", result.stderr, result) raise TrainingFailed gatherState() def gatherState(): global c3 if not networkKey in c3.state: c3.state[networkKey] = bytearray() with open(newNetworkAbsPath, "rb+") as file: c3.state[networkKey] = file.read() c3.state[augImagesKey] = [] # r=root, d=directories, f=files for r, d, f in os.walk(augAbsPath): for file in f: if "." + standardImgFormat in file: c3.state[augImagesKey].append(readBytesFromFile(os.path.join(r, file))) if __name__ == "__main__": main()
4,458
tests/test_config_toolkit.py
FlexiGroBots-H2020/datacube-ows
4
2024481
# This file is part of datacube-ows, part of the Open Data Cube project. # See https://opendatacube.org for more information. # # Copyright (c) 2017-2021 OWS Contributors # SPDX-License-Identifier: Apache-2.0 from datacube_ows.config_toolkit import deepinherit def test_deepinherit_shallow(): parent = { "a": 72, "b": "eagle", "c": False } child = { "a": 365 } child = deepinherit(parent, child) assert child['a'] == 365 assert child["b"] == "eagle" assert not child["c"] def test_deepinherit_deep(): parent = { "a": 72, "b": { "fruit": "grapes", "spice": "cummin", "cake": "chocolate", "y": ["some", "body", "once"], "z": [44, 42, 53], "c": { "foo": "bar", "wing": "wang" } } } child = { "b": { "spice": "nutmeg", "c": { "wing": "chicken" }, "y": ["told", "me"], "z": [11] } } child = deepinherit(parent, child) assert child["a"] == 72 assert child["b"]["spice"] == "nutmeg" assert child["b"]["fruit"] == "grapes" assert child["b"]["c"]["foo"] == "bar" assert child["b"]["c"]["wing"] == "chicken" assert child["b"]["z"] == [11] assert child["b"]["y"] == ["some", "body", "once", "told", "me"] def test_array_inheritance(): inherit_from = { "foo": "bar", "ding": "dong", "bing": "bang", "wham": ["a-lam", "a-bing", "bong"], "king": { "tide": "oceanography", "crab": "crustacean", "Sick-Nasty": "Spades", } } inherit_to = { "foo": "baz", "wham": [], "king": { "Penguin": "Antarctica" } } inherited = deepinherit(inherit_from, inherit_to) assert inherited["foo"] == "baz" assert inherited["wham"] == [] assert inherited["king"]["Penguin"] == "Antarctica" assert inherited["king"]["tide"] == "oceanography" inherit_to["wham"] = ["bim", "bala", "boom"] inherited = deepinherit(inherit_from, inherit_to) assert "a-bing" in inherited["wham"] assert "bim" in inherited["wham"]
2,303
test_path.py
devsysenv/tests
0
2022781
#!/usr/bin/env python import pytest import os import sys import logging logging.basicConfig() logger = logging.getLogger(__name__) logger.setLevel(logging.DEBUG) from pathlib import Path from dselib.thread import initTLS initTLS() from constants import CONST from dselib.path import normalizePath, dumpPath, isRootdir, GetBinpath, GetRootBinpath from dselib.path import GetRootShellpath, AddElementToSysPath, AddElementToSearchPath from dselib.path import RemoveElementFromSysPath, RemoveElementFromSearchPath from dselib.path import RemoveElementFromPath, RemoveElementsFromPath from dselib.path import chmodx, chpymod, pysymlink, pysymlinkdir def test_1(): assert isRootdir(r'\\unc\path\foo\bar') == False assert isRootdir(r'\\unc\path') == (True if os.name == 'nt' else False) def test_2(): # add tests for dumpenvstrings assert True def test_3(): # add tests for pushenvvar/removefromenv/getenvironmentvariabledictionary assert True def test_4(): # add tests for SubstituteEnvStrings assert True if __name__ == '__main__': pytest.main(['-k', 'test_path.py'])
1,112
neuro-cli/src/neuro_cli/completion.py
neuro-inc/neuro-cli
5
2023812
import os import sys from pathlib import Path import click from .root import Root from .utils import argument, group CFG_FILE = {"bash": Path("~/.bashrc"), "zsh": Path("~/.zshrc")} SOURCE_CMD = {"bash": "bash_source", "zsh": "zsh_source"} ACTIVATION_TEMPLATE = 'eval "$(_NEURO_COMPLETE={cmd} {exe})"' @group() def completion() -> None: """ Output shell completion code. """ @completion.command() @argument("shell", type=click.Choice(["bash", "zsh"])) async def generate(root: Root, shell: str) -> None: """ Show instructions for shell completion. """ root.print(f"Push the following line into your {CFG_FILE[shell]}") root.print( ACTIVATION_TEMPLATE.format(cmd=SOURCE_CMD[shell], exe=sys.argv[0]), crop=False, overflow="ignore", ) @completion.command() @argument("shell", type=click.Choice(["bash", "zsh"])) async def patch(root: Root, shell: str) -> None: """ Patch shell profile to enable completion Patches shell configuration while depending of current shell. Files patched: bash: `~/.bashrc` zsh: `~/.zshrc` """ GENERATED_START = ( b"# Start of generated by neuro. Please do not edit this comment.\n" ) GENERATED_END = b"\n# End of generated by neuro. Please do not edit this comment.\n" profile_file = CFG_FILE[shell].expanduser() code = ( GENERATED_START + os.fsencode( ACTIVATION_TEMPLATE.format(cmd=SOURCE_CMD[shell], exe=sys.argv[0]) ) + GENERATED_END ) try: with profile_file.open("rb+") as profile: content = profile.read() except FileNotFoundError: content = b"" start = content.find(GENERATED_START) if start != -1: end = content.find(GENERATED_END) if end == -1: raise click.ClickException( f"Malformed guarding comments. Please modify {profile_file} manually" ) content = content[:start] + code + content[end + len(GENERATED_END) :] else: if content != b"": content += b"\n" + code else: content = code with profile_file.open("wb+") as profile: profile.write(content) root.print(f"Added completion configuration into '{profile_file}'")
2,301
tests/unit/test_conf_parser.py
splunk/addonfactory-ucc-generator
16
2024275
# # Copyright 2021 Splunk Inc. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # import configparser import io import unittest from splunk_add_on_ucc_framework import conf_parser class TABConfigParserTest(unittest.TestCase): def test_read(self): conf = """ # # Very big copyright comment. # [source] # This is a very simple field aliasing. FIELDALIAS-field1 = field2 AS field1 EVAL-field3 = case(isnotnull(field4), "success",\ isnotnull(field5), "failure") [sourcetype:deprecated] EVAL-deprecated_field = "old_value" [eventtype=some_eventtype] tag = enabled """ parser = conf_parser.TABConfigParser() parser.read_string(conf) self.assertEqual(parser.get("source", "FIELDALIAS-field1"), "field2 AS field1") self.assertEqual( parser.get("source", "EVAL-field3"), 'case(isnotnull(field4), "success", isnotnull(field5), "failure")', ) self.assertEqual( parser.get("sourcetype:deprecated", "EVAL-deprecated_field"), '"old_value"' ) self.assertEqual(parser.get("eventtype=some_eventtype", "tag"), "enabled") def test_read_incorrect_conf(self): conf = """ [source] # This is a very simple field aliasing. FIELDALIAS-field1 = field2 AS field1 EVAL-field3 = case(isnotnull(field4), "success", isnotnull(field5), "failure") """ parser = conf_parser.TABConfigParser() with self.assertRaises(configparser.ParsingError): parser.read_string(conf) def test_write(self): conf = """ # # Very big copyright comment. # [source] # This is a very simple field aliasing. FIELDALIAS-field1 = field2 AS field1 EVAL-field3 = case(isnotnull(field4), "success",\ isnotnull(field5), "failure") [sourcetype:deprecated] EVAL-deprecated_field = "old_value" [eventtype=some_eventtype] tag = enabled """ parser = conf_parser.TABConfigParser() parser.read_string(conf) output = io.StringIO() parser.write(output) expected_output = conf + "\n" self.assertEqual(expected_output, output.getvalue()) def test_items(self): conf = """ # # Very big copyright comment. # [source] # This is a very simple field aliasing. FIELDALIAS-field1 = field2 AS field1 EVAL-field3 = case(isnotnull(field4), "success",\ isnotnull(field5), "failure") [sourcetype:deprecated] EVAL-deprecated_field = "old_value" [eventtype=some_eventtype] tag1 = enabled tag2 = enabled """ parser = conf_parser.TABConfigParser() parser.read_string(conf) expected_items = [ ("__name__", "eventtype=some_eventtype"), ("tag1", "enabled"), ("tag2", "enabled"), ] self.assertEqual(expected_items, parser.items("eventtype=some_eventtype")) def test_options(self): conf = """ # Comment [source] EVAL-field1 = "field1" # please pay attention to this extraction FIELDALIAS-field2 = field3 AS field2 [not_used_sourcetype] EVAL-field1 = "field1" """ parser = conf_parser.TABConfigParser() parser.read_string(conf) expected_options = ["__name__", "EVAL-field1", "FIELDALIAS-field2"] self.assertEqual(expected_options, parser.options("source")) def test_item_dict(self): conf = """ # # Very big copyright comment. # [source] # This is a very simple field aliasing. FIELDALIAS-field1 = field2 AS field1 EVAL-field3 = case(isnotnull(field4), "success",\ isnotnull(field5), "failure") [sourcetype:deprecated] EVAL-deprecated_field = "old_value" [eventtype=some_eventtype] tag1 = enabled tag2 = enabled """ parser = conf_parser.TABConfigParser() parser.read_string(conf) expected_item_dict = { "source": { "FIELDALIAS-field1": "field2 AS field1", "EVAL-field3": 'case(isnotnull(field4), "success", isnotnull(field5), "failure")', }, "sourcetype:deprecated": { "EVAL-deprecated_field": '"old_value"', }, "eventtype=some_eventtype": { "tag1": "enabled", "tag2": "enabled", }, } self.assertEqual(expected_item_dict, parser.item_dict()) def test_remove_existing_section(self): conf = """ # Comment [source] EVAL-field1 = "field1" # please pay attention to this extraction FIELDALIAS-field2 = field3 AS field2 [not_used_sourcetype] EVAL-field1 = "field1" """ parser = conf_parser.TABConfigParser() parser.read_string(conf) parser.remove_section("not_used_sourcetype") def test_remove_section_that_does_not_exist(self): conf = """ # Comment [source] EVAL-field1 = "field1" # please pay attention to this extraction FIELDALIAS-field2 = field3 AS field2 [not_used_sourcetype] EVAL-field1 = "field1" """ parser = conf_parser.TABConfigParser() parser.read_string(conf) parser.remove_section("does_not_exist") def test_add_remove_section(self): conf = """ # Comment [source] EVAL-field1 = "field1" # please pay attention to this extraction FIELDALIAS-field2 = field3 AS field2 [not_used_sourcetype] EVAL-field1 = "field1" """ parser = conf_parser.TABConfigParser() parser.read_string(conf) parser.add_section("useless_section") parser.set("useless_section", "deprecated_tag", "enabled") self.assertEqual(parser.get("useless_section", "deprecated_tag"), "enabled") parser.remove_section("useless_section")
6,135
tests/difficulty/wide_difficulty.py
Project-WAZN/wazn
2
2024008
#!/usr/bin/env python from __future__ import print_function import sys import subprocess python = sys.argv[1] py = sys.argv[2] c = sys.argv[3] data = sys.argv[4] first = python + " " + py + " > " + data second = [c, '--wide', data] try: print('running: ', first) subprocess.check_call(first, shell=True) print('running: ', second) subprocess.check_call(second) except: sys.exit(1)
418
python/test_formula_to_intervals.py
chaosite/SMTSampler
0
2024701
from z3_utils import * import sys as _sys from formula_strengthener import strengthen from interval import Interval, IntervalSet, INF, MINF def timed(func): def func_wrapper(*args, **kwargs): from datetime import datetime s = datetime.now() result = func(*args, **kwargs) e = datetime.now() return result, e-s return func_wrapper def solve_and_strengthen_formula(f, debug = True): print("f is: " + str(f)) s = Solver() s.add(f) s.check() m = s.model() r, stren_time = timed(strengthen)(f, m, debug) print("f after strengthening:") print(r) print(f"time to strengthen f: {stren_time.total_seconds()}s") return r def read_smt2(filename): formula = parse_smt2_file(filename) if is_and(formula): return formula.children() else: return formula def built_in_tests(): x = Int("x") y = Int("y") z = Int("z") t = Int("t") b = Bool("b") f = (x * y >= 60) r = solve_and_strengthen_formula(f, True) assert not r.unsimplified_demands # # I_1 == IntervalSet({"x": Interval(3, 4), "y": Interval(-3, -2), "z": Interval(3,4)}) # I = IntervalSet({"x": Interval(60, INF), "y": Interval(1, INF)}) # assert r.interval_set == I f = (x % y == 4) r = solve_and_strengthen_formula(f, True) assert not r.unsimplified_demands f = (x % y >= 4) r = solve_and_strengthen_formula(f, True) assert r.unsimplified_demands f = (x * y * z >= 70) solve_and_strengthen_formula(f, True) f = And(x * y * z >= 70, y==-1, z==-1) solve_and_strengthen_formula(f, True) f = And(x * y * z >= -70, y==1, z==-1) solve_and_strengthen_formula(f, True) f = And(x * y * 4 * z >= -70, y==1, z==-1) solve_and_strengthen_formula(f, True) f = And(x * y * 4 * z >= -70, x + 3*y <= 9) solve_and_strengthen_formula(f, True) f = And(((x + y) * (x + 1) <= 8), (y <= 2), (x + z > 3)) solve_and_strengthen_formula(f, True) f = Or(Not(b), x>8) solve_and_strengthen_formula(f, True) f = (x > 0) solve_and_strengthen_formula(f, True) f = Implies(And(Not(If(x > 0, y < 0, y > 0)), Or(z <= 7, x <= 8)), y == 2) solve_and_strengthen_formula(f, True) f = And(x > 0, And(y < 0, x >= 7)) solve_and_strengthen_formula(f, True) f = And(x <= 0, y + z <= 7) solve_and_strengthen_formula(f, True) f = And(x > 0, x - t <= 3, 5 * y >= 4, y + z <= 7, z == 5, t != 4) solve_and_strengthen_formula(f, True) f = And(-7 * z + 2 * t - 6 * y != 5) solve_and_strengthen_formula(f, True) if __name__ == "__main__": sys_args = _sys.argv[1:] if len(sys_args) == 0: print("No files were given. Running built-in tests.") built_in_tests() for file in sys_args: print(f"reading from file: {file}") constraints = read_smt2(file) # file-error handling is done inside read_smt2 f = And(constraints) solve_and_strengthen_formula(f)
2,992
main/lib/idds/rest/v1/logs.py
wguanicedew/iDDS
0
2023682
#!/usr/bin/env python # # 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.0OA # # Authors: # - <NAME>, <<EMAIL>>, 2020 import os from traceback import format_exc from flask import Blueprint, send_from_directory from idds.common import exceptions from idds.common.constants import HTTP_STATUS_CODE from idds.common.utils import tar_zip_files, get_rest_cacher_dir from idds.core import (transforms as core_transforms) from idds.rest.v1.controller import IDDSController class Logs(IDDSController): """ get(download) logs. """ def get(self, workload_id, request_id): """ Get(download) logs. :param workload_id: the workload id. :param request_id: The id of the request. HTTP Success: 200 OK HTTP Error: 404 Not Found 500 InternalError :returns: logs. """ try: if workload_id == 'null': workload_id = None if request_id == 'null': request_id = None if workload_id is None and request_id is None: error = "One of workload_id and request_id should not be None or empty" return self.generate_http_response(HTTP_STATUS_CODE.InternalError, exc_cls=exceptions.CoreException.__name__, exc_msg=error) except Exception as error: print(error) print(format_exc()) return self.generate_http_response(HTTP_STATUS_CODE.InternalError, exc_cls=exceptions.CoreException.__name__, exc_msg=error) try: transforms = core_transforms.get_transforms(request_id=request_id, workload_id=workload_id) workdirs = [] for transform in transforms: work = transform['transform_metadata']['work'] workdir = work.get_workdir() if workdir: workdirs.append(workdir) if not workdirs: error = "No log files founded." return self.generate_http_response(HTTP_STATUS_CODE.InternalError, exc_cls=exceptions.CoreException.__name__, exc_msg=error) cache_dir = get_rest_cacher_dir() if request_id and workload_id: output_filename = "request_%s.workload_%s.logs.tar.gz" % (request_id, workload_id) elif request_id: output_filename = "request_%s.logs.tar.gz" % (request_id) elif workload_id: output_filename = "workload_%s.logs.tar.gz" % (workload_id) else: output_filename = "%s.logs.tar.gz" % (os.path.basename(cache_dir)) tar_zip_files(cache_dir, output_filename, workdirs) return send_from_directory(cache_dir, output_filename, as_attachment=True, mimetype='application/x-tgz') except exceptions.NoObject as error: return self.generate_http_response(HTTP_STATUS_CODE.NotFound, exc_cls=error.__class__.__name__, exc_msg=error) except exceptions.IDDSException as error: return self.generate_http_response(HTTP_STATUS_CODE.InternalError, exc_cls=error.__class__.__name__, exc_msg=error) except Exception as error: print(error) print(format_exc()) return self.generate_http_response(HTTP_STATUS_CODE.InternalError, exc_cls=exceptions.CoreException.__name__, exc_msg=error) def post_test(self): import pprint pprint.pprint(self.get_request()) pprint.pprint(self.get_request().endpoint) pprint.pprint(self.get_request().url_rule) """---------------------- Web service url maps ----------------------""" def get_blueprint(): bp = Blueprint('logs', __name__) logs_view = Logs.as_view('logs') bp.add_url_rule('/logs/<workload_id>/<request_id>', view_func=logs_view, methods=['get', ]) return bp
4,022
libs/auth_token.py
zhanghe06/flask_restful
1
2024098
#!/usr/bin/env python # encoding: utf-8 """ @author: zhanghe @software: PyCharm @file: auth_token.py @time: 2018-06-21 10:52 """ from itsdangerous import TimedJSONWebSignatureSerializer as Serializer from config import current_config SECRET_KEY = current_config.SECRET_KEY TOKEN_TTL = current_config.TOKEN_TTL def generate_auth_token(user_id): s = Serializer(SECRET_KEY, expires_in=TOKEN_TTL) return s.dumps({'user_id': user_id}) def verify_auth_token(token): s = Serializer(SECRET_KEY) data = s.loads(token) return data
550
tests/end2end/test_cpc.py
srinivas32/python-zhmcclient
0
2023291
# Copyright 2019 IBM Corp. 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. """ End2end tests for CPCs that do not change anything. """ from __future__ import absolute_import, print_function from requests.packages import urllib3 import zhmcclient # pylint: disable=line-too-long,unused-import from zhmcclient.testutils.hmc_definition_fixtures import hmc_definition, hmc_session # noqa: F401, E501 # pylint: disable=unused-import from zhmcclient.testutils.cpc_fixtures import all_cpcs # noqa: F401 urllib3.disable_warnings() # Detect machine generation from machine type MACHINE_GENERATIONS = { '2817': 'gen11', # z196 '2818': 'gen11', # z114 '2827': 'gen12', # EC12 '2828': 'gen12', # BC12 '2964': 'gen13', # z13 '2965': 'gen13', # z13s '3906': 'gen14', # z14 '3907': 'gen14', # z14-ZR1 (MR) } # Properties in Cpc objects returned by List CPC Objects PROPS_CPC_LIST = { 'gen11': ['object-uri', 'name', 'status'], 'gen12': ['object-uri', 'name', 'status'], 'gen13': ['object-uri', 'name', 'status'], 'gen14': ['object-uri', 'name', 'status', 'has-unacceptable-status', 'dpm-enabled', 'se-version'], } # Properties in minimalistic Cpc objects PROPS_CPC_MINIMAL = ['object-uri', 'name'] def assert_cpc_minimal(cpc, exp_name, exp_prop_names): """ Check a Cpc object. """ act_prop_names = cpc.properties.keys() for prop_name in exp_prop_names: assert prop_name in act_prop_names, \ "CPC {0}".format(exp_name) assert cpc.properties['name'] == exp_name, \ "CPC {0}".format(exp_name) assert cpc.name == exp_name, \ "CPC {0}".format(exp_name) # Printing is disabled by default, rename to test_...() to enable it. def disabled_test_print_cpcs(all_cpcs): # noqa: F811 # pylint: disable=redefined-outer-name """ Print some information about the CPCs under test. """ for cpc in sorted(all_cpcs, key=lambda obj: obj.name): hd = cpc.manager.client.session.hmc_definition print("") print("CPC {} on HMC {}:".format(cpc.name, hd.nickname)) if cpc.dpm_enabled: print(" Partitions:") partitions = cpc.partitions.list() for partition in sorted(partitions, key=lambda obj: obj.name): print(" {}".format(partition.name)) print(" Adapters:") adapters = cpc.adapters.list() for adapter in sorted(adapters, key=lambda obj: obj.name): print(" {}".format(adapter.name)) else: print(" LPARs:") lpars = cpc.lpars.list() for lpar in sorted(lpars, key=lambda obj: obj.name): print(" {}".format(lpar.name)) print(" Reset profiles:") reset_profiles = cpc.reset_activation_profiles.list() for reset_profile in sorted(reset_profiles, key=lambda obj: obj.name): print(" {}".format(reset_profile.name)) print(" Load profiles:") load_profiles = cpc.load_activation_profiles.list() for load_profile in sorted(load_profiles, key=lambda obj: obj.name): print(" {}".format(load_profile.name)) print(" Image profiles:") image_profiles = cpc.image_activation_profiles.list() for image_profile in sorted(image_profiles, key=lambda obj: obj.name): print(" {}".format(image_profile.name)) def test_cpc_find_by_name(hmc_session): # noqa: F811 # pylint: disable=redefined-outer-name """ Test that all CPCs in the HMC definition can be found using find_by_name(). """ client = zhmcclient.Client(hmc_session) hd = hmc_session.hmc_definition for def_name in hd.cpcs: # The code to be tested cpc = client.cpcs.find_by_name(def_name) assert_cpc_minimal(cpc, def_name, PROPS_CPC_MINIMAL) def test_cpc_find_with_name(hmc_session): # noqa: F811 # pylint: disable=redefined-outer-name """ Test that all CPCs in the HMC definition can be found using find() with the name as a filter argument. """ client = zhmcclient.Client(hmc_session) hd = hmc_session.hmc_definition for def_name in hd.cpcs: # The code to be tested found_cpc = client.cpcs.find(name=def_name) assert_cpc_minimal(found_cpc, def_name, PROPS_CPC_MINIMAL) def test_cpc_findall_with_name(hmc_session): # noqa: F811 # pylint: disable=redefined-outer-name """ Test that all CPCs in the HMC definition can be found using findall() with the name as a filter argument. """ client = zhmcclient.Client(hmc_session) hd = hmc_session.hmc_definition for def_name in hd.cpcs: # The code to be tested found_cpcs = client.cpcs.findall(name=def_name) assert len(found_cpcs) == 1 found_cpc = found_cpcs[0] assert_cpc_minimal(found_cpc, def_name, PROPS_CPC_MINIMAL) def test_cpc_list_with_name(hmc_session): # noqa: F811 # pylint: disable=redefined-outer-name """ Test that all CPCs in the HMC definition can be found using list() with the name as a filter argument. """ client = zhmcclient.Client(hmc_session) hd = hmc_session.hmc_definition for def_name in hd.cpcs: # The code to be tested found_cpcs = client.cpcs.list(filter_args=dict(name=def_name)) exp_prop_names = [] def_machine_type = hd.cpcs[def_name].get('machine_type', None) if def_machine_type: gen = MACHINE_GENERATIONS.get(def_machine_type, None) if gen: exp_prop_names = PROPS_CPC_LIST[gen] assert len(found_cpcs) == 1 found_cpc = found_cpcs[0] assert_cpc_minimal(found_cpc, def_name, exp_prop_names) def test_cpc_list_with_name_full(hmc_session): # noqa: F811 # pylint: disable=redefined-outer-name """ Test that all CPCs in the HMC definition can be found using list() with full properties and the name as a filter argument. """ client = zhmcclient.Client(hmc_session) hd = hmc_session.hmc_definition for def_name in hd.cpcs: # The code to be tested found_cpcs = client.cpcs.list(filter_args=dict(name=def_name), full_properties=True) exp_prop_names = [] def_machine_type = hd.cpcs[def_name].get('machine_type', None) if def_machine_type: gen = MACHINE_GENERATIONS.get(def_machine_type, None) if gen: exp_prop_names = PROPS_CPC_LIST[gen] assert len(found_cpcs) == 1 found_cpc = found_cpcs[0] assert_cpc_minimal(found_cpc, def_name, exp_prop_names)
7,415
yat-master/pymodule/yat/cli/command/backup.py
opengauss-mirror/Yat
0
2023871
#!/usr/bin/env python # encoding=utf-8 """ Copyright (c) 2021 Huawei Technologies Co.,Ltd. openGauss is licensed under Mulan PSL v2. You can use this software according to the terms and conditions of the Mulan PSL v2. You may obtain a copy of Mulan PSL v2 at: http://license.coscl.org.cn/MulanPSL2 THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE. See the Mulan PSL v2 for more details. """ import click from yat.backup import backup from yat.cli.entry import cli from yat.errors import YatError @cli.command(name='backup', short_help='Backup last running result') @click.option('-a', '--action', help='Action to do', required=True, type=click.Choice(['backup', 'init', 'config'])) @click.option('-d', '--dir', help='Directory to scan and backup suite', default='.') @click.option('-m', '--mode', type=click.Choice(['full', 'quick', 'log']), help='Backup mode to using', default='quick') @click.option('-b', '--backup-dir', help='Set the backup directory') @click.option('-c', '--config', help='Set the config content[key=value]') def backup_cli(action, **opts): """ Backup last running result \b yat backup [-d /path/to/suite/dirs] [-m mode] -b /path/to/backup/dir """ if action == 'backup': backup.do_backup(**opts) elif action == 'init': backup.do_init(**opts) elif action == 'config': backup.do_config(**opts) else: raise YatError('error: unknown value for -a/--action')
1,613
interfaces/ATS_VM/utils/airtime-test-soundcard.py
krattai/AEBL
4
2023271
import subprocess import os import pwd import grp import sys import getopt """ we need to run the program as non-root because Liquidsoap refuses to run as root. It is possible to run change the effective user id (seteuid) before calling Liquidsoap but this introduces other problems (fake root user is not part of audio group after calling seteuid) """ if os.geteuid() == 0: print "Please run this program as non-root" sys.exit(1) def printUsage(): print "airtime-test-soundcard [-v] [-o alsa | ao | oss | portaudio | pulseaudio ] [-h]" print " Where: " print " -v verbose mode" print " -o Linux Sound API (default: alsa)" print " -h show help menu " def find_liquidsoap_binary(): """ Starting with Airtime 2.0, we don't know the exact location of the Liquidsoap binary because it may have been installed through a debian package. Let's find the location of this binary. """ rv = subprocess.call("which airtime-liquidsoap > /dev/null", shell=True) if rv == 0: return "airtime-liquidsoap" return None try: optlist, args = getopt.getopt(sys.argv[1:], 'hvo:') except getopt.GetoptError, g: printUsage() sys.exit(1) sound_api_types = set(["alsa", "ao", "oss", "portaudio", "pulseaudio"]) verbose = False sound_api = "alsa" for o, a in optlist: if "-v" == o: verbose = True if "-o" == o: if a.lower() in sound_api_types: sound_api = a.lower() else: print "Unknown sound api type\n" printUsage() sys.exit(1) if "-h" == o and len(optlist) == 1: printUsage() sys.exit(0) try: print "Sound API: %s" % sound_api print "Outputting to soundcard. You should be able to hear a monotonous tone. Press ctrl-c to quit." liquidsoap_exe = find_liquidsoap_binary() if liquidsoap_exe is None: raise Exception("Liquidsoap not found!") command = "%s 'output.%s(sine())'" % (liquidsoap_exe, sound_api) if not verbose: command += " > /dev/null" #print command rv = subprocess.call(command, shell=True) #if we reach this point, it means that our subprocess exited without the user #doing a keyboard interrupt. This means there was a problem outputting to the #soundcard. Print appropriate message. print "There was an error using the selected sound API. Please select a different API " + \ "and run this program again. Use the -h option for help" except KeyboardInterrupt, ki: print "\nExiting" except Exception, e: raise
2,634
image_helper/tests/test_fields.py
madisona/django-image-helper
1
2024328
import os import shutil from os.path import join, dirname from django import test from django.core.files.uploadedfile import SimpleUploadedFile from django.core.management import call_command from django.conf import settings from image_helper.tests.test_app.models import TestModel from image_helper.fields import _get_thumbnail_filename class SizedImageFieldTests(test.TestCase): def setUp(self): call_command("migrate", verbosity=0) def tearDown(self): test_images_path = os.path.join(settings.MEDIA_ROOT, "test_images") if os.path.exists(test_images_path): shutil.rmtree(test_images_path) def _get_simple_uploaded_file(self): return SimpleUploadedFile( "sample_photo.png", open(join(dirname(__file__), "test_app/sample_photo.png"), 'rb').read(), content_type="image/png") def _save_image_model(self): upload_file = self._get_simple_uploaded_file() m = TestModel(image=upload_file) m.save() return m def test_saves_image_and_thumbnail(self): upload_file = self._get_simple_uploaded_file() m = TestModel(image=upload_file) m.save() model = TestModel.objects.get(pk=1) self.assertEqual("test_images/sample_photo.png", model.image.name) self.assertEqual("{}test_images/sample_photo.png".format( settings.MEDIA_URL), model.image.url) self.assertEqual("{}/test_images/sample_photo.png".format( settings.MEDIA_ROOT), model.image.path) self.assertEqual(True, os.path.exists(model.image.path)) self.assertEqual("test_images/sample_photo-thumbnail.png", model.image.thumbnail.name) self.assertEqual("{}test_images/sample_photo-thumbnail.png".format( settings.MEDIA_URL), model.image.thumbnail.url) self.assertEqual("{}/test_images/sample_photo-thumbnail.png".format( settings.MEDIA_ROOT), model.image.thumbnail.path) self.assertEqual(True, os.path.exists(model.image.thumbnail.path)) def test_saves_appropriately_when_finding_valid_image_name(self): # Thumbnail should be named the same as image, just with the -thumbnail piece. self._save_image_model() self._save_image_model() model = TestModel.objects.get(pk=2) self.assertTrue( model.image.name.startswith("test_images/sample_photo")) self.assertNotEqual("test_images/sample_photo.png", model.image.name) self.assertEqual("{}{}".format(settings.MEDIA_URL, model.image.name), model.image.url) self.assertEqual("{}/{}".format(settings.MEDIA_ROOT, model.image.name), model.image.path) self.assertEqual(True, os.path.exists(model.image.path)) expected_thumbnail_name = _get_thumbnail_filename(model.image.name) self.assertEqual(expected_thumbnail_name, model.image.thumbnail.name) self.assertEqual("{}{}".format(settings.MEDIA_URL, expected_thumbnail_name), model.image.thumbnail.url) self.assertEqual("{}/{}".format(settings.MEDIA_ROOT, expected_thumbnail_name), model.image.thumbnail.path) self.assertEqual(True, os.path.exists(model.image.thumbnail.path)) class GetThumbnailFilenameTests(test.TestCase): def test_get_thumbnail_filename(self): thumbnail_name = _get_thumbnail_filename("my_image.jpg") self.assertEqual("my_image-thumbnail.jpg", thumbnail_name) def test_allows_customized_append_text(self): thumbnail_name = _get_thumbnail_filename( "my_image.jpg", append_text="-small") self.assertEqual("my_image-small.jpg", thumbnail_name)
3,879
scripts/textgrid_stats.py
RuntimeRacer/Real-Time-Voice-Cloning
0
2024081
# use a different docker image! # make build_align && make run_align # bin/mfa_align \ # /datasets/CommonVoice/en/speakers \ # /datasets/slr60/english.dict \ # /opt/Montreal-Forced-Aligner/dist/montreal-forced-aligner/pretrained_models/english.zip \ # /output/montreal-aligned/cv-en/ # bin/mfa_validate_dataset \ # /datasets/slr60/test-clean \ # /datasets/slr60/english.dict\ # english import sys import tgt import json from pathlib import Path from tqdm import tqdm import numpy as np DATASET = 'dev-clean' # DATASET = 'dev-other' # DATASET = 'test-clean' # DATASET = 'test-other' # DATASET = 'train-clean-100' # DATASET = 'train-clean-360' # DATASET = 'train-other-500' base_path = Path('/output/montreal-aligned/{}'.format(DATASET)) speaker_dirs = [f for f in base_path.glob("*") if f.is_dir()] dataset_phones = {} dataset_words = {} for speaker_dir in tqdm(speaker_dirs): book_dirs = [f for f in speaker_dir.glob("*") if f.is_dir()] for book_dir in book_dirs: # find our textgrid files textgrid_files = sorted([f for f in book_dir.glob("*.TextGrid") if f.is_file()]) # process each grid file and add to our output for textgrid_file in textgrid_files: # read the grid input = tgt.io.read_textgrid(textgrid_file) # print("input: {}".format(input)) # sys.exit(1) # get all the word tiers word_tier = input.get_tier_by_name('words') phone_tier = input.get_tier_by_name('phones') for interval in word_tier: if interval.text not in dataset_words: dataset_words[interval.text] = { "text": interval.text, "count": 0, "duration": [] } # increase the count dataset_words[interval.text]["count"] += 1 # add to our duration dataset_words[interval.text]["duration"].append( interval.end_time - interval.start_time ) for interval in phone_tier: if interval.text not in dataset_phones: dataset_phones[interval.text] = { "text": interval.text, "count": 0, "duration": [] } # increase the count dataset_phones[interval.text]["count"] += 1 # add to our duration dataset_phones[interval.text]["duration"].append( interval.end_time - interval.start_time ) def duration_stats(dataset): for k in dataset.keys(): vals = np.array(dataset[k]["duration"]) dataset[k]["duration"] = { "min": np.min(vals), "max": np.max(vals), "avg": np.mean(vals), "std": np.std(vals) } return dataset duration_stats(dataset_words) duration_stats(dataset_phones) with open(base_path.joinpath("stats.json"), "w") as json_out: json.dump( { "words": dataset_words, "phones": dataset_phones, }, json_out, indent=4 ) print("All done, thanks for playing!")
3,290
tests/test_document.py
gitwyy/chinese-calendar
616
2023821
# -*- coding: utf-8 -*- from __future__ import absolute_import, unicode_literals import unittest class DocTests(unittest.TestCase): def test_same_code_as_readme(self): import datetime # Check if 2018-04-30 is holiday in China from chinese_calendar import is_holiday, is_workday april_last = datetime.date(2018, 4, 30) self.assertFalse(is_workday(april_last)) self.assertTrue(is_holiday(april_last)) # or check and get the holiday name import chinese_calendar as calendar # with different import style on_holiday, holiday_name = calendar.get_holiday_detail(april_last) self.assertTrue(on_holiday) self.assertEqual(calendar.Holiday.labour_day.value, holiday_name) # even check if a holiday is in lieu import chinese_calendar self.assertFalse(chinese_calendar.is_in_lieu(datetime.date(2006, 2, 1))) self.assertTrue(chinese_calendar.is_in_lieu(datetime.date(2006, 2, 2)))
1,002
pydeepmerge/errors/__init__.py
sjhewitt/pydeepmerge
2
2024434
from pydeepmerge.errors.errors import ( # noqa: F401 FileTypeError, ParserNotAvailableError, )
104
nncf/tensorflow/sparsity/rb/functions.py
sarthakpati/nncf
310
2023004
""" Copyright (c) 2021 Intel Corporation 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 tensorflow as tf from nncf.tensorflow.functions import logit, st_threshold def binary_mask(mask): return tf.round(tf.math.sigmoid(mask)) def st_binary_mask(mask): return st_threshold(tf.math.sigmoid(mask)) def calc_rb_binary_mask(mask, seed, eps=0.01): uniform = tf.random.stateless_uniform(mask.shape, seed=seed, minval=0, maxval=1) mask = mask + logit(tf.clip_by_value(uniform, eps, 1 - eps)) return st_binary_mask(mask)
1,036
flaskr/settings.py
datahappy1/flask_mvc_github_boilerplate
0
2024801
""" settings module """ REPO = "datahappy1/flask_mvc_github_example_project" REPO_FOLDER = "files_playground/" INITIAL_BRANCH_NAME = "master" EDITABLE_FILE_EXTENSION_LIST = ['.csv', '.txt', '.json', '.ini', '.conf', '.yml', '.yaml'] API_BASE_ENDPOINT = 'api/version1'
268
notifications/signals/posts.py
RawrLion/vas3k.club
0
2024444
import telegram from django.db.models.signals import post_save from django.dispatch import receiver from django_q.tasks import async_task from bot.common import ADMIN_CHAT, send_telegram_message, render_html_message, CLUB_ONLINE from posts.models import Post @receiver(post_save, sender=Post) def create_or_update_post(sender, instance, created, **kwargs): if not created and "is_visible" not in instance.changed_fields: return None # we're not interested in updates, only if it's changing visibility if instance.type in {Post.TYPE_INTRO, Post.TYPE_WEEKLY_DIGEST}: return None # skip intros and emails if not instance.is_visible: return None # skip drafts too async_task(async_create_or_update_post, instance, created) def async_create_or_update_post(post, is_created): if not post.is_approved_by_moderator: send_telegram_message( chat=ADMIN_CHAT, text=render_html_message("moderator_post.html", post=post), reply_markup=telegram.InlineKeyboardMarkup([ [ telegram.InlineKeyboardButton("👍 Одобрить", callback_data=f"approve_post:{post.id}"), telegram.InlineKeyboardButton("😕 Так себе", callback_data=f"forgive_post:{post.id}"), ], [ telegram.InlineKeyboardButton("❌ В черновики", callback_data=f"delete_post:{post.id}"), ] ]) ) # post to online channel send_telegram_message( chat=CLUB_ONLINE, text=render_html_message("channel_post_announce.html", post=post), parse_mode=telegram.ParseMode.HTML, disable_preview=True, )
1,708
project/testmodule/__init__.py
nanvel/tornado-boilerplate
0
2023284
from project.common import settings settings.register(name='DEBUG', content_type=settings.TYPE_BOOL, default_value=True) settings.register(name='PORT', setting_type=settings.TYPE_INTEGER, default_value=8000) from .handlers import * from .urls import *
256
test/__init__.py
phseiff/gender-render
24
2024335
# ToDo: Apparently, the warnings-module's warning catching function is not thread save; feel free to make a pr to # replace it with `self.assertWarns` in all tests. Tests that expect no warning to happen could be implemented by # stickign a `@unittest.expectedFailure` to them. # On 2nd thought, that might not be a good idea for any test except the tests of the `warnings` module, since these are # the only multi-threaded tests, and `@unittest.expectedFailure` would require fragmenting the test functions.
513
app/menus/gameover_menu.py
Ahmed-Khaled-dev/modern-meerkats
1
2024816
import asyncio from typing import Literal, Optional from asciimatics.effects import Print from asciimatics.renderers import FigletText, Fire, SpeechBubble from asciimatics.scene import Scene from asciimatics.screen import Screen from app.types.events import Event _gameover_key: Optional[Literal["m", "r"]] = None def update_screen( end_time: int, loop: asyncio.AbstractEventLoop, screen: Screen ) -> None: """Checks if the user input matches with keys m or r.""" event = screen.get_event() screen.draw_next_frame() global _gameover_key try: if event is not None and chr(event.key_code) == "m": _gameover_key = "m" loop.stop() elif event is not None and chr(event.key_code) == "r": _gameover_key = "r" loop.stop() else: if loop.time() < end_time: loop.call_later(0.05, update_screen, end_time, loop, screen) else: loop.stop() except: # noqa: E722 if loop.time() < end_time: loop.call_later(0.05, update_screen, end_time, loop, screen) else: loop.stop() def gameover(screen: Screen, fail_reason: str) -> Event: """Displays the gameover screen.""" scenes = [] effects = [ Print( screen, SpeechBubble("Press m to return to main menu."), x=screen.width // 2 - 40, y=screen.height // 2 + 3, start_frame=5, transparent=True, colour=Screen.COLOUR_RED, ), ] effects.append( Print( screen, SpeechBubble("Press r to retry the level."), x=screen.width // 2 + 10, y=screen.height // 2 + 3, start_frame=5, transparent=False, colour=Screen.COLOUR_RED, ) ) # Check https://asciimatics.readthedocs.io/en/stable/asciimatics.html?highlight=fire#asciimatics.renderers.Fire effects.append( Print( screen, Fire(screen.height // 2 - 10, 80, "!!!!@@@@###", 1, 40, screen.colours), speed=1, transparent=True, x=screen.width // 2 + 30, y=screen.height // 2 - 20, ), ) # Check https://asciimatics.readthedocs.io/en/stable/asciimatics.html?highlight=fire#asciimatics.renderers.Fire effects.append( Print( screen, Fire(screen.height // 2 - 10, 80, "!!!!@@@@###", 1, 40, screen.colours), speed=1, transparent=True, x=screen.width // 2 - 110, y=screen.height // 2 - 20, ), ) effects.append( Print( screen, SpeechBubble(f"Congratulations! {fail_reason}."), screen.height // 2 - 8, speed=1, start_frame=5, transparent=False, ) ) effects.append( Print( screen, FigletText("GAME OVER!", "banner"), screen.height // 2 - 17, colour=Screen.COLOUR_RED, bg=Screen.COLOUR_BLACK, speed=1, ) ) scenes.append(Scene(effects, -1)) screen.set_scenes(scenes) loop = asyncio.new_event_loop() end_time = loop.time() + 500.0 loop.call_soon(update_screen, end_time, loop, screen) loop.run_forever() loop.close() screen.clear() screen.close() if _gameover_key == "m": return Event.ToMainMenu elif _gameover_key == "r": return Event.RetryLevel else: return Event.RetryLevel
3,618
examples/hlapi/v1arch/asyncore/sync/manager/cmdgen/enable-mib-lookup.py
RKinsey/pysnmp
492
2023031
""" Enable MIB lookup +++++++++++++++++ Perform SNMP GETNEXT operation with the following options: * with SNMPv2c, community 'public' * over IPv4/UDP * to an Agent at demo.snmplabs.com:161 * for an OID in string form * resolve request and response OIDs and values from/to human-friendly form The `lookupMib=True` keyword argument makes pysnmp resolving request and response variable-bindings from/to human-friendly form. Functionally similar to: | $ snmpwalk -v2c -c public -ObentU demo.snmplabs.com 1.3.6.1.2.1 """# from pysnmp.hlapi.v1arch import * iterator = nextCmd( SnmpDispatcher(), CommunityData('public'), UdpTransportTarget(('demo.snmplabs.com', 161)), ObjectType(ObjectIdentity('1.3.6.1.2.1.1')), lookupMib=True ) for errorIndication, errorStatus, errorIndex, varBinds in iterator: if errorIndication: print(errorIndication) break elif errorStatus: print('%s at %s' % (errorStatus.prettyPrint(), errorIndex and varBinds[int(errorIndex) - 1][0] or '?')) break else: for varBind in varBinds: print(' = '.join([x.prettyPrint() for x in varBind]))
1,178
lab10/lab10.py
ilyacoding/datascience
0
2024628
#!/usr/bin/env python # coding: utf-8 # # ml lab10 # In[52]: import numpy as np import matplotlib.pyplot as plt import sklearn import sklearn.datasets import sklearn.model_selection import sklearn.metrics import sklearn.tree import sklearn.linear_model # ### 1. get dataset from `sklearn` # In[7]: boston = sklearn.datasets.load_boston() boston.data.shape # ### 2. get train and validation sets # In[12]: X_train, X_test, y_train, y_test = sklearn.model_selection.train_test_split( boston.data.astype(np.float32), boston.target, test_size=0.25, random_state=42 ) X_train.shape, X_test.shape # ### 3-6. train with `DecisionTreeRegressor` # In[34]: def default_get_weight(x): return 0.9 def iter_get_weight(i): return 0.9 / (1.0 + i) def get_clf(depth): return sklearn.tree.DecisionTreeRegressor(max_depth=depth, random_state=42) def predict_boosted(models, X, y, weights): p = np.zeros(y.shape) for i, model in enumerate(models): p += model.predict(X) * weights[i] loss = sklearn.metrics.mean_squared_error(y, p) return p, loss def train_boosted(X, y, num_iters=50, get_weight=default_get_weight, depth=5): models = [] y = np.copy(y) weights = np.ones(shape=(num_iters,)) for i in range(num_iters): clf = get_clf(depth) clf.fit(X_train, y) models.append(clf) weights[i] = get_weight(i) pred, loss = predict_boosted(models, X_train, y_train, weights) h = clf.predict(X_train) y = y - h * weights[i] return models, weights # In[68]: models, weights = train_boosted(X_train, y_train) # In[69]: def print_results(models, weights): p, loss = predict_boosted(models, X_train, y_train, weights) test_p, test_loss = predict_boosted(models, X_test, y_test, weights) print(f'Training Set MSE loss:\t{loss}') print(f'Test Set MSE loss:\t{test_loss}') return test_loss test_loss = print_results(models, weights) # ### 7. change weights on each iteration # In[70]: models, weights = train_boosted(X_train, y_train, get_weight=iter_get_weight) test_loss = print_results(models, weights) # > при константном весе модель имеет меньшую ошибку на тренировочных данных, но большую на валидационной выборке # ### 8a. test on large number of iterations # In[39]: def test_num_iters(X_train, y_train, X_val, y_val): steps = 10 iters = np.linspace(10, 400, steps, dtype=int) train_loss = np.zeros(steps) val_loss = np.zeros(steps) for i, num_iters in enumerate(iters): models, weights = train_boosted(X_train, y_train, num_iters, get_weight=iter_get_weight) p, loss = predict_boosted(models, X_train, y_train, weights) test_p, test_loss = predict_boosted(models, X_val, y_val, weights) train_loss[i] = loss val_loss[i] = test_loss best_iters = iters[val_loss.argmin()] return best_iters, train_loss, val_loss, iters # In[40]: best_num_iters, train_loss, test_loss, iters = test_num_iters(X_train, y_train, X_test, y_test) best_num_iters # In[41]: def plot_data(iters, train_loss, test_loss, xlabel): plt.figure(figsize=(10, 6)) plt.plot(iters, train_loss, c='b', label='Train') plt.plot(iters, test_loss, c='r', label='Test') plt.xlabel(xlabel) plt.ylabel('MSE Loss') plt.legend() plt.show() plot_data(iters, train_loss, test_loss, 'Number of iterations') # > По графику ошибка убывает с числом итераций для обоих выборок (тренировочной и валидационной) - те модель не переобучается с ростом числа итераций # ### 8b. test on large tree depth # In[53]: def test_tree_depth(X_train, y_train, X_val, y_val): depths = range(2, 20) steps = len(depths) train_loss = np.zeros(steps) val_loss = np.zeros(steps) for i, depth in enumerate(depths): models, weights = train_boosted(X_train, y_train, depth=depth, get_weight=iter_get_weight) p, loss = predict_boosted(models, X_train, y_train, weights) test_p, test_loss = predict_boosted(models, X_val, y_val, weights) train_loss[i] = loss val_loss[i] = test_loss best_depth = depths[val_loss.argmin()] return best_depth, train_loss, val_loss, depths # In[54]: best_depth, train_loss, test_loss, depths = test_tree_depth(X_train, y_train, X_test, y_test) best_depth # In[55]: plot_data(depths, train_loss, test_loss, 'Max Tree Depth') # > При увеличении глубины дерева, ошибка на тренировочной выборке падает, а на валидационной скачет - что говорит о переобучении модели # ### 9. compare with `sklearn.linear_model` # In[72]: lr = sklearn.linear_model.LinearRegression() lr.fit(X_train, y_train) lr_p = lr.predict(X_train) lr_test_p = lr.predict(X_test) lr_train_loss = sklearn.metrics.mean_squared_error(y_train, lr_p) lr_test_loss = sklearn.metrics.mean_squared_error(y_test, lr_test_p) # In[74]: print(f'LR train MSE:\t{lr_train_loss}') print(f'LR test MSE:\t{lr_test_loss}') print(f'GB RMSE loss:\t{np.sqrt(test_loss)}') print(f'LR RMSE loss:\t{np.sqrt(lr_test_loss)}') print(f'GB perfomance is {np.sqrt(lr_test_loss)/np.sqrt(test_loss):.2}x better') # ### 10. conclusions # Был рассмотрен метод градиентного бустинга используя деревья решений. # # Проанализировано влияние параметров (количество итераций и глубина дерева) на качество обучения. # # Проведено сравнение градиентного бустинга с линейной регрессией.
5,536
commiter/src/factories.py
Rob174/Commiter
0
2024323
from commiter.src.backend.backend import Backend from pathlib import Path from commiter.src.command.actions import * from commiter.src.command.selectors import * from commiter.src.backend.tasks import * class Factory1: def create(self, path_config: Path, path_backup: Path): task_type = Task1 backend = Backend(path=path_backup, tasks_parsers=[task_type]) selector = IndexSelector(backend) actions = [AddTask(backend, task_type), DeleteTask(backend, selector), ModifyProperty( backend, selector), Issue(backend, task_type, selector)] return task_type, backend, selector, actions class Processor: def __init__(self, backend: Backend, actions: List): self.backend = backend self.actions = actions def process(self, command: str): commands = command.split(";") for command in commands: for action in self.actions: if action.can_parse(command): action.parse(command) break else: print("Unknown command: " + command) self.backend.write()
1,138
Xana/XParam/scratch.py
ClLov/Xana
0
2023779
kb = 1.381e-23 R = 11e-9 T = 25 e_rheo = 10 def getD(eta, err=0): dD = 0 D = kb*(T+273.15)/(6*np.pi*R*eta) if err: dD = D*err/eta return D, dD def geteta(D, err=0): deta = 0 eta = kb*(T+273.15)/(6*np.pi*R*D*1e-18) if err: deta = eta*err/D return eta, deta fig, ax = plt.subplots(2,2,figsize=(9,8)) ax = ax.ravel() cmap = plt.get_cmap('Set1') qp = np.arange(nq) qvn = qv[qp]*10 qvn2 = qvn**2 x = np.linspace(np.min(qvn),np.max(qvn),100) x2 = x*x #-------plot decay rates-------- for i in range(2): y = 1/rates[qp,1+3*i,0] dy = y**2*rates[qp,1+3*i,1] ax[0].errorbar(qvn2[qp],y,dy,fmt='o',color=cmap(i), alpha=.6, label=r'$\Gamma_{}$'.format(i)) nfl = [np.arange(9)] if i==0: nfl.append(np.arange(11,16)) qp = np.arange(9) if i==1: continue for nf in nfl: nf = np.delete(nf,np.where(rates[nf,1,1]==0)) D_mc, b_mc = emceefit_sl(qvn2[nf], y[nf], dy[nf])[:2] D_mc, b_mc = map(lambda x: (x[0],np.mean(x[1:])),[D_mc,b_mc]) popt, pcov = np.polyfit(qvn2[nf], y[nf], 1, w=1/dy[nf], cov=1) perr = np.sqrt(np.diag(pcov)) D_exp, b_exp = (popt[0],perr[0]), (popt[1],perr[1]) y_dif = y[nf] / qvn2[nf] dy_dif = dy[nf] / qvn2[nf] D_dif = (np.sum(y_dif/dy_dif**2)/np.sum(1/dy_dif**2), np.sqrt(1/np.sum(1/dy_dif**2))) e_dif = geteta(*D_dif) e_exp = geteta(*D_exp) e_mle = geteta(*D_mc) D_rheo = getD(e_rheo) ax[0].plot(x2, np.polyval(popt,x2), color=cmap(i)) #ax[0].plot(x2, np.polyval([D_dif[0],0],x2), color='gray') print('\nResults for {} decay:'.format(i+1)) print('-'*20) print('D_rheo = {:.2f} nm2s-1'.format(D_rheo[0]*1e18)) print(r'D_exp = {:.2f} +/- {:.2f} nm2s-1'.format(*D_exp)) print(r'b_exp = {:.2f} +/- {:.2f} s-1'.format(*b_exp)) print(r'D_mle = {:.4f} +/- {:.4f} nm2s-1'.format(*D_mc)) print(r'b_mle = {:.4f} +/- {:.4f} s-1'.format(*b_mc)) print(r'D_dif = {:.2f} +/- {:.2f} nm2s-1'.format(*D_dif)) print('\neta_rheo = {:.2f} Pas'.format(e_rheo)) print(r'eta_exp = {:.2f} +/- {:.2f} Pas'.format(*e_exp)) print(r'eta_mle = {:.4f} +/- {:.4f} Pas'.format(*e_mle)) print(r'eta_dif = {:.2f} +/- {:.2f} Pas'.format(*e_dif)) #-------plot KWW exponent-------- qp = np.arange(nq) g = rates[qp,2,0] dg = rates[qp,2,1] ax[2].errorbar(qvn,g,dg,fmt='o',color=cmap(0), alpha=.6, label=r'$\gamma_{}$'.format(0)) qp = np.arange(9) g = rates[qp,5,0] dg = rates[qp,5,1] ax[2].errorbar(qvn[qp],g,dg,fmt='s',color=cmap(1), alpha=.6, label=r'$\gamma_{}$'.format(1)) #-------plot nonergodicity parameter-------- def blc(q,L,k,lc): def A(q): return 4*np.pi/lc*q/k*np.sqrt(1-q**2/(4*k**2)) return 2*(A(q)*L-1+np.exp(-A(q)*L))/(A(q)*L)**2 b = np.sum(rates[:,3::3,0],1) db = np.sum(rates[:,3::3,1],1) ax[1].errorbar(qvn2, b, db, fmt='o', color=cmap(0), alpha=.6, label=r'$f_0(q)$') nf = np.arange(8) nf = np.delete(nf,np.where(rates[nf,1,1]==0)) y = np.log(b[nf]) dy = db[nf]/b[nf] popt1, cov1 = np.polyfit(qvn2[nf], y, 1, w=1/dy, cov=1) cov1 = np.sqrt(np.diag(cov1))[0] ax[1].plot(x2, exp(np.polyval(popt1,x2)), '-', color=cmap(0)) #label=r'${:.3g}\, \exp{{(-q^2\cdot{:.3g}nm^{{2}})}}$'.format(np.exp(popt1[1]),-1*popt1[0])) #---- b = rates[qp,6,0] db = rates[qp,6,1] ax[1].errorbar(qvn2[qp], b, db, fmt='s', color=cmap(1), alpha=.6, label=r'$f_1(q)$') #---- y_th = exp(popt[1])*blc(x, 1e-5, 2*np.pi/(12.4/21/10), 1e-6) y = np.mean(cnorm[2:nq+2,1:6],1) dy = np.std(cnorm[2:nq+2,1:6],1) ax[1].errorbar(qvn2, y, dy, fmt='o', color='k', alpha=.6, label=r'$\beta_0(q)$') popt2, cov2 = np.polyfit(qvn2, np.log(y), 1, w=y/dy, cov=1) cov2 = np.sqrt(np.diag(cov2))[0] ax[1].plot(x2, exp(np.polyval(popt2,x2)), '-', color='k') #ax[1].legend(loc=3) x_labels = ax[1].get_xticks() ax[1].xaxis.set_major_formatter(ticker.FormatStrFormatter('%0.0g')) c = popt2[0]-popt1[0] r_loc = np.sqrt(6*(c)/2) dr_loc = 3/2/r_loc*np.sqrt(cov1**2+cov2**2) print('\n\nlocalization length: {:.2f} +/- {:.2f} nm'.format(r_loc,dr_loc)) # set style ax[0].set_xlabel(r'$\mathrm{q}^2$ [$\mathrm{nm}^{-2}]$') ax[0].set_ylabel(r'$\Gamma [s^{-1}]$') ax[2].set_xlabel(r'$\mathrm{q}$ [$\mathrm{nm}^{-1}]$') ax[2].set_ylabel(r'KWW exponent') ax[1].set_yscale('log') ax[1].set_xlabel(r'$\mathrm{q}^2$ [$\mathrm{nm}^{-2}]$') ax[1].set_ylabel(r'contrast') for axi in ax: axi.legend(loc='best') niceplot(axi) plt.tight_layout() plt.savefig('um2018/cfpars1.eps')
4,597
backtester/urls.py
gem763/qit
2
2023277
from django.urls import path from . import views as v urlpatterns = [ path('', v.dashboard, name='dashboard'), path('run_backtest/', v.RunBacktestView.as_view(), name='run_backtest'), path('get_source/', v.GetSourceView.as_view(), name='get_source') ]
265
zbmain/utils/file.py
zbmain/py_pub
0
2024210
#!/usr/bin/env python # -*- coding: utf-8 -*- # @Author : zb # @Time : 2020/11/18 22:27 # @Blog : https://blog.zbmain.com def write(char, filepath='tmp.txt', mode='w'): with open(filepath, mode) as file: file.write(str(char) + "\n")
254
ui/webapp.py
phucnh22/mapintel_dev
0
2024365
import os import sys from datetime import date, timedelta import pandas as pd import streamlit as st dirname = os.path.dirname(__file__) sys.path.append(os.path.join(dirname, "../")) from ui.ui_components.umap_search import umap_page from ui.utils import ( feedback_doc, retrieve_doc, get_all_docs, umap_query, topic_names, doc_count ) # TODO: A problem with the application is that when setting the slider value the query # will execute even if we didn't finish selecting the value we want. A temporary solution # is to wrap the sliders inside a form component. The ideal solution would be to create # a custom slider component that only updates the value when we release the mouse. # TODO: When selecting a point in the UMAP, show the KNN points highlighted on the plot # and the listed below (the action of selecting the point will call the query endpoint) # TODO: Create a function to parse the query and allow search operators like "term" to # restrict the query to documents that contain "term" # Init variables default_question = "Stock Market News" unique_topics = topic_names() debug = False batch_size = 10000 filters = [] # Set page configuration st.set_page_config( page_title = "MapIntel App", layout = "wide" ) # Title st.write("# Mapintel App") # UI sidebar with st.sidebar: st.header("Options:") with st.form(key="options_form"): end_of_week = date.today() + timedelta(6 - date.today().weekday()) _, mid, _ = st.beta_columns([1, 10, 1]) with mid: # Use columns to avoid slider labels being off-window filter_date = st.slider( "Date range", min_value=date(2020,1,1), value=(date(2020,1,1), end_of_week), step=timedelta(7), format="DD-MM-YY" ) with st.beta_expander("Query Options"): filter_category = st.multiselect( "Category", options=unique_topics, default="-1_news_covid_people_2021" ) filter_category_exclude = st.checkbox( "Exclude", value=True ) with st.beta_expander("Results Options"): top_k_reader = st.slider( "Number of returned documents", min_value=1, max_value=20, value=10, step=1 ) top_k_retriever = st.slider( "Number of candidate documents", min_value=1, max_value=200, value=100, step=1 ) with st.beta_expander("Visualization Options"): umap_perc = st.slider( "Percentage of documents displayed", min_value=1, max_value=100, value=10, step=1, help="Display a randomly sampled percentage of the documents to improve performance" ) st.form_submit_button(label='Submit') # Prepare filters if filter_category: filter_topics = list(map(lambda x: x.lower(), filter_category)) # If filters should be excluded if filter_category_exclude: filter_topics = list(set(unique_topics).difference(set(filter_topics))) # Sort filters filter_topics.sort(key=lambda x: int(x.split("_")[0])) filters.append( { "terms": { "topic_label": filter_topics } } ) else: filter_topics = unique_topics filters.append( { "range": { "publishedat": { "gte": filter_date[0].strftime("%Y-%m-%d"), "lte": filter_date[1].strftime("%Y-%m-%d") } } } ) # Search bar question = st.text_input(label="Please provide your query:", value=default_question) # TODO: create a umatrix endpoint much like the umap one and use it to display the umatrix? # Sampling the docs and passing them to the UMAP plot doc_num = doc_count(filters) sample_size = int(umap_perc/100 * doc_num) st.subheader("UMAP") with st.spinner( "Getting documents from database... \n " "Documents will be plotted when ready." ): # Read data for umap plot (create generator) umap_docs = get_all_docs( filters=filters, batch_size=batch_size, sample_size=sample_size ) # Plot the completed UMAP plot fig, config = umap_page( documents=pd.DataFrame(umap_docs), query=umap_query(question), unique_topics=filter_topics ) st.plotly_chart(fig, use_container_width=True, config=config) st.write("___") # Get results for query with st.spinner( "Performing neural search on documents... 🧠 \n " "Do you want to optimize speed or accuracy? \n" "Check out the docs: https://haystack.deepset.ai/docs/latest/optimizationmd " ): results, raw_json = retrieve_doc( query=question, filters=filters, top_k_reader=top_k_reader, top_k_retriever=top_k_retriever ) st.write("## Retrieved answers:") # Make every button key unique count = 0 raw_json_feedback = "" for result in results: # Define columns for answer text and image col1, _, col2 = st.beta_columns([6, 1, 3]) with col1: title, description, content = result["answer"].split("#SEPTAG#") st.write(f"### {title}\n{description}\n\n{content}") with col2: if result['image_url'] is not None and result['image_url'] != "null": image_url = result['image_url'] else: image_url = 'http://www.jennybeaumont.com/wp-content/uploads/2015/03/placeholder.gif' if result['url'] is not None: st.markdown( f""" <a href={result['url']}> <img src={image_url} alt={result['url']} style="width:600px;"/> </a> """ , unsafe_allow_html=True ) else: st.markdown( f""" <img src={image_url} alt="Placeholder Image" style="width:600px;"> """ , unsafe_allow_html=True ) "**Relevance:** ", result["relevance"], "**Topic:** ", result["topic"], "**Published At:** ", result["publishedat"][:-4].replace('T', ', ') # Define columns for feedback buttons button_col1, button_col2, _ = st.beta_columns([1, 1, 8]) if button_col1.button("👍", key=(result["answer"] + str(count)), help="Relevant document"): raw_json_feedback = feedback_doc( question, result["answer"], result["document_id"], 1, "true", "true" ) st.success("Thanks for your feedback") if button_col2.button("👎", key=(result["answer"] + str(count)), help="Irrelevant document"): raw_json_feedback = feedback_doc( question, result["answer"], result["document_id"], 1, "false", "false" ) st.success("Thanks for your feedback!") count += 1 st.write("___") if debug: st.subheader("REST API JSON response") st.write(raw_json)
7,131
debexpo/settings/common.py
debexpo/debexpo
3
2024061
# common.py - Django settings for debexpo project, common settings # # This file is part of debexpo # https://salsa.debian.org/mentors.debian.net-team/debexpo # # Copyright © 2019 <NAME> <<EMAIL>> # # 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. from os import path from django.utils.translation import gettext_lazy as _ # Build paths inside the project like this: path.join(BASE_DIR, ...) BASE_DIR = path.dirname( path.dirname(path.dirname(path.abspath(__file__))) ) # Application definition INSTALLED_APPS = [ 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'django_celery_beat', 'debexpo.base', 'debexpo.accounts', 'debexpo.keyring', 'debexpo.packages', 'debexpo.comments', 'debexpo.importer', 'debexpo.repository', 'debexpo.plugins', 'debexpo.bugs', 'debexpo.nntp', 'rest_framework', 'django_filters', ] MIDDLEWARE = [ 'django.middleware.security.SecurityMiddleware', 'django.contrib.sessions.middleware.SessionMiddleware', 'django.middleware.locale.LocaleMiddleware', 'django.middleware.common.CommonMiddleware', 'django.middleware.csrf.CsrfViewMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', 'django.contrib.sites.middleware.CurrentSiteMiddleware', 'django.middleware.clickjacking.XFrameOptionsMiddleware', ] ROOT_URLCONF = 'debexpo.urls' TEMPLATES = [ { 'BACKEND': 'django.template.backends.django.DjangoTemplates', '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', ], }, }, ] LANGUAGES = [ ('en', _('English')), # ('fr', _('French')), ] LOCALE_PATHS = [ path.join(BASE_DIR, 'debexpo', 'locale') ] WSGI_APPLICATION = 'debexpo.wsgi.application' CACHES = { 'default': { 'BACKEND': 'django_redis.cache.RedisCache', 'LOCATION': 'redis://127.0.0.1:6379/1', 'OPTIONS': { 'CLIENT_CLASS': 'django_redis.client.DefaultClient', } } } # Internationalization # https://docs.djangoproject.com/en/2.2/topics/i18n/ LANGUAGE_CODE = 'en-us' TIME_ZONE = 'UTC' USE_I18N = True USE_L10N = True USE_TZ = True # Static files (CSS, JavaScript, Images) # https://docs.djangoproject.com/en/2.2/howto/static-files/ STATIC_URL = '/static/' STATIC_ROOT = path.join(BASE_DIR, 'static') # Password hashes (read bcrypt and md5, update/create to bcrypt) # https://docs.djangoproject.com/en/2.2/topics/auth/passwords/ PASSWORD_HASHERS = ( 'django.contrib.auth.hashers.BCryptPasswordHasher', 'django.contrib.auth.hashers.UnsaltedMD5PasswordHasher', ) # Debexpo common settings LOGO = '/img/debexpo-logo.png' SITE_NAME = 'debexpo' SITE_TITLE = 'Debexpo' TAGLINE = _('Helps you get your packages into Debian') VCS_BROWSER = 'https://salsa.debian.org/mentors.debian.net-team/debexpo' # SMTP and NNTP settings SMTP_SERVER = 'localhost' SMTP_PORT = 25 # SMTP_USERNAME = 'foo' # SMTP_PASSWORD = '<PASSWORD>' NNTP_SERVER = 'news.gmane.io' # Debexpo User model AUTH_USER_MODEL = 'accounts.User' # GPG settings GPG_PATH = '/usr/bin/gpg' # Celery settings CELERY_BROKER_URL = 'redis://localhost:6379' CELERY_RESULT_BACKEND = 'redis://localhost:6379' CELERY_ACCEPT_CONTENT = ['application/json'] CELERY_TASK_SERIALIZER = 'json' CELERY_RESULT_SERIALIZER = 'json' CELERY_TIMEZONE = TIME_ZONE CELERY_BEAT_SCHEDULER = 'django' CELERY_BEAT_SCHEDULE = { 'remove-old-uploads': { 'task': 'debexpo.packages.tasks.remove_old_uploads', 'schedule': 60 * 10, # Every 10 minutes }, 'cleanup-accounts': { 'task': 'debexpo.accounts.tasks.CleanupAccounts', 'schedule': 60 * 60, # Every hours }, 'importer': { 'task': 'debexpo.importer.tasks.importer', 'schedule': 60 * 15, # Every 15 minutes }, 'remove-uploaded-packages': { 'task': 'debexpo.packages.tasks.remove_uploaded_packages', 'schedule': 60 * 10, # Every 10 minutes }, } # Account registration expiration REGISTRATION_EXPIRATION_DAYS = 7 # Plugins to load IMPORTER_PLUGINS = ( ('debexpo.plugins.distribution', 'PluginDistribution',), ('debexpo.plugins.buildsystem', 'PluginBuildSystem',), ('debexpo.plugins.watch-file', 'PluginWatchFile',), ('debexpo.plugins.native', 'PluginNative',), ('debexpo.plugins.maintaineremail', 'PluginMaintainerEmail',), ('debexpo.plugins.lintian', 'PluginLintian',), ('debexpo.plugins.diffclean', 'PluginDiffClean',), ('debexpo.plugins.closedbugs', 'PluginClosedBugs'), ('debexpo.plugins.controlfields', 'PluginControlFields',), ('debexpo.plugins.debianqa', 'PluginDebianQA',), ('debexpo.plugins.rfs', 'PluginRFS',), ) # Debian Archive access DEBIAN_ARCHIVE_URL = 'https://deb.debian.org/debian' LIMIT_SIZE_DOWNLOAD = 100 * 1024 * 1024 # Bug plugin settings BUGS_REPORT_NOT_OPEN = True # Debian tracker access TRACKER_URL = 'https://tracker.debian.org' FTP_MASTER_NEW_PACKAGES_URL = 'https://ftp-master.debian.org/new.822' FTP_MASTER_API_URL = 'https://api.ftp-master.debian.org' # Cleanup package older than NN weeks MAX_AGE_UPLOAD_WEEKS = 20 # Cleanup incoming queue QUEUE_EXPIRED_TIME = 6 * 60 * 60 # File TTL is 6 hours # API settings REST_FRAMEWORK = { # Filtering 'DEFAULT_FILTER_BACKENDS': ('django_filters.rest_framework.DjangoFilterBackend',), # Versioning 'DEFAULT_VERSIONING_CLASS': 'rest_framework.versioning.AcceptHeaderVersioning', 'DEFAULT_VERSION': '1', 'ALLOWED_VERSIONS': ('1',), # Rate Limiting 'DEFAULT_THROTTLE_CLASSES': ( 'rest_framework.throttling.AnonRateThrottle', ), 'DEFAULT_THROTTLE_RATES': { 'anon': '200/day', # Approximatively 2 request every 15 minutes }, } # Spam detection REGISTRATION_SPAM_DETECTION = False # Time between GET and POST of the registration form REGISTRATION_MIN_ELAPSED = 3 # How any time an IP can register an account (currently per day) REGISTRATION_PER_IP = 5 # Forget the IP after 1 day (set to 0 to disable spam detection) REGISTRATION_CACHE_TIMEOUT = 1 * 24 * 3600 # Timeout for processes (10 minutes by default, 30 minutes for lintian) SUBPROCESS_TIMEOUT = 10 * 60 SUBPROCESS_TIMEOUT_LINTIAN = 30 * 60
7,708
VGGish/f_FeatureExtraction.py
ducphucnguyen/TransferLearningWFN
0
2024645
from __future__ import print_function import numpy as np import tensorflow.compat.v1 as tf import vggish_input import vggish_params import vggish_slim import pyenvnoise from pyenvnoise.utils import ptiread import scipy.io print('\nTesting your install of VGGish\n') # Paths to downloaded VGGish files. checkpoint_path = 'vggish_model.ckpt' pca_params_path = 'vggish_pca_params.npz' # Load audio files from folder info = scipy.io.loadmat('R:\\CMPH-Windfarm Field Study\\Hallett\\Hallett_file_info.mat') num_secs = 624 num_files = info['filelist'].shape[0] # X = np.empty([num_files, 128]) result_conv1 = np.empty([1000, 32]) for i in range(0,1000): # range(1, num_files) try: # wav_file = 'R:\\CMPH-Windfarm Field Study\\Duc Phuc Nguyen\\4. Machine Listening\\Data set\\set8\\audio\\so%d.wav'%(i+1,) # input_batch = vggish_input.wavfile_to_examples(wav_file) # Produce a batch of log mel spectrogram examples. #wav_file = 'R:\\CMPH-Windfarm Field Study\\Hallett\\set1\\Recording-3.%d.pti'%(i+1,) name = info['filelist'][i]['name'][0][0] folder = info['filelist'][i]['folder'][0][0] file_name_i = folder + '\\' + name x, sr, t, d = ptiread(file_name_i) input_batch = vggish_input.waveform_to_examples(x[:,3], sr) #print(file_name_i) # np.testing.assert_equal( # input_batch.shape, # [num_secs, vggish_params.NUM_FRAMES, vggish_params.NUM_BANDS]) # Define VGGish,load the checkpoint,and run the batch through the model to # produce embeddings. with tf.Graph().as_default(), tf.Session() as sess: vggish_slim.define_vggish_slim() vggish_slim.load_vggish_slim_checkpoint(sess, checkpoint_path) features_tensor = sess.graph.get_tensor_by_name( vggish_params.INPUT_TENSOR_NAME) embedding_tensor = sess.graph.get_tensor_by_name( vggish_params.OUTPUT_TENSOR_NAME) [embedding_batch] = sess.run([embedding_tensor], feed_dict={features_tensor: input_batch}) # print('VGGish embedding: ', embedding_batch[2]) # print(embedding_batch.shape) result_conv1[i] = embedding_batch.mean(axis=-1).mean(axis=1).mean(axis=0) # X[i] = np.mean(embedding_batch, axis=0) # X = np.mean(embedding_batch, axis=0) # print('\nLooks Good To Me!\n') print(i) #np.savetxt("R:\\CMPH-Windfarm Field Study\\Duc Phuc Nguyen\\4. Machine Listening\\Deepfeature\\HL\\X%d.txt"%(i+1), X, # delimiter=",") except: print("An exception occurred") np.savetxt("R:\\CMPH-Windfarm Field Study\\Duc Phuc Nguyen\\4. Machine Listening\\Low_high_feature\\2.Hallett\\result_conv1.csv", result_conv1, delimiter=",")
2,912
scripts/clarity/metaData.py
alee156/clarityexplorer
2
2024218
#!/usr/bin/python #-*- coding:utf-8 -*- __author__ = 'david' from __builtin__ import * import ndio import ndio.remote.neurodata as ND import pprint, json import resources def metaFile(token): return resources.METADATAPATH+"%s.meta"%(token) def getMetaData(token): with open(metaFile(token)+".json",'r') as file: metaData = json.load(file) return metaData def downloadMetaData(nd,token): metadata = nd.get_proj_info(token) return metadata def main(): nd = ND() print "Download and save meta datas." print 'ndio version = %s ... ...'%(ndio.version), for token in resources.TOKENS+resources.ANNO_TOKENS: print "Downloading meta TOKEN=%s"%(token) metaData = downloadMetaData(nd,token) filename = metaFile(token) with open(filename,'w') as file: pprint.pprint(metaData, file) with open(filename+".json",'w') as file: json.dump(metaData,file) print "OK" print "Finish all." if __name__ == '__main__': main()
1,037
python/challenges/python/introduction-if-else.py
KoderDojo/hackerrank
1
2024592
""" Given an integer, , perform the following conditional actions: If is odd, print Weird If is even and in the inclusive range of to , print Not Weird If is even and in the inclusive range of to , print Weird If is even and greater than , print Not Weird """ N = int(input().strip()) if N % 2 == 1 or 6 <= N <= 20: print('Weird') else: print('Not Weird')
373
python_test/anjuke.py
doubtfire009/huizhi_python
0
2023482
from selenium import webdriver from bs4 import BeautifulSoup import time default_encoding = 'utf-8' driver = webdriver.PhantomJS() # webdriver.Firefox() page_num_max = 6 page_num = 1 url1= 'http://shanghai.anjuke.com/sale/hongkou/p' url2= '-rd1/?kw=%E5%9C%B0%E6%9A%96&from_url=kw_final' while(page_num <= page_num_max): url3 = url1 + str(page_num) + url2 print(url3) driver.get(url3) f=open(r'f:/data/anjukehk'+ str(page_num) +'.txt','w',encoding='utf-8') f.write(driver.page_source) time.sleep(3) page_num = page_num + 1 f.close() driver.quit() # driver.find_element_by_id('search-esf').send_keys("地暖") # driver.find_element_by_id("search-button").click() # print(driver.find_element_by_xpath("//span[@class='comm-address']").text) # print(driver.page_source)
802
BOJ14494.py
INYEONGKIM/BOJ
2
2023713
m,n=map(int,input().split());d=[] for i in range(m): if i==0: d.append([1]*n) else: t=[1];t+=[0]*(n-1) d.append(t) for i in range(1,m): for j in range(1,n): d[i][j]=(d[i-1][j-1]+d[i-1][j]+d[i][j-1])%(1e9+7) print(int(d[-1][-1]))
273
source/apps/modules/urls.py
udbhav/eurorack-planner
1
2024808
from django.conf.urls.defaults import patterns, url from django.contrib.auth.decorators import login_required from apps.modules.views import * urlpatterns = patterns( '', #url(r'^manufacturers/$', ManufacturersView.as_view(), {}, name='manufacturers'), #url(r'^manufacturers/(?P<pk>\d+)/modules/$', ModulesByManufacturer.as_view(), name='modules_by_manufacturer'), #url(r'^$', ModulesView.as_view(), {}, name='modules'), url(r'^(?P<pk>\d+)/$', ModuleView.as_view(), name='module'), url(r'^json/(?P<pk>\d+)/$', JSONModuleView.as_view(), name='json_module'), url(r'^setups/$', login_required(SetupsView.as_view()), name='setups'), url(r'^setup/(?P<pk>\d+)/$', login_required(SetupView.as_view()), name='setup'), url(r'^setup/(?P<pk>\d+)/delete/$', 'apps.modules.views.delete_setup', name='delete_setup'), url(r'^setup/save/$', 'apps.modules.views.save_setup', name='save_online_setup'), url(r'^planner/$', 'apps.modules.views.planner', name='planner'), url(r'^save-to-file/$', 'apps.modules.views.save_to_file', name='save_to_file'), url(r'^save-setup-image/$', 'apps.modules.views.save_setup_image', name='save_setup_image'), url(r'^custom/$', login_required(CustomModulesView.as_view()), name='custom_modules'), url(r'^custom/new$', login_required(NewCustomModuleView.as_view()), name='new_custom_module'), url(r'^custom/(?P<pk>\d+)/$', login_required(EditCustomModuleView.as_view()), name='edit_custom_module'), url(r'^custom/(?P<pk>\d+)/delete/$', login_required(DeleteCustomModuleView.as_view()), name='delete_custom_module'), )
1,613
plotter/__main__.py
majo48/froeling-web-connect-logger
2
2024733
""" main part of the plotter app Copyright (c) 2020 <NAME> (<EMAIL>) """ from plotter import app if __name__ == '__main__': app.manage_arguments()
156
local_ancestry/fix_classes.py
berebolledo/sofia
0
2023781
#! /bin/env python import sys newvalues = [] for line in sys.stdin: values = line.strip().split() for value in values: newvalues.append(str(value)) newvalues.append(str(value)) newvalues.append('\n') sys.stdout.write(' '.join(newvalues))
264
src/olympia/amo/migrations/__init__.py
covariant/addons-server
843
2024793
from django.db import migrations class RenameConstraintsOperation(migrations.RunSQL): RENAME_FRAGMENT = "RENAME KEY `{0}` TO `{1}`" RENAME_FRAGMENT_REVERSE = "RENAME KEY `{1}` TO `{0}`" REMOVE_CLASS = migrations.RemoveConstraint OPERATION_PROP = 'constraint' def _format_renames(self, fragment, adds): return [ fragment.format(old_name, getattr(operation, self.OPERATION_PROP).name) for operation, old_name in adds ] def _gather_state_operations(self, adds): state_operations = [] for operation, old_name in adds: state_operations.append(operation) state_operations.append( self.REMOVE_CLASS( model_name=operation.model_name, name=old_name, ) ) return state_operations def __init__(self, table_name, adds): """ `table_name` is the database table name. `adds` is a iterable of (<AddOperation>, <old name>) tuples. """ state_operations = self._gather_state_operations(adds) forward_sql = f'ALTER TABLE `{table_name}` {", ".join(self._format_renames(self.RENAME_FRAGMENT, adds))}' reverse_sql = f'ALTER TABLE `{table_name}` {", ".join(self._format_renames(self.RENAME_FRAGMENT_REVERSE, adds))}' return super().__init__( sql=forward_sql, reverse_sql=reverse_sql, state_operations=state_operations) class RenameIndexesOperation(RenameConstraintsOperation): RENAME_FRAGMENT = "RENAME INDEX `{0}` TO `{1}`" RENAME_FRAGMENT_REVERSE = "RENAME INDEX `{1}` TO `{0}`" REMOVE_CLASS = migrations.RemoveIndex OPERATION_PROP = 'index'
1,744
cogs/games/__init__.py
z03h/stella_bot
0
2022672
from __future__ import annotations from typing import TYPE_CHECKING from .wordle import WordleCommandCog if TYPE_CHECKING: from main import StellaBot class GamesCog(WordleCommandCog, name="Games"): """Contains games that stella made.""" async def setup(bot: StellaBot): await bot.add_cog(GamesCog(bot))
320
tests/run_test_DataSplitter.py
damicoedoardo/NNMF
2
2024408
#!/usr/bin/env python3 # -*- coding: utf-8 -*- """ Created on 02/08/18 @author: XXX """ import unittest from RecSysFramework.DataManager.Reader import Movielens1MReader from RecSysFramework.DataManager.Splitter import Holdout, ColdItemsHoldout from RecSysFramework.DataManager.Splitter import WarmItemsKFold, ColdItemsKFold from RecSysFramework.DataManager.Splitter import LeaveKOut from RecSysFramework.Utils import invert_dictionary class SplitterTestCase(unittest.TestCase): def setUp(self): self.reader = Movielens1MReader() self.dataset = self.reader.load_data() def matrix_contained(self, new_URM, old_URM, new_mapper, old_mapper): new_mapper = invert_dictionary(new_mapper[0]), invert_dictionary(new_mapper[1]) old_URM.eliminate_zeros() nnz_row, nnz_col = new_URM.nonzero() for t in range(len(nnz_row)): row, col = old_mapper[0][new_mapper[0][nnz_row[t]]], old_mapper[1][new_mapper[1][nnz_col[t]]] self.assertEqual(old_URM[row, col], new_URM[nnz_row[t], nnz_col[t]], "Value {} in ({}, {}) of new URM is zero in old URM" .format(new_URM[nnz_row[t], nnz_col[t]], nnz_row[t], nnz_col[t])) def split_contained(self, URM_train, URM_test, URM_valid, new_mapper, sum_equals_original=False): URM_all = self.dataset.get_URM() old_mapper = self.dataset.get_URM_mapper() URM_sum = URM_train + URM_test if URM_valid is not None: URM_sum += URM_valid if sum_equals_original: self.assertEqual(len(URM_sum.data), len(URM_all.data), "Original URM and sum of train, test and validation have different number of entries") self.matrix_contained(URM_train, URM_all, new_mapper, old_mapper) self.matrix_contained(URM_test, URM_all, new_mapper, old_mapper) if URM_valid is not None: self.matrix_contained(URM_valid, URM_all, new_mapper, old_mapper) self.matrix_contained(URM_sum, URM_all, new_mapper, old_mapper) class SplitterHoldoutTest(SplitterTestCase): splits = [(0.6, 0.2, 0.2), (0.8, 0.2, 0.0)] def test_holdout(self): print("Holdout Test") for trio in self.splits: train_perc, test_perc, validation_perc = trio splitter = Holdout(train_perc=train_perc, test_perc=test_perc, validation_perc=validation_perc) if validation_perc > 0.0: train, test, validation = splitter.split(self.dataset) URM_valid = validation.get_URM() else: train, test = splitter.split(self.dataset) URM_valid = None URM_train = train.get_URM() URM_test = test.get_URM() self.split_contained(URM_train, URM_test, URM_valid, train.get_URM_mapper()) def test_cold_holdout(self): print("Cold Items Holdout Test") for trio in self.splits: train_perc, test_perc, validation_perc = trio splitter = ColdItemsHoldout(train_perc=train_perc, test_perc=test_perc, validation_perc=validation_perc) if validation_perc > 0.0: train, test, validation = splitter.split(self.dataset) URM_valid = validation.get_URM() else: train, test = splitter.split(self.dataset) URM_valid = None URM_train = train.get_URM() URM_test = test.get_URM() self.split_contained(URM_train, URM_test, URM_valid, train.get_URM_mapper()) def test_load_and_save_data(self): print("Holdout load and save Test") splitter = Holdout(train_perc=0.6, test_perc=0.2, validation_perc=0.2) train, test, validation = splitter.load_split(self.reader) splitter.save_split([train, test, validation]) class SplitterKFoldTest(SplitterTestCase): def test_kfold(self): print("K Fold Test") n_folds = 5 splitter = WarmItemsKFold(n_folds=n_folds) counter = 0 for train, test in splitter.split(self.dataset): URM_train = train.get_URM() URM_test = test.get_URM() self.split_contained(URM_train, URM_test, None, train.get_URM_mapper()) counter += 1 self.assertEqual(counter, n_folds, "Number of folds generated not consistent") def test_cold_kfold(self): print("Cold Items K Fold Test") n_folds = 5 splitter = ColdItemsKFold(n_folds=n_folds) counter = 0 for train, test in splitter.split(self.dataset): URM_train = train.get_URM() URM_test = test.get_URM() self.split_contained(URM_train, URM_test, None, train.get_URM_mapper()) counter += 1 self.assertEqual(counter, n_folds, "Number of folds generated not consistent") def test_load_and_save_data(self): print("K Fold load and save Test") splitter = WarmItemsKFold(n_folds=5) for train, test in splitter.load_split(self.reader): splitter.save_split([train, test]) class SplitterLeaveKOutTest(SplitterTestCase): def test_leavekout(self): print("Leave K Out Test") for k_value, with_validation in [(1, False), (5, True)]: splitter = LeaveKOut(k_value=k_value, with_validation=with_validation) if with_validation: train, test, validation = splitter.split(self.dataset) URM_valid = validation.get_URM() else: train, test = splitter.split(self.dataset) URM_valid = None URM_train = train.get_URM() URM_test = test.get_URM() self.split_contained(URM_train, URM_test, URM_valid, train.get_URM_mapper()) def test_load_and_save_data(self): print("Leave K Out load and save Test") splitter = LeaveKOut(k_value=1, with_validation=True) train, test, validation = splitter.load_split(self.reader) splitter.save_split([train, test, validation]) if __name__ == '__main__': unittest.main()
6,192
jpeg/huffman/core.py
alexa-infra/py-imagineer
1
2022858
""" Huffman table """ from collections import defaultdict from collections import namedtuple import heapq from .utils import byte_to_bits from .utils import rev_dict Node = namedtuple('Node', ['cargo', 'left', 'right']) def iter_nodes(node): """ Depth-first, left-to-right binary tree traversal """ stack = list() while stack or node: if node: stack.append(node) node = node.left else: node = stack.pop() yield node node = node.right def iter_leafs(root): """ Iterate throw leafs in binary tree For each leaf returns its value (cargo) and the path from root node to the leaf. Path is represented by (1, 0, 1) tuple, where 0 is left, 1 is right. """ parents = dict() leafs = list() node_is_leaf = lambda node: not node.left and not node.right for node in iter_nodes(root): if node_is_leaf(node): leafs.append(node) else: parents[node.left] = (node, 0) parents[node.right] = (node, 1) for node in leafs: cargo = node.cargo path = list() while node in parents: node, left_or_right = parents[node] path.append(left_or_right) path.reverse() yield cargo, tuple(path) def get_frequences(array): """ Get frequency of each element of array Returns dictionary where key is unique element of the array, value is the number of occurances of the element """ frequences = defaultdict(int) for element in array: frequences[element] += 1 return frequences def make_huffman_tree(freq): """ Make a binary-tree from array-element frequences, where left node is more probable than right node. So more frequent element will have shorter path from the root. Note: we sort at first by number of nodes in subtree and then by weight In this case leafs on n-th raw will have no gaps. It give us an advantage in more optimal size of resulting table. In general case this doesn't matter, so we can simply use only weight (frequency). """ nodes = {k: Node(k, None, None) for k, v in freq.items()} heap = [(0, v, nodes[k]) for k, v in freq.items()] heapq.heapify(heap) while len(heap) > 1: num1, weight1, node1 = heapq.heappop(heap) num2, weight2, node2 = heapq.heappop(heap) ttype = type(node1.cargo) node = Node(ttype(), node1, node2) heapq.heappush(heap, (num1+num2+2, weight1+weight2, node)) _, _, root = heap[0] return root def get_huffman_table(freq): """ Gives Huffman encoding table, by making a binary tree from frequences and then building a path of each node from the root. Returns a dictionary, where key is element, value is (1, 0, 1) tuple """ root = make_huffman_tree(freq) codes = {ch: path for ch, path in iter_leafs(root)} return codes def check_huffman_table(codes): """ Check huffman table for validity """ code = 0 revcodes = rev_dict(codes) codeslist = list(codes.values()) codeslist.sort(key=len) last_size = 0 for value in codeslist: size = len(value) if size != last_size: code = code << 1 last_size = size bits = byte_to_bits(code, size) if bits not in revcodes: return False code += 1 for i, value in enumerate(codeslist): size = len(value) for value2 in codeslist[i+1:]: if value == value2[:size]: return False return True
3,605
RLtoolkit/G/gtests1.py
AmiiThinks/rltoolkit
6
2023992
# G tests - color and font from RLtoolkit.g import * w = Gwindow(gdViewport=(0, 20, 600, 800)) # named colors colors = ['black', 'white', 'pink', 'red', 'orange', 'yellow', 'green', \ 'dark green', 'light blue', 'blue', 'purple', 'brown', 'tan', \ 'light gray', 'gray', 'dark gray', 'cyan', 'magenta'] i = 0 for c in colors: gdFillRect(w, i, 0, i + 20, 20, c) i += 20 gdDrawLine(w, 0, 21, 600, 21) # colors globals colors = [gBlack, gWhite, gPink, gRed, gOrange, gYellow, gGreen, \ gDarkGreen, gLightBlue, gBlue, gPurple, gBrown, gTan, \ gLightGray, gGray, gDarkGray, gCyan, gMagenta] i = 0 j = 22 for c in colors: gdFillRect(w, i, j, i + 20, j + 20, c) i += 20 gdDrawLine(w, 0, 43, 600, 43) # Now try calculating shades of one color given intensity in 256 range (red) i = 0 j = 44 for c in range(256): col = gColorRGB255(w, 255, 255 - c, 255 - c) gdFillRect(w, i, j, i + 20, j + 20, col) i += 20 if i > 580: i = 0 j += 20 j += 21 gdDrawLine(w, 0, j, 600, j) # Now try calculating black and white shades i = 0 j += 1 for c in range(256): col = gColorBW(w, float(c) / 256) gdFillRect(w, i, j, i + 20, j + 20, col) i += 20 if i > 580: i = 0 j += 20 j += 21 gdDrawLine(w, 0, j, 600, j) # Now try calculating shades of one color with intensities 0-1 (green) i = 0 j += 1 for c in range(256): col = gColorRGB(w, float(255 - c) / 256, 1.0, float(255 - c) / 256) gdFillRect(w, i, j, i + 20, j + 20, col) i += 20 if i > 580: i = 0 j += 20 j += 21 gdDrawLine(w, 0, j, 600, j) # change pen sizes to get thicker lines j += 5 p = gColorPen(w, 'red') gdDrawLine(w, 0, j, 600, j, p) j += 5 p2 = gColorPen(w, p, xsize=2) gdDrawLine(w, 0, j, 600, j, p2) j += 5 p3 = gColorPen(w, p, '', 'copy', 3, 2) gdDrawLine(w, 0, j, 600, j, p3) j += 5 gdDrawLine(w, 0, j, 600, j) # Draw lines and text with default color, color for view and specified color gSetColor(w, 'purple') gdDrawLine(w, 0, j + 5, 600, j + 5) gdDrawText(w, 'purple', None, 10, j + 20) gdDrawText(w, 'red', None, 100, j + 20, p2) gdDrawText(w, 'black', None, 190, j + 20, 'black') # check out fonts f = gFont('Times', 14, 'italic') gdDrawText(w, 'purple', f, 10, j + 50) f2 = gFont('Times', 14, 'bold') gdDrawText(w, 'red', f2, 100, j + 50, p2) f3 = gFont('Times', 14, 'bold italic') gdDrawText(w, 'black', f3, 190, j + 50, 'black') gStartEventLoop()
2,462
src/model_tools.py
ivallesp/abs
0
2023938
import torch import random import numpy as np from torch import nn from torch.optim.lr_scheduler import _LRScheduler def set_random_seed(seed): torch.manual_seed(seed) np.random.seed(seed) random.seed(seed) def initialize_weights(net): # https://discuss.pytorch.org/t/initializing-parameters-of-a-multi-layer-lstm/5791 for name, param in net.named_parameters(): if "bias" in name: nn.init.constant_(param, 0.0) elif "weight" in name: nn.init.kaiming_normal_(param) elif "emb" in name: nn.init.kaiming_normal_(param) class GradualWarmupScheduler(_LRScheduler): """Gradually warm-up(increasing) learning rate in optimizer. Borrowed from here https://github.com/ildoonet/pytorch-gradual-warmup-lr/blob/master/warmup_scheduler/scheduler.py Proposed in 'Accurate, Large Minibatch SGD: Training ImageNet in 1 Hour'. Args: optimizer (Optimizer): Wrapped optimizer. multiplier: target learning rate = base lr * multiplier if multiplier > 1.0. if multiplier = 1.0, lr starts from 0 and ends up with the base_lr. total_epoch: target learning rate is reached at total_epoch, gradually after_scheduler: after target_epoch, use this scheduler(eg. ReduceLROnPlateau) """ def __init__(self, optimizer, multiplier, total_epoch, after_scheduler=None): self.multiplier = multiplier if self.multiplier <= 1.0: raise ValueError("multiplier should be greater than 1.") self.total_epoch = total_epoch self.after_scheduler = after_scheduler self.finished = False super(GradualWarmupScheduler, self).__init__(optimizer) def get_lr(self): if self.last_epoch > self.total_epoch: if self.after_scheduler: if not self.finished: self.after_scheduler.base_lrs = [ base_lr * self.multiplier for base_lr in self.base_lrs ] self.finished = True return self.after_scheduler.get_last_lr() return [base_lr * self.multiplier for base_lr in self.base_lrs] lr = [ base_lr / self.multiplier + (base_lr - (base_lr / self.multiplier)) # Delta * (self.last_epoch - 1) / self.total_epoch for base_lr in self.base_lrs ] return lr def step(self, epoch=None, metrics=None): if self.finished and self.after_scheduler: if epoch is None: self.after_scheduler.step(None) else: self.after_scheduler.step(epoch - self.total_epoch) self._last_lr = self.after_scheduler.get_last_lr() else: return super(GradualWarmupScheduler, self).step(epoch)
2,833
bin/install.py
dingzg/onepanel
2
2024755
#!/usr/bin/env python2.6 #-*- coding: utf-8 -*- # Copyright [OnePanel] # # 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. """ Install script for OnePanel """ import os import sys import platform import shlex import subprocess import urllib2 import re import socket onepanel_downloadurl = 'https://github.com/dingzg/onepanel/archive/master.zip' paramiko_downloadurl = 'https://github.com/paramiko/paramiko/archive/release-1.7.5.zip' class Install(object): def __init__(self): if hasattr(platform, 'linux_distribution'): self.dist = platform.linux_distribution(full_distribution_name=0) else: self.dist = platform.dist() self.arch = platform.machine() if self.arch != 'x86_64': self.arch = 'i386' self.installpath = '/usr/local/onepanel' self.distname = self.dist[0].lower() self.version = self.dist[1] def _run(self, cmd, shell=False): if shell: return subprocess.call(cmd, shell=shell) else: return subprocess.call(shlex.split(cmd)) def check_platform(self): supported = True if self.distname == 'centos': if float(self.version) < 5.4: supported = False elif self.distname == 'redhat': if float(self.version) < 5.4: supported = False #elif self.distname == 'ubuntu': # if float(self.version) < 10.10: # supported = False #elif self.distname == 'debian': # if float(self.version) < 6.0: # supported = False else: supported = False return supported def install_python(self): if self.distname in ('centos', 'redhat'): # following this: http://fedoraproject.org/wiki/EPEL/FAQ if int(float(self.version)) == 5: epelrpm = 'epel-release-5-4.noarch.rpm' epelurl = 'http://download.fedoraproject.org/pub/epel/5/%s/%s' % (self.arch, epelrpm) # install fastestmirror plugin for yum fastestmirror = 'http://mirror.centos.org/centos/5/os/%s/CentOS/yum-fastestmirror-1.1.16-21.el5.centos.noarch.rpm' % (self.arch, ) elif int(float(self.version)) == 6: epelrpm = 'epel-release-6-7.noarch.rpm' epelurl = 'http://download.fedoraproject.org/pub/epel/6/%s/' % (self.arch, epelrpm) fastestmirror = 'http://mirror.centos.org/centos/6/os/%s/Packages/yum-plugin-fastestmirror-1.1.30-14.el6.noarch.rpm' % (self.arch, ) self._run('wget -nv -c %s' % epelurl) self._run('rpm -Uvh %s' % epelrpm) self._run('rpm -Uvh %s' % fastestmirror) self._run('yum -y install python26') if self.distname == 'centos': pass elif self.distname == 'redhat': pass elif self.distname == 'ubuntu': pass elif self.distname == 'debian': pass def install_paramiko(self): localpkg_found = False if os.path.exists(os.path.join(os.path.dirname(__file__), 'paramiko.zip')): localpkg_found = True else: self._run('wget -nv -c "%s" -O paramiko.zip' % paramiko_downloadurl) self._run('unzip -o paramiko.zip') if not localpkg_found: os.remove('paramiko.zip') self._run('cd paramiko-release-1.7.5;python setup.py install;cd ..', True) def install_onepanel(self): localpkg_found = False if os.path.exists(os.path.join(os.path.dirname(__file__), 'onepanel.zip')): # local install package found localpkg_found = True else: # or else install online print '* Downloading install package from www.onepanel.org' #f = urllib2.urlopen('http://www.onepanel.org/api/latest') #data = f.read() #f.close() #https://github.com/dingzg/onepanel/archive/master.zip #onepanel-master.zip #downloadurl = re.search('"download":"([^"]+)"', data).group(1).replace('\/', '/') self._run('wget -nv -c "%s" -O onepanel.zip' % onepanel_downloadurl) # uncompress and install it #self._run('mkdir onepanel') #self._run('tar zxmf onepanel.tar.gz -C onepanel') self._run('unzip onepanel.zip') if not localpkg_found: os.remove('onepanel.zip') # stop service print if os.path.exists('/etc/init.d/onepanel'): self._run('/etc/init.d/onepanel stop') # backup data and remove old code if os.path.exists('%s/data/' % self.installpath): self._run('cp -r %s/data/ onepanel-master/data/' % self.installpath, True) self._run('rm -rf %s' % self.installpath) # install new code self._run('mv onepanel-master %s' % self.installpath) self._run('chmod +x %s/bin/install_config.py %s/bin/start_server.py' % (self.installpath, self.installpath)) # install service initscript = '%s/bin/init.d/%s/onepanel' % (self.installpath, self.distname) self._run('cp %s /etc/init.d/onepanel' % initscript) if os.path.exists('%s/data/' % self.installpath)==False: self._run('mkdir %s/data/' % self.installpath) self._run('chmod +x /etc/init.d/onepanel') # start service if self.distname in ('centos', 'redhat'): #self._run('chkconfig onepanel on') self._run('service onepanel start') elif self.distname == 'ubuntu': pass elif self.distname == 'debian': pass def config(self, username, password): self._run('%s/bin/install_config.py username "%s"' % (self.installpath, username)) self._run('%s/bin/install_config.py password "%s"' % (self.installpath, password)) def detect_ip(self): s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM) s.connect(('www.baidu.com', 80)) ip = s.getsockname()[0] s.close() return ip def install(self): # check platform environment print '* Checking platform...', supported = self.check_platform() if not supported: print 'FAILED' print 'Unsupport platform %s %s %s' % self.dist sys.exit() else: print 'OK' # check python version print '* Checking python version ...', if sys.version_info[:2] == (2, 6): print 'OK' else: print 'FAILED' # install the right version print '* Installing python 2.6 ...' self.install_python() # check paramiko print '* Checking paramiko ...', try: import paramiko print 'OK' except: print 'FAILED' # install the right version print '* Installing paramiko ...' self.install_paramiko() # stop firewall if os.path.exists('/etc/init.d/iptables'): self._run('/etc/init.d/iptables stop') # get the latest onepanel version print '* Installing latest OnePanel' self.install_onepanel() # set username and password print print '============================' print '* INSTALL COMPLETED! *' print '============================' print username = 'onepanel' password = '<PASSWORD>' self.config(username, password) print print '* The URL of your OnePanel is:', print 'http://%s:6666/' % self.detect_ip() print pass def main(): print('==============================Warning==============================') print('If you want to update OnePanel,please copy install.py to other path and run it!') print('') continueflg = raw_input('Press "Y" to Continue or press "N" to Quit: ').strip() if continueflg in ('Y','y'): install = Install() install.install() else: exit if __name__ == "__main__": main()
8,731
cs15211/FindEventualSafeStates.py
JulyKikuAkita/PythonPrac
1
2024324
__source__ = 'https://leetcode.com/problems/find-eventual-safe-states/' # Time: O(N + E) # Space: O(N) # # Description: Leetcode # 802. Find Eventual Safe States # # In a directed graph, we start at some node and every turn, # walk along a directed edge of the graph. # If we reach a node that is terminal (that is, it has no outgoing directed edges), we stop. # # Now, say our starting node is eventually safe if and only if we must eventually walk to a terminal node. # More specifically, there exists a natural number K so that for any choice of where to walk, # we must have stopped at a terminal node in less than K steps. # # Which nodes are eventually safe? Return them as an array in sorted order. # # The directed graph has N nodes with labels 0, 1, ..., N-1, where N is the length of graph. # The graph is given in the following form: graph[i] is a list of labels j # such that (i, j) is a directed edge of the graph. # # Example: # Input: graph = [[1,2],[2,3],[5],[0],[5],[],[]] # Output: [2,4,5,6] # Here is a diagram of the above graph. # # Illustration of graph # # Note: # # graph will have length at most 10000. # The number of edges in the graph will not exceed 32000. # Each graph[i] will be a sorted list of different integers, # chosen within the range [0, graph.length - 1]. # import collections import unittest # 512ms 18.54% class Solution(object): def eventualSafeNodes(self, graph): """ :type graph: List[List[int]] :rtype: List[int] """ N = len(graph) safe = [False] * N graph = map(set, graph) rgraph = [set() for _ in xrange(N)] q = collections.deque() for i, js in enumerate(graph): if not js: q.append(i) for j in js: rgraph[j].add(i) while q: j = q.popleft() safe[j] = True for i in rgraph[j]: graph[i].remove(j) if len(graph[i]) == 0: q.append(i) return [i for i, v in enumerate(safe) if v] # 304ms 35.35% class Solution2(object): def eventualSafeNodes(self, graph): """ :type graph: List[List[int]] :rtype: List[int] """ WHITE, GRAY, BLACK = 0, 1, 2 color = collections.defaultdict(int) def dfs(node): if color[node] != WHITE: return color[node] == BLACK color[node] = GRAY for nei in graph[node]: if color[nei] == BLACK: continue if color[nei] == GRAY or not dfs(nei): return False color[node] = BLACK return True return filter(dfs, range(len(graph))) class TestMethods(unittest.TestCase): def test_Local(self): self.assertEqual(1, 1) if __name__ == '__main__': unittest.main() Java = ''' # Thought: https://leetcode.com/problems/find-eventual-safe-states/solution/ Approach #1: Reverse Edges [Accepted] Complexity Analysis Time Complexity: O(N + E), where N is the number of nodes in the given graph, and E is the total number of edges. Space Complexity: O(N) in additional space complexity. # 114ms 22.56% class Solution { public List<Integer> eventualSafeNodes(int[][] graph) { int N = graph.length; boolean[] safe = new boolean[N]; List<Set<Integer>> tmp = new ArrayList(); List<Set<Integer>> rgraph = new ArrayList(); for (int i = 0; i < N; ++i) { tmp.add(new HashSet()); rgraph.add(new HashSet()); } Queue<Integer> queue = new LinkedList(); for (int i = 0; i < N; i++) { if (graph[i].length == 0) queue.offer(i); for (int j : graph[i]) { tmp.get(i).add(j); rgraph.get(j).add(i); } } while (!queue.isEmpty()) { int j = queue.poll(); safe[j] = true; for (int i : rgraph.get(j)) { tmp.get(i).remove(j); if (tmp.get(i).isEmpty()) queue.offer(i); } } List<Integer> ans = new ArrayList(); for (int i = 0; i < N; i++) { if (safe[i]) ans.add(i); } return ans; } } Approach #2: Depth-First Search [Accepted] Complexity Analysis Time Complexity: O(N + E), where N is the number of nodes in the given graph, and E is the total number of edges. Space Complexity: O(N) in additional space complexity. # 11ms 97.36% class Solution { public List<Integer> eventualSafeNodes(int[][] graph) { int N = graph.length; int[] color = new int[N]; List<Integer> ans = new ArrayList(); for (int i = 0; i < N; i++) { if (dfs(i, color, graph)) ans.add(i); } return ans; } // colors: WHITE 0, GRAY 1, BLACK 2; private boolean dfs(int node, int[] color, int[][] graph) { if (color[node] > 0) return color[node] == 2; color[node] = 1; for (int nei: graph[node]) { if (color[node] == 2) continue; if (color[nei] == 1 || !dfs(nei, color, graph)) return false; } color[node] = 2; return true; } } # https://leetcode.com/problems/find-eventual-safe-states/discuss/120633/Java-Solution-(DFS-andand-Topological-Sort) # topological sort # 62ms 36.36% class Solution { public List<Integer> eventualSafeNodes(int[][] graph) { int n = graph.length; int[] degree = new int [n]; Set<Integer>[] map = new HashSet[n]; for (int i = 0; i < n; i++) map[i] = new HashSet(); for (int i = 0; i < n; i++) { for (int node : graph[i]) { map[node].add(i); degree[i]++; } } Queue<Integer> queue = new LinkedList(); Set<Integer> set = new HashSet(); for (int i = 0; i < n; i++) { if (degree[i] == 0) { set.add(i); queue.add(i); } } while (!queue.isEmpty()) { int node = queue.poll(); set.add(node); for (int nei : map[node]) { degree[nei]--; if (degree[nei] == 0) { queue.add(nei); } } } List<Integer> ans = new ArrayList(set); Collections.sort(ans); return ans; } } # https://leetcode.com/problems/find-eventual-safe-states/discuss/119871/Straightforward-Java-solution-easy-to-understand! # 14ms 60.33% class Solution { // value of color represents three states: static int NOT_V = 0; // 0:have not been visited static int SAFE = 1; // 1:safe static int LOOP = 2; // 2:unsafe public List<Integer> eventualSafeNodes(int[][] graph) { List<Integer> res = new ArrayList(); int[] color = new int[graph.length]; for (int i = 0; i < graph.length; i++) { if (dfs(graph, color, i)) res.add(i); } return res; } private boolean dfs(int[][] graph, int[] color, int start) { if (color[start] == LOOP) return false; if (color[start] == SAFE) return true; color[start] = LOOP; for (int nei : graph[start]) { if (!dfs(graph, color, nei)) return false; } color[start] = SAFE; return true; } } '''
7,463
girder_plugin/arbor_nova/__init__.py
girder/arbor_tasks
4
2022919
#!/usr/bin/env python # -*- coding: utf-8 -*- from girder.plugin import getPlugin, GirderPlugin from girder.models.user import User from .client_webroot import ClientWebroot from . import rest class ArborNovaGirderPlugin(GirderPlugin): DISPLAY_NAME = '<NAME>' def _create_anonymous_user(self): ANONYMOUS_USER = 'anonymous' ANONYMOUS_PASSWORD = '<PASSWORD>' anon_user = User().findOne({ 'login': ANONYMOUS_USER }) if not anon_user: anon_user = User().createUser( login=ANONYMOUS_USER, password=<PASSWORD>, firstName='Public', lastName='User', email='<EMAIL>', admin=False, public=False) anon_user['status'] = 'enabled' anon_user = User().save(anon_user) return anon_user def load(self, info): # Relocate Girder info['serverRoot'], info['serverRoot'].girder = (ClientWebroot(), info['serverRoot']) info['serverRoot'].api = info['serverRoot'].girder.api self._create_anonymous_user() getPlugin('jobs').load(info) info['apiRoot'].arbor_nova = rest.ArborNova()
1,289
rat-sql-gap/bart/model.py
JuruoMP/Text2SQL-Multiturn
0
2023278
import torch import torch.nn as nn from transformers import BartModel, BartTokenizer, BartConfig class SQLBartModel(nn.Module): def __init__(self): super().__init__() config_name = 'facebook/bart-large' self.bart_config = BartConfig.from_pretrained(config_name, cache_dir='bart/cache') self.bart_tokenizer = BartTokenizer.from_pretrained(config_name, cache_dir='bart/cache') self.bart_model = BartModel.from_pretrained(config_name, cache_dir='bart/cache') self.register_buffer("final_logits_bias", torch.zeros((1, self.bart_model.shared.num_embeddings))) self.lm_head = nn.Linear(self.bart_config.d_model, self.bart_model.shared.num_embeddings, bias=False) def forward(self, x): bart_outputs = self.bart_model( input_ids=x['input_ids'], attention_mask=x['attention_mask'], decoder_input_ids=x['decoder_input_ids'], decoder_attention_mask=x['decoder_attention_mask'] ) lm_logits = self.lm_head(bart_outputs[0]) + self.final_logits_bias return lm_logits
1,100
Batch_5_August2021/Week4/Kodlar/main.py
seccily/Applied-AI-Study-Group
40
2023936
import numpy as np import pandas as pd import mlflow from lightgbm import LGBMClassifier from sklearn.metrics import classification_report, average_precision_score, accuracy_score, f1_score, roc_auc_score from ray import tune from ray.tune.integration.mlflow import mlflow_mixin from ray.tune.suggest.optuna import OptunaSearch from ray.tune.suggest.ax import AxSearch from helper_funcs import give_data import logging logging.basicConfig(level=logging.WARN) logger = logging.getLogger(__name__) experiment_name = "LGBM + SMOTETomek + E50 + Ax " fet_sel_dict = {0: "No Selection", 1: "KBest", 2: "Selector"} #experiment_name = "Default" @mlflow_mixin def LightGBMCallback(env): """Assumes that `valid_0` is the target validation score.""" _, metric, score, _ = env.evaluation_result_list[0] mlflow.log_metric(metric, score) @mlflow_mixin def objective(config): # Get and log parameters params = { "num_leaves": config["num_leaves"], "learning_rate": config["learning_rate"], "n_estimators": config["n_estimators"], "objective": config["objective"], "reg_alpha": config["reg_alpha"], "reg_lambda": config["reg_lambda"], "tree_learner": config["tree_learner"], "subsample" : config["subsample"], "subsample_freq": config["subsample_freq"], "feature_sel": fet_sel_dict[config["feature_sel"]] } mlflow.log_params(params) model = LGBMClassifier(**params, random_state=0) X_train, X_test, y_train, y_test = give_data(feature_sel=config["feature_sel"]) model.fit(X_train, np.ravel(y_train), eval_set=[(X_test, np.ravel(y_test))], verbose=False, early_stopping_rounds=50, callbacks=[LightGBMCallback]) eval_results = classification_report(np.ravel(y_test), model.predict(X_test), output_dict=True) eval_results["accuracy"] = accuracy_score(y_test, model.predict(X_test)) eval_results["auroc"] = roc_auc_score(y_test, model.predict_proba(X_test)[:, 1]) mlflow.log_metric("val_auroc", eval_results["auroc"]) fold_accuracy = eval_results["accuracy"] mlflow.log_metric("val_accuracy", fold_accuracy) fold_f1 = eval_results["1"]["f1-score"] mlflow.log_metric("val_f1-score-1", fold_f1) mlflow.log_metric("val_f1-score-0", eval_results["0"]["f1-score"]) fold_precision = eval_results["1"]["precision"] mlflow.log_metric("val_precision", fold_precision) fold_recall = eval_results["1"]["recall"] mlflow.log_metric("val_recall", fold_recall) eval_results_tr = classification_report(np.ravel(y_train), model.predict(X_train), output_dict=True) eval_results_tr["accuracy"] = accuracy_score(y_train, model.predict(X_train)) fold_accuracy_tr = eval_results_tr["accuracy"] mlflow.log_metric("tr_accuracy", fold_accuracy_tr) fold_f1_tr = eval_results_tr["1"]["f1-score"] mlflow.log_metric("tr_f1-score", fold_f1_tr) fold_precision_tr = eval_results_tr["1"]["precision"] mlflow.log_metric("tr_precision", fold_precision_tr) fold_recall_tr = eval_results_tr["1"]["recall"] mlflow.log_metric("tr_recall", fold_recall_tr) tune.report(auroc = eval_results["auroc"], done=True) def tune_fn(): mlflow.set_experiment(experiment_name=experiment_name) optuna_search = OptunaSearch( metric="auroc", mode="max") ax_search = AxSearch( metric="auroc", mode="max") tune.run( objective, name="mlflow_gbdt", num_samples=65, config={ "num_leaves": tune.randint(5, 95), "learning_rate": tune.loguniform(1e-4, 1.0), "n_estimators": tune.randint(100, 100000), "subsample" : tune.loguniform(0.01, 1.0), "subsample_freq": tune.randint(1, 5), "objective": "binary", "reg_alpha": tune.loguniform(1e-4, 1.0), "reg_lambda": tune.loguniform(1e-4, 1.0), "tree_learner": "feature", "feature_sel": 0, "mlflow": { "experiment_name": experiment_name, "tracking_uri": mlflow.get_tracking_uri() } }, search_alg=optuna_search ) if __name__=="__main__": tune_fn() # "n_components": tune.qrandint(20, 1000, 10), # "gamma": tune.uniform(0.1, 2.0),
4,353
accounting/jslink.py
jacob22/accounting
0
2023562
# Copyright 2019 Open End AB # # 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 logging log = logging.getLogger(__name__) from bson.errors import InvalidId from bson.objectid import ObjectId import os import time import uuid import simplejson import werkzeug import flask from pytransact.object.attribute import BlobVal from pytransact.contextbroker import ContextBroker from pytransact import link as Link from pytransact import mongo try: from cStringIO import StringIO except ImportError: from io import StringIO StringIOs = StringIO, type(StringIO()) #, io.BytesIO def simpleResponse(code, stream): return werkzeug.Response(response=stream, status=code) class JsLink(object): """ resource to create python endpoint for JsLink callback system """ version = 2 TOUCH_INTERVAL = 60 * 60 def __init__(self, linkFactory, registerClient=None, logout=None): """ linkFactory - factory function which takes the request and returns a Link subclass """ self.linkFactory = linkFactory self.registerClient = registerClient self.logout = logout @property def database(self): return ContextBroker().context.database def render(self, request): try: messages = request.json['messages'] except (TypeError, KeyError): raise werkzeug.exceptions.UnprocessableEntity() resp = [] for msg in messages: msgType = msg['type'] meth = getattr(self, '_msg_%s' % msgType) clientId = msg.get('clientId') if clientId is not None: try: clientId = ObjectId(msg['clientId']) except (InvalidId, KeyError): return simpleResponse(403, "Unknown clientId") answ = meth(clientId, msg, request) resp.append(answ) return flask.jsonify(results=resp) def _msg_client_deactivate(self, clientId, msg, request): log.debug('client deactivate %s', clientId) database = self.database mongo.remove(database.links, {'client': clientId}, multi=True) mongo.remove(database.clients, {'_id': clientId}) return {'client_deactivate': str(clientId)} def _msg_handshake(self, client, msg, request): clientId = mongo.insert(self.database.clients, {'updates': [], 'timestamp': time.time()}) if self.registerClient: self.registerClient(clientId, request) return { 'type' : 'handshake', 'version' : self.version, 'clientId' : str(clientId), 'extraInfo': {} } def _msg_poll(self, clientId, msg, request): log.debug('client poll %s', clientId) updated_or_outdated = False for link in self.linkFactory.iter({'client': clientId, 'outdatedBy': {'$ne': None}}): link.run() updated_or_outdated = True now = time.time() if not updated_or_outdated: updated_or_outdated = mongo.find( self.database.clients, {'_id': clientId, '$or': [{'updates': {'$ne': []}}, {'timestamp': {'$lt': now - self.TOUCH_INTERVAL}}]}, projection=[]).count() if updated_or_outdated: client = mongo.find_and_modify(self.database.clients, {'_id': clientId}, {'$set': {'updates': [], 'timestamp': now}}, projection={'updates'}) # Only dereference, files should not be deleted yet, as they are # used when json serializing. # Will be deleted by gridfs garbage collector. mongo.update(self.database.blobvals.files, {'metadata.references.value': {'$in': [clientId]}}, {'$pull': {'metadata.references.value': clientId}}, multi=True) return client['updates'] return [] def _msg_link(self, client, msg, request): linkId = msg['id'] log.debug("link start %s %s", client, linkId) args = dict([(str(k),v) for (k,v) in msg['args'].items()]) link = self.linkFactory.create(msg['name'], client, linkId, **args) link.run() return {'new': linkId} def _msg_upload(self, client, msg, request): import ntpath linkId = msg['id'] log.debug("link start %s %s", client, linkId) args = dict([(str(k),v) for (k,v) in msg['args'].items()]) value = [] for fkey, fobj in request.files.iteritems(multi=True): if not fobj.filename: pos = fobj.tell() fobj.seek(0, os.SEEK_END) if fobj.tell() == 0: continue fobj.seek(pos) value.append(BlobVal(fobj, filename=ntpath.basename(fobj.filename), content_type=fobj.content_type)) args.setdefault('params',{}).setdefault('args',[]).append(value) link = self.linkFactory.create(msg['name'], client, linkId, **args) link.run() return {'new': linkId} def _msg_link_update(self, client, msg, request): linkId = msg['id'] log.debug("link update %s %s", client, linkId) link = self.linkFactory.create(None, client, linkId) if link is None: return {} args = dict([(str(k),v) for (k,v) in msg['args'].items()]) getattr(link, msg['name'])(**args) return {'link_update': linkId} def _msg_grant(self, client, msg, request): toid = ObjectId(msg['toid']) auth = str(uuid.uuid4()) log.debug('grant %s %s %s', client, toid, auth) self.database.grants.insert({'toid': toid, 'auth': auth, 'timestamp': time.time()}) return {'auth': auth} def _msg_link_deactivate(self, client, msg, request): linkId = msg['id'] coll = self.database.links link = self.linkFactory.create(None, client, linkId) log.debug("link end %s %s", client, linkId) if link: link.remove() return {'link_deactivate': linkId} else: return {} def _msg_logout(self, client, msg, request): if self.logout: self.logout(client)
7,113
cron/closeout_listings.py
slavik81/market43
1
2024284
#!/usr/bin/python import MySQLdb db = MySQLdb.connect(host="localhost", user="root", passwd="<PASSWORD>", db="market43") cursor = db.cursor() cursor.execute("""SELECT ListingId, ListingUserId, ListedItemId FROM listing WHERE CURRENT_TIMESTAMP > ExpiryTimestamp AND Open <> 0 """) db.commit() biddercursor = db.cursor() writecursor = db.cursor() numrows = int(cursor.rowcount) for x in range(0, numrows): row = cursor.fetchone() item = row[2] seller = row[1] listingid = row[0] biddercursor.execute("""SELECT Bidder, Value FROM bid WHERE Listing = """ + str(listingid) + " ORDER BY Value DESC") winner = 0 saleprice = 0 numbidderrows = int(cursor.rowcount) for y in range(numbidderrows): try: bidderrow = biddercursor.fetchone() winner = bidderrow[0] saleprice = bidderrow[1] break; except: break; if winner > 0: print "transfering " + str(item) + ":" + str(saleprice) + " between " + str(seller) + ":" + str(winner) writecursor.execute("UPDATE item SET OwnerUserId = " + str(winner) + " WHERE ItemId = """ + str(item)) writecursor.execute("""INSERT INTO transaction ( NetBalanceChange, TransactionType, TransactionUser) values (-""" + str(saleprice) + ", 0, " + str(winner) + ")") writecursor.execute("""INSERT INTO transaction ( NetBalanceChange, TransactionType, TransactionUser) values (""" + str(saleprice) + ", 0, " + str(seller) + ")") writecursor.execute("UPDATE listing SET Open=false WHERE ListingId = " + str(listingid)) print "closing transaction " + str(listingid) db.commit()
1,620
acwingcli/config.py
jasonsun0310/acwingcli
0
2024562
from colorama import Fore, Back, Style, init import acwingcli.commandline_writer as cmdwrite import sys import os import json package_data_file = os.path.join(os.path.dirname(__file__), 'assets/data.json') def input_with_default(title_name, default): path = default if str(input(Fore.LIGHTCYAN_EX + Style.BRIGHT + 'default {} is {}, accept? [y/n] '.format(title_name, path))).lower() == 'n': path = str(input('enter custom {}: '.format(title_name))) sys.stdout.write(Style.RESET_ALL) sys.stdout.flush() return path def setup_assistant(): print() config_path = input_with_default('config path', os.path.join(os.path.expanduser('~'), '.acwing/')) cache_path = os.path.join(config_path, 'cache') problembook_path = input_with_default('problembook path', os.path.join(os.path.expanduser('~'), 'acwing-problembook/')) submission_template_path = input_with_default('submission template path', os.path.join(problembook_path, 'submission_templates/')) default_language = input_with_default('default language', 'C++') if not os.path.exists(config_path): os.makedirs(config_path) if not os.path.exists(problembook_path): os.makedirs(problembook_path) if not os.path.exists(submission_template_path): os.makedirs(submission_template_path) if not os.path.exists(cache_path): os.makedirs(cache_path) with open(os.path.join(os.path.dirname(__file__), 'assets/data.json'), 'w') as f: json.dump({'config_path' : config_path}, f) f.close() with open(config_path + 'config.json', 'w') as f: json.dump({'path_problem_book_folder' : problembook_path, 'path_problem_cache_file' : os.path.join(config_path, 'cache/problem.json'), 'path_cookie_file' : os.path.join(config_path, 'cache/cookie'), 'path_submission_template_files' : submission_template_path, 'default_language' : default_language}, f) f.close() def load_problem_cache(path): try: with open(path, 'r') as f: problem_cache = dict(map(lambda kv : (int(kv[0]), kv[1]), json.load(f).items())) return problem_cache except FileNotFoundError: return {} def load_package_data(): try: with open(package_data_file, 'r') as f: return json.load(f) except Exception as e: print(e) return None def load_config_data(): package_data = load_package_data() if package_data is None or not 'config_path' in package_data.keys(): setup_assistant() package_data = load_package_data() if not os.path.exists(package_data['config_path']): os.makedirs(package_data['config_path']) config_file_path = os.path.join(package_data['config_path'], 'config.json') with open(config_file_path, 'r') as f: config_data = json.load(f) problem_cache_file_path = config_data['path_problem_cache_file'] path_problem_book = config_data['path_problem_book_folder'] path_cookie = config_data['path_cookie_file'] cmdwrite.client_debug('config data: {}'.format(config_data)) problem_cache = load_problem_cache(problem_cache_file_path) if problem_cache == {}: import acwingcli.update acwingcli.update.problem_list(problem_cache_file_path, path_cookie) problem_cache = load_problem_cache(problem_cache_file_path) # cmdwrite.client_debug('cache updated, ' + str(problem_cache)) return (config_data, problem_cache_file_path, path_problem_book, path_cookie, problem_cache) config_data, problem_cache_file_path, path_problem_book, path_cookie, problem_cache = load_config_data() def reload(): config_data, problem_cache_file_path, path_problem_book, path_cookie, problem_cache = load_config_data()
4,095
src/database/base.py
week-with-me/quiz-server
0
2024809
from datetime import datetime from sqlalchemy import Column, DateTime, Integer, func from sqlalchemy.ext.declarative import as_declarative, declared_attr @as_declarative() class Base: id: int = Column('id', Integer, primary_key=True, autoincrement=True) created_at: datetime = Column( 'created_at', DateTime(timezone=True), default = func.now() ) updated_at: datetime = Column('updated_at', DateTime(timezone=True)) deleted_at: datetime = Column('deleted_at', DateTime(timezone=True)) @declared_attr def __tablename__(cls): return cls.__name__.lower() + 's'
625
burp_plugins/filter_plugins/copsf_burp.py
corpusops/roles
0
2024773
#!/usr/bin/env python # -*- coding: utf-8 -*- from __future__ import absolute_import from __future__ import division from __future__ import print_function def copsfburp_get_cname(avars, hvars, *args, **kwargs): return hvars.get('burp_cname', '') or hvars['inventory_hostname'] def copsfburp_get_cname_and_profile(avars, hvars, profile_key=None, *args, **kwargs): cname = copsfburp_get_cname(avars, hvars, *args, **kwargs) if profile_key is None: profile_key = 'burp_client_profile' if profile_key in ['burp_clientside_profile']: profile = None else: profile = avars.get('ansible_virtualization_type', None) in [ 'docker', 'lxc', 'container'] and 'vm' or 'baremetal' try: if profile_key is None: raise KeyError('next') profile = hvars[profile_key] except KeyError: try: hvars['cops_burpclientserver_profiles_{0}'.format(cname)] profile = cname except KeyError: try: avars['cops_burpclientserver_profiles_{0}'.format(cname)] profile = cname except KeyError: pass return cname, profile def copsfburp_finish_settings(data, prefixmode, hvars, *args, **kwargs): prefixes = { 'client': 'burp_client_conf_', 'server': 'burp_client_', } for k in ['restore_clients', 'custom_lines']: val = hvars.get(prefixes[prefixmode] + k, None) if val is not None: data.update({k: val}) data.update(hvars.get(prefixes['client'] + 'extras', {})) return data __funcs__ = { 'copsfburp_get_cname': copsfburp_get_cname, 'copsfburp_get_cname_and_profile': copsfburp_get_cname_and_profile, 'copsfburp_finish_settings': copsfburp_finish_settings, } class FilterModule(object): def filters(self): return __funcs__ # vim:set et sts=4 ts=4 tw=80
1,955
exercises/exc_01_11.py
tuomastik/spacy-course
4
2024402
import spacy # Import the Matcher from spacy.____ import ____ nlp = spacy.load("en_core_web_sm") doc = nlp("New iPhone X release date leaked as Apple reveals pre-orders by mistake") # Initialize the Matcher with the shared vocabulary matcher = ____(____.____) # Create a pattern matching two tokens: "iPhone" and "X" pattern = [____] # Add the pattern to the matcher ____.____("IPHONE_X_PATTERN", None, ____) # Use the matcher on the doc matches = ____ print("Matches:", [doc[start:end].text for match_id, start, end in matches])
536
integration_test/test_all.py
cffbots/muscle3
11
2024056
from collections import OrderedDict import numpy as np from ymmsl import (Component, Conduit, Configuration, Model, Operator, Settings) from libmuscle import Grid, Instance, Message from libmuscle.runner import run_simulation def macro(): """Macro model implementation. """ instance = Instance({ Operator.O_I: ['out[]'], Operator.S: ['in[]']}) while instance.reuse_instance(): # f_init assert instance.get_setting('test1') == 13 # o_i assert instance.is_vector_port('out') for slot in range(10): instance.send('out', Message(0.0, 10.0, 'testing'), slot) # s/b for slot in range(10): msg = instance.receive('in', slot) assert msg.data['string'] == 'testing back' assert msg.data['int'] == 42 assert msg.data['float'] == 3.1416 assert msg.data['grid'].array.dtype == np.float64 assert msg.data['grid'].array[0, 1] == 34.0 def micro(): """Micro model implementation. """ instance = Instance({ Operator.F_INIT: ['in'], Operator.O_F: ['out']}) while instance.reuse_instance(): # f_init assert instance.get_setting('test3', 'str') == 'testing' assert instance.get_setting('test4', 'bool') is True assert instance.get_setting('test6', '[[float]]')[0][1] == 2.0 msg = instance.receive('in') assert msg.data == 'testing' # o_f result = { 'string': 'testing back', 'int': 42, 'float': 3.1416, 'grid': Grid(np.array([[12.0, 34.0, 56.0], [1.0, 2.0, 3.0]]))} instance.send('out', Message(0.1, None, result)) def test_all(log_file_in_tmpdir): """A positive all-up test of everything. """ elements = [ Component('macro', 'macro_impl'), Component('micro', 'micro_impl', [10])] conduits = [ Conduit('macro.out', 'micro.in'), Conduit('micro.out', 'macro.in')] model = Model('test_model', elements, conduits) settings = Settings(OrderedDict([ ('test1', 13), ('test2', 13.3), ('test3', 'testing'), ('test4', True), ('test5', [2.3, 5.6]), ('test6', [[1.0, 2.0], [3.0, 1.0]])])) configuration = Configuration(model, settings) implementations = {'macro_impl': macro, 'micro_impl': micro} run_simulation(configuration, implementations)
2,585
python_face_swap/utils.py
ForrestPi/FaceSolution
1
2024151
import numpy as np import cv2 import models from dlib import rectangle import NonLinearLeastSquares def getNormal(triangle): a = triangle[:, 0] b = triangle[:, 1] c = triangle[:, 2] axisX = b - a axisX = axisX / np.linalg.norm(axisX) axisY = c - a axisY = axisY / np.linalg.norm(axisY) axisZ = np.cross(axisX, axisY) axisZ = axisZ / np.linalg.norm(axisZ) return axisZ def flipWinding(triangle): return [triangle[1], triangle[0], triangle[2]] def fixMeshWinding(mesh, vertices): for i in range(mesh.shape[0]): triangle = mesh[i] normal = getNormal(vertices[:, triangle]) if normal[2] > 0: mesh[i] = flipWinding(triangle) return mesh def getShape3D(mean3DShape, blendshapes, params): #skalowanie s = params[0] #rotacja r = params[1:4] #przesuniecie (translacja) t = params[4:6] w = params[6:] #macierz rotacji z wektora rotacji, wzor Rodriguesa R = cv2.Rodrigues(r)[0] shape3D = mean3DShape + np.sum(w[:, np.newaxis, np.newaxis] * blendshapes, axis=0) shape3D = s * np.dot(R, shape3D) shape3D[:2, :] = shape3D[:2, :] + t[:, np.newaxis] return shape3D def getMask(renderedImg): mask = np.zeros(renderedImg.shape[:2], dtype=np.uint8) def load3DFaceModel(filename): faceModelFile = np.load(filename) mean3DShape = faceModelFile["mean3DShape"] mesh = faceModelFile["mesh"] idxs3D = faceModelFile["idxs3D"] idxs2D = faceModelFile["idxs2D"] blendshapes = faceModelFile["blendshapes"] mesh = fixMeshWinding(mesh, mean3DShape) return mean3DShape, blendshapes, mesh, idxs3D, idxs2D def getFaceTextureCoords(img, mean3DShape, blendshapes, idxs2D, idxs3D, detector, predictor): projectionModel = models.OrthographicProjectionBlendshapes(blendshapes.shape[0]) keypoints = getFaceKeypoints(img, detector, predictor)[0] modelParams = projectionModel.getInitialParameters(mean3DShape[:, idxs3D], keypoints[:, idxs2D]) modelParams = NonLinearLeastSquares.GaussNewton(modelParams, projectionModel.residual, projectionModel.jacobian, ([mean3DShape[:, idxs3D], blendshapes[:, :, idxs3D]], keypoints[:, idxs2D]), verbose=0) textureCoords = projectionModel.fun([mean3DShape, blendshapes], modelParams) return textureCoords
2,315
ssrlsim/__init__.py
tangkong/ssrlsim
0
2023999
from ._version import get_versions __version__ = get_versions()['version'] del get_versions import os import numpy as np import random from pathlib import Path import uuid from ophyd import Signal from ophyd.sim import SynSignal from ophyd.areadetector.filestore_mixins import resource_factory import tifffile import h5py # Basic signals # TODO: sort out file formats into trigger mixins? class SynTiffFilestore(SynSignal): def trigger(self): # not running at the moment.... but super.trigger() is. tmpRoot = Path(self.fstore_path) tmpPath = 'tmp' os.makedirs(tmpRoot / tmpPath, exist_ok=True) st = super().trigger() # re-evaluates self._func, puts into value # Returns NullType ret = super().read() # Signal.read() exists, not SynSignal.read() # But using Signal.read() does not allow uid's to be passed into mem. val = ret[self.name]['value'] # AD_TIFF handler generates filename by populating template # self.template % (self.path, self.filename, self.point_number) self.point_number += 1 resource, datum_factory = resource_factory( spec='AD_TIFF', root=tmpRoot, resource_path=tmpRoot / tmpPath, resource_kwargs={'template': '%s%s_%d.tiff' , 'filename': f'{uuid.uuid4()}'}, path_semantics='windows') datum = datum_factory({'point_number': self.point_number}) self._asset_docs_cache.append(('resource', resource)) self._asset_docs_cache.append(('datum', datum)) fname = (resource['resource_kwargs']['filename'] + f'_{self.point_number}.tiff') fpath = Path(resource['root']) / resource['resource_path'] / fname # for tiff spec tifffile.imsave(fpath, val) # replace 'value' in read dict with some datum id ret[self.name]['value'] = datum['datum_id'] self._last_ret = ret return st class SynHDF5Filestore(SynSignal): def trigger(self): # not running at the moment.... but super.trigger() is. tmpRoot = Path(self.fstore_path) tmpPath = 'tmp' os.makedirs(tmpRoot / tmpPath, exist_ok=True) st = super().trigger() # re-evaluates self._func, puts into value # Returns NullType ret = super().read() # Signal.read() exists, not SynSignal.read() # But using Signal.read() does not allow uid's to be passed into mem. val = ret[self.name]['value'] self.point_number += 1 fn = f'{uuid.uuid4()}.h5' resource, datum_factory = resource_factory( spec='XSP3', root=tmpRoot, resource_path=tmpRoot / tmpPath / fn, resource_kwargs={}, # Handler takes only one 'filename' argument, which is pulled from the... path_semantics='windows') datum = datum_factory({}) print(resource) self._asset_docs_cache.append(('resource', resource)) self._asset_docs_cache.append(('datum', datum)) fpath = Path(resource['root']) / resource['resource_path'] # for h5 spec with h5py.File(fpath, 'w') as f: e = f.create_group('/entry/instrument/detector') dset = e.create_dataset('data', data=val) # replace 'value' in read dict with some datum id ret[self.name]['value'] = datum['datum_id'] self._last_ret = ret return st class ArraySynSignal(SynSignal): """ Base class for synthetic array signals. Same interface as a normal ArraySignal, but with simulated data and filestore """ _asset_docs_cache = [] _last_ret = None point_number = 0 def __init__(self, fstore_path=None, *args, **kwargs): self.fstore_path = fstore_path super(ArraySynSignal, self).__init__(*args, **kwargs) def describe(self): ret = super().describe() ret[self.name]['external'] = 'FILESTORE:' return ret def read(self): '''Put the status of the signal into a simple dictionary format for data acquisition Returns ------- dict ''' # Appears to break things, throw resource sentinel issue... # need to initialize sentinel when starting RunEngine # Is ostensibly the same as Signal.read()?... if self._last_ret is not None: return self._last_ret # return {self.name: {'value': self._last_ret, # 'timestamp': self.timestamp}} else: # If detector has not been triggered already raise Exception('read before being triggered') # return {self.name: {'value': self.get(), # 'timestamp': self.timestamp}} def collect_asset_docs(self): items = list(self._asset_docs_cache) self._asset_docs_cache.clear() for item in items: yield item # position generator def gen_wafer_locs(shape='circle', radius=10): """ Create square grid of locations, with spacing of 1 between return lists of x, y locations """ vals = np.arange(-radius, radius+1, 1) xv, yv = np.meshgrid(vals, vals) x = xv.flatten() y = yv.flatten() if shape == 'circle': xout = [] #np.array([]) yout = [] # np.array([]) for i in range(len(x)): if (x[i]**2 + y[i]**2) <= radius**2: xout.append(x[i]) yout.append(y[i]) return xout, yout else: return x, y
5,701
examples/csv_parse_entity.py
raipc/atsd-api-python
20
2024538
import pandas as pd from atsd_client import connect from atsd_client.models import Entity from atsd_client.services import EntitiesService def read_csv(path): return pd.read_csv(path, sep=',', dtype=str) # Connect to ATSD # connection = connect_url('https://atsd_hostname:8443', 'username', 'password') connection = connect('/path/to/connection.properties') entities_service = EntitiesService(connection) df = read_csv('Entity.csv') fields_dict = { 'asset_name': 'label', 'asset_path': 'name' } time_zone_dict = { 'USRI': 'EDT', 'PRJU': 'PRT' } time_zone_field = 'site_is_code' for index, row in df.where(pd.notnull(df), None).iterrows(): row_dict = row.to_dict() fields_columns = {k: v for k, v in row_dict.iteritems() if k in fields_dict and row_dict[k] is not None} entity_params = dict(map(lambda kv: (fields_dict[kv[0]], kv[1]), fields_columns.iteritems())) if time_zone_field in row_dict and row_dict[time_zone_field] in time_zone_dict: site_code = row_dict[time_zone_field] entity_params['time_zone'] = time_zone_dict[site_code] entity_params['tags'] = dict( {k: v for k, v in row_dict.iteritems() if k not in fields_dict and row_dict[k] is not None}) entity = Entity(**entity_params) print(entity) # entities_service.create_or_replace(entity)
1,371
import_playlists.py
arru/plex-utilities
1
2024195
import ImportUtils import plexapi.playlist CONFIGURATION = ImportUtils.get_configuration() plex = ImportUtils.PlexWrapper(CONFIGURATION) MUSIC_SECTION = plex.server.library.section('Music') plex_tracks = plex.get_tracks_dict() itunes = ImportUtils.ItunesWrapper(CONFIGURATION) itunesPlaylists=itunes.library.getPlaylistNames() print("[INFO] Getting ready to import %d iTunes playlists" % len(itunesPlaylists)) nonempty_playlists_counter = 0 not_found_set = set() for playlist in itunesPlaylists: playlist_content = itunes.library.getPlaylist(playlist) # name (String) # tracks (List[Song]) # is_folder = False (Boolean) # playlist_persistent_id = None (String) # parent_persistent_id = None (String) if playlist_content.is_folder: print("Skipping playlist folder %s" % playlist_content.name) elif len(playlist_content.tracks) == 0: print("Skipping empty playlist %s" % playlist_content.name) else: playlist_items = [] for track in playlist_content.tracks: if not ImportUtils.is_song_on_disk(track) or not '/iTunes Media/Music/' in track.location: continue track_path = ImportUtils.normalizeTrackPath(track.location) if track_path in plex_tracks: playlist_items.append (plex_tracks[track_path]) else: not_found_set.add(track_path) if len(playlist_items) > 0: plexapi.playlist.Playlist.create(plex.server, playlist_content.name, items=playlist_items, section=MUSIC_SECTION) print ("%s\t(%d)\timported" % (playlist_content.name, len(playlist_items))) nonempty_playlists_counter += 1 print ("Tracks not found: %d" % len(not_found_set))
1,754
pipeline/metadata/beam_metadata.py
censoredplanet/censoredplanet-analysis
6
2024452
"""Helpers for merging metadata with rows in beam pipelines""" from __future__ import absolute_import from typing import Tuple, Dict, List, Iterator from pipeline.metadata.flatten import Row # A key containing a date and IP # ex: ("2020-01-01", '1.2.3.4') DateIpKey = Tuple[str, str] # PCollection key names used internally by the beam pipeline IP_METADATA_PCOLLECTION_NAME = 'metadata' ROWS_PCOLLECION_NAME = 'rows' def make_date_ip_key(row: Row) -> DateIpKey: """Makes a tuple key of the date and ip from a given row dict.""" return (row['date'], row['ip']) def merge_metadata_with_rows( # pylint: disable=unused-argument key: DateIpKey, value: Dict[str, List[Row]], field: str = None) -> Iterator[Row]: # pyformat: disable """Merge a list of rows with their corresponding metadata information. Args: key: The DateIpKey tuple that we joined on. This is thrown away. value: A two-element dict {IP_METADATA_PCOLLECTION_NAME: One element list containing an ipmetadata ROWS_PCOLLECION_NAME: Many element list containing row dicts} where ipmetadata is a dict of the format {column_name, value} {'netblock': '1.0.0.1/24', 'asn': 13335, 'as_name': 'CLOUDFLARENET', ...} and row is a dict of the format {column_name, value} {'domain': 'test.com', 'ip': '1.1.1.1', 'success': true ...} field: indicates a row field to update with metadata instead of the row (default). Yields: row dict {column_name, value} containing both row and metadata cols/values """ # pyformat: enable if value[IP_METADATA_PCOLLECTION_NAME]: ip_metadata = value[IP_METADATA_PCOLLECTION_NAME][0] else: ip_metadata = {} rows = value[ROWS_PCOLLECION_NAME] for row in rows: new_row: Row = {} new_row.update(row) if field == 'received': if new_row['received']: new_row['received'].update(ip_metadata) new_row['received'].pop('date', None) new_row['received'].pop('name', None) new_row['received'].pop('country', None) else: new_row.update(ip_metadata) yield new_row
2,111
api/dorest/dorest/libs/django/decorators/validation/arguments.py
ichise-laboratory/uwkgm
0
2023553
"""Argument-validator decorator for Dorest-based endpoints The Dorest project :copyright: (c) 2020 Ichise Laboratory at NII & AIST :author: <NAME> """ from rest_framework.response import Response from django.utils.translation import ugettext_lazy as _ def existence(**params): """Checks whether all required request parameters are included in an HTTP request to an APIView :param params: parameter 'fields' contains required request parameters parameter 'strict_fields' are 'fields' that cannot be blank """ def decorator(func): def wrapper(*args, **kwargs): """Receives HTTP request handler (function) of Django rest_framework's APIView class.""" # Assign rest_framework.request.Request object to 'request' variable, which is to be validated request = args[1] missings = [] blanks = [] fields = params['fields'] if 'fields' in params else [] + params['strict_fields'] if 'strict_fields' in params else [] strict_fields = params['strict_fields'] if 'strict_fields' in params else [] for kwarg in fields: if kwarg not in request.data and kwarg not in request.GET: missings.append(kwarg) for kwarg in strict_fields: if kwarg in request.data and len(request.data[kwarg]) == 0: blanks.append(kwarg) if len(missings) > 0 or len(blanks): return Response({'detail': _('Parameters missing or containing blank value'), 'missing': missings, 'blank': blanks}, status=400) return func(*args, **kwargs) return wrapper return decorator
1,777
application/forms.py
PyColorado/boulderpython.org
5
2023663
# -*- coding: utf-8 -*- """ forms.py ~~~~~~~~ Flask-WTForms """ from flask_wtf import FlaskForm from wtforms import TextField, TextAreaField, SelectField from wtforms.fields.html5 import EmailField from wtforms.validators import InputRequired, Email pitchPlaceholder = 'You have 300 characters to sell your talk. This is known as the "elevator pitch". \ Make it exciting.' talkFormats = [ (0, "-- select --"), ("IN-DEPTH", "In-Depth Talk (~20-30 minutes, 5-10 minute Q&A)"), ("LIGHTNING", "Lightning Talk (~5-10 minutes, no Q&A)"), ("DEMO", "Short Demo (~15-20 minutes, &lt; 5 minute Q&A)"), ("BEGINNER", "Beginner Track (20 minutes, 5 minute Q&A)"), ] audienceLevels = [ (0, "-- select --"), ("BEGINNER", "Beginner"), ("INTERMEDIATE", "Intermediate"), ("ADVANCED", "Advanced"), ] descPlaceholder = "This field supports Markdown. The description will be seen by reviewers during \ the CFP process and may eventually be seen by the attendees of the event." notesPlaceholder = "This field supports Markdown. Notes will only be seen by reviewers during the CFP \ process. This is where you should explain things such as technical requirements, \ why you're the best person to speak on this subject, etc..." class SubmissionForm(FlaskForm): email = EmailField( "Email", validators=[InputRequired("Please enter your email address."), Email("Please enter your email address.")], render_kw={"placeholder": "Email"}, ) title = TextField( "Title", validators=[InputRequired("Your talk needs a name.")], render_kw={"placeholder": "Talk Title"} ) pitch = TextAreaField( "Pitch", validators=[InputRequired("Field is required.")], render_kw={"placeholder": pitchPlaceholder} ) format = SelectField("Talk Format", choices=talkFormats) audience = SelectField("Audience Level", choices=audienceLevels) description = TextAreaField( "Description", validators=[InputRequired("Field is required.")], render_kw={"placeholder": descPlaceholder} ) notes = TextAreaField("Notes", render_kw={"placeholder": notesPlaceholder})
2,150
queue_/queue_on_stack_test.py
katearb/programming-2021-19fpl
0
2023899
""" Programming for linguists Tests for Queue class. """ import unittest from queue_.queue_on_stack import QueueOnStack_, LimitError class QueueOnStackTestCase(unittest.TestCase): """ This Case of tests checks the functionality of the implementation of Queue on stack """ def test_new_queue_is_empty(self): """ Create an empty Queue. Test that its size is 0. """ queue_on_stack = QueueOnStack_() self.assertTrue(queue_on_stack.empty()) self.assertEqual(queue_on_stack.size(), 0) def test_get_element(self): """ Get an element from a queue. Test that it is 1. """ data = (1, 2, 3, 4) queue_on_stack = QueueOnStack_(data) self.assertEqual(queue_on_stack.get(), data[0]) def test_new_queue_from_tuple(self): """ Create a Queue from an iterable object. Check that the size of queue_ equals to the size of the given tuple. """ data = (1, 2, 3, 4) queue_on_stack = QueueOnStack_(data) self.assertFalse(queue_on_stack.empty()) self.assertEqual(queue_on_stack.size(), len(data)) for value in data: test_value = queue_on_stack.get() self.assertEqual(test_value, value) self.assertTrue(queue_on_stack.empty()) self.assertEqual(queue_on_stack.size(), 0) def test_new_queue_from_list(self): """ Create a Queue from a list. Check that the size of queue equals to the size of the queue. Check that the top element of queue equals to the latest element of the list. """ data = [1, 3, 5, 7, 2, 4] queue_on_stack = QueueOnStack_(data) self.assertFalse(queue_on_stack.empty()) self.assertEqual(queue_on_stack.size(), len(data)) self.assertEqual(queue_on_stack.top(), data[0]) def test_new_queue_from_generator(self): """ Create a Queue_ from a generator. Test that its size equals to the number provided in the generator. """ queue_on_stack = QueueOnStack_(range(10)) self.assertFalse(queue_on_stack.empty()) self.assertEqual(queue_on_stack.size(), 10) self.assertEqual(queue_on_stack.top(), 0) def test_put_element(self): """ Put an element in queue. Test that its size is 1. """ queue_on_stack = QueueOnStack_() queue_on_stack.put(1) self.assertFalse(queue_on_stack.empty()) self.assertEqual(queue_on_stack.size(), 1) self.assertEqual(queue_on_stack.top(), 1) def test_call_get_of_empty_queue_raised_error(self): """ Create an empty Queue. Test that call of get function raises Assertion error """ queue_on_stack = QueueOnStack_() self.assertRaises(IndexError, queue_on_stack.get) def test_push_limit(self): """ Create a Queue with max number of elements. Test that an exception will be raised """ queue_on_stack = QueueOnStack_([1, 2, 3], 3) self.assertRaises(LimitError, queue_on_stack.put, 4)
3,172
Course/exceptions/example_12.py
zevgenia/Python_shultais
0
2023315
# -*- coding: utf-8 -*- import sys print("Открыть соединение с БД") try: raise ValueError print("Запись данных") finally: print("Закрыть соединение с БД") print("Продолжение программы")
200
venv/lib/python2.7/site-packages/geocode/geocode.py
NoahFlowa/glowing-spoon
0
2024605
import os import urllib import cPickle as pickle import json import time class NoResultError(Exception): pass class QueryLimitError(Exception): pass last_read = time.time() try: pickle_dir = os.path.expanduser('~/.geocode/') os.makedirs(pickle_dir) except: pickle_dir = './' pickle_path = os.path.join(pickle_dir, 'latlons.pkl') try: with open(pickle_path) as pkl_file: _latlons = pickle.load(pkl_file) except: _latlons = {} def save_cache(): with open(pickle_path, 'w') as pkl_file: pickle.dump(_latlons, pkl_file, -1) def latlon(location, throttle=0.5, center=True, round_digits=2): '''Look up the latitude/longitude coordinates of a given location using the Google Maps API. The result is cached to avoid redundant API requests. throttle: send at most one request in this many seconds center: return the center of the region; if False, returns the region (lat1, lon1, lat2, lon2) round_digits: round coordinates to this many digits ''' global last_read if isinstance(location, list): return map(lambda x: latlon(x, throttle=throttle, center=center, round_digits=round_digits), location) if location in _latlons: result = _latlons[location] if center: lat1, lon1, lat2, lon2 = result result = (lat1+lat2)/2, (lon1+lon2)/2 return tuple([round(n) for n in result]) while time.time() - last_read < throttle: pass last_read = time.time() try: url = "http://maps.google.com/maps/api/geocode/json?address=%s&sensor=false" % location.replace(' ', '+') data = json.loads(urllib.urlopen(url).read()) if data['status'] == 'OVER_QUERY_LIMIT': raise QueryLimitError('Google Maps API query limit exceeded. (Use the throttle keyword to control the request rate.') try: bounds = data['results'][0]['geometry']['bounds'] result1 = bounds['northeast'] lat1, lon1 = result1['lat'], result1['lng'] result2 = bounds['southwest'] lat2, lon2 = result2['lat'], result2['lng'] except KeyError: bounds = data['results'][0]['geometry']['location'] lat1 = bounds['lat'] lon1 = bounds['lng'] lat2 = lat1 lon2 = lon1 except IndexError: raise NoResultError('No result was found for location %s' % location) _latlons[location] = (lat1, lon1, lat2, lon2) save_cache() if center: return round((lat1+lat2)/2, round_digits), round((lon1+lon2)/2, round_digits) else: return tuple([round(n, round_digits) for n in (lat1, lon1, lat2, lon2)]) except Exception as e: raise return None if __name__ == '__main__': input = True while input: input = raw_input('Enter the name of a location: ') print latlon(input)
2,974
src/specific_models/bezerra/attack_identification/cnn_sample_based_2d.py
kaylani2/sbseg2020
7
2023866
import functools import time import math import tensorflow as tf from tensorflow.keras import layers, models from tensorflow import keras import datetime import sys import matplotlib as mpl import matplotlib.pyplot as plt import numpy as np import pandas as pd import time import sklearn from sklearn.metrics import confusion_matrix from sklearn.preprocessing import StandardScaler STATES = [0, 10, 100, 1000, 10000] DATASET_DIR = '../../../datasets/Dataset-IoT/' NETFLOW_DIRS = ['MC/NetFlow/', 'SC/NetFlow/', 'ST/NetFlow/'] # MC_I_FIRST: Has infected data by Hajime, Aidra and BashLite botnets' # MC_I_SECOND: Has infected data from Mirai botnets # MC_I_THIR: Has infected data from Mirai, Doflo, Tsunami and Wroba botnets # MC_L: Has legitimate data, no infection df = load_dataset () print ("Data Loaded") #making the final DataFrame #dropping the number of the rows column df = df.sample (frac = 1, replace = True, random_state = 0) df = df.drop (df.columns [0], axis = 1) #dropping bad columns nUniques = df.nunique () for column, nUnique in zip (df.columns, nUniques): if (nUnique == 1): df.drop (axis = 'columns', columns = column, inplace = True) #dropping unrelated columns df.drop (axis = 'columns', columns= ['ts', 'te', 'sa', 'da'], inplace = True) #counting different labels neg, pos = np.bincount (df ['Label']) ################################## ## encoding categorical columns ## ################################## from sklearn import preprocessing cat_cols, num_cols = df.columns [df.dtypes == 'O'], df.columns [df.dtypes != 'O'] num_cols = num_cols [1:] categories = [df [column].unique () for column in df [cat_cols]] categorical_encoder = preprocessing.OrdinalEncoder (categories = categories) categorical_encoder.fit (df [cat_cols]) df [cat_cols] = categorical_encoder.transform (df [cat_cols]) ######################### ## Splitting the Data ## ######################### from tensorflow import feature_column from tensorflow.keras import layers from sklearn.model_selection import train_test_split #for state in STATES: train, test = train_test_split (df, test_size = 0.3, random_state = state) train, val = train_test_split (train, test_size = 0.25, random_state = state) print (len (train), 'train examples') print (len (val), 'validation examples') print (len (test), 'test examples') train_labels = np.array (train.pop ('Label')) bool_train_labels = train_labels != 0 val_labels = np.array (val.pop ('Label')) test_labels = np.array (test.pop ('Label')) train_features = np.array (train) val_features = np.array (val) test_features = np.array (test) ########################### ## Normalizing the Data ## ########################### #getting the index of the numerical columns index = [df.columns.get_loc (c)-1 for c in num_cols] index = np.array (index) cat_index = [df.columns.get_loc (c) for c in cat_cols] cat_index = np.array (index) scaler = StandardScaler () train_features [:, index] = scaler.fit_transform (train_features [:, index]) val_features [:, index] = scaler.transform (val_features [:, index]) test_features [:, index] = scaler.transform (test_features [:, index]) train_features [:, index] = np.clip (train_features [:, index], -5, 5) val_features [:, index] = np.clip (val_features [:, index], -5, 5) test_features [:, index] = np.clip (test_features [:, index], -5, 5) ######################## ## Reshaping the Data ## ######################## SAMPLE_2D_SIZE = 3 # 3x3 ## zero padding and reshaping train_features.resize ((train_features.shape [0], SAMPLE_2D_SIZE, SAMPLE_2D_SIZE)) train_features = train_features.reshape ((train_features.shape [0], 3, 3, 1)) val_features.resize ((val_features.shape [0], SAMPLE_2D_SIZE, SAMPLE_2D_SIZE)) val_features = val_features.reshape ((val_features.shape [0], 3, 3, 1)) test_features.resize ((test_features.shape [0], SAMPLE_2D_SIZE, SAMPLE_2D_SIZE)) test_features = test_features.reshape ((test_features.shape [0], 3, 3, 1)) print (train_features.shape) ######################## ## Building the Model ## ######################## FILTERS = 4 METRICS = [ keras.metrics.TruePositives (name = 'tp'), keras.metrics.FalsePositives (name = 'fp'), keras.metrics.TrueNegatives (name = 'tn'), keras.metrics.FalseNegatives (name = 'fn'), keras.metrics.BinaryAccuracy (name = 'accuracy'), keras.metrics.Precision (name = 'precision'), keras.metrics.Recall (name = 'recall'), keras.metrics.AUC (name = 'auc'), ] def create_model (lr = 1e-1, dropout_rate = 0.0): initializer = tf.initializers.VarianceScaling (scale = 2.0) model = models.Sequential () model.add (layers.Conv2D (64, (2, 2), activation = 'relu', input_shape= (3, 3, 1), kernel_initializer = initializer)) model.add (layers.Flatten ()) model.add (layers.Dense (64, activation = 'relu', kernel_initializer = initializer)) model.add (layers.Dropout (dropout_rate)) model.add (layers.Dense (1, activation = 'sigmoid', kernel_initializer = initializer)) # model.summary () model.compile (optimizer = keras.optimizers.Adam (lr = 1e-3), loss = keras.losses.BinaryCrossentropy (), metrics= ['binary_accuracy']) return model # ####GRID SEARCH # from sklearn.model_selection import GridSearchCV # from tensorflow.keras.wrappers.scikit_learn import KerasClassifier # from sklearn.model_selection import PredefinedSplit # model = KerasClassifier (build_fn = create_model, verbose = 2) # batch_size = [1000, 2048, 3200] # epochs = [3, 5, 10] # lr = [1e-3, 1e-2, 1e-1, 2e-1] # dropout_rate = [0.0, 0.2, 0.3] # test_fold = np.repeat ( [-1, 0] , [train_features.shape [0], val_features.shape [0]]) # myPreSplit = PredefinedSplit (test_fold) # param_grid = dict (batch_size = batch_size, epochs = epochs, lr = lr, dropout_rate = dropout_rate) # grid = GridSearchCV (estimator = model, cv = myPreSplit, param_grid = param_grid, scoring= 'f1_weighted', verbose = 2, n_jobs = -1) # grid_result = grid.fit ( np.concatenate ((train_features, val_features), axis = 0,), # np.concatenate ((train_labels, val_labels), axis = 0)) # print (grid_result.best_params_) # print ("Best: %f using %s" % (grid_result.best_score_, grid_result.best_params_)) # means = grid_result.cv_results_ ['mean_test_score'] # stds = grid_result.cv_results_ ['std_test_score'] # params = grid_result.cv_results_ ['params'] # for mean, stdev, param in zip (means, stds, params): # print ("%f (%f) with: %r" % (mean, stdev, param)) # sys.exit () model = create_model (lr = 1e-3) startTime = time.time () history = model.fit (train_features, train_labels, epochs = 50, validation_data= (val_features, val_labels), batch_size = 100, verbose = 2) print ("{} s to train model".format (time.time ()-startTime)) from sklearn.metrics import confusion_matrix, precision_score, recall_score from sklearn.metrics import f1_score, classification_report, accuracy_score from sklearn.metrics import cohen_kappa_score y_pred = model.predict (test_features) y_pred = y_pred.round () # print (y_pred) TARGET = 'Label' print ('\nPerformance on TEST set:') my_confusion_matrix = confusion_matrix (test_labels, y_pred, labels = df [TARGET].unique ()) tn, fp, fn, tp = my_confusion_matrix.ravel () print ('Confusion matrix:') print (my_confusion_matrix) print ('Accuracy:', accuracy_score (test_labels, y_pred)) print ('Precision:', precision_score (test_labels, y_pred, average = 'macro')) print ('Recall:', recall_score (test_labels, y_pred, average = 'macro')) print ('F1:', f1_score (test_labels, y_pred, average = 'macro')) print ('Cohen Kappa:', cohen_kappa_score (test_labels, y_pred, labels = df [TARGET].unique ())) print ('TP:', tp) print ('TN:', tn) print ('FP:', fp) print ('FN:', fn)
7,802
adsl_server/main.py
pythonyhd/AdslProxy
11
2023930
# -*- coding: utf-8 -*- import re import platform import time import requests from requests.exceptions import ConnectionError, ConnectTimeout, ReadTimeout from fake_useragent import UserAgent from adsl_server.settings import ADSL_NETMASK, TEST_URL, TEST_TIMEOUT, VALID_STATUS_CODES, CLIENT_NAME, ADSL_BASH, \ PROXY_PORT, USER_NAME, PASSWORD, REDIS_URI, ADSL_ERROR_CYCLE, ADSL_CYCLE, ADSL_KEEP_USE if platform.python_version().startswith('2.'): import commands as subprocess elif platform.python_version().startswith('3.'): import subprocess else: raise ValueError('python version must be 2 or 3') class SenderAdsl(object): def get_ip(self, netname=ADSL_NETMASK): """ 获取拨号IP :param netname: 网卡名称 :return: 拨号ip """ (status, output) = subprocess.getstatusoutput('ifconfig') if status == 0: pattern = re.compile(netname + '.*?inet.*?(\d+\.\d+\.\d+\.\d+).*?netmask', re.S) result = re.search(pattern, output) if result: ip = result.group(1) return ip def test_proxy(self, proxy): """ 测试代理 :param proxy: 代理 :return: 测试结果 """ proxies = { 'http': 'http://{}:{}@{}:{}'.format(USER_NAME, PASSWORD, proxy, PROXY_PORT), 'https': 'https://{}:{}@{}:{}'.format(USER_NAME, PASSWORD, proxy, PROXY_PORT), } headers = {'User-Agent': UserAgent().random} try: response = requests.get(url=TEST_URL, headers=headers, proxies=proxies, timeout=TEST_TIMEOUT) if response.status_code in VALID_STATUS_CODES: # print(response.text) return True except (ConnectTimeout, ReadTimeout, ConnectionError): return False def remove_proxy(self): """ 移除代理 """ url = '{}/remove?name={}'.format(REDIS_URI, CLIENT_NAME) res = requests.get(url=url) print(res.text) def add_proxy(self, proxy): """ 添加代理 """ url = '{}/put?name={}&proxy={}'.format(REDIS_URI, CLIENT_NAME, proxy) res = requests.get(url=url) print(res.text) def adsl(self): """ 拨号主进程 ADSL代码优化,保证拨号前把IP删掉, 确保入库的IP在拨号前都是可用的。 执行删除后再次休眠10秒,确保取出来的IP最少能用10秒 """ while True: try: self.remove_proxy() # 删除之后再次休眠10秒,万一在刚要拨号的时候取到那个IP,那么取出来就拨号了,IP直接不能使用 # 再次休眠确保即使已经删除,取到之后还能用,但是删除后会有一段时间没有IP进来,所以需要开尽可能多的服务器 # 确保池子里面有IP可用 time.sleep(ADSL_KEEP_USE) except: while True: (status, output) = subprocess.getstatusoutput(ADSL_BASH) if status == 0: self.remove_proxy() break (status, output) = subprocess.getstatusoutput(ADSL_BASH) if status == 0: print('ADSL拨号成功') ip = self.get_ip() if ip: if self.test_proxy(ip): proxies = str(ip) + ":" + PROXY_PORT self.add_proxy(proxies) time.sleep(ADSL_CYCLE) else: print('代理IP不可用,测试不通过,上次已经拨号成功的IP已经不可用,删除') self.remove_proxy() else: print('没有匹配到IP') time.sleep(ADSL_ERROR_CYCLE) else: print('ADSL拨号失败') time.sleep(ADSL_ERROR_CYCLE) self.adsl() if __name__ == '__main__': conn = SenderAdsl() conn.adsl()
3,688
benchmarks/microbenchmarks/atomic_ops.py
gaoxinge/taichi
1
2024484
from microbenchmarks._items import AtomicOps, Container, DataSize, DataType from microbenchmarks._metric import MetricType from microbenchmarks._plan import BenchmarkPlan from microbenchmarks._utils import dtype_size, fill_random, scaled_repeat_times import taichi as ti def reduction_default(arch, repeat, atomic_op, container, dtype, dsize, get_metric): repeat = scaled_repeat_times(arch, dsize, repeat) num_elements = dsize // dtype_size(dtype) x = container(dtype, shape=num_elements) y = container(dtype, shape=()) y[None] = 0 @ti.kernel def reduction_field(y: ti.template(), x: ti.template()): for i in x: atomic_op(y[None], x[i]) @ti.kernel def reduction_array(y: ti.types.ndarray(), x: ti.types.ndarray()): for i in x: atomic_op(y[None], x[i]) fill_random(x, dtype, container) func = reduction_field if container == ti.field else reduction_array return get_metric(repeat, func, y, x) class AtomicOpsPlan(BenchmarkPlan): def __init__(self, arch: str): super().__init__('atomic_ops', arch, basic_repeat_times=10) atomic_ops = AtomicOps() atomic_ops.remove( ['atomic_sub', 'atomic_and', 'atomic_xor', 'atomic_max']) self.create_plan(atomic_ops, Container(), DataType(), DataSize(), MetricType()) self.add_func(['field'], reduction_default) self.add_func(['ndarray'], reduction_default)
1,499
smu/geometry/topology_from_geom_main.py
xxdreck/google-research
23,901
2024649
# coding=utf-8 # Copyright 2021 The Google Research Authors. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. """Topology from Geometry.""" from absl import app from absl import flags import apache_beam as beam from apache_beam.options.pipeline_options import PipelineOptions import topology_from_geom from smu import dataset_pb2 from smu.geometry import bond_length_distribution FLAGS = flags.FLAGS flags.DEFINE_string("input", None, "TFDataRecord file containg Conformer protos") flags.DEFINE_string("bonds", None, "File name stem for bond length distributions") flags.DEFINE_string("output", None, "Output file") flags.DEFINE_boolean("xnonbond", False, "Exclude non bonded interactions") class SummaryData(beam.DoFn): """Given BondTopologies as input, yield summary data.""" def process(self, topology_matches): result = f"{len(topology_matches.bond_topology)}" for bt in topology_matches.bond_topology: result += f",{bt.score:.3f},{bt.smiles}" if len(topology_matches.bond_topology) == 1: break if bt.is_starting_topology: result += ",T" else: result += ",F" yield result def ReadConFormer( bond_lengths, input_string, output): """Reads conformer. Args: bond_lengths: input_string: output: Returns: """ # class GetAtoms(beam.DoFn): # def process(self, item): # yield item.optimized_geometry.atom_positions[0].x with beam.Pipeline(options=PipelineOptions()) as p: protos = ( p | beam.io.tfrecordio.ReadFromTFRecord( input_string, coder=beam.coders.ProtoCoder(dataset_pb2.Conformer().__class__)) | beam.ParDo(topology_from_geom.TopologyFromGeom(bond_lengths)) | beam.ParDo(SummaryData()) | beam.io.textio.WriteToText(output)) return protos def TopologyFromGeometryMain(unused_argv): del unused_argv bond_lengths = bond_length_distribution.AllAtomPairLengthDistributions() bond_lengths.add_from_files(FLAGS.bonds, 0.0, FLAGS.xnonbond) protos = ReadConFormer(bond_lengths, FLAGS.input, FLAGS.output) print(protos) if __name__ == "__main__": flags.mark_flag_as_required("input") flags.mark_flag_as_required("bonds") flags.mark_flag_as_required("output") app.run(TopologyFromGeometryMain)
2,832
giraffez/encrypt.py
istvan-fodor/giraffez
122
2023998
# -*- coding: utf-8 -*- # # Copyright 2016 Capital One Services, LLC # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. import os import time import hashlib import base64 from Crypto.Cipher import AES from ._compat import * __all__ = ['create_key_file', 'generate_key', 'Crypto'] def create_key_file(path): """ Creates a new encryption key in the path provided and sets the file permissions. Setting the file permissions currently does not work on Windows platforms because of the differences in how file permissions are read and modified. """ iv = "{}{}".format(os.urandom(32), time.time()) new_key = generate_key(ensure_bytes(iv)) with open(path, "wb") as f: f.write(base64.b64encode(new_key)) os.chmod(path, 0o400) def generate_key(s): for i in range(65536): s = hashlib.sha256(s).digest() return s class Crypto(object): def __init__(self, key, bs=16): self.key = hashlib.sha256(key).digest() self.bs = bs def decrypt(self, enc): enc = base64.b64decode(enc) iv = enc[:self.bs] cipher = AES.new(self.key, AES.MODE_CBC, iv) return self.unpad(cipher.decrypt(enc[self.bs:])).decode("utf-8") def encrypt(self, raw): raw = self.pad(raw).encode("utf-8") iv = os.urandom(self.bs) cipher = AES.new(self.key, AES.MODE_CBC, iv) return base64.b64encode(iv + cipher.encrypt(raw)) def pad(self, s): return s + (self.bs - len(s) % self.bs) * chr(self.bs - len(s) % self.bs) def unpad(self, s): return s[:-ord(s[len(s)-1:])] @classmethod def from_key_file(cls, path): with open(path, "rb") as f: return cls(base64.b64decode(f.read()))
2,242
cli/menu.py
merwane/shield
0
2024630
from PyInquirer import prompt from cli.upload import upload_file from cli.download import download_file, delete_file, nuke_everything from cli.access import revoke_access from config import RESTART_CLI_COMMAND import time import os menu_list = [{ "type": "list", "name": "action", "message": "What do you want to do?", "choices": ['Upload a file', 'Download a file', 'Delete a file', 'Exit', 'Reload CLI', 'Revoke access', 'Nuke everything'] }] def restart_cli(n=3): time.sleep(n) os.system(RESTART_CLI_COMMAND) def display(): menu_list_answer = prompt(menu_list) menu_list_answer = menu_list_answer['action'] if menu_list_answer == 'Upload a file': upload_file() elif menu_list_answer == 'Download a file': download_file() elif menu_list_answer == 'Delete a file': delete_file() elif menu_list_answer == 'Reload CLI': restart_cli(0.1) elif menu_list_answer == 'Revoke access': revoke_access() elif menu_list_answer == 'Nuke everything': nuke_everything() else: os.system('clear') exit()
1,120
dotnet/deps.bzl
purkhusid/rules_dotnet
143
2023079
"Public declarations" load( "@io_bazel_rules_dotnet//dotnet/private:repositories.bzl", _dotnet_repositories = "dotnet_repositories", ) dotnet_repositories = _dotnet_repositories
188
calrissian/retry.py
pymonger/calrissian
25
2024211
from tenacity import retry, wait_exponential, retry_if_exception_type, stop_after_attempt, before_sleep_log import logging import os class RetryParameters(object): MULTIPLIER = float(os.getenv('RETRY_MULTIPLIER', 5)) # Unit for multiplying the exponent MIN = float(os.getenv('RETRY_MIN', 5)) # Min time for retrying MAX = float(os.getenv('RETRY_MAX', 1200)) # Max interval between retries ATTEMPTS = int(os.getenv('RETRY_ATTEMPTS', 10)) # Max number of retries before giving up def retry_exponential_if_exception_type(exc_type, logger): """ Decorator function that returns the tenacity @retry decorator with our commonly-used config :param exc_type: Type of exception (or tuple of types) to retry if encountered :param logger: A logger instance to send retry logs to :return: Result of tenacity.retry decorator function """ return retry(retry=retry_if_exception_type(exc_type), wait=wait_exponential(multiplier=RetryParameters.MULTIPLIER, min=RetryParameters.MIN, max=RetryParameters.MAX), stop=stop_after_attempt(RetryParameters.ATTEMPTS), before_sleep=before_sleep_log(logger, logging.DEBUG), reraise=True)
1,206
2021/12a.py
combatopera/advent2020
2
2024764
#!/usr/bin/env python3 from pathlib import Path class Graph: def __init__(self, edges): self.smallnodes = {n for e in edges for n in e if n == n.lower()} self.edges = edges def _paths(self, p, visited): if p[-1] == 'end': yield p else: for e in self.edges: n = e - {p[-1]} if 1 == len(n): n, = n if not (n in self.smallnodes and n in visited): yield from self._paths(p + [n], visited | {n}) def paths(self): yield from self._paths(['start'], {'start'}) def main(): g = Graph([set(line.split('-')) for line in Path('input', '12').read_text().splitlines()]) print(sum(1 for _ in g.paths())) if '__main__' == __name__: main()
814
find-center-of-star-graph.py
xXHachimanXx/LeetCode-Problems
0
2023371
# docs: https://docs.google.com/document/d/1mkb83sHrXUhwyjFkqzQfyOAxfrBB0IBkZLddTVRuGdY/edit def findCenter(graph): dict = {} for edge in graph: dict[edge[0]] = 0 dict[edge[1]] = 0 for edge in graph: dict[edge[0]] += 1 dict[edge[1]] += 1 if dict[edge[0]] > 1: return edge[0] if dict[edge[1]] > 1: return edge[1] return 1 assert findCenter([[1,2],[2,3],[4,2]]) == 2 assert findCenter([[1,2],[5,1],[1,3],[1,4]]) == 1
547
4band_to_NIR_G_R_3band.py
gfrancis-ALElab/tools
0
2023348
# -*- coding: utf-8 -*- """ Created on Mon May 10 15:52:58 2021 Tool for creating a 3band (NIR,G,R) image from Planet images Images are converted to uint8 with average magnitudes balanced on 127 @author: <NAME> email: <EMAIL> """ import os home = os.path.expanduser('~') ### Set OSGEO env PATHS os.environ['PROJ_LIB'] = '/usr/share/proj' os.environ['GDAL_DATA'] = '/usr/share/gdal' import rasterio import numpy as np import glob import geopandas as gpd from shapely import speedups speedups.disable() ### IO folder = home + '/Planet/HWC/Data' lib = folder + '/mosaics' out = folder + '/NIR_G_R_mosaics' if os.path.isdir(out) is False: os.makedirs(out) ### Get CRS from truths path_t = home + '/Planet/HWC/Data/Slumps/HotWeatherCreek_slumps.shp' truths = gpd.read_file(path_t) crs = truths.crs def get_name(file_location): filename = file_location.split('/')[-1] filename = filename.split('.') return filename[0] for pic in glob.glob(lib + '/Hot*.tif'): ras = rasterio.open(pic) name = get_name(pic) if ras.meta['count'] == 4: bandRed = ras.read(3) bandgreen = ras.read(2) bandNIR = ras.read(4) ### NIR is channel 4 in Planet Scope 4band if ras.meta['count'] == 5: bandRed = ras.read(3) bandgreen = ras.read(2) bandNIR = ras.read(5) ### NIR is channel 5 in Rapid Eye 5band NIR_arr = bandNIR.astype(float) green_arr = bandgreen.astype(float) red_arr = bandRed.astype(float) ### replace nodata zeros & 65535 to Nan if NIR_arr.min() == 0: NIR_arr = np.where(NIR_arr==0, np.nan, NIR_arr) green_arr = np.where(green_arr==0, np.nan, green_arr) red_arr = np.where(red_arr==0, np.nan, red_arr) if NIR_arr.max() == 65535: NIR_arr = np.where(NIR_arr==65535, np.nan, NIR_arr) green_arr = np.where(green_arr==65535, np.nan, green_arr) red_arr = np.where(red_arr==65535, np.nan, red_arr) ### normalize 0 to 1 NIR_norm = NIR_arr/np.nanmax(NIR_arr) green_norm = green_arr/np.nanmax(green_arr) red_norm = red_arr/np.nanmax(red_arr) ### center average on 50% NIR_norm = NIR_norm + (0.5 - np.nanmean(NIR_norm)) green_norm = green_norm + (0.5 - np.nanmean(green_norm)) red_norm = red_norm + (0.5 - np.nanmean(red_norm)) # ### scale (0 to 255) NIR_scaled = NIR_norm*255 green_scaled = green_norm*255 red_scaled = red_norm*255 ### change dtype NIR_scaled = NIR_scaled.astype(np.uint8) green_scaled = green_scaled.astype(np.uint8) red_scaled = red_scaled.astype(np.uint8) kwargs3band = ras.meta kwargs3band.update( dtype=rasterio.uint8, nodata=255, crs=crs, count=3) # print(kwargs3band) # print('\n') with rasterio.open(out + '/%s_NIR_G_R_avg50_scaled0_255.tif'%name, 'w', **kwargs3band) as dst: dst.write_band(1, NIR_scaled.astype(rasterio.uint8)) dst.write_band(2, green_scaled.astype(rasterio.uint8)) dst.write_band(3, red_scaled.astype(rasterio.uint8)) ras.close()
3,084