blob_id
stringlengths
40
40
directory_id
stringlengths
40
40
path
stringlengths
3
288
content_id
stringlengths
40
40
detected_licenses
listlengths
0
112
license_type
stringclasses
2 values
repo_name
stringlengths
5
115
snapshot_id
stringlengths
40
40
revision_id
stringlengths
40
40
branch_name
stringclasses
684 values
visit_date
timestamp[us]date
2015-08-06 10:31:46
2023-09-06 10:44:38
revision_date
timestamp[us]date
1970-01-01 02:38:32
2037-05-03 13:00:00
committer_date
timestamp[us]date
1970-01-01 02:38:32
2023-09-06 01:08:06
github_id
int64
4.92k
681M
star_events_count
int64
0
209k
fork_events_count
int64
0
110k
gha_license_id
stringclasses
22 values
gha_event_created_at
timestamp[us]date
2012-06-04 01:52:49
2023-09-14 21:59:50
gha_created_at
timestamp[us]date
2008-05-22 07:58:19
2023-08-21 12:35:19
gha_language
stringclasses
147 values
src_encoding
stringclasses
25 values
language
stringclasses
1 value
is_vendor
bool
2 classes
is_generated
bool
2 classes
length_bytes
int64
128
12.7k
extension
stringclasses
142 values
content
stringlengths
128
8.19k
authors
listlengths
1
1
author_id
stringlengths
1
132
e6459bee9d2e891da08c7850fcd9eb2629fbf12c
0905b794ccd3f3e4af9819a3c77505ba43067556
/reporter/uhl_reports/lenten/data_quality/redcap.py
c45938be0cdcadb138799cfb2a26b02e2f383995
[ "MIT" ]
permissive
LCBRU/reporter
57807fd358eee46d37c529e08baa1a76164588f8
8cb0ae403346e375a5e99d1d4df375cf2d5f3b81
refs/heads/master
2021-09-27T23:22:39.806232
2021-09-27T11:34:10
2021-09-27T11:34:10
88,853,864
0
0
null
null
null
null
UTF-8
Python
false
false
1,425
py
#!/usr/bin/env python3 from reporter.connections import RedcapInstance from reporter.application_abstract_reports.redcap.percentage_complete import ( RedcapPercentageCompleteReport, ) from reporter.application_abstract_reports.redcap.withdrawn_or_excluded_with_data import ( RedcapWithdrawnOrExcludedWithDataReport, ) from reporter.emailing import ( RECIPIENT_LENTEN_ADMIN as RECIPIENT_ADMIN, RECIPIENT_LENTEN_MANAGER as RECIPIENT_MANAGER, RECIPIENT_IT_DQ, ) from reporter.application_abstract_reports.redcap.web_data_quality import ( RedcapWebDataQuality, ) from reporter.core import Schedule REDCAP_PROJECT_ID = 25 REDCAP_INSTANCE = RedcapInstance.internal class LentenRedcapPercentageCompleteReport(RedcapPercentageCompleteReport): def __init__(self): super().__init__( 'Lenten', [RECIPIENT_ADMIN, RECIPIENT_MANAGER], ) class LentenRedcapWithdrawnOrExcludedWithDataReport( RedcapWithdrawnOrExcludedWithDataReport): def __init__(self): super().__init__( 'Lenten', [RECIPIENT_ADMIN, RECIPIENT_MANAGER], schedule=Schedule.never, ) class LentenRedcapWebDataQuality(RedcapWebDataQuality): def __init__(self): super().__init__( REDCAP_INSTANCE, REDCAP_PROJECT_ID, [RECIPIENT_IT_DQ] )
[ "rabramley@gmail.com" ]
rabramley@gmail.com
64429c608293d0377a94b8e6dbd8d5d331e7697f
08615c64a62fc364a802bb92314cf49080ddbcee
/AuthDemo/AuthDemo/wsgi.py
0242575bfbf148c81be31a540de5b6781323ff4a
[]
no_license
xiangys0134/python_study
afc4591fca1db6ebddf83f0604e35ed2ef614728
6ec627af7923b9fd94d244c561297ccbff90c1e9
refs/heads/master
2023-02-24T01:24:45.734510
2022-10-29T02:11:20
2022-10-29T02:11:20
143,358,792
2
0
null
2023-02-08T03:07:26
2018-08-03T00:43:46
Python
UTF-8
Python
false
false
393
py
""" WSGI config for AuthDemo project. It exposes the WSGI callable as a module-level variable named ``application``. For more information on this file, see https://docs.djangoproject.com/en/2.1/howto/deployment/wsgi/ """ import os from django.core.wsgi import get_wsgi_application os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'AuthDemo.settings') application = get_wsgi_application()
[ "ops@xuncetech.com" ]
ops@xuncetech.com
bf247cf69a66b8ff4454138a34af99d0b08b99e6
f82e67dd5f496d9e6d42b4fad4fb92b6bfb7bf3e
/scripts/client/gui/scaleform/daapi/view/dialogs/systemmessagedialog.py
064246170a75ceabb84e841361acd59298472adb
[]
no_license
webiumsk/WOT0.10.0
4e4413ed4e7b00e22fb85d25fdae9400cbb4e76b
a84f536c73f86d9e8fab559e97f88f99f2ad7e95
refs/heads/master
2021-01-09T21:55:00.662437
2015-10-23T20:46:45
2015-10-23T20:46:45
44,835,654
1
0
null
null
null
null
UTF-8
Python
false
false
991
py
# Embedded file name: scripts/client/gui/Scaleform/daapi/view/dialogs/SystemMessageDialog.py from gui.Scaleform.daapi.view.meta.SystemMessageDialogMeta import SystemMessageDialogMeta class SystemMessageDialog(SystemMessageDialogMeta): def __init__(self, meta, handler): super(SystemMessageDialog, self).__init__() self.__meta = meta self.__handler = handler def _populate(self): super(SystemMessageDialog, self)._populate() self.as_setInitDataS({'title': self.__meta.getTitle(), 'closeBtnTitle': self.__meta.getCancelLabel(), 'settings': self.__meta.getSettings()}) self.as_setMessageDataS(self.__meta.getMessageObject()) def onWindowClose(self): self.destroy() def _dispose(self): if self.__handler: self.__handler(True) self.__meta.cleanUp() self.__meta = None self.__handler = None super(SystemMessageDialog, self)._dispose() return
[ "info@webium.sk" ]
info@webium.sk
defcda15eaf1c00f1035720961bce208482c6d40
9372026aec32fa10896225813986346e472f7a7c
/pygame/class51/Dokdo.py
0c63cee12cccf37bd475e4b304622f68bc6adf5f
[]
no_license
mjsong0712/learn_python
5809df5b0366b37836633f5fa5e2d96a9cb99798
1cc31ca750e76b436596e3a4f6b8f39d7b873624
refs/heads/master
2022-05-17T00:54:17.975679
2022-05-01T08:07:33
2022-05-01T08:07:33
235,795,862
0
0
null
null
null
null
UTF-8
Python
false
false
747
py
import pygame import sys SCREEN_WIDTH = 2560 SCREEN_HEIGHT = 1440 white = (255, 255, 255) black = (0, 0, 0) pygame.init() pygame.display.set_caption("Dokdo Defense") #screen = pygame.display.set_mode((2560, 1440), pygame.FULLSCREEN) screen = pygame.display.set_mode((SCREEN_WIDTH, SCREEN_HEIGHT)) def startScreen(screen): background = pygame.Rect((0,0), (SCREEN_WIDTH, SCREEN_HEIGHT)) pygame.draw.rect(screen, white, background) cardimg=pygame.image.load('res/back_1.png') clock = pygame.time.Clock() while True: clock.tick(10) for event in pygame.event.get(): if event.type == pygame.QUIT: sys.exit() if event.type == pygame.KEYDOWN: if event.key == pygame.K_q: sys.exit() start() pygame.quit()
[ "mjsong070712@gmail.com" ]
mjsong070712@gmail.com
5c1e63c1b8a880d64aa1f8c6cbf60d0447fcd106
e0ede722874d222a789411070f76b50026bbe3d8
/practice/solution/0412_fizz_buzz.py
26105eb5a028bef229555eeec690aee2097470a2
[]
no_license
kesarb/leetcode-summary-python
cd67456cb57bdff7ee227dab3930aaf9c2a6ad00
dc45210cb2cc50bfefd8c21c865e6ee2163a022a
refs/heads/master
2023-05-26T06:07:25.943854
2021-06-06T20:02:13
2021-06-06T20:02:13
null
0
0
null
null
null
null
UTF-8
Python
false
false
576
py
class Solution(object): def fizzBuzz(self, n): """ :type n: int :rtype: List[str] """ res = [] for i in range(1, n + 1): if not i % 3 and not i % 5: res.append('FizzBuzz') continue if not i % 3: res.append('Fizz') continue if not i % 5: res.append('Buzz') continue res.append(str(i)) return res
[ "weikunhan@g.ucla.edu" ]
weikunhan@g.ucla.edu
a4716d3670a1df6c98afc4c1f78fd43d91364b30
80502d898ad01a6043add30def0e99b853b49bb8
/shop/admin.py
33c0ed22a2bc0afdb20b44f5b310fb90f90212c8
[]
no_license
sadirahman/e-comarce-online-shop
ea1a01473ea8ba54573e7d6d19129aa223270a21
e2146e61cce44535e05deb24e609116dd690dec0
refs/heads/master
2020-04-20T21:48:39.081071
2019-02-04T19:35:53
2019-02-04T19:35:53
169,119,941
0
0
null
null
null
null
UTF-8
Python
false
false
613
py
from django.contrib import admin from .models import Category,Product # Register your models here. class CategoryAdmin(admin.ModelAdmin): list_display = ['name', 'slug'] prepopulated_fields = {'slug': ('name',)} class ProductAdmin(admin.ModelAdmin): list_display = ['name', 'slug', 'category', 'price', 'stock', 'available', 'created', 'updated'] list_filter = ['available', 'created', 'updated', 'category'] list_editable = ['price', 'stock', 'available'] prepopulated_fields = {'slug': ('name',)} admin.site.register(Category, CategoryAdmin) admin.site.register(Product, ProductAdmin)
[ "42184120+sadirahman@users.noreply.github.com" ]
42184120+sadirahman@users.noreply.github.com
0cf65ac8cdb0ab41d431b699f505a24259348f33
2995ab9f4d8e4292763f215709bd3da266c812d4
/proyecto_ibis/ibis/portal/models.py
0e51ce44dc24ec8b17554d791b66ff494f21cf8d
[]
no_license
mrinxx/Ibis
a45c84184c03c5983cfb67ba303235162f22abfb
4435fad66bf8082eb9a3b41b0b2d415607cd207a
refs/heads/main
2023-06-01T19:40:16.092648
2021-06-14T20:48:10
2021-06-14T20:48:10
376,138,283
0
0
null
null
null
null
UTF-8
Python
false
false
2,624
py
from django.db import models from django.db.models.constraints import UniqueConstraint from django.core.exceptions import ValidationError from datetime import date from users.models import Cicle # Create your models here. #Modelos que se van a migrar a la base de datos y que sirven para formae los elementos de la web #################Validators############## def validate_date(value): actualdate=date.today() if(actualdate>value): raise ValidationError( "La fecha del evento tiene que ser posterior a la actual" ) ######################################### #MODELO DE EVENTOS class Event(models.Model): id=models.AutoField(primary_key=True) date=models.DateField(blank=False,null=False,validators=[validate_date]) Description=models.CharField(max_length=400) created_at=models.DateField(auto_now_add=True) updated_at=models.DateField(auto_now=True) class Meta: db_table="events" ordering= ["date"] #SELECCION DE # #MODELO DE HORARIOS class Timetable(models.Model): id=models.AutoField(primary_key=True) cicle = models.OneToOneField(Cicle, on_delete=models.CASCADE,unique=True) timetable_image=models.ImageField(upload_to="timetables") timetable_created_at=models.DateField(auto_now_add=True) timetable_updated_at=models.DateField(auto_now=True) created_at=models.DateField(auto_now_add=True) updated_at=models.DateField(auto_now=True) class Meta: db_table="timetables" #MODELO DE MENUS class Menu(models.Model): id=models.AutoField(primary_key=True) cicle = models.OneToOneField(Cicle, on_delete=models.CASCADE,unique=True) menu_image=models.ImageField(upload_to="menus") created_at=models.DateField(auto_now_add=True) updated_at=models.DateField(auto_now=True) class Meta: db_table="menus" class New(models.Model): id=models.AutoField(primary_key=True) #Id autoincremental title=models.CharField(max_length=50) subtitle=models.CharField(max_length=100) content=models.TextField(max_length=3000) media1=models.ImageField(upload_to="news") #Estas imágenes no son obligatorias, solo lo es una para el encabezado de la noticia media2=models.ImageField(blank=True, null=True) media3=models.ImageField(blank=True, null=True) media4=models.ImageField(blank=True, null=True) media5=models.ImageField(blank=True, null=True) media6=models.ImageField(blank=True, null=True) created_at=models.DateField(auto_now_add=True) updated_at=models.DateField(auto_now=True) class Meta: db_table="news"
[ "mrinxx5@gmail.com" ]
mrinxx5@gmail.com
ea53046f3fac847f0398e3a783f17bf0a3c454ac
49c4d5ddda86f05c15587c13cda11f9a40e4c4f1
/yggdrasil/examples/tests/test_formatted_io9.py
9ed59f8a2e93244a0cf30c9acf07705baa1c548c
[ "BSD-3-Clause" ]
permissive
ritviksahajpal/yggdrasil
816c314db9fa48d5e8effbe498c014c7efd063ec
777549413719918ba208d73018da4df678a1754e
refs/heads/master
2020-05-17T12:58:44.339879
2019-04-24T21:21:56
2019-04-24T21:21:56
null
0
0
null
null
null
null
UTF-8
Python
false
false
449
py
import os from yggdrasil.examples.tests import TestExample class TestExampleFIO9(TestExample): r"""Test the Formatted I/O lesson 9 example.""" example_name = 'formatted_io9' @property def input_files(self): r"""Input file.""" return [os.path.join(self.yamldir, 'Input', 'input.txt')] @property def output_files(self): r"""Output file.""" return [os.path.join(self.yamldir, 'output.txt')]
[ "langmm.astro@gmail.com" ]
langmm.astro@gmail.com
e862fa70f7cc1f43f2f29a5c978aa33e06a1d5d6
29eacf3b29753d65d8ec0ab4a60ea1f7ddecbd68
/setup.py
94d96ef1f119f85d0d5af99f2492c039438445db
[ "MIT" ]
permissive
lightly-ai/lightly
5b655fe283b7cc2ddf1d7f5bd098603fc1cce627
5650ee8d4057139acf8aa10c884d5d5cdc2ccb17
refs/heads/master
2023-08-17T11:08:00.135920
2023-08-16T12:43:02
2023-08-16T12:43:02
303,705,119
2,473
229
MIT
2023-09-14T14:47:16
2020-10-13T13:02:56
Python
UTF-8
Python
false
false
4,985
py
import os import sys import setuptools try: import builtins except ImportError: import __builtin__ as builtins PATH_ROOT = PATH_ROOT = os.path.dirname(__file__) builtins.__LIGHTLY_SETUP__ = True import lightly def load_description(path_dir=PATH_ROOT, filename="DOCS.md"): """Load long description from readme in the path_dir/ directory""" with open(os.path.join(path_dir, filename)) as f: long_description = f.read() return long_description def load_requirements(path_dir=PATH_ROOT, filename="base.txt", comment_char="#"): """From pytorch-lightning repo: https://github.com/PyTorchLightning/pytorch-lightning. Load requirements from text file in the path_dir/requirements/ directory. """ with open(os.path.join(path_dir, "requirements", filename), "r") as file: lines = [ln.strip() for ln in file.readlines()] reqs = [] for ln in lines: # filer all comments if comment_char in ln: ln = ln[: ln.index(comment_char)].strip() # skip directly installed dependencies if ln.startswith("http"): continue if ln: # if requirement is not empty reqs.append(ln) return reqs if __name__ == "__main__": name = "lightly" version = lightly.__version__ description = lightly.__doc__ author = "Philipp Wirth & Igor Susmelj" author_email = "philipp@lightly.ai" description = "A deep learning package for self-supervised learning" entry_points = { "console_scripts": [ "lightly-crop = lightly.cli.crop_cli:entry", "lightly-train = lightly.cli.train_cli:entry", "lightly-embed = lightly.cli.embed_cli:entry", "lightly-magic = lightly.cli.lightly_cli:entry", "lightly-download = lightly.cli.download_cli:entry", "lightly-version = lightly.cli.version_cli:entry", ] } long_description = load_description() python_requires = ">=3.6" base_requires = load_requirements(filename="base.txt") openapi_requires = load_requirements(filename="openapi.txt") torch_requires = load_requirements(filename="torch.txt") video_requires = load_requirements(filename="video.txt") dev_requires = load_requirements(filename="dev.txt") setup_requires = ["setuptools>=21"] install_requires = base_requires + openapi_requires + torch_requires extras_require = { "video": video_requires, "dev": dev_requires, "all": dev_requires + video_requires, } packages = [ "lightly", "lightly.api", "lightly.cli", "lightly.cli.config", "lightly.data", "lightly.embedding", "lightly.loss", "lightly.loss.regularizer", "lightly.models", "lightly.models.modules", "lightly.transforms", "lightly.utils", "lightly.utils.benchmarking", "lightly.utils.cropping", "lightly.active_learning", "lightly.active_learning.config", "lightly.openapi_generated", "lightly.openapi_generated.swagger_client", "lightly.openapi_generated.swagger_client.api", "lightly.openapi_generated.swagger_client.models", ] project_urls = { "Homepage": "https://www.lightly.ai", "Web-App": "https://app.lightly.ai", "Documentation": "https://docs.lightly.ai", "Github": "https://github.com/lightly-ai/lightly", "Discord": "https://discord.gg/xvNJW94", } classifiers = [ "Development Status :: 5 - Production/Stable", "Intended Audience :: Developers", "Intended Audience :: Education", "Intended Audience :: Science/Research", "Topic :: Scientific/Engineering", "Topic :: Scientific/Engineering :: Mathematics", "Topic :: Scientific/Engineering :: Artificial Intelligence", "Topic :: Software Development", "Topic :: Software Development :: Libraries", "Topic :: Software Development :: Libraries :: Python Modules", "Programming Language :: Python :: 3", "Programming Language :: Python :: 3.6", "Programming Language :: Python :: 3.7", "Programming Language :: Python :: 3.8", "Programming Language :: Python :: 3.9", "License :: OSI Approved :: MIT License", ] setuptools.setup( name=name, version=version, author=author, author_email=author_email, description=description, entry_points=entry_points, license="MIT", long_description=long_description, long_description_content_type="text/markdown", setup_requires=setup_requires, install_requires=install_requires, extras_require=extras_require, python_requires=python_requires, packages=packages, classifiers=classifiers, include_package_data=True, project_urls=project_urls, )
[ "noreply@github.com" ]
lightly-ai.noreply@github.com
308747fceafd6a00ad1ac91e400c9ebee602e95c
13774b1a03473d9a7061ea01a5045f93f901b08d
/myproject/settings.py
62faf0b532ea14aad8715c08dd939d45e19b5258
[]
no_license
adiram17/django-simple-signup
eebdb81165289dac4cb824eba3cfd0ea46ed9e73
7f71c44dabb80ac35673ce32cc3ea06df594d21e
refs/heads/master
2022-11-20T09:30:27.577393
2020-07-25T15:52:28
2020-07-25T15:52:28
282,475,552
0
0
null
null
null
null
UTF-8
Python
false
false
3,215
py
""" Django settings for myproject project. Generated by 'django-admin startproject' using Django 3.0.8. For more information on this file, see https://docs.djangoproject.com/en/3.0/topics/settings/ For the full list of settings and their values, see https://docs.djangoproject.com/en/3.0/ref/settings/ """ import os # Build paths inside the project like this: os.path.join(BASE_DIR, ...) BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) # Quick-start development settings - unsuitable for production # See https://docs.djangoproject.com/en/3.0/howto/deployment/checklist/ # SECURITY WARNING: keep the secret key used in production secret! SECRET_KEY = 'luc4h*=^mfhxz!8kc*5aprn6b#nou=*7$9e(uy_-vquj%ln&f2' # SECURITY WARNING: don't run with debug turned on in production! DEBUG = True ALLOWED_HOSTS = [] # Application definition INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'myapp' ] MIDDLEWARE = [ 'django.middleware.security.SecurityMiddleware', 'django.contrib.sessions.middleware.SessionMiddleware', 'django.middleware.common.CommonMiddleware', 'django.middleware.csrf.CsrfViewMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', 'django.middleware.clickjacking.XFrameOptionsMiddleware', ] ROOT_URLCONF = 'myproject.urls' TEMPLATES = [ { 'BACKEND': 'django.template.backends.django.DjangoTemplates', 'DIRS': [os.path.join(BASE_DIR, 'myapp', 'templates')], #updated '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', ], }, }, ] WSGI_APPLICATION = 'myproject.wsgi.application' # Database # https://docs.djangoproject.com/en/3.0/ref/settings/#databases DATABASES = { 'default': { 'ENGINE': 'django.db.backends.sqlite3', 'NAME': os.path.join(BASE_DIR, 'db.sqlite3'), } } # Password validation # https://docs.djangoproject.com/en/3.0/ref/settings/#auth-password-validators AUTH_PASSWORD_VALIDATORS = [ { 'NAME': 'django.contrib.auth.password_validation.UserAttributeSimilarityValidator', }, { 'NAME': 'django.contrib.auth.password_validation.MinimumLengthValidator', }, { 'NAME': 'django.contrib.auth.password_validation.CommonPasswordValidator', }, { 'NAME': 'django.contrib.auth.password_validation.NumericPasswordValidator', }, ] # Internationalization # https://docs.djangoproject.com/en/3.0/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/3.0/howto/static-files/ STATIC_URL = '/static/' LOGIN_URL = '/login/' LOGIN_REDIRECT_URL = '/secure'
[ "adi.ramadhan@sigma.co.id" ]
adi.ramadhan@sigma.co.id
a2b83590bed0d255ae0533729ebdcba5e226bb37
f6b8532182ccad913f63cd8babc67bb8a57d5ac7
/test/test_dbref.py
f658dbd6dc4012e97fde4d57c20bae167c3a11cb
[ "Apache-2.0" ]
permissive
mikejs/mongo-python-driver
c08a44a3616ead4de47a8fa49e47e9549042aa2d
5c357865fbc25ec99265fdd49ee04545caabb986
refs/heads/master
2021-01-18T08:50:11.531684
2009-08-19T23:07:38
2009-08-19T23:07:38
null
0
0
null
null
null
null
UTF-8
Python
false
false
2,445
py
# Copyright 2009 10gen, 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. """Tests for the dbref module.""" import unittest import types import sys sys.path[0:0] = [""] from pymongo.objectid import ObjectId from pymongo.dbref import DBRef class TestDBRef(unittest.TestCase): def setUp(self): pass def test_creation(self): a = ObjectId() self.assertRaises(TypeError, DBRef) self.assertRaises(TypeError, DBRef, "coll") self.assertRaises(TypeError, DBRef, 4, a) self.assertRaises(TypeError, DBRef, 1.5, a) self.assertRaises(TypeError, DBRef, a, a) self.assertRaises(TypeError, DBRef, None, a) self.assert_(DBRef("coll", a)) self.assert_(DBRef(u"coll", a)) self.assert_(DBRef(u"coll", 5)) def test_read_only(self): a = DBRef("coll", ObjectId()) def foo(): a.collection = "blah" def bar(): a.id = "aoeu" a.collection a.id self.assertRaises(AttributeError, foo) self.assertRaises(AttributeError, bar) def test_repr(self): self.assertEqual(repr(DBRef("coll", ObjectId("123456789012"))), "DBRef(u'coll', ObjectId('123456789012'))") self.assertEqual(repr(DBRef(u"coll", ObjectId("123456789012"))), "DBRef(u'coll', ObjectId('123456789012'))") def test_cmp(self): self.assertEqual(DBRef("coll", ObjectId("123456789012")), DBRef(u"coll", ObjectId("123456789012"))) self.assertNotEqual(DBRef("coll", ObjectId("123456789012")), DBRef("col", ObjectId("123456789012"))) self.assertNotEqual(DBRef("coll", ObjectId("123456789012")), DBRef("coll", ObjectId("123456789011"))) self.assertNotEqual(DBRef("coll", ObjectId("123456789012")), 4) if __name__ == "__main__": unittest.main()
[ "mike@10gen.com" ]
mike@10gen.com
e57e7d1e41f91d390fc6009b0151fb57eda330f5
4ef688b93866285bcc27e36add76dc8d4a968387
/moto/servicequotas/__init__.py
d8e8601eff43bb74613024d11aa51f0e1cc3367f
[ "Apache-2.0" ]
permissive
localstack/moto
cec77352df216cac99d5e0a82d7ada933950a0e6
b0b2947e98e05d913d7ee2a0379c1bec73f7d0ff
refs/heads/localstack
2023-09-01T05:18:16.680470
2023-07-10T09:00:26
2023-08-07T14:10:06
118,838,444
22
42
Apache-2.0
2023-09-07T02:07:17
2018-01-25T00:10:03
Python
UTF-8
Python
false
false
219
py
"""servicequotas module initialization; sets value for base decorator.""" from .models import servicequotas_backends from ..core.models import base_decorator mock_servicequotas = base_decorator(servicequotas_backends)
[ "info@bertblommers.nl" ]
info@bertblommers.nl
21ae708a7a4a0fcba96568d51deb0386e8b57608
58eac1826eb44833ffc5a4c61ae017883b202334
/my_cookbook/skill/main.py
a4513dc5f798434e87c43e29f84c7060515b1e12
[]
no_license
PeterMitrano/my_cookbook
dd8b91170cd101d453c942972a87b2d85dc163b4
46d47e863d10947b3052fc59351da5d83a8dba36
refs/heads/master
2021-01-19T06:36:26.718989
2016-10-17T03:35:17
2016-10-17T03:35:17
61,961,054
0
0
null
null
null
null
UTF-8
Python
false
false
4,092
py
import copy import json import logging import os from my_cookbook import stage from my_cookbook.skill import intent_handler from my_cookbook.util import responder from my_cookbook.util import core from my_cookbook.util import dbhelper import my_cookbook.skill.handlers as handlers import pkgutil class Skill: def __init__(self): self.intent_handler = intent_handler.Handler() # automagically add all the handlers for importer, modname, _ in pkgutil.iter_modules(handlers.__path__): handler_mod = importer.find_module(modname).load_module(modname) self.intent_handler.add(handler_mod.state, handler_mod.handler) def handle_event(self, event, context): # check if we're debugging locally if stage.PROD: debug = False endpoint_url = None logging.getLogger(core.LOGGER).setLevel(logging.INFO) else: debug = True logging.getLogger(core.LOGGER).setLevel(logging.DEBUG) endpoint_url = core.LOCAL_DB_URI # check application id and user user = event['session']['user']['userId'] request_appId = event['session']['application']['applicationId'] if core.APP_ID != request_appId: raise Exception('application id %s does not match.' % request_appId) # store session attributes so the various handlers know what's up if 'attributes' in event['session']: session_attributes = event['session']['attributes'] else: session_attributes = {} # try to pull the current values from the database so we can initialize # the persistant_attributes dict. This will also create the user if they # do not exist self.db_helper = dbhelper.DBHelper(user, endpoint_url) self.db_helper.init_table() result = self.db_helper.getAll() persistant_attributes = {} if result.value: #user at least exists persistant_attributes = result.value # but we don't want to save the userId so pop that persistant_attributes.pop('userId', None) initial_persistant_attributes = copy.deepcopy(persistant_attributes) # next try to figure out the current state. Look in the event first # and if that fails check our database via the persistant_attributes we just got state = "" if core.STATE_KEY in session_attributes: state = session_attributes[core.STATE_KEY] elif core.STATE_KEY in persistant_attributes: state = persistant_attributes[core.STATE_KEY] # increment invocations if this is a new session. invocations is used # to improve VUI because we know how many times the user has used the skill if event['session']['new']: if 'invocations' in persistant_attributes: persistant_attributes['invocations'] += 1 else: persistant_attributes['invocations'] = 1 # add whether the request is 'new' into the attributes for conveneince # and make sure state is in session_attributes, not persistant attributes session_attributes['new'] = event['session']['new'] session_attributes['user'] = user # at this point we either know the state, or we have returned an error, # or we know it's the users first time and there is no state # so now we dispatch response = self.intent_handler.dispatch(state, persistant_attributes, session_attributes, event) # now that we're done, we need to favorite the recipe # the persistant_attributes dict to our database # but only do it if something change if persistant_attributes != initial_persistant_attributes: self.db_helper.setAll(persistant_attributes) # don't delete this or you can't debug production logging.getLogger(core.LOGGER).warn(json.dumps(response, indent=2)) # ok we're finally done return response
[ "mitranopeter@gmail.com" ]
mitranopeter@gmail.com
b45f60440404180a0a7bd6b2360db7563ad17d57
6946c6ff6fa229e5b968928b34620fe85192729b
/val/evaluate_atr.py
98169caa00056c9cb0bdb0597d90690d67ec181f
[]
no_license
wovai/Hierarchical-Human-Parsing
8a98236930b239fb412033b67c2614376e42769a
58737dbb7763f5a7baafd4801c5a287facf536cd
refs/heads/master
2022-12-18T12:53:10.928088
2020-09-19T15:26:17
2020-09-19T15:26:17
null
0
0
null
null
null
null
UTF-8
Python
false
false
8,024
py
import argparse import os import cv2 import matplotlib.pyplot as plt import numpy as np import torch import torch.nn as nn from torch.autograd import Variable from torch.utils import data from dataset.data_atr import ATRTestGenerator as TestGenerator from network.baseline import get_model def get_arguments(): """Parse all the arguments provided from the CLI. Returns: A list of parsed arguments. """ parser = argparse.ArgumentParser(description="Pytorch Segmentation") parser.add_argument("--root", type=str, default='./data/ATR/test_set/') parser.add_argument("--data-list", type=str, default='./dataset/ATR/test_id.txt') parser.add_argument("--crop-size", type=int, default=513) parser.add_argument("--num-classes", type=int, default=18) parser.add_argument("--ignore-label", type=int, default=255) parser.add_argument("--restore-from", type=str, default='./checkpoints/exp/model_best.pth') parser.add_argument("--is-mirror", action="store_true") parser.add_argument('--eval-scale', nargs='+', type=float, default=[1.0]) # parser.add_argument('--eval-scale', nargs='+', type=float, default=[0.50, 0.75, 1.0, 1.25, 1.50, 1.75]) parser.add_argument("--save-dir", type=str) parser.add_argument("--gpu", type=str, default='0') return parser.parse_args() def main(): """Create the model and start the evaluation process.""" args = get_arguments() # initialization print("Input arguments:") for key, val in vars(args).items(): print("{:16} {}".format(key, val)) os.environ["CUDA_VISIBLE_DEVICES"] = args.gpu model = get_model(num_classes=args.num_classes) # if not os.path.exists(args.save_dir): # os.makedirs(args.save_dir) palette = get_lip_palette() restore_from = args.restore_from saved_state_dict = torch.load(restore_from) model.load_state_dict(saved_state_dict) model.eval() model.cuda() testloader = data.DataLoader(TestGenerator(args.root, args.data_list, crop_size=args.crop_size), batch_size=1, shuffle=False, pin_memory=True) confusion_matrix = np.zeros((args.num_classes, args.num_classes)) for index, batch in enumerate(testloader): if index % 100 == 0: print('%d images have been proceeded' % index) image, label, ori_size, name = batch ori_size = ori_size[0].numpy() output = predict(model, image.numpy(), (np.asscalar(ori_size[0]), np.asscalar(ori_size[1])), is_mirror=args.is_mirror, scales=args.eval_scale) seg_pred = np.asarray(np.argmax(output, axis=2), dtype=np.uint8) # output_im = PILImage.fromarray(seg_pred) # output_im.putpalette(palette) # output_im.save(args.save_dir + name[0] + '.png') seg_gt = np.asarray(label[0].numpy(), dtype=np.int) ignore_index = seg_gt != 255 seg_gt = seg_gt[ignore_index] seg_pred = seg_pred[ignore_index] confusion_matrix += get_confusion_matrix(seg_gt, seg_pred, args.num_classes) pos = confusion_matrix.sum(1) res = confusion_matrix.sum(0) tp = np.diag(confusion_matrix) pixel_accuracy = tp.sum() / pos.sum() mean_accuracy = (tp / np.maximum(1.0, pos)).mean() IU_array = (tp / np.maximum(1.0, pos + res - tp)) mean_IU = IU_array.mean() # get_confusion_matrix_plot() print('Pixel accuracy: %f \n' % pixel_accuracy) print('Mean accuracy: %f \n' % mean_accuracy) print('Mean IU: %f \n' % mean_IU) for index, IU in enumerate(IU_array): print('%f ', IU) def scale_image(image, scale): image = image[0, :, :, :] image = image.transpose((1, 2, 0)) image = cv2.resize(image, None, fx=scale, fy=scale, interpolation=cv2.INTER_LINEAR) image = image.transpose((2, 0, 1)) return image def predict(net, image, output_size, is_mirror=True, scales=[1]): if is_mirror: image_rev = image[:, :, :, ::-1] interp = nn.Upsample(size=output_size, mode='bilinear', align_corners=True) outputs = [] if is_mirror: for scale in scales: if scale != 1: image_scale = scale_image(image=image, scale=scale) image_rev_scale = scale_image(image=image_rev, scale=scale) else: image_scale = image[0, :, :, :] image_rev_scale = image_rev[0, :, :, :] image_scale = np.stack((image_scale, image_rev_scale)) with torch.no_grad(): prediction = net(Variable(torch.from_numpy(image_scale)).cuda()) prediction = interp(prediction[0]).cpu().data.numpy() prediction_rev = prediction[1, :, :, :].copy() prediction_rev[9, :, :] = prediction[1, 10, :, :] prediction_rev[10, :, :] = prediction[1, 9, :, :] prediction_rev[12, :, :] = prediction[1, 13, :, :] prediction_rev[13, :, :] = prediction[1, 12, :, :] prediction_rev[14, :, :] = prediction[1, 15, :, :] prediction_rev[15, :, :] = prediction[1, 14, :, :] prediction_rev = prediction_rev[:, :, ::-1] prediction = prediction[0, :, :, :] prediction = np.mean([prediction, prediction_rev], axis=0) outputs.append(prediction) outputs = np.mean(outputs, axis=0) outputs = outputs.transpose(1, 2, 0) else: for scale in scales: if scale != 1: image_scale = scale_image(image=image, scale=scale) else: image_scale = image[0, :, :, :] with torch.no_grad(): prediction = net(Variable(torch.from_numpy(image_scale).unsqueeze(0)).cuda()) prediction = interp(prediction[0]).cpu().data.numpy() outputs.append(prediction[0, :, :, :]) outputs = np.mean(outputs, axis=0) outputs = outputs.transpose(1, 2, 0) return outputs def get_confusion_matrix(gt_label, pred_label, class_num): """ Calculate the confusion matrix by given label and pred :param gt_label: the ground truth label :param pred_label: the pred label :param class_num: the nunber of class """ index = (gt_label * class_num + pred_label).astype('int32') label_count = np.bincount(index) confusion_matrix = np.zeros((class_num, class_num)) for i_label in range(class_num): for i_pred_label in range(class_num): cur_index = i_label * class_num + i_pred_label if cur_index < len(label_count): confusion_matrix[i_label, i_pred_label] = label_count[cur_index] return confusion_matrix def get_confusion_matrix_plot(conf_arr): norm_conf = [] for i in conf_arr: tmp_arr = [] a = sum(i, 0) for j in i: tmp_arr.append(float(j) / max(1.0, float(a))) norm_conf.append(tmp_arr) fig = plt.figure() plt.clf() ax = fig.add_subplot(111) ax.set_aspect(1) res = ax.imshow(np.array(norm_conf), cmap=plt.cm.jet, interpolation='nearest') width, height = conf_arr.shape cb = fig.colorbar(res) alphabet = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ' plt.xticks(range(width), alphabet[:width]) plt.yticks(range(height), alphabet[:height]) plt.savefig('confusion_matrix.png', format='png') def get_lip_palette(): palette = [0, 0, 0, 128, 0, 0, 255, 0, 0, 0, 85, 0, 170, 0, 51, 255, 85, 0, 0, 0, 85, 0, 119, 221, 85, 85, 0, 0, 85, 85, 85, 51, 0, 52, 86, 128, 0, 128, 0, 0, 0, 255, 51, 170, 221, 0, 255, 255, 85, 255, 170, 170, 255, 85, 255, 255, 0, 255, 170, 0] return palette if __name__ == '__main__': main()
[ "908865817@qq.com" ]
908865817@qq.com
2e37583a1831659a3dc55f96a8b9ced27ebfee96
c071eb46184635818e8349ce9c2a78d6c6e460fc
/system/python_stubs/-745935208/PySide2/QtNetwork/QNetworkRequest.py
ccb10fdfe22346491df2ee7774c525d73ba453d0
[]
no_license
sidbmw/PyCharm-Settings
a71bc594c83829a1522e215155686381b8ac5c6e
083f9fe945ee5358346e5d86b17130d521d1b954
refs/heads/master
2020-04-05T14:24:03.216082
2018-12-28T02:29:29
2018-12-28T02:29:29
156,927,399
0
0
null
null
null
null
UTF-8
Python
false
false
6,151
py
# encoding: utf-8 # module PySide2.QtNetwork # from C:\Users\siddh\AppData\Local\Programs\Python\Python37\lib\site-packages\PySide2\QtNetwork.pyd # by generator 1.146 # no doc # imports import PySide2.QtCore as __PySide2_QtCore import Shiboken as __Shiboken class QNetworkRequest(__Shiboken.Object): # no doc def attribute(self, *args, **kwargs): # real signature unknown pass def hasRawHeader(self, *args, **kwargs): # real signature unknown pass def header(self, *args, **kwargs): # real signature unknown pass def maximumRedirectsAllowed(self, *args, **kwargs): # real signature unknown pass def originatingObject(self, *args, **kwargs): # real signature unknown pass def priority(self, *args, **kwargs): # real signature unknown pass def rawHeader(self, *args, **kwargs): # real signature unknown pass def rawHeaderList(self, *args, **kwargs): # real signature unknown pass def setAttribute(self, *args, **kwargs): # real signature unknown pass def setHeader(self, *args, **kwargs): # real signature unknown pass def setMaximumRedirectsAllowed(self, *args, **kwargs): # real signature unknown pass def setOriginatingObject(self, *args, **kwargs): # real signature unknown pass def setPriority(self, *args, **kwargs): # real signature unknown pass def setRawHeader(self, *args, **kwargs): # real signature unknown pass def setSslConfiguration(self, *args, **kwargs): # real signature unknown pass def setUrl(self, *args, **kwargs): # real signature unknown pass def sslConfiguration(self, *args, **kwargs): # real signature unknown pass def swap(self, *args, **kwargs): # real signature unknown pass def url(self, *args, **kwargs): # real signature unknown pass def __copy__(self, *args, **kwargs): # real signature unknown pass def __eq__(self, *args, **kwargs): # real signature unknown """ Return self==value. """ pass def __ge__(self, *args, **kwargs): # real signature unknown """ Return self>=value. """ pass def __gt__(self, *args, **kwargs): # real signature unknown """ Return self>value. """ pass def __init__(self, *args, **kwargs): # real signature unknown pass def __le__(self, *args, **kwargs): # real signature unknown """ Return self<=value. """ pass def __lt__(self, *args, **kwargs): # real signature unknown """ Return self<value. """ pass @staticmethod # known case of __new__ def __new__(*args, **kwargs): # real signature unknown """ Create and return a new object. See help(type) for accurate signature. """ pass def __ne__(self, *args, **kwargs): # real signature unknown """ Return self!=value. """ pass AlwaysCache = None # (!) real value is '' AlwaysNetwork = None # (!) real value is '' Attribute = None # (!) real value is '' AuthenticationReuseAttribute = None # (!) real value is '' Automatic = None # (!) real value is '' BackgroundRequestAttribute = None # (!) real value is '' CacheLoadControl = None # (!) real value is '' CacheLoadControlAttribute = None # (!) real value is '' CacheSaveControlAttribute = None # (!) real value is '' ConnectionEncryptedAttribute = None # (!) real value is '' ContentDispositionHeader = None # (!) real value is '' ContentLengthHeader = None # (!) real value is '' ContentTypeHeader = None # (!) real value is '' CookieHeader = None # (!) real value is '' CookieLoadControlAttribute = None # (!) real value is '' CookieSaveControlAttribute = None # (!) real value is '' CustomVerbAttribute = None # (!) real value is '' DoNotBufferUploadDataAttribute = None # (!) real value is '' DownloadBufferAttribute = None # (!) real value is '' EmitAllUploadProgressSignalsAttribute = None # (!) real value is '' FollowRedirectsAttribute = None # (!) real value is '' HighPriority = None # (!) real value is '' HTTP2AllowedAttribute = None # (!) real value is '' Http2DirectAttribute = None # (!) real value is '' HTTP2WasUsedAttribute = None # (!) real value is '' HttpPipeliningAllowedAttribute = None # (!) real value is '' HttpPipeliningWasUsedAttribute = None # (!) real value is '' HttpReasonPhraseAttribute = None # (!) real value is '' HttpStatusCodeAttribute = None # (!) real value is '' KnownHeaders = None # (!) real value is '' LastModifiedHeader = None # (!) real value is '' LoadControl = None # (!) real value is '' LocationHeader = None # (!) real value is '' LowPriority = None # (!) real value is '' Manual = None # (!) real value is '' ManualRedirectPolicy = None # (!) real value is '' MaximumDownloadBufferSizeAttribute = None # (!) real value is '' NoLessSafeRedirectPolicy = None # (!) real value is '' NormalPriority = None # (!) real value is '' OriginalContentLengthAttribute = None # (!) real value is '' PreferCache = None # (!) real value is '' PreferNetwork = None # (!) real value is '' Priority = None # (!) real value is '' RedirectionTargetAttribute = None # (!) real value is '' RedirectPolicy = None # (!) real value is '' RedirectPolicyAttribute = None # (!) real value is '' ResourceTypeAttribute = None # (!) real value is '' SameOriginRedirectPolicy = None # (!) real value is '' ServerHeader = None # (!) real value is '' SetCookieHeader = None # (!) real value is '' SourceIsFromCacheAttribute = None # (!) real value is '' SpdyAllowedAttribute = None # (!) real value is '' SpdyWasUsedAttribute = None # (!) real value is '' SynchronousRequestAttribute = None # (!) real value is '' User = None # (!) real value is '' UserAgentHeader = None # (!) real value is '' UserMax = None # (!) real value is '' UserVerifiedRedirectPolicy = None # (!) real value is '' __hash__ = None
[ "siddharthnatamai@gmail.com" ]
siddharthnatamai@gmail.com
e619cceed7ad73fb07942df520efdbcc1f04a953
163bbb4e0920dedd5941e3edfb2d8706ba75627d
/Code/CodeRecords/2570/60618/303481.py
0337b9b984df63071c855f8763aef609192d23b7
[]
no_license
AdamZhouSE/pythonHomework
a25c120b03a158d60aaa9fdc5fb203b1bb377a19
ffc5606817a666aa6241cfab27364326f5c066ff
refs/heads/master
2022-11-24T08:05:22.122011
2020-07-28T16:21:24
2020-07-28T16:21:24
259,576,640
2
1
null
null
null
null
UTF-8
Python
false
false
531
py
from bisect import bisect_left n=int(input()) arr=[[0]*2]*n for i in range(0,n): arr[i]=[int(k) for k in input().split(",")] # sort increasing in first dimension and decreasing on second arr.sort(key=lambda x: (x[0], -x[1])) def lis(nums): dp = [] for i in range(len(nums)): idx = bisect_left(dp, nums[i]) if idx == len(dp): dp.append(nums[i]) else: dp[idx] = nums[i] return len(dp) # extract the second dimension and run the LIS return lis([i[1] for i in arr])
[ "1069583789@qq.com" ]
1069583789@qq.com
0a7b49b4e997fd25af6ea472f4e98a232abd3f33
597c3a6200867b45b45b7f33ee020bfa91aede5d
/Week-1024/879.py
02d46ee3996da11cbfb581d23007f55e65f568e6
[]
no_license
Bieneath/LeetCode_training
997251387f9faf7c1301cbc9900d3fbfcc7a7a37
822747436c3499c802b90fab2577577309e2f5b7
refs/heads/master
2023-05-09T21:30:36.409743
2021-06-15T15:22:34
2021-06-15T15:22:34
377,205,044
0
0
null
null
null
null
UTF-8
Python
false
false
920
py
# 二维DP算法 https://leetcode.com/problems/profitable-schemes/discuss/154617/C%2B%2BJavaPython-DP # 这题基本思路不难,类似搭桥问题,计划方案“2人3收益”相当于桥梁,dp[i+3][j+2]的方案数能继承自dp[i][j]通过此方案。但是这题细节方面比较难想。比如这里为什么要反向遍历?原因是当前dp[i][j]需要由dp[i-?][j-?]计算获得,同时这里有个时序性,新的方案要在之前方案实施结果之上计算得出。 class Solution: def profitableSchemes(self, n: int, target: int, group: List[int], profit: List[int]) -> int: dp = [[0] * (n + 1) for _ in range(target + 1)] dp[0][0] = 1 for g, p in zip(group, profit): for i in range(target, -1, -1): for j in range(n - g, -1, -1): dp[min(target, i + p)][j + g] += dp[i][j] return sum(dp[target]) % (10**9 + 7)
[ "wulijieru@gmail.com" ]
wulijieru@gmail.com
7908104ec0c51de2f7300174a01e4037848a0656
9430ebd88984bf5b5fdbca90988d03e45c5fb78f
/apps/app/admin.py
e4aa5b8eeb8b88ef17387bb43f237d144b59330b
[]
no_license
osw4l/liveset-api
6beb05e7f1ce52fe5ef1e6dc0615f6a0a9312e83
a72f0b86f1f452b577c10f195ecb6d28c2ee5c07
refs/heads/master
2022-12-11T20:48:54.295538
2019-09-16T14:01:00
2019-09-16T14:01:00
207,845,311
1
0
null
2022-07-15T20:31:03
2019-09-11T15:26:20
Python
UTF-8
Python
false
false
485
py
from django.contrib import admin from . import models # Register your models here. admin.site.site_header = 'LiveSet Admin' admin.site.site_title = 'LiveSet Admin' admin.site.index_title = 'LiveSet Admin' COMMON_LIST_DISPLAY = ['id', 'name', 'order', 'file', 'active'] @admin.register(models.Song) class SongAdmin(admin.ModelAdmin): list_display = COMMON_LIST_DISPLAY @admin.register(models.Video) class VideoAdmin(admin.ModelAdmin): list_display = COMMON_LIST_DISPLAY
[ "ioswxd@gmail.com" ]
ioswxd@gmail.com
d04c6ba42829c8b9e5a5013b0e250ab5033003eb
e32bb97b6b18dfd48760ed28553a564055878d48
/source_py3/python_toolbox/nifty_collections/frozen_counter.py
fd7ef390df0b1a0045e8ed9d52e4159678f1f422
[ "MIT" ]
permissive
rfdiazpr/python_toolbox
26cb37dd42342c478931699b00d9061aedcd924a
430dd842ed48bccdb3a3166e91f76bd2aae75a88
refs/heads/master
2020-12-31T04:15:53.977935
2014-04-30T23:54:58
2014-04-30T23:54:58
null
0
0
null
null
null
null
UTF-8
Python
false
false
7,032
py
# Copyright 2009-2014 Ram Rachum., # This program is distributed under the MIT license. import operator import heapq import itertools import collections from .frozen_dict import FrozenDict try: # Load C helper function if available from _collections import _count_elements except ImportError: def _count_elements(mapping, iterable): '''Tally elements from the iterable.''' mapping_get = mapping.get for element in iterable: mapping[element] = mapping_get(element, 0) + 1 class FrozenCounter(FrozenDict): ''' An immutable counter. A counter that can't be changed. The advantage of this over `collections.Counter` is mainly that it's hashable, and thus can be used as a key in dicts and sets. In other words, `FrozenCounter` is to `Counter` what `frozenset` is to `set`. ''' def __init__(self, iterable=None, **kwargs): super().__init__() if iterable is not None: if isinstance(iterable, collections.Mapping): self._dict.update(iterable) else: _count_elements(self._dict, iterable) if kwargs: self._dict.update(kwargs) for key, value in self.items(): if value == 0: del self._dict[key] __getitem__ = lambda self, key: self._dict.get(key, 0) def most_common(self, n=None): ''' List the `n` most common elements and their counts, sorted. Results are sorted from the most common to the least. If `n is None`, then list all element counts. >>> FrozenCounter('abcdeabcdabcaba').most_common(3) [('a', 5), ('b', 4), ('c', 3)] ''' # Emulate Bag.sortedByCount from Smalltalk if n is None: return sorted(self.items(), key=operator.itemgetter(1), reverse=True) return heapq.nlargest(n, self.items(), key=operator.itemgetter(1)) def elements(self): ''' Iterate over elements repeating each as many times as its count. >>> c = FrozenCounter('ABCABC') >>> sorted(c.elements()) ['A', 'A', 'B', 'B', 'C', 'C'] # Knuth's example for prime factors of 1836: 2**2 * 3**3 * 17**1 >>> prime_factors = FrozenCounter({2: 2, 3: 3, 17: 1}) >>> product = 1 >>> for factor in prime_factors.elements(): # loop over factors ... product *= factor # and multiply them >>> product 1836 Note, if an element's count has been set to zero or is a negative number, `.elements()` will ignore it. ''' # Emulate Bag.do from Smalltalk and Multiset.begin from C++. return itertools.chain.from_iterable( itertools.starmap(itertools.repeat, self.items()) ) @classmethod def fromkeys(cls, iterable, v=None): # There is no equivalent method for counters because setting v=1 # means that no element can have a count greater than one. raise NotImplementedError( 'FrozenCounter.fromkeys() is undefined. Use ' 'FrozenCounter(iterable) instead.' ) def __repr__(self): if not self: return '%s()' % self.__class__.__name__ try: items = ', '.join(map('%r: %r'.__mod__, self.most_common())) return '%s({%s})' % (self.__class__.__name__, items) except TypeError: # handle case where values are not orderable return '{0}({1!r})'.format(self.__class__.__name__, dict(self)) __pos__ = lambda self: self __neg__ = lambda self: type(self)({key: -value for key, value in self.items()}) # Multiset-style mathematical operations discussed in: # Knuth TAOCP Volume II section 4.6.3 exercise 19 # and at http://en.wikipedia.org/wiki/Multiset # # Outputs guaranteed to only include positive counts. # # To strip negative and zero counts, add-in an empty counter: # c += FrozenCounter() def __add__(self, other): ''' Add counts from two counters. >>> FrozenCounter('abbb') + FrozenCounter('bcc') FrozenCounter({'b': 4, 'c': 2, 'a': 1}) ''' if not isinstance(other, FrozenCounter): return NotImplemented result = collections.Counter() for element, count in self.items(): new_count = count + other[element] if new_count > 0: result[element] = new_count for element, count in other.items(): if element not in self and count > 0: result[element] = count return FrozenCounter(result) def __sub__(self, other): ''' Subtract count, but keep only results with positive counts. >>> FrozenCounter('abbbc') - FrozenCounter('bccd') FrozenCounter({'b': 2, 'a': 1}) ''' if not isinstance(other, FrozenCounter): return NotImplemented result = collections.Counter() for element, count in self.items(): new_count = count - other[element] if new_count > 0: result[element] = new_count for element, count in other.items(): if element not in self and count < 0: result[element] = 0 - count return FrozenCounter(result) def __or__(self, other): ''' Get the maximum of value in either of the input counters. >>> FrozenCounter('abbb') | FrozenCounter('bcc') FrozenCounter({'b': 3, 'c': 2, 'a': 1}) ''' if not isinstance(other, FrozenCounter): return NotImplemented result = collections.Counter() for element, count in self.items(): other_count = other[element] new_count = other_count if count < other_count else count if new_count > 0: result[element] = new_count for element, count in other.items(): if element not in self and count > 0: result[element] = count return FrozenCounter(result) def __and__(self, other): ''' Get the minimum of corresponding counts. >>> FrozenCounter('abbb') & FrozenCounter('bcc') FrozenCounter({'b': 1}) ''' if not isinstance(other, FrozenCounter): return NotImplemented result = collections.Counter() for element, count in self.items(): other_count = other[element] new_count = count if count < other_count else other_count if new_count > 0: result[element] = new_count return FrozenCounter(result)
[ "ram@rachum.com" ]
ram@rachum.com
249f9e2f69877fe4448d722e21e8c98bdfa37b13
b9ad209a76cbe0d2abf8831b9ac645e6d71819a0
/pharos/model/laser/_skeleton.py
1c1d5ecf6833a55fde8a36f26d341b9b8ae36e68
[ "MIT" ]
permissive
uetke/UUPharosController
75327213b487eee675c6a597616825e29357fac7
1663dcb5acab78fe65eab9eee7948d1257dec1f0
refs/heads/master
2022-12-09T22:09:35.715086
2019-11-08T08:53:24
2019-11-08T08:53:24
125,031,611
0
0
NOASSERTION
2022-12-08T00:39:50
2018-03-13T10:11:02
Python
UTF-8
Python
false
false
1,199
py
""" Pharos.Model.laser._skeleton.py ================================== .. note:: **IMPORTANT** Whatever new function is implemented in a specific model, it should be first declared in the laserBase class. In this way the other models will have access to the method and the program will keep running (perhaps with non intended behavior though). .. sectionauthor:: Aquiles Carattino <aquiles@uetke.com> """ class LaserBase(): # Trigger modes TRIG_NO = 0 TRIG_EXTERNAL = 1 TRIG_SOFTWARE = 2 TRIG_OUTPUT = 3 # Scan modes MODE_SINGLE = 1 MODE_TWO_WAY = 2 MODE_STEP_SINGLE = 3 MODE_STEP_TWO_WAY = 4 # Parameters (wavelength or frequency) PARAM_WAVELENGTH = 1 PARAM_FREQUENCY = 2 def __init__(self): self.trig_mode = self.TRIG_NO # Means the trigger was not set. def wavelength_scan_setup(self, start, end, steps, time, trigger, mode): pass def frequency_scan_setup(self, start, end, steps, time, trigger, mode): pass def trigger_scan(self): pass def is_running(self): pass def stop_scan(self): pass
[ "aquiles@aquicarattino.com" ]
aquiles@aquicarattino.com
51c9b07ba3496bc09cd69c35dafcc738492c8585
387587c753e76d98a6a0401327766c45561d5109
/ros_catkin_ws/build_isolated/catkin/catkin_generated/generate_cached_setup.py
50eaf805d6a24edc1d0be26eba3b7c3229fbea9a
[ "MIT" ]
permissive
letrend/neopixel_fpga
7a4819a566fab02bd602c3338b8aaa0ddf4bee85
d9247417a9d311eceebad5898571846c6e33a44a
refs/heads/master
2021-01-23T01:00:55.290431
2017-05-30T20:15:38
2017-05-30T20:15:38
92,855,363
0
0
null
null
null
null
UTF-8
Python
false
false
1,286
py
# -*- coding: utf-8 -*- from __future__ import print_function import argparse import os import stat import sys # find the import for catkin's python package - either from source space or from an installed underlay if os.path.exists(os.path.join('/root/ros_catkin_ws/src/catkin/cmake', 'catkinConfig.cmake.in')): sys.path.insert(0, os.path.join('/root/ros_catkin_ws/src/catkin/cmake', '..', 'python')) try: from catkin.environment_cache import generate_environment_script except ImportError: # search for catkin package in all workspaces and prepend to path for workspace in "".split(';'): python_path = os.path.join(workspace, 'lib/python2.7/dist-packages') if os.path.isdir(os.path.join(python_path, 'catkin')): sys.path.insert(0, python_path) break from catkin.environment_cache import generate_environment_script code = generate_environment_script('/root/ros_catkin_ws/devel_isolated/catkin/env.sh') output_filename = '/root/ros_catkin_ws/build_isolated/catkin/catkin_generated/setup_cached.sh' with open(output_filename, 'w') as f: #print('Generate script for cached setup "%s"' % output_filename) f.write('\n'.join(code)) mode = os.stat(output_filename).st_mode os.chmod(output_filename, mode | stat.S_IXUSR)
[ "simon.trendel@tum.de" ]
simon.trendel@tum.de
15d31e1ef365d5c015dfb414451088dad3046aa5
93039551fbdef0a112a9c39181d30b0c170eb3a6
/day18/threadingDemo.py
fae63177bdaf8ea6bd2a0e600b6f0182253b4090
[]
no_license
wenzhe980406/PythonLearning
8714de8a472c71e6d02b6de64efba970a77f6f4a
af0e85f0b11bf9d2f8e690bac480b92b971c01bb
refs/heads/master
2020-07-14T20:46:45.146134
2020-05-28T12:16:21
2020-05-28T12:16:21
205,398,758
0
0
null
null
null
null
UTF-8
Python
false
false
2,128
py
# _*_ coding : UTF-8 _*_ # 开发人员 : ChangYw # 开发时间 : 2019/8/7 14:17 # 文件名称 : threadingDemo.PY # 开发工具 : PyCharm #创建线程 import threading import time import random # def foo(info): # # 每个线程都会有个ID # print("线程ID:",threading.get_ident()) # # 当前线程名字 # print(threading.current_thread()) # # 当前线程所在进程下,活的线程数目 # print(threading.active_count()) # print("%s : abcdef"%info) # # t = threading.Thread(target=foo,name="FirstThread",args=("first thread demo",)) # # t.start() # # def addnum(): # m = 0 # for i in range(1,101): # m += i # print("m: ",m) # # 每个线程都会有个ID # print("线程ID:", threading.get_ident()) # # 当前线程名字 # print(threading.current_thread()) # # 当前线程所在进程下,活的线程数目 # print(threading.active_count()) # # t1 = threading.Thread(target=addnum,name="addNumThread" ) # t1.start() # # s_name = "常译文" # # def show(tname) : # print(tname,end=" : ") # while True: # for c in s_name: # print(c,end="") # print() # # # #show("demo") # threading.Thread(target=show,name = "C1",args=("thread-1",)).start() # threading.Thread(target=show,name = "C2",args=("thread-2",)).start() class MyThread(threading.Thread): def __init__(self,info): super().__init__() self.info = info def run(self): print(self.info) time.sleep(2) print("当前存活的线程数目:%d"%threading.active_count()) print(threading.current_thread()," ending...") if __name__ == '__main__': start_time = time.time() t1 = MyThread("Hello World!") t2 = MyThread("Heelo Python!") t1.start() t2.start() t1.join() t2.join() print("main : 当前存活的线程数目:%d !" % threading.active_count()) print("main threading ...........") end_time = time.time() print("运行时间:",start_time-end_time)
[ "noreply@github.com" ]
wenzhe980406.noreply@github.com
578a554b115b2e94e83688007ac6dae9ef220ae9
600df3590cce1fe49b9a96e9ca5b5242884a2a70
/tools/perf/benchmarks/chrome_signin_startup.py
dc5c26d8f0da3caecaadf66654f24c754fa71e16
[ "BSD-3-Clause", "LGPL-2.0-or-later", "LicenseRef-scancode-unknown-license-reference", "GPL-2.0-only", "Apache-2.0", "LicenseRef-scancode-unknown", "MIT" ]
permissive
metux/chromium-suckless
efd087ba4f4070a6caac5bfbfb0f7a4e2f3c438a
72a05af97787001756bae2511b7985e61498c965
refs/heads/orig
2022-12-04T23:53:58.681218
2017-04-30T10:59:06
2017-04-30T23:35:58
89,884,931
5
3
BSD-3-Clause
2022-11-23T20:52:53
2017-05-01T00:09:08
null
UTF-8
Python
false
false
930
py
# Copyright 2015 The Chromium Authors. All rights reserved. # Use of this source code is governed by a BSD-style license that can be # found in the LICENSE file. from core import perf_benchmark from measurements import startup import page_sets from telemetry import benchmark class _StartupWarm(perf_benchmark.PerfBenchmark): """Measures warm startup time with a clean profile.""" options = {'pageset_repeat': 5} @classmethod def Name(cls): return 'chrome_signin_starup' def CreatePageTest(self, options): return startup.Startup(cold=False) @benchmark.Disabled('all') # crbug.com/551938 # On android logging in is done through system accounts workflow. @benchmark.Disabled('android') class SigninStartup(_StartupWarm): """Measures warm startup time of signing a profile into Chrome.""" page_set = page_sets.ChromeSigninPageSet @classmethod def Name(cls): return 'startup.warm.chrome_signin'
[ "enrico.weigelt@gr13.net" ]
enrico.weigelt@gr13.net
e3a1d26b74c3f2fce64a4ca7a8279e45eaa60168
3a958811aaecab99efd57c35613aa88251eae0ec
/openrec/tf2/recommenders/bpr.py
7f8a91595fb878698bfc8835a10c03f338260ce2
[ "Apache-2.0" ]
permissive
jstephenj14/openrec
99c74f7c600b000828fa355bc66653b3857391a4
82e7644d062be5fbe62eec80975023c8acd7ba69
refs/heads/master
2022-11-08T04:13:09.901161
2020-07-01T17:03:02
2020-07-01T17:03:02
275,661,063
0
0
Apache-2.0
2020-06-28T20:15:29
2020-06-28T20:15:29
null
UTF-8
Python
false
false
1,958
py
import tensorflow as tf from tensorflow.keras import Model from openrec.tf2.modules import LatentFactor, PairwiseLogLoss class BPR(Model): def __init__(self, dim_user_embed, dim_item_embed, total_users, total_items): super(BPR, self).__init__() self.user_latent_factor = LatentFactor(num_instances=total_users, dim=dim_user_embed, name='user_latent_factor') self.item_latent_factor = LatentFactor(num_instances=total_items, dim=dim_item_embed, name='item_latent_factor') self.item_bias = LatentFactor(num_instances=total_items, dim=1, name='item_bias') self.pairwise_log_loss = PairwiseLogLoss() def call(self, user_id, p_item_id, n_item_id): user_vec = self.user_latent_factor(user_id) p_item_vec = self.item_latent_factor(p_item_id) p_item_bias = self.item_bias(p_item_id) n_item_vec = self.item_latent_factor(n_item_id) n_item_bias = self.item_bias(n_item_id) loss = self.pairwise_log_loss(user_vec=user_vec, p_item_vec=p_item_vec, p_item_bias=p_item_bias, n_item_vec=n_item_vec, n_item_bias=n_item_bias) l2_loss = tf.nn.l2_loss(user_vec) + tf.nn.l2_loss(p_item_vec) + tf.nn.l2_loss(n_item_vec) return loss, l2_loss def inference(self, user_id): user_vec = self.user_latent_factor(user_id) return tf.linalg.matmul(user_vec, self.item_latent_factor.variables[0], transpose_b=True) + \ tf.reshape(self.item_bias.variables[0], [-1])
[ "ylongqi@gmail.com" ]
ylongqi@gmail.com
e01e22f4e81782157601986893044790c22e2567
25d8bac5635ac1cc3577a3593a4512e042ea7ecd
/scripts/stringio-example-1.py
feb5a0c9f91412032c72f30c0a1526508d1ff671
[]
no_license
mtslong/demo
2333fa571d6d9def7bdffc90f7bcb623b15e6e4b
a78b74e0eea7f84df489f5c70969b9b4797a4873
refs/heads/master
2020-05-18T18:28:48.237100
2013-11-11T16:10:11
2013-11-11T16:10:11
4,136,487
0
0
null
null
null
null
UTF-8
Python
false
false
221
py
import StringIO MESSAGE = "That man is depriving a village somewhere of a computer scientist." file = StringIO.StringIO(MESSAGE) print file.read() ## That man is depriving a village somewhere of a computer scientist.
[ "mofeng@netease.com" ]
mofeng@netease.com
f3c9309ccc53b3488f54d9bbe3080b0db359c756
acaed6ad4a2bb3f6df553debf547d0feafdd99e9
/Projects/Object-Oriented Python/s4v3/yatzy/dice.py
cfc2b1878f219bb3a9d4beb3fb205377aa310e4c
[]
no_license
SAM1363/TH-Python
764691b7b8281b3298ace985039ee9c05ef340a1
421c4d7f54ed56233a87c7d9907ac3d1ab993c94
refs/heads/master
2020-05-30T01:12:49.404476
2019-08-04T04:45:32
2019-08-04T04:45:32
189,472,375
0
0
null
null
null
null
UTF-8
Python
false
false
1,049
py
import random class Die: def __init__(self, sides=2, value=0): if not sides >= 2: raise ValueError("Must have at least 2 sides") if not isinstance(sides, int): raise ValueError("Sides must be a whole number") self.value = value or random.randint(1, sides) def __int__(self): return self.value def __eq__(self, other): return int(self) == other def __ne__(self, other): return int(self) != other def __gt__(self, other): return int(self) > other def __lt__(self, other): return int(self) < other def __ge__(self, other): return int(self) > other or int(self) == other def __le__(self, other): return int(self) < other or int(self) == other def __add__(self, other): return int(self) + other def __radd__(self, other): return int(self) + other class D6(Die): def __init__(self, value=0): super().__init__(sides=6, value=value)
[ "isamu3636136@gmail.com" ]
isamu3636136@gmail.com
844a6397218e0f54788ae9dc1533204565febe03
b6df7cda5c23cda304fcc0af1450ac3c27a224c1
/data/codes/rharkanson___main__.py
7f6c1bda290f0be888529fc6a288b0d71d4581a4
[ "LicenseRef-scancode-unknown-license-reference", "MIT" ]
permissive
vieira-rafael/py-search
88ee167fa1949414cc4f3c98d33f8ecec1ce756d
b8c6dccc58d72af35e4d4631f21178296f610b8a
refs/heads/master
2021-01-21T04:59:36.220510
2016-06-20T01:45:34
2016-06-20T01:45:34
54,433,313
2
4
null
null
null
null
UTF-8
Python
false
false
463
py
"""Copyright (c) 2015 Russell HarkansonSee the file LICENSE.txt for copying permission.""" import sys if sys.version < '3': print("Error: Python 3+ required to run Pyriscope.") sys.exit(1) from pyriscope import processor def main(args=None): if args is None: args = sys.argv[1:] if len(args) == 1 and args[0] == "__magic__": args = input("Enter args now: ").strip(' ').split(' ') processor.process(args) if __name__ == "__main__": main()
[ "thaisnviana@gmail.com" ]
thaisnviana@gmail.com
87a4d6379a57b223782ee0439925eb51823274c4
bd498cbbb28e33370298a84b693f93a3058d3138
/NVIDIA/benchmarks/transformer/implementations/pytorch/fairseq/modules/linearized_convolution.py
63a048b847b360f6553b6887b508f4883a8867dd
[ "Apache-2.0", "BSD-3-Clause" ]
permissive
piyushghai/training_results_v0.7
afb303446e75e3e9789b0f6c40ce330b6b83a70c
e017c9359f66e2d814c6990d1ffa56654a73f5b0
refs/heads/master
2022-12-19T16:50:17.372320
2020-09-24T01:02:00
2020-09-24T18:01:01
298,127,245
0
1
Apache-2.0
2020-09-24T00:27:21
2020-09-24T00:27:21
null
UTF-8
Python
false
false
3,686
py
# Copyright (c) 2017-present, Facebook, Inc. # All rights reserved. # # This source code is licensed under the license found in the LICENSE file in # the root directory of this source tree. An additional grant of patent rights # can be found in the PATENTS file in the same directory. import torch import torch.nn.functional as F from fairseq import utils from .conv_tbc import ConvTBC class LinearizedConvolution(ConvTBC): """An optimized version of nn.Conv1d. At training time, this module uses ConvTBC, which is an optimized version of Conv1d. At inference time, it optimizes incremental generation (i.e., one time step at a time) by replacing the convolutions with linear layers. Note that the input order changes from training to inference. """ def __init__(self, in_channels, out_channels, kernel_size, **kwargs): super().__init__(in_channels, out_channels, kernel_size, **kwargs) self._linearized_weight = None self.register_backward_hook(self._clear_linearized_weight) def forward(self, input, incremental_state=None): """ Input: Time x Batch x Channel during training Batch x Time x Channel during inference Args: incremental_state: Used to buffer signal; if not None, then input is expected to contain a single frame. If the input order changes between time steps, call reorder_incremental_state. """ if incremental_state is None: output = super().forward(input) if self.kernel_size[0] > 1 and self.padding[0] > 0: # remove future timesteps added by padding output = output[:-self.padding[0], :, :] return output # reshape weight weight = self._get_linearized_weight() kw = self.kernel_size[0] bsz = input.size(0) # input: bsz x len x dim if kw > 1: input = input.data input_buffer = self._get_input_buffer(incremental_state) if input_buffer is None: input_buffer = input.new(bsz, kw, input.size(2)).zero_() self._set_input_buffer(incremental_state, input_buffer) else: # shift buffer input_buffer[:, :-1, :] = input_buffer[:, 1:, :].clone() # append next input input_buffer[:, -1, :] = input[:, -1, :] input = input_buffer with torch.no_grad(): output = F.linear(input.view(bsz, -1), weight, self.bias) return output.view(bsz, 1, -1) def reorder_incremental_state(self, incremental_state, new_order): input_buffer = self._get_input_buffer(incremental_state) if input_buffer is not None: input_buffer = input_buffer.index_select(0, new_order) self._set_input_buffer(incremental_state, input_buffer) def _get_input_buffer(self, incremental_state): return utils.get_incremental_state(self, incremental_state, 'input_buffer') def _set_input_buffer(self, incremental_state, new_buffer): return utils.set_incremental_state(self, incremental_state, 'input_buffer', new_buffer) def _get_linearized_weight(self): if self._linearized_weight is None: kw = self.kernel_size[0] weight = self.weight.transpose(2, 1).transpose(1, 0).contiguous() assert weight.size() == (self.out_channels, kw, self.in_channels) self._linearized_weight = weight.view(self.out_channels, -1) return self._linearized_weight def _clear_linearized_weight(self, *args): self._linearized_weight = None
[ "vbittorf@google.com" ]
vbittorf@google.com
ce2898edf44b34d49b7ae631ffd775947a938bf7
6189f34eff2831e3e727cd7c5e43bc5b591adffc
/WebMirror/management/rss_parser_funcs/feed_parse_extractLogatseTranslations.py
c472045f62f8112b3f4a93c84e4c956a1e0a6b9b
[ "BSD-3-Clause" ]
permissive
fake-name/ReadableWebProxy
24603660b204a9e7965cfdd4a942ff62d7711e27
ca2e086818433abc08c014dd06bfd22d4985ea2a
refs/heads/master
2023-09-04T03:54:50.043051
2023-08-26T16:08:46
2023-08-26T16:08:46
39,611,770
207
20
BSD-3-Clause
2023-09-11T15:48:15
2015-07-24T04:30:43
Python
UTF-8
Python
false
false
243
py
def extractLogatseTranslations(item): """ 'Logatse Translations' """ vol, chp, frag, postfix = extractVolChapterFragmentPostfix(item['title']) if not (chp or vol or frag) or 'preview' in item['title'].lower(): return None return False
[ "something@fake-url.com" ]
something@fake-url.com
d949bab15336048347206f24e80edcb3b9586150
9743d5fd24822f79c156ad112229e25adb9ed6f6
/xai/brain/wordbase/nouns/_arboreta.py
8f30afffeead00e6448a171ca4b8fe383e7af1de
[ "MIT" ]
permissive
cash2one/xai
de7adad1758f50dd6786bf0111e71a903f039b64
e76f12c9f4dcf3ac1c7c08b0cc8844c0b0a104b6
refs/heads/master
2021-01-19T12:33:54.964379
2017-01-28T02:00:50
2017-01-28T02:00:50
null
0
0
null
null
null
null
UTF-8
Python
false
false
255
py
from xai.brain.wordbase.nouns._arboretum import _ARBORETUM #calss header class _ARBORETA(_ARBORETUM, ): def __init__(self,): _ARBORETUM.__init__(self) self.name = "ARBORETA" self.specie = 'nouns' self.basic = "arboretum" self.jsondata = {}
[ "xingwang1991@gmail.com" ]
xingwang1991@gmail.com
4d2a900624783e7d5da52ded2b406ddd862041b0
3cdb4faf34d8375d6aee08bcc523adadcb0c46e2
/web/env/lib/python3.6/site-packages/sqlparse/filters/aligned_indent.py
d3433c94e5a2c9090a3e7492d265483a8e72d2eb
[ "MIT", "GPL-3.0-only" ]
permissive
rizwansoaib/face-attendence
bc185d4de627ce5adab1cda7da466cb7a5fddcbe
59300441b52d32f3ecb5095085ef9d448aef63af
refs/heads/master
2020-04-25T23:47:47.303642
2019-09-12T14:26:17
2019-09-12T14:26:17
173,157,284
45
12
MIT
2020-02-11T23:47:55
2019-02-28T17:33:14
Python
UTF-8
Python
false
false
5,219
py
# -*- coding: utf-8 -*- # # Copyright (C) 2009-2018 the sqlparse authors and contributors # <see AUTHORS file> # # This module is part of python-sqlparse and is released under # the BSD License: https://opensource.org/licenses/BSD-3-Clause from sqlparse import sql, tokens as T from sqlparse.compat import text_type from sqlparse.utils import offset, indent class AlignedIndentFilter(object): join_words = (r'((LEFT\s+|RIGHT\s+|FULL\s+)?' r'(INNER\s+|OUTER\s+|STRAIGHT\s+)?|' r'(CROSS\s+|NATURAL\s+)?)?JOIN\b') by_words = r'(GROUP|ORDER)\s+BY\b' split_words = ('FROM', join_words, 'ON', by_words, 'WHERE', 'AND', 'OR', 'HAVING', 'LIMIT', 'UNION', 'VALUES', 'SET', 'BETWEEN', 'EXCEPT') def __init__(self, char=' ', n='\n'): self.n = n self.offset = 0 self.indent = 0 self.char = char self._max_kwd_len = len('select') def nl(self, offset=1): # offset = 1 represent a single space after SELECT offset = -len(offset) if not isinstance(offset, int) else offset # add two for the space and parenthesis indent = self.indent * (2 + self._max_kwd_len) return sql.Token(T.Whitespace, self.n + self.char * ( self._max_kwd_len + offset + indent + self.offset)) def _process_statement(self, tlist): if len(tlist.tokens) > 0 and tlist.tokens[0].is_whitespace \ and self.indent == 0: tlist.tokens.pop(0) # process the main query body self._process(sql.TokenList(tlist.tokens)) def _process_parenthesis(self, tlist): # if this isn't a subquery, don't re-indent _, token = tlist.token_next_by(m=(T.DML, 'SELECT')) if token is not None: with indent(self): tlist.insert_after(tlist[0], self.nl('SELECT')) # process the inside of the parenthesis self._process_default(tlist) # de-indent last parenthesis tlist.insert_before(tlist[-1], self.nl()) def _process_identifierlist(self, tlist): # columns being selected identifiers = list(tlist.get_identifiers()) identifiers.pop(0) [tlist.insert_before(token, self.nl()) for token in identifiers] self._process_default(tlist) def _process_case(self, tlist): offset_ = len('case ') + len('when ') cases = tlist.get_cases(skip_ws=True) # align the end as well end_token = tlist.token_next_by(m=(T.Keyword, 'END'))[1] cases.append((None, [end_token])) condition_width = [len(' '.join(map(text_type, cond))) if cond else 0 for cond, _ in cases] max_cond_width = max(condition_width) for i, (cond, value) in enumerate(cases): # cond is None when 'else or end' stmt = cond[0] if cond else value[0] if i > 0: tlist.insert_before(stmt, self.nl( offset_ - len(text_type(stmt)))) if cond: ws = sql.Token(T.Whitespace, self.char * ( max_cond_width - condition_width[i])) tlist.insert_after(cond[-1], ws) def _next_token(self, tlist, idx=-1): split_words = T.Keyword, self.split_words, True tidx, token = tlist.token_next_by(m=split_words, idx=idx) # treat "BETWEEN x and y" as a single statement if token and token.normalized == 'BETWEEN': tidx, token = self._next_token(tlist, tidx) if token and token.normalized == 'AND': tidx, token = self._next_token(tlist, tidx) return tidx, token def _split_kwds(self, tlist): tidx, token = self._next_token(tlist) while token: # joins, group/order by are special case. only consider the first # word as aligner if ( token.match(T.Keyword, self.join_words, regex=True) or token.match(T.Keyword, self.by_words, regex=True) ): token_indent = token.value.split()[0] else: token_indent = text_type(token) tlist.insert_before(token, self.nl(token_indent)) tidx += 1 tidx, token = self._next_token(tlist, tidx) def _process_default(self, tlist): self._split_kwds(tlist) # process any sub-sub statements for sgroup in tlist.get_sublists(): idx = tlist.token_index(sgroup) pidx, prev_ = tlist.token_prev(idx) # HACK: make "group/order by" work. Longer than max_len. offset_ = 3 if ( prev_ and prev_.match(T.Keyword, self.by_words, regex=True) ) else 0 with offset(self, offset_): self._process(sgroup) def _process(self, tlist): func_name = '_process_{cls}'.format(cls=type(tlist).__name__) func = getattr(self, func_name.lower(), self._process_default) func(tlist) def process(self, stmt): self._process(stmt) return stmt
[ "rizwansoaib@gmail.com" ]
rizwansoaib@gmail.com
099d3cdad0d9ed1606e82426da889f71b9bb767a
482623fe41cccf4d9fe0136f658aeae76bdd92c3
/Linux_python/Update.py
09bce8e7a77f73fa9bb65354d03c8a7d6f2e1f33
[ "MIT" ]
permissive
DiptoChakrabarty/Python
9b671a673e169609215c00947b3a31636bf8435c
075dfb780b24d31137cfe54f9dc396ebfc034cda
refs/heads/master
2020-04-21T18:05:49.000026
2020-04-05T13:42:36
2020-04-05T13:42:36
169,757,136
0
2
MIT
2019-10-01T16:33:44
2019-02-08T15:38:07
Python
UTF-8
Python
false
false
569
py
import subprocess as sp import pyttsx3 as py print("\t\t\t Gods Menu ") speaker=py.init() while True: print("Enter Choice") print(""" 1) Date 2)Calendar 3)Yell """) speaker.say("Enter Your Choice") speaker.runAndWait() ch=int(input()) if(ch==1): speaker.say("The Date is") speaker.runAndWait() x= sp.getoutput("date") print(x) elif(ch==2): speaker.say("The Calendar is") speaker.runAndWait() x=sp.getoutput("cal") print(x) elif(ch==3): print("Yipeeee") speaker.say("yipeeeeeeeeeeeeeeee") speaker.runAndWait() else: break
[ "diptochuck123@gmail.com" ]
diptochuck123@gmail.com
aea1f201ace40ff4bc1992cff6240b6bfa2b754c
63cddfe42baa72895ae6f2261df6582f19f65bc0
/web/dispatch/object/release.py
1410af9dc04b31fe0d3da700d83d3d727154e80b
[ "MIT" ]
permissive
marrow/web.dispatch.object
d6d7ac226405080386d37d604c6f85ee8157dde5
70d471df7d4342e079f47572e94f55b83e7890e7
refs/heads/master
2023-01-24T13:24:44.643732
2019-09-08T14:32:52
2019-09-08T14:32:52
32,564,722
1
1
null
null
null
null
UTF-8
Python
false
false
704
py
"""Release information about Object Dispatch.""" from collections import namedtuple version_info = namedtuple('version_info', ('major', 'minor', 'micro', 'releaselevel', 'serial'))(3, 0, 0, 'final', 0) version = ".".join([str(i) for i in version_info[:3]]) + ((version_info.releaselevel[0] + str(version_info.serial)) if version_info.releaselevel != 'final' else '') author = namedtuple('Author', ['name', 'email'])("Alice Bevan-McGregor", 'alice@gothcandy.com') description = "Object dispatch; a method to resolve path components to Python objects using directed attribute access." copyright = "2009-2019, Alice Bevan-McGregor and contributors" url = 'https://github.com/marrow/web.dispatch.object'
[ "alice@gothcandy.com" ]
alice@gothcandy.com
b89ee63a76bde5c022810e592b6b0dd62ef7b7c7
52b5773617a1b972a905de4d692540d26ff74926
/.history/mergeSort_20200731130122.py
f70e03125e745ffb9bf8d31041c665be3e738044
[]
no_license
MaryanneNjeri/pythonModules
56f54bf098ae58ea069bf33f11ae94fa8eedcabc
f4e56b1e4dda2349267af634a46f6b9df6686020
refs/heads/master
2022-12-16T02:59:19.896129
2020-09-11T12:05:22
2020-09-11T12:05:22
null
0
0
null
null
null
null
UTF-8
Python
false
false
148
py
# MERGE SORT # --> Recursive # ---> divide and conquer # ---> If the problem is too big , break it down # --> if its a single def merge(arr):
[ "mary.jereh@gmail.com" ]
mary.jereh@gmail.com
e741e0068da1e39e086fca252a9003a7ce67ce9c
05324b134108e0e0fde392e0ae0fc22bfa1fb75f
/df_cart/migrations/0001_initial.py
da0857848018ab3964a63745f672aa7960bfd71a
[]
no_license
2339379789/zhang_ttshop
2c8d546b9ed3710fd1f48d6075ea01955247d34f
44f9eb998182f4aa027d5d313b4957410b54a39d
refs/heads/master
2020-03-06T15:40:54.261769
2018-03-27T09:23:52
2018-03-27T09:23:52
126,960,140
2
1
null
null
null
null
UTF-8
Python
false
false
899
py
# -*- coding: utf-8 -*- # Generated by Django 1.10.6 on 2018-03-21 12:48 from __future__ import unicode_literals from django.db import migrations, models import django.db.models.deletion class Migration(migrations.Migration): initial = True dependencies = [ ('df_goods', '0002_auto_20180321_1141'), ('df_user', '0001_initial'), ] operations = [ migrations.CreateModel( name='CartInfo', fields=[ ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')), ('count', models.IntegerField(default=0)), ('goods', models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, to='df_goods.GoodsInfo')), ('user', models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, to='df_user.UserInfo')), ], ), ]
[ "2339379789@qq.com.com" ]
2339379789@qq.com.com
f813ff9f301518820dea08599e6cf4ed8f9e515e
56f5b2ea36a2258b8ca21e2a3af9a5c7a9df3c6e
/CMGTools/H2TauTau/prod/25aug_corrMC/up/mc/DYJetsToLL_M-50_TuneZ2Star_8TeV-madgraph-tarball/Summer12_DR53X-PU_S10_START53_V7A-v1/AODSIM/V5_B/PAT_CMG_V5_16_0_1377544840/HTT_24Jul_newTES_manzoni_Up_Jobs/Job_91/run_cfg.py
85ec7b9d549bb4d5428ab39aa50f69e857621350
[]
no_license
rmanzoni/HTT
18e6b583f04c0a6ca10142d9da3dd4c850cddabc
a03b227073b2d4d8a2abe95367c014694588bf98
refs/heads/master
2016-09-06T05:55:52.602604
2014-02-20T16:35:34
2014-02-20T16:35:34
null
0
0
null
null
null
null
UTF-8
Python
false
false
1,542
py
import FWCore.ParameterSet.Config as cms import os,sys sys.path.append('/afs/cern.ch/user/m/manzoni/summer13/CMGTools/CMSSW_5_3_9/src/CMGTools/H2TauTau/prod/25aug_corrMC/up/mc/DYJetsToLL_M-50_TuneZ2Star_8TeV-madgraph-tarball/Summer12_DR53X-PU_S10_START53_V7A-v1/AODSIM/V5_B/PAT_CMG_V5_16_0_1377544840/HTT_24Jul_newTES_manzoni_Up_Jobs') from base_cfg import * process.source = cms.Source("PoolSource", noEventSort = cms.untracked.bool(True), inputCommands = cms.untracked.vstring('keep *', 'drop cmgStructuredPFJets_cmgStructuredPFJetSel__PAT'), duplicateCheckMode = cms.untracked.string('noDuplicateCheck'), fileNames = cms.untracked.vstring('/store/cmst3/user/cmgtools/CMG/DYJetsToLL_M-50_TuneZ2Star_8TeV-madgraph-tarball/Summer12_DR53X-PU_S10_START53_V7A-v1/AODSIM/V5_B/PAT_CMG_V5_16_0/cmgTuple_1404.root', '/store/cmst3/user/cmgtools/CMG/DYJetsToLL_M-50_TuneZ2Star_8TeV-madgraph-tarball/Summer12_DR53X-PU_S10_START53_V7A-v1/AODSIM/V5_B/PAT_CMG_V5_16_0/cmgTuple_1405.root', '/store/cmst3/user/cmgtools/CMG/DYJetsToLL_M-50_TuneZ2Star_8TeV-madgraph-tarball/Summer12_DR53X-PU_S10_START53_V7A-v1/AODSIM/V5_B/PAT_CMG_V5_16_0/cmgTuple_1406.root', '/store/cmst3/user/cmgtools/CMG/DYJetsToLL_M-50_TuneZ2Star_8TeV-madgraph-tarball/Summer12_DR53X-PU_S10_START53_V7A-v1/AODSIM/V5_B/PAT_CMG_V5_16_0/cmgTuple_1407.root', '/store/cmst3/user/cmgtools/CMG/DYJetsToLL_M-50_TuneZ2Star_8TeV-madgraph-tarball/Summer12_DR53X-PU_S10_START53_V7A-v1/AODSIM/V5_B/PAT_CMG_V5_16_0/cmgTuple_1408.root') )
[ "riccardo.manzoni@cern.ch" ]
riccardo.manzoni@cern.ch
b4388223417883b80f3fefbe754dc0269073dbed
e4066b34668bbf7fccd2ff20deb0d53392350982
/project_scrapy/spiders/sony.py
81dc174a3a4237abed1440e66d88c27564b3529a
[]
no_license
sushma535/WebSites
24a688b86e1c6571110f20421533f0e7fdf6e1a8
16a3bfa44e6c7e22ae230f5b336a059817871a97
refs/heads/master
2023-08-18T09:09:16.052555
2021-10-11T00:41:50
2021-10-11T00:41:50
415,621,279
0
0
null
null
null
null
UTF-8
Python
false
false
2,535
py
import scrapy from scrapy.crawler import CrawlerProcess import os import csv from csv import reader import re total_data = {} class SimilarWeb(scrapy.Spider): name = 'SW' user_agent = 'Mozilla/5.0 (Windows NT 6.3; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/44.0.2403.157 Safari/537.36' start_urls = ['https://www.sony.com/en/', 'https://www.similarsites.com/site/sony.com/'] csv_columns = ['Category', 'Description', 'Name', 'Url'] csv_file = 'websites1_data.csv' count = 0 def parse(self, response): data, desc, cat = '', '', '' print('response url:', response.url) if response.url == self.start_urls[0]: data = response.css('title::text').get() if data: data = re.sub("\n\t\t", '', data) total_data['Name'] = data self.count += 1 elif response.url == self.start_urls[1]: cat = response.css( 'div[class="StatisticsCategoriesDistribution__CategoryTitle-fnuckk-6 jsMDeK"]::text').getall() desc = response.css('div[class="SiteHeader__Description-sc-1ybnx66-8 hhZNQm"]::text').get() if cat: cat = ": ".join(cat[:]) total_data['Category'] = cat total_data['Description'] = desc total_data['Url'] = self.start_urls[0] self.count += 1 if self.count == 2: print("total data", total_data) new_data = [total_data['Category'], total_data['Description'], total_data['Name'], total_data['Url']] print("new data", new_data) self.row_appending_to_csv_file(new_data) def row_appending_to_csv_file(self, data): if os.path.exists(self.csv_file): need_to_add_headers = False with open(self.csv_file, 'a+', newline='') as file: file.seek(0) csv_reader = reader(file) if len(list(csv_reader)) == 0: need_to_add_headers = True csv_writer = csv.writer(file) if need_to_add_headers: csv_writer.writerow(self.csv_columns) csv_writer.writerow(data) else: with open(self.csv_file, 'w', newline='') as file: csv_writer = csv.writer(file) csv_writer.writerow(self.csv_columns) # header csv_writer.writerow(data) process = CrawlerProcess() process.crawl(SimilarWeb) process.start()
[ "sushmakusumareddy@gmail.com" ]
sushmakusumareddy@gmail.com
ccfde10e9450e03a564e8089cb6cd056121cdde5
0958cceb81de1c7ee74b0c436b800a1dc54dd48a
/wincewebkit/WebKitTools/Scripts/webkitpy/common/system/user.py
dd132cdf84611aaa44da242424360ff1e148ae33
[]
no_license
datadiode/WinCEWebKit
3586fac69ba7ce9efbde42250266ddbc5c920c5e
d331d103dbc58406ed610410736b59899d688632
refs/heads/master
2023-03-15T23:47:30.374484
2014-08-14T14:41:13
2014-08-14T14:41:13
null
0
0
null
null
null
null
UTF-8
Python
false
false
5,772
py
# Copyright (c) 2009, Google Inc. All rights reserved. # # Redistribution and use in source and binary forms, with or without # modification, are permitted provided that the following conditions are # met: # # * Redistributions of source code must retain the above copyright # notice, this list of conditions and the following disclaimer. # * Redistributions in binary form must reproduce the above # copyright notice, this list of conditions and the following disclaimer # in the documentation and/or other materials provided with the # distribution. # * Neither the name of Google Inc. nor the names of its # contributors may be used to endorse or promote products derived from # this software without specific prior written permission. # # THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS # "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT # LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR # A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT # OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, # SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT # LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, # DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY # THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT # (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE # OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. import logging import os import re import shlex import subprocess import sys import webbrowser _log = logging.getLogger("webkitpy.common.system.user") try: import readline except ImportError: if sys.platform != "win32": # There is no readline module for win32, not much to do except cry. _log.warn("Unable to import readline.") # FIXME: We could give instructions for non-mac platforms. # Lack of readline results in a very bad user experiance. if sys.platform == "mac": _log.warn("If you're using MacPorts, try running:") _log.warn(" sudo port install py25-readline") class User(object): DEFAULT_NO = 'n' DEFAULT_YES = 'y' # FIXME: These are @classmethods because bugzilla.py doesn't have a Tool object (thus no User instance). @classmethod def prompt(cls, message, repeat=1, raw_input=raw_input): response = None while (repeat and not response): repeat -= 1 response = raw_input(message) return response @classmethod def prompt_with_list(cls, list_title, list_items, can_choose_multiple=False, raw_input=raw_input): print list_title i = 0 for item in list_items: i += 1 print "%2d. %s" % (i, item) # Loop until we get valid input while True: if can_choose_multiple: response = cls.prompt("Enter one or more numbers (comma-separated), or \"all\": ", raw_input=raw_input) if not response.strip() or response == "all": return list_items try: indices = [int(r) - 1 for r in re.split("\s*,\s*", response)] except ValueError, err: continue return [list_items[i] for i in indices] else: try: result = int(cls.prompt("Enter a number: ", raw_input=raw_input)) - 1 except ValueError, err: continue return list_items[result] def edit(self, files): editor = os.environ.get("EDITOR") or "vi" args = shlex.split(editor) # Note: Not thread safe: http://bugs.python.org/issue2320 subprocess.call(args + files) def _warn_if_application_is_xcode(self, edit_application): if "Xcode" in edit_application: print "Instead of using Xcode.app, consider using EDITOR=\"xed --wait\"." def edit_changelog(self, files): edit_application = os.environ.get("CHANGE_LOG_EDIT_APPLICATION") if edit_application and sys.platform == "darwin": # On Mac we support editing ChangeLogs using an application. args = shlex.split(edit_application) print "Using editor in the CHANGE_LOG_EDIT_APPLICATION environment variable." print "Please quit the editor application when done editing." self._warn_if_application_is_xcode(edit_application) subprocess.call(["open", "-W", "-n", "-a"] + args + files) return self.edit(files) def page(self, message): pager = os.environ.get("PAGER") or "less" try: # Note: Not thread safe: http://bugs.python.org/issue2320 child_process = subprocess.Popen([pager], stdin=subprocess.PIPE) child_process.communicate(input=message) except IOError, e: pass def confirm(self, message=None, default=DEFAULT_YES, raw_input=raw_input): if not message: message = "Continue?" choice = {'y': 'Y/n', 'n': 'y/N'}[default] response = raw_input("%s [%s]: " % (message, choice)) if not response: response = default return response.lower() == 'y' def can_open_url(self): try: webbrowser.get() return True except webbrowser.Error, e: return False def open_url(self, url): if not self.can_open_url(): _log.warn("Failed to open %s" % url) webbrowser.open(url)
[ "achellies@163.com" ]
achellies@163.com
f59579831d4ee07630c69532055596b6baf39a8d
935bf47c8f1ee0b2e248f9e233000602e46f9b6e
/tests/test_tapioca_jarbas.py
eebafe31165d25595ab88c49b5888e4f8532be27
[ "MIT" ]
permissive
giovanisleite/tapioca-jarbas
f6356babdaba24eefbf6d1b043e7b7eea43e387c
8365f795d0cab530106f970a852ea8052aead60c
refs/heads/master
2021-05-07T19:11:55.541940
2017-02-18T21:29:48
2017-02-18T21:29:48
null
0
0
null
null
null
null
UTF-8
Python
false
false
264
py
import pytest from tapioca_jarbas import Jarbas @pytest.fixture def wrapper(): return Jarbas() def test_resource_access(wrapper): resource = wrapper.reimbursement_list() assert resource.data == 'http://jarbas.datasciencebr.com/api/reimbursement/'
[ "daniloshiga@gmail.com" ]
daniloshiga@gmail.com
e0a63e7723643efc634c042a932d9ce6f655b570
440b0eaec8067321a2519d2b4309b42acf661ba6
/DALLE-pytorch-sm-210513/source_code/dalle_pytorch/vae.py
673f0925884ba25c78cd57ffdf0fae5cb0944bc8
[ "MIT" ]
permissive
daekeun-ml/smdalle
0f99b8a24fbf8409ddcd8abc6a7cd98f5fcd6129
416e381dc33575f7659b41cc206b94c72865b0fb
refs/heads/master
2023-05-03T05:57:56.346613
2021-05-19T06:21:42
2021-05-19T06:21:42
null
0
0
null
null
null
null
UTF-8
Python
false
false
6,135
py
import io import sys import os, sys import requests import PIL import warnings import os import hashlib import urllib import yaml from pathlib import Path from tqdm import tqdm from math import sqrt from omegaconf import OmegaConf from taming.models.vqgan import VQModel import torch from torch import nn import torch.nn.functional as F from einops import rearrange from dalle_pytorch import distributed_utils # constants CACHE_PATH = os.path.expanduser("~/.cache/dalle") OPENAI_VAE_ENCODER_PATH = 'https://cdn.openai.com/dall-e/encoder.pkl' OPENAI_VAE_DECODER_PATH = 'https://cdn.openai.com/dall-e/decoder.pkl' VQGAN_VAE_PATH = 'https://heibox.uni-heidelberg.de/f/140747ba53464f49b476/?dl=1' VQGAN_VAE_CONFIG_PATH = 'https://heibox.uni-heidelberg.de/f/6ecf2af6c658432c8298/?dl=1' # helpers methods def exists(val): return val is not None def default(val, d): return val if exists(val) else d def load_model(path): with open(path, 'rb') as f: return torch.load(f, map_location = torch.device('cpu')) def map_pixels(x, eps = 0.1): return (1 - 2 * eps) * x + eps def unmap_pixels(x, eps = 0.1): return torch.clamp((x - eps) / (1 - 2 * eps), 0, 1) def download(args, url, filename = None, root = CACHE_PATH): print(f"args.local_rank : {args.local_rank}") if ( not distributed_utils.is_distributed or args.local_rank == 0 # or distributed_utils.backend.is_local_root_worker() ): os.makedirs(root, exist_ok = True) filename = default(filename, os.path.basename(url)) download_target = os.path.join(root, filename) download_target_tmp = os.path.join(root, f'tmp.{filename}') if os.path.exists(download_target) and not os.path.isfile(download_target): raise RuntimeError(f"{download_target} exists and is not a regular file") if ( distributed_utils.is_distributed and not args.local_rank == 0 # and not distributed_utils.backend.is_local_root_worker() and not os.path.isfile(download_target) ): # If the file doesn't exist yet, wait until it's downloaded by the root worker. distributed_utils.backend.local_barrier() if args.local_rank == 0: if os.path.isfile(download_target): return download_target with urllib.request.urlopen(url) as source, open(download_target_tmp, "wb") as output: with tqdm(total=int(source.info().get("Content-Length")), ncols=80) as loop: while True: buffer = source.read(8192) if not buffer: break output.write(buffer) loop.update(len(buffer)) os.rename(download_target_tmp, download_target) if ( distributed_utils.is_distributed and args.local_rank == 0 # and distributed_utils.backend.is_local_root_worker() ): distributed_utils.backend.local_barrier() return download_target # pretrained Discrete VAE from OpenAI class OpenAIDiscreteVAE(nn.Module): def __init__(self, args): super().__init__() self.enc = load_model(download(args, OPENAI_VAE_ENCODER_PATH)) self.dec = load_model(download(args, OPENAI_VAE_DECODER_PATH)) self.num_layers = 3 self.image_size = 256 self.num_tokens = 8192 @torch.no_grad() def get_codebook_indices(self, img): img = map_pixels(img) z_logits = self.enc.blocks(img) z = torch.argmax(z_logits, dim = 1) return rearrange(z, 'b h w -> b (h w)') def decode(self, img_seq): b, n = img_seq.shape img_seq = rearrange(img_seq, 'b (h w) -> b h w', h = int(sqrt(n))) z = F.one_hot(img_seq, num_classes = self.num_tokens) z = rearrange(z, 'b h w c -> b c h w').float() x_stats = self.dec(z).float() x_rec = unmap_pixels(torch.sigmoid(x_stats[:, :3])) return x_rec def forward(self, img): raise NotImplemented # VQGAN from Taming Transformers paper # https://arxiv.org/abs/2012.09841 class VQGanVAE1024(nn.Module): def __init__(self, args): super().__init__() print(f" ************** VQGanVAE1024 **************** ") model_filename = 'vqgan.1024.model.ckpt' config_filename = 'vqgan.1024.config.yml' download(args, VQGAN_VAE_CONFIG_PATH, config_filename) download(args, VQGAN_VAE_PATH, model_filename) config = OmegaConf.load(str(Path(CACHE_PATH) / config_filename)) model = VQModel(**config.model.params) state = torch.load(str(Path(CACHE_PATH) / model_filename), map_location = 'cpu')['state_dict'] model.load_state_dict(state, strict = False) self.model = model self.num_layers = 4 self.image_size = 256 self.num_tokens = 1024 self._register_external_parameters() def _register_external_parameters(self): """Register external parameters for DeepSpeed partitioning.""" if ( not distributed_utils.is_distributed or not distributed_utils.using_backend( distributed_utils.DeepSpeedBackend) ): return deepspeed = distributed_utils.backend.backend_module deepspeed.zero.register_external_parameter( self, self.model.quantize.embedding.weight) @torch.no_grad() def get_codebook_indices(self, img): b = img.shape[0] img = (2 * img) - 1 _, _, [_, _, indices] = self.model.encode(img) return rearrange(indices, '(b n) () -> b n', b = b) def decode(self, img_seq): b, n = img_seq.shape one_hot_indices = F.one_hot(img_seq, num_classes = self.num_tokens).float() z = (one_hot_indices @ self.model.quantize.embedding.weight) z = rearrange(z, 'b (h w) c -> b c h w', h = int(sqrt(n))) img = self.model.decode(z) img = (img.clamp(-1., 1.) + 1) * 0.5 return img def forward(self, img): raise NotImplemented
[ "dolpal2@gmail.com" ]
dolpal2@gmail.com
7e7fd33ed0c2c7145d9620b60897981559f98688
1e1016423b4b97c022ed7eebe9051389144e0b4b
/ir/assignment1/src/question1/question1.py
79e591f5776065d9cbe61d6674d137fc2bc61269
[]
no_license
jhabarsingh/LABS
eca4c8bf92bf340504a6306670ca4984f27cb184
cdc06c4479e696b53cd5afb0bad78ae18bdc5fbe
refs/heads/main
2023-04-17T05:13:25.343094
2021-05-07T12:36:13
2021-05-07T12:36:13
353,227,617
0
0
null
null
null
null
UTF-8
Python
false
false
3,041
py
import io import re import os import sys import string import unicodedata import nltk from nltk.corpus import stopwords import unicodedata from nltk.tokenize import word_tokenize from nltk.stem import PorterStemmer from nltk.stem import WordNetLemmatizer from nltk.tokenize import word_tokenize lemmatizer = WordNetLemmatizer() nltk.download('wordnet') nltk.download('stopwords') DEBUG = False class DataCleaner(): def __init__(self, filename): self.filename = filename self.data = None def getText(self): return self.data def removeSpaces(self, data): return re.sub(' +', ' ', data) def removeNumPun(self, data): data = re.sub(r'\d+', '', data) translator = str.maketrans('', '', string.punctuation) return data.translate(translator) def replaceNewline(self, data): return data.replace('\\n', '\n') def replaceReturnCarrige(self, data): return data.replace('\\r', '') def assignData(self): newData = "" with open(self.filename, "rb") as rfile: newData = rfile.read() self.data = str(newData)[2:-1] self.data = self.removeSpaces(self.data) self.data = self.replaceNewline(self.data) self.data = self.replaceReturnCarrige(self.data) return newData def removeAccent(self): nfkd_form = unicodedata.normalize('NFKD', self.data) return u"".join([c for c in nfkd_form if not unicodedata.combining(c)]) def removestopWord(self): stop_words = set(stopwords.words('english')) words = self.data.split() newData = "" newData = [word for word in words if word not in stopwords.words('english')] return " ".join(newData) def stemming(self): ps = PorterStemmer() words = self.data.split() newData = "" for w in words: newData += ps.stem(w) + " " return newData def lemmatize(self): lm = WordNetLemmatizer() words = self.data.split() newData = "" for w in words: newData += lm.lemmatize(w) + " " return newData def removeSingleLetter(self): data = self.data.split() temp = "" for word in data: if len(word) > 1: temp += word + " " return temp def cleanData(self): self.data = self.removeAccent() self.data = self.removestopWord() self.data = self.removeNumPun(self.data) self.data = self.stemming() self.data = self.lemmatize() self.data = self.removestopWord() self.data = self.removeSingleLetter() return self.data def createFile(self, data): filename =self.filename.split('.')[0] + "_output." + self.filename.split('.')[1] with open(filename, "w+") as wfile: wfile.write(data) os.system(f'mv {filename} outputs') return True def countWords(self, input, output): return len(input.split()) - len(output.split()) if __name__ == "__main__": filename = sys.argv[1] datacleaner = DataCleaner(filename) datacleaner.assignData() input = datacleaner.getText() if DEBUG: print(datacleaner.getText()) changedData = datacleaner.cleanData() datacleaner.createFile(changedData) print(f"File words difference {datacleaner.countWords(input, changedData)}")
[ "jhabarsinghbhati23@gmail.com" ]
jhabarsinghbhati23@gmail.com
f8e2c31b7e307513f8daeb6c82a1ea2573bceca7
fc3f419dae08f7b5c706d65c23238b70d679beb8
/deepiu/textsum/prepare/default/conf.py
a1724e7a01434644e8a1395583d7ffeaf8c91cbf
[]
no_license
tangqiqi123/hasky
772b83e482f9755f8f95bf0c6c02087b5aaf01aa
97a840fba614bb68074a6d91f88582a391c81525
refs/heads/master
2021-06-22T05:11:04.679660
2017-08-14T00:52:17
2017-08-14T00:52:17
null
0
0
null
null
null
null
UTF-8
Python
false
false
130
py
IMAGE_FEATURE_LEN = 2048 MAX_EMB_WORDS = 200000 INPUT_TEXT_MAX_WORDS = 30 TEXT_MAX_WORDS = 20 NUM_RESERVED_IDS = 1 ENCODE_UNK = 0
[ "29109317@qq.com" ]
29109317@qq.com
214a278213ce6f374c77030134e559ebf3ef0cbe
7ed93ec573f4d17afe954ad1a269a00cd45c1d25
/app/__init__.py
ffb75a192f0ee04cf151ba9ce95692730d6299ac
[ "MIT" ]
permissive
nerevu/hdxscraper-hdro
06ddcf97a6820e43a024b4039578776315f6e7d4
ff027cd794d694932468f8c356c7b06fdd74f816
refs/heads/master
2021-06-01T01:11:44.894192
2016-02-08T09:22:08
2016-02-08T09:22:08
null
0
0
null
null
null
null
UTF-8
Python
false
false
805
py
# -*- coding: utf-8 -*- """ app ~~~ Provides the flask application """ from __future__ import ( absolute_import, division, print_function, with_statement, unicode_literals) import config from flask import Flask from flask.ext.sqlalchemy import SQLAlchemy __version__ = '0.9.0' __title__ = 'hdxscraper-hdro' __author__ = 'Reuben Cummings' __description__ = ( 'Collector for the UN Human Development Report Office (HDRO) API') __email__ = 'reubano@gmail.com' __license__ = 'MIT' __copyright__ = 'Copyright 2015 Reuben Cummings' db = SQLAlchemy() def create_app(mode=None): app = Flask(__name__) db.init_app(app) if mode: app.config.from_object(getattr(config, mode)) else: app.config.from_envvar('APP_SETTINGS', silent=True) return app
[ "reubano@gmail.com" ]
reubano@gmail.com
6ecf0e32c426ff5d3aa97d40c9616f9198a1d9a8
50402cc4388dfee3a9dbe9e121ef217759ebdba8
/demo/GazeboMonitor/GazeboMonitor.py
d88abf2b20229ba2f2f6bfe35928c19bdba3c2c1
[]
no_license
dqyi11/SVNBackup
bd46a69ec55e3a4f981a9bca4c8340944d8d5886
9ad38e38453ef8539011cf4d9a9c0a363e668759
refs/heads/master
2020-03-26T12:15:01.155873
2015-12-10T01:11:36
2015-12-10T01:11:36
144,883,382
2
1
null
null
null
null
UTF-8
Python
false
false
266
py
''' Created on Apr 22, 2014 @author: walter ''' from MapViewer import * from MapViewForm import * from PyQt4 import QtGui, QtCore import sys if __name__ == '__main__': app = QtGui.QApplication(sys.argv) form = MapViewForm(5) sys.exit(app.exec_())
[ "walter@e224401c-0ce2-47f2-81f6-2da1fe30fd39" ]
walter@e224401c-0ce2-47f2-81f6-2da1fe30fd39
8eebb159bd582927ff7999a9eb8293248153121e
2a2ce1246252ef6f59e84dfea3888c5a98503eb8
/examples/introduction.to.programming.with.turtle/windows_only/2-4.triangle2.py
0c22578c98e9af9023324fe1179378beef41406c
[ "BSD-3-Clause" ]
permissive
royqh1979/PyEasyGraphics
c7f57c1fb5a829287e9c462418998dcc0463a772
842121e461be3273f845866cf1aa40c312112af3
refs/heads/master
2021-06-11T10:34:03.001842
2021-04-04T10:47:52
2021-04-04T10:47:52
161,438,503
8
4
BSD-3-Clause
2021-04-04T10:47:53
2018-12-12T05:43:31
Python
UTF-8
Python
false
false
133
py
from easygraphics.turtle import * create_world() rt(30); for i in range(3): fd(100) rt(120) lt(30); pause() close_world()
[ "royqh1979@gmail.com" ]
royqh1979@gmail.com
5c67fd9f16289c5ae30f21e429cec1bea3ac5f35
dac8fbce2724abfb444bf3c2482758be088dd79e
/puzzle-3/test.py
db7e8f290cc7ac59d224bafb7be62062df30e328
[]
no_license
mattvenn/oshcamp-treasurehunt
f7312534872c1b98cd0b31c1e65c214bd2f0902c
d95b3fb7bc6a0d7925560e076bcd42a46c2218de
refs/heads/master
2021-01-10T07:23:45.410262
2015-09-29T14:00:06
2015-09-29T14:00:06
43,370,774
0
0
null
null
null
null
UTF-8
Python
false
false
2,197
py
import unittest import socket import time host = "10.10.0.29" port = 1337 password = 'MK_DCBY07I3YA8]PBVEU' # has good pass embedded bad_pass = 'B3d,P@U^=S<GPc*VNdN\MK_DCBY07I3YA8]PBVEUO``EM*)M2Ma,5CGAN<)' class TestClue3(unittest.TestCase): def test_bad_pass(self): soc = socket.socket(socket.AF_INET, socket.SOCK_STREAM) soc.connect((host, port)) soc.send("bad_pass") self.assertEqual(soc.recv(1000), "bad password") """ def test_pass_overflow(self): soc = socket.socket(socket.AF_INET, socket.SOCK_STREAM) soc.connect((host, port)) # ddoesn't actually overflow! thought 40k would do it. soc.send("a" * 100000) self.assertEqual(soc.recv(1000), "bad password") """ def test_no_pass_strobe_on(self): soc = socket.socket(socket.AF_INET, socket.SOCK_STREAM) soc.connect((host, port)) soc.send("strobe_on") self.assertEqual(soc.recv(1000), "bad password") def test_bad_pass_strobe_on(self): soc = socket.socket(socket.AF_INET, socket.SOCK_STREAM) soc.connect((host, port)) soc.send("aaaaa:strobe_on") self.assertEqual(soc.recv(1000), "bad password") def test_good_pass(self): soc = socket.socket(socket.AF_INET, socket.SOCK_STREAM) soc.connect((host, port)) soc.send(password) self.assertEqual(soc.recv(1000), "invalid request") def test_strobe_on(self): soc = socket.socket(socket.AF_INET, socket.SOCK_STREAM) soc.connect((host, port)) soc.send(password + " strobe_on") self.assertEqual(soc.recv(1000), "strobe on") time.sleep(3) # so we can see it def test_strobe_off(self): soc = socket.socket(socket.AF_INET, socket.SOCK_STREAM) soc.connect((host, port)) soc.send(password + " strobe_off") self.assertEqual(soc.recv(1000), "strobe off") def tearDown(self): soc = socket.socket(socket.AF_INET, socket.SOCK_STREAM) soc.connect((host, port)) soc.send(password + " strobe_off") self.assertEqual(soc.recv(1000), "strobe off") if __name__ == '__main__': unittest.main()
[ "matt@mattvenn.net" ]
matt@mattvenn.net
3b2b4904ef3a9d34a33b493e1db7d8c82900bd7b
372a0eb8d3be3d40b9dfb5cf45a7df2149d2dd0d
/charles/Week 10/lab11/lab11_extra.py
eda9fad861bf25b41aefaa377c70ad28baaa8b5f
[]
no_license
charlesfrye/cs61a-summer2015
5d14b679e5bea53cfa26c2a6a86720e8e77c322c
1f5c0fbf5dce5d1322285595ca964493d9adbdfe
refs/heads/master
2016-08-07T06:06:09.335913
2015-08-21T00:33:25
2015-08-21T00:33:25
38,509,126
0
0
null
null
null
null
UTF-8
Python
false
false
2,606
py
from lab11 import * ########### # Streams # ########### class Stream: class empty: def __repr__(self): return 'Stream.empty' empty = empty() def __init__(self, first, compute_rest=lambda: Stream.empty): assert callable(compute_rest), 'compute_rest must be callable.' self.first = first self._compute_rest = compute_rest @property def rest(self): """Return the rest of the stream, computing it if necessary.""" if self._compute_rest is not None: self._rest = self._compute_rest() self._compute_rest = None return self._rest def __repr__(self): return 'Stream({0}, <...>)'.format(repr(self.first)) def make_integer_stream(first=1): def compute_rest(): return make_integer_stream(first+1) return Stream(first, compute_rest) def add_streams(s1, s2): """Returns a stream that is the sum of s1 and s2. >>> stream1 = make_integer_stream() >>> stream2 = make_integer_stream(9) >>> added = add_streams(stream1, stream2) >>> added.first 10 >>> added.rest.first 12 >>> added.rest.rest.first 14 """ def compute_rest(): return add_streams(s1.rest,s2.rest) return Stream(s1.first+s2.first,compute_rest) def make_fib_stream(): """Return a stream containing the Fib sequence. >>> fib = make_fib_stream() >>> fib.first 0 >>> fib.rest.first 1 >>> fib.rest.rest.rest.rest.first 3 """ "*** YOUR CODE HERE ***" def compute_rest(): return add_streams(make_fib_stream(),make_fib_stream().rest) return Stream(0, lambda: Stream(1, compute_rest)) def filter_stream(filter_func, stream): def make_filtered_rest(): return filter_stream(filter_func, stream.rest) if stream == Stream.empty: return stream if filter_func(stream.first): return Stream(stream.first, make_filtered_rest) else: return filter_stream(filter_func, stream.rest) def interleave(stream1, stream2): """Return a stream with alternating values from stream1 and stream2. >>> ints = make_integer_stream(1) >>> fib = make_fib_stream() >>> alternating = interleave(ints, fib) >>> alternating.first 1 >>> alternating.rest.first 0 >>> alternating.rest.rest.first 2 >>> alternating.rest.rest.rest.first 1 """ def compute_rest(): return interleave(stream2,stream1.rest) if stream1 is Stream.empty: return stream1 else: return Stream(stream1.first,compute_rest)
[ "charlesfrye@berkeley.edu" ]
charlesfrye@berkeley.edu
c896ee7e54f79068157566d9203dc2d377ab2874
f07a42f652f46106dee4749277d41c302e2b7406
/Data Set/bug-fixing-5/98e7d4b49d1d6755da3d385d6496f22a6f85c1e8-<run>-bug.py
ac06e08164e75d877292881899411463204fb40d
[]
no_license
wsgan001/PyFPattern
e0fe06341cc5d51b3ad0fe29b84098d140ed54d1
cc347e32745f99c0cd95e79a18ddacc4574d7faa
refs/heads/main
2023-08-25T23:48:26.112133
2021-10-23T14:11:22
2021-10-23T14:11:22
null
0
0
null
null
null
null
UTF-8
Python
false
false
5,380
py
def run(self, tmp=None, task_vars=None): ' handler for fetch operations ' if (task_vars is None): task_vars = dict() result = super(ActionModule, self).run(tmp, task_vars) if self._play_context.check_mode: result['skipped'] = True result['msg'] = 'check mode not (yet) supported for this module' return result source = self._task.args.get('src', None) dest = self._task.args.get('dest', None) flat = boolean(self._task.args.get('flat')) fail_on_missing = boolean(self._task.args.get('fail_on_missing')) validate_checksum = boolean(self._task.args.get('validate_checksum', self._task.args.get('validate_md5'))) if (('validate_md5' in self._task.args) and ('validate_checksum' in self._task.args)): result['failed'] = True result['msg'] = 'validate_checksum and validate_md5 cannot both be specified' return result if ((source is None) or (dest is None)): result['failed'] = True result['msg'] = 'src and dest are required' return result source = self._connection._shell.join_path(source) source = self._remote_expand_user(source) remote_checksum = None if (not self._play_context.become): remote_checksum = self._remote_checksum(source, all_vars=task_vars, follow=True) remote_data = None if (remote_checksum in ('1', '2', None)): slurpres = self._execute_module(module_name='slurp', module_args=dict(src=source), task_vars=task_vars, tmp=tmp) if slurpres.get('failed'): if ((not fail_on_missing) and (slurpres.get('msg').startswith('file not found') or (remote_checksum == '1'))): result['msg'] = 'the remote file does not exist, not transferring, ignored' result['file'] = source result['changed'] = False else: result.update(slurpres) return result else: if (slurpres['encoding'] == 'base64'): remote_data = base64.b64decode(slurpres['content']) if (remote_data is not None): remote_checksum = checksum_s(remote_data) remote_source = slurpres.get('source') if (remote_source and (remote_source != source)): source = remote_source if (os.path.sep not in self._connection._shell.join_path('a', '')): source = self._connection._shell._unquote(source) source_local = source.replace('\\', '/') else: source_local = source dest = os.path.expanduser(dest) if flat: if dest.endswith(os.sep): base = os.path.basename(source_local) dest = os.path.join(dest, base) if (not dest.startswith('/')): dest = self._loader.path_dwim(dest) else: if ('inventory_hostname' in task_vars): target_name = task_vars['inventory_hostname'] else: target_name = self._play_context.remote_addr dest = ('%s/%s/%s' % (self._loader.path_dwim(dest), target_name, source_local)) dest = dest.replace('//', '/') if (remote_checksum in ('0', '1', '2', '3', '4')): result['changed'] = False result['file'] = source if (remote_checksum == '0'): result['msg'] = 'unable to calculate the checksum of the remote file' elif (remote_checksum == '1'): if fail_on_missing: result['failed'] = True del result['changed'] result['msg'] = 'the remote file does not exist' else: result['msg'] = 'the remote file does not exist, not transferring, ignored' elif (remote_checksum == '2'): result['msg'] = 'no read permission on remote file, not transferring, ignored' elif (remote_checksum == '3'): result['msg'] = 'remote file is a directory, fetch cannot work on directories' elif (remote_checksum == '4'): result['msg'] = "python isn't present on the system. Unable to compute checksum" return result local_checksum = checksum(dest) if (remote_checksum != local_checksum): makedirs_safe(os.path.dirname(dest)) if (remote_data is None): self._connection.fetch_file(source, dest) else: try: f = open(to_bytes(dest, errors='surrogate_or_strict'), 'wb') f.write(remote_data) f.close() except (IOError, OSError) as e: raise AnsibleError(('Failed to fetch the file: %s' % e)) new_checksum = secure_hash(dest) try: new_md5 = md5(dest) except ValueError: new_md5 = None if (validate_checksum and (new_checksum != remote_checksum)): result.update(dict(failed=True, md5sum=new_md5, msg='checksum mismatch', file=source, dest=dest, remote_md5sum=None, checksum=new_checksum, remote_checksum=remote_checksum)) else: result.update(dict(changed=True, md5sum=new_md5, dest=dest, remote_md5sum=None, checksum=new_checksum, remote_checksum=remote_checksum)) else: try: local_md5 = md5(dest) except ValueError: local_md5 = None result.update(dict(changed=False, md5sum=local_md5, file=source, dest=dest, checksum=local_checksum)) return result
[ "dg1732004@smail.nju.edu.cn" ]
dg1732004@smail.nju.edu.cn
a4e1450cfb99d5495a226f1f9091b65989006053
090538afc77e19066b312465ce8ca1423d5a5a0f
/scripts/validate_chicago_stkde.py
2a6ba38f6dcc398e294cb9231c9956514641a565
[]
no_license
gaberosser/crime-fighter
f632676bc19c67c81d0a2bc587845ebfb9a116e8
4b0249696126910cf8781fa9c1ec884bb7b4a8b3
refs/heads/master
2020-05-29T20:44:41.710045
2016-08-26T07:13:53
2016-08-26T07:13:53
17,255,773
0
0
null
null
null
null
UTF-8
Python
false
false
4,085
py
__author__ = 'gabriel' import datetime import time import os import dill as pickle import logging import sys from pytz import utc from validation import validation, hotspot from kde import models as k_models from . import OUT_DIR, IN_DIR OUT_SUBDIR = 'validate_chicago_stkde' # global parameters num_sample_points = 30 grid_size = 150 # metres num_validation = 100 # number of predict - assess cycles start_date = datetime.datetime(2011, 3, 1) # first date for which data are required start_day_number = 366 # number of days (after start date) on which first prediction is made model_kwargs = { 'number_nn': 15, 'parallel': True, 'ncpu': 2, } ## DEBUGGING: #niter = 2 # number of SEPP iterations before convergence is assumed #num_validation = 2 # number of predict - assess cycles #num_sample_points = 2 # end_date is the maximum required date end_date = start_date + datetime.timedelta(days=start_day_number + num_validation) def run_me(data, data_index, domain, out_dir, run_name): log_file = os.path.join(out_dir, '%s.log' % run_name) if not os.path.isdir(out_dir): try: os.makedirs(out_dir) except OSError: # wait a moment, just in case another process has just done the folder creation time.sleep(1) if not os.path.isdir(out_dir): raise # set loggers logger = logging.getLogger(run_name) logger.setLevel(logging.DEBUG) fh = logging.FileHandler(log_file) formatter = logging.Formatter('%(asctime)s - %(name)s - %(levelname)s - %(message)s') fh.setFormatter(formatter) logger.addHandler(fh) this_logger = logging.getLogger('validation.validation') this_logger.setLevel(logging.DEBUG) this_logger.handlers = [] # clear existing handlers this_logger.addHandler(fh) # replace with the same file output logger.info("Logger set. Script started.") # check that num_validation iterations is feasible if start_day_number + num_validation - 1 > data[-1, 0]: this_num_validation = int(data[-1, 0]) - start_day_number + 1 logger.info("Can only do %d validation runs" % this_num_validation) else: this_num_validation = num_validation logger.info("Instantiating validation object") hs = hotspot.STGaussianNn(**model_kwargs) vb = validation.ValidationIntegration(data, model=hs, data_index=data_index, spatial_domain=domain, cutoff_t=start_day_number) logger.info("Setting validation grid") vb.set_sample_units(grid_size, num_sample_points) file_stem = os.path.join(out_dir, run_name) try: logger.info("Starting validation run.") res = vb.run(time_step=1, n_iter=this_num_validation, verbose=True) except Exception as exc: logger.error(repr(exc)) res = None finally: logger.info("Saving results (or None).") with open(file_stem + '-validation.pickle', 'w') as f: pickle.dump(res, f) def main(region, crime_type): poly_file = os.path.join(IN_DIR, 'boundaries.pickle') with open(poly_file, 'r') as f: boundaries = pickle.load(f) domain = boundaries[region] data_infile = os.path.join(IN_DIR, 'chicago', region, '%s.pickle' % crime_type) with open(data_infile, 'r') as f: data, t0, cid = pickle.load(f) # cut data to selected date range sd = (start_date.replace(tzinfo=utc) - t0).days ed = (end_date.replace(tzinfo=utc) - t0).days data = data[(data[:, 0] >= sd) & (data[:, 0] < ed + 1)] data[:, 0] -= min(data[:, 0]) out_dir = os.path.join(OUT_DIR, OUT_SUBDIR, region, crime_type) run_name = '%s-%s' % (region, crime_type) run_me(data, cid, domain, out_dir, run_name) if __name__ == '__main__': assert len(sys.argv) == 3, "Two input arguments required" sys.exit(main(sys.argv[1], sys.argv[2]))
[ "gabriel.rosser@gmail.com" ]
gabriel.rosser@gmail.com
ce2ba36a18a2a4acb2aca126e488184e19fa6a7d
9743d5fd24822f79c156ad112229e25adb9ed6f6
/xai/brain/wordbase/nouns/_scenario.py
158e94ece2140a0ae55a41fbc16537dc39bde965
[ "MIT" ]
permissive
cash2one/xai
de7adad1758f50dd6786bf0111e71a903f039b64
e76f12c9f4dcf3ac1c7c08b0cc8844c0b0a104b6
refs/heads/master
2021-01-19T12:33:54.964379
2017-01-28T02:00:50
2017-01-28T02:00:50
null
0
0
null
null
null
null
UTF-8
Python
false
false
409
py
#calss header class _SCENARIO(): def __init__(self,): self.name = "SCENARIO" self.definitions = [u'a description of possible actions or events in the future: ', u'a written plan of the characters and events in a play or film'] self.parents = [] self.childen = [] self.properties = [] self.jsondata = {} self.specie = 'nouns' def run(self, obj1 = [], obj2 = []): return self.jsondata
[ "xingwang1991@gmail.com" ]
xingwang1991@gmail.com
cd72d7606f7019baa03db391740675aa139dde2e
ac42f1d918bdbd229968cea0954ed75250acd55c
/admin/monitor/openstack_dashboard/enabled/_3040_identity_groups_panel.py
3299a47aacf92880e05b774f367c4f0212074d24
[ "Apache-2.0" ]
permissive
naanal/product
016e18fd2f35608a0d8b8e5d2f75b653bac7111a
bbaa4cd60d4f2cdda6ce4ba3d36312c1757deac7
refs/heads/master
2020-04-03T22:40:48.712243
2016-11-15T11:22:00
2016-11-15T11:22:00
57,004,514
1
1
null
null
null
null
UTF-8
Python
false
false
402
py
# The slug of the panel to be added to HORIZON_CONFIG. Required. PANEL = 'groups' # The slug of the dashboard the PANEL associated with. Required. PANEL_DASHBOARD = 'identity' # The slug of the panel group the PANEL is associated with. PANEL_GROUP = 'default' # Python panel class of the PANEL to be added. ADD_PANEL = 'openstack_dashboard.dashboards.identity.groups.panel.Groups' REMOVE_PANEL = True
[ "rajagopalx@gmail.com" ]
rajagopalx@gmail.com
0e84475758c04231804f9e3b3af5ad23d2892a62
6afc41d5a658c5023a31fbc384a36ac9c0166e8b
/backend/test_3719/wsgi.py
a602ac78a119422d7ba99b6885f180aa4ce03f12
[]
no_license
crowdbotics-apps/test-3719
ed5545b57780f0d50fca61192ea73aa9418a92da
144082c4eaa720315e5a07df3f9f865ed5fb4511
refs/heads/master
2022-12-21T08:07:20.957261
2019-05-23T04:02:43
2019-05-23T04:02:43
188,159,177
0
0
null
2022-12-09T03:36:44
2019-05-23T04:02:28
Python
UTF-8
Python
false
false
396
py
""" WSGI config for test_3719 project. It exposes the WSGI callable as a module-level variable named ``application``. For more information on this file, see https://docs.djangoproject.com/en/1.11/howto/deployment/wsgi/ """ import os from django.core.wsgi import get_wsgi_application os.environ.setdefault("DJANGO_SETTINGS_MODULE", "test_3719.settings") application = get_wsgi_application()
[ "team@crowdbotics.com" ]
team@crowdbotics.com
5b20a0765681fd54ab67717db8404968a2462b98
b72dbc51279d3e59cb6410367b671f8a956314c1
/프로그래머스/그외/17680_캐시.py
87b058fb7469357e9c360c933a261e08deb41fec
[]
no_license
ddobokki/coding-test-practice
7b16d20403bb1714d97adfd1f47aa7d3ccd7ea4b
c88d981a1d43b986169f7884ff3ef1498e768fc8
refs/heads/main
2023-07-08T15:09:32.269059
2021-08-08T12:19:44
2021-08-08T12:19:44
344,116,013
0
0
null
null
null
null
UTF-8
Python
false
false
1,064
py
#https://programmers.co.kr/learn/courses/30/lessons/17680 def solution(cacheSize, cities): answer = 0 cache = [] #캐시 for city in cities: # 도시 리스트를 순회 city = city.lower() # 소문자 변환 if city in cache: # 처리하려는 도시가 이미 캐시에 있으면 answer += 1 # cache hit, 1초 cache[cache.index(city)],cache[-1] = cache[-1], cache[cache.index(city)] # 캐시내의 사용된 데이터를 가장 마지막 인덱스로 옮긴다. else: answer += 5 # 캐시내에 없으면 5초 추가 if cacheSize > 0: # 캐시 사이즈가 0보다 크고 if len(cache) == cacheSize: # 캐시가 꽉차있다면 cache.pop(0) # 가장 사용 안된 데이터를 pop 해준다. cache.append(city) # 새로 들어온 데이터를 캐시에 넣어준다. else: # 사이즈에 여유가 있으면 cache.append(city) # 캐시에 넣어준다 return answer
[ "44228269+ddobokki@users.noreply.github.com" ]
44228269+ddobokki@users.noreply.github.com
98f7167189da23eafba697046764bd15df60eeae
45794e797df8695f3c4844363ea937ea52300ae0
/barbican/openstack/common/notifier/api.py
495f5abdd1a984af4f9fef55a832e746af7e5c5f
[ "Apache-2.0" ]
permissive
ss7pro/barbican
46ed5086d40dc2b14e36aa791d0d71c5b2b91f02
887fddedc5ef0e8383cd06487d1ad1b518de7fdc
refs/heads/master
2022-04-17T06:31:45.801422
2013-11-21T16:48:47
2013-11-21T16:48:47
null
0
0
null
null
null
null
UTF-8
Python
false
false
5,527
py
# Copyright 2011 OpenStack Foundation. # All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); you may # not use this file except in compliance with the License. You may obtain # a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, WITHOUT # WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the # License for the specific language governing permissions and limitations # under the License. import socket import uuid from oslo.config import cfg from barbican.openstack.common import context from barbican.openstack.common.gettextutils import _ # noqa from barbican.openstack.common import importutils from barbican.openstack.common import jsonutils from barbican.openstack.common import log as logging from barbican.openstack.common import timeutils LOG = logging.getLogger(__name__) notifier_opts = [ cfg.MultiStrOpt('notification_driver', default=[], help='Driver or drivers to handle sending notifications'), cfg.StrOpt('default_notification_level', default='INFO', help='Default notification level for outgoing notifications'), cfg.StrOpt('default_publisher_id', default=None, help='Default publisher_id for outgoing notifications'), ] CONF = cfg.CONF CONF.register_opts(notifier_opts) WARN = 'WARN' INFO = 'INFO' ERROR = 'ERROR' CRITICAL = 'CRITICAL' DEBUG = 'DEBUG' log_levels = (DEBUG, WARN, INFO, ERROR, CRITICAL) class BadPriorityException(Exception): pass def notify_decorator(name, fn): """Decorator for notify which is used from utils.monkey_patch(). :param name: name of the function :param function: - object of the function :returns: function -- decorated function """ def wrapped_func(*args, **kwarg): body = {} body['args'] = [] body['kwarg'] = {} for arg in args: body['args'].append(arg) for key in kwarg: body['kwarg'][key] = kwarg[key] ctxt = context.get_context_from_function_and_args(fn, args, kwarg) notify(ctxt, CONF.default_publisher_id or socket.gethostname(), name, CONF.default_notification_level, body) return fn(*args, **kwarg) return wrapped_func def publisher_id(service, host=None): if not host: try: host = CONF.host except AttributeError: host = CONF.default_publisher_id or socket.gethostname() return "%s.%s" % (service, host) def notify(context, publisher_id, event_type, priority, payload): """Sends a notification using the specified driver :param publisher_id: the source worker_type.host of the message :param event_type: the literal type of event (ex. Instance Creation) :param priority: patterned after the enumeration of Python logging levels in the set (DEBUG, WARN, INFO, ERROR, CRITICAL) :param payload: A python dictionary of attributes Outgoing message format includes the above parameters, and appends the following: message_id a UUID representing the id for this notification timestamp the GMT timestamp the notification was sent at The composite message will be constructed as a dictionary of the above attributes, which will then be sent via the transport mechanism defined by the driver. Message example:: {'message_id': str(uuid.uuid4()), 'publisher_id': 'compute.host1', 'timestamp': timeutils.utcnow(), 'priority': 'WARN', 'event_type': 'compute.create_instance', 'payload': {'instance_id': 12, ... }} """ if priority not in log_levels: raise BadPriorityException( _('%s not in valid priorities') % priority) # Ensure everything is JSON serializable. payload = jsonutils.to_primitive(payload, convert_instances=True) msg = dict(message_id=str(uuid.uuid4()), publisher_id=publisher_id, event_type=event_type, priority=priority, payload=payload, timestamp=str(timeutils.utcnow())) for driver in _get_drivers(): try: driver.notify(context, msg) except Exception as e: LOG.exception(_("Problem '%(e)s' attempting to " "send to notification system. " "Payload=%(payload)s") % dict(e=e, payload=payload)) _drivers = None def _get_drivers(): """Instantiate, cache, and return drivers based on the CONF.""" global _drivers if _drivers is None: _drivers = {} for notification_driver in CONF.notification_driver: try: driver = importutils.import_module(notification_driver) _drivers[notification_driver] = driver except ImportError: LOG.exception(_("Failed to load notifier %s. " "These notifications will not be sent.") % notification_driver) return _drivers.values() def _reset_drivers(): """Used by unit tests to reset the drivers.""" global _drivers _drivers = None
[ "john.wood@rackspace.com" ]
john.wood@rackspace.com
0beb21467f8c50ffddcf0194336a4947b2e0ec79
bc3093b61564c9ae9a92c3b63a998b4b72dec934
/stacks_and_queues/implement_stack_using_queue.py
667acb09cbd3d621b6def14ddd5a1a2fd25d0445
[]
no_license
rayankikavitha/InterviewPrep
012f15e86fc5bb8b98ad82d83af1d0745e6fcd2d
cfc64f121413dc2466d968ebf3f18078f4969f18
refs/heads/master
2021-04-28T02:24:54.782253
2019-12-05T03:51:14
2019-12-05T03:51:14
122,113,708
1
3
null
null
null
null
UTF-8
Python
false
false
592
py
from queue import Queue class Stack(Queue): def __init__(self): self.eq = Queue() self.dq = Queue() def push(self,item): self.eq.enqueue(item) def pop(self): if self.dq.size() == 0: while self.eq.size() > 0: self.dq.enqueue(self.eq.dequeue()) return self.dq.dequeue() def size(self): return self.dq.size() + self.eq.size() s = Stack() s.push(1) s.push(2) s.push(3) s.push(4) s.push(5) print "queue size=" print s.size() print s.eq.items, s.dq.items print s.pop() print s.eq.items, s.dq.items
[ "rayanki.kavitha@gmail.com" ]
rayanki.kavitha@gmail.com
1639dc7e80712447aaa10c5fc680b3f84a5cc8f2
2dd26e031162e75f37ecb1f7dd7f675eeb634c63
/tests/collections/tts/losses/test_audio_codec_loss.py
0fe7991e92cb557bcfd95516aaef6f1b9a9d76a1
[ "Apache-2.0" ]
permissive
NVIDIA/NeMo
1b001fa2ae5d14defbfd02f3fe750c5a09e89dd1
c20a16ea8aa2a9d8e31a98eb22178ddb9d5935e7
refs/heads/main
2023-08-21T15:28:04.447838
2023-08-21T00:49:36
2023-08-21T00:49:36
200,722,670
7,957
1,986
Apache-2.0
2023-09-14T18:49:54
2019-08-05T20:16:42
Python
UTF-8
Python
false
false
1,715
py
# Copyright (c) 2023, NVIDIA CORPORATION & AFFILIATES. All rights reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. import pytest import torch from nemo.collections.tts.losses.audio_codec_loss import MaskedMAELoss, MaskedMSELoss class TestAudioCodecLoss: @pytest.mark.run_only_on('CPU') @pytest.mark.unit def test_masked_loss_l1(self): loss_fn = MaskedMAELoss() target = torch.tensor([[[1.0], [2.0], [0.0]], [[3.0], [0.0], [0.0]]]).transpose(1, 2) predicted = torch.tensor([[[0.5], [1.0], [0.0]], [[4.5], [0.0], [0.0]]]).transpose(1, 2) target_len = torch.tensor([2, 1]) loss = loss_fn(predicted=predicted, target=target, target_len=target_len) assert loss == 1.125 @pytest.mark.run_only_on('CPU') @pytest.mark.unit def test_masked_loss_l2(self): loss_fn = MaskedMSELoss() target = torch.tensor([[[1.0], [2.0], [4.0]], [[3.0], [0.0], [0.0]]]).transpose(1, 2) predicted = torch.tensor([[[0.5], [1.0], [4.0]], [[4.5], [0.0], [0.0]]]).transpose(1, 2) target_len = torch.tensor([3, 1]) loss = loss_fn(predicted=predicted, target=target, target_len=target_len) assert loss == (4 / 3)
[ "noreply@github.com" ]
NVIDIA.noreply@github.com
572fff90f7b8b8d74601eb806280e978c5175a85
ab31caa57057a03872c858b65fecbcefb7f519db
/ttfquery/glyph.py
7fd8543d74749ab8de8362deb4e9ee1291400360
[]
no_license
mcfletch/ttfquery
737039e28ce453c4626c82da023361c25444ba56
6988e599a9461859843cb18d1585730a969a0604
refs/heads/master
2020-09-13T08:33:00.864669
2018-08-10T05:44:56
2018-08-10T05:44:56
222,712,423
1
0
null
null
null
null
UTF-8
Python
false
false
7,783
py
"""Representation of a single glyph including contour extraction""" from ttfquery import glyphquery import numpy class Glyph( object): """Object encapsulating metadata regarding a particular glyph""" def __init__(self, glyphName ): """Initialize the glyph object glyphName -- font's glyphName for this glyph, see glyphquery.glyphName() for extracting the appropriate name from character and encoding. """ self.glyphName = glyphName def compile( self, font, steps = 3 ): """Compile the glyph to a set of poly-line outlines""" self.contours = self.calculateContours( font ) self.outlines = [ decomposeOutline(contour,steps) for contour in self.contours ] self.width = glyphquery.width( font, self.glyphName ) self.height = glyphquery.lineHeight( font ) def calculateContours( self, font ): """Given a character, determine contours to draw returns a list of contours, with each contour being a list of ((x,y),flag) elements. There may be only a single contour. """ glyf = font['glyf'] charglyf = glyf[self.glyphName] return self._calculateContours( charglyf, glyf, font ) def _calculateContours( self, charglyf, glyf, font ): """Create expanded contour data-set from TTF charglyph entry This is called recursively for composite glyphs, so I suppose a badly-formed TTF file could cause an infinite loop. charglyph -- glyf table's entry for the target character glyf -- the glyf table (used for recursive calls) """ charglyf.expand( font ) # XXX is this extraneous? contours = [] if charglyf.numberOfContours == 0: # does not display at all, for instance, space pass elif charglyf.isComposite(): # composed out of other items... for component in charglyf.components: subContours = self._calculateContours( glyf[component.glyphName], glyf, font ) dx,dy = component.getComponentInfo()[1][-2:] # XXX we're ignoring the scaling/shearing/etceteras transformation # matrix which is given by component.getComponentInfo()[1][:4] subContours = [ [((x+dx,y+dy),f) for ((x,y),f) in subContour] for subContour in subContours ] contours.extend( subContours ) else: flags = charglyf.flags coordinates = charglyf.coordinates # We need to convert from the "end point" representation # to a distinct contour representation, requires slicing # each contour out of the list and then closing it last = 0 for e in charglyf.endPtsOfContours: set = zip( list(coordinates[last:e+1])+list(coordinates[last:last+1]), list(flags[last:e+1])+list(flags[last:last+1]) ) contours.append( list(set) ) last = e+1 if coordinates[last:]: contours.append( list(zip( list(coordinates[last:])+list(coordinates[last:last+1]), list(flags[last:])+list(flags[last:]) ) )) return contours def decomposeOutline( contour, steps=3 ): """Decompose a single TrueType contour to a line-loop In essence, this is the "interpretation" of the font as geometric primitives. I only support line and quadratic (conic) segments, which should support most TrueType fonts as far as I know. The process consists of first scanning for any multi- off-curve control-point runs. For each pair of such control points, we insert a new on-curve control point. Once we have the "expanded" control point array we scan through looking for each segment which includes an off-curve control point. These should only be bracketed by on-curve control points. For each found segment, we call our integrateQuadratic method to produce a set of points interpolating between the end points as affected by the middle control point. All other control points merely generate a single line-segment between the endpoints. """ # contours must be closed, but they can start with # (and even end with) items not on the contour... # so if we do, we need to create a new point to serve # as the midway... if len(contour)<3: return () set = contour[:] def on( record ): """Is this record on the contour? record = ((Ax,Ay),Af) """ return record[-1] == 1 def merge( first, second): """Merge two off-point records into an on-point record""" ((Ax,Ay),Af) = first ((Bx,By),Bf) = second return (((Ax+Bx)/2.0),((Ay+By))/2.0),1 # create an expanded set so that all adjacent # off-curve items have an on-curve item added # in between them last = contour[-1] expanded = [] for item in set: if (not on(item)) and (not on(last)): expanded.append( merge(last, item)) expanded.append( item ) last = item result = [] last = expanded[-1] while expanded: assert on(expanded[0]), "Expanded outline doesn't have proper format! Should always have either [on, off, on] or [on, on] as the first items in the outline" if len(expanded)>1: if on(expanded[1]): # line segment from 0 to 1 result.append( expanded[0][0] ) #result.append( expanded[1][0] ) del expanded[:1] else: if len(expanded) == 2: #KH assert on(expanded[0]), """Expanded outline finishes off-curve""" #KH result.append( expanded[1][0] ) #KH del expanded[:1] break assert on(expanded[2]), "Expanded outline doesn't have proper format!" points = integrateQuadratic( expanded[:3], steps = steps ) result.extend( points ) del expanded[:2] else: assert on(expanded[0]), """Expanded outline finishes off-curve""" result.append( expanded[0][0] ) del expanded[:1] result.append( result[-1] ) return result def integrateQuadratic( points, steps=3 ): """Get points on curve for quadratic w/ end points A and C Basis Equations are taken from here: http://www.truetype.demon.co.uk/ttoutln.htm This is a very crude approach to the integration, everything is coded directly in Python, with no attempts to speed up the process. XXX Should eventually provide adaptive steps so that the angle between the elements can determine how many steps are used. """ step = 1.0/steps ((Ax,Ay),_),((Bx,By),_),((Cx,Cy),_) = points result = [(Ax,Ay)] ### XXX This is dangerous, in certain cases floating point error ## can wind up creating a new point at 1.0-(some tiny number) if step ## is sliaghtly less than precisely 1.0/steps for t in numpy.arange( step, 1.0, step ): invT = 1.0-t px = (invT*invT * Ax) + (2*t*invT*Bx) + (t*t*Cx) py = (invT*invT * Ay) + (2*t*invT*By) + (t*t*Cy) result.append( (px,py) ) # the end-point will be added by the next segment... #result.append( (Cx,Cy) ) return result
[ "mcfletch@vrplumber.com" ]
mcfletch@vrplumber.com
0782284dc476f8da4e4d59915521a24c83c513d8
6af44c684d1164e849c47a381facce11af6b45a1
/jd/api/rest/KplOpenGetnewstockbyidQueryRequest.py
968c30821ac951f6ac6d871e528a60d61d02ee4a
[ "MIT" ]
permissive
dsjbc/linjuanbang
cdfa84f7c7e2a89dc840c476bea92c4ff4d4de84
8cdc4e81df73ccd737ac547da7f2c7dca545862a
refs/heads/master
2022-03-16T20:43:42.005432
2019-11-25T10:15:11
2019-11-25T10:15:11
null
0
0
null
null
null
null
UTF-8
Python
false
false
300
py
from jd.api.base import RestApi class KplOpenGetnewstockbyidQueryRequest(RestApi): def __init__(self,domain='gw.api.360buy.com',port=80): RestApi.__init__(self,domain, port) self.skuNums = None self.area = None def getapiname(self): return 'jd.kpl.open.getnewstockbyid.query'
[ "tarena_feng@126.com" ]
tarena_feng@126.com
c600dfcd1ccb951bb47544233ce09acd8c8b0f9d
0109264211df54f53f0c52cf7a61af72b4d31717
/watchFaceParser/models/elements/activity/pulseLinearElement.py
e7744d2da14f0fc2de001025707dc4496e266bfb
[ "LicenseRef-scancode-warranty-disclaimer" ]
no_license
abhishekhbhootwala/py_amazfit_tools
fb4fc10457a6696b7a2815e7ae01f70d01ed8d35
e9c144eb5a8a9bf2354ec182a02004dc9f1e6c80
refs/heads/master
2023-02-12T22:46:33.629564
2021-01-07T01:54:46
2021-01-07T01:54:46
null
0
0
null
null
null
null
UTF-8
Python
false
false
2,461
py
import logging from watchFaceParser.models.elements.common.iconSetElement import IconSetElement class PulseLinearElement(IconSetElement): # private static readonly Dictionary<DayOfWeek, int> DaysOfWeek = new Dictionary<DayOfWeek, int> # { # {DayOfWeek.Monday, 0}, # {DayOfWeek.Tuesday, 1}, # {DayOfWeek.Wednesday, 2}, # {DayOfWeek.Thursday, 3}, # {DayOfWeek.Friday, 4}, # {DayOfWeek.Saturday, 5}, # {DayOfWeek.Sunday, 6} # }; def __init__(self, parameter, parent, name = None): self._ar = [] #self._slices = 0 super(PulseLinearElement, self).__init__(parameter = parameter, parent = parent, name = name) def getCoordinatesArray(self): return self._ar def draw3(self, drawer, resources, state): assert(type(resources) == list) # pulse image does not overlap fakeZone = int(state.getPulse() * len(self._ar) / 200) x = self.getCoordinatesArray()[fakeZone]._x y = self.getCoordinatesArray()[fakeZone]._y temp = resources[self._imageIndex + fakeZone].getBitmap() drawer.paste(temp, (x,y), temp) def createChildForParameter(self, parameter): if parameter.getId() == 1: self._imageIndex = parameter.getValue() #print ("ARRAY",self._imageIndex) from watchFaceParser.models.elements.basic.valueElement import ValueElement return ValueElement(parameter, self, '?ImageIndex?') #print ( parameter.getValue(),parameter.getChildren()) elif parameter.getId() == 2: #print ( [ c.getValue() for c in parameter.getChildren()]) from watchFaceParser.models.elements.common.coordinatesElement import CoordinatesElement #print ( parameter.getValue(),parameter.getChildren()) #print (self.getName(),[c.getValue() for c in parameter.getChildren()]) #self._coordinates = [ CoordinatesElement(parameter = c, parent = self, name = 'CenterOffset') for c in parameter.getChildren()] #print (self._coordinates) self._coordinates = CoordinatesElement(parameter = parameter, parent = self, name = 'CenterOffset') self._ar.append(self._coordinates) #print (self._slices) #self._slices += 1 #return self._coordinates else: super(IconSetElement, self).createChildForParameter(parameter)
[ "gtalpo@gmail.com" ]
gtalpo@gmail.com
accb283546d8db9c6c849aabc2073d96eb85f4b9
95e0c6e6f6f01ce9dd4121269985620ec651074f
/gmhelper/panel/migrations/0012_auto_20190902_1445.py
930445223989f48b59e0672c7e5486acd687ef0a
[]
no_license
admiralbolt/gmhelper
88e60333d52d62bca63158b0c04c512bd7a76765
1ada3cb3eb27edf307cf08e7a7025c03d04b299a
refs/heads/master
2020-06-23T17:47:40.473826
2019-10-18T02:02:36
2019-10-18T02:02:36
198,703,886
1
0
null
null
null
null
UTF-8
Python
false
false
501
py
# Generated by Django 2.2.4 on 2019-09-02 14:45 from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('panel', '0011_cityitem_name'), ] operations = [ migrations.AlterModelOptions( name='cityitem', options={'ordering': ['number']}, ), migrations.AddField( model_name='city', name='description', field=models.TextField(blank=True), ), ]
[ "aviknecht@gmail.com" ]
aviknecht@gmail.com
fc872aa394709078b797782309ec81784b4a2e96
5095200e9ca55cd3a37af34ed44448c02e2a1bb5
/modules/image/classification/darknet53_imagenet/darknet.py
58c5b090172b042d7df701c6691b3c1e867c1b23
[ "Apache-2.0" ]
permissive
PaddlePaddle/PaddleHub
8712603ef486c45e83eb0bc5725b0b3ed3ddbbde
b402610a6f0b382a978e82473b541ea1fc6cf09a
refs/heads/develop
2023-07-24T06:03:13.172978
2023-03-28T11:49:55
2023-03-28T11:49:55
162,672,577
12,914
2,239
Apache-2.0
2023-07-06T21:38:19
2018-12-21T06:00:48
Python
UTF-8
Python
false
false
5,029
py
# coding=utf-8 from __future__ import absolute_import from __future__ import division from __future__ import print_function import six import math from paddle import fluid from paddle.fluid.param_attr import ParamAttr from paddle.fluid.regularizer import L2Decay __all__ = ['DarkNet'] class DarkNet(object): """DarkNet, see https://pjreddie.com/darknet/yolo/ Args: depth (int): network depth, currently only darknet 53 is supported norm_type (str): normalization type, 'bn' and 'sync_bn' are supported norm_decay (float): weight decay for normalization layer weights get_prediction (bool): whether to get prediction class_dim (int): number of class while classification """ def __init__(self, depth=53, norm_type='sync_bn', norm_decay=0., weight_prefix_name='', get_prediction=False, class_dim=1000): assert depth in [53], "unsupported depth value" self.depth = depth self.norm_type = norm_type self.norm_decay = norm_decay self.depth_cfg = {53: ([1, 2, 8, 8, 4], self.basicblock)} self.prefix_name = weight_prefix_name self.class_dim = class_dim self.get_prediction = get_prediction def _conv_norm(self, input, ch_out, filter_size, stride, padding, act='leaky', name=None): conv = fluid.layers.conv2d( input=input, num_filters=ch_out, filter_size=filter_size, stride=stride, padding=padding, act=None, param_attr=ParamAttr(name=name + ".conv.weights"), bias_attr=False) bn_name = name + ".bn" bn_param_attr = ParamAttr(regularizer=L2Decay(float(self.norm_decay)), name=bn_name + '.scale') bn_bias_attr = ParamAttr(regularizer=L2Decay(float(self.norm_decay)), name=bn_name + '.offset') out = fluid.layers.batch_norm( input=conv, act=None, param_attr=bn_param_attr, bias_attr=bn_bias_attr, moving_mean_name=bn_name + '.mean', moving_variance_name=bn_name + '.var') # leaky relu here has `alpha` as 0.1, can not be set by # `act` param in fluid.layers.batch_norm above. if act == 'leaky': out = fluid.layers.leaky_relu(x=out, alpha=0.1) return out def _downsample(self, input, ch_out, filter_size=3, stride=2, padding=1, name=None): return self._conv_norm(input, ch_out=ch_out, filter_size=filter_size, stride=stride, padding=padding, name=name) def basicblock(self, input, ch_out, name=None): conv1 = self._conv_norm(input, ch_out=ch_out, filter_size=1, stride=1, padding=0, name=name + ".0") conv2 = self._conv_norm(conv1, ch_out=ch_out * 2, filter_size=3, stride=1, padding=1, name=name + ".1") out = fluid.layers.elementwise_add(x=input, y=conv2, act=None) return out def layer_warp(self, block_func, input, ch_out, count, name=None): out = block_func(input, ch_out=ch_out, name='{}.0'.format(name)) for j in six.moves.xrange(1, count): out = block_func(out, ch_out=ch_out, name='{}.{}'.format(name, j)) return out def __call__(self, input): """Get the backbone of DarkNet, that is output for the 5 stages. :param input: Variable of input image :type input: Variable :Returns: The last variables of each stage. """ stages, block_func = self.depth_cfg[self.depth] stages = stages[0:5] conv = self._conv_norm( input=input, ch_out=32, filter_size=3, stride=1, padding=1, name=self.prefix_name + "yolo_input") downsample_ = self._downsample( input=conv, ch_out=conv.shape[1] * 2, name=self.prefix_name + "yolo_input.downsample") blocks = [] for i, stage in enumerate(stages): block = self.layer_warp( block_func=block_func, input=downsample_, ch_out=32 * 2**i, count=stage, name=self.prefix_name + "stage.{}".format(i)) blocks.append(block) if i < len(stages) - 1: # do not downsaple in the last stage downsample_ = self._downsample( input=block, ch_out=block.shape[1] * 2, name=self.prefix_name + "stage.{}.downsample".format(i)) if self.get_prediction: pool = fluid.layers.pool2d(input=block, pool_type='avg', global_pooling=True) stdv = 1.0 / math.sqrt(pool.shape[1] * 1.0) out = fluid.layers.fc( input=pool, size=self.class_dim, param_attr=ParamAttr(initializer=fluid.initializer.Uniform(-stdv, stdv), name='fc_weights'), bias_attr=ParamAttr(name='fc_offset')) out = fluid.layers.softmax(out) return out else: return blocks
[ "wuzewu@baidu.com" ]
wuzewu@baidu.com
9cd0d2eb1ad55a66abea7fa857b94d0ed57ca72c
048d970d83519074993dbc948b058cccda48a893
/untitled6/testvideo/views.py
0f404eeb76f5d87239a80507d97511b294d8904f
[]
no_license
alingb/PycharmProjects
0669ec007779a3265a0026409a3b2aeb2dc5406f
9592454f4847da1618136e756fa641013e573889
refs/heads/master
2020-03-25T20:02:21.840945
2018-11-07T09:52:40
2018-11-07T09:52:40
null
0
0
null
null
null
null
UTF-8
Python
false
false
5,473
py
# -*- coding: utf-8 -*- from __future__ import unicode_literals from django.shortcuts import render # Create your views here. from django.templatetags.static import register from django.utils.safestring import mark_safe from testvideo import models @register.simple_tag def action_all(current_url, index): """ 获取当前url,video-1-1-2.html :param current_url: :param item: :return: """ url_part_list = current_url.split('-') if index == 3: if url_part_list[index] == "0.html": temp = "<a href='%s' class='active'>全部</a>" else: temp = "<a href='%s'>全部</a>" url_part_list[index] = "0.html" else: if url_part_list[index] == "0": temp = "<a href='%s' class='active'>全部</a>" else: temp = "<a href='%s'>全部</a>" url_part_list[index] = "0" href = '-'.join(url_part_list) temp = temp % (href,) return mark_safe(temp) @register.simple_tag def action(current_url, item, index): # videos-0-0-1.html # item: id name # video- 2 -0-0.html url_part_list = current_url.split('-') if index == 3: if str(item['id']) == url_part_list[3].split('.')[0]: # 如果当前标签被选中 temp = "<a href='%s' class='active'>%s</a>" else: temp = "<a href='%s'>%s</a>" url_part_list[index] = str(item['id']) + '.html' # 拼接对应位置的部分url else: if str(item['id']) == url_part_list[index]: temp = "<a href='%s' class='active'>%s</a>" else: temp = "<a href='%s'>%s</a>" url_part_list[index] = str(item['id']) ur_str = '-'.join(url_part_list) # 拼接整体url temp = temp % (ur_str, item['name']) # 生成对应的a标签 return mark_safe(temp) # 返回安全的html def video(request,*args,**kwargs): print(kwargs) # 当前请求的路径 request_path = request.path # 从数据库获取视频时的filter条件字典 q = {} # 状态为审核通过的 q['status'] = 1 # 获取url中的视频分类id class_id = int(kwargs.get('classification_id')) # 从数据库中获取所有的视频方向(包括视频方向的id和name) direction_list = models.Direction.objects.all().values('id','name') # 如果视频方向是0 if kwargs.get('direction_id') == '0': # 方向选择全部 # 方向id=0,即获取所有的视频分类(包括视频分类的id和name) class_list = models.Classification.objects.all().values('id', 'name') # 如果视频分类id也为0,即全部分类,那就什么都不用做,因为已经全取出来了 if kwargs.get('classification_id') == '0': pass else: # 如果视频分类不是全部,过滤条件为视频分类id在[url中的视频分类id] q['classification_id__in'] = [class_id,] else: print('方向不为0') # 方向选择某一个方向, # 如果分类是0 if kwargs.get('classification_id') == '0': print('分类为0') # 获取已选择的视频方向 obj = models.Direction.objects.get(id=int(kwargs.get('direction_id'))) # 获取该方向的所有视频分类 class_list = obj.classification.all().values('id', 'name') # 获取所有视频分类对应的视频分类id id_list = list(map(lambda x: x['id'], class_list)) # 过滤条件为视频分类id in [该方向下的所有视频分类id] q['classification_id__in'] = id_list else: # 方向不为0,分类也不为0 obj = models.Direction.objects.get(id=int(kwargs.get('direction_id'))) class_list = obj.classification.all().values('id', 'name') id_list = list(map(lambda x:x['id'], class_list)) # 过滤条件为视频分类id in [已经选择的视频分类id] q['classification_id__in'] = [class_id,] print('分类不为0') # 当前分类如果在获取的所有分类中,则方向下的所有相关分类显示 # 当前分类如果不在获取的所有分类中, if int(kwargs.get('classification_id')) in id_list: pass else: print('不再,获取指定方向下的所有分类:选中的回到全部') url_part_list = request_path.split('-') url_part_list[2] = '0' request_path = '-'.join(url_part_list) # 视频等级id level_id = int(kwargs.get('level_id')) if level_id == 0: pass else: # 过滤条件增加视频等级 q['level'] = level_id # 取出相对应的视频 video_list = models.Video.objects.filter(**q).values('title','summary', 'img', 'href') # 把视频等级转化为单个标签是字典格式,整体是列表格式 ret = map(lambda x:{"id": x[0], 'name': x[1]}, models.Video.level_choice) level_list = list(ret) return render(request, 'video.html', {'direction_list': direction_list, 'class_list': class_list, 'level_list': level_list, 'current_url': request_path, "video_list": video_list})
[ "375272990@qq.com" ]
375272990@qq.com
1403668c6a8f650ba3160210a868b2cf3eb0c8b4
d4412fbe37540e2c4cbe59ed6503d3661ccb7d9c
/tests/test_auto_parallel/test_tensor_shard/test_find_repeat_block.py
a0b407b240e1fc4432002ed50a1e0132348e3ded
[ "BSD-3-Clause", "LicenseRef-scancode-warranty-disclaimer", "Apache-2.0", "BSD-2-Clause", "MIT" ]
permissive
hpcaitech/ColossalAI
a082ed08a3807b53c49d1f86835b9808590d9042
c7b60f75470f067d1342705708810a660eabd684
refs/heads/main
2023-09-01T04:13:13.834565
2023-08-30T15:07:21
2023-08-30T15:07:21
422,274,596
32,044
4,084
Apache-2.0
2023-09-14T15:19:54
2021-10-28T16:19:44
Python
UTF-8
Python
false
false
3,747
py
from typing import Optional, Tuple import torch import torch.nn as nn from torch.fx import GraphModule from transformers.pytorch_utils import Conv1D from colossalai._analyzer.fx.graph_module import ColoGraphModule from colossalai._analyzer.fx.passes import shape_prop_pass # from colossalai.fx.tracer.tracer import ColoTracer from colossalai._analyzer.fx.tracer.tracer import ColoTracer from colossalai.auto_parallel.tensor_shard.utils.factory import find_repeat_blocks from colossalai.testing import clear_cache_before_run, parameterize, run_on_environment_flag NUM_REPEAT_BLOCKS = 4 BATCH_SIZE = 1 SEQ_LENGTH = 32 HIDDEN_DIM = 384 class RepeatBlock(nn.Module): def __init__(self, intermediate_size, hidden_size): super().__init__() self.c_fc = Conv1D(intermediate_size, hidden_size) self.c_proj = Conv1D(hidden_size, intermediate_size) self.act = torch.nn.ReLU() def forward(self, hidden_states: Optional[Tuple[torch.FloatTensor]]) -> torch.FloatTensor: hidden_states = self.c_fc(hidden_states) hidden_states = self.act(hidden_states) hidden_states = self.c_proj(hidden_states) return hidden_states class RepeatModel(nn.Module): def __init__(self, intermediate_size, hidden_size, num_layers): super().__init__() self.blocks = nn.ModuleList([RepeatBlock(intermediate_size, hidden_size) for i in range(num_layers)]) def forward(self, x): for block in self.blocks: x = block(x) return x class NonRepeatBlock(nn.Module): def __init__(self, intermediate_size, hidden_size, layer_index): super().__init__() intermediate_size //= (layer_index + 1) self.c_fc = Conv1D(intermediate_size, hidden_size) self.c_proj = Conv1D(hidden_size, intermediate_size) self.act = torch.nn.ReLU() def forward(self, hidden_states: Optional[Tuple[torch.FloatTensor]]) -> torch.FloatTensor: hidden_states = self.c_fc(hidden_states) hidden_states = self.act(hidden_states) hidden_states = self.c_proj(hidden_states) return hidden_states class NonRepeatModel(nn.Module): def __init__(self, intermediate_size, hidden_size, num_layers): super().__init__() self.blocks = nn.ModuleList([NonRepeatBlock(intermediate_size, hidden_size, i) for i in range(num_layers)]) def forward(self, x): for block in self.blocks: x = block(x) return x @run_on_environment_flag(name='AUTO_PARALLEL') @clear_cache_before_run() @parameterize('model_cls', [RepeatModel, NonRepeatModel]) def test_repeat_blocks(model_cls): model = model_cls(4 * HIDDEN_DIM, HIDDEN_DIM, NUM_REPEAT_BLOCKS) tracer = ColoTracer(bias_addition_split=True) input_sample = {'x': torch.rand(BATCH_SIZE, SEQ_LENGTH, HIDDEN_DIM).to('meta')} graph = tracer.trace(root=model, meta_args=input_sample) gm = GraphModule(model, graph, model.__class__.__name__) shape_prop_pass(gm, *input_sample.values()) gm.recompile() node_list = list(graph.nodes) root_module = graph.owning_module common_blocks = find_repeat_blocks(node_list, root_module, common_length_threshold=10) total_num_nodes = len(list(graph.nodes)) # remove the input placeholder node and the output node num_repeat_nodes_per_block = (total_num_nodes - 2) // NUM_REPEAT_BLOCKS for common_block in common_blocks: print(common_block) if model_cls == RepeatModel: assert len(common_blocks) == NUM_REPEAT_BLOCKS assert len(common_blocks[0]) == num_repeat_nodes_per_block elif model_cls == NonRepeatModel: assert len(common_blocks) == 0 if __name__ == '__main__': test_repeat_blocks()
[ "noreply@github.com" ]
hpcaitech.noreply@github.com
e6ec76c65798d40248d5a90ddffc9772d75c8291
46c521a85f567c609f8a073cb9569ea59e2a104f
/28_7_1.py
4c10dd39b5917d3c3039704439b344bc05c305fc
[]
no_license
Kunal352000/python_adv
c046b6b785b52eaaf8d089988d4dadf0a25fa8cb
d9736b6377ae2d486854f93906a6bf5bc4e45a98
refs/heads/main
2023-07-15T23:48:27.131948
2021-08-21T13:16:42
2021-08-21T13:16:42
398,557,910
0
0
null
null
null
null
UTF-8
Python
false
false
357
py
import threading print("Welcome") class test(threading.Thread): def run(self): for i in range(5): print("hey") t1=test() t1.run() for j in range(5): print("hello") """ Welcome hey hey hey hey hey hello hello hello hello hello in this above example we are creating a thread but it is not activated """
[ "noreply@github.com" ]
Kunal352000.noreply@github.com
8754d0a57ec86b3d5a931c7fc157021615b21c84
b8ed71f3d1a36c119d846e97f1aa7d8ba6774f52
/289_Game_of_Life.py
74198f0167a8743c4175a626070e5f5a27f45fd3
[]
no_license
imjaya/Leetcode_solved
0831c4114dd919864452430c4e46d3f69b4bd0cd
374eb0f23ae14d9638d20bbfe622209f71397ae0
refs/heads/master
2023-05-24T17:57:56.633611
2023-05-16T06:31:42
2023-05-16T06:31:42
284,203,426
0
0
null
null
null
null
UTF-8
Python
false
false
1,461
py
#space complexity(O(1)) class Solution: def gameOfLife(self, board: List[List[int]]) -> None: m=len(board) n=len(board[0]) def isValidNeighbor(x, y): return x < len(board) and x >= 0 and y < len(board[0]) and y >= 0 # All directions of neighbors x_dir = [-1, -1, -1, 0, 0, 1, 1, 1] y_dir = [-1, 0, 1, -1,1,-1, 0, 1] for row in range(0,m): for col in range(0,n): live_neighbors = 0 for i in range(8): curr_x, curr_y = row + x_dir[i], col + y_dir[i] if isValidNeighbor(curr_x, curr_y) and abs(board[curr_x][curr_y]) == 1: live_neighbors+=1 # Rules 1 and 3: -1 indicates a cell that was live but now is dead. if board[row][col] == 1 and (live_neighbors < 2 or live_neighbors > 3): board[row][col] = -1 # Rule 4: 2 indicates a cell that was dead but now is live. if board[row][col] == 0 and live_neighbors == 3: board[row][col] = 2 # Get the final board for row in range(len(board)): for col in range(len(board[0])): if board[row][col] >= 1: board[row][col] = 1 else: board[row][col] = 0
[ "smjayasurya1997@gmail.com" ]
smjayasurya1997@gmail.com
e83ca298c78ac124bae7c759a8b88993346c5704
06d32fa1f306c7c4f48e115cb8cd17576f4786d4
/kagi/upper/west/five.py
ebd7bbf742ad56902dc7e86facc43e21692724df
[ "MIT" ]
permissive
jedhsu/kagi
b2e146749f5a4840675a59bf3a2511b3aae82b6a
1301f7fc437bb445118b25ca92324dbd58d6ad2d
refs/heads/main
2023-06-29T18:09:57.723463
2021-08-04T23:40:50
2021-08-04T23:40:50
392,842,759
0
0
null
null
null
null
UTF-8
Python
false
false
384
py
""" *Upper-West 5* |⠟| The upper-west five gi. """ from dataclasses import dataclass from kagi import Kagi from ..._gi import StrismicGi from ...west import WesternGi from ..._number import FiveGi from .._gi import UpperGi __all__ = ["UpperWest5"] @dataclass class UpperWest5( Gi, StrismicGi, UpperGi, WesternGi, FiveGi, ): symbol = "\u281f"
[ "jed910@gmail.com" ]
jed910@gmail.com
b98f6b0a66040c69b6a1cb34ce379a01039469bb
52a32a93942b7923b7c0c6ca5a4d5930bbba384b
/dojo/tools/api_cobalt/importer.py
93ba6a06e0c98ea1cb6d94de2f84a8dd0f031cf3
[ "MIT-open-group", "GCC-exception-2.0", "BSD-3-Clause", "LicenseRef-scancode-free-unknown", "LGPL-3.0-only", "GPL-3.0-or-later", "LicenseRef-scancode-warranty-disclaimer", "LGPL-3.0-or-later", "IJG", "Zlib", "LicenseRef-scancode-proprietary-license", "PSF-2.0", "LicenseRef-scancode-python-cwi...
permissive
DefectDojo/django-DefectDojo
43bfb1c728451335661dadc741be732a50cd2a12
b98093dcb966ffe972f8719337de2209bf3989ec
refs/heads/master
2023-08-21T13:42:07.238370
2023-08-14T18:00:34
2023-08-14T18:00:34
31,028,375
2,719
1,666
BSD-3-Clause
2023-09-14T19:46:49
2015-02-19T17:53:47
HTML
UTF-8
Python
false
false
2,002
py
import logging from django.core.exceptions import ValidationError from dojo.models import Product_API_Scan_Configuration from .api_client import CobaltAPI logger = logging.getLogger(__name__) class CobaltApiImporter(object): """ Import from Cobalt.io API """ def get_findings(self, test): client, config = self.prepare_client(test) findings = client.get_findings(config.service_key_1) return findings def prepare_client(self, test): product = test.engagement.product if test.api_scan_configuration: config = test.api_scan_configuration # Double check of config if config.product != product: raise ValidationError( "API Scan Configuration for Cobalt.io and Product do not match. " f'Product: "{product.name}" ({product.id}), config.product: "{config.product.name}" ({config.product.id})' ) else: configs = Product_API_Scan_Configuration.objects.filter( product=product, tool_configuration__tool_type__name="Cobalt.io", ) if configs.count() == 1: config = configs.first() elif configs.count() > 1: raise ValidationError( "More than one Product API Scan Configuration has been configured, but none of them has been " "chosen. Please specify at Test which one should be used. " f'Product: "{product.name}" ({product.id})' ) else: raise ValidationError( "There are no API Scan Configurations for this Product. Please add at least one API Scan " "Configuration for Cobalt.io to this Product. " f'Product: "{product.name}" ({product.id})' ) tool_config = config.tool_configuration return CobaltAPI(tool_config), config
[ "noreply@github.com" ]
DefectDojo.noreply@github.com
2a73ccb328b4920d2f01f6669bdc5893366856cc
9743d5fd24822f79c156ad112229e25adb9ed6f6
/xai/brain/wordbase/otherforms/_mooting.py
bf6f2ecc1479abe52448d6823a2c0e6190595738
[ "MIT" ]
permissive
cash2one/xai
de7adad1758f50dd6786bf0111e71a903f039b64
e76f12c9f4dcf3ac1c7c08b0cc8844c0b0a104b6
refs/heads/master
2021-01-19T12:33:54.964379
2017-01-28T02:00:50
2017-01-28T02:00:50
null
0
0
null
null
null
null
UTF-8
Python
false
false
218
py
#calss header class _MOOTING(): def __init__(self,): self.name = "MOOTING" self.definitions = moot self.parents = [] self.childen = [] self.properties = [] self.jsondata = {} self.basic = ['moot']
[ "xingwang1991@gmail.com" ]
xingwang1991@gmail.com
54cc0636b26ccf62e0b9bcdd44704905d3cdfa6b
efbc8c73e9ac5cbcb9321518ab06b3965369a5f0
/Baekjoon/Silver/Silver5/2628_종이자르기.py
d451947b0161c3b6cdab39d493483d9302941333
[]
no_license
AshOil/APS
56b9395dcbb8eeec87a047407d4326b879481612
fe5a2cd63448fcc4b11b5e5bc060976234ed8eea
refs/heads/master
2023-07-15T17:32:20.684742
2021-08-23T13:04:05
2021-08-23T13:04:05
283,709,661
0
0
null
null
null
null
UTF-8
Python
false
false
970
py
import sys sys.stdin = open('input_data/2628.txt','r') # 정보 주워담기 width, height = list(map(int,input().split())) cutting = int(input()) cuttings = [] verti = [width] hori = [height] for _ in range(cutting): cuttings.append(list(map(int,input().split()))) #가로 / 세로 분류하기 for cut in cuttings: if cut[0] == 0: hori.append(cut[1]) else: verti.append(cut[1]) # 분류한거 순서대로 분류하기 verti.sort() hori.sort() verti_len = len(verti) hori_len = len(hori) # 자른 선 크기별로 구분하기 verti_paper,hori_paper = [0] * verti_len, [0] * hori_len hori_paper[0], verti_paper[0] = hori[0], verti[0] for i in range(1,verti_len): verti_paper[i] = verti[i]-verti[i-1] for i in range(1, hori_len): hori_paper[i] = hori[i] - hori[i - 1] # 크기 구하기 result = [] for i in hori_paper: for j in verti_paper: result.append(i*j) print(max(result)) # 4,10 --> 4,6 # 2,3,8 --> 2 ,1 5
[ "ka0@kakao.com" ]
ka0@kakao.com
7f5855dedb64367070b0ef77a897b9586ad9e416
ad13583673551857615498b9605d9dcab63bb2c3
/output/models/sun_data/elem_decl/value_constraint/value_constraint01001m/value_constraint01001m4_xsd/__init__.py
dae74b497b244e9ac0e2a6dc6d9bf257666e0089
[ "MIT" ]
permissive
tefra/xsdata-w3c-tests
397180205a735b06170aa188f1f39451d2089815
081d0908382a0e0b29c8ee9caca6f1c0e36dd6db
refs/heads/main
2023-08-03T04:25:37.841917
2023-07-29T17:10:13
2023-07-30T12:11:13
239,622,251
2
0
MIT
2023-07-25T14:19:04
2020-02-10T21:59:47
Python
UTF-8
Python
false
false
196
py
from output.models.sun_data.elem_decl.value_constraint.value_constraint01001m.value_constraint01001m4_xsd.value_constraint01001m4 import ( Id, Root, ) __all__ = [ "Id", "Root", ]
[ "tsoulloftas@gmail.com" ]
tsoulloftas@gmail.com
1888a818f62e4bd9f2d753f36a3b611afa16fa52
877ad498d10ad8d2ab2891e5d3709fcf3aa4f513
/setup.py
fc6be61f8184572dda654f760e2988b8e78734cf
[ "LicenseRef-scancode-unknown-license-reference", "Apache-2.0" ]
permissive
rdcli/rdc.dic
a3f2601e258cd3afe17673045a8029794c72a65f
61aca591afdc53613a1cec3ebce23b8d69e3780d
refs/heads/master
2020-12-25T18:22:25.401882
2014-01-14T19:31:21
2014-01-14T19:33:27
15,901,266
1
0
null
null
null
null
UTF-8
Python
false
false
1,248
py
from setuptools import setup, find_packages tolines = lambda c: filter(None, map(lambda s: s.strip(), c.split('\n'))) def read(filename, flt=None): with open(filename) as f: content = f.read().strip() return flt(content) if callable(flt) else content def requirements_filter(c): install_requires = [] for requirement in tolines(c): _pound_pos = requirement.find('#') if _pound_pos != -1: requirement = requirement[0:_pound_pos].strip() if len(requirement): install_requires.append(requirement) return install_requires version = read('version.txt') setup( name='rdc.dic', namespace_packages = ['rdc'], version=version, description="Simple dependency injection container", long_description=read('README.rst'), classifiers=read('classifiers.txt', tolines), author='Romain Dorgueil', author_email='romain@dorgueil.net', url='http://dic.rdc.li/', download_url='https://github.com/rdcli/rdc.dic/tarball/' + version, license='Apache License, Version 2.0', packages=find_packages(exclude=['ez_setup', 'example', 'test']), include_package_data=True, install_requires=read('requirements.txt', requirements_filter), )
[ "romain@dorgueil.net" ]
romain@dorgueil.net
5a66f8c5c341634eda246b688a5bef1215c1b5a0
20ec76fa5627b4989cc5b21cfb390adb1ea931ea
/env/bin/pip
b8a7d601f3c19eec4634ff0020f275838022b520
[]
no_license
nimadorostkar/simpleCRM
7b925586ca20ce143734ec8a5118cb9210c3258b
654ba33b1fcc236485780a4d3838f75a373ad7b8
refs/heads/master
2023-08-23T21:21:26.731016
2021-10-17T13:29:31
2021-10-17T13:29:31
null
0
0
null
null
null
null
UTF-8
Python
false
false
250
#!/Users/nima/github/AtroCRM/env/bin/python3 # -*- coding: utf-8 -*- import re import sys from pip._internal.cli.main import main if __name__ == '__main__': sys.argv[0] = re.sub(r'(-script\.pyw?|\.exe)?$', '', sys.argv[0]) sys.exit(main())
[ "nimadorostkar97@gmail.com" ]
nimadorostkar97@gmail.com
d2ff20eb2738923869af9a4e0deb817d5078bc67
cd9224afd9f377adf00b9dfd18669daf39f2663f
/src/datasets/cifar10.py
e659ae738fa2338b3e5bc22cafac4c6758c927f4
[]
no_license
luzai/few-shot
56fc03ff87652d18eda291980cf01486ce2f339e
792406d990b5a0aaea0f8589883643120ede1170
refs/heads/master
2021-03-27T13:34:05.766349
2017-11-11T10:56:21
2017-11-22T08:32:36
96,596,064
1
0
null
null
null
null
UTF-8
Python
false
false
4,122
py
# Copyright 2016 The TensorFlow Authors. All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # ============================================================================== """Provides data for the Cifar10 dataset. The dataset scripts used to create the dataset can be found at: tensorflow/models/slim/datasets/download_and_convert_cifar10.py """ from __future__ import division from __future__ import absolute_import import os import tensorflow as tf from datasets import dataset_utils from preprocessing import cifar_preprocessing slim = tf.contrib.slim _FILE_PATTERN = 'cifar10_%s.tfrecord' SPLITS_TO_SIZES = {'train': 50000, 'test': 10000} _NUM_CLASSES = 10 _ITEMS_TO_DESCRIPTIONS = { 'image': 'A [32 x 32 x 3] color image.', 'label': 'A single integer between 0 and 9', } def load_batch(dataset, batch_size, height=32, width=32, is_training=False): data_provider = slim.dataset_data_provider.DatasetDataProvider( dataset, num_readers=8, common_queue_capacity=40 * batch_size, common_queue_min=20 * batch_size) image, label = data_provider.get(['image', 'label']) image = cifar_preprocessing.preprocess_image( image, height, width, is_training,label=label) images, labels = tf.train.batch( [image, label], batch_size=batch_size, # allow_smaller_final_batch=True, num_threads=8, capacity=30 * batch_size, ) batch_queue = slim.prefetch_queue.prefetch_queue( [images, labels], num_threads=512, capacity=10 * batch_size, name='prefetch/train' if is_training else 'prefetch/val' ) return batch_queue def get_split(split_name, dataset_dir, file_pattern=None, reader=None): """Gets a dataset tuple with instructions for reading cifar10. Args: split_name: A train/test split name. dataset_dir: The base directory of the dataset sources. file_pattern: The file pattern to use when matching the dataset sources. It is assumed that the pattern contains a '%s' string so that the split name can be inserted. reader: The TensorFlow reader type. Returns: A `Dataset` namedtuple. Raises: ValueError: if `split_name` is not a valid train/test split. """ if split_name not in SPLITS_TO_SIZES: raise ValueError('split name %s was not recognized.' % split_name) if not file_pattern: file_pattern = _FILE_PATTERN file_pattern = os.path.join(dataset_dir, file_pattern % split_name) # Allowing None in the signature so that dataset_factory can use the default. if not reader: reader = tf.TFRecordReader keys_to_features = { 'image/encoded': tf.FixedLenFeature((), tf.string, default_value=''), 'image/format': tf.FixedLenFeature((), tf.string, default_value='png'), 'image/class/label': tf.FixedLenFeature( [], tf.int64, default_value=tf.zeros([], dtype=tf.int64)), } items_to_handlers = { 'image': slim.tfexample_decoder.Image(shape=[32, 32, 3]), 'label': slim.tfexample_decoder.Tensor('image/class/label'), } decoder = slim.tfexample_decoder.TFExampleDecoder( keys_to_features, items_to_handlers) labels_to_names = None if dataset_utils.has_labels(dataset_dir): labels_to_names = dataset_utils.read_label_file(dataset_dir) return slim.dataset.Dataset( data_sources=file_pattern, reader=reader, decoder=decoder, num_samples=SPLITS_TO_SIZES[split_name], items_to_descriptions=_ITEMS_TO_DESCRIPTIONS, num_classes=_NUM_CLASSES, labels_to_names=labels_to_names)
[ "907682447@qq.com" ]
907682447@qq.com
6083f0ba54a255447e8adac48b77b46dd2abf103
2bb90b620f86d0d49f19f01593e1a4cc3c2e7ba8
/pardus/tags/2007.1/server/database/mysql/actions.py
e0a2bd5db26466cb3d1c1d0aa46b0ac8ea0b63ad
[]
no_license
aligulle1/kuller
bda0d59ce8400aa3c7ba9c7e19589f27313492f7
7f98de19be27d7a517fe19a37c814748f7e18ba6
refs/heads/master
2021-01-20T02:22:09.451356
2013-07-23T17:57:58
2013-07-23T17:57:58
null
0
0
null
null
null
null
UTF-8
Python
false
false
5,013
py
#!/usr/bin/python # -*- coding: utf-8 -*- # # Copyright 2005 TUBITAK/UEKAE # Licensed under the GNU General Public License, version 2. # See the file http://www.gnu.org/copyleft/gpl.txt. from pisi.actionsapi import autotools from pisi.actionsapi import libtools from pisi.actionsapi import pisitools from pisi.actionsapi import shelltools from pisi.actionsapi import get def setup(): # Don't use zlib from source pisitools.dosed("configure.in", "zlib/Makefile dnl", "dnl zlib/Makefile") # Plain autoconf doesn't work here... shelltools.export("WANT_AUTOCONF", "2.59") autotools.autoreconf("--force") libtools.libtoolize("--copy --force") libtools.gnuconfig_update() shelltools.cd("innobase/") autotools.autoreconf("--force") libtools.libtoolize("--copy --force") libtools.gnuconfig_update() shelltools.cd("../") # Export flags shelltools.export("CFLAGS", "%s -DHAVE_ERRNO_AS_DEFINE=1" % get.CFLAGS()) shelltools.export("CXXFLAGS", "%s \ -felide-constructors \ -fno-exceptions \ -fno-rtti \ -fno-implicit-templates" % get.CXXFLAGS()) # Configure! autotools.configure("--libexecdir=/usr/sbin \ --sysconfdir=/etc/mysql \ --localstatedir=/var/lib/mysql \ --with-low-memory \ --enable-local-infile \ --with-mysqld-user=mysql \ --with-client-ldflags=-lstdc++ \ --enable-thread-safe-client \ --with-comment=\"Pardus Linux\" \ --with-unix-socket-path=/var/run/mysqld/mysqld.sock \ --with-lib-ccflags=\"-fPIC\" \ --with-readline \ --without-docs \ --enable-shared \ --disable-static \ --without-libwrap \ --with-openssl \ --without-debug \ --with-charset=utf8 \ --with-collation=utf8_general_ci \ --with-extra-charsets=all \ --with-berkeley-db=./bdb \ --with-geometry \ --with-big-tables \ --without-bench \ --with-max-indexes=128 \ --enable-assembler") def build(): autotools.make() def install(): autotools.rawInstall("DESTDIR=%s benchdir_root=\"/usr/share/mysql\"" % get.installDIR()) # Extra headers pisitools.insinto("/usr/include/mysql", "include/my_config.h") pisitools.insinto("/usr/include/mysql", "include/my_dir.h") # Links pisitools.dosym("mysqlcheck", "/usr/bin/mysqlanalyze") pisitools.dosym("mysqlcheck", "/usr/bin/mysqlrepair") pisitools.dosym("mysqlcheck", "/usr/bin/mysqloptimize") # Cleanup pisitools.remove("/usr/bin/make*distribution") pisitools.remove("/usr/share/mysql/make_*_distribution") pisitools.remove("/usr/share/mysql/mysql.server") pisitools.remove("/usr/share/mysql/binary-configur") pisitools.remove("/usr/share/mysql/mysql-log-rotate") pisitools.remove("/usr/share/mysql/postinstall") pisitools.remove("/usr/share/mysql/preinstall") pisitools.remove("/usr/share/mysql/mi_test*") pisitools.remove("/usr/share/mysql/*.spec") pisitools.remove("/usr/share/mysql/*.plist") pisitools.remove("/usr/share/mysql/my-*.cnf") # Move libs to /usr/lib pisitools.domove("/usr/lib/mysql/libmysqlclient*.so*", "/usr/lib") # Links to libs pisitools.dosym("../libmysqlclient.so", "/usr/lib/mysql/libmysqlclient.so") pisitools.dosym("../libmysqlclient_r.so", "/usr/lib/mysql/libmysqlclient_r.so") # No perl for i in ["mysqlhotcopy", "mysql_find_rows", "mysql_convert_table_format", "mysqld_multi", "mysqlaccess", "mysql_fix_extensions", "mysqldumpslow", "mysql_zap", "mysql_explain_log", "mysql_tableinfo", "mysql_setpermission"]: pisitools.remove("/usr/bin/%s" % i) # No tests pisitools.removeDir("/usr/share/mysql/mysql-test") # Config pisitools.insinto("/etc/mysql", "scripts/mysqlaccess.conf") # Data dir pisitools.dodir("/var/lib/mysql") # Logs pisitools.dodir("/var/log/mysql") shelltools.touch("%s/var/log/mysql/mysql.log" % get.installDIR()) shelltools.touch("%s/var/log/mysql/mysql.err" % get.installDIR()) # Runtime data pisitools.dodir("/var/run/mysqld") # Documents pisitools.dodoc("README", "COPYING", "ChangeLog", "EXCEPTIONS-CLIENT", "INSTALL-SOURCE") pisitools.dohtml("Docs/*.html") pisitools.dodoc("Docs/manual.txt," "Docs/manual.ps") pisitools.dodoc("support-files/my-*.cnf")
[ "yusuf.aydemir@istanbul.com" ]
yusuf.aydemir@istanbul.com
0022297ee89784ff19c6b6f84fb8702deceee5c1
d52413173437ba73ecdf822ca895e659f00a8ce7
/kiwibackend/application/website/messages/http/smallGameFinish_request.py
7aafc4af6b19014945fe13957c24d557650e4a53
[]
no_license
whiteprism/mywork
2329b3459c967c079d6185c5acabd6df80cab8ea
a8e568e89744ca7acbc59e4744aff2a0756d7252
refs/heads/master
2021-01-21T11:15:49.090408
2017-03-31T03:28:13
2017-03-31T03:28:13
83,540,646
0
0
null
null
null
null
UTF-8
Python
false
false
194
py
# -*- encoding:utf8 -*- from messages.http import BaseHttp class SmallGameFinishRequest(BaseHttp): def __init__(self): super(self.__class__, self).__init__() self.score = -1
[ "snoster@163.com" ]
snoster@163.com
316c3d03ff530707876f94d6ee6d974d375a63d5
b8b6a5c77e8f55ec5757e06cb25c9f087a69565a
/b_NaiveBayes/Vectorized/Basic.py
f86efee8601811184c0c5c439748c05cc9b1ce24
[]
no_license
CourAgeZ/MachineLearning
57a1cf53cccc0c6479a82ee1f9a9cb83c15f307a
dacd7b239ae0e13709d04067bb3ff6c9848ca53a
refs/heads/master
2021-06-12T10:52:00.946162
2017-02-27T13:44:58
2017-02-27T13:44:58
null
0
0
null
null
null
null
UTF-8
Python
false
false
2,545
py
import numpy as np from math import pi from Util.Timing import Timing from Util.Bases import ClassifierBase from Util.Metas import ClassifierMeta sqrt_pi = (2 * pi) ** 0.5 class NBFunctions: @staticmethod def gaussian(x, mu, sigma): return np.exp(-(x - mu) ** 2 / (2 * sigma ** 2)) / (sqrt_pi * sigma) @staticmethod def gaussian_maximum_likelihood(labelled_x, n_category, dim): mu = [np.sum( labelled_x[c][dim]) / len(labelled_x[c][dim]) for c in range(n_category)] sigma = [np.sum( (labelled_x[c][dim] - mu[c]) ** 2) / len(labelled_x[c][dim]) for c in range(n_category)] def func(_c): def sub(_x): return NBFunctions.gaussian(_x, mu[_c], sigma[_c]) return sub return [func(_c=c) for c in range(n_category)] class NaiveBayes(ClassifierBase, metaclass=ClassifierMeta): NaiveBayesTiming = Timing() def __init__(self): self._x = self._y = None self._data = self._func = None self._n_possibilities = None self._labelled_x = self._label_zip = None self._cat_counter = self._con_counter = None self.label_dic = self._feat_dics = None def feed_data(self, x, y, sample_weight=None): pass def _feed_sample_weight(self, sample_weight=None): pass @NaiveBayesTiming.timeit(level=2, prefix="[API] ") def get_prior_probability(self, lb=1): return [(_c_num + lb) / (len(self._y) + lb * len(self._cat_counter)) for _c_num in self._cat_counter] @NaiveBayesTiming.timeit(level=2, prefix="[API] ") def fit(self, x=None, y=None, sample_weight=None, lb=1): if x is not None and y is not None: self.feed_data(x, y, sample_weight) self._func = self._fit(lb) def _fit(self, lb): pass @NaiveBayesTiming.timeit(level=1, prefix="[API] ") def predict(self, x, get_raw_result=False): if isinstance(x, np.ndarray): x = x.tolist() else: x = [xx[:] for xx in x] x = self._transfer_x(x) m_arg, m_probability = np.zeros(len(x), dtype=np.int8), np.zeros(len(x)) for i in range(len(self._cat_counter)): p = self._func(x, i) _mask = p > m_probability m_arg[_mask], m_probability[_mask] = i, p[_mask] if not get_raw_result: return np.array([self.label_dic[arg] for arg in m_arg]) return m_probability def _transfer_x(self, x): return x
[ "syameimaru_kurumi@pku.edu.cn" ]
syameimaru_kurumi@pku.edu.cn
ed5cfa850b7454b812a97955c6826d3f6a7e0781
90419da201cd4948a27d3612f0b482c68026c96f
/sdk/python/pulumi_azure_nextgen/authorization/v20160401/get_policy_assignment.py
5bb2543c721ece32d8f504f7f2199e5c835d0238
[ "BSD-3-Clause", "Apache-2.0" ]
permissive
test-wiz-sec/pulumi-azure-nextgen
cd4bee5d70cb0d332c04f16bb54e17d016d2adaf
20a695af0d020b34b0f1c336e1b69702755174cc
refs/heads/master
2023-06-08T02:35:52.639773
2020-11-06T22:39:06
2020-11-06T22:39:06
312,993,761
0
0
Apache-2.0
2023-06-02T06:47:28
2020-11-15T09:04:00
null
UTF-8
Python
false
false
4,069
py
# coding=utf-8 # *** WARNING: this file was generated by the Pulumi SDK Generator. *** # *** Do not edit by hand unless you're certain you know what you are doing! *** import warnings import pulumi import pulumi.runtime from typing import Any, Mapping, Optional, Sequence, Union from ... import _utilities, _tables __all__ = [ 'GetPolicyAssignmentResult', 'AwaitableGetPolicyAssignmentResult', 'get_policy_assignment', ] @pulumi.output_type class GetPolicyAssignmentResult: """ The policy assignment. """ def __init__(__self__, display_name=None, name=None, policy_definition_id=None, scope=None, type=None): if display_name and not isinstance(display_name, str): raise TypeError("Expected argument 'display_name' to be a str") pulumi.set(__self__, "display_name", display_name) if name and not isinstance(name, str): raise TypeError("Expected argument 'name' to be a str") pulumi.set(__self__, "name", name) if policy_definition_id and not isinstance(policy_definition_id, str): raise TypeError("Expected argument 'policy_definition_id' to be a str") pulumi.set(__self__, "policy_definition_id", policy_definition_id) if scope and not isinstance(scope, str): raise TypeError("Expected argument 'scope' to be a str") pulumi.set(__self__, "scope", scope) if type and not isinstance(type, str): raise TypeError("Expected argument 'type' to be a str") pulumi.set(__self__, "type", type) @property @pulumi.getter(name="displayName") def display_name(self) -> Optional[str]: """ The display name of the policy assignment. """ return pulumi.get(self, "display_name") @property @pulumi.getter def name(self) -> Optional[str]: """ The name of the policy assignment. """ return pulumi.get(self, "name") @property @pulumi.getter(name="policyDefinitionId") def policy_definition_id(self) -> Optional[str]: """ The ID of the policy definition. """ return pulumi.get(self, "policy_definition_id") @property @pulumi.getter def scope(self) -> Optional[str]: """ The scope for the policy assignment. """ return pulumi.get(self, "scope") @property @pulumi.getter def type(self) -> Optional[str]: """ The type of the policy assignment. """ return pulumi.get(self, "type") class AwaitableGetPolicyAssignmentResult(GetPolicyAssignmentResult): # pylint: disable=using-constant-test def __await__(self): if False: yield self return GetPolicyAssignmentResult( display_name=self.display_name, name=self.name, policy_definition_id=self.policy_definition_id, scope=self.scope, type=self.type) def get_policy_assignment(policy_assignment_name: Optional[str] = None, scope: Optional[str] = None, opts: Optional[pulumi.InvokeOptions] = None) -> AwaitableGetPolicyAssignmentResult: """ Use this data source to access information about an existing resource. :param str policy_assignment_name: The name of the policy assignment to get. :param str scope: The scope of the policy assignment. """ __args__ = dict() __args__['policyAssignmentName'] = policy_assignment_name __args__['scope'] = scope if opts is None: opts = pulumi.InvokeOptions() if opts.version is None: opts.version = _utilities.get_version() __ret__ = pulumi.runtime.invoke('azure-nextgen:authorization/v20160401:getPolicyAssignment', __args__, opts=opts, typ=GetPolicyAssignmentResult).value return AwaitableGetPolicyAssignmentResult( display_name=__ret__.display_name, name=__ret__.name, policy_definition_id=__ret__.policy_definition_id, scope=__ret__.scope, type=__ret__.type)
[ "public@paulstack.co.uk" ]
public@paulstack.co.uk
0ed74b75cbe013a56cf016c6af9b4c55bdcbb98f
d751b167ac5b1ef414815f946f2cdf1c46c4c3bc
/third_party/onnx-tensorrt/third_party/onnx/onnx/backend/test/case/node/greater.py
bc04c37fb414bdaa562e063e9dd5192a8ed3a83c
[ "BSD-3-Clause", "LicenseRef-scancode-generic-cla", "Apache-2.0", "BSD-2-Clause", "MIT" ]
permissive
kurff/pytorch
3356d8f44f2f0f4784af90dfcc8a6ae0b0b7a435
2871c0db2cb516a3546103577d88149882ed406d
refs/heads/master
2022-10-22T17:20:18.696100
2019-03-24T02:51:28
2019-03-24T02:51:28
163,299,370
2
1
NOASSERTION
2022-10-13T08:26:24
2018-12-27T13:44:29
C++
UTF-8
Python
false
false
1,107
py
from __future__ import absolute_import from __future__ import division from __future__ import print_function from __future__ import unicode_literals import numpy as np # type: ignore import onnx from ..base import Base from . import expect class Greater(Base): @staticmethod def export(): node = onnx.helper.make_node( 'Greater', inputs=['x', 'y'], outputs=['greater'], ) x = np.random.randn(3, 4, 5).astype(np.float32) y = np.random.randn(3, 4, 5).astype(np.float32) z = np.greater(x, y) expect(node, inputs=[x, y], outputs=[z], name='test_greater') @staticmethod def export_greater_broadcast(): node = onnx.helper.make_node( 'Greater', inputs=['x', 'y'], outputs=['greater'], broadcast=1, ) x = np.random.randn(3, 4, 5).astype(np.float32) y = np.random.randn(5).astype(np.float32) z = np.greater(x, y) expect(node, inputs=[x, y], outputs=[z], name='test_greater_bcast')
[ "kurffzhou@tencent.com" ]
kurffzhou@tencent.com
4ee9eab0c7e56c4690d64f2418700d0b8dd57179
f1ef7f1b0701add6532613abc72411196e41b631
/tests/test_bind.py
40589a21bc6fcc459b860c582da10b13b9c885e4
[ "MIT" ]
permissive
TrendingTechnology/typical
afdd482f9ac30c1a61502119b5f219d767d468a3
125b3bda8c1c1c18edf0eccd9160fffdef0749ee
refs/heads/main
2023-07-17T01:55:02.590174
2021-09-02T01:13:52
2021-09-02T01:16:14
null
0
0
null
null
null
null
UTF-8
Python
false
false
1,293
py
from __future__ import annotations import inspect import pytest import typic def foo(arg, *args, kwd=None, **kwargs): # pragma: nocover pass def one(arg): # pragma: nocover pass def pos(arg, *args): # pragma: nocover pass def kwd(*, kwd=None): # pragma: nocover pass def kwarg(arg, **kwargs): # pragma: nocover pass def typed(arg: str): # pragma: nocover return type(arg) def test_bind(): sig = inspect.signature(foo) args, kwargs = (1, 2), {"kwd": "kwd", "kwarg": "kwarg"} builtin: inspect.BoundArguments = sig.bind(*args, **kwargs) baked = typic.bind(foo, *args, **kwargs) assert builtin.kwargs == baked.kwargs assert builtin.args == baked.args assert dict(builtin.arguments) == baked.arguments def test_typed_no_coerce(): bound = typic.bind(typed, 1, coerce=False) assert bound.arguments["arg"] == 1 @pytest.mark.parametrize( argnames=("func", "params"), argvalues=[ (one, ((1, 1), {})), (one, ((), {})), (one, ((1,), {"arg": 1})), (kwd, ((1,), {})), (kwd, ((), {"foo": 1})), (kwarg, ((1, 1), {})), ], ) def test_bind_errors(func, params): args, kwargs = params with pytest.raises(TypeError): typic.bind(func, *args, **kwargs)
[ "sean_stewart@me.com" ]
sean_stewart@me.com
f12efd5ed35fd74e1473fbc7a4e486b309acacb7
add74ecbd87c711f1e10898f87ffd31bb39cc5d6
/xcp2k/classes/_hydronium4.py
443fc603162a0a0656a7d260f804120f0b86d348
[]
no_license
superstar54/xcp2k
82071e29613ccf58fc14e684154bb9392d00458b
e8afae2ccb4b777ddd3731fe99f451b56d416a83
refs/heads/master
2021-11-11T21:17:30.292500
2021-11-06T06:31:20
2021-11-06T06:31:20
62,589,715
8
2
null
null
null
null
UTF-8
Python
false
false
3,357
py
from xcp2k.inputsection import InputSection from _point66 import _point66 class _hydronium4(InputSection): def __init__(self): InputSection.__init__(self) self.Oxygens = [] self.Hydrogens = [] self.Roo = None self.Pno = None self.Qno = None self.Roh = None self.Pnh = None self.Qnh = None self.Nh = None self.P = None self.Q = None self.Lambda = None self.Lambda = None self.POINT_list = [] self._name = "HYDRONIUM" self._keywords = {'Roh': 'ROH', 'Nh': 'NH', 'P': 'P', 'Roo': 'ROO', 'Q': 'Q', 'Pnh': 'PNH', 'Pno': 'PNO', 'Qno': 'QNO', 'Qnh': 'QNH', 'Lambda': 'LAMBDA'} self._repeated_keywords = {'Oxygens': 'OXYGENS', 'Hydrogens': 'HYDROGENS'} self._repeated_subsections = {'POINT': '_point66'} self._aliases = {'Expon_numerator': 'P', 'Nhtest': 'Nh', 'R_oh': 'Roh', 'Expon_denominator': 'Q', 'R_oo': 'Roo', 'Expon_numeratorb': 'Pnh', 'Expon_numeratora': 'Pno', 'Expon_denominatorb': 'Qnh', 'Expon_denominatora': 'Qno'} self._attributes = ['POINT_list'] def POINT_add(self, section_parameters=None): new_section = _point66() if section_parameters is not None: if hasattr(new_section, 'Section_parameters'): new_section.Section_parameters = section_parameters self.POINT_list.append(new_section) return new_section @property def R_oo(self): """ See documentation for Roo """ return self.Roo @property def Expon_numeratora(self): """ See documentation for Pno """ return self.Pno @property def Expon_denominatora(self): """ See documentation for Qno """ return self.Qno @property def R_oh(self): """ See documentation for Roh """ return self.Roh @property def Expon_numeratorb(self): """ See documentation for Pnh """ return self.Pnh @property def Expon_denominatorb(self): """ See documentation for Qnh """ return self.Qnh @property def Nhtest(self): """ See documentation for Nh """ return self.Nh @property def Expon_numerator(self): """ See documentation for P """ return self.P @property def Expon_denominator(self): """ See documentation for Q """ return self.Q @R_oo.setter def R_oo(self, value): self.Roo = value @Expon_numeratora.setter def Expon_numeratora(self, value): self.Pno = value @Expon_denominatora.setter def Expon_denominatora(self, value): self.Qno = value @R_oh.setter def R_oh(self, value): self.Roh = value @Expon_numeratorb.setter def Expon_numeratorb(self, value): self.Pnh = value @Expon_denominatorb.setter def Expon_denominatorb(self, value): self.Qnh = value @Nhtest.setter def Nhtest(self, value): self.Nh = value @Expon_numerator.setter def Expon_numerator(self, value): self.P = value @Expon_denominator.setter def Expon_denominator(self, value): self.Q = value
[ "xingwang1991@gmail.com" ]
xingwang1991@gmail.com
75d3b3834258ef72bfb6de302d88c71fb7d08026
dd9836546e93c6a080b2a3f01379648abe82d7f6
/sdk/test/test_filtered_client_payload_list_institution.py
1e887f5b5a291c053d55786b4ad7b9a8ef04f6d9
[ "MIT" ]
permissive
yapily/yapily-sdk-python
f5c21ff9dc59fecca97948f1e2b263e537d59a85
92ede62b0069fdffb7f22bfea92b91a93747c296
refs/heads/master
2022-12-10T09:24:54.029376
2022-11-25T12:42:30
2022-11-25T12:42:30
133,962,026
13
9
MIT
2022-02-11T16:57:11
2018-05-18T14:02:57
Python
UTF-8
Python
false
false
1,489
py
""" Yapily API The Yapily API enables connections between your application and users' banks. For more information check out our [documentation](https://docs.yapily.com/).<br><br>In particular, make sure to view our [Getting Started](https://docs.yapily.com/pages/home/getting-started/) steps if this is your first time here.<br><br>While testing the API, our list of [sandbox credentials](https://docs.yapily.com/pages/key-concepts/sandbox-credentials/) maybe useful. # noqa: E501 The version of the OpenAPI document: 2.15.0 Contact: support@yapily.com Generated by: https://openapi-generator.tech """ import sys import unittest import yapily from yapily.model.filter_and_sort import FilterAndSort from yapily.model.institution import Institution globals()['FilterAndSort'] = FilterAndSort globals()['Institution'] = Institution from yapily.model.filtered_client_payload_list_institution import FilteredClientPayloadListInstitution class TestFilteredClientPayloadListInstitution(unittest.TestCase): """FilteredClientPayloadListInstitution unit test stubs""" def setUp(self): pass def tearDown(self): pass def testFilteredClientPayloadListInstitution(self): """Test FilteredClientPayloadListInstitution""" # FIXME: construct object with mandatory attributes with example values # model = FilteredClientPayloadListInstitution() # noqa: E501 pass if __name__ == '__main__': unittest.main()
[ "bitbucket@yapily.com" ]
bitbucket@yapily.com
43fb48803324825fa92d12d78fbc9e7e170ada28
f6371fe3c848a7dae6dc7a5325bc6f19be63046f
/2048.py
5a92587b6e99937d55c45028539cb48380f96576
[]
no_license
zhangdavids/2048youxi
9b8fe8dbc851b1a380197bd435b24e079dee7707
aee515288b922f7d353fbf3433b8fecd56d23125
refs/heads/master
2021-01-10T01:44:39.718816
2016-04-03T14:33:18
2016-04-03T14:33:18
55,350,492
2
0
null
null
null
null
UTF-8
Python
false
false
7,105
py
#!usr/bin/python #-*- coding:utf-8 -*- #导入需要的包 import curses from random import randrange, choice # generate and place new tile from collections import defaultdict #区分下大小写 letter_codes = [ord(ch) for ch in 'WASDRQwasdrq'] #用户行为 actions = ['Up', 'Left', 'Down', 'Right', 'Restart', 'Exit'] #行为关联 actions_dict = dict(zip(letter_codes, actions * 2)) # 用户处理 def get_user_action(keyboard): char = "N" while char not in actions_dict: char = keyboard.getch() return actions_dict[char] # 矩阵转置 def transpose(field): return [list(row) for row in zip(*field)] # 矩阵逆转 def invert(field): return [row[::-1] for row in field] # 创建棋盘 class GameField(object): def __init__(self, height=4, width=4, win=2048): self.height = height self.width = width self.win_value = 2048 self.score = 0 self.highscore = 0 self.reset() #重置棋盘 def reset(self): if self.score > self.highscore: self.highscore = self.score self.score = 0 self.field = [[0 for i in range(self.width)] for j in range(self.height)] self.spawn() self.spawn() def move(self, direction): def move_row_left(row): def tighten(row): # squeese non-zero elements together new_row = [i for i in row if i != 0] new_row += [0 for i in range(len(row) - len(new_row))] return new_row def merge(row): pair = False new_row = [] for i in range(len(row)): if pair: new_row.append(2 * row[i]) self.score += 2 * row[i] pair = False else: if i + 1 < len(row) and row[i] == row[i + 1]: pair = True new_row.append(0) else: new_row.append(row[i]) assert len(new_row) == len(row) return new_row return tighten(merge(tighten(row))) moves = {} moves['Left'] = lambda field:[move_row_left(row) for row in field] moves['Right'] = lambda field:invert(moves['Left'](invert(field))) moves['Up'] = lambda field:transpose(moves['Left'](transpose(field))) moves['Down'] = lambda field:transpose(moves['Right'](transpose(field))) if direction in moves: if self.move_is_possible(direction): self.field = moves[direction](self.field) self.spawn() return True else: return False def is_win(self): return any(any(i >= self.win_value for i in row) for row in self.field) def is_gameover(self): return not any(self.move_is_possible(move) for move in actions) def draw(self, screen): help_string1 = '(W)Up (S)Down (A)Left (D)Right' help_string2 = ' (R)Restart (Q)Exit' gameover_string = ' GAME OVER' win_string = ' YOU WIN!' def cast(string): screen.addstr(string + '\n') def draw_hor_separator(): line = '+' + ('+------' * self.width + '+')[1:] separator = defaultdict(lambda: line) if not hasattr(draw_hor_separator, "counter"): draw_hor_separator.counter = 0 cast(separator[draw_hor_separator.counter]) draw_hor_separator.counter += 1 def draw_row(row): cast(''.join('|{: ^5} '.format(num) if num > 0 else '| ' for num in row) + '|') screen.clear() cast('SCORE: ' + str(self.score)) if 0 != self.highscore: cast('HGHSCORE: ' + str(self.highscore)) for row in self.field: draw_hor_separator() draw_row(row) draw_hor_separator() if self.is_win(): cast(win_string) else: if self.is_gameover(): cast(gameover_string) else: cast(help_string1) cast(help_string2) def spawn(self): new_element = 4 if randrange(100) > 89 else 2 (i,j) = choice([(i,j) for i in range(self.width) for j in range(self.height) if self.field[i][j] == 0]) self.field[i][j] = new_element def move_is_possible(self, direction): def row_is_left_movable(row): def change(i): # true if there'll be change in i-th tile if row[i] == 0 and row[i + 1] != 0: # Move return True if row[i] != 0 and row[i + 1] == row[i]: # Merge return True return False return any(change(i) for i in range(len(row) - 1)) check = {} check['Left'] = lambda field: \ any(row_is_left_movable(row) for row in field) check['Right'] = lambda field: \ check['Left'](invert(field)) check['Up'] = lambda field: \ check['Left'](transpose(field)) check['Down'] = lambda field: \ check['Right'](transpose(field)) if direction in check: return check[direction](self.field) else: return False def main(stdscr): def init(): #重置游戏棋盘 game_field.reset() return 'Game' def not_game(state): #画出 GameOver 或者 Win 的界面 game_field.draw(stdscr) #读取用户输入得到action,判断是重启游戏还是结束游戏 action = get_user_action(stdscr) responses = defaultdict(lambda: state) #默认是当前状态,没有行为就会一直在当前界面循环 responses['Restart'], responses['Exit'] = 'Init', 'Exit' #对应不同的行为转换到不同的状态 return responses[action] def game(): #画出当前棋盘状态 game_field.draw(stdscr) #读取用户输入得到action action = get_user_action(stdscr) if action == 'Restart': return 'Init' if action == 'Exit': return 'Exit' if game_field.move(action): # move successful if game_field.is_win(): return 'Win' if game_field.is_gameover(): return 'Gameover' return 'Game' state_actions = { 'Init': init, 'Win': lambda: not_game('Win'), 'Gameover': lambda: not_game('Gameover'), 'Game': game } curses.use_default_colors() game_field = GameField(win=32) state = 'Init' #状态机开始循环 while state != 'Exit': state = state_actions[state]() curses.wrapper(main)
[ "1269969739@qq.com" ]
1269969739@qq.com
70d96d19ee9e1ef10f8830c60a370e52578457b6
d0c34e4c346d59236da84b35ca0e5f032a997efd
/Python/Excel/xlrdwtDemo.py
7552d5d1b055c4012b435fc7fe6e38d79cfdcb04
[]
no_license
kinscloud/kinscloud.github.io
898b7309485493578a4ecbc1976b3e158f2a3d93
3ff8d74a85bcc62464796d529874fc9e226d120a
refs/heads/master
2022-12-14T22:01:34.245628
2020-05-31T02:49:05
2020-05-31T02:49:05
244,150,397
0
0
null
2022-12-08T04:02:36
2020-03-01T13:03:23
Python
UTF-8
Python
false
false
1,103
py
import xlrd,xlwt workbook = xlrd.open_workbook("testxls.xls") sheet = workbook.sheet_by_name("Sheet1") title_row = sheet.row(0) # print(title_row[0].value) # print(sheet.nrows) datas = [] for i in range(1,sheet.nrows): data_row = sheet.row(i) data ={} for j in range(sheet.ncols): cell = data_row[j] if cell.ctype == xlrd.XL_CELL_DATE: value = xlrd.xldate_as_datetime(cell.value,0).strftime(("%Y-%m-%d")) elif cell.ctype == xlrd.XL_CELL_NUMBER: value = int(cell.value) else: value = cell.value # print(value) data[title_row[j].value] = value datas.append(data) print(datas) workbook = xlwt.Workbook() sheet = workbook.add_sheet("kins") for i in range(len(title_row)): sheet.write(0,i,title_row[i].value) for i in range(len(datas)): data = datas[i] value_datas = list(data.values()) for j in range((len(value_datas))): sheet.write(i+1,j,value_datas[j]) workbook.save("test2.xlsx")
[ "yuan_haoting@163.com" ]
yuan_haoting@163.com
e304282d4c8f4ab18ba35702c0703ad72a67782a
b99619d109a5106155feb3f4c4e82cd97f0f4fa6
/ace/label.py
a8a6a53463714a6eeacb8267e2982af1e1460d45
[ "MIT" ]
permissive
chenruixiaoluoye/ACE
7b9ddbed7e0ce611d92b0d6e6b68758a3cf99d34
914d67d7ea879078ba8c9b5fe44dbdd3e3a886ff
refs/heads/master
2021-01-18T17:51:23.704640
2013-11-07T18:43:13
2013-11-07T18:43:13
null
0
0
null
null
null
null
UTF-8
Python
false
false
451
py
# from nltk import * import re from collections import Counter class Labeler: ''' Labels articles with features. ''' def __init__(self): pass def extract_word_features(self, text, pattern=r'[^\sa-z\-]+', normalize=None): ''' Takes text from an article as input and returns a dict of features --> weights. ''' patt = re.compile(pattern) clean = patt.sub('', text.lower()) tokens = re.split('\s+', clean) n_words = len(tokens)
[ "tyarkoni@gmail.com" ]
tyarkoni@gmail.com
76f68c393e14fa5280deb2f7eb959af34d25c1b9
4dec0f934760ca69e40b62fa56b37a1aa3918b24
/test/test_secureTeaHeaders.py
80274e003a9517ebcf9c8c78454095994b267bc0
[ "MIT" ]
permissive
rejahrehim/SecureTea-Project
28ebc89f27ed59e3845b8c82f9316108cda40a24
43dec187e5848b9ced8a6b4957b6e9028d4d43cd
refs/heads/master
2020-03-27T12:36:21.779426
2019-09-02T16:01:55
2019-09-02T16:01:55
146,556,097
1
0
MIT
2018-08-29T06:35:54
2018-08-29T06:35:53
null
UTF-8
Python
false
false
1,645
py
# -*- coding: utf-8 -*- import unittest from securetea.lib.security_header import secureTeaHeaders try: # if python 3.x.x from unittest.mock import patch except ImportError: # python 2.x.x from mock import patch class TestSecureTeaHeaders(unittest.TestCase): """Test class for SecureTeaHeaders.""" def setUp(self): """ Setup test class for SecureTeaHeaders. """ self.securetea_header_obj = secureTeaHeaders.SecureTeaHeaders(url='https://random.com') def test_verify_url(self): """ Test verify_url. """ u1 = "h://random.com" u2 = "http://" u3 = "http://www.random.com" u4 = "https://www.random.com" self.assertFalse(self.securetea_header_obj.verify_url(u1)) self.assertFalse(self.securetea_header_obj.verify_url(u2)) self.assertTrue(self.securetea_header_obj.verify_url(u3)) self.assertTrue(self.securetea_header_obj.verify_url(u4)) @patch('securetea.lib.security_header.secureTeaHeaders.requests') def test_call_url(self, mock_requests): """ Test call_url. """ mock_requests.get.return_value = "random" self.assertEqual("random", self.securetea_header_obj.call_url()) @patch('securetea.lib.security_header.secureTeaHeaders.SecureTeaHeaders.call_url') def test_gather_headers(self, mock_call): """ Test gather_headers. """ mock_call.return_value.headers = "random" headers_dict = self.securetea_header_obj.gather_headers() self.assertEqual("random", headers_dict)
[ "abhishek_official@hotmail.com" ]
abhishek_official@hotmail.com
a01c9e08511b51bf50b3030a1e188422c644b72d
4d51545a8072fa8f67c16655ec4054239dbaa5c0
/migrations/versions/4d0367090b41_.py
3fdcd4b266f4e0ea0f7eee4bb1165c5a559795ed
[]
no_license
chaelysh6z/hanium
b3cf4360ab47d66c1bddbece542981577b173c68
78067717f1406e66033dfafb7f186159a6cb032e
refs/heads/master
2023-08-15T03:59:01.794004
2021-09-25T12:43:19
2021-09-25T12:43:19
410,238,513
0
0
null
null
null
null
UTF-8
Python
false
false
755
py
"""empty message Revision ID: 4d0367090b41 Revises: 220cbe1a485d Create Date: 2021-09-23 18:30:46.632858 """ from alembic import op import sqlalchemy as sa # revision identifiers, used by Alembic. revision = '4d0367090b41' down_revision = '220cbe1a485d' branch_labels = None depends_on = None def upgrade(): # ### commands auto generated by Alembic - please adjust! ### op.add_column('user', sa.Column('gender', sa.Boolean(), nullable=True)) op.add_column('user', sa.Column('age', sa.Integer(), nullable=True)) # ### end Alembic commands ### def downgrade(): # ### commands auto generated by Alembic - please adjust! ### op.drop_column('user', 'age') op.drop_column('user', 'gender') # ### end Alembic commands ###
[ "renee8369@likelion.org" ]
renee8369@likelion.org
88f5ebcc36922a472a6c004c6d1820c5f74cf0bc
9efca95a55cb4df52d895d42f1ec10331516a734
/tools/c7n_azure/tests_azure/tests_resources/test_recovery_services.py
fcf0faa4c288f4e814cef3e704af19756b478d1b
[ "Apache-2.0" ]
permissive
cloud-custodian/cloud-custodian
519e602abe00c642786441b64cc40857ef5bc9de
27563cf4571040f923124e1acb2463f11e372225
refs/heads/main
2023-09-04T10:54:55.963703
2023-09-01T17:40:17
2023-09-01T17:40:17
52,837,350
3,327
1,096
Apache-2.0
2023-09-14T14:03:30
2016-03-01T01:11:20
Python
UTF-8
Python
false
false
972
py
# Copyright The Cloud Custodian Authors. # SPDX-License-Identifier: Apache-2.0 from ..azure_common import BaseTest, arm_template class RecoveryServicesTest(BaseTest): def test_recovery_services_schema_validate(self): with self.sign_out_patch(): p = self.load_policy({ 'name': 'test-recovery-services', 'resource': 'azure.recovery-services' }, validate=True) self.assertTrue(p) @arm_template('recoveryservices.json') def test_find_by_name(self): p = self.load_policy({ 'name': 'test-recovery-services', 'resource': 'azure.recovery-services', 'filters': [ {'type': 'value', 'key': 'name', 'op': 'eq', 'value_type': 'normalize', 'value': 'cfbukqrkhntars655e53akvrc4k'}], }) resources = p.run() self.assertEqual(len(resources), 1)
[ "noreply@github.com" ]
cloud-custodian.noreply@github.com
bc1f728763c7e47e6575a536dcee1578a9e44c46
8c5f61b9438f67d7439301c1f3995f2995873e0d
/trinity/protocol/eth/events.py
aa9aaf69900a7c927b7f82b25d9c5b8867bea93b
[ "MIT" ]
permissive
rampenke/trinity
9efb7de2f3911f393b3f2c23adea356f4acb4fb2
38fa6826b80bbda4f608e6dca366e468c362e3c2
refs/heads/master
2020-06-12T13:48:10.579223
2019-06-27T15:20:31
2019-06-27T15:20:31
null
0
0
null
null
null
null
UTF-8
Python
false
false
4,948
py
from dataclasses import ( dataclass, ) from typing import ( List, Tuple, Type, ) from eth.rlp.blocks import BaseBlock from eth.rlp.headers import BlockHeader from eth.rlp.receipts import Receipt from eth.rlp.transactions import BaseTransactionFields from lahja import ( BaseEvent, ) from p2p.kademlia import ( Node, ) from eth_typing import ( BlockIdentifier, Hash32, ) from trinity.protocol.common.events import ( HasRemoteEvent, HasRemoteAndTimeoutRequest, PeerPoolMessageEvent, ) from trinity.protocol.common.types import ( BlockBodyBundles, NodeDataBundles, ReceiptsBundles, ) # Events flowing from PeerPool to Proxy class GetBlockHeadersEvent(PeerPoolMessageEvent): """ Event to carry a ``GetBlockHeaders`` command from the peer pool to any process that subscribes the event through the event bus. """ pass class GetBlockBodiesEvent(PeerPoolMessageEvent): """ Event to carry a ``GetBlockBodies`` command from the peer pool to any process that subscribes the event through the event bus. """ pass class GetReceiptsEvent(PeerPoolMessageEvent): """ Event to carry a ``GetReceipts`` command from the peer pool to any process that subscribes the event through the event bus. """ pass class GetNodeDataEvent(PeerPoolMessageEvent): """ Event to carry a ``GetNodeData`` command from the peer pool to any process that subscribes the event through the event bus. """ pass class TransactionsEvent(PeerPoolMessageEvent): """ Event to carry a ``Transactions`` command from the peer pool to any process that subscribes the event through the event bus. """ pass class NewBlockHashesEvent(PeerPoolMessageEvent): """ Event to carry a ``Transactions`` command from the peer pool to any process that subscribes the event through the event bus. """ pass # Events flowing from Proxy to PeerPool @dataclass class SendBlockHeadersEvent(HasRemoteEvent): """ Event to proxy a ``ETHPeer.sub_proto.send_block_headers`` call from a proxy peer to the actual peer that sits in the peer pool. """ headers: Tuple[BlockHeader, ...] @dataclass class SendBlockBodiesEvent(HasRemoteEvent): """ Event to proxy a ``ETHPeer.sub_proto.send_block_bodies`` call from a proxy peer to the actual peer that sits in the peer pool. """ blocks: List[BaseBlock] @dataclass class SendNodeDataEvent(HasRemoteEvent): """ Event to proxy a ``ETHPeer.sub_proto.send_node_data`` call from a proxy peer to the actual peer that sits in the peer pool. """ nodes: Tuple[bytes, ...] @dataclass class SendReceiptsEvent(HasRemoteEvent): """ Event to proxy a ``ETHPeer.sub_proto.send_receipts`` call from a proxy peer to the actual peer that sits in the peer pool. """ receipts: List[List[Receipt]] @dataclass class SendTransactionsEvent(HasRemoteEvent): """ Event to proxy a ``ETHPeer.sub_proto.send_transactions`` call from a proxy peer to the actual peer that sits in the peer pool. """ transactions: List[BaseTransactionFields] # EXCHANGE HANDLER REQUEST / RESPONSE PAIRS @dataclass class GetBlockHeadersResponse(BaseEvent): headers: Tuple[BlockHeader, ...] exception: Exception = None # noqa: E701 @dataclass class GetBlockHeadersRequest(HasRemoteAndTimeoutRequest[GetBlockHeadersResponse]): remote: Node block_number_or_hash: BlockIdentifier max_headers: int skip: int reverse: bool timeout: float @staticmethod def expected_response_type() -> Type[GetBlockHeadersResponse]: return GetBlockHeadersResponse @dataclass class GetBlockBodiesResponse(BaseEvent): bundles: BlockBodyBundles exception: Exception = None # noqa: E701 @dataclass class GetBlockBodiesRequest(HasRemoteAndTimeoutRequest[GetBlockBodiesResponse]): remote: Node headers: Tuple[BlockHeader, ...] timeout: float @staticmethod def expected_response_type() -> Type[GetBlockBodiesResponse]: return GetBlockBodiesResponse @dataclass class GetNodeDataResponse(BaseEvent): bundles: NodeDataBundles exception: Exception = None # noqa: E701 @dataclass class GetNodeDataRequest(HasRemoteAndTimeoutRequest[GetNodeDataResponse]): remote: Node node_hashes: Tuple[Hash32, ...] timeout: float @staticmethod def expected_response_type() -> Type[GetNodeDataResponse]: return GetNodeDataResponse @dataclass class GetReceiptsResponse(BaseEvent): bundles: ReceiptsBundles exception: Exception = None # noqa: E701 @dataclass class GetReceiptsRequest(HasRemoteAndTimeoutRequest[GetReceiptsResponse]): remote: Node headers: Tuple[BlockHeader, ...] timeout: float @staticmethod def expected_response_type() -> Type[GetReceiptsResponse]: return GetReceiptsResponse
[ "christoph.burgdorf@gmail.com" ]
christoph.burgdorf@gmail.com
a15d6f32d6627ee0cf9e94d8afbfa77f742f459d
148072ce210ca4754ea4a37d83057e2cf2fdc5a1
/src/core/w3af/w3af/plugins/attack/db/sqlmap/tamper/bluecoat.py
ff6756e0d26798db31aecb6f8529e3c75d34f196
[]
no_license
ycc1746582381/webfuzzer
8d42fceb55c8682d6c18416b8e7b23f5e430c45f
0d9aa35c3218dc58f81c429cae0196e4c8b7d51b
refs/heads/master
2021-06-14T18:46:59.470232
2017-03-14T08:49:27
2017-03-14T08:49:27
null
0
0
null
null
null
null
UTF-8
Python
false
false
1,318
py
#!/usr/bin/env python """ Copyright (c) 2006-2015 sqlmap developers (http://sqlmap.org/) See the file 'doc/COPYING' for copying permission """ import re from lib.core.data import kb from lib.core.enums import PRIORITY __priority__ = PRIORITY.NORMAL def dependencies(): pass def tamper(payload, **kwargs): """ Replaces space character after SQL statement with a valid random blank character. Afterwards replace character = with LIKE operator Requirement: * Blue Coat SGOS with WAF activated as documented in https://kb.bluecoat.com/index?page=content&id=FAQ2147 Tested against: * MySQL 5.1, SGOS Notes: * Useful to bypass Blue Coat's recommended WAF rule configuration >>> tamper('SELECT id FROM users WHERE id = 1') 'SELECT%09id FROM%09users WHERE%09id LIKE 1' """ def process(match): word = match.group('word') if word.upper() in kb.keywords: return match.group().replace(word, "%s%%09" % word) else: return match.group() retVal = payload if payload: retVal = re.sub(r"\b(?P<word>[A-Z_]+)(?=[^\w(]|\Z)", lambda match: process(match), retVal) retVal = re.sub(r"\s*=\s*", " LIKE ", retVal) retVal = retVal.replace("%09 ", "%09") return retVal
[ "everping@outlook.com" ]
everping@outlook.com
0a2ec311dff71792436b0cdbcbde3e182282f8bb
da4bbc54b2310d2f00b89e8a7fb97f414bbc10d7
/tests/test_serializer.py
c52a07692a29f782a65e268c4b9cdf294eb9af35
[ "MIT" ]
permissive
auro-star/html-json-forms
13f0d00cccd8ba3e57254fd2e0e0ab1b85372c37
abffa4324a5f6d650283dd29deb347ba39d99e56
refs/heads/main
2023-02-21T12:57:34.213464
2020-01-10T02:16:45
2020-01-10T02:16:45
null
0
0
null
null
null
null
UTF-8
Python
false
false
836
py
from rest_framework.test import APITestCase from tests.test_app.models import Parent class RestTestCase(APITestCase): def test_submit(self): response = self.client.post('/parents/', { 'name': 'Test', 'children[0][name]': 'Test 1', 'children[1][name]': 'Test 2', }) p = Parent.objects.first() self.assertEqual( { 'id': p.pk, 'name': 'Test', 'children': [ { 'id': p.children.first().pk, 'name': 'Test 1', }, { 'id': p.children.last().pk, 'name': 'Test 2', }, ] }, response.data )
[ "andrew@wq.io" ]
andrew@wq.io
39d71e94e2ca1adfb2160ba0450bec2dfbcefea0
a6cb9d2e4a2191a1177dd9eca8f464946654704c
/docs/examples/__init__.py
72588c5d9576d1340bb0e2a33d6866e9b6dd1811
[ "Apache-2.0" ]
permissive
peterlhn/dash-bootstrap-components
71a04479da96bef12d186404fd44cf0ded401b77
c222424f05fdbba6c05282c06b61b83b3c4a8ee5
refs/heads/master
2023-06-11T23:31:30.639330
2021-06-30T09:29:49
2021-06-30T09:29:49
294,058,430
0
0
Apache-2.0
2020-09-09T08:59:06
2020-09-09T08:59:05
null
UTF-8
Python
false
false
3,733
py
import os import re from pathlib import Path import dash import dash_bootstrap_components as dbc from jinja2 import Environment, FileSystemLoader from .vendor.graphs_in_tabs import app as git_app from .vendor.iris import app as iris_app HREF_PATTERN = re.compile(r'href="') HERE = Path(__file__).parent EXAMPLES = HERE / "vendor" TEMPLATES = HERE.parent / "templates" GITHUB_EXAMPLES = ( "https://github.com/" "facultyai/dash-bootstrap-components/blob/master/examples/" ) INDEX_STRING_TEMPLATE = """{% extends "example.html" %} {% block head %} {{ super() }} {{ "{%metas%}{%css%}" }} {% endblock %} {% block title %} <title>{{ "{%title%}" }}</title> {% endblock %} <WARNING> {% block content %} {{ "{%app_entry%}" }} {% endblock %} {% block code %}<CODE>{% endblock %} {% block scripts %} <footer> {{ "{%config%}{%scripts%}{%renderer%}" }} {{ super() }} </footer> {% endblock %} """ SIZE_WARNING = """{% block size_warning %} <div class="d-sm-none"> <div class="alert alert-warning"> Warning: This example app has not been optimized for small screens, results may vary... </div> </div> {% endblock %} """ def mod_callback(fn): def wrapper(path, **kwargs): path = path.replace("/examples/simple-sidebar", "") return fn(path, **kwargs) return wrapper def build_app_from_example(app, name, code, code_link, show_warning=False): if show_warning: template = INDEX_STRING_TEMPLATE.replace("<WARNING>", SIZE_WARNING) else: template = INDEX_STRING_TEMPLATE.replace("<WARNING>", "") env = Environment(loader=FileSystemLoader(TEMPLATES.as_posix())) template = env.from_string(template) template = template.render(example_link=code_link) new_app = dash.Dash( external_stylesheets=["/static/loading.css", dbc.themes.BOOTSTRAP], requests_pathname_prefix=f"/examples/{name}/", serve_locally=False, index_string=template.replace("<CODE>", code), update_title=None, ) new_app.title = f"{name.capitalize().replace('-', ' ')} - dbc examples" new_app.layout = app.layout new_app.callback_map = app.callback_map new_app._callback_list = app._callback_list return new_app def register_apps(): iris_app_ = build_app_from_example( iris_app, "iris", (EXAMPLES / "iris.py").read_text(), os.path.join(GITHUB_EXAMPLES, "gallery/iris-kmeans/app.py"), ) git_app_ = build_app_from_example( git_app, "graphs-in-tabs", (EXAMPLES / "graphs_in_tabs.py").read_text(), os.path.join( GITHUB_EXAMPLES, "advanced-component-usage/graphs_in_tabs.py" ), ) # need to do a bit of hackery to make sure the links of the multi page app # work correctly when the app is exposed at a particular route sidebar_source = (EXAMPLES / "simple_sidebar.py").read_text() env = {} exec( HREF_PATTERN.sub('href="/examples/simple-sidebar', sidebar_source), env ) sidebar_app = env["app"] sidebar_app = build_app_from_example( sidebar_app, "simple-sidebar", sidebar_source, os.path.join(GITHUB_EXAMPLES, "multi-page-apps/simple_sidebar.py"), show_warning=True, ) # shim navigation callbacks keys = [ "..page-1-link.active...page-2-link.active...page-3-link.active..", "page-content.children", ] for key in keys: sidebar_app.callback_map[key]["callback"] = mod_callback( sidebar_app.callback_map[key]["callback"] ) return { "/examples/graphs-in-tabs": git_app_, "/examples/iris": iris_app_, "/examples/simple-sidebar": sidebar_app, }
[ "tomcbegley@gmail.com" ]
tomcbegley@gmail.com
8eb52ea6863ebef6d0668ba54548d9644fd3731c
06685fa3aceb620ea13b593ddc52bba53300b93a
/monit/recipes/default.py
908930472420766a6bc81b416ce21f076548239c
[]
no_license
66laps/kokki-cookbooks
a900f958d346e35a35a05ed6cbb12bbe2f5bf4a4
6c059f8cda577c765083dfe92688094bc38dfd4b
refs/heads/master
2021-01-01T17:00:28.952170
2010-11-20T13:39:52
2010-11-20T13:39:52
null
0
0
null
null
null
null
UTF-8
Python
false
false
646
py
from kokki import * Package("monit") File("%s/monitrc" % env['monit']['config_path'], owner = "root", group = "root", mode = 0700, content = Template("monit/monitrc.j2")) if env.system.platform == "ubuntu": File("/etc/default/monit", content = Template("monit/default.j2")) Directory("%s/monit.d" % env['monit']['config_path'], owner = "root", group = "root", mode = 0700) Directory("/var/monit", owner = "root", group = "root", mode = 0700) Service("monit", supports_restart = True, subscribes = [('restart', env.resources['File']["%s/monitrc" % env['monit']['config_path']])])
[ "samuel@descolada.com" ]
samuel@descolada.com
131730ae0dfc16ee2405747ef616b9f126049880
d2c4934325f5ddd567963e7bd2bdc0673f92bc40
/tests/artificial/transf_Integration/trend_MovingAverage/cycle_30/ar_/test_artificial_1024_Integration_MovingAverage_30__100.py
969df4a567f8ec74ee546288633ba4ba09693684
[ "BSD-3-Clause", "LicenseRef-scancode-unknown-license-reference" ]
permissive
jmabry/pyaf
797acdd585842474ff4ae1d9db5606877252d9b8
afbc15a851a2445a7824bf255af612dc429265af
refs/heads/master
2020-03-20T02:14:12.597970
2018-12-17T22:08:11
2018-12-17T22:08:11
137,104,552
0
0
BSD-3-Clause
2018-12-17T22:08:12
2018-06-12T17:15:43
Python
UTF-8
Python
false
false
278
py
import pyaf.Bench.TS_datasets as tsds import pyaf.tests.artificial.process_artificial_dataset as art art.process_dataset(N = 1024 , FREQ = 'D', seed = 0, trendtype = "MovingAverage", cycle_length = 30, transform = "Integration", sigma = 0.0, exog_count = 100, ar_order = 0);
[ "antoine.carme@laposte.net" ]
antoine.carme@laposte.net
c6d124b769bc84c50f8a497e6c8e0f524c399100
6600834a4d2455e41a0b587c57f9fc606a39d1cb
/python/dnest4/sampler.py
b6c173256ab8e3c81fb725dab58cc4816c33d3d5
[ "MIT" ]
permissive
eggplantbren/DNest4
2504bc03f885ed98cc1e5a3302fd41b2a5c78291
15254a885f6720006070834e15e845b0df6c6860
refs/heads/master
2023-03-29T21:10:01.725767
2023-03-20T00:09:24
2023-03-20T00:09:24
47,721,004
59
23
MIT
2021-08-30T11:57:39
2015-12-09T21:46:21
C++
UTF-8
Python
false
false
1,255
py
# -*- coding: utf-8 -*- from .analysis import postprocess from .backends import MemoryBackend try: from ._dnest4 import sample as _sample except ImportError: _sample = None __all__ = ["DNest4Sampler"] class DNest4Sampler(object): def __init__(self, model, backend=None): if _sample is None: raise ImportError("You must build the Cython extensions to use " "the Python API") self._model = model if backend is None: backend = MemoryBackend() self.backend = backend def sample(self, max_num_levels, **kwargs): self.backend.reset() for sample in _sample(self._model, max_num_levels, **kwargs): self.backend.write_particles( sample["samples"], sample["sample_info"] ) self.backend.write_levels(sample["levels"]) yield sample def run(self, num_steps, max_num_levels, **kwargs): if num_steps <= 0: raise ValueError("Invalid number of steps") kwargs["num_steps"] = int(num_steps) for _ in self.sample(max_num_levels, **kwargs): pass def postprocess(self, **kwargs): return postprocess(self.backend, **kwargs)
[ "danfm@nyu.edu" ]
danfm@nyu.edu
60931f9c05009d545e4a09d9160315d49798defd
fa16525085e017babe82a779428aac062e8a72b6
/test/functional/feature_config_args.py
9c08f319248dd45769b842299ce376486592604a
[ "MIT" ]
permissive
minblock/baetcoin
381cb0fe9444404bc69d5b6c4e71beec6fc74429
8527c30b7c414b479ce7f60c1af31be0afbd63f1
refs/heads/master
2021-05-22T17:12:27.444781
2020-04-04T14:17:21
2020-04-04T14:17:21
253,015,556
0
0
null
null
null
null
UTF-8
Python
false
false
5,311
py
#!/usr/bin/env python3 # Copyright (c) 2017-2018 The Bitcoin Core developers # Distributed under the MIT software license, see the accompanying # file COPYING or http://www.opensource.org/licenses/mit-license.php. """Test various command line arguments and configuration file parameters.""" import os from test_framework.test_framework import BitcoinTestFramework class ConfArgsTest(BitcoinTestFramework): def set_test_params(self): self.setup_clean_chain = True self.num_nodes = 1 def test_config_file_parser(self): # Assume node is stopped inc_conf_file_path = os.path.join(self.nodes[0].datadir, 'include.conf') with open(os.path.join(self.nodes[0].datadir, 'baetcoin.conf'), 'a', encoding='utf-8') as conf: conf.write('includeconf={}\n'.format(inc_conf_file_path)) with open(inc_conf_file_path, 'w', encoding='utf-8') as conf: conf.write('-dash=1\n') self.nodes[0].assert_start_raises_init_error(expected_msg='Error reading configuration file: parse error on line 1: -dash=1, options in configuration file must be specified without leading -') with open(inc_conf_file_path, 'w', encoding='utf-8') as conf: conf.write('nono\n') self.nodes[0].assert_start_raises_init_error(expected_msg='Error reading configuration file: parse error on line 1: nono, if you intended to specify a negated option, use nono=1 instead') with open(inc_conf_file_path, 'w', encoding='utf-8') as conf: conf.write('server=1\nrpcuser=someuser\nrpcpassword=some#pass') self.nodes[0].assert_start_raises_init_error(expected_msg='Error reading configuration file: parse error on line 3, using # in rpcpassword can be ambiguous and should be avoided') with open(inc_conf_file_path, 'w', encoding='utf-8') as conf: conf.write('server=1\nrpcuser=someuser\nmain.rpcpassword=some#pass') self.nodes[0].assert_start_raises_init_error(expected_msg='Error reading configuration file: parse error on line 3, using # in rpcpassword can be ambiguous and should be avoided') with open(inc_conf_file_path, 'w', encoding='utf-8') as conf: conf.write('server=1\nrpcuser=someuser\n[main]\nrpcpassword=some#pass') self.nodes[0].assert_start_raises_init_error(expected_msg='Error reading configuration file: parse error on line 4, using # in rpcpassword can be ambiguous and should be avoided') with open(inc_conf_file_path, 'w', encoding='utf-8') as conf: conf.write('testnot.datadir=1\n[testnet]\n') self.restart_node(0) self.nodes[0].stop_node(expected_stderr='Warning: Section [testnet] is not recognized.' + os.linesep + 'Warning: Section [testnot] is not recognized.') with open(inc_conf_file_path, 'w', encoding='utf-8') as conf: conf.write('') # clear def run_test(self): self.stop_node(0) self.test_config_file_parser() # Remove the -datadir argument so it doesn't override the config file self.nodes[0].args = [arg for arg in self.nodes[0].args if not arg.startswith("-datadir")] default_data_dir = self.nodes[0].datadir new_data_dir = os.path.join(default_data_dir, 'newdatadir') new_data_dir_2 = os.path.join(default_data_dir, 'newdatadir2') # Check that using -datadir argument on non-existent directory fails self.nodes[0].datadir = new_data_dir self.nodes[0].assert_start_raises_init_error(['-datadir=' + new_data_dir], 'Error: Specified data directory "' + new_data_dir + '" does not exist.') # Check that using non-existent datadir in conf file fails conf_file = os.path.join(default_data_dir, "baetcoin.conf") # datadir needs to be set before [regtest] section conf_file_contents = open(conf_file, encoding='utf8').read() with open(conf_file, 'w', encoding='utf8') as f: f.write("datadir=" + new_data_dir + "\n") f.write(conf_file_contents) # Temporarily disabled, because this test would access the user's home dir (~/.bitcoin) #self.nodes[0].assert_start_raises_init_error(['-conf=' + conf_file], 'Error reading configuration file: specified data directory "' + new_data_dir + '" does not exist.') # Create the directory and ensure the config file now works os.mkdir(new_data_dir) # Temporarily disabled, because this test would access the user's home dir (~/.bitcoin) #self.start_node(0, ['-conf='+conf_file, '-wallet=w1']) #self.stop_node(0) #assert os.path.exists(os.path.join(new_data_dir, 'regtest', 'blocks')) #if self.is_wallet_compiled(): #assert os.path.exists(os.path.join(new_data_dir, 'regtest', 'wallets', 'w1')) # Ensure command line argument overrides datadir in conf os.mkdir(new_data_dir_2) self.nodes[0].datadir = new_data_dir_2 self.start_node(0, ['-datadir='+new_data_dir_2, '-conf='+conf_file, '-wallet=w2']) assert os.path.exists(os.path.join(new_data_dir_2, 'regtest', 'blocks')) if self.is_wallet_compiled(): assert os.path.exists(os.path.join(new_data_dir_2, 'regtest', 'wallets', 'w2')) if __name__ == '__main__': ConfArgsTest().main()
[ "POSTMASTER@provgn.com" ]
POSTMASTER@provgn.com
d95b65bed944fae8e9c2fbf1340151d1f007f4e9
52b5773617a1b972a905de4d692540d26ff74926
/.history/length_20200528185715.py
3ea39907837c76154f9a178d2a6eea6680302f1a
[]
no_license
MaryanneNjeri/pythonModules
56f54bf098ae58ea069bf33f11ae94fa8eedcabc
f4e56b1e4dda2349267af634a46f6b9df6686020
refs/heads/master
2022-12-16T02:59:19.896129
2020-09-11T12:05:22
2020-09-11T12:05:22
null
0
0
null
null
null
null
UTF-8
Python
false
false
399
py
def removeDuplicates(nums): length = len(nums) i = 0 for i in range(length): if nums[i] in nums: nums.remove(nums[i]) else: # for i in range(length): # print('i--------->',i) # for j in range(i+1,length): # print('j----->',j) removeDuplicates([1,1,1,2,2])
[ "mary.jereh@gmail.com" ]
mary.jereh@gmail.com
25494d2bd6e4f43fef81a4f5b6eaf97f9b1bf970
6838d66f8dec23db63923f375438af2dd9fb22fe
/veci.py
ac79c7cb73d425d1b12de28ccdb49c58223331b3
[]
no_license
xCiaraG/Kattis
795ef7c463c60f362068f0d0e7c8ec8da4a69d19
ec08aa588f61d78937fb3c63bdb803e999fc9c36
refs/heads/master
2021-01-22T21:27:54.736451
2020-10-25T17:44:09
2020-10-25T17:44:09
85,432,383
9
9
null
2020-10-25T17:44:10
2017-03-18T21:13:13
Python
UTF-8
Python
false
false
520
py
def find_next_highest(num): prev = num[-1] i = len(num) - 2 while i > 0 and num[i] >= prev: prev = num[i] i -= 1 last = num[i] if i + 1 < len(num): tmp = num[i+1:] tmp = sorted(tmp) j = 0 while tmp[j] <= last: j += 1 prev = tmp[j] tmp[j] = last num = num[:i] + prev + "".join(sorted(list(tmp))) return num num = input().strip() if list(num) == sorted(num, reverse=True): print("0") else: tmp = find_next_highest(num) print(tmp)
[ "ciara.godwin3@mail.dcu.ie" ]
ciara.godwin3@mail.dcu.ie
eff332cddfac6e33b29f86fc23e80db171ef1789
9743d5fd24822f79c156ad112229e25adb9ed6f6
/xai/brain/wordbase/nouns/_rosters.py
f8631bb8682147eb7da6cb389f061eb4ec7083e6
[ "MIT" ]
permissive
cash2one/xai
de7adad1758f50dd6786bf0111e71a903f039b64
e76f12c9f4dcf3ac1c7c08b0cc8844c0b0a104b6
refs/heads/master
2021-01-19T12:33:54.964379
2017-01-28T02:00:50
2017-01-28T02:00:50
null
0
0
null
null
null
null
UTF-8
Python
false
false
238
py
from xai.brain.wordbase.nouns._roster import _ROSTER #calss header class _ROSTERS(_ROSTER, ): def __init__(self,): _ROSTER.__init__(self) self.name = "ROSTERS" self.specie = 'nouns' self.basic = "roster" self.jsondata = {}
[ "xingwang1991@gmail.com" ]
xingwang1991@gmail.com
a60aa5073db426c3692adf396ef7d4fd84425185
94bd3bb35729a470cd2568f909184db4fbe916c0
/calculaPCT_grasspy_esc10000.py
53a708cff411da9907152a9b4e95f5049757a358
[]
no_license
JohnWRRC/Scripts_DelimitaBacias_TrabalhoFinalizado_Tadeu
a8b3b2f73b06f2d5eff0251cc45f283327cfefdc
544270aadbd7df379d0aeb4c231aa5bd79c4a827
refs/heads/master
2021-01-18T14:11:49.329090
2015-07-17T20:10:42
2015-07-17T20:10:42
39,273,273
0
0
null
null
null
null
UTF-8
Python
false
false
2,378
py
import grass.script as grass import os #mapa de vegetacao vegetacao="vegetacao_natural_cli_rast_30m_tif" mapa="mosaic_topodata_30m_extract_tif_10000_30m_vect" length=1 os.chdir(r'E:\data_2015\___john\Tadeu_finlandia\TXTs_PCT\esc_10000') def stats_area(mapa,id_map): id_map=id_map.replace('\n','') acumla_area=0 grass.run_command('g.region',rast=mapa) x=grass.read_command('r.stats',flags='a',input=mapa) y=x.split('\n') del y[-1];del y[-1] #for aculuma area_m2 for i in y: split=i.split(' ') area_m2=float(split[1]) acumla_area=acumla_area+area_m2 txt=open('basin_'+id_map+'.txt','w') cabecalho='id'',''pct_veg\n' txt.write(cabecalho) for i in y: split=i.split(' ') id=split[0] area_m2=float(split[1]) pct=round(area_m2/acumla_area*100,3) txt.write(id+','+`pct`+'\n') txt.close() #stats_area("mapa_soma_int",5965) def create_bins(mapa_temp): vegetacao="vegetacao_natural_cli_rast_30m_tif" expressao1='veg_temp=if('+mapa_temp+'>0,'+vegetacao+',null())' grass.mapcalc(expressao1, overwrite = True, quiet = True) grass.run_command('r.series',inpu='veg_temp,'+mapa_temp,out='mapa_soma',method='sum',overwrite=True) expressao2='mapa_soma_int=int(mapa_soma)' grass.mapcalc(expressao2, overwrite = True, quiet = True) return 'mapa_soma_int' def stats(mapa): grass.run_command('g.region',vect=mapa) con=3116 while con <= 3155: query="id=%d"%con x=grass.read_command('v.db.select', flags='c', map=mapa, column='id', where=query,verbose=False) grass.run_command('v.extract', input=mapa, output='temp', where=query, type='area', new=1,overwrite=True,verbose=False) grass.run_command('v.to.rast', input='temp', out='temp_rast_masc', use="cat",overwrite=True,verbose=False) grass.run_command('r.mask',input="temp_rast_masc",overwrite=True) mapa_soma=create_bins("temp_rast_masc") stats_area(mapa_soma,x) grass.run_command('g.remove',flags='f',rast=mapa_soma+',mapa_soma_int') grass.run_command('g.remove',flags='f',vect='temp') grass.run_command('r.mask',flags='r') grass.run_command('g.remove',flags='f',rast='temp_rast_masc') con=con+1 stats(mapa)
[ "jw.ribeiro.rc@gmail.com" ]
jw.ribeiro.rc@gmail.com
59ac86859ebc3b4feecda7d118d1f89861e4695c
9a3262882123a0937d5b713919688ba7c580ae9f
/eslearn/utils/regression/multi_test2.py
5d1b0ec4b7a57ac57eedc26e5eb57905a0f1398d
[ "MIT" ]
permissive
sysunwenbo/easylearn
fa7f6dd6cf2e0e66780469dc7046b46e486574fd
145274cb374c0337b7ec5aed367841663c527a6f
refs/heads/master
2022-04-18T00:16:56.263547
2020-04-16T15:45:07
2020-04-16T15:45:07
256,792,139
0
1
MIT
2020-04-18T15:49:10
2020-04-18T15:49:09
null
UTF-8
Python
false
false
560
py
# -*- coding: utf-8 -*- """ Created on Tue Aug 14 20:25:12 2018 @author: lenovo """ def func(msg): print (multiprocessing.current_process().name + '-' + msg) if __name__ == "__main__": pool = multiprocessing.Pool(processes=4) # 创建4个进程 for i in range(10): msg = "hello %d" %(i) pool.apply_async(func, (msg, )) pool.close() # 关闭进程池,表示不能在往进程池中添加进程 pool.join() # 等待进程池中的所有进程执行完毕,必须在close()之后调用 print ("Sub-process(es) done.")
[ "you@example.com" ]
you@example.com