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
87990ee7c013adfed4d8152d526bab78f47feee2
9550ce4a80169d21b556b22679a9462f98438e32
/app/urls.py
32f3b1ab973c04cbcb9ce11ea3ea6d0850315945
[ "Apache-2.0" ]
permissive
erics1996/questionnaire_django
87cc44bd745eb810861349effc126ed3dfbd6508
1006c61eba1e9efec0801299938eb13c16a0b292
refs/heads/master
2022-12-15T04:47:39.042594
2020-09-02T17:34:33
2020-09-02T17:34:33
284,580,189
0
0
Apache-2.0
2020-09-02T17:34:34
2020-08-03T02:02:20
Python
UTF-8
Python
false
false
300
py
from django.contrib import admin from django.urls import path, re_path from .views import backend urlpatterns = [ path('', backend.IndexView.as_view()), re_path('survey/(?P<pk>\d+)/', backend.SurveyDetailView.as_view()), re_path('(?P<pk>\d+)/download/', backend.DownloadView.as_view()) ]
a78acddf6eebc59cad1ebc0e8fdaf53ee0ce2702
44a7101ae18c84ffa0e3c674763ba7b500937773
/root/Desktop/Scripts/pyinstaller-1.5.1/bh_sshRcmd/bh_sshRcmd.spec
66707266787869a8fdd977ad9985b57711fe3880
[]
no_license
Draft2007/Scripts
cbaa66ce0038f3370c42d93da9308cbd69fb701a
0dcc720a1edc882cfce7498ca9504cd9b12b8a44
refs/heads/master
2016-09-05T20:05:46.601503
2015-06-23T00:05:02
2015-06-23T00:05:02
37,945,893
7
2
null
null
null
null
UTF-8
Python
false
false
561
spec
# -*- mode: python -*- a = Analysis([os.path.join(HOMEPATH,'support/_mountzlib.py'), os.path.join(HOMEPATH,'support/useUnicode.py'), '/usr/local/tools/bh_sshRcmd.py'], pathex=['/usr/local/tools/pyinstaller-1.5.1']) pyz = PYZ(a.pure) exe = EXE( pyz, a.scripts, a.binaries, a.zipfiles, a.datas, name=os.path.join('dist', 'bh_sshRcmd'), debug=False, strip=False, upx=True, console=1 ) app = BUNDLE(exe, name=os.path.join('dist', 'bh_sshRcmd.app'))
dc0f1debf616d07e130ae2adb13b8209fd2e2f74
99afa83eda09cf552466ddf90314cb01d07b166a
/testapp/models.py
c1fa45c2c96048893e614bf9142070231858f126
[]
no_license
jithinvijayan007/Lithoera
358c9a6191d6510ac07229e7a92eadd89d70e14f
33e3639e882f79b12541f92070dad74483fdfa72
refs/heads/master
2023-01-05T18:29:37.388869
2020-11-02T11:58:27
2020-11-02T11:58:27
309,316,888
0
0
null
null
null
null
UTF-8
Python
false
false
1,764
py
from django.db import models from django.contrib.auth.models import AbstractBaseUser, BaseUserManager # Create your models here. class MyAccountManager(BaseUserManager): def create_user(self, email, username, password=None): if not email: raise ValueError('Users must have an email address') if not username: raise ValueError('Users must have a username') user = self.model( email=self.normalize_email(email), username=username, ) user.set_password(password) user.save(using=self._db) return user def create_superuser(self, email, username, password): user = self.create_user( email=self.normalize_email(email), password=password, username=username, ) user.is_admin = True user.is_staff = True user.is_superuser = True user.save(using=self._db) return user class Account(AbstractBaseUser): email = models.EmailField(verbose_name="email", max_length=60, unique=True) username = models.CharField(max_length=30, unique=True) date_joined = models.DateTimeField(verbose_name='date joined', auto_now_add=True) last_login = models.DateTimeField(verbose_name='last login', auto_now=True) is_admin = models.BooleanField(default=False) is_active = models.BooleanField(default=True) is_staff = models.BooleanField(default=False) is_superuser = models.BooleanField(default=False) USERNAME_FIELD = 'email' REQUIRED_FIELDS = ['username'] objects = MyAccountManager() def __str__(self): return self.email # For checking permissions. to keep it simple all admin have ALL permissons def has_perm(self, perm, obj=None): return self.is_admin # Does this user have permission to view this app? (ALWAYS YES FOR SIMPLICITY) def has_module_perms(self, app_label): return True
21064aaea82657175bb68471f1411164393e0210
657c80336bce1cc6158cd349ce208c5e680a4d0d
/contrib/projection/tests/projection/base_projection.py
de53d6895412de112d31a959926d9cdb47b6ef9c
[ "BSD-3-Clause" ]
permissive
Xinmudotmoe/pyglet
b37628618647bf3b1e3d7db28202a5e14c60450c
144257c365ca85528c6a4c5bed8141e683d7a9b6
refs/heads/master
2021-05-29T22:05:40.676643
2015-10-24T05:55:49
2015-10-24T05:55:49
null
0
0
null
null
null
null
UTF-8
Python
false
false
429
py
#!/usr/bin/python # $Id:$ from pyglet.gl import * def fillrect(x, y, width, height): glBegin(GL_QUADS) glVertex2f(x, y) glVertex2f(x + width, y) glVertex2f(x + width, y + height) glVertex2f(x, y + height) glEnd() def rect(x, y, width, height): glBegin(GL_LINE_LOOP) glVertex2f(x, y) glVertex2f(x + width, y) glVertex2f(x + width, y + height) glVertex2f(x, y + height) glEnd()
d811f5d03ae12bdeb567632e2d82b3ecccc87751
a1e3e7cf1d27b85d9472c6353e7646d37528b241
/q11.py
3ea7528239387d3ae6df885be655e4e6ebe1b32f
[]
no_license
osama1998H/standerdLearnd-string
421148f81c2c604f6c75dac568ff1faeb20922ce
0af39cd2fd43be45bb54aca2826bc8bf56e399ed
refs/heads/main
2023-09-01T04:21:52.499680
2021-05-15T19:54:50
2021-05-15T19:54:50
365,533,408
0
0
null
2023-08-29T08:31:40
2021-05-08T14:21:53
Python
UTF-8
Python
false
false
325
py
string = input("enter the string: ") def del_odd(string: str)->str: new_string = "" string = [i for i in string] for i in string: if string.index(i) % 2 != 0: string.remove(i) for i in string: new_string += i return new_string new_string = del_odd(string) print(new_string)
da3f5d0d4b3c71ac3db45cece6411a3233f8b68a
f576f0ea3725d54bd2551883901b25b863fe6688
/sdk/webpubsub/azure-mgmt-webpubsub/generated_samples/web_pub_sub_replicas_create_or_update.py
81ff6144e4226d349866642540011deb03744386
[ "LicenseRef-scancode-generic-cla", "MIT", "LGPL-2.1-or-later" ]
permissive
Azure/azure-sdk-for-python
02e3838e53a33d8ba27e9bcc22bd84e790e4ca7c
c2ca191e736bb06bfbbbc9493e8325763ba990bb
refs/heads/main
2023-09-06T09:30:13.135012
2023-09-06T01:08:06
2023-09-06T01:08:06
4,127,088
4,046
2,755
MIT
2023-09-14T21:48:49
2012-04-24T16:46:12
Python
UTF-8
Python
false
false
1,920
py
# coding=utf-8 # -------------------------------------------------------------------------- # Copyright (c) Microsoft Corporation. All rights reserved. # Licensed under the MIT License. See License.txt in the project root for license information. # Code generated by Microsoft (R) AutoRest Code Generator. # Changes may cause incorrect behavior and will be lost if the code is regenerated. # -------------------------------------------------------------------------- from azure.identity import DefaultAzureCredential from azure.mgmt.webpubsub import WebPubSubManagementClient """ # PREREQUISITES pip install azure-identity pip install azure-mgmt-webpubsub # USAGE python web_pub_sub_replicas_create_or_update.py Before run the sample, please set the values of the client ID, tenant ID and client secret of the AAD application as environment variables: AZURE_CLIENT_ID, AZURE_TENANT_ID, AZURE_CLIENT_SECRET. For more info about how to get the value, please see: https://docs.microsoft.com/azure/active-directory/develop/howto-create-service-principal-portal """ def main(): client = WebPubSubManagementClient( credential=DefaultAzureCredential(), subscription_id="00000000-0000-0000-0000-000000000000", ) response = client.web_pub_sub_replicas.begin_create_or_update( resource_group_name="myResourceGroup", resource_name="myWebPubSubService", replica_name="myWebPubSubService-eastus", parameters={ "location": "eastus", "properties": {}, "sku": {"capacity": 1, "name": "Premium_P1", "tier": "Premium"}, "tags": {"key1": "value1"}, }, ).result() print(response) # x-ms-original-file: specification/webpubsub/resource-manager/Microsoft.SignalRService/preview/2023-06-01-preview/examples/WebPubSubReplicas_CreateOrUpdate.json if __name__ == "__main__": main()
1dbfcc3d47f3a48af022c5b19fdcc27352f4d401
d2b54d3df1dc8f7e88c0d209b35949089facc73f
/treenode/memory.py
b5c7ddd2c1dd51260daf32b36666209d52ca2176
[ "MIT" ]
permissive
domlysi/django-treenode
df8b08e756884bc8daffdfad7b5b3b102e92e309
86e7c76e2b2d60c071cfce6ad1493b2b51f2d304
refs/heads/master
2022-12-12T18:10:44.668904
2020-08-17T11:01:09
2020-08-17T11:01:09
287,275,877
0
0
MIT
2020-08-13T12:37:54
2020-08-13T12:37:54
null
UTF-8
Python
false
false
522
py
# -*- coding: utf-8 -*- from collections import defaultdict import weakref __refs__ = defaultdict(weakref.WeakSet) def clear_refs(cls): __refs__[cls].clear() def get_refs(cls): return __refs__[cls] def set_ref(cls, obj): if obj.pk: __refs__[cls].add(obj) def update_refs(cls, data): for obj in get_refs(cls): obj_key = str(obj.pk) obj_data = data.get(obj_key) if obj_data: for key, value in obj_data.items(): setattr(obj, key, value)
925028b08297779546c047873b5ba67c870ad692
15f321878face2af9317363c5f6de1e5ddd9b749
/solutions_python/Problem_55/59.py
09da2bcfaa4c411daa5449e6b502ef93033a8f6c
[]
no_license
dr-dos-ok/Code_Jam_Webscraper
c06fd59870842664cd79c41eb460a09553e1c80a
26a35bf114a3aa30fc4c677ef069d95f41665cc0
refs/heads/master
2020-04-06T08:17:40.938460
2018-10-14T10:12:47
2018-10-14T10:12:47
null
0
0
null
null
null
null
UTF-8
Python
false
false
1,319
py
#!/usr/bin/env python import sys filename=sys.argv[1] inputfile=file(filename, 'r') numcases=int(inputfile.readline().strip()) for case in range(1,numcases+1): R, k, N = map(long, inputfile.readline().strip().split()) g = map(long, inputfile.readline().strip().split()) y = 0 first_ride = [None] * N ride_groups = [None] * N ride_seats = [None] * N ride = 0 start = 0 while ride < R: if first_ride[start] is not None: break ridestart = start seats = 0 groups = 0 while seats + g[start] <= k and groups < N: seats += g[start] groups += 1 start += 1 if start >= N: start = 0 if start == ridestart: break first_ride[ridestart] = ride ride_groups[ridestart] = groups ride_seats[ridestart] = seats ride += 1 y += seats if ride < R: cyclelen = ride - first_ride[start] if R - ride >= cyclelen: cycles = (R - ride) / cyclelen cycle_euros = 0 cycle_start = start while True: cycle_euros += ride_seats[start] start = (start + ride_groups[start]) % N ride += 1 if start == cycle_start: break y += cycle_euros * cycles ride += (cycles - 1) * cyclelen while ride < R: y += ride_seats[start] start = (start + ride_groups[start]) % N ride += 1 print "Case #%d: %d" % (case, y)
eeb5073afecbaf0f35097a0d4970f139fc0282fd
014e9a6f3d48ffa7b9ee759904d2e33284a6f4d6
/api/caoloapi/model/auth.py
c73941f6992e52e8c9728cbae96791221e95e3a7
[ "MIT" ]
permissive
kissmikijr/caolo-backend
33c0262239182b96d1215677c45065b4ef90455b
efec05bb793bd40951cb4e5ae4e930d972f63d36
refs/heads/master
2023-09-04T01:09:50.068148
2021-10-18T22:00:59
2021-10-18T22:06:01
null
0
0
null
null
null
null
UTF-8
Python
false
false
1,079
py
from datetime import datetime as dt, timedelta from passlib.context import CryptContext from jose import jwt SECRET_KEY = "fe9fb923daa2a5c34a57b6da5d807a1e9cb48d4afee5c10095bab37bcf860059" ALGORITHM = "HS256" ACCESS_TOKEN_EXPIRE_MINUTES = 30 PEPPER_RANGE = (128, 139, 3) pwd_context = CryptContext(schemes=["bcrypt"], deprecated="auto") def __concatpw(pw: str, salt: str, pepper): return f"{pw}{salt}{pepper}" def verifypw(plain, salt, pepper, hashed_pw): pw = __concatpw(plain, salt, pepper) return pwd_context.verify(pw, hashed_pw) def hashpw(pw: str, salt: str, pepper): return pwd_context.hash(__concatpw(pw, salt, pepper)) def create_access_token(data: dict): payload = data.copy() payload.update({"exp": dt.utcnow() + timedelta(minutes=15)}) return jwt.encode(payload, SECRET_KEY, algorithm=ALGORITHM) def decode_access_token(token: str): """ raises jose.JWTError or AssertionError on invalid token """ payload = jwt.decode(token, SECRET_KEY, algorithms=[ALGORITHM]) assert "sub" in payload return payload
3e1738529ae55e62ae6843901eca2eb0d436e07a
6189f34eff2831e3e727cd7c5e43bc5b591adffc
/WebMirror/management/rss_parser_funcs/feed_parse_extractIntheinkpotfictionWordpressCom.py
5a22827f09f4623da612321d5379b4873ab2b614
[ "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
576
py
def extractIntheinkpotfictionWordpressCom(item): ''' Parser for 'intheinkpotfiction.wordpress.com' ''' vol, chp, frag, postfix = extractVolChapterFragmentPostfix(item['title']) if not (chp or vol) or "preview" in item['title'].lower(): return None tagmap = [ ('PRC', 'PRC', 'translated'), ('Loiterous', 'Loiterous', 'oel'), ] for tagname, name, tl_type in tagmap: if tagname in item['tags']: return buildReleaseMessageWithType(item, name, vol, chp, frag=frag, postfix=postfix, tl_type=tl_type) return False
15487621d75896236eb3ebe106a4f8748a6a389b
e43b78db4ff598944e58e593610f537f3833d79c
/py-faster-rcnn/lib/roi_data_layer/roidb.py
93f713e1f127d432736a654ce6fa292eef3b6c67
[ "MIT", "LicenseRef-scancode-generic-cla", "BSD-2-Clause" ]
permissive
ZJUZQ/Net_caffe
577e9b3e80a391d772a21c27639465d539fceb1f
bed3c7384a259339c5a0fb2ea34fa0cdd32ddd29
refs/heads/master
2021-09-08T12:19:37.039970
2018-03-09T14:44:24
2018-03-09T14:44:24
114,853,721
4
1
null
null
null
null
UTF-8
Python
false
false
6,356
py
# -------------------------------------------------------- # Fast R-CNN # Copyright (c) 2015 Microsoft # Licensed under The MIT License [see LICENSE for details] # Written by Ross Girshick # -------------------------------------------------------- """Transform a roidb into a trainable roidb by adding a bunch of metadata.""" import numpy as np from fast_rcnn.config import cfg from fast_rcnn.bbox_transform import bbox_transform from utils.cython_bbox import bbox_overlaps import PIL def prepare_roidb(imdb): """Enrich the imdb's roidb by adding some derived quantities that are useful for training. This function precomputes the maximum overlap, taken over ground-truth boxes, between each ROI and each ground-truth box. The class with maximum overlap is also recorded. """ sizes = [PIL.Image.open(imdb.image_path_at(i)).size for i in xrange(imdb.num_images)] roidb = imdb.roidb # roidb is a list of dictionaries, each with the following keys: # boxes # gt_overlaps # gt_classes # flipped for i in xrange(len(imdb.image_index)): roidb[i]['image'] = imdb.image_path_at(i) roidb[i]['width'] = sizes[i][0] roidb[i]['height'] = sizes[i][1] # need gt_overlaps as a dense array for argmax gt_overlaps = roidb[i]['gt_overlaps'].toarray() # max overlap with gt over classes (columns) max_overlaps = gt_overlaps.max(axis=1) # gt class that had the max overlap max_classes = gt_overlaps.argmax(axis=1) roidb[i]['max_classes'] = max_classes ## gt class that had the max overlap (columns) roidb[i]['max_overlaps'] = max_overlaps ## max overlap with gt over classes (columns) # sanity checks # max overlap of 0 => class should be zero (background) zero_inds = np.where(max_overlaps == 0)[0] assert all(max_classes[zero_inds] == 0) # max overlap > 0 => class should not be zero (must be a fg class) nonzero_inds = np.where(max_overlaps > 0)[0] assert all(max_classes[nonzero_inds] != 0) def add_bbox_regression_targets(roidb): """Add information needed to train bounding-box regressors.""" assert len(roidb) > 0 assert 'max_classes' in roidb[0], 'Did you call prepare_roidb first?' num_images = len(roidb) # Infer number of classes from the number of columns in gt_overlaps num_classes = roidb[0]['gt_overlaps'].shape[1] for im_i in xrange(num_images): rois = roidb[im_i]['boxes'] max_overlaps = roidb[im_i]['max_overlaps'] max_classes = roidb[im_i]['max_classes'] roidb[im_i]['bbox_targets'] = \ _compute_targets(rois, overlaps=max_overlaps, labels=max_classes) # Compute bounding-box regression targets for an image if cfg.TRAIN.BBOX_NORMALIZE_TARGETS_PRECOMPUTED: ## RPN can only use precomputed normalization because there are no fixed statistics to compute a priori # Use fixed / precomputed "means" and "stds" instead of empirical values means = np.tile( np.array(cfg.TRAIN.BBOX_NORMALIZE_MEANS), (num_classes, 1)) # shape = (num_classes, 4) stds = np.tile( np.array(cfg.TRAIN.BBOX_NORMALIZE_STDS), (num_classes, 1)) # shape = (num_classes, 4) else: # Compute values needed for means and stds # var(x) = E(x^2) - E(x)^2 class_counts = np.zeros((num_classes, 1)) + cfg.EPS sums = np.zeros((num_classes, 4)) squared_sums = np.zeros((num_classes, 4)) for im_i in xrange(num_images): targets = roidb[im_i]['bbox_targets'] for cls in xrange(1, num_classes): cls_inds = np.where(targets[:, 0] == cls)[0] if cls_inds.size > 0: class_counts[cls] += cls_inds.size sums[cls, :] += targets[cls_inds, 1:].sum(axis=0) squared_sums[cls, :] += \ (targets[cls_inds, 1:] ** 2).sum(axis=0) means = sums / class_counts stds = np.sqrt(squared_sums / class_counts - means ** 2) print 'bbox target means:' print means print means[1:, :].mean(axis=0) # ignore bg class print 'bbox target stdevs:' print stds print stds[1:, :].mean(axis=0) # ignore bg class # Normalize targets if cfg.TRAIN.BBOX_NORMALIZE_TARGETS: print "Normalizing targets" for im_i in xrange(num_images): targets = roidb[im_i]['bbox_targets'] for cls in xrange(1, num_classes): cls_inds = np.where(targets[:, 0] == cls)[0] roidb[im_i]['bbox_targets'][cls_inds, 1:] -= means[cls, :] roidb[im_i]['bbox_targets'][cls_inds, 1:] /= stds[cls, :] else: print "NOT normalizing targets" # These values will be needed for making predictions # (the predicts will need to be unnormalized and uncentered) return means.ravel(), stds.ravel() ## Return a contiguous flattened array def _compute_targets(rois, overlaps, labels): """Compute bounding-box regression targets for an image.""" """ overlaps: max_overlaps of rois labels: max_classes of rois return: [[cls, dx, dy, dw, dh] ... ] """ # Indices of ground-truth ROIs gt_inds = np.where(overlaps == 1)[0] if len(gt_inds) == 0: # Fail if the image has no ground-truth ROIs return np.zeros((rois.shape[0], 5), dtype=np.float32) # Indices of examples for which we try to make predictions ex_inds = np.where(overlaps >= cfg.TRAIN.BBOX_THRESH)[0] ## e.g., 0.5 # Get IoU overlap between each ex ROI and gt ROI ex_gt_overlaps = bbox_overlaps( np.ascontiguousarray(rois[ex_inds, :], dtype=np.float), np.ascontiguousarray(rois[gt_inds, :], dtype=np.float)) # Find which gt ROI each ex ROI has max overlap with: # this will be the ex ROI's gt target gt_assignment = ex_gt_overlaps.argmax(axis=1) gt_rois = rois[gt_inds[gt_assignment], :] ex_rois = rois[ex_inds, :] targets = np.zeros((rois.shape[0], 5), dtype=np.float32) targets[ex_inds, 0] = labels[ex_inds] targets[ex_inds, 1:] = bbox_transform(ex_rois, gt_rois) # compute [dx, dy, dw, dh] return targets
ad73927538d2a6b51e3e9da4eaa96818ced5e08a
f714db4463dd37fc33382364dc4b1963a9053e49
/tests/sentry/event_manager/interfaces/test_frame.py
22dd3b8b5756050429bafb0bd12c3db6daa422ae
[ "BUSL-1.1", "Apache-2.0" ]
permissive
macher91/sentry
92171c2ad23564bf52627fcd711855685b138cbd
dd94d574403c95eaea6d4ccf93526577f3d9261b
refs/heads/master
2021-07-07T08:23:53.339912
2020-07-21T08:03:55
2020-07-21T08:03:55
140,079,930
0
0
BSD-3-Clause
2020-05-13T11:28:35
2018-07-07T11:50:48
Python
UTF-8
Python
false
false
1,366
py
# -*- coding: utf-8 -*- from __future__ import absolute_import import pytest from sentry import eventstore from sentry.event_manager import EventManager @pytest.fixture def make_frames_snapshot(insta_snapshot): def inner(data): mgr = EventManager(data={"stacktrace": {"frames": [data]}}) mgr.normalize() evt = eventstore.create_event(data=mgr.get_data()) frame = evt.interfaces["stacktrace"].frames[0] insta_snapshot({"errors": evt.data.get("errors"), "to_json": frame.to_json()}) return inner @pytest.mark.parametrize( "input", [ {"filename": 1}, {"filename": "foo", "abs_path": 1}, {"function": 1}, {"module": 1}, {"function": "?"}, ], ) def test_bad_input(make_frames_snapshot, input): make_frames_snapshot(input) @pytest.mark.parametrize( "x", [float("inf"), float("-inf"), float("nan")], ids=["inf", "neginf", "nan"] ) def test_context_with_nan(make_frames_snapshot, x): make_frames_snapshot({"filename": "x", "vars": {"x": x}}) def test_address_normalization(make_frames_snapshot): make_frames_snapshot( { "lineno": 1, "filename": "blah.c", "function": "main", "instruction_addr": 123456, "symbol_addr": "123450", "image_addr": "0x0", } )
e259df553081c2a0843857a31971fbeb29ab02d1
8c9df3465ec7cab68b10e67823c1f9b475dab68e
/square__transverse_longitudinal_field_af_ising__static/square_ising.py
12dad1d1699c6934cd3da33fb9d3ea8f37bdd5f5
[ "BSD-3-Clause" ]
permissive
deyh2020/quspin_example
f86cf3cea2b8c04efc017e9618cb935494e94f82
931ca2ea5e6bbe02ebdd6d6a22d90db24d6c760c
refs/heads/master
2023-02-07T21:27:12.913763
2020-12-30T08:00:57
2020-12-30T08:00:57
null
0
0
null
null
null
null
UTF-8
Python
false
false
3,427
py
## http://weinbe58.github.io/QuSpin/generated/quspin.basis.spin_basis_general.html#quspin.basis.spin_basis_general ## https://doi.org/10.1103/PhysRevX.8.021069 ## https://doi.org/10.1103/PhysRevX.8.021070 ## consider nearest neighbor Ising from __future__ import print_function, division from quspin.operators import hamiltonian # operators from quspin.basis import spin_basis_general # spin basis constructor import numpy as np # general math functions def exact_diag(J,Hx,Hz,Lx,Ly): N_2d = Lx*Ly # number of sites ###### setting up user-defined symmetry transformations for 2d lattice ###### s = np.arange(N_2d) # sites [0,1,2,....] x = s%Lx # x positions for sites y = s//Lx # y positions for sites T_x = (x+1)%Lx + Lx*y # translation along x-direction T_y = x +Lx*((y+1)%Ly) # translation along y-direction P_x = x + Lx*(Ly-y-1) # reflection about x-axis P_y = (Lx-x-1) + Lx*y # reflection about y-axis Z = -(s+1) # spin inversion ###### setting up bases ###### # basis_2d = spin_basis_general(N=N_2d,S="1/2",pauli=0) basis_2d = spin_basis_general(N=N_2d,S="1/2",pauli=0,kxblock=(T_x,0),kyblock=(T_y,0)) ###### setting up hamiltonian ###### # setting up site-coupling lists Jzzs = [[J,i,T_x[i]] for i in range(N_2d)]+[[J,i,T_y[i]] for i in range(N_2d)] Hxs = [[-Hx,i] for i in range(N_2d)] Hzs = [[-Hz,i] for i in range(N_2d)] static = [["zz",Jzzs],["x",Hxs],["z",Hzs]] # build hamiltonian # H = hamiltonian(static,[],static_fmt="csr",basis=basis_2d,dtype=np.float64) no_checks = dict(check_symm=False, check_pcon=False, check_herm=False) H = hamiltonian(static,[],static_fmt="csr",basis=basis_2d,dtype=np.float64,**no_checks) # diagonalise H ene,vec = H.eigsh(time=0.0,which="SA",k=2) # ene = H.eigsh(time=0.0,which="SA",k=2,return_eigenvectors=False); ene = np.sort(ene) norm2 = np.linalg.norm(vec[:,0])**2 # calculate uniform magnetization int_mx = [[1.0,i] for i in range(N_2d)] int_mz = [[1.0,i] for i in range(N_2d)] static_mx = [["x",int_mx]] static_mz = [["z",int_mz]] op_mx = hamiltonian(static_mx,[],static_fmt="csr",basis=basis_2d,dtype=np.float64,**no_checks).tocsr(time=0) op_mz = hamiltonian(static_mz,[],static_fmt="csr",basis=basis_2d,dtype=np.float64,**no_checks).tocsr(time=0) mx = (np.conjugate(vec[:,0]).dot(op_mx.dot(vec[:,0])) / norm2).real / N_2d mz = (np.conjugate(vec[:,0]).dot(op_mz.dot(vec[:,0])) / norm2).real / N_2d # calculate n.n. sz.sz correlation int_mz0mz1 = [[1.0,i,T_x[i]] for i in range(N_2d)]+[[1.0,i,T_y[i]] for i in range(N_2d)] static_mz0mz1 = [["zz",int_mz0mz1]] op_mz0mz1 = hamiltonian(static_mz0mz1,[],static_fmt="csr",basis=basis_2d,dtype=np.float64,**no_checks).tocsr(time=0) mz0mz1 = (np.conjugate(vec[:,0]).dot(op_mz0mz1.dot(vec[:,0])) / norm2).real / N_2d return ene, mx, mz, mz0mz1 def main(): ###### define model parameters ###### Lx, Ly = 4, 4 # linear dimension of 2d lattice N_2d = Lx*Ly # number of sites J = 1.0 # AF Ising # Hz = 2.00 # longitudinal field Hzs = np.linspace(0.0,4.0,401) # Hzs = np.linspace(1.99,2.03,41) Hx = 0.10 # transverse field for Hz in Hzs: ene, mx, mz, mz0mz1 = exact_diag(J,Hx,Hz,Lx,Ly) # print(J,Hz,Hx,Lx,Ly,ene[0]/N_2d,ene[1]/N_2d) print(J,Hz,Hx,Lx,Ly,ene[0]/N_2d,mx,mz,mz0mz1) if __name__ == "__main__": main()
7534fdc5e9d0e271082d603c5c0a1ba2262d679e
873d858b79a51a6a14e74e1a6fe4cc97809a69bc
/rosserial_ws/devel/lib/rosserial_client/make_library.py
eed0f221f32c99f4c790655eeb0d5132d20cacf2
[]
no_license
nichoteloo/ROS-Noetic-devel
cf3058014fc491f38a23426c136cb8fbdee7a397
81e7090c5dc0e548aed4aa57b9579e355e9bcd25
refs/heads/master
2023-05-07T19:21:03.804523
2021-06-02T21:13:48
2021-06-02T21:13:48
373,293,635
0
0
null
null
null
null
UTF-8
Python
false
false
597
py
#!/usr/bin/python3 # -*- coding: utf-8 -*- # generated from catkin/cmake/template/script.py.in # creates a relay to a python script source file, acting as that file. # The purpose is that of a symlink python_script = '/home/nichotelo/ros/rosserial_ws/src/rosserial/rosserial_client/src/rosserial_client/make_library.py' with open(python_script, 'r') as fh: context = { '__builtins__': __builtins__, '__doc__': None, '__file__': python_script, '__name__': __name__, '__package__': None, } exec(compile(fh.read(), python_script, 'exec'), context)
dde7d82754424f14d0b28a6142c13333535560f6
e3adbec6cd8d0b50880b3b606352a1c751d4ac79
/functions/singly_linked_list.py
7cadf3954044adea1f9fcd0cccd0b5268d96d8b1
[]
no_license
ZiyaoGeng/LeetCode
3cc5b553df5eac2e5bbb3ccd0f0ed4229574fa2f
c4c60b289c0bd9d9f228d04abe948d6287e70ea8
refs/heads/master
2022-04-07T08:19:58.647408
2020-03-12T08:56:13
2020-03-12T08:56:13
218,981,503
1
0
null
null
null
null
UTF-8
Python
false
false
211
py
# Definition for singly-linked list. # class ListNode: # def __init__(self, x): # self.val = x # self.next = None class ListNode: def __init__(self, x): self.val = x self.next = None
811e650b58eaf4337be5d070b3152062620dfaa4
1d1a21b37e1591c5b825299de338d18917715fec
/Mathematics/Data science/Mathmatics/02/inverse_matrix.py
5531c0cc7924c0fa9e1eb9313e95e425439086b8
[]
no_license
brunoleej/study_git
46279c3521f090ebf63ee0e1852aa0b6bed11b01
0c5c9e490140144caf1149e2e1d9fe5f68cf6294
refs/heads/main
2023-08-19T01:07:42.236110
2021-08-29T16:20:59
2021-08-29T16:20:59
null
0
0
null
null
null
null
UTF-8
Python
false
false
249
py
import numpy as np A = np.array([[1,1,0],[0,1,1],[1,1,1]]) print(A) ''' [[1 1 0] [0 1 1] [1 1 1]] ''' # 역행렬(inverse_matrix 계산) Ainv = np.linalg.inv(A) print(Ainv) ''' [[ 0. -1. 1.] [ 1. 1. -1.] [-1. 0. 1.]] '''
f327af434bdb44b8db26624273fa576fedb584a9
371fe9a1fdeb62ad1142b34d732bde06f3ce21a0
/scripts/compute_path_pair_distances.py
32499ed5d2cd2871d18a77acc24343b70b16f798
[]
no_license
maickrau/rdna_resolution
971f3b7e803565c9432be69b8e2a2852f55b8b79
aab42310c31e655cbbc318331082fa3436d69075
refs/heads/master
2023-03-03T05:14:33.966930
2021-02-17T20:45:20
2021-02-17T20:45:20
339,851,442
0
0
null
null
null
null
UTF-8
Python
false
false
6,426
py
#!/usr/bin/python import sys graphfile = sys.argv[1] max_diff = int(sys.argv[2]) modulo = int(sys.argv[3]) moduloindex = int(sys.argv[4]) # name \t path from stdin def revcomp(s): comp = {'A': 'T', 'T': 'A', 'C': 'G', 'G': 'C'} return "".join(comp[c] for c in s[::-1]) def pathseq(p): global nodeseqs seq_no_hpc = "".join(nodeseqs[n[1:]] if n[0] == '>' else revcomp(nodeseqs[n[1:]]) for n in p) # seq_hpc = seq_no_hpc[0] # for i in range(1, len(seq_no_hpc)): # if seq_no_hpc[i] != seq_no_hpc[i-1]: seq_hpc += seq_no_hpc[i] # return seq_hpc return seq_no_hpc def edit_distance_simple(p1, p2): global max_diff if len(p1) - len(p2) <= -max_diff or len(p1) - len(p2) >= max_diff: return None last_row = [] for i in range(0, len(p2)+1): last_row.append(i) for i in range(1, len(p1)): next_row = [i] min_this_row = i for j in range(0, len(p2)): index = len(next_row) next_row.append(min(next_row[index-1]+1, last_row[index]+1)) if p1[i] == p2[j]: next_row[index] = min(next_row[index], last_row[index-1]) else: next_row[index] = min(next_row[index], last_row[index-1]+1) min_this_row = min(min_this_row, next_row[index]) last_row = next_row # if min_this_row >= max_diff: return None return last_row[-1] def edit_distance_wfa(p1, p2): global max_diff # use wfa because new and fancy # https://academic.oup.com/bioinformatics/advance-article/doi/10.1093/bioinformatics/btaa777/5904262?rss=1 if len(p1) - len(p2) < -max_diff or len(p1) - len(p2) > max_diff: return None start_match = -1 while start_match+1 < len(p1) and start_match+1 < len(p2) and p1[start_match+1] == p2[start_match+1]: start_match += 1 if start_match == len(p1) and start_match == len(p2): return 0 last_column = [start_match] # sys.stderr.write("0" + "\n") for i in range(1, max_diff): offset = i-1 # sys.stderr.write(str(i) + "\n") next_column = [] last_match =last_column[-i+offset+1] while last_match+1-i < len(p1) and last_match+1 < len(p2) and p1[last_match+1-i] == p2[last_match+1]: last_match += 1 if last_match+1-i >= len(p1) and last_match+1 >= len(p2): return i next_column.append(last_match) for j in range(-i+1, +i): last_match = last_column[j+offset]+1 if j > -i+1: last_match = max(last_match, last_column[j+offset-1]-1) if j < i-1: last_match = max(last_match, last_column[j+offset+1]) while last_match+1+j < len(p1) and last_match+1 < len(p2) and p1[last_match+1+j] == p2[last_match+1]: last_match += 1 if last_match+1+j >= len(p1) and last_match+1 >= len(p2): return i next_column.append(last_match) last_match = last_column[i+offset-1]-1 while last_match+1+i < len(p1) and last_match+1 < len(p2) and p1[last_match+1+i] == p2[last_match+1]: last_match += 1 if last_match+1+i >= len(p1) and last_match+1 >= len(p2): return i next_column.append(last_match) last_column = next_column return None def edit_distance(p1, p2): global max_diff # use wfa because new and fancy # https://academic.oup.com/bioinformatics/advance-article/doi/10.1093/bioinformatics/btaa777/5904262?rss=1 if len(p1) - len(p2) < -max_diff or len(p1) - len(p2) > max_diff: return None start_match = -1 while start_match+1 < len(p1) and start_match+1 < len(p2) and p1[start_match+1] == p2[start_match+1]: start_match += 1 if start_match == len(p1) and start_match == len(p2): return 0 last_column = {0: start_match} for i in range(1, max_diff): offset = i-1 next_column = {} for column in last_column: if column not in next_column: next_column[column] = 0 next_column[column] = max(next_column[column], last_column[column]+1) if column+1 not in next_column: next_column[column+1] = 0 next_column[column+1] = max(next_column[column+1], last_column[column]) if column-1 not in next_column: next_column[column-1] = 0 next_column[column-1] = max(next_column[column-1], last_column[column]-1) p1_pos = last_column[column] p2_pos = last_column[column] + column if p1_pos >= 4 and p2_pos >= 4: if p1[p1_pos-4:p1_pos] == p2[p2_pos-4:p2_pos] and p1[p1_pos-4:p1_pos-2] == p1[p1_pos-2:p1_pos]: if p1_pos+2 <= len(p1) and p1[p1_pos:p1_pos+2] == p1[p1_pos-2:p1_pos]: extend_until = 0 while True: if column-extend_until not in next_column: next_column[column-extend_until] = 0 next_column[column-extend_until] = max(next_column[column-extend_until], last_column[column]+extend_until) if p1_pos+extend_until+2 <= len(p1) and p1[p1_pos+extend_until:p1_pos+extend_until+2] == p1[p1_pos-2:p1_pos]: extend_until += 2 else: break if p2_pos+2 <= len(p2) and p2[p2_pos:p2_pos+2] == p2[p2_pos-2:p2_pos]: extend_until = 0 while True: if column+extend_until+2 not in next_column: next_column[column+extend_until+2] = 0 next_column[column+extend_until+2] = max(next_column[column+extend_until+2], last_column[column]) if p2_pos+extend_until+2 <= len(p2) and p2[p2_pos+extend_until:p2_pos+extend_until+2] == p2[p2_pos-2:p2_pos]: extend_until += 2 else: break for column in next_column: p1_pos = next_column[column] p2_pos = next_column[column] + column while p1_pos+1 < len(p1) and p2_pos+1 < len(p2) and p1[p1_pos+1] == p2[p2_pos+1]: next_column[column] += 1 p1_pos += 1 p2_pos += 1 if p1_pos+1 >= len(p1) and p2_pos+1 >= len(p2): return i last_column = next_column return None nodeseqs = {} with open(graphfile) as f: for l in f: parts = l.strip().split('\t') if parts[0] == 'S': nodeseqs[parts[1]] = parts[2] num = 0 pathnum = {} paths = {} for l in sys.stdin: parts = l.strip().split('\t') name = parts[0] last_break = 0 path = [] pathstr = parts[1] + '>' for i in range(1, len(pathstr)): if pathstr[i] == '<' or pathstr[i] == '>': path.append(pathstr[last_break:i]) last_break = i if name in paths: print(name) assert name not in paths paths[name] = pathseq(path) pathnum[name] = num num += 1 # print(name + "\t" + paths[name]) for path1 in paths: if pathnum[path1] % modulo != moduloindex: continue for path2 in paths: if path1 <= path2: continue value = max_diff + 1 edit_dist = edit_distance(paths[path1], paths[path2]) # edit_dist = edit_distance_simple(paths[path1], paths[path2]) if edit_dist is None: continue if edit_dist is not None: value = edit_dist print(path1 + "\t" + path2 + "\t" + str(value))
598aa5789fc89d20614a949df27117f073692147
b2c780661aec8076a0b6d00bf8ea0d443a117df6
/Popularity/DCAFPilot/test/utils_t.py
b5af29934995578af40c4def334385a5c2d302eb
[]
no_license
maitdaoud/DMWMAnalytics
894fa2afb8d83a5275f0abd61b74f4f839150cb0
fec7ef3e5240973db96ba53179940950002adbd8
refs/heads/master
2020-04-11T03:33:43.164136
2017-04-01T14:07:42
2017-04-01T14:07:42
null
0
0
null
null
null
null
UTF-8
Python
false
false
975
py
#!/usr/bin/env python #pylint: disable-msg=C0301,C0103 """ Unit test for StorageManager class """ import os import re import time import unittest from pymongo import MongoClient from DCAF.utils.utils import popdb_date, ndays class testStorageManager(unittest.TestCase): """ A test class for the StorageManager class """ def setUp(self): "set up connection" pass def tearDown(self): "Perform clean-up" pass def test_popdb_date(self): "Test popdb_date method" result = popdb_date('20140105') expect = '2014-1-5' self.assertEqual(expect, result) result = popdb_date(expect) self.assertEqual(expect, result) def test_ndays(self): "Test ndays function" time1, time2 = '20141120', '20141124' result = ndays(time1, time2) expect = 4 self.assertEqual(expect, result) # # main # if __name__ == '__main__': unittest.main()
3c699961c03db0286e4b397de0a722d189504754
30e2a85fc560165a16813b0486a862317c7a486a
/datastruct_algorithm/jan.py
bb5cbcfb654440320b08cce91cc4251879eb8dfd
[]
no_license
muryliang/python_prac
2f65b6fdb86c3b3a44f0c6452a154cd497eb2d01
0301e8f523a2e31e417fd99a968ad8414e9a1e08
refs/heads/master
2021-01-21T11:03:48.397178
2017-09-18T04:13:27
2017-09-18T04:13:27
68,801,688
1
0
null
null
null
null
UTF-8
Python
false
false
2,328
py
import time import sys def perform(a, b, goal, failset, trueset): """a is limaL, b is limbL, failset is a list failseting action""" # time.sleep(1) # print(a, b) global lima global limb res = False if a == goal or b == goal or a + b == goal: return True if res is False and a > 0 and b < limb: ares = max(a - (limb-b), 0) bres = min(limb, b + a) if (ares , bres) not in failset: failset.append((ares, bres) ) res = perform(ares, bres, goal, failset, trueset) if res: trueset.append("rmove") if res is False and b > 0 and a < lima: ares = min(lima, a + b) bres = max(b - (lima-a), 0) if (ares , bres) not in failset: failset.append((ares, bres)) res = perform(ares, bres, goal, failset, trueset) if res: trueset.append("lmove") if res is False and b > 0: ares = a bres = 0 if (ares , bres) not in failset: failset.append((ares, bres)) res = perform(ares, bres, goal, failset, trueset) if res: trueset.append("drop b") if res is False and a > 0: ares = 0 bres = b if (ares , bres) not in failset: failset.append((ares, bres)) res = perform(ares, bres, goal, failset, trueset) if res: trueset.append("drop a") if res is False and a < lima: ares = lima bres = b if (ares , bres) not in failset: failset.append((ares, bres)) res = perform(ares, bres, goal, failset, trueset) if res: trueset.append("fill a") if res is False and b < limb: ares = a bres = limb if (ares , bres) not in failset: failset.append((ares, bres)) res = perform(ares, bres, goal, failset, trueset) if res: trueset.append("fill b") # if res is False: # print ("nothing true, return") return res failset = [(0,0)] trueset = list() lima = int(sys.argv[1]) limb = int(sys.argv[2]) goal = int(sys.argv[3]) if perform(0, 0, goal, failset, trueset): print ("success") else: print ("fail") print (list(reversed(trueset)))
3724941a22eb118782c4c142d7dc6097e8d37e35
ad13583673551857615498b9605d9dcab63bb2c3
/output/instances/nistData/atomic/integer/Schema+Instance/NISTXML-SV-IV-atomic-integer-fractionDigits-1-3.py
32add0c922d5342c7b50eaabb85bc7ee39adc0d0
[ "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
297
py
from output.models.nist_data.atomic.integer.schema_instance.nistschema_sv_iv_atomic_integer_fraction_digits_1_xsd.nistschema_sv_iv_atomic_integer_fraction_digits_1 import NistschemaSvIvAtomicIntegerFractionDigits1 obj = NistschemaSvIvAtomicIntegerFractionDigits1( value=825606520242485152 )
cca9f2e5ed6c7cd9fe744913449f05e61d1ed854
8a47ab47a101d4b44dd056c92a1763d5fac94f75
/力扣/简单练习/300-最长上升子序列.py
edecfbee733ea3c1f051716235583aa67c1a5524
[]
no_license
Clint-cc/Leecode
d5528aa7550a13a5bcf2f3913be2d5db2b5299f3
8befe73ab3eca636944800e0be27c179c45e1dbf
refs/heads/master
2020-09-14T07:35:41.382377
2020-07-01T01:27:18
2020-07-01T01:27:18
223,066,742
0
0
null
null
null
null
UTF-8
Python
false
false
1,663
py
# !D:/Code/python # -*- coding:utf-8 -*- # @Author : Clint # @Question : 给定一个无序的整数数组,找到其中最长上升子序列的长度。 def lengthOfLIS(nums): ''' 思路:遍历数组,当前的下一个元素大于当前,count+1,当不大于时比较count和max_count, 最后输出max_count 这题有坑: 输入[10,9,2,5,3,7,101,18],输出4,解释:最长的上升子序列是 [2,3,7,101],它的长度是 4 :param nums: :return: ''' count = 1 max_count = 1 for i in range(len(nums) - 1): if nums[i + 1] >= nums[i]: count += 1 else: if count > max_count: max_count = count count = 1 else: count = 1 if max_count < count: max_count = count return max_count # 动态规划 def lengthOfLIS(nums): if not nums: return 0 dp = [1] * len(nums) for i in range(len(nums)): for j in range(i): if nums[j] < nums[i]: # 如果要求非严格递增,将此行 '<' 改为 '<=' 即可。 dp[i] = max(dp[i], dp[j] + 1) return max(dp) # 二分查找 def lengthOfLIS(nums): d = [] for n in nums: if not d or n > d[-1]: d.append(n) else: l, r = 0, len(d) - 1 loc = r while l <= r: mid = (l + r) // 2 if d[mid] >= n: loc = mid r = mid - 1 else: l = mid + 1 d[loc] = n return len(d) print(lengthOfLIS([1, 2, 5, 3, 7, 11, 18]))
119da14a29035eb8a5b1c9ba0c64dc7cb316c170
fab39aa4d1317bb43bc11ce39a3bb53295ad92da
/nncf/tensorflow/graph/pattern_operations.py
23435d263c3de7adf57353e47709a005e220e0df
[ "Apache-2.0" ]
permissive
dupeljan/nncf
8cdce27f25f01ce8e611f15e1dc3036fb8548d6e
0abfd7103ca212888a946ba4d0fbdb9d436fdaff
refs/heads/develop
2023-06-22T00:10:46.611884
2021-07-22T10:32:11
2021-07-22T10:32:11
388,719,455
0
0
Apache-2.0
2021-07-23T07:46:15
2021-07-23T07:43:43
null
UTF-8
Python
false
false
3,416
py
""" Copyright (c) 2021 Intel Corporation Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. """ from nncf.common.graph.patterns import merge_two_types_of_operations from nncf.tensorflow.graph.metatypes.common import ELEMENTWISE_LAYER_METATYPES from nncf.tensorflow.graph.metatypes.common import GENERAL_CONV_LAYER_METATYPES from nncf.tensorflow.graph.metatypes.common import LAYER_METATYPES_AGNOSTIC_TO_DATA_PRECISION_WITH_ONE_INPUT from nncf.tensorflow.graph.metatypes.common import LINEAR_LAYER_METATYPES LINEAR_OPERATIONS = {'type': list( { *{layer_name for m in GENERAL_CONV_LAYER_METATYPES for layer_name in m.get_all_aliases()}, *{layer_name for m in LINEAR_LAYER_METATYPES for layer_name in m.get_all_aliases()}, } ), 'label': 'LINEAR' } ELEMENTWISE_OPERATIONS = {'type': list(set( layer_name for m in ELEMENTWISE_LAYER_METATYPES for layer_name in m.get_all_aliases() )), 'label': 'ELEMENTWISE' } QUANTIZATION_AGNOSTIC_OPERATIONS = { 'type': list(set( layer_name for m in LAYER_METATYPES_AGNOSTIC_TO_DATA_PRECISION_WITH_ONE_INPUT for layer_name in m.get_all_aliases() )), 'label': 'ELEMENTWISE' } BATCH_NORMALIZATION_OPERATIONS = {'type': ['BatchNormalization', 'SyncBatchNormalization',], 'label': 'BATCH_NORMALIZATION' } KERAS_ACTIVATIONS_OPERATIONS = { 'type': ['ReLU', 'ThresholdedReLU', 'ELU', 'PReLU', 'LeakyReLU', 'Activation'], 'label': 'KERAS_ACTIVATIONS' } TF_ACTIVATIONS_OPERATIONS = { 'type': ['Relu'], 'label': 'TF_ACTIVATIONS' } ATOMIC_ACTIVATIONS_OPERATIONS = merge_two_types_of_operations(KERAS_ACTIVATIONS_OPERATIONS, TF_ACTIVATIONS_OPERATIONS, 'ATOMIC_ACTIVATIONS') POOLING_OPERATIONS = {'type': ['AveragePooling2D', 'AveragePooling3D', 'GlobalAveragePooling2D', 'GlobalAveragePooling3D'], 'label': 'POOLING'} SINGLE_OPS = merge_two_types_of_operations(POOLING_OPERATIONS, { 'type': [ 'Average', 'LayerNormalization', 'UpSampling2D' ] }, label='SINGLE_OPS') ARITHMETIC_OPERATIONS = {'type': ['__iadd__', '__add__', '__mul__', '__rmul__'], 'label': 'ARITHMETIC'}
d4b3c37168303b568f64ff5fef401bc1cc1264b2
3400394303380c2510b17b95839dd4095abc55a4
/src/py310/lesson02/comments.py
a4dca2ef7c776bd871c81c1adcdd13adb12c2fce
[ "MIT" ]
permissive
IBRAR21/py310_sp2021
daf53b76decf060d72201a3db66f0f7c697876a7
584e37b9d96654c1241fc787d157c292301d5bf7
refs/heads/master
2023-05-30T16:43:09.614565
2021-06-09T21:41:14
2021-06-09T21:41:14
null
0
0
null
null
null
null
UTF-8
Python
false
false
2,828
py
# --------------------------------------------------------------------------------- # # AQUABUTTON wxPython IMPLEMENTATION # # Andrea Gavana, @ 07 October 2008 # Latest Revision: 24 Nov 2011, 22.00 GMT # # # TODO List # # 1) Anything to do? # # # For all kind of problems, requests of enhancements and bug reports, please # write to me at: # # [email protected] # [email protected] # # Or, obviously, to the wxPython mailing list!!! # # # End Of Comments # --------------------------------------------------------------------------------- # """ :class:`AquaButton` is another custom-drawn button class which *approximatively* mimics the behaviour of Aqua buttons on the Mac. Description =========== :class:`AquaButton` is another custom-drawn button class which *approximatively* mimics the behaviour of Aqua buttons on the Mac. At the moment this class supports: * Bubble and shadow effects; * Customizable background, foreground and hover colours; * Rounded-corners buttons; * Text-only or image+text buttons; * Pulse effect on gaining focus. And a lot more. Check the demo for an almost complete review of the functionalities. Usage ===== Sample usage:: import wx import wx.lib.agw.aquabutton as AB app = wx.App(0) frame = wx.Frame(None, -1, "AquaButton Test") mainPanel = wx.Panel(frame) mainPanel.SetBackgroundColour(wx.WHITE) # Initialize AquaButton 1 (with image) bitmap = wx.Bitmap("my_button_bitmap.png", wx.BITMAP_TYPE_PNG) btn1 = AB.AquaButton(mainPanel, -1, bitmap, "AquaButton") # Initialize AquaButton 2 (no image) btn2 = AB.AquaButton(mainPanel, -1, None, "Hello World!") frame.Show() app.MainLoop() Supported Platforms =================== AquaButton has been tested on the following platforms: * Windows (Windows XP); * Linux Ubuntu (10.10). Window Styles ============= `No particular window styles are available for this class.` Events Processing ================= This class processes the following events: ================= ================================================== Event Name Description ================= ================================================== ``wx.EVT_BUTTON`` Process a `wxEVT_COMMAND_BUTTON_CLICKED` event, when the button is clicked. ================= ================================================== License And Version =================== :class:`AquaButton` control is distributed under the wxPython license. Latest Revision: Andrea Gavana @ 22 Nov 2011, 22.00 GMT Version 0.4 """ x = x + 1 # allow for border BORDER = 1 x = x + BORDER def allow_for_border(coordinate): return coordinate + 1 y = allow_for_border(y) def calc(num1, num2): # calc product 2 numbers return num1 + num2 def calculate_product(left, right): return left * right
3b4b65765a6275e2b4fed60d9412aac3f7fb9665
d12b59b33df5c467abf081d48e043dac70cc5a9c
/ixnetwork_restpy/testplatform/sessions/ixnetwork/quicktest/passcriteria_985f11fda90dc3b8dac84a4a881b8740.py
6920d6cfe8478b76037b42d0c156e50d2daa5519
[ "MIT" ]
permissive
ajbalogh/ixnetwork_restpy
59ce20b88c1f99f95a980ff01106bda8f4ad5a0f
60a107e84fd8c1a32e24500259738e11740069fd
refs/heads/master
2023-04-02T22:01:51.088515
2021-04-09T18:39:28
2021-04-09T18:39:28
null
0
0
null
null
null
null
UTF-8
Python
false
false
7,492
py
# MIT LICENSE # # Copyright 1997 - 2020 by IXIA Keysight # # Permission is hereby granted, free of charge, to any person obtaining a copy # of this software and associated documentation files (the "Software"), # to deal in the Software without restriction, including without limitation # the rights to use, copy, modify, merge, publish, distribute, sublicense, # and/or sell copies of the Software, and to permit persons to whom the # Software is furnished to do so, subject to the following conditions: # # The above copyright notice and this permission notice shall be included in # all copies or substantial portions of the Software. # # THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR # IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, # FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE # AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER # LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, # OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN # THE SOFTWARE. from ixnetwork_restpy.base import Base from ixnetwork_restpy.files import Files class PassCriteria(Base): """This applies the Pass Criteria to each trial in the test and determines whether the trial passed or failed. The PassCriteria class encapsulates a required passCriteria resource which will be retrieved from the server every time the property is accessed. """ __slots__ = () _SDM_NAME = 'passCriteria' _SDM_ATT_MAP = { 'EnablePassFail': 'enablePassFail', } def __init__(self, parent): super(PassCriteria, self).__init__(parent) @property def EnablePassFail(self): """ Returns ------- - bool: If true, the pass fail criteria is set. """ return self._get_attribute(self._SDM_ATT_MAP['EnablePassFail']) @EnablePassFail.setter def EnablePassFail(self, value): self._set_attribute(self._SDM_ATT_MAP['EnablePassFail'], value) def update(self, EnablePassFail=None): """Updates passCriteria resource on the server. Args ---- - EnablePassFail (bool): If true, the pass fail criteria is set. Raises ------ - ServerError: The server has encountered an uncategorized error condition """ return self._update(self._map_locals(self._SDM_ATT_MAP, locals())) def Apply(self): """Executes the apply operation on the server. Applies the specified Quick Test. Raises ------ - NotFoundError: The requested resource does not exist on the server - ServerError: The server has encountered an uncategorized error condition """ payload = { "Arg1": self.href } return self._execute('apply', payload=payload, response_object=None) def ApplyAsync(self): """Executes the applyAsync operation on the server. Raises ------ - NotFoundError: The requested resource does not exist on the server - ServerError: The server has encountered an uncategorized error condition """ payload = { "Arg1": self.href } return self._execute('applyAsync', payload=payload, response_object=None) def ApplyAsyncResult(self): """Executes the applyAsyncResult operation on the server. Raises ------ - NotFoundError: The requested resource does not exist on the server - ServerError: The server has encountered an uncategorized error condition """ payload = { "Arg1": self.href } return self._execute('applyAsyncResult', payload=payload, response_object=None) def ApplyITWizardConfiguration(self): """Executes the applyITWizardConfiguration operation on the server. Applies the specified Quick Test. Raises ------ - NotFoundError: The requested resource does not exist on the server - ServerError: The server has encountered an uncategorized error condition """ payload = { "Arg1": self.href } return self._execute('applyITWizardConfiguration', payload=payload, response_object=None) def GenerateReport(self): """Executes the generateReport operation on the server. Generate a PDF report for the last succesfull test run. Raises ------ - NotFoundError: The requested resource does not exist on the server - ServerError: The server has encountered an uncategorized error condition """ payload = { "Arg1": self.href } return self._execute('generateReport', payload=payload, response_object=None) def Run(self, *args, **kwargs): """Executes the run operation on the server. Starts the specified Quick Test and waits for its execution to finish. The IxNetwork model allows for multiple method Signatures with the same name while python does not. run(InputParameters=string)list ------------------------------- - InputParameters (str): The input arguments of the test. - Returns list(str): This method is synchronous and returns the result of the test. Raises ------ - NotFoundError: The requested resource does not exist on the server - ServerError: The server has encountered an uncategorized error condition """ payload = { "Arg1": self.href } for i in range(len(args)): payload['Arg%s' % (i + 2)] = args[i] for item in kwargs.items(): payload[item[0]] = item[1] return self._execute('run', payload=payload, response_object=None) def Start(self, *args, **kwargs): """Executes the start operation on the server. Starts the specified Quick Test. The IxNetwork model allows for multiple method Signatures with the same name while python does not. start(InputParameters=string) ----------------------------- - InputParameters (str): The input arguments of the test. Raises ------ - NotFoundError: The requested resource does not exist on the server - ServerError: The server has encountered an uncategorized error condition """ payload = { "Arg1": self.href } for i in range(len(args)): payload['Arg%s' % (i + 2)] = args[i] for item in kwargs.items(): payload[item[0]] = item[1] return self._execute('start', payload=payload, response_object=None) def Stop(self): """Executes the stop operation on the server. Stops the currently running Quick Test. Raises ------ - NotFoundError: The requested resource does not exist on the server - ServerError: The server has encountered an uncategorized error condition """ payload = { "Arg1": self.href } return self._execute('stop', payload=payload, response_object=None) def WaitForTest(self): """Executes the waitForTest operation on the server. Waits for the execution of the specified Quick Test to be completed. Raises ------ - NotFoundError: The requested resource does not exist on the server - ServerError: The server has encountered an uncategorized error condition """ payload = { "Arg1": self.href } return self._execute('waitForTest', payload=payload, response_object=None)
ec356e53c4d259f06b48074389ec9b57fb66f575
199522cb43b4e2c7e3bf034a0e604794258562b1
/0x03-python-data_structures/7-add_tuple.py
96d715528f3d23cdf3d725a9838247a97a8e4635
[]
no_license
jormao/holbertonschool-higher_level_programming
a0fd92f2332f678e6fe496057c04f2995d24a4ac
360b3a7294e9e0eadcadb57d4c48c22369c05111
refs/heads/master
2020-09-29T01:36:20.094209
2020-05-15T03:27:06
2020-05-15T03:27:06
226,915,744
0
0
null
null
null
null
UTF-8
Python
false
false
454
py
#!/usr/bin/python3 def add_tuple(tuple_a=(), tuple_b=()): if len(tuple_a) != 2: if len(tuple_a) == 1: tuple_a = (tuple_a[0], 0) if len(tuple_a) == 0: tuple_a = (0, 0) if len(tuple_b) != 2: if len(tuple_b) == 1: tuple_b = (tuple_b[0], 0) if len(tuple_b) == 0: tuple_b = (0, 0) tuple_c = ((tuple_a[0] + tuple_b[0]), (tuple_a[1] + tuple_b[1])) return (tuple_c)
796a852c4ccdd0bc598e0b373567c854094d0cfd
45fb509bf21ac003a40fd404d7c0cc995e741672
/perceptron_algorithm/perceptron_algo_2nd_method.py
59807adb1a2c854110b8644f2b103f49899851f4
[]
no_license
FarahAgha/MachineLearning
0d17511f7495190dfd2368554428208c7d0eadf7
cf385135e016a63fb16bd326586fcd8ecb3c4355
refs/heads/master
2021-01-04T01:03:08.810401
2020-03-15T18:42:16
2020-03-15T18:42:16
240,314,331
0
0
null
null
null
null
UTF-8
Python
false
false
1,011
py
# Perceptron Algorithm perceptron_algo_2nd_method.py # See https://medium.com/@thomascountz/19-line-line-by-line-python-perceptron-b6f113b161f3 for details. import numpy as np class Perceptron(object): def __init__(self, no_of_inputs, threshold=100, learning_rate=0.01): self.threshold = threshold self.learning_rate = learning_rate self.weights = np.zeros(no_of_inputs + 1) def predict(self, inputs): summation = np.dot(inputs, self.weights[1:]) + self.weights[0] if summation > 0: activation = 1 else: activation = 0 return activation def train(self, training_inputs, labels): for _ in range(self.threshold): for inputs, label in zip(training_inputs, labels): prediction = self.predict(inputs) self.weights[1:] += self.learning_rate * (label - prediction) * inputs self.weights[0] += self.learning_rate * (label - prediction)
f9dd6d91e8aaee9919ed20cb74c14fc6f2d22c8b
44c81d8cc9c148c93cf9a77faec345693059c973
/fetch.py
568adf1e9271c6ebe976f93a3b0c8306a2ea428a
[]
no_license
neoatlantis/currency-data
26566a5131b814f324153db451ae9f879fda9b72
c19bc94d6d6ba6706f625e94e176b77bee455b04
refs/heads/master
2020-06-10T19:02:58.973856
2016-12-08T06:35:46
2016-12-08T06:35:46
75,902,576
0
0
null
null
null
null
UTF-8
Python
false
false
1,231
py
#!/usr/bin/env python import os import time import requests import shelve import sys BASEPATH = os.path.realpath(os.path.dirname(sys.argv[0])) filepath = lambda *i: os.path.join(BASEPATH, *i) # check for api key try: apikeyFilepath = filepath('apikey') apikey = open(apikeyFilepath).read().strip() except: print "Put your API key at `openexchangerates.org` into file `apikey`." sys.exit(1) # check for database db = shelve.open(filepath('currencies.db'), flag='c') latest = 0 for key in db: timestamp = float(key) if timestamp > latest: latest = timestamp if time.time() - latest < 3000 and 'force' not in sys.argv: print "You are requesting too frequent. Abandoned to prevent API", print "exhaustion. Use `force` in command line to force a request." db.close() sys.exit(2) # fetch url url = "https://openexchangerates.org/api/latest.json?app_id=%s" % apikey try: req = requests.get(url) if req.status_code != 200: raise json = req.json() json = { 'rates': json['rates'], 'timestamp': json['timestamp'] } except: print "Failed fetching newest data. Abort." sys.exit(3) print json db[str(time.time())] = json db.close() sys.exit(0)
179abd03f2ae118cfb2b85da6360707ead06748a
1b10b46afdf24b4ce4f2d57e315e09e17c0a9c2b
/winding_helix.py
51d16cff03b2651355fadbdb7bd2a560ed49af5b
[]
no_license
tthtlc/sansagraphics
e6aad1541dabc85b3871e1890c9f79aa33055355
113e559fb128c93ed1f02155ec74e76878b86c37
refs/heads/master
2021-01-15T15:52:35.126301
2020-03-30T16:58:57
2020-03-30T16:58:57
15,507,431
2
1
null
null
null
null
UTF-8
Python
false
false
3,415
py
# Pygame/PyopenGL example by Bastiaan Zapf, Apr 2009 ### From http://python-opengl-examples.blogspot.sg/ # # Draw an helix, wiggle it pleasantly # # Keywords: Alpha Blending, Textures, Animation, Double Buffer from OpenGL.GL import * from OpenGL.GLU import * from math import * # trigonometry import pygame # just to get a display # get an OpenGL surface pygame.init() pygame.display.set_mode((800,600), pygame.OPENGL|pygame.DOUBLEBUF) # How to catch errors here? done = False t=0 while not done: t=t+1 # for fun comment out these two lines glClearColor(0.0, 0.0, 0.0, 1.0) glClear(GL_COLOR_BUFFER_BIT|GL_DEPTH_BUFFER_BIT) # Get a perspective at the helix glMatrixMode(GL_PROJECTION); glLoadIdentity() gluPerspective(90,1,0.01,1000) gluLookAt(sin(t/200.0)*3,sin(t/500.0)*3,cos(t/200.0)*3,0,0,0,0,1,0) # Draw the helix (this ought to be a display list call) glMatrixMode(GL_MODELVIEW) # get a texture (this ought not to be inside the inner loop) texture=glGenTextures( 1 ) glBindTexture( GL_TEXTURE_2D, texture ); glTexEnvf( GL_TEXTURE_ENV, GL_TEXTURE_ENV_MODE, GL_MODULATE ); # set sane defaults for a plethora of potentially uninitialized # variables glTexParameterf( GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_REPEAT); glTexParameterf( GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_REPEAT ); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR) glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR) # a texture #pulse = sin(t/30)*0.5+0.5 # try this one pulse = 0 texdata=[[[0.0,0,1,1], [0.0,0,0,0], [0.0,1,0,1], [0.0,0,0,0]], [[0.0,0,0,0], [pulse,pulse,pulse,1], [pulse,pulse,pulse,1], [0.0,0,0,0]], [[0.0,1,0,1], [1,pulse,pulse,1], [pulse,pulse,0,1], [0.0,0,0,0]], [[0.0,0,0,0], [0.0,0,0,0], [0.0,0,0,0], [0.0,0,0,0]]]; glTexImage2Df(GL_TEXTURE_2D, 0,4,0,GL_RGBA, texdata) glEnable(GL_BLEND); glBlendFunc (GL_SRC_ALPHA, GL_ONE); # XXX Why GL_ONE? # alternatively: # glEnable(GL_DEPTH_TEST); glEnable( GL_TEXTURE_2D ); # use the texture glBindTexture( GL_TEXTURE_2D, texture ); # vertices & texture data glBegin(GL_TRIANGLE_STRIP); #pulse2 = 0.5 for i in range(0,100): r=5.0 # try other values - integers as well R=10.0 d=1 # try other values j=i #pulse2 += 0.5 if (i%3==0): glTexCoord2f(0,i); glVertex3f( cos(i/r)*cos(j/R) + (-2.5+i*0.05)*sin(j/R), (-2.5+i*0.05)*cos(j/R) - cos(i/r)*sin(j/R), sin(i/r)); elif (i%3==1): glTexCoord2f(1,i); glVertex3f( cos(i/r + 3.14/2)*cos(j/R) + (-2.5+i*0.05)*sin(j/R), (-2.5+i*0.05)*cos(j/R) - cos(i/r)*sin(j/R), sin(i/r + 3.14/1)); else: glTexCoord2f(2,i); glVertex3f( cos(i/r + 3.14/1)*cos(j/R) + (-2.5+i*0.05)*sin(j/R), (-2.5+i*0.05)*cos(j/R) - cos(i/r)*sin(j/R), sin(i/r+3.14/1)); # glVertex3f( cos(i/r+3.14)*pulse2, -2.5+i*0.05+d+pulse2*1, sin(i/r+3.14)*pulse2); glEnd(); glFlush() glDeleteTextures(texture) pygame.display.flip()
c4bbebeeaa1fede9542e856ca68e24409905d33f
c0f808504dd3d7fd27c39f1503fbc14c1d37bf9f
/sources/scipy-scipy-414c1ab/scipy/io/tests/test_wavfile.py
266775ecd99e28e8010c480d95ff5fce9e266339
[]
no_license
georgiee/lip-sync-lpc
7662102d4715e4985c693b316a02d11026ffb117
e931cc14fe4e741edabd12471713bf84d53a4250
refs/heads/master
2018-09-16T08:47:26.368491
2018-06-05T17:01:08
2018-06-05T17:01:08
5,779,592
17
4
null
null
null
null
UTF-8
Python
false
false
2,146
py
import os import tempfile import warnings import numpy as np from numpy.testing import assert_equal, assert_, assert_raises, assert_array_equal from numpy.testing.utils import WarningManager from scipy.io import wavfile def datafile(fn): return os.path.join(os.path.dirname(__file__), 'data', fn) def test_read_1(): warn_ctx = WarningManager() warn_ctx.__enter__() try: warnings.simplefilter('ignore', wavfile.WavFileWarning) rate, data = wavfile.read(datafile('test-44100-le-1ch-4bytes.wav')) finally: warn_ctx.__exit__() assert_equal(rate, 44100) assert_(np.issubdtype(data.dtype, np.int32)) assert_equal(data.shape, (4410,)) def test_read_2(): rate, data = wavfile.read(datafile('test-8000-le-2ch-1byteu.wav')) assert_equal(rate, 8000) assert_(np.issubdtype(data.dtype, np.uint8)) assert_equal(data.shape, (800, 2)) def test_read_fail(): fp = open(datafile('example_1.nc')) assert_raises(ValueError, wavfile.read, fp) fp.close() def _check_roundtrip(rate, dtype, channels): fd, tmpfile = tempfile.mkstemp(suffix='.wav') try: os.close(fd) data = np.random.rand(100, channels) if channels == 1: data = data[:,0] data = (data*128).astype(dtype) wavfile.write(tmpfile, rate, data) rate2, data2 = wavfile.read(tmpfile) assert_equal(rate, rate2) assert_(data2.dtype.byteorder in ('<', '=', '|'), msg=data2.dtype) assert_array_equal(data, data2) finally: os.unlink(tmpfile) def test_write_roundtrip(): for signed in ('i', 'u'): for size in (1, 2, 4, 8): if size == 1 and signed == 'i': # signed 8-bit integer PCM is not allowed continue for endianness in ('>', '<'): if size == 1 and endianness == '<': continue for rate in (8000, 32000): for channels in (1, 2, 5): dt = np.dtype('%s%s%d' % (endianness, signed, size)) yield _check_roundtrip, rate, dt, channels
41cc8cb8ec10ccb8c7eb432e8f3cc4602df5f651
d043a51ff0ca2f9fb3943c3f0ea21c61055358e9
/python3网络爬虫开发实战/数据存储/MySQL实验/删除数据2.py
7af2d45b23cc102f658c4407ee7362981f7f0c80
[]
no_license
lj1064201288/dell_python
2f7fd9dbcd91174d66a2107c7b7f7a47dff4a4d5
529985e0e04b9bde2c9e0873ea7593e338b0a295
refs/heads/master
2020-03-30T03:51:51.263975
2018-12-11T13:21:13
2018-12-11T13:21:13
150,707,725
0
0
null
null
null
null
UTF-8
Python
false
false
382
py
import pymysql db = pymysql.connect(host="localhost", user='root', password='123456', port=3306, db='django') cursor = db.cursor() table = "friends" age = "age > 30" sql = 'DELETE FROM {table} WHERE {age}'.format(table=table, age=age) try: cursor.execute(sql) print("Successful...") db.commit() except: print("Failed...") db.rollback() finally: db.close()
92ed6a36ac6f7be76144f403a841125f2a79c943
633c18a9e1931f937f7f91f05ce9749a4ac169f6
/work_with_pythest/tests/test_math.py
05d5b8bf6daeef827b40a6d56148b1075e179af4
[]
no_license
borko81/python_scripts
fb3ff79377f19233e18d20f4f150735cdbe52c29
4e8ed38550f3b90bc00c07605d7e92822b079206
refs/heads/master
2022-07-07T19:26:52.467714
2022-06-24T15:46:57
2022-06-24T15:46:57
224,904,971
0
0
null
null
null
null
UTF-8
Python
false
false
280
py
import pytest def test_one_plus_one(): assert 1 + 1 == 2 def test_one_plust_two(): a = 1 b = 2 c = 3 assert a + b == c def test_division_by_zero(): with pytest.raises(ZeroDivisionError) as e: num = 1 / 0 assert 'division' in str(e.value)
f2ebf591f742eb1433a9072d3c9826170e1cb8cd
2f73a3d4daac2aa2c38c3443b4f5555c49faa1c8
/Data.py
d8e917bf4fa96358299cdd241123799362a03919
[]
no_license
18021009/project
656b6c8f9a0120c1185493d04405660895db93e9
0133f412e50e3dadd13bd0028832babf846070e5
refs/heads/main
2023-05-07T17:08:41.529766
2021-06-01T04:06:38
2021-06-01T04:06:38
372,696,937
0
0
null
null
null
null
UTF-8
Python
false
false
4,718
py
from math import nan from os import name from Station import station import numpy as np import datetime import pandas as pd from Map import map from Point import point # standardline date data.csv to college.csv # ds = pd.read_csv('data.csv') def changeToDate(output_file): ds = pd.read_csv('data.csv') day_delta = datetime.timedelta(days=1) start_date = datetime.date(2019, 1, 1) end_date = datetime.date(2020, 1, 1) for i in range((end_date - start_date).days): day = start_date + i*day_delta _day = day.strftime('X%m/X%d/%Y').replace('X0','X').replace('X','') ds['time'] = ds['time'].replace({_day: day}) ds.to_csv(output_file, index=False) def buffer_data(input_file, buffer): dataStation = pd.read_csv(input_file) dataStation['wind_speed'] = nan dataStation['temperature'] = nan dataStation['satellite_NO2'] = nan dataStation["road_density"] = nan dataStation["relative_humidity"] = nan dataStation["pressure"] = nan dataStation["population_density"] = nan dataStation["pblh"] = nan dataStation["NDVI"] = nan dataStation["dpt"] = nan dataStationArray = dataStation.values dataStation = pd.DataFrame(dataStationArray, columns=['time', 'lat', 'long', 'NO2', 'name', 'wind_speed' + str(buffer), 'temperature' + str(buffer), 'satellite_NO2' + str(buffer), 'road_density' + str(buffer), 'relative_humidity' + str(buffer), 'pressure' + str(buffer), 'population_density' + str(buffer), 'pblh' + str(buffer), 'NDVI' + str(buffer), 'dpt' + str(buffer)]) dataStation.to_csv(input_file, float_format='{:f}'.format, index=False) changeToDate('buffer_1_data.csv') buffer_data('buffer_1_data.csv', 1) changeToDate('buffer_2_data.csv') buffer_data('buffer_2_data.csv', 2) changeToDate('buffer_3_data.csv') buffer_data('buffer_3_data.csv', 3) # a = pd.read_csv("buffer_1_data.csv") # b = pd.read_csv("buffer_2_data.csv") # merged = a.merge(b, on=['time', 'lat', 'long', 'name'], how='inner') # merged.to_csv('merge.csv', index=False) # c = pd.read_csv("merge.csv") # d = pd.read_csv("buffer_3_data.csv") # merged = c.merge(d, on=['time', 'lat', 'long', 'name'], how='inner') # merged.to_csv('merge.csv', index=False) # buffer_radius # _buffer_radius = 1 # dataStation = pd.read_csv('college.csv') # dataStation['wind_speed'] = -999.0 # dataStation["road_dens"] = -999.0 # dataStation["pp_dens"] = -999.0 # dataStation["earth_no2"] = -999.0 # dataStationArray = dataStation.values # # add wind speed to dataStationArray # start_date = datetime.date(2019, 1, 1) # end_date = datetime.date(2020, 1, 1) # day_delta = datetime.timedelta(days=1) # for i in range((end_date - start_date).days): # fileName = "WSPDCombine_" # day = start_date + i*day_delta # file = "map/wind_speed/" + fileName + day.strftime('%Y%m%d') + ".tif" # _map = map() # _map.setMap(file) # for data in dataStationArray: # if((data[0] == day.strftime('%Y-%m-%d'))): # _point = point(data[2], data[1]) # _point.set_position_on_matrix(_map) # _station = station(_point, _buffer_radius) # _station.setBufferValue(_map) # data[5] = np.float64(_station.bufferValue) # # add road to college.csv # _map = map() # _map.setMap('map/road_density/road_dens.tif') # for data in dataStationArray: # _point = point(data[2], data[1]) # _point.set_position_on_matrix(_map) # _station = station(_point, _buffer_radius) # _station.setBufferValue(_map) # data[6] = _station.bufferValue # # add population_density # _map = map() # _map.setMap('map/population_density/ppd.tif') # for data in dataStationArray: # _point = point(data[2], data[1]) # _point.set_position_on_matrix(_map) # _station = station(_point, _buffer_radius) # _station.setBufferValue(_map) # data[7] = _station.bufferValue # # add earth_no2 # for i in range((end_date - start_date).days): # fileName = "NO2_" # day = start_date + i*day_delta # file = "map/NO2/" + fileName + day.strftime('%Y%m%d') + ".tif" # _map = map() # _map.setMap(file) # for data in dataStationArray: # if((data[0] == day.strftime('%Y-%m-%d'))): # _point = point(data[2], data[1]) # _point.set_position_on_matrix(_map) # _station = station(_point, _buffer_radius) # _station.setBufferValue(_map) # data[8] = _station.bufferValue # newDataStation = pd.DataFrame(dataStationArray, columns=['time', 'lat', 'long', 'NO2', 'name', 'wind_speed', 'road_dens', 'pp_dens', 'earth_no2']) # newDataStation.to_csv('college_2.csv', float_format='{:f}'.format, index=False)
c08ce6dd49ab813444d35c3c9349c72f052e228b
5e255ad1360c90478393744586663741a9569c21
/linebot/models/base.py
164fca9d9e9240236cfe90b9b6b2b37ba835814f
[ "Apache-2.0" ]
permissive
line/line-bot-sdk-python
d76268e8b542060d6eccbacc5dbfab16960ecc35
cffd35948238ae24982173e30b1ea1e595bbefd9
refs/heads/master
2023-08-31T22:12:31.698183
2023-08-28T01:10:09
2023-08-28T01:10:09
70,553,423
1,898
1,181
Apache-2.0
2023-09-11T05:14:07
2016-10-11T03:42:26
Python
UTF-8
Python
false
false
4,121
py
# -*- coding: utf-8 -*- # Licensed under the Apache License, Version 2.0 (the "License"); you may # not use this file except in compliance with the License. You may obtain # a copy of the License at # # https://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, WITHOUT # WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the # License for the specific language governing permissions and limitations # under the License. """linebot.models.base module.""" import json from .. import utils class Base(object): """Base class of model. Suitable for JSON base data. """ def __init__(self, **kwargs): """__init__ method. :param kwargs: """ pass def __str__(self): """__str__ method.""" return self.as_json_string() def __repr__(self): """__repr__ method.""" return str(self) def __eq__(self, other): """__eq__ method. :param other: """ return other and self.as_json_dict() == other.as_json_dict() def __ne__(self, other): """__ne__ method. :param other: """ return not self.__eq__(other) def as_json_string(self): """Return JSON string from this object. :rtype: str """ return json.dumps(self.as_json_dict(), sort_keys=True) def as_json_dict(self): """Return dictionary from this object. :return: dict """ data = {} for key, value in self.__dict__.items(): camel_key = utils.to_camel_case(key) if isinstance(value, (list, tuple, set)): data[camel_key] = list() for item in value: if hasattr(item, 'as_json_dict'): data[camel_key].append(item.as_json_dict()) else: data[camel_key].append(item) elif hasattr(value, 'as_json_dict'): data[camel_key] = value.as_json_dict() elif value is not None: data[camel_key] = value return data @classmethod def new_from_json_dict(cls, data, use_raw_message=False): """Create a new instance from a dict. :param data: JSON dict :param bool use_raw_message: Using original Message key as attribute """ if use_raw_message: return cls(use_raw_message=use_raw_message, **data) new_data = {utils.to_snake_case(key): value for key, value in data.items()} return cls(**new_data) @staticmethod def get_or_new_from_json_dict(data, cls): """Get `cls` object w/ deserialization from json if needed. If data is instance of cls, return data. Else if data is instance of dict, create instance from dict. Else, return None. :param data: :param cls: :rtype: object """ if isinstance(data, cls): return data elif isinstance(data, dict): return cls.new_from_json_dict(data) return None @staticmethod def get_or_new_from_json_dict_with_types( data, cls_map, type_key='type', use_raw_message=False ): """Get `cls` object w/ deserialization from json by using type key hint if needed. If data is instance of one of cls, return data. Else if data is instance of dict, create instance from dict. Else, return None. :param data: :param cls_map: :param type_key: :rtype: object :param bool use_raw_message: Using original Message key as attribute """ if isinstance(data, tuple(cls_map.values())): return data elif isinstance(data, dict): type_val = data[type_key] if type_val in cls_map: return cls_map[type_val].new_from_json_dict(data, use_raw_message=use_raw_message) return None
241b062d29b2a2e895a396fb385dd2ffb44bab96
3ff9821b1984417a83a75c7d186da9228e13ead9
/No_1410_HTML Entity Parser/by_re_replacement.py
c017682935944a4f3a73df684c4c097a91d80e6d
[ "MIT" ]
permissive
brianchiang-tw/leetcode
fd4df1917daef403c48cb5a3f5834579526ad0c2
6978acfb8cb767002cb953d02be68999845425f3
refs/heads/master
2023-06-11T00:44:01.423772
2023-06-01T03:52:00
2023-06-01T03:52:00
222,939,709
41
12
null
null
null
null
UTF-8
Python
false
false
3,076
py
''' Description: HTML entity parser is the parser that takes HTML code as input and replace all the entities of the special characters by the characters itself. The special characters and their entities for HTML are: Quotation Mark: the entity is &quot; and symbol character is ". Single Quote Mark: the entity is &apos; and symbol character is '. Ampersand: the entity is &amp; and symbol character is &. Greater Than Sign: the entity is &gt; and symbol character is >. Less Than Sign: the entity is &lt; and symbol character is <. Slash: the entity is &frasl; and symbol character is /. Given the input text string to the HTML parser, you have to implement the entity parser. Return the text after replacing the entities by the special characters. Example 1: Input: text = "&amp; is an HTML entity but &ambassador; is not." Output: "& is an HTML entity but &ambassador; is not." Explanation: The parser will replace the &amp; entity by & Example 2: Input: text = "and I quote: &quot;...&quot;" Output: "and I quote: \"...\"" Example 3: Input: text = "Stay home! Practice on Leetcode :)" Output: "Stay home! Practice on Leetcode :)" Example 4: Input: text = "x &gt; y &amp;&amp; x &lt; y is always false" Output: "x > y && x < y is always false" Example 5: Input: text = "leetcode.com&frasl;problemset&frasl;all" Output: "leetcode.com/problemset/all" Constraints: 1 <= text.length <= 10^5 The string may contain any possible characters out of all the 256 ASCII characters. ''' import re class Solution: def entityParser(self, text: str) -> str: html_symbol = [ '&quot;', '&apos;', '&gt;', '&lt;', '&frasl;', '&amp;'] formal_symbol = [ '"', "'", '>', '<', '/', '&'] for html_sym, formal_sym in zip(html_symbol, formal_symbol): text = re.sub( html_sym , formal_sym, text ) return text # n : the character length of input, text. ## Time Complexity: O( n ) # # The overhead in time is the cost of string replacement, which is of O( n ). ## Space Complexity: O( n ) # # The overhead in space is the storage for output string, which is of O( n ). from collections import namedtuple TestEntry = namedtuple('TestEntry', 'text') def test_bench(): test_data = [ TestEntry( text = "&amp; is an HTML entity but &ambassador; is not." ), TestEntry( text = "and I quote: &quot;...&quot;" ), TestEntry( text = "Stay home! Practice on Leetcode :)" ), TestEntry( text = "x &gt; y &amp;&amp; x &lt; y is always false" ), TestEntry( text = "leetcode.com&frasl;problemset&frasl;all" ), ] # expected output: ''' & is an HTML entity but &ambassador; is not. and I quote: "..." Stay home! Practice on Leetcode :) x > y && x < y is always false leetcode.com/problemset/all ''' for t in test_data: print( Solution().entityParser( text = t.text) ) return if __name__ == '__main__': test_bench()
f76d5f3aec244f5d33fcd7e2887d2eb61bb5658a
0b25b1c2ea3e3f05ea388e1105cd2fab50e7ba54
/mysite/blog/forms.py
68ba9afdb13950be95db2f366aa5aebf783e6d1c
[]
no_license
webclinic017/Django-project
f8337aeb296d12760143951635d0297c13313a50
e757aef633c63aaf857afd1f274d42d16703ca0c
refs/heads/master
2022-12-25T17:30:14.503627
2020-10-12T08:47:08
2020-10-12T08:47:08
null
0
0
null
null
null
null
UTF-8
Python
false
false
397
py
from django import forms from .models import Comment class EmailPostForm(forms.Form): name = forms.CharField() email = forms.EmailField() to = forms.EmailField() comments = forms.CharField(required=False, widget=forms.Textarea) class CommentForm(forms.ModelForm): class Meta: model = Comment fields = ('name', 'email', 'body')
91c2e382f455de622a8bfb58b1df4f5bbe6b01ff
e13a79dec2668c1870b3fea05f071fe872d400f0
/pde/storage/tests/test_generic_storages.py
474649dd328980f34d7df91ecac637408b9e3bd6
[ "MIT" ]
permissive
yiweizhang1025/py-pde
b27cc0b058b50d6af921e1ea84bf59a5bb0ff370
3862a35505b9ce4d62557bc65dfedd40638a90f3
refs/heads/master
2023-03-14T17:21:07.004742
2021-03-15T15:33:47
2021-03-15T15:33:47
null
0
0
null
null
null
null
UTF-8
Python
false
false
7,739
py
""" .. codeauthor:: David Zwicker <[email protected]> """ import functools import numpy as np import pytest from pde import DiffusionPDE, FileStorage, MemoryStorage, UnitGrid from pde.fields import FieldCollection, ScalarField, Tensor2Field, VectorField from pde.tools.misc import module_available def test_storage_write(tmp_path): """ test simple memory storage """ dim = 5 grid = UnitGrid([dim]) field = ScalarField(grid) storage_classes = {"MemoryStorage": MemoryStorage} if module_available("h5py"): file_path = tmp_path / "test_storage_write.hdf5" storage_classes["FileStorage"] = functools.partial(FileStorage, file_path) for name, storage_cls in storage_classes.items(): storage = storage_cls(info={"a": 1}) storage.start_writing(field, info={"b": 2}) storage.append(field.copy(data=np.arange(dim)), 0) storage.append(field.copy(data=np.arange(dim)), 1) storage.end_writing() assert not storage.has_collection np.testing.assert_allclose(storage.times, np.arange(2)) for f in storage: np.testing.assert_array_equal(f.data, np.arange(dim)) for i in range(2): np.testing.assert_array_equal(storage[i].data, np.arange(dim)) assert {"a": 1, "b": 2}.items() <= storage.info.items() storage = storage_cls() storage.clear() for i in range(3): storage.start_writing(field) storage.append(field.copy(data=np.arange(dim) + i), i) storage.end_writing() np.testing.assert_allclose( storage.times, np.arange(3), err_msg="storage class: " + name ) def test_storage_truncation(tmp_path): """ test whether simple trackers can be used """ file = tmp_path / "test_storage_truncation.hdf5" for truncate in [True, False]: storages = [MemoryStorage()] if module_available("h5py"): storages.append(FileStorage(file)) tracker_list = [s.tracker(interval=0.01) for s in storages] grid = UnitGrid([8, 8]) state = ScalarField.random_uniform(grid, 0.2, 0.3) pde = DiffusionPDE() pde.solve(state, t_range=0.1, dt=0.001, tracker=tracker_list) if truncate: for storage in storages: storage.clear() pde.solve(state, t_range=[0.1, 0.2], dt=0.001, tracker=tracker_list) times = np.arange(0.1, 0.201, 0.01) if not truncate: times = np.r_[np.arange(0, 0.101, 0.01), times] for storage in storages: msg = f"truncate={truncate}, storage={storage}" np.testing.assert_allclose(storage.times, times, err_msg=msg) assert not storage.has_collection def test_storing_extract_range(tmp_path): """ test methods specific to FieldCollections in memory storage """ sf = ScalarField(UnitGrid([1])) storage_classes = {"MemoryStorage": MemoryStorage} if module_available("h5py"): file_path = tmp_path / "test_storage_write.hdf5" storage_classes["FileStorage"] = functools.partial(FileStorage, file_path) for storage_cls in storage_classes.values(): # store some data s1 = storage_cls() s1.start_writing(sf) s1.append(sf.copy(data=np.array([0])), 0) s1.append(sf.copy(data=np.array([2])), 1) s1.end_writing() np.testing.assert_equal(s1[0].data, 0) np.testing.assert_equal(s1[1].data, 2) np.testing.assert_equal(s1[-1].data, 2) np.testing.assert_equal(s1[-2].data, 0) with pytest.raises(IndexError): s1[2] with pytest.raises(IndexError): s1[-3] # test extraction s2 = s1.extract_time_range() assert s2.times == list(s1.times) np.testing.assert_allclose(s2.data, s1.data) s3 = s1.extract_time_range(0.5) assert s3.times == s1.times[:1] np.testing.assert_allclose(s3.data, s1.data[:1]) s4 = s1.extract_time_range((0.5, 1.5)) assert s4.times == s1.times[1:] np.testing.assert_allclose(s4.data, s1.data[1:]) def test_storing_collection(tmp_path): """ test methods specific to FieldCollections in memory storage """ grid = UnitGrid([2, 2]) f1 = ScalarField.random_uniform(grid, 0.1, 0.4, label="a") f2 = VectorField.random_uniform(grid, 0.1, 0.4, label="b") f3 = Tensor2Field.random_uniform(grid, 0.1, 0.4, label="c") fc = FieldCollection([f1, f2, f3]) storage_classes = {"MemoryStorage": MemoryStorage} if module_available("h5py"): file_path = tmp_path / "test_storage_write.hdf5" storage_classes["FileStorage"] = functools.partial(FileStorage, file_path) for storage_cls in storage_classes.values(): # store some data storage = storage_cls() storage.start_writing(fc) storage.append(fc, 0) storage.append(fc, 1) storage.end_writing() assert storage.has_collection assert storage.extract_field(0)[0] == f1 assert storage.extract_field(1)[0] == f2 assert storage.extract_field(2)[0] == f3 assert storage.extract_field(0)[0].label == "a" assert storage.extract_field(0, label="new label")[0].label == "new label" assert storage.extract_field(0)[0].label == "a" # do not alter label assert storage.extract_field("a")[0] == f1 assert storage.extract_field("b")[0] == f2 assert storage.extract_field("c")[0] == f3 with pytest.raises(ValueError): storage.extract_field("nonsense") def test_storage_apply(tmp_path): """ test the apply function of StorageBase """ grid = UnitGrid([2]) field = ScalarField(grid) storage_classes = {"None": None, "MemoryStorage": MemoryStorage} if module_available("h5py"): file_path = tmp_path / "test_storage_apply.hdf5" storage_classes["FileStorage"] = functools.partial(FileStorage, file_path) s1 = MemoryStorage() s1.start_writing(field, info={"b": 2}) s1.append(field.copy(data=np.array([0, 1])), 0) s1.append(field.copy(data=np.array([1, 2])), 1) s1.end_writing() for name, storage_cls in storage_classes.items(): out = None if storage_cls is None else storage_cls() s2 = s1.apply(lambda x: x + 1, out=out) assert storage_cls is None or s2 is out assert len(s2) == 2 np.testing.assert_allclose(s2.times, s1.times) assert s2[0] == ScalarField(grid, [1, 2]), name assert s2[1] == ScalarField(grid, [2, 3]), name # test empty storage s1 = MemoryStorage() s2 = s1.apply(lambda x: x + 1) assert len(s2) == 0 def test_storage_copy(tmp_path): """ test the copy function of StorageBase """ grid = UnitGrid([2]) field = ScalarField(grid) storage_classes = {"None": None, "MemoryStorage": MemoryStorage} if module_available("h5py"): file_path = tmp_path / "test_storage_apply.hdf5" storage_classes["FileStorage"] = functools.partial(FileStorage, file_path) s1 = MemoryStorage() s1.start_writing(field, info={"b": 2}) s1.append(field.copy(data=np.array([0, 1])), 0) s1.append(field.copy(data=np.array([1, 2])), 1) s1.end_writing() for name, storage_cls in storage_classes.items(): out = None if storage_cls is None else storage_cls() s2 = s1.copy(out=out) assert storage_cls is None or s2 is out assert len(s2) == 2 np.testing.assert_allclose(s2.times, s1.times) assert s2[0] == s1[0], name assert s2[1] == s1[1], name # test empty storage s1 = MemoryStorage() s2 = s1.copy() assert len(s2) == 0
7b1bd474762dbf9fa0ad77e916a9a288222c806a
44494598f8edcee0319f3b4ef69b704fbf6d88f2
/code/twurtle/src/TestDCMotorRobot.py
aad26a3b8a287a62bb2e513d1e4b4b865f1e0879
[]
no_license
whaleygeek/pyws
3cebd7e88b41e14d9c1e4dbb8148de63dadbdd57
e60724646e49287f1e12af609f325ac228b31512
refs/heads/master
2021-01-02T09:01:47.644851
2014-09-02T19:47:20
2014-09-02T19:47:20
null
0
0
null
null
null
null
UTF-8
Python
false
false
168
py
# This is mainly to test that the packaging has worked for robot correctly import robot r = robot.MotorRobot(robot.DCMotorDrive(a1=11, a2=12, b1=13, b2=14)) r.test()
a5f5ad934ab6b4548d185c57b55e75a4fe701d2d
75dcb56e318688499bdab789262839e7f58bd4f6
/_algorithms_challenges/pybites/bitesofpy-master/!201-300/239/test_fizzbuzz.py
374796ea04fb39da68675115964e7be47e23b93c
[]
no_license
syurskyi/Algorithms_and_Data_Structure
9a1f358577e51e89c862d0f93f373b7f20ddd261
929dde1723fb2f54870c8a9badc80fc23e8400d3
refs/heads/master
2023-02-22T17:55:55.453535
2022-12-23T03:15:00
2022-12-23T03:15:00
226,243,987
4
1
null
2023-02-07T21:01:45
2019-12-06T04:14:10
Jupyter Notebook
UTF-8
Python
false
false
483
py
from fizzbuzz import fizzbuzz # write one or more pytest functions below, they need to start with test_ def test_fizzbuzz_base(): assert fizzbuzz(1) == 1 assert fizzbuzz(2) == 2 def test_fizzbuzz_fizz(): assert fizzbuzz(3) == 'Fizz' assert fizzbuzz(6) == 'Fizz' def test_fizzbuzz_buzz(): assert fizzbuzz(5) == 'Buzz' assert fizzbuzz(10) == 'Buzz' def test_fizzbuzz_fizzbuzz(): assert fizzbuzz(15) == 'Fizz Buzz' assert fizzbuzz(30) == 'Fizz Buzz'
ef9b5b666e8749d77a7b64d744affbcd8a64a543
963cac9e78c4b742f7e7800200de8d1582799955
/test/veetou/parserTests.py
797c7be4f0f217a2fd7bbe13910a3ec1cd8fde32
[]
no_license
ptomulik/veetou
c79ceb3ca3d7ef7b261b2219489b6f0a7a83e1fa
b30be2a604f4426f832ec9805547ecd6cc9083fe
refs/heads/master
2021-01-22T17:28:57.271251
2019-01-05T01:46:43
2020-05-04T16:23:44
85,016,513
0
1
null
null
null
null
UTF-8
Python
false
false
3,386
py
#!/usr/bin/env python3 # -*- coding: utf8 -*- import unittest import veetou.parser as parser class Test__Parser(unittest.TestCase): def test__funcions_symbols__1(self): self.assertIs(parser.dictmatcher , parser.functions_.dictmatcher) self.assertIs(parser.fullmatch , parser.functions_.fullmatch) self.assertIs(parser.fullmatchdict , parser.functions_.fullmatchdict) self.assertIs(parser.ifullmatch , parser.functions_.ifullmatch) self.assertIs(parser.imatch , parser.functions_.imatch) self.assertIs(parser.imatcher , parser.functions_.imatcher) self.assertIs(parser.match , parser.functions_.match) self.assertIs(parser.matchdict , parser.functions_.matchdict) self.assertIs(parser.matcher , parser.functions_.matcher) self.assertIs(parser.permutexpr , parser.functions_.permutexpr) self.assertIs(parser.reentrant , parser.functions_.reentrant) self.assertIs(parser.scatter , parser.functions_.scatter) self.assertIs(parser.search , parser.functions_.search) self.assertIs(parser.searchpd , parser.functions_.searchpd) self.assertIs(parser.skipemptylines , parser.functions_.skipemptylines) def test__parsererror_symbols__1(self): self.assertIs(parser.ParserError, parser.parsererror_.ParserError) def test__parser_symbols__1(self): self.assertIs(parser.Parser, parser.parser_.Parser) self.assertIs(parser.RootParser, parser.parser_.RootParser) def test__addressparser__1(self): self.assertIs(parser.AddressParser, parser.addressparser_.AddressParser) def test__contactparser__1(self): self.assertIs(parser.ContactParser, parser.contactparser_.ContactParser) def test__footerparser__1(self): self.assertIs(parser.FooterParser, parser.footerparser_.FooterParser) def test__headerparser__1(self): self.assertIs(parser.HeaderParser, parser.headerparser_.HeaderParser) def test__keymapparser__1(self): self.assertIs(parser.KeyMapParser, parser.keymapparser_.KeyMapParser) def test__pageparser__1(self): self.assertIs(parser.PageParser, parser.pageparser_.PageParser) def test__preambleparser__1(self): self.assertIs(parser.PreambleParser, parser.preambleparser_.PreambleParser) def test__reportparser__1(self): self.assertIs(parser.ReportParser, parser.reportparser_.ReportParser) def test__sheetparser__1(self): self.assertIs(parser.SheetParser, parser.sheetparser_.SheetParser) def test__summaryparser__1(self): self.assertIs(parser.SummaryParser, parser.summaryparser_.SummaryParser) def test__tableparser__1(self): self.assertIs(parser.TableParser, parser.tableparser_.TableParser) def test__tbodyparser__1(self): self.assertIs(parser.TbodyParser, parser.tbodyparser_.TbodyParser) def test__thparser__1(self): self.assertIs(parser.ThParser, parser.thparser_.ThParser) def test__trparser__1(self): self.assertIs(parser.TrParser, parser.trparser_.TrParser) if __name__ == '__main__': unittest.main() # Local Variables: # # tab-width:4 # # indent-tabs-mode:nil # # End: # vim: set syntax=python expandtab tabstop=4 shiftwidth=4:
832a298328bc29b34d0110a3029f906ad483a34d
37c3b81ad127c9e3cc26fa9168fda82460ca9bda
/Baekjoon/boj_20055_컨베이어 벨트 위의 로봇.py
dfdb3152402dc2cfac4c545e7cd087fba933dcf0
[]
no_license
potomatoo/TIL
5d85b69fdaed68966db7cfe2a565b7c64ed3e816
395dc190fa13e5ed036e1e3c7d9e0bc2e1ee4d6c
refs/heads/master
2021-07-08T16:19:40.410097
2021-04-19T02:33:40
2021-04-19T02:33:40
238,872,774
0
0
null
null
null
null
UTF-8
Python
false
false
751
py
def work(): global cnt while True: board.rotate(1) robot.rotate(1) robot[N-1] = 0 for i in range(N-2, -1, -1): if robot[i] and not robot[i+1] and board[i+1] > 0: board[i+1] -= 1 robot[i+1] = 1 robot[i] = 0 robot[N-1] = 0 if not robot[0] and board[0] > 0: board[0] -= 1 robot[0] = 1 flag = 0 for i in range(len(board)): if board[i] == 0: flag += 1 if flag >= K: break cnt += 1 from collections import deque N, K = map(int, input().split()) board = deque(map(int, input().split())) cnt = 1 robot = deque([0] * len(board)) work() print(cnt)
9305c3a78026026cae6e03d11b5982d9cee7f094
0617c812e9bf58a2dbc1c1fef35e497b054ed7e4
/venv/Lib/site-packages/pyrogram/raw/functions/stats/get_megagroup_stats.py
320398dd3f9fb86f271aeb14aaca77b3bc298f8c
[]
no_license
howei5163/my_framework
32cf510e19a371b6a3a7c80eab53f10a6952f7b2
492c9af4ceaebfe6e87df8425cb21534fbbb0c61
refs/heads/main
2023-01-27T14:33:56.159867
2020-12-07T10:19:33
2020-12-07T10:19:33
306,561,184
1
0
null
null
null
null
UTF-8
Python
false
false
2,553
py
# Pyrogram - Telegram MTProto API Client Library for Python # Copyright (C) 2017-2020 Dan <https://github.com/delivrance> # # This file is part of Pyrogram. # # Pyrogram is free software: you can redistribute it and/or modify # it under the terms of the GNU Lesser General Public License as published # by the Free Software Foundation, either version 3 of the License, or # (at your option) any later version. # # Pyrogram is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU Lesser General Public License for more details. # # You should have received a copy of the GNU Lesser General Public License # along with Pyrogram. If not, see <http://www.gnu.org/licenses/>. from io import BytesIO from pyrogram.raw.core.primitives import Int, Long, Int128, Int256, Bool, Bytes, String, Double, Vector from pyrogram.raw.core import TLObject from pyrogram import raw from typing import List, Union, Any # # # # # # # # # # # # # # # # # # # # # # # # # !!! WARNING !!! # # This is a generated file! # # All changes made in this file will be lost! # # # # # # # # # # # # # # # # # # # # # # # # # class GetMegagroupStats(TLObject): # type: ignore """Telegram API method. Details: - Layer: ``117`` - ID: ``0xdcdf8607`` Parameters: channel: :obj:`InputChannel <pyrogram.raw.base.InputChannel>` dark (optional): ``bool`` Returns: :obj:`stats.MegagroupStats <pyrogram.raw.base.stats.MegagroupStats>` """ __slots__: List[str] = ["channel", "dark"] ID = 0xdcdf8607 QUALNAME = "pyrogram.raw.functions.stats.GetMegagroupStats" def __init__(self, *, channel: "raw.base.InputChannel", dark: Union[None, bool] = None) -> None: self.channel = channel # InputChannel self.dark = dark # flags.0?true @staticmethod def read(data: BytesIO, *args: Any) -> "GetMegagroupStats": flags = Int.read(data) dark = True if flags & (1 << 0) else False channel = TLObject.read(data) return GetMegagroupStats(channel=channel, dark=dark) def write(self) -> bytes: data = BytesIO() data.write(Int(self.ID, False)) flags = 0 flags |= (1 << 0) if self.dark is not None else 0 data.write(Int(flags)) data.write(self.channel.write()) return data.getvalue()
[ "houwei5163" ]
houwei5163
b645ed1a0ad19262304bef16a69381cbb05cbc2c
4a211e279ec89239033c5fe2d6d8d3e49b48d369
/salvo/src/lib/job_control_loader.py
d179d460ec8b996e850b26e0c4f04fbb774d9d79
[ "Apache-2.0" ]
permissive
envoyproxy/envoy-perf
cfb1e8f7af806600f11ebc235c1a72939420b087
d131bc2f1a7f8ae4f640da30fd30c027735d9788
refs/heads/main
2023-08-31T14:02:50.891888
2023-08-24T16:19:26
2023-08-24T16:19:26
94,845,161
109
29
Apache-2.0
2023-08-24T16:19:28
2017-06-20T03:20:02
Python
UTF-8
Python
false
false
3,111
py
"""This object abstracts the loading of json strings into protobuf objects.""" import json import logging import yaml from google.protobuf import json_format import api.control_pb2 as proto_control log = logging.getLogger(__name__) def _load_json_doc(filename: str) -> proto_control.JobControl: """Load a disk file as JSON. This function reads the specified filename and parses the contents as JSON. Args: filename: The file whose contents are to be read as JSON data Returns: A JobControl object populated with the contents from the specified JSON file """ contents = None log.debug(f"Opening JSON file {filename}") try: with open(filename, 'r') as json_doc: contents = json_format.Parse(json_doc.read(), proto_control.JobControl()) except FileNotFoundError as file_not_found: log.exception(f"Unable to load {filename}: {file_not_found}") except json_format.Error as json_parse_error: log.exception(f"Unable to parse JSON contents {filename}: {json_parse_error}") return contents def _load_yaml_doc(filename: str) -> proto_control.JobControl: """Load a disk file as YAML. This function reads the specified filename and parses the contents as YAML. Args: filename: The file whose contents are to be read as YAML data Returns: A JobControl object populated with the contents from the specified YAML file """ log.debug(f"Opening YAML file {filename}") contents = None try: with open(filename, 'r') as yaml_doc: contents = yaml.safe_load(yaml_doc.read()) contents = json_format.Parse(json.dumps(contents), proto_control.JobControl()) except FileNotFoundError as file_not_found: log.exception(f"Unable to load {filename}: {file_not_found}") except json_format.Error as yaml_parse_error: log.exception(f"Unable to parse YAML contents {filename}: {yaml_parse_error}") return contents def load_control_doc(filename: str) -> proto_control.JobControl: """Return a JobControl object from the identified filename. This function uses the extension of the specified file to read its contents as YAML or JSON Args: filename: The file whose contents are to be read and parsed as a Job Control object. Returns: A JobControl object populated with the contents from the specified filename """ contents = None # Try loading the contents based on the file extension if filename.endswith('.json'): log.debug(f"Loading JSON file {filename}") return _load_json_doc(filename) elif filename.endswith('.yaml'): log.debug(f"Loading YAML file {filename}") return _load_yaml_doc(filename) else: log.debug(f"Auto-detecting contents of {filename}") # Attempt to autodetect the contents try: contents = _load_json_doc(filename) except json_format.Error: log.info(f"Parsing {filename} as JSON failed. Trying YAML") if not contents: try: contents = _load_yaml_doc(filename) except json_format.Error: log.info(f"Parsing {filename} as YAML failed.") return contents
b14adaf5a89b66b23c4ea53b5a93cd242caca777
0f16edb46a48f9b5a125abb56fc0545ede1d65aa
/test_utilities/src/d1_test/mock_api/tests/test_get.py
d1eaef95d18355fd89576cc41c693343b6516ba0
[ "Apache-2.0" ]
permissive
DataONEorg/d1_python
5e685f1af0c356190f2d6df45d1ac849e2f56972
d72a9461894d9be7d71178fb7310101b8ef9066a
refs/heads/master
2023-08-29T03:16:38.131760
2023-06-27T21:59:37
2023-06-27T21:59:37
60,103,877
15
12
Apache-2.0
2023-09-06T18:27:53
2016-05-31T16:01:00
Python
UTF-8
Python
false
false
2,721
py
# This work was created by participants in the DataONE project, and is # jointly copyrighted by participating institutions in DataONE. For # more information on DataONE, see our web site at http://dataone.org. # # Copyright 2009-2019 DataONE # # 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 requests import responses import d1_test.d1_test_case import d1_test.mock_api.get class TestMockGet(d1_test.d1_test_case.D1TestCase): @responses.activate def test_1000(self, mn_client_v1_v2): """mock_api.get() returns a Requests Response object.""" d1_test.mock_api.get.add_callback(d1_test.d1_test_case.MOCK_MN_BASE_URL) assert isinstance(mn_client_v1_v2.get("test_pid_1"), requests.Response) @responses.activate def test_1010(self, mn_client_v1_v2): """mock_api.get() returns the same content each time for a given PID.""" d1_test.mock_api.get.add_callback(d1_test.d1_test_case.MOCK_MN_BASE_URL) obj_1a_str = mn_client_v1_v2.get("test_pid_1").content obj_2a_str = mn_client_v1_v2.get("test_pid_2").content obj_1b_str = mn_client_v1_v2.get("test_pid_1").content obj_2b_str = mn_client_v1_v2.get("test_pid_2").content assert obj_1a_str == obj_1b_str assert obj_2a_str == obj_2b_str @responses.activate def test_1020(self, mn_client_v1_v2): """mock_api.get(): Redirects.""" d1_test.mock_api.get.add_callback(d1_test.d1_test_case.MOCK_MN_BASE_URL) direct_sciobj_bytes = mn_client_v1_v2.get("test_pid_1").content redirect_sciobj_bytes = mn_client_v1_v2.get( "<REDIRECT:303:3>test_pid_1" ).content assert direct_sciobj_bytes == redirect_sciobj_bytes # @responses.activate # def test_0012(self): # """mock_api.get() returns 1024 bytes""" # obj_str = self.client.get('test_pid_1').content # self.assertEqual(len(obj_str), 1024) # @responses.activate # def test_0013(self): # """mock_api.get(): Passing a trigger header triggers a DataONEException""" # self.assertRaises( # d1_common.types.exceptions.NotAuthorized, self.client.get, 'test_pid', # vendorSpecific={'trigger': '401'} # )
fe69d824ce277807f6d3e0d5eaaff8a66490ae4b
b1bc2e54f8cd35c9abb6fc4adb35b386c12fe6b4
/otp/src/level/ModelEntity.py
5850215d12244dd9e104ca4eebaf6cf5fd012828
[]
no_license
satire6/Anesidora
da3a44e2a49b85252b87b612b435fb4970469583
0e7bfc1fe29fd595df0b982e40f94c30befb1ec7
refs/heads/master
2022-12-16T20:05:13.167119
2020-09-11T16:58:04
2020-09-11T17:02:06
294,751,966
89
32
null
null
null
null
UTF-8
Python
false
false
4,052
py
from toontown.toonbase.ToontownGlobals import * from direct.directnotify import DirectNotifyGlobal import BasicEntities class ModelEntity(BasicEntities.NodePathEntity): LoadFuncs = { 'loadModelCopy': loader.loadModelCopy, 'loadModel': loader.loadModel, 'loadModelOnce': loader.loadModelOnce, } def __init__(self, level, entId): # TODO: fill in default values automatically for missing attribs self.collisionsOnly = False self.loadType = 'loadModelCopy' self.flattenType = 'light' self.goonHatType = 'none' self.entInitialized = False BasicEntities.NodePathEntity.__init__(self, level, entId) self.entInitialized = True self.model = None self.loadModel() def destroy(self): if self.model: self.model.removeNode() del self.model BasicEntities.NodePathEntity.destroy(self) def loadModel(self): if self.model: self.model.removeNode() self.model = None if self.modelPath is None: return self.model = ModelEntity.LoadFuncs[self.loadType](self.modelPath) if self.model: self.model.reparentTo(self) # hide/show as appropriate if self.collisionsOnly: if __dev__: self.model.setTransparency(1) self.model.setColorScale(1,1,1,.1) else: self.model.hide() else: self.model.show() # HACK SDN: special code for moving crate wall collisions down if self.modelPath in ("phase_9/models/cogHQ/woodCrateB.bam", "phase_9/models/cogHQ/metal_crateB.bam", "phase_10/models/cashbotHQ/CBMetalCrate.bam", "phase_10/models/cogHQ/CBMetalCrate2.bam", "phase_10/models/cashbotHQ/CBWoodCrate.bam", "phase_11/models/lawbotHQ/LB_metal_crate.bam", "phase_11/models/lawbotHQ/LB_metal_crate2.bam", ): # get rid of any scales #self.model.flattenLight() # move walls down cNode = self.find("**/wall") cNode.setZ(cNode, -.75) # duplicate the floor and move it down to crate a # catch effect for low-hopped toons colNode = self.find("**/collision") floor = colNode.find("**/floor") floor2 = floor.copyTo(colNode) floor2.setZ(floor2, -.75) """ # incorporate the entity's overall scale self.model.setScale(self.getScale()) self.setScale(1) self.model.flattenLight() """ if self.goonHatType is not 'none': self.goonType = {'hardhat':'pg','security':'sg'}[self.goonHatType] self.hat = self.model ### this was copied from Goon.createHead if self.goonType == "pg": self.hat.find("**/security_hat").hide() elif self.goonType == "sg": self.hat.find("**/hard_hat").hide() ### del self.hat del self.goonType if self.flattenType == 'light': self.model.flattenLight() elif self.flattenType == 'medium': self.model.flattenMedium() elif self.flattenType == 'strong': self.model.flattenStrong() def setModelPath(self, path): self.modelPath = path self.loadModel() def setCollisionsOnly(self, collisionsOnly): self.collisionsOnly = collisionsOnly self.loadModel() def setGoonHatType(self, goonHatType): self.goonHatType = goonHatType self.loadModel()
bb35ccd3ccfc92a049807e3711182d740eb677b8
eab2dc435028b2548554d97b24eb7b7e3576b953
/iblrig/check_sync_pulses.py
b53097729443914a5879f7b454f1900b4316e049
[ "MIT" ]
permissive
k1o0/iblrig
35edd8570215ca591b1f1e26e47439e633aa587a
9177b852b344a9bbc26e4a4aeb5f0182bd8a9b25
refs/heads/master
2021-05-24T12:58:47.552912
2020-02-25T20:19:59
2020-02-25T20:19:59
253,573,669
0
0
MIT
2020-04-06T17:48:28
2020-04-06T17:48:28
null
UTF-8
Python
false
false
2,875
py
#!/usr/bin/env python # -*- coding:utf-8 -*- # @Author: Niccolò Bonacchi # @Date: Monday, February 25th 2019, 2:10:38 pm import logging import sys from pathlib import Path import ibllib.io.raw_data_loaders as raw import matplotlib.pyplot as plt import numpy as np from iblrig.misc import get_port_events log = logging.getLogger("iblrig") def sync_check(tph): events = tph.behavior_data["Events timestamps"] ev_bnc1 = get_port_events(events, name="BNC1") ev_bnc2 = get_port_events(events, name="BNC2") ev_port1 = get_port_events(events, name="Port1") NOT_FOUND = "COULD NOT FIND DATA ON {}" bnc1_msg = NOT_FOUND.format("BNC1") if not ev_bnc1 else "OK" bnc2_msg = NOT_FOUND.format("BNC2") if not ev_bnc2 else "OK" port1_msg = NOT_FOUND.format("Port1") if not ev_port1 else "OK" warn_msg = f""" ########################################## NOT FOUND: SYNC PULSES ########################################## VISUAL STIMULUS SYNC: {bnc1_msg} SOUND SYNC: {bnc2_msg} CAMERA SYNC: {port1_msg} ##########################################""" if not ev_bnc1 or not ev_bnc2 or not ev_port1: log.warning(warn_msg) if __name__ == "__main__": if len(sys.argv) == 1: print("I need a file name...") session_data_file = Path(sys.argv[1]) if not session_data_file.exists(): raise FileNotFoundError(f"{session_data_file}") if session_data_file.name.endswith(".jsonable"): data = raw.load_data(session_data_file.parent.parent) else: try: data = raw.load_data(session_data_file) except Exception: print("Not a file or a valid session folder") unsynced_trial_count = 0 frame2ttl = [] sound = [] camera = [] trial_end = [] for trial_data in data: tevents = trial_data["behavior_data"]["Events timestamps"] ev_bnc1 = get_port_events(tevents, name="BNC1") ev_bnc2 = get_port_events(tevents, name="BNC2") ev_port1 = get_port_events(tevents, name="Port1") if not ev_bnc1 or not ev_bnc2 or not ev_port1: unsynced_trial_count += 1 frame2ttl.extend(ev_bnc1) sound.extend(ev_bnc2) camera.extend(ev_port1) trial_end.append(trial_data["behavior_data"]["Trial end timestamp"]) print(f"Found {unsynced_trial_count} trials with bad sync data") f = plt.figure() # figsize=(19.2, 10.8), dpi=100) ax = plt.subplot2grid((1, 1), (0, 0), rowspan=1, colspan=1) ax.plot(camera, np.ones(len(camera)) * 1, "|") ax.plot(sound, np.ones(len(sound)) * 2, "|") ax.plot(frame2ttl, np.ones(len(frame2ttl)) * 3, "|") [ax.axvline(t, alpha=0.5) for t in trial_end] ax.set_ylim([0, 4]) ax.set_yticks(range(4)) ax.set_yticklabels(["", "camera", "sound", "frame2ttl"]) plt.show()
c43dee062a7499d04b64507171d861b11b09912e
df3c8c521a51f2b412118bd9d0e477da06a3b7cc
/build/view_environments/post_create_/create_post/create_post.py
2a6a13f8a1551a30e01dd4e643e8f14b345f9bfd
[]
no_license
bharatmudragada/fb_post
c30b900731db5844df6b438e5d38a0dfb607412a
c5e7bb185a561bdcfcd7b2e30264554b07106044
refs/heads/master
2020-06-21T04:05:22.296755
2019-07-17T07:48:22
2019-07-17T07:48:22
197,339,717
0
0
null
null
null
null
UTF-8
Python
false
false
1,835
py
from django_swagger_utils.drf_server.decorators.request_response import request_response from django_swagger_utils.drf_server.default.parser_mapping import PARSER_MAPPING from django_swagger_utils.drf_server.default.renderer_mapping import RENDERER_MAPPING from fb_post.build.serializers.definitions.PostContent.PostContentSerializer import PostContentSerializer from fb_post.build.serializers.definitions.PostId.PostIdSerializer import PostIdSerializer options = { 'METHOD': 'POST', 'REQUEST_WRAPPING_REQUIRED': True, 'REQUEST_ENCRYPTION_REQUIRED': False, 'REQUEST_IS_PARTIAL': False, 'PARSER_CLASSES': [ PARSER_MAPPING["application/json"] ], 'RENDERER_CLASSES': [ RENDERER_MAPPING["application/json"] ], 'REQUEST_QUERY_PARAMS_SERIALIZER': None, 'REQUEST_HEADERS_SERIALIZER': None, 'REQUEST_SERIALIZER': PostContentSerializer, 'REQUEST_SERIALIZER_MANY_ITEMS': False, 'RESPONSE': { '201' : { 'RESPONSE_SERIALIZER': PostIdSerializer, 'RESPONSE_SERIALIZER_MANY_ITEMS': False, 'HEADERS_SERIALIZER': None, } , '400' : { 'RESPONSE_SERIALIZER': None, 'RESPONSE_SERIALIZER_MANY_ITEMS': False, 'HEADERS_SERIALIZER': None, } }, "SECURITY":{ "oauth" : [ "write" ] } } app_name = "fb_post" operation_id = "create_post" group_name = "" @request_response(options=options, app_name=app_name, operation_id=operation_id, group_name=group_name) def create_post(request, *args, **kwargs): args = (request,) + args from django_swagger_utils.drf_server.wrappers.view_env_wrapper import view_env_wrapper return view_env_wrapper(app_name, "create_post", group_name, *args, **kwargs)
8608678850cf6031586f8b1bce7e8531244232c5
7869035b72807394154285d307e0597ee16f11d8
/src/data_loader.py
2a23407ac8c03daa931088d7b07b81b5ff04a48b
[]
no_license
tiffany70072/TokenPositioning
cb74edae92e19c16f8ca763935e56b0f2e698b85
a2ab63640a2aff1abfccaa1c1486d8a97026ef0b
refs/heads/master
2022-07-19T11:21:04.716882
2020-04-17T06:02:18
2020-04-17T06:02:18
254,995,440
0
0
null
null
null
null
UTF-8
Python
false
false
2,225
py
import numpy as np import os from sklearn.model_selection import train_test_split def load_data(task, data_name, data_type): if task == "autoenc-last" or task == 'token-posi': assert data_type == "train" or data_type == "valid", "no this data type." data_path = os.path.join("../data", data_name) encoder_data = np.load(os.path.join(data_path, "encoder_%s.npy" % data_type)) decoder_data = np.load(os.path.join(data_path, "decoder_%s.npy" % data_type)) assert encoder_data.shape[0] == decoder_data.shape[0], "data size not match." decoder_output = set_decoder_output_data(decoder_data) return encoder_data, decoder_data, decoder_output else: raise "No this task for load_data." def set_decoder_output_data(decoder_input): # Reshape 2d array into 3d array for Keras training. # Shift one time step because decoder_input and decoder_output are different with one time step. decoder_output = decoder_input.copy() for i in range(len(decoder_output)): decoder_output[i, :-1] = decoder_input[i, 1:] # Remove the first token in decoder output. decoder_output[i, -1] *= 0 decoder_output = np.reshape(decoder_output, [decoder_output.shape[0], decoder_output.shape[1], 1]) return decoder_output """ def cut_validation(self): # TODO: cut training, validation and testing split_result = data_reader.data_split(self.encoder_in, self.decoder_in, self.decoder_out) self.encoder_in = split_result[0] self.decoder_in = split_result[1] self.decoder_out = split_result[2] self.encoder_in_valid = split_result[3][:50000] # TODO: Deal with too many data. self.decoder_in_valid = split_result[4][:50000] self.decoder_out_valid = split_result[5][:50000] self.encoder_in_test = split_result[6] self.decoder_in_test = split_result[7] self.decoder_out_test = split_result[8] self.encoder_in = split_result[0]#[:3000] self.decoder_in = split_result[1]#[:3000] self.decoder_out = split_result[2]#[:3000] print("(Cut validation) training size:", self.encoder_in.shape) print("(Cut validation) validation size:", self.encoder_in_valid.shape) print("(Cut validation) testing size:", self.encoder_in_test.shape) """
84fdc9040b3bcc55c94270233da3cce4c9b669d5
babc56e88a3b5f5038be70ad676d5bd8f1bbf0d2
/wind_direction_byo.py
94bc6600dd5986d16cb2cf6d96ba20ac2a7f7738
[]
no_license
VicenteYago/CustomWeatherStation
873405ca16aa0b6f4f291cbc0068a6ea10aef745
c655f947cca2cd0f8827c18f6f7a7c4c11ef4d43
refs/heads/master
2022-11-13T06:48:05.736830
2020-06-30T00:43:07
2020-06-30T00:43:07
269,812,727
0
0
null
null
null
null
UTF-8
Python
false
false
1,408
py
from gpiozero import MCP3008 import time import math adc = MCP3008(channel=0) count = 0 values = [] volts = [0.4, 1.4, 1.2, 2.8, 2.9, 2.2, 2.5, 1.8, 2.0, 0.7, 0.8, 0.1, 0.3, 0.2, 0.6, 2.7] volts_dic = { 0.4: 0.0, 1.4: 22.5, 1.2: 45.0, 2.8: 67.5, 2.7: 90.5, 2.9: 112.5, 2.2: 135.0, 2.5: 157.5, 1.8: 180.0, 2.0: 202.5, 0.7: 225.0, 0.8: 247.5, 0.1: 270.0, 0.3: 292.5, 0.2: 315.0, 0.6: 337.5 } def get_average(angles): sin_sum = 0.0 cos_sum = 0.0 for angle in angles: r = math.radians(angle) sin_sum += math.sin(r) cos_sum += math.cos(r) flen = float(len(angles)) s = sin_sum / flen c = cos_sum / flen arc = math.degrees(math.atan(s / c)) average = 0.0 if s > 0 and c > 0: average = arc elif c < 0: average = arc + 180 elif s < 0 and c > 0: average = arc + 360 return 0.0 if average == 360 else average def get_value(length = 5): data = [] print("Measuring wind direction for %d seconds..." % length) start_time = time.time() while time.time() - start_time <= length: wind = round(adc.value*3.3,1) if not wind in volts_dic: print("Unknown value :", str(wind)) else: data.append(volts_dic[wind]) return get_average(data) while True: print(get_value())
[ "=" ]
=
b676c5cba48c2e1efd64286543f5f6aadfef51fd
ec0b8bfe19b03e9c3bb13d9cfa9bd328fb9ca3f1
/res/packages/scripts/scripts/common/wotdecorators.py
1554469a75cbd2eab8d57565f8457da484b5051a
[]
no_license
webiumsk/WOT-0.9.20.0
de3d7441c5d442f085c47a89fa58a83f1cd783f2
811cb4e1bca271372a1d837a268b6e0e915368bc
refs/heads/master
2021-01-20T22:11:45.505844
2017-08-29T20:11:38
2017-08-29T20:11:38
101,803,045
0
1
null
null
null
null
WINDOWS-1250
Python
false
false
2,832
py
# 2017.08.29 21:52:48 Střední Evropa (letní čas) # Embedded file name: scripts/common/wotdecorators.py import inspect from functools import update_wrapper from debug_utils import LOG_WRAPPED_CURRENT_EXCEPTION, CRITICAL_ERROR from time_tracking import LOG_TIME_WARNING import time import time_tracking def noexcept(func): def wrapper(*args, **kwArgs): try: return func(*args, **kwArgs) except: LOG_WRAPPED_CURRENT_EXCEPTION(wrapper.__name__, func.__name__, func.func_code.co_filename, func.func_code.co_firstlineno + 1) return wrapper def nofail(func): def wrapper(*args, **kwArgs): try: return func(*args, **kwArgs) except: LOG_WRAPPED_CURRENT_EXCEPTION(wrapper.__name__, func.__name__, func.func_code.co_filename, func.func_code.co_firstlineno + 1) CRITICAL_ERROR('Exception in no-fail code') return wrapper def exposedtoclient(func): def wrapper(*args, **kwArgs): try: lastTick = time.time() result = func(*args, **kwArgs) timeSinceLastTick = time.time() - lastTick if timeSinceLastTick > time_tracking.DEFAULT_TIME_LIMIT: LOG_TIME_WARNING(timeSinceLastTick, context=(getattr(args[0], 'id', 0), func.__name__, args, kwArgs)) return result except: LOG_WRAPPED_CURRENT_EXCEPTION(wrapper.__name__, func.__name__, func.func_code.co_filename, func.func_code.co_firstlineno + 1) return wrapper def singleton(cls): return cls() def decorate(func, dec): argspec = inspect.getargspec(func) name = func.__name__ signature = inspect.formatargspec(*argspec) params = inspect.formatargspec(formatvalue=(lambda value: ''), *argspec) source = 'def %s%s: return __dec%s\n' % (name, signature, params) code = compile(source, '<decorator-gen>', 'single') env = {'__dec': dec} eval(code, env) return update_wrapper(env[name], func) def decorator(dec): def wrapper(func): return decorate(func, dec(func)) return wrapper def condition(attributeName, logFunc = None, logStack = True): def decorator(func): def wrapper(*args, **kwargs): attribute = getattr(args[0], attributeName) if not bool(attribute): if logFunc: logFunc('Method condition failed', args, kwargs, stack=logStack) return return func(*args, **kwargs) return decorate(func, wrapper) return decorator # okay decompyling c:\Users\PC\wotmods\files\originals\res\packages\scripts\scripts\common\wotdecorators.pyc # decompiled 1 files: 1 okay, 0 failed, 0 verify failed # 2017.08.29 21:52:48 Střední Evropa (letní čas)
218046a18f59c8cc6a566f6a16807e74d5250298
a4e502e9487cf17c53f9f931ec0dbc12168fea52
/packages/pyre/platforms/PackageManager.py
0877270914d7a2f1326787f57abfbb1ac0125b31
[ "BSD-3-Clause" ]
permissive
bryanvriel/pyre
bdc5dd59c46d53ff81f2ece532b9073ac3b65be1
179359634a7091979cced427b6133dd0ec4726ea
refs/heads/master
2021-09-28T00:10:26.454282
2018-11-11T16:42:07
2018-11-11T16:42:07
null
0
0
null
null
null
null
UTF-8
Python
false
false
2,373
py
# -*- coding: utf-8 -*- # # michael a.g. aïvázis # orthologue # (c) 1998-2018 all rights reserved # # the framework import pyre # declaration class PackageManager(pyre.protocol, family='pyre.platforms.packagers'): """ Encapsulation of host specific information """ # requirements @pyre.provides def prefix(self): """ The package manager install location """ @pyre.provides def installed(self): """ Retrieve available information for all installed packages """ @pyre.provides def packages(self, category): """ Provide a sequence of package names that provide compatible installations for the given package {category}. If the package manager provides a way for the user to select a specific installation as the default, care should be taken to rank the sequence appropriately. """ @pyre.provides def info(self, package): """ Return information about the given {package} The type of information returned is determined by the package manager. This method should return success if and only if {package} is actually fully installed. """ @pyre.provides def contents(self, package): """ Generate a sequence of the contents of {package} The type of information returned is determined by the package manager. Typically, it contains the list of files that are installed by this package, but it may contain other filesystem entities as well. This method should return a non-empty sequence if and only if {pakage} is actually fully installed """ @pyre.provides def configure(self, packageInstance): """ Dispatch to the {packageInstance} configuration procedure that is specific to the particular implementation of this protocol """ # framework obligations @classmethod def pyre_default(cls, **kwds): """ Build the preferred host implementation """ # the host should specify a sensible default; if there is nothing there, this is an # unmanaged system that relies on environment variables and standard locations from .Bare import Bare # return the support for unmanaged systems return Bare # end of file
68caed12611a8b789a1964a22fb49575eca70c7f
76d388b5d2e74ff0eda748c7868fadf0704cf700
/tensorpack/utils/develop.py
496de1dd245db766c3e4ba256ddb638d5e621b48
[ "Apache-2.0" ]
permissive
jooyounghun/tensorpack
eebf0867e5a82ffd52660dccfbd34879b8d0f5af
90cdae380c40a1e91f627520c4a739bd6ee3f18b
refs/heads/master
2020-03-23T23:24:41.651089
2018-07-27T02:57:19
2018-07-27T02:57:19
142,232,523
1
0
Apache-2.0
2018-07-25T01:45:06
2018-07-25T01:45:05
null
UTF-8
Python
false
false
4,773
py
# -*- coding: utf-8 -*- # File: develop.py # Author: tensorpack contributors """ Utilities for developers only. These are not visible to users (not automatically imported). And should not appeared in docs.""" import os import functools from datetime import datetime import importlib import types import six from . import logger def create_dummy_class(klass, dependency): """ When a dependency of a class is not available, create a dummy class which throws ImportError when used. Args: klass (str): name of the class. dependency (str): name of the dependency. Returns: class: a class object """ class _DummyMetaClass(type): # throw error on class attribute access def __getattr__(_, __): raise ImportError("Cannot import '{}', therefore '{}' is not available".format(dependency, klass)) @six.add_metaclass(_DummyMetaClass) class _Dummy(object): # throw error on constructor def __init__(self, *args, **kwargs): raise ImportError("Cannot import '{}', therefore '{}' is not available".format(dependency, klass)) return _Dummy def create_dummy_func(func, dependency): """ When a dependency of a function is not available, create a dummy function which throws ImportError when used. Args: func (str): name of the function. dependency (str or list[str]): name(s) of the dependency. Returns: function: a function object """ if isinstance(dependency, (list, tuple)): dependency = ','.join(dependency) def _dummy(*args, **kwargs): raise ImportError("Cannot import '{}', therefore '{}' is not available".format(dependency, func)) return _dummy def building_rtfd(): """ Returns: bool: if tensorpack is being imported to generate docs now. """ return os.environ.get('READTHEDOCS') == 'True' \ or os.environ.get('DOC_BUILDING') def log_deprecated(name="", text="", eos=""): """ Log deprecation warning. Args: name (str): name of the deprecated item. text (str, optional): information about the deprecation. eos (str, optional): end of service date such as "YYYY-MM-DD". """ assert name or text if eos: eos = "after " + datetime(*map(int, eos.split("-"))).strftime("%d %b") if name: if eos: warn_msg = "%s will be deprecated %s. %s" % (name, eos, text) else: warn_msg = "%s was deprecated. %s" % (name, text) else: warn_msg = text if eos: warn_msg += " Legacy period ends %s" % eos logger.warn("[Deprecated] " + warn_msg) def deprecated(text="", eos=""): """ Args: text, eos: same as :func:`log_deprecated`. Returns: a decorator which deprecates the function. Example: .. code-block:: python @deprecated("Explanation of what to do instead.", "2017-11-4") def foo(...): pass """ def get_location(): import inspect frame = inspect.currentframe() if frame: callstack = inspect.getouterframes(frame)[-1] return '%s:%i' % (callstack[1], callstack[2]) else: stack = inspect.stack(0) entry = stack[2] return '%s:%i' % (entry[1], entry[2]) def deprecated_inner(func): @functools.wraps(func) def new_func(*args, **kwargs): name = "{} [{}]".format(func.__name__, get_location()) log_deprecated(name, text, eos) return func(*args, **kwargs) return new_func return deprecated_inner def HIDE_DOC(func): func.__HIDE_SPHINX_DOC__ = True return func # Copied from https://github.com/tensorflow/tensorflow/blob/master/tensorflow/python/util/lazy_loader.py class LazyLoader(types.ModuleType): def __init__(self, local_name, parent_module_globals, name): self._local_name = local_name self._parent_module_globals = parent_module_globals super(LazyLoader, self).__init__(name) def _load(self): # Import the target module and insert it into the parent's namespace module = importlib.import_module(self.__name__) self._parent_module_globals[self._local_name] = module # Update this object's dict so that if someone keeps a reference to the # LazyLoader, lookups are efficient (__getattr__ is only called on lookups # that fail). self.__dict__.update(module.__dict__) return module def __getattr__(self, item): module = self._load() return getattr(module, item) def __dir__(self): module = self._load() return dir(module)
bcded7ca3347b631cb06ccb49aa49c5ef2291909
6cb18c62758bfbf783d3fabe851d1c4d9f323483
/setup.py
9319f44e05f51de89cc40224949e07be98a9e018
[ "MIT" ]
permissive
bruinxiong/performer-pytorch
68e505ff5e59d35e339b23661feef377795fd2df
c368b5e4efd46f72e2abaa655dc813021f911014
refs/heads/main
2023-01-04T02:25:42.898296
2020-10-26T22:41:09
2020-10-26T22:41:09
null
0
0
null
null
null
null
UTF-8
Python
false
false
815
py
from setuptools import setup, find_packages setup( name = 'performer-pytorch', packages = find_packages(exclude=['examples']), version = '0.1.4', license='MIT', description = 'Performer - Pytorch', author = 'Phil Wang', author_email = '[email protected]', url = 'https://github.com/lucidrains/performer-pytorch', keywords = [ 'artificial intelligence', 'attention mechanism', 'efficient attention', 'transformers' ], install_requires=[ 'pytorch-fast-transformers>=0.3.0', 'torch>=1.6', 'einops>=0.3' ], classifiers=[ 'Development Status :: 4 - Beta', 'Intended Audience :: Developers', 'Topic :: Scientific/Engineering :: Artificial Intelligence', 'License :: OSI Approved :: MIT License', 'Programming Language :: Python :: 3.6', ], )
a4c71809c35378bb39dbbce97d55d2a122ab4dcd
f51c6d0cebb27c377ce9830deec4b727b9b2ee90
/AI/05_tictactoe/02grid_plot.py
b2fb6cbc7f65ddac4fc048c6664f6bdd82dfb227
[]
no_license
dbbudd/Python-Experiments
1c3c1322583aaaf2016a2f2f3061e6d034c5d1c8
b6d294bf11a5c92b8578d16aa2f63cc27fc47b07
refs/heads/master
2020-04-17T02:21:36.693593
2019-01-17T00:18:34
2019-01-17T00:18:34
166,130,283
1
0
null
null
null
null
UTF-8
Python
false
false
1,098
py
#!/usr/bin/env python import numpy as np import itertools import matplotlib import matplotlib.pyplot as plt import matplotlib.patches as mpatches class gameboard(object): def __init__(self): #player 1 puts a "X", player 2 puts a "O" self.g = [[1,0,1],[0,0,2],[0,2,0]] self.grid = np.array(self.g) print(self.grid) def drawGrid(self): fig = plt.figure() ax = fig.add_subplot(111, xlim=(0,3), ylim = (0,3)) self.myCells = [(0,0),(0,1),(0,2),(1,0),(1,1),(1,2),(2,0),(2,1),(2,2)] for i in self.myCells: if self.grid[i] == 1: cell = mpatches.Rectangle((i), 1, 1, alpha=1, facecolor="red") ax.add_patch(cell) elif self.grid[i] == 2: cell = mpatches.Rectangle((i), 1, 1, alpha=1, facecolor="blue") ax.add_patch(cell) else: cell = mpatches.Rectangle((i), 1, 1, alpha=1, facecolor="none") ax.add_patch(cell) plt.show() board = gameboard() board.drawGrid()
1697ff12097d074fe9a08b7e8cfbf1ecd1348016
cca89a7bbe2da907a38eb00e9a083f57597273f0
/162. 寻找峰值/pythonCode.py
ecfc5d414241c3d0b4d2b4aac3531e9ced628696
[]
no_license
xerprobe/LeetCodeAnswer
cc87941ef2a25c6aa1366e7a64480dbd72750670
ea1822870f15bdb1a828a63569368b7cd10c6ab8
refs/heads/master
2022-09-23T09:15:42.628793
2020-06-06T16:29:59
2020-06-06T16:29:59
270,215,362
0
0
null
null
null
null
UTF-8
Python
false
false
1,154
py
from typing import List class Solution: def findPeakElement(self, nums: List[int]) -> int: def binarySearch(l:int,r:int) -> int: if(l == r): return l mid = (l + r) // 2 if(nums[mid] > nums[mid + 1]): return binarySearch(l,mid) else: return binarySearch(mid+1,r) return binarySearch(0,len(nums)-1) # 峰值元素是指其值大于左右相邻值的元素。 # 给定一个输入数组 nums,其中 nums[i] ≠ nums[i+1],找到峰值元素并返回其索引。 # 数组可能包含多个峰值,在这种情况下,返回任何一个峰值所在位置即可。 # 你可以假设 nums[-1] = nums[n] = -∞。 # 示例 1: # 输入: nums = [1,2,3,1] # 输出: 2 # 解释: 3 是峰值元素,你的函数应该返回其索引 2。 # 示例 2: # 输入: nums = [1,2,1,3,5,6,4] # 输出: 1 或 5 # 解释: 你的函数可以返回索引 1,其峰值元素为 2; # 或者返回索引 5, 其峰值元素为 6。 # 说明: # 你的解法应该是 O(logN) 时间复杂度的。 # 链接:https://leetcode-cn.com/problems/find-peak-element/
96eb58da2807780f7f78eb49453cd03e2e4a57bb
33f30925224a7db3e3bf6948c6c569ad850e9c76
/Server/bin/rst2xml.py
6a7fab179644d60c2959331900cdea30a7350337
[]
no_license
duelle/CTT
2bc64fffaf4b2eb3976fedd7aea231a51da8fbe9
e2da2ab9c599833cc8409728b456a9e37825986b
refs/heads/master
2022-04-06T15:25:06.747919
2020-02-19T14:04:37
2020-02-19T14:04:37
237,939,126
0
0
null
null
null
null
UTF-8
Python
false
false
642
py
#!/home/duelle/Repositories/git/RadonCTT/Server/bin/python # $Id: rst2xml.py 4564 2006-05-21 20:44:42Z wiemann $ # Author: David Goodger <[email protected]> # Copyright: This module has been placed in the public domain. """ A minimal front end to the Docutils Publisher, producing Docutils XML. """ try: import locale locale.setlocale(locale.LC_ALL, '') except: pass from docutils.core import publish_cmdline, default_description description = ('Generates Docutils-native XML from standalone ' 'reStructuredText sources. ' + default_description) publish_cmdline(writer_name='xml', description=description)
eba5e24cb7ae539f05831d88b27d99b2346a8f0a
ec9129d3eb1880df9f0b54c76510352a7e004b0c
/tools/make_vps_tarball.py
b03537feaa59ec1a6a93c522cfd621963bf12eba
[]
no_license
eugen-don/vps
4057e6ddb1db274dbd8d78fa926376cfc3a40aa7
6a16569868241b35d8137b7f2b2f8db0cf67ff55
refs/heads/master
2021-01-11T16:29:53.109075
2014-05-14T09:20:33
2014-05-14T09:20:33
null
0
0
null
null
null
null
UTF-8
Python
false
false
771
py
#!/usr/bin/env python import sys import os import _env import ops.os_init as os_init import conf assert conf.OS_IMAGE_DIR and os.path.isdir(conf.OS_IMAGE_DIR) def usage(): print """usage: \n%s [image_path/partion_path] [tarball_dir] """ % (sys.argv[0]) def main(): if len(sys.argv) < 3: usage() os._exit(0) img_path = sys.argv[1] tarball_dir = sys.argv[2] if not os.path.exists(img_path): print "%s not exists" % (img_path) os._exit(1) if not os.path.isdir(tarball_dir): print '%s is not a directory' % (tarball_dir) os._exit(1) tarball_path = os_init.pack_vps_fs_tarball(img_path, tarball_dir) print "%s packed in %s" % (img_path, tarball_path) if "__main__" == __name__: main()
f716de44a80a10f01bfaa8b3a8d58b4ec092c945
dbe1f4110921a08cb13e22ea325d503bd5627195
/chuhuo_2.71/bluedon/monitor/sbin/checkproc.py
cd3521785adb14ce48baf65ec961b05655ab0e50
[]
no_license
Hehouhua/waf_branches
92dc1b1cbecba20f24ef6c7372dde7caa43f9158
ca76f3a1ed8150b423474c9e37aee37841a5ee35
refs/heads/main
2023-01-07T11:33:31.667688
2020-11-03T06:58:33
2020-11-03T06:58:33
null
0
0
null
null
null
null
UTF-8
Python
false
false
1,048
py
import os, re, sys rexplogstart = re.compile(r'grep logstart.pl') rexpwebvisit = re.compile(r'grep webvisit.pl') def checklogstart(): if not os.path.exists("/usr/local/bdwaf/logs_bridge/data"): os.popen("mkdir -p /usr/local/bdwaf/logs_bridge/data") if not os.path.exists("/usr/local/bdwaf/logs_proxy/data"): os.popen("mkdir -p /usr/local/bdwaf/logs_proxy/data") flag = 0 pfp = os.popen('ps ax | grep logstart.pl') lines = pfp.readlines() for line in lines: match = rexplogstart.search(line) if match: flag += 1 if flag >= len(lines): os.system('/usr/local/bluedon/monitor/sbin/logstart.pl') def checkwebvisit(): flag = 0 pfp = os.popen('ps ax | grep webvisit.pl') lines = pfp.readlines() for line in lines: match = rexplogstart.search(line) if match: flag += 1 if flag >= len(lines): os.system('/usr/local/bluedon/monitor/sbin/webvisit.pl') if __name__ == '__main__': checklogstart() checkwebvisit()
dc95cfc1d53773ef74245ed5c8a5b6bbbf3ce933
65e076e4fcc00a67faa0932b3f3a3d3a3a11e2aa
/sdk/python/pulumi_google_native/datastore/v1/_enums.py
15df09472641b2ebbeb23bd87aeab08fb357fbf9
[ "Apache-2.0", "BSD-3-Clause" ]
permissive
TheJaySmith-Google/pulumi-google-native
816babe5c7316724e02d5b8b9d789df00262bb8e
566c295a39fe8c3dd16e4a7894ff6de72423e5da
refs/heads/master
2023-06-05T06:45:19.979837
2021-06-23T11:42:27
2021-06-23T11:42:27
null
0
0
null
null
null
null
UTF-8
Python
false
false
801
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! *** from enum import Enum __all__ = [ 'GoogleDatastoreAdminV1IndexedPropertyDirection', 'IndexAncestor', ] class GoogleDatastoreAdminV1IndexedPropertyDirection(str, Enum): """ Required. The indexed property's direction. Must not be DIRECTION_UNSPECIFIED. """ DIRECTION_UNSPECIFIED = "DIRECTION_UNSPECIFIED" ASCENDING = "ASCENDING" DESCENDING = "DESCENDING" class IndexAncestor(str, Enum): """ Required. The index's ancestor mode. Must not be ANCESTOR_MODE_UNSPECIFIED. """ ANCESTOR_MODE_UNSPECIFIED = "ANCESTOR_MODE_UNSPECIFIED" NONE = "NONE" ALL_ANCESTORS = "ALL_ANCESTORS"
cef9a68afdddd61d9d2c7d5510d7a38174bc8f1c
4b68243d9db908945ee500174a8a12be27d150f9
/pogoprotos/networking/requests/messages/update_fitness_metrics_message_pb2.py
522382d168f4fe3adab53afbb40fe730c7070bd9
[]
no_license
ykram/pogoprotos-py
7285c86498f57dcbbec8e6c947597e82b2518d80
a045b0140740625d9a19ded53ece385a16c4ad4a
refs/heads/master
2020-04-20T10:19:51.628964
2019-02-02T02:58:03
2019-02-02T02:58:03
168,787,721
0
0
null
null
null
null
UTF-8
Python
false
true
2,937
py
# Generated by the protocol buffer compiler. DO NOT EDIT! # source: pogoprotos/networking/requests/messages/update_fitness_metrics_message.proto import sys _b=sys.version_info[0]<3 and (lambda x:x) or (lambda x:x.encode('latin1')) from google.protobuf import descriptor as _descriptor from google.protobuf import message as _message from google.protobuf import reflection as _reflection from google.protobuf import symbol_database as _symbol_database from google.protobuf import descriptor_pb2 # @@protoc_insertion_point(imports) _sym_db = _symbol_database.Default() from pogoprotos.data.fitness import fitness_sample_pb2 as pogoprotos_dot_data_dot_fitness_dot_fitness__sample__pb2 DESCRIPTOR = _descriptor.FileDescriptor( name='pogoprotos/networking/requests/messages/update_fitness_metrics_message.proto', package='pogoprotos.networking.requests.messages', syntax='proto3', serialized_pb=_b('\nLpogoprotos/networking/requests/messages/update_fitness_metrics_message.proto\x12\'pogoprotos.networking.requests.messages\x1a,pogoprotos/data/fitness/fitness_sample.proto\"^\n\x1bUpdateFitnessMetricsMessage\x12?\n\x0f\x66itness_samples\x18\x01 \x03(\x0b\x32&.pogoprotos.data.fitness.FitnessSampleb\x06proto3') , dependencies=[pogoprotos_dot_data_dot_fitness_dot_fitness__sample__pb2.DESCRIPTOR,]) _UPDATEFITNESSMETRICSMESSAGE = _descriptor.Descriptor( name='UpdateFitnessMetricsMessage', full_name='pogoprotos.networking.requests.messages.UpdateFitnessMetricsMessage', filename=None, file=DESCRIPTOR, containing_type=None, fields=[ _descriptor.FieldDescriptor( name='fitness_samples', full_name='pogoprotos.networking.requests.messages.UpdateFitnessMetricsMessage.fitness_samples', index=0, number=1, type=11, cpp_type=10, label=3, has_default_value=False, default_value=[], message_type=None, enum_type=None, containing_type=None, is_extension=False, extension_scope=None, options=None), ], extensions=[ ], nested_types=[], enum_types=[ ], options=None, is_extendable=False, syntax='proto3', extension_ranges=[], oneofs=[ ], serialized_start=167, serialized_end=261, ) _UPDATEFITNESSMETRICSMESSAGE.fields_by_name['fitness_samples'].message_type = pogoprotos_dot_data_dot_fitness_dot_fitness__sample__pb2._FITNESSSAMPLE DESCRIPTOR.message_types_by_name['UpdateFitnessMetricsMessage'] = _UPDATEFITNESSMETRICSMESSAGE _sym_db.RegisterFileDescriptor(DESCRIPTOR) UpdateFitnessMetricsMessage = _reflection.GeneratedProtocolMessageType('UpdateFitnessMetricsMessage', (_message.Message,), dict( DESCRIPTOR = _UPDATEFITNESSMETRICSMESSAGE, __module__ = 'pogoprotos.networking.requests.messages.update_fitness_metrics_message_pb2' # @@protoc_insertion_point(class_scope:pogoprotos.networking.requests.messages.UpdateFitnessMetricsMessage) )) _sym_db.RegisterMessage(UpdateFitnessMetricsMessage) # @@protoc_insertion_point(module_scope)
22ffc7c4ae1f6b16b2ece3c70722f0a2d0ec48c5
163bbb4e0920dedd5941e3edfb2d8706ba75627d
/Code/CodeRecords/2480/59018/262642.py
80da0919c460c290863470859367203af1d15933
[]
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
281
py
def even_odd(N,a): b=[] for j in a: if j%2==0: b.append(j) a.pop(j) c=b+a return c T=int(input()) for i in range(T): N=int(input()) info=input().split(' ') a=[int(y) for y in info] print(even_odd(N,a))
66e5e2cd1dd250b00922b3b3211b1c0c1c510d35
53565e19de1d345552f5f469f4e4ea311a421bb8
/app/artist/models/artist.py
de30a6078bcfde1cf589a711184a2c568c8bfd52
[]
no_license
standbyme227/fc-melon
18e17aa8b85906a62e1631e54a70ff85d72ea435
8f0f4d40021f75a025e91fa6aebea143bccb6ce3
refs/heads/master
2021-05-03T18:59:13.495171
2018-03-20T02:32:02
2018-03-20T02:32:02
120,418,135
0
0
null
null
null
null
UTF-8
Python
false
false
4,632
py
from django.conf import settings from django.db import models from django.forms import model_to_dict from django.http import JsonResponse, HttpResponse from .artist_youtube import ArtistYouTube from .managers import ArtistManager __all__ = ( 'Artist', ) class Artist(models.Model): BLOOD_TYPE_A = 'a' BLOOD_TYPE_B = 'b' BLOOD_TYPE_O = 'o' BLOOD_TYPE_AB = 'c' BLOOD_TYPE_OTHER = 'x' CHOICES_BLOOD_TYPE = ( (BLOOD_TYPE_A, 'A형'), (BLOOD_TYPE_B, 'B형'), (BLOOD_TYPE_O, 'O형'), (BLOOD_TYPE_AB, 'AB형'), (BLOOD_TYPE_OTHER, '기타'), ) melon_id = models.CharField('멜론 Artist ID', max_length=20, blank=True, null=True, unique=True) image = models.ImageField('프로필 이미지', upload_to='artist', blank=True) # upload_to는 media폴더를 기준으로 그안의 경로를 지정 name = models.CharField('이름', max_length=50, ) real_name = models.CharField('본명', max_length=30, blank=True, default='') nationality = models.CharField('국적', max_length=50, blank=True, ) birth_date = models.DateField(max_length=50, blank=True, null=True, ) constellation = models.CharField('별자리', max_length=30, blank=True, null=True) blood_type = models.CharField('혈액형', max_length=50, blank=True, choices=CHOICES_BLOOD_TYPE) # choices를 넣어야지만 위의 선택을 이용할 수 있다. intro = models.TextField('소개', blank=True) # likes = models.IntegerField(default=0) like_users = models.ManyToManyField( settings.AUTH_USER_MODEL, through='ArtistLike', related_name='like_artists', blank=True, ) youtube_videos = models.ManyToManyField( ArtistYouTube, related_name='artists', blank=True, ) objects = ArtistManager() def __str__(self): return self.name def toggle_like_user(self, user): # 자신이 'artist이며 user가 주어진 user인 ArtistLike를 가져오거나 없으면 생성 like, like_created = self.like_user_info_list.get_or_create(user=user) # 만약 이미 잇엇을 경우 (새로 생성 X) if not like_created: # Like를 지워줌 like.delete() # 생성여부를 반환 return like_created # if self.like_users.filter(user=user).exists(): # self.like_users.filter(user).delete() # else: # self.like_users.create(user=user) # # 자신이 artist이며, 주어진 user와의 ArtistLike의 QuerySet # query = ArtistLike.objects.filter(artist=self, user=user) # # QuerySet이 존재할 졍우 # if query.exists(): # query.delete() # return False # # QuerySet이 존재하지 않을 경우 # else: # ArtistLike.objects.create(artist=self, user=user) # return True def to_json(self): from django.db.models.fields.files import FieldFile from django.contrib.auth import get_user_model user_class = get_user_model() ret = model_to_dict(self) # model_to_dict의 결과가 dict # 해당 dict의 item을 순회하며 # JSON Serialize할때 에러나는 타입의 value를 # 적절히 변환해서 value에 다시 대입 def convert_value(value): if isinstance(value, FieldFile): return value.url if value else None elif isinstance(value, user_class): return value.pk elif isinstance(value, ArtistYouTube): return value.pk return value def convert_obj(obj): """ 객체 또는 컨테이너 객체에 포함된 객체들 중 직렬화가 불가능한 객체를 가능하도록 형태를 변환해주는 함수 :param obj: :return: convert_value()를 거친 객체 """ if isinstance(obj, list): # list타입일 경우 각 항목을 순회하며 index에 해당하는 값을 변환 for index, item in enumerate(obj): obj[index] = convert_obj(item) elif isinstance(obj, dict): # dict타입일 경우 각 항목을 순회하며 key에 해당하는 값을 변환 for key, value in obj.items(): obj[key] = convert_obj(value) # list나 dict가 아닐 경우, 객체 자체를 변환한 값을 리턴 return convert_value(obj) convert_obj(ret) return ret
ac071ec7c195c0c7838f31cdd9f41fe37a46ad9c
a44a9279258ace54be0ea6d410e6ddb5a2d72bcb
/project-addons/custom_reports/models/product.py
719faf154fd24aa8c981b08a03877ad3b5b456aa
[]
no_license
athlontado/PXGO_00064_2014_PHA
346f33185a07c2e1766a7cc79cd300252d9b2480
3086baba490e47a5dcc7942c7c5fee9fc047ddcd
refs/heads/master
2020-04-06T03:56:15.828784
2016-04-18T12:24:53
2016-04-18T12:24:53
59,216,028
0
0
null
2016-05-19T14:50:54
2016-05-19T14:50:54
null
UTF-8
Python
false
false
1,240
py
# -*- coding: utf-8 -*- ############################################################################## # # Copyright (C) 2016 Pharmadus. All Rights Reserved # $Óscar Salvador <[email protected]>$ # # This program is free software: you can redistribute it and/or modify # it under the terms of the GNU Affero General Public License as published # by the Free Software Foundation, either version 3 of the License, or # (at your option) any later version. # # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU Affero General Public License for more details. # # You should have received a copy of the GNU Affero General Public License # along with this program. If not, see <http://www.gnu.org/licenses/>. # ############################################################################## from openerp import fields, models class ProductCategory(models.Model): _inherit = 'product.category' commissions_parent_category = fields.Boolean('Commissions parent category', default=False)
2b2a54641d5f56d801a5a0f1798713935087ef28
09e5cfe06e437989a2ccf2aeecb9c73eb998a36c
/modules/cctbx_project/simtbx/run_tests.py
5c3244e65192c78f2e1b57410133b5e40024a0a5
[ "BSD-3-Clause", "BSD-3-Clause-LBNL" ]
permissive
jorgediazjr/dials-dev20191018
b81b19653624cee39207b7cefb8dfcb2e99b79eb
77d66c719b5746f37af51ad593e2941ed6fbba17
refs/heads/master
2020-08-21T02:48:54.719532
2020-01-25T01:41:37
2020-01-25T01:41:37
216,089,955
0
1
BSD-3-Clause
2020-01-25T01:41:39
2019-10-18T19:03:17
Python
UTF-8
Python
false
false
468
py
from __future__ import absolute_import, division, print_function from libtbx import test_utils import libtbx.load_env tst_list = ( "$D/nanoBragg/tst_nanoBragg_minimal.py", "$D/nanoBragg/tst_nanoBragg_mosaic.py", "$D/nanoBragg/tst_gaussian_mosaicity.py", ) def run(): build_dir = libtbx.env.under_build("simtbx") dist_dir = libtbx.env.dist_path("simtbx") test_utils.run_tests(build_dir, dist_dir, tst_list) if (__name__ == "__main__"): run()
80d457fe0e0df539d494873fa3d8e41ce774ae0b
487ce91881032c1de16e35ed8bc187d6034205f7
/codes/CodeJamCrawler/16_0_1/palemale/a.py
f78d73ef5adea50522114802f390513ce3e2cfff
[]
no_license
DaHuO/Supergraph
9cd26d8c5a081803015d93cf5f2674009e92ef7e
c88059dc66297af577ad2b8afa4e0ac0ad622915
refs/heads/master
2021-06-14T16:07:52.405091
2016-08-21T13:39:13
2016-08-21T13:39:13
49,829,508
2
0
null
2021-03-19T21:55:46
2016-01-17T18:23:00
Python
UTF-8
Python
false
false
810
py
import os, sys with open(sys.argv[1], 'r') as infile: N = int(infile.readline().strip()) for x in xrange(1, N+1): T = infile.readline().strip() cases = set(list(T)) intT = int(T) current = intT count = 2 stablecount = 0 while len(cases) < 10: current = count*intT count += 1 cur_num = len(cases) cases.update(list(str(current))) if cur_num == len(cases): stablecount += 1 else: stablecount = 0 if stablecount > 100: current = 'INSOMNIA' break if isinstance(current, int): current = str(current) print "Case #%s: %s" % (x, current)
0bf9f14a7d8f3b313cb14ebe38a4ae36709d9164
92237641f61e9b35ff6af6294153a75074757bec
/Algorithm/programmers/lv2/lv2_짝지어 제거하기.py
dc49c17ce25e718214f85eb4831fb672b343a239
[]
no_license
taepd/study
8ded115765c4f804813e255d9272b727bf41ec80
846d3f2a5a4100225b750f00f992a640e9287d9c
refs/heads/master
2023-03-08T13:56:57.366577
2022-05-08T15:24:35
2022-05-08T15:24:35
245,838,600
0
1
null
2023-03-05T23:54:41
2020-03-08T15:25:15
JavaScript
UTF-8
Python
false
false
278
py
def solution(s): stack = [] for e in s: if not stack: stack.append(e) else: if stack[-1] == e: stack.pop() else: stack.append(e) if stack: return 0 else: return 1
69b384952afa18b41fb769869d637c21f4a61bbb
2075052d028ed31a30bdb9acb0a2022c2634f52b
/chat/consumers.py
761dd8369a35c0e33e7d8ef65e1ce163904ade18
[]
no_license
igoo-Y/live_chat_app
b67704caa2e5944b131a4299716e501b555985b5
d65c87a35d3f3a120da35290addb798e412dad72
refs/heads/main
2023-06-30T13:21:49.860265
2021-08-03T09:11:29
2021-08-03T09:11:29
392,256,262
0
0
null
null
null
null
UTF-8
Python
false
false
1,140
py
import json from channels.generic.websocket import AsyncWebsocketConsumer class ChatConsumer(AsyncWebsocketConsumer): async def connect(self): self.room_name = self.scope["url_route"]["kwargs"]["room_name"] self.room_group_name = "chat_%s" % self.room_name # Join room group await self.channel_layer.group_add(self.room_group_name, self.channel_name) await self.accept() async def disconnect(self, close_code): # Leave room group await self.channel_layer.group_discard(self.room_group_name, self.channel_name) # Receive message from WebSocket async def receive(self, text_data): text_data_json = json.loads(text_data) message = text_data_json["message"] # Send message to room group await self.channel_layer.group_send( self.room_group_name, {"type": "chat_message", "message": message} ) # Receive message from room group async def chat_message(self, event): message = event["message"] # Send message to WebSocket await self.send(text_data=json.dumps({"message": message}))
aa41fbd83ac1923d6fda08de4cc8f3ebd55904e0
90390ddcc21d2f2c0dd5ee3c0e7a3d8d61be9638
/wsgi/app/forms.py
4141cbb7183fc430344eb1bf806ca44a244d8598
[ "MIT" ]
permissive
pjamesjoyce/lcoptview_legacy
b27926e31c16f1fca07c6294e66d706fcb600682
e0ebeb155d6f62d8619d33cf48db98bab8b7a4cd
refs/heads/master
2021-07-16T11:38:58.451239
2017-09-26T10:43:50
2017-09-26T10:43:50
107,691,179
0
0
null
null
null
null
UTF-8
Python
false
false
615
py
from flask_wtf import FlaskForm from wtforms import TextField, PasswordField from wtforms.validators import DataRequired class LoginForm(FlaskForm): login_data = TextField('username or email', validators=[DataRequired()]) password = PasswordField('password', validators=[DataRequired()]) class RegistrationForm(FlaskForm): username = TextField('username', validators=[DataRequired()]) email = TextField('email', validators=[DataRequired()]) password = PasswordField('password', validators=[DataRequired()]) password_repeat = PasswordField('repeat password', validators=[DataRequired()])
3823340ea644b2feec0858721dad3a7c2d67d330
1b597dd7630f9a3023faf557e383b0fae703e72b
/test_autogalaxy/unit/aggregator/test_aggregator.py
40b7acd97191da8084e06012b80ef34395849c57
[ "MIT" ]
permissive
knut0815/PyAutoGalaxy
96e9dfc558182169c41e19d3297cdf46b42d5f77
cc2bc0db5080a278ba7519f94d2a8b2468141e2d
refs/heads/master
2023-03-05T00:59:51.594715
2021-02-09T18:21:30
2021-02-09T18:21:30
null
0
0
null
null
null
null
UTF-8
Python
false
false
7,428
py
from os import path import pytest import autofit as af import autogalaxy as ag from autogalaxy.mock import mock directory = path.dirname(path.realpath(__file__)) @pytest.fixture(name="path") def make_path(): return path.join("{}".format(path.dirname(path.realpath(__file__))), "files") @pytest.fixture(name="samples") def make_samples(): galaxy_0 = ag.Galaxy(redshift=0.5, light=ag.lp.EllipticalSersic(centre=(0.0, 1.0))) galaxy_1 = ag.Galaxy(redshift=1.0, light=ag.lp.EllipticalSersic()) plane = ag.Plane(galaxies=[galaxy_0, galaxy_1]) return mock.MockSamples(max_log_likelihood_instance=plane) def test__dataset_generator_from_aggregator(imaging_7x7, mask_7x7, samples): phase_imaging_7x7 = ag.PhaseImaging( galaxies=dict( galaxy=ag.GalaxyModel(redshift=0.5, light=ag.lp.EllipticalSersic), source=ag.GalaxyModel(redshift=1.0, light=ag.lp.EllipticalSersic), ), search=mock.MockSearch(samples=samples, name="test_phase_aggregator"), ) imaging_7x7.positions = ag.Grid2DIrregular([[1.0, 1.0], [2.0, 2.0]]) phase_imaging_7x7.run( dataset=imaging_7x7, mask=mask_7x7, results=mock.MockResults(samples=samples) ) agg = af.Aggregator(directory=phase_imaging_7x7.paths.output_path) dataset = list(agg.values("dataset")) print(dataset) def test__plane_generator_from_aggregator(imaging_7x7, mask_7x7, samples): phase_imaging_7x7 = ag.PhaseImaging( galaxies=dict( galaxy=ag.GalaxyModel(redshift=0.5, light=ag.lp.EllipticalSersic), source=ag.GalaxyModel(redshift=1.0, light=ag.lp.EllipticalSersic), ), search=mock.MockSearch(samples=samples, name="test_phase_aggregator"), ) phase_imaging_7x7.run( dataset=imaging_7x7, mask=mask_7x7, results=mock.MockResults(samples=samples) ) agg = af.Aggregator(directory=phase_imaging_7x7.paths.output_path) plane_gen = ag.agg.Plane(aggregator=agg) for plane in plane_gen: assert plane.galaxies[0].redshift == 0.5 assert plane.galaxies[0].light.centre == (0.0, 1.0) assert plane.galaxies[1].redshift == 1.0 def test__masked_imaging_generator_from_aggregator(imaging_7x7, mask_7x7, samples): phase_imaging_7x7 = ag.PhaseImaging( galaxies=dict( galaxy=ag.GalaxyModel(redshift=0.5, light=ag.lp.EllipticalSersic), source=ag.GalaxyModel(redshift=1.0, light=ag.lp.EllipticalSersic), ), settings=ag.SettingsPhaseImaging( settings_masked_imaging=ag.SettingsMaskedImaging( grid_class=ag.Grid2DIterate, grid_inversion_class=ag.Grid2DIterate, fractional_accuracy=0.5, sub_steps=[2], ) ), search=mock.MockSearch(samples=samples, name="test_phase_aggregator"), ) phase_imaging_7x7.run( dataset=imaging_7x7, mask=mask_7x7, results=mock.MockResults(samples=samples) ) agg = af.Aggregator(directory=phase_imaging_7x7.paths.output_path) masked_imaging_gen = ag.agg.MaskedImaging(aggregator=agg) for masked_imaging in masked_imaging_gen: assert (masked_imaging.imaging.image == imaging_7x7.image).all() assert isinstance(masked_imaging.grid, ag.Grid2DIterate) assert isinstance(masked_imaging.grid_inversion, ag.Grid2DIterate) assert masked_imaging.grid.sub_steps == [2] assert masked_imaging.grid.fractional_accuracy == 0.5 def test__fit_imaging_generator_from_aggregator(imaging_7x7, mask_7x7, samples): phase_imaging_7x7 = ag.PhaseImaging( galaxies=dict( galaxy=ag.GalaxyModel(redshift=0.5, light=ag.lp.EllipticalSersic), source=ag.GalaxyModel(redshift=1.0, light=ag.lp.EllipticalSersic), ), search=mock.MockSearch(samples=samples, name="test_phase_aggregator"), ) phase_imaging_7x7.run( dataset=imaging_7x7, mask=mask_7x7, results=mock.MockResults(samples=samples) ) agg = af.Aggregator(directory=phase_imaging_7x7.paths.output_path) fit_imaging_gen = ag.agg.FitImaging(aggregator=agg) for fit_imaging in fit_imaging_gen: assert (fit_imaging.masked_imaging.imaging.image == imaging_7x7.image).all() def test__masked_interferometer_generator_from_aggregator( interferometer_7, visibilities_mask_7, mask_7x7, samples ): phase_interferometer_7x7 = ag.PhaseInterferometer( galaxies=dict( galaxy=ag.GalaxyModel(redshift=0.5, light=ag.lp.EllipticalSersic), source=ag.GalaxyModel(redshift=1.0, light=ag.lp.EllipticalSersic), ), settings=ag.SettingsPhaseInterferometer( settings_masked_interferometer=ag.SettingsMaskedInterferometer( grid_class=ag.Grid2DIterate, grid_inversion_class=ag.Grid2DIterate, fractional_accuracy=0.5, sub_steps=[2], transformer_class=ag.TransformerDFT, ) ), search=mock.MockSearch(samples=samples, name="test_phase_aggregator"), real_space_mask=mask_7x7, ) phase_interferometer_7x7.run( dataset=interferometer_7, mask=visibilities_mask_7, results=mock.MockResults(samples=samples), ) agg = af.Aggregator(directory=phase_interferometer_7x7.paths.output_path) masked_interferometer_gen = ag.agg.MaskedInterferometer(aggregator=agg) for masked_interferometer in masked_interferometer_gen: assert ( masked_interferometer.interferometer.visibilities == interferometer_7.visibilities ).all() assert (masked_interferometer.real_space_mask == mask_7x7).all() assert isinstance(masked_interferometer.grid, ag.Grid2DIterate) assert isinstance(masked_interferometer.grid_inversion, ag.Grid2DIterate) assert masked_interferometer.grid.sub_steps == [2] assert masked_interferometer.grid.fractional_accuracy == 0.5 assert isinstance(masked_interferometer.transformer, ag.TransformerDFT) def test__fit_interferometer_generator_from_aggregator( interferometer_7, visibilities_mask_7, mask_7x7, samples ): phase_interferometer_7x7 = ag.PhaseInterferometer( galaxies=dict( galaxy=ag.GalaxyModel(redshift=0.5, light=ag.lp.EllipticalSersic), source=ag.GalaxyModel(redshift=1.0, light=ag.lp.EllipticalSersic), ), search=mock.MockSearch(samples=samples, name="test_phase_aggregator"), real_space_mask=mask_7x7, ) phase_interferometer_7x7.run( dataset=interferometer_7, mask=visibilities_mask_7, results=mock.MockResults(samples=samples), ) agg = af.Aggregator(directory=phase_interferometer_7x7.paths.output_path) fit_interferometer_gen = ag.agg.FitInterferometer(aggregator=agg) for fit_interferometer in fit_interferometer_gen: assert ( fit_interferometer.masked_interferometer.interferometer.visibilities == interferometer_7.visibilities ).all() assert ( fit_interferometer.masked_interferometer.real_space_mask == mask_7x7 ).all()
a11962ae95b28d1923e23d0a5c514d53c454524e
7889f7f0532db6a7f81e6f8630e399c90438b2b9
/3.7.1/_downloads/a54f19823bde998a456571636498aa98/auto_subplots_adjust.py
bd6326b8291f4b1a16db182e1f642d2279a8f0b0
[]
no_license
matplotlib/matplotlib.github.com
ef5d23a5bf77cb5af675f1a8273d641e410b2560
2a60d39490941a524e5385670d488c86083a032c
refs/heads/main
2023-08-16T18:46:58.934777
2023-08-10T05:07:57
2023-08-10T05:08:30
1,385,150
25
59
null
2023-08-30T15:59:50
2011-02-19T03:27:35
null
UTF-8
Python
false
false
3,366
py
""" =============================================== Programmatically controlling subplot adjustment =============================================== .. note:: This example is primarily intended to show some advanced concepts in Matplotlib. If you are only looking for having enough space for your labels, it is almost always simpler and good enough to either set the subplot parameters manually using `.Figure.subplots_adjust`, or use one of the automatic layout mechanisms (:doc:`/tutorials/intermediate/constrainedlayout_guide` or :doc:`/tutorials/intermediate/tight_layout_guide`). This example describes a user-defined way to read out Artist sizes and set the subplot parameters accordingly. Its main purpose is to illustrate some advanced concepts like reading out text positions, working with bounding boxes and transforms and using :ref:`events <event-handling-tutorial>`. But it can also serve as a starting point if you want to automate the layouting and need more flexibility than tight layout and constrained layout. Below, we collect the bounding boxes of all y-labels and move the left border of the subplot to the right so that it leaves enough room for the union of all the bounding boxes. There's one catch with calculating text bounding boxes: Querying the text bounding boxes (`.Text.get_window_extent`) needs a renderer (`.RendererBase` instance), to calculate the text size. This renderer is only available after the figure has been drawn (`.Figure.draw`). A solution to this is putting the adjustment logic in a draw callback. This function is executed after the figure has been drawn. It can now check if the subplot leaves enough room for the text. If not, the subplot parameters are updated and second draw is triggered. .. redirect-from:: /gallery/pyplots/auto_subplots_adjust """ import matplotlib.pyplot as plt import matplotlib.transforms as mtransforms fig, ax = plt.subplots() ax.plot(range(10)) ax.set_yticks([2, 5, 7], labels=['really, really, really', 'long', 'labels']) def on_draw(event): bboxes = [] for label in ax.get_yticklabels(): # Bounding box in pixels bbox_px = label.get_window_extent() # Transform to relative figure coordinates. This is the inverse of # transFigure. bbox_fig = bbox_px.transformed(fig.transFigure.inverted()) bboxes.append(bbox_fig) # the bbox that bounds all the bboxes, again in relative figure coords bbox = mtransforms.Bbox.union(bboxes) if fig.subplotpars.left < bbox.width: # Move the subplot left edge more to the right fig.subplots_adjust(left=1.1*bbox.width) # pad a little fig.canvas.draw() fig.canvas.mpl_connect('draw_event', on_draw) plt.show() ############################################################################# # # .. admonition:: References # # The use of the following functions, methods, classes and modules is shown # in this example: # # - `matplotlib.artist.Artist.get_window_extent` # - `matplotlib.transforms.Bbox` # - `matplotlib.transforms.BboxBase.transformed` # - `matplotlib.transforms.BboxBase.union` # - `matplotlib.transforms.Transform.inverted` # - `matplotlib.figure.Figure.subplots_adjust` # - `matplotlib.figure.SubplotParams` # - `matplotlib.backend_bases.FigureCanvasBase.mpl_connect`
b28bbc203b60e128307f6f9d8d309793f3dc1e1a
6fa7f99d3d3d9b177ef01ebf9a9da4982813b7d4
/yXZhG7zq6dWhWhirt_24.py
1b4a59876a63f5dfdb4b9e7de1d41c308c735314
[]
no_license
daniel-reich/ubiquitous-fiesta
26e80f0082f8589e51d359ce7953117a3da7d38c
9af2700dbe59284f5697e612491499841a6c126f
refs/heads/master
2023-04-05T06:40:37.328213
2021-04-06T20:17:44
2021-04-06T20:17:44
355,318,759
0
0
null
null
null
null
UTF-8
Python
false
false
215
py
def is_prime(n): if (n==1): return False for i in range(2,round(n**(0.5))+1): if i!=n and (n%i)==0: return False return True def filter_primes(num): return [n for n in num if is_prime(n)]
bbda84923f2c455dc60051aa1e126bf4dd187233
4a88ec266b64521fcaef88d92cb2b57776d3192b
/powerUsageNotification/powerUsageNotification.py
132c11551e75d59adb52856ce265d156f20d6af7
[ "MIT" ]
permissive
johntdyer/appdaemon-scripts
4e5ea345d27d54d8133be212e5f7af57b8dfd57f
ce7e32a919be5a835d0bdf95e6650ff34b699220
refs/heads/master
2020-03-31T18:01:49.517418
2018-10-07T14:06:38
2018-10-07T14:06:38
152,443,705
1
0
null
2018-10-10T15:10:00
2018-10-10T15:09:59
null
UTF-8
Python
false
false
4,100
py
import appdaemon.plugins.hass.hassapi as hass import globals # # App which notifies you when a power usage sensor indicated a device is on/off # # # Args: # # app_switch: on/off switch for this app. example: input_boolean.turn_fan_on_when_hot # sensor: power sensor. example: sensor.dishwasher_power_usage # notify_name: Who to notify. example: group_notifications # delay: seconds to wait until a the device is considered "off". example: 60 # threshold: amount of "usage" which indicated the device is on. example: 2 # alternative_name: Name to use in notification. example: Waschmaschine # # Release Notes # # Version 1.3: # use Notify App # # Version 1.2: # message now directly in own yaml instead of message module # # Version 1.1: # Added app_switch # # Version 1.0: # Initial Version class PowerUsageNotification(hass.Hass): def initialize(self): self.timer_handle_list = [] self.listen_event_handle_list = [] self.listen_state_handle_list = [] self.app_switch = globals.get_arg(self.args,"app_switch") self.sensor = globals.get_arg(self.args,"sensor") self.alternative_name = globals.get_arg(self.args,"alternative_name") self.notify_name = globals.get_arg(self.args,"notify_name") self.delay = globals.get_arg(self.args,"delay") self.threshold = globals.get_arg(self.args,"threshold") self.message = globals.get_arg(self.args,"message_DE") self.message_off = globals.get_arg(self.args,"message_off_DE") self.triggered = False self.isWaitingHandle = None self.notifier = self.get_app('Notifier') # Subscribe to sensors self.listen_state_handle_list.append(self.listen_state(self.state_change, self.sensor)) def state_change(self, entity, attribute, old, new, kwargs): if self.get_state(self.app_switch) == "on": # Initial: power usage goes up if ( new != None and new != "" and not self.triggered and float(new) > self.threshold ): self.triggered = True self.log("Power Usage is: {}".format(float(new))) self.log("Setting triggered to: {}".format(self.triggered)) self.notifier.notify(self.notify_name, self.message.format(self.alternative_name)) # Power usage goes down below threshold elif ( new != None and new != "" and self.triggered and self.isWaitingHandle == None and float(new) <= self.threshold): self.log("Waiting: {} seconds to notify.".format(self.delay)) self.isWaitingHandle = self.run_in(self.notify_device_off,self.delay) self.log("Setting isWaitingHandle to: {}".format(self.isWaitingHandle)) self.timer_handle_list.append(self.isWaitingHandle) # Power usage goes up before delay elif( new != None and new != "" and self.triggered and self.isWaitingHandle != None and float(new) > self.threshold): self.log("Cancelling timer") self.cancel_timer(self.isWaitingHandle) self.isWaitingHandle = None self.log("Setting isWaitingHandle to: {}".format(self.isWaitingHandle)) def notify_device_off(self, kwargs): """Notify User that device is off. This may get cancelled if it turns on again in the meantime""" self.triggered = False self.log("Setting triggered to: {}".format(self.triggered)) self.isWaitingHandle = None self.log("Setting isWaitingHandle to: {}".format(self.isWaitingHandle)) self.log("Notifying user") self.notifier.notify(self.notify_name, self.message_off.format(self.alternative_name)) def terminate(self): for timer_handle in self.timer_handle_list: self.cancel_timer(timer_handle) for listen_event_handle in self.listen_event_handle_list: self.cancel_listen_event(listen_event_handle) for listen_state_handle in self.listen_state_handle_list: self.cancel_listen_state(listen_state_handle)
c4281a41c161ba65c8915083ae81b981745630ca
9775ab319e5c1f2270a132b0244f0847db42589b
/nilai/migrations/0008_auto_20210117_1010.py
d2abe2075f8f24b61525b7b5c136dcc1bf54b97d
[]
no_license
nabaman/SPK-SAW
9aa8dfaf1bf5162bae1dc5c97e2b3e033a08294b
5c0b8d491f23939615aa968cd52f081072fe2230
refs/heads/master
2023-02-18T17:38:21.028901
2021-01-22T15:37:06
2021-01-22T15:37:06
331,987,703
0
0
null
null
null
null
UTF-8
Python
false
false
511
py
# Generated by Django 3.1.5 on 2021-01-17 10:10 from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('nilai', '0007_auto_20210117_1004'), ] operations = [ migrations.RemoveField( model_name='data_krips', name='kriteria', ), migrations.AddField( model_name='data_kriteria', name='krips', field=models.ManyToManyField(to='nilai.Data_Krips'), ), ]
a643d38e90646191463eca1bc229387c66c1a11f
65e0c11d690b32c832b943fb43a4206739ddf733
/bsdradius/trunk/bsdradius/configDefaults.py
244f2e4ef1d3488677ee5ad1c6d9c71ef18e43ac
[ "BSD-3-Clause" ]
permissive
Cloudxtreme/bsdradius
b5100062ed75c3201d179e190fd89770d8934aee
69dba67e27215dce49875e94a7eedbbdf77bc784
refs/heads/master
2021-05-28T16:50:14.711056
2015-04-30T11:54:17
2015-04-30T11:54:17
null
0
0
null
null
null
null
UTF-8
Python
false
false
4,442
py
## BSDRadius is released under BSD license. ## Copyright (c) 2006, DATA TECH LABS ## 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 the DATA TECH LABS 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. """ Define configuration defaults here """ # HeadURL $HeadURL: file:///Z:/backup/svn/bsdradius/trunk/bsdradius/configDefaults.py $ # Author: $Author: valts $ # File version: $Revision: 278 $ # Last changes: $Date: 2006-11-26 15:45:52 +0200 (Sv, 26 Nov 2006) $ prefix = '/usr/local' # define default values # format: {'section' : {'option' : value}} defaultOptions = { 'PATHS' : { 'prefix' : prefix, 'conf_dir' : '%(prefix)s/etc/bsdradius', 'run_dir' : '%(prefix)s/var/run', 'log_dir' : '%(prefix)s/var/log/bsdradius', 'user_module_dir' : '%(conf_dir)s/user_modules', 'dictionary_dir' : '%(prefix)s/share/bsdradius/dictionaries', 'dictionary_file' : '%(dictionary_dir)s/dictionary', 'server_log_file' : '%(log_dir)s/bsdradiusd.log', 'pid_file' : '%(run_dir)s/bsdradiusd.pid', 'clients_file' : '%(conf_dir)s/clients.conf', 'modules_file' : '%(conf_dir)s/modules.conf', 'user_modules_file' : '%(conf_dir)s/user_modules.conf', 'config_file' : '%(conf_dir)s/bsdradiusd.conf' }, 'SERVER' : { 'home' : '', 'user' : '', 'group' : '', 'auth_port' : '1812', 'acct_port' : '1813', 'number_of_threads' : '10', 'foreground' : 'no', 'no_threads' : 'no', 'log_to_screen': 'no', 'log_to_file' : 'no', 'debug_mode' : 'no', 'log_client' : '', 'fast_accounting': 'no', }, 'DATABASE' : { 'enable' : 'no', 'type' : 'postgresql', 'host' : 'localhost', 'user' : 'bsdradius', 'pass' : '', 'name' : 'bsdradius', 'refresh_rate' : '60', 'clients_query' : 'select address, name, secret from radiusClients', }, 'AUTHORIZATION' : { 'packet_timeout' : '5', 'auth_queue_maxlength' : '300', 'modules' : '', }, 'ACCOUNTING' : { 'acct_queue_maxlength' : '300', 'modules' : '', }, } # Define option types. # It is really neccessary to define only other types # than string because Config parser converts everything # to string by default. # Format: {'section' : {'option' : 'type'}} defaultTypes = { 'SERVER' : { 'auth_port' : 'int', 'acct_port' : 'int', 'number_of_threads' : 'int', 'foreground' : 'bool', 'no_threads' : 'bool', 'log_to_screen': 'bool', 'log_to_file': 'bool', 'debug_mode' : 'bool', 'fast_accounting': 'bool', }, 'DATABASE' : { 'enable' : 'bool', 'refresh_rate' : 'int', }, 'AUTHORIZATION' : { 'packet_timeout' : 'int', 'auth_queue_maxlength' : 'int', }, 'ACCOUNTING' : { 'acct_queue_maxlength' : 'int', }, } # configuration defaults for one BSD Radius module moduleConfigDefaults = { 'enable': 'yes', 'configfile': '', 'startup_module': '', 'startup_function': '', 'authorization_module': '', 'authorization_function': '', 'authentication_module': '', 'authentication_function': '', 'accounting_module': '', 'accounting_function': '', 'shutdown_module': '', 'shutdown_function': '', 'pythonpath' : '', }
[ "valdiic@72071c86-a5be-11dd-a5cd-697bfd0a0cef" ]
valdiic@72071c86-a5be-11dd-a5cd-697bfd0a0cef
a842ae5ed2fa9404270a2b872f3c9f04a42ac434
2652fd6261631794535589427a384693365a585e
/trunk/workspace/Squish/src/TestScript/UI/suite_UI_51/tst_UI_51_Pref_BufferAutoView/test.py
e1a9d9fe2212331ae4697f3a3269cdded8842a9c
[]
no_license
ptqatester1/ptqa
88c652380167f64a953bfd7a65041e7d8ac48c90
5b5997ea459e9aac17db8da2041e2af331927104
refs/heads/master
2021-01-21T19:06:49.275364
2017-06-19T03:15:00
2017-06-19T03:15:00
92,115,462
0
0
null
null
null
null
UTF-8
Python
false
false
1,735
py
from API.Utility.Util import Util from API.Utility import UtilConst from API.MenuBar.Options.Options import Options from API.MenuBar.Options.OptionsConst import OptionsConst from API.MenuBar.Options.Preferences.Miscellaneous.MiscellaneousConst import MiscellaneousConst from API.SimulationPanel.EventList.EventListConst import EventListConst from API.SimulationPanel.EventListFilters.EventListFilters import EventListFilters from API.SimulationPanel.PlayControls.PlayControlsConst import PlayControlsConst from API.MenuBar.Options.Preferences.PreferencesConst import PreferencesConst util = Util() options = Options() eventListFilters = EventListFilters() def main(): util.init() util.open("UI13.pkt", UtilConst.UI_TEST ) util.speedUpConvergence() editOptionsSetting() checkpoint1() resetOptionsSetting() def editOptionsSetting(): options.selectOptionsItem(OptionsConst.PREFERENCES) util.clickTab(PreferencesConst.TAB_BAR, PreferencesConst.MISCELLANEOUS) util.clickButton(MiscellaneousConst.AUTO_VIEW_PREVIOUS_EVENTS) util.close(OptionsConst.OPTIONS_DIALOG) def checkpoint1(): util.clickOnSimulation() util.clickButton(EventListConst.RESET_SIMULATION) for i in range(0, 8): util.clickButton(PlayControlsConst.CAPTURE_FORWARD) snooze(10) if (object.exists(PlayControlsConst.BUFFER_FULL_DIALOG_LABEL)): test.fail("Buffer window found") else: test.passes("Buffer window not found") def resetOptionsSetting(): options.selectOptionsItem(OptionsConst.PREFERENCES) util.clickTab(PreferencesConst.TAB_BAR, PreferencesConst.MISCELLANEOUS) util.clickButton(MiscellaneousConst.PROMPT) util.close(OptionsConst.OPTIONS_DIALOG)
509c23e3bf72658ffd093ae405cf9de4958fb78f
102d09ef1d6effe166ad703ba4472c45dfb03263
/py/Maximum_Depth_of_Binary_Tree.py
199982277744c0985b39cfc2326fc115a739fec4
[]
no_license
bitcsdby/Codes-for-leetcode
5693100d4b66de65d7f135bbdd81b32650aed7d0
9e24e621cfb9e7fd46f9f02dfc40a18a702d4990
refs/heads/master
2016-09-05T08:43:31.656437
2014-08-02T15:14:53
2014-08-02T15:14:53
null
0
0
null
null
null
null
UTF-8
Python
false
false
444
py
# Definition for a binary tree node # class TreeNode: # def __init__(self, x): # self.val = x # self.left = None # self.right = None class Solution: # @param root, a tree node # @return an integer def maxDepth(self, root): if root == None: return 0; l = self.maxDepth(root.left) + 1; r = self.maxDepth(root.right) + 1; return l if l > r else r;
d0089bd15b2c1ffac1e167de02e3ee215da07c7b
74698be74d244ebbabcb0b3cf17ebed26adfa37c
/orbit/utils/epoch_helper.py
6eb110768887e95055c34f7fc3857f08a6b9c276
[ "Apache-2.0" ]
permissive
lfads/models
aa75616fee2476641aa98ca1cbdce7e5d27a9aff
fd700f0cb2e104544c445d9fbf3991d8388ff18a
refs/heads/master
2021-01-25T13:50:55.423010
2021-01-05T18:27:01
2021-01-05T18:27:01
123,619,512
16
9
Apache-2.0
2021-01-05T18:27:02
2018-03-02T19:07:50
Python
UTF-8
Python
false
false
2,136
py
# Copyright 2020 The Orbit 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 a utility class for training in epochs.""" import tensorflow as tf class EpochHelper: """A helper class handle bookkeeping of epochs in custom training loops.""" def __init__(self, epoch_steps: int, global_step: tf.Variable): """Initializes the `EpochHelper` instance. Args: epoch_steps: An integer indicating how many steps are in an epoch. global_step: A `tf.Variable` providing the current global step. """ self._epoch_steps = epoch_steps self._global_step = global_step self._current_epoch = None self._epoch_start_step = None self._in_epoch = False def epoch_begin(self): """Returns whether a new epoch should begin.""" if self._in_epoch: return False current_step = self._global_step.numpy() self._epoch_start_step = current_step self._current_epoch = current_step // self._epoch_steps self._in_epoch = True return True def epoch_end(self): """Returns whether the current epoch should end.""" if not self._in_epoch: raise ValueError("`epoch_end` can only be called inside an epoch.") current_step = self._global_step.numpy() epoch = current_step // self._epoch_steps if epoch > self._current_epoch: self._in_epoch = False return True return False @property def batch_index(self): """Index of the next batch within the current epoch.""" return self._global_step.numpy() - self._epoch_start_step @property def current_epoch(self): return self._current_epoch
ad9a3b50ae05c454484d9697933ee5e00f730b4a
5dd7c4ec44b76180040badc67849ad44f81690f9
/unittests/test_stockitem.py
751eb41a7c209613f1a6e803ac526f15a85a3c77
[]
no_license
myluco/Phoenix
68f9abe15a673fe56da6ef4375849ba6a642622d
2de746beda35b8b5db547658cae1c65cfe164039
refs/heads/master
2021-01-18T15:59:05.001240
2016-12-04T00:08:36
2016-12-04T00:08:36
null
0
0
null
null
null
null
UTF-8
Python
false
false
455
py
import unittest from unittests import wtc import wx #--------------------------------------------------------------------------- class stockitem_Tests(wtc.WidgetTestCase): # TODO: Remove this test and add real ones. def test_stockitem1(self): self.fail("Unit tests for stockitem not implemented yet.") #--------------------------------------------------------------------------- if __name__ == '__main__': unittest.main()
6c10278bce7d441831f59503418233abcba5dee8
17c14b758959cdceec0dce8f783346fdeee8e111
/chap05_nlp/automl/train.py
bca8b1fd41ce03b243523430bdc8d09621f7daa4
[]
no_license
yurimkoo/tensormsa_jupyter
b0a340119339936d347d12fbd88fb017599a0029
0e75784114ec6dc8ee7eff8094aef9cf37131a5c
refs/heads/master
2021-07-18T12:22:31.396433
2017-10-25T01:42:24
2017-10-25T01:42:24
109,469,220
1
0
null
2017-11-04T05:20:15
2017-11-04T05:20:15
null
UTF-8
Python
false
false
3,650
py
""" Utility used by the Network class to actually train. Based on: https://github.com/fchollet/keras/blob/master/examples/mnist_mlp.py """ from keras.datasets import mnist, cifar10 from keras.models import Sequential from keras.layers import Dense, Dropout from keras.utils.np_utils import to_categorical from keras.callbacks import EarlyStopping # Helper: Early stopping. early_stopper = EarlyStopping(patience=5) def get_cifar10(): """Retrieve the CIFAR dataset and process the data.""" # Set defaults. nb_classes = 10 batch_size = 64 input_shape = (3072,) # Get the data. (x_train, y_train), (x_test, y_test) = cifar10.load_data() x_train = x_train.reshape(50000, 3072) x_test = x_test.reshape(10000, 3072) x_train = x_train.astype('float32') x_test = x_test.astype('float32') x_train /= 255 x_test /= 255 # convert class vectors to binary class matrices y_train = to_categorical(y_train, nb_classes) y_test = to_categorical(y_test, nb_classes) return (nb_classes, batch_size, input_shape, x_train, x_test, y_train, y_test) def get_mnist(): """Retrieve the MNIST dataset and process the data.""" # Set defaults. nb_classes = 10 batch_size = 128 input_shape = (784,) # Get the data. (x_train, y_train), (x_test, y_test) = mnist.load_data() x_train = x_train.reshape(60000, 784) x_test = x_test.reshape(10000, 784) x_train = x_train.astype('float32') x_test = x_test.astype('float32') x_train /= 255 x_test /= 255 # convert class vectors to binary class matrices y_train = to_categorical(y_train, nb_classes) y_test = to_categorical(y_test, nb_classes) return (nb_classes, batch_size, input_shape, x_train, x_test, y_train, y_test) def compile_model(network, nb_classes, input_shape): """Compile a sequential model. Args: network (dict): the parameters of the network Returns: a compiled network. """ # Get our network parameters. nb_layers = network['nb_layers'] nb_neurons = network['nb_neurons'] activation = network['activation'] optimizer = network['optimizer'] model = Sequential() # Add each layer. for i in range(nb_layers): # Need input shape for first layer. if i == 0: model.add(Dense(nb_neurons, activation=activation, input_shape=input_shape)) else: model.add(Dense(nb_neurons, activation=activation)) model.add(Dropout(0.2)) # hard-coded dropout # Output layer. model.add(Dense(nb_classes, activation='softmax')) model.compile(loss='categorical_crossentropy', optimizer=optimizer, metrics=['accuracy']) return model def train_and_score(network, dataset): """Train the model, return test loss. Args: network (dict): the parameters of the network dataset (str): Dataset to use for training/evaluating """ if dataset == 'cifar10': nb_classes, batch_size, input_shape, x_train, \ x_test, y_train, y_test = get_cifar10() elif dataset == 'mnist': nb_classes, batch_size, input_shape, x_train, \ x_test, y_train, y_test = get_mnist() model = compile_model(network, nb_classes, input_shape) model.fit(x_train, y_train, batch_size=batch_size, epochs=10000, # using early stopping, so no real limit verbose=0, validation_data=(x_test, y_test), callbacks=[early_stopper]) score = model.evaluate(x_test, y_test, verbose=0) return score[1] # 1 is accuracy. 0 is loss.
00c9949db590246f66d2bb3310ffbfe39a1fee79
9b24eb3a15e9acd4aaf7af00d88488f5a056438f
/backend/home/api/v1/viewsets.py
c7c28c17f806e899fca335a7c524c6cb75b776a2
[]
no_license
crowdbotics-apps/dashboard-app-18025
b8fb28008d42371c7d74102b78ae380725b3221a
202f33b00e14f65adfc9dbf84f748ad5cc051652
refs/heads/master
2022-11-15T12:16:12.733390
2020-06-15T17:24:52
2020-06-15T17:24:52
271,619,959
0
0
null
null
null
null
UTF-8
Python
false
false
2,485
py
from rest_framework import viewsets from rest_framework import authentication from .serializers import ( AddressSerializer, CustomTextSerializer, HomePageSerializer, XYSerializer, ) from rest_framework.authentication import SessionAuthentication, TokenAuthentication from rest_framework.authtoken.serializers import AuthTokenSerializer from rest_framework.permissions import IsAdminUser from rest_framework.viewsets import ModelViewSet, ViewSet from rest_framework.authtoken.models import Token from rest_framework.response import Response from home.api.v1.serializers import ( SignupSerializer, CustomTextSerializer, HomePageSerializer, UserSerializer, ) from home.models import Address, CustomText, HomePage, XY class SignupViewSet(ModelViewSet): serializer_class = SignupSerializer http_method_names = ["post"] class LoginViewSet(ViewSet): """Based on rest_framework.authtoken.views.ObtainAuthToken""" serializer_class = AuthTokenSerializer def create(self, request): serializer = self.serializer_class( data=request.data, context={"request": request} ) serializer.is_valid(raise_exception=True) user = serializer.validated_data["user"] token, created = Token.objects.get_or_create(user=user) user_serializer = UserSerializer(user) return Response({"token": token.key, "user": user_serializer.data}) class CustomTextViewSet(ModelViewSet): serializer_class = CustomTextSerializer queryset = CustomText.objects.all() authentication_classes = (SessionAuthentication, TokenAuthentication) permission_classes = [IsAdminUser] http_method_names = ["get", "put", "patch"] class HomePageViewSet(ModelViewSet): serializer_class = HomePageSerializer queryset = HomePage.objects.all() authentication_classes = (SessionAuthentication, TokenAuthentication) permission_classes = [IsAdminUser] http_method_names = ["get", "put", "patch"] class XYViewSet(viewsets.ModelViewSet): serializer_class = XYSerializer authentication_classes = ( authentication.SessionAuthentication, authentication.TokenAuthentication, ) queryset = XY.objects.all() class AddressViewSet(viewsets.ModelViewSet): serializer_class = AddressSerializer authentication_classes = ( authentication.SessionAuthentication, authentication.TokenAuthentication, ) queryset = Address.objects.all()
005b11fedd1241560633f3f19ce4ab82b6cf9068
43dabf77afd5c44d55b465c1b88bf9a5e7c4c9be
/resize.py
306400848b45f96d2ec9be96bbc1dbae1a9871f7
[]
no_license
geegatomar/OpenCV-Computer-Vision-Adrian-Rosebrock
cc81a990a481b5e4347dd97369b38479b46e55bc
daa579309010e6e7fefb004b878ffb26374401d0
refs/heads/master
2022-11-18T13:07:08.040483
2020-07-20T01:55:39
2020-07-20T01:55:39
280,987,262
0
0
null
null
null
null
UTF-8
Python
false
false
506
py
import cv2 import argparse import numpy as np ap = argparse.ArgumentParser() ap.add_argument("-i", "--image", required=True, help="Path of image") ap.add_argument("-w", "--width", default=100, help="Width of resized img") args = vars(ap.parse_args()) image = cv2.imread(args["image"]) width = int(args["width"]) ratio = width / image.shape[1] dim = (int(ratio * image.shape[0]), width) resized = cv2.resize(image, dim, interpolation = cv2.INTER_AREA) cv2.imshow("Resized img", resized) cv2.waitKey(0)
2534efd7cf1a472d4c24db7e37fb628ef53a3a0f
9adda6cef38c05c0d6bc4f5d0be25e75500f3406
/ques 2 sol.py
00f2329450eb86ff204e44c7f8653fbee1abdcff
[]
no_license
GLAU-TND/python-programming-assignment4-upadhyay8844
09255dd1ef340f7af3ee57e4eee3c671c010d5c4
bc5c31d40f03cceebb2c842bdd933e0e73a998a1
refs/heads/master
2021-05-19T05:26:14.857261
2020-04-01T11:43:27
2020-04-01T11:43:27
251,547,215
0
0
null
null
null
null
UTF-8
Python
false
false
414
py
def is_dict(var): return str(type(var)) == "<class 'dict'>" def flatten_helper(d, flat_d, path): if not is_dict(d): flat_d[path] = d return for key in d: new_keypath = "{}.{}".format(path, key) if path else key flatten_helper(d[key], flat_d, new_keypath) def flatten(d): flat_d = dict() flatten_helper(d, flat_d, "") return flat_d
4c61a7aae73fa64897e0df01720f5f1eed93b6dd
16de2efcba33961633c1e63e493986bad54c99bd
/test.py
73b7e8d90f6b8b0378a1486d70f70ac2af704483
[]
no_license
thakur-nishant/Algorithms
a0cc45de5393d4cbb428cccdbf81b6937cdf97d7
1a0306ca9a9fc68f59e28ea26c24822c15350294
refs/heads/master
2022-01-07T22:22:09.764193
2019-05-17T20:10:24
2019-05-17T20:10:24
109,093,687
0
0
null
null
null
null
UTF-8
Python
false
false
424
py
from math import log from random import random import matplotlib.pyplot as plt import numpy as np l = 2 T = 24 curr = -1/l * log(random()) arrival = [curr] while curr < T: curr = curr -1/l * log(random()) arrival.append(curr) arrival = arrival[1:] t = np.arange(0.0, T, 0.01) N = len(t) X = np.zeros(N) for i in range(N): X[i] = np.sum(arrival <= t[i]) plt.plot(t, X) plt.xlabel('time(hrs)') plt.show()
a3dc231f3dbd0e2e1ef4dbdd546e09d37e950ff2
f224fad50dbc182cda86291c83954607bbb60901
/inference.py
ce98cbf4d15f6bc1e05363be1db9afeb1e519de5
[]
no_license
Hongpeng1992/pytorch-commands
7fd26202b7cf7d46a0ac8e1241336e8ca5dad30e
5853625d9852e948c1ac337547f8078d048699a0
refs/heads/master
2020-05-04T15:38:26.704013
2019-02-07T07:04:01
2019-02-07T07:04:01
null
0
0
null
null
null
null
UTF-8
Python
false
false
6,644
py
import argparse import io import os import csv import time import numpy as np import pandas as pd from collections import OrderedDict from datetime import datetime from dataset import CommandsDataset, get_labels from models import model_factory from utils import AverageMeter, get_outdir import torch import torch.autograd as autograd import torch.nn import torch.nn.functional as F import torch.utils.data as data import torchvision.utils parser = argparse.ArgumentParser(description='Inference') parser.add_argument('data', metavar='DIR', help='path to dataset') parser.add_argument('--model', default='resnet101', type=str, metavar='MODEL', help='Name of model to train (default: "countception"') parser.add_argument('--gp', default='avg', type=str, metavar='POOL', help='Type of global pool, "avg", "max", "avgmax", "avgmaxc" (default: "avg")') parser.add_argument('--tta', type=int, default=0, metavar='N', help='Test/inference time augmentation (oversampling) factor. 0=None (default: 0)') parser.add_argument('--pretrained', action='store_true', default=False, help='Start with pretrained version of specified network (if avail)') parser.add_argument('-b', '--batch-size', type=int, default=512, metavar='N', help='input batch size for training (default: 512)') parser.add_argument('-j', '--workers', type=int, default=2, metavar='N', help='how many training processes to use (default: 1)') parser.add_argument('--num-gpu', type=int, default=1, help='Number of GPUS to use') parser.add_argument('--checkpoint', default='', type=str, metavar='PATH', help='path to restore checkpoint (default: none)') parser.add_argument('--print-freq', '-p', default=10, type=int, metavar='N', help='print frequency (default: 10)') parser.add_argument('--save-batches', action='store_true', default=False, help='save images of batch inputs and targets every log interval for debugging/verification') parser.add_argument('--output', default='', type=str, metavar='PATH', help='path to output folder (default: none, current dir)') def main(): args = parser.parse_args() num_classes = len(get_labels()) test_time_pool = 0 #5 if 'dpn' in args.model else 0 model = model_factory.create_model( args.model, in_chs=1, num_classes=num_classes, global_pool=args.gp, test_time_pool=test_time_pool) #model.reset_classifier(num_classes=num_classes) if args.num_gpu > 1: model = torch.nn.DataParallel(model, device_ids=list(range(args.num_gpu))).cuda() else: model.cuda() if not os.path.exists(args.checkpoint): print("=> no checkpoint found at '{}'".format(args.checkpoint)) exit(1) print("=> loading checkpoint '{}'".format(args.checkpoint)) checkpoint = torch.load(args.checkpoint) if isinstance(checkpoint, dict) and 'state_dict' in checkpoint: model.load_state_dict(checkpoint['state_dict']) print("=> loaded checkpoint '{}' (epoch {})".format(args.checkpoint, checkpoint['epoch'])) else: model.load_state_dict(checkpoint) csplit = os.path.normpath(args.checkpoint).split(sep=os.path.sep) if len(csplit) > 1: exp_name = csplit[-2] + '-' + csplit[-1].split('.')[0] else: exp_name = '' if args.output: output_base = args.output else: output_base = './output' output_dir = get_outdir(output_base, 'predictions', exp_name) dataset = CommandsDataset( root=args.data, mode='test', format='spectrogram' ) loader = data.DataLoader( dataset, batch_size=args.batch_size, pin_memory=True, shuffle=False, num_workers=args.workers ) model.eval() batch_time_m = AverageMeter() data_time_m = AverageMeter() try: # open CSV for writing predictions cf = open(os.path.join(output_dir, 'results.csv'), mode='w') res_writer = csv.writer(cf) res_writer.writerow(['fname'] + dataset.id_to_label) # open CSV for writing submission cf = open(os.path.join(output_dir, 'submission.csv'), mode='w') sub_writer = csv.writer(cf) sub_writer.writerow(['fname', 'label', 'prob']) end = time.time() batch_sample_idx = 0 for batch_idx, (input, target) in enumerate(loader): data_time_m.update(time.time() - end) input = input.cuda() output = model(input) # augmentation reduction #reduce_factor = loader.dataset.get_aug_factor() #if reduce_factor > 1: # output = output.unfold(0, reduce_factor, reduce_factor).mean(dim=2).squeeze(dim=2) # index = index[0:index.size(0):reduce_factor] # move data to CPU and collect) output_logprob = F.log_softmax(output, dim=1).cpu().numpy() output = F.softmax(output, dim=1) output_prob, output_idx = output.max(1) output_prob = output_prob.cpu().numpy() output_idx = output_idx.cpu().numpy() for i in range(output_logprob.shape[0]): index = batch_sample_idx + i pred_label = dataset.id_to_label[output_idx[i]] pred_prob = output_prob[i] filename = dataset.filename(index) res_writer.writerow([filename] + list(output_logprob[i])) sub_writer.writerow([filename] + [pred_label, pred_prob]) batch_sample_idx += input.size(0) batch_time_m.update(time.time() - end) if batch_idx % args.print_freq == 0: print('Inference: [{}/{} ({:.0f}%)] ' 'Time: {batch_time.val:.3f}s, {rate:.3f}/s ' '({batch_time.avg:.3f}s, {rate_avg:.3f}/s) ' 'Data: {data_time.val:.3f} ({data_time.avg:.3f})'.format( batch_sample_idx, len(loader.sampler), 100. * batch_idx / len(loader), batch_time=batch_time_m, rate=input.size(0) / batch_time_m.val, rate_avg=input.size(0) / batch_time_m.avg, data_time=data_time_m)) end = time.time() # end iterating through dataset except KeyboardInterrupt: pass except Exception as e: print(str(e)) if __name__ == '__main__': main()
14117448fe850d69ae5fcf1bd41049c19247b557
91d1a6968b90d9d461e9a2ece12b465486e3ccc2
/appmesh_write_2/virtual-router_delete.py
db6df7702ffc69ca7d3bbf5c3eda2b1680913ce2
[]
no_license
lxtxl/aws_cli
c31fc994c9a4296d6bac851e680d5adbf7e93481
aaf35df1b7509abf5601d3f09ff1fece482facda
refs/heads/master
2023-02-06T09:00:33.088379
2020-12-27T13:38:45
2020-12-27T13:38:45
318,686,394
0
0
null
null
null
null
UTF-8
Python
false
false
1,343
py
#!/usr/bin/python # -*- codding: utf-8 -*- import os import sys sys.path.append(os.path.dirname(os.path.abspath(os.path.dirname(__file__)))) from common.execute_command import write_two_parameter # url : https://awscli.amazonaws.com/v2/documentation/api/latest/reference/appmesh/delete-virtual-router.html if __name__ == '__main__': """ create-virtual-router : https://awscli.amazonaws.com/v2/documentation/api/latest/reference/appmesh/create-virtual-router.html describe-virtual-router : https://awscli.amazonaws.com/v2/documentation/api/latest/reference/appmesh/describe-virtual-router.html list-virtual-routers : https://awscli.amazonaws.com/v2/documentation/api/latest/reference/appmesh/list-virtual-routers.html update-virtual-router : https://awscli.amazonaws.com/v2/documentation/api/latest/reference/appmesh/update-virtual-router.html """ parameter_display_string = """ # mesh-name : The name of the service mesh to delete the virtual router in. # virtual-router-name : The name of the virtual router to delete. """ add_option_dict = {} add_option_dict["parameter_display_string"] = parameter_display_string # ex: add_option_dict["no_value_parameter_list"] = "--single-parameter" write_two_parameter("appmesh", "delete-virtual-router", "mesh-name", "virtual-router-name", add_option_dict)
53fa6c563e9983afb729af1af3be08c9c03dd4a1
8792e3449fbc6c8dec99f6af1d9f1b4caddad1f7
/51player.py
470f81860462904d56f98294142a2c26cd476828
[]
no_license
aarthisandhiya/aarthisandhiya1
c19c1951c9ba01cd97eeddd44614953088718357
e6f10247b6a84d6eaf371a23f2f9c3bebbc73e5b
refs/heads/master
2020-04-15T17:17:07.151242
2019-05-20T05:24:19
2019-05-20T05:24:19
164,868,494
0
1
null
null
null
null
UTF-8
Python
false
false
202
py
a=int(input()) s=[int(a) for a in input().split()] s=list(s) z=[] for i in range(0,len(s)): val=s[i] i=i-1 while i>=0: if val<s[i]: s[i+1]=s[i] s[i]=val i=i-1 else: break print(s[1])
98244b23e0ce113db9acb33b85781abda3504fab
82115f52db1783a2ce963e2621bf185c61ceb419
/Teoría/03 Widgets para formularios/3-1 Etiquetas/programa.py
f824e536fbaa1c1de04e3356c2ce610ec1b992ff
[]
no_license
lesclaz/curso-qt-pyside-udemy
ce227df451a7cff40d90543ee6c892ea1a6b131c
8b9bbf5d45e916f1d7db9411728b2759b30d2fd9
refs/heads/master
2023-07-01T18:11:47.959668
2021-08-03T09:38:12
2021-08-03T09:38:12
null
0
0
null
null
null
null
UTF-8
Python
false
false
1,020
py
from PySide6.QtWidgets import QApplication, QMainWindow, QLabel from PySide6.QtCore import QSize, Qt from PySide6.QtGui import QFont, QPixmap from pathlib import Path import sys def absPath(file): # Devuelve la ruta absoluta a un fichero desde el propio script return str(Path(__file__).parent.absolute() / file) class MainWindow(QMainWindow): def __init__(self): super().__init__() self.setMinimumSize(QSize(480, 320)) etiqueta = QLabel("Soy una etiqueta") self.setCentralWidget(etiqueta) # Creamos la imagen imagen = QPixmap(absPath("naturaleza.jpg")) # la asginamos a la etiqueta etiqueta.setPixmap(imagen) # hacemos que se escale con la ventana etiqueta.setScaledContents(True) # establecemos unas flags de alineamiento etiqueta.setAlignment(Qt.AlignHCenter | Qt.AlignVCenter) if __name__ == "__main__": app = QApplication() window = MainWindow() window.show() sys.exit(app.exec_())
6576a596822baf4eb435a1fe47e11d479398497b
fd878bcdaa9489883894c942aae5e316a15c2085
/tests/dataset_readers/sst_test.py
477e1a51ec7a5efbd55ddd0006bc58ee474d6ddc
[]
no_license
Shuailong/SPM
a12d18baa39a72a9243ad9cd4238168ab42b96d1
0105dae90a4acdebfc875001efab7439b3eb8259
refs/heads/master
2020-04-26T04:51:14.279859
2019-06-24T03:55:11
2019-06-24T03:55:11
173,315,858
0
0
null
null
null
null
UTF-8
Python
false
false
2,551
py
# pylint: disable=no-self-use,invalid-name import pytest import pathlib import random import os from allennlp.common import Params from allennlp.common.util import ensure_list from allennlp.common.testing import ModelTestCase from allennlp.data.dataset import Batch from allennlp.data.fields import TextField from allennlp.data.instance import Instance from allennlp.data.token_indexers.wordpiece_indexer import PretrainedBertIndexer from allennlp.data.tokenizers import WordTokenizer, Token from allennlp.data.tokenizers.word_splitter import BertBasicWordSplitter from allennlp.data.vocabulary import Vocabulary from allennlp.modules.token_embedders.bert_token_embedder import PretrainedBertEmbedder from spm.data.dataset_readers import GLUESST2DatasetReader from spm import DATA_DIR as DATA_ROOT class TestSSTReader: FIXTURES_ROOT = (pathlib.Path(__file__).parent / ".." / ".." / "tests" / "fixtures").resolve() BERT_VOCAB_PATH = os.path.join( DATA_ROOT, 'bert/bert-base-uncased-vocab.txt') @pytest.mark.parametrize("lazy", (True, False)) def test_read(self, lazy): reader = GLUESST2DatasetReader( tokenizer=WordTokenizer(word_splitter=BertBasicWordSplitter()), token_indexers={'bert': PretrainedBertIndexer( pretrained_model=self.BERT_VOCAB_PATH)}, skip_label_indexing=False ) instances = reader.read( str(self.FIXTURES_ROOT / 'dev.tsv')) instances = ensure_list(instances) example = instances[0] tokens = [t.text for t in example.fields['tokens']] label = example.fields['label'].label print(label) print(tokens) batch = Batch(instances) vocab = Vocabulary.from_instances(instances) batch.index_instances(vocab) padding_lengths = batch.get_padding_lengths() tensor_dict = batch.as_tensor_dict(padding_lengths) tokens = tensor_dict["tokens"] print(tokens['mask'].tolist()[0]) print(tokens["bert"].tolist()[0]) print([vocab.get_token_from_index(i, "bert") for i in tokens["bert"].tolist()[0]]) print(len(tokens['bert'][0])) print(tokens["bert-offsets"].tolist()[0]) print(tokens['bert-type-ids'].tolist()[0]) def test_can_build_from_params(self): reader = GLUESST2DatasetReader.from_params(Params({})) # pylint: disable=protected-access assert reader._token_indexers['tokens'].__class__.__name__ == 'SingleIdTokenIndexer'
25eaf0a29411821417765885863acfd5166a02e3
7298d1692c6948f0880e550d6100c63a64ce3ea1
/deriva-annotations/catalog99/catalog-configs/Vocab/ihm_residues_not_modeled_reason.py
9a62ee7fbe832a6a342ee44c46b17d4607a9f500
[]
no_license
informatics-isi-edu/protein-database
b7684b3d08dbf22c1e7c4a4b8460248c6f0d2c6d
ce4be1bf13e6b1c22f3fccbb513824782609991f
refs/heads/master
2023-08-16T10:24:10.206574
2023-07-25T23:10:42
2023-07-25T23:10:42
174,095,941
2
0
null
2023-06-16T19:44:43
2019-03-06T07:39:14
Python
UTF-8
Python
false
false
5,585
py
import argparse from deriva.core import ErmrestCatalog, AttrDict, get_credential import deriva.core.ermrest_model as em from deriva.core.ermrest_config import tag as chaise_tags from deriva.utils.catalog.manage.update_catalog import CatalogUpdater, parse_args groups = { 'pdb-reader': 'https://auth.globus.org/8875a770-3c40-11e9-a8c8-0ee7d80087ee', 'pdb-writer': 'https://auth.globus.org/c94a1e5c-3c40-11e9-a5d1-0aacc65bfe9a', 'pdb-admin': 'https://auth.globus.org/0b98092c-3c41-11e9-a8c8-0ee7d80087ee', 'pdb-curator': 'https://auth.globus.org/eef3e02a-3c40-11e9-9276-0edc9bdd56a6', 'isrd-staff': 'https://auth.globus.org/176baec4-ed26-11e5-8e88-22000ab4b42b', 'pdb-submitter': 'https://auth.globus.org/99da042e-64a6-11ea-ad5f-0ef992ed7ca1' } table_name = 'ihm_residues_not_modeled_reason' schema_name = 'Vocab' column_annotations = { 'ID': {}, 'URI': {}, 'Name': {}, 'Description': {}, 'Synonyms': {}, 'Owner': {} } column_comment = { 'ID': 'The preferred Compact URI (CURIE) for this term.', 'URI': 'The preferred URI for this term.', 'Name': 'None', 'Description': 'None', 'Synonyms': 'Alternate human-readable names for this term.', 'Owner': 'Group that can update the record.' } column_acls = {} column_acl_bindings = {} column_defs = [ em.Column.define( 'ID', em.builtin_types['ermrest_curie'], nullok=False, default='PDB:{RID}', comment=column_comment['ID'], ), em.Column.define( 'URI', em.builtin_types['ermrest_uri'], nullok=False, default='/id/{RID}', comment=column_comment['URI'], ), em.Column.define( 'Name', em.builtin_types['text'], nullok=False, comment=column_comment['Name'], ), em.Column.define( 'Description', em.builtin_types['markdown'], nullok=False, comment=column_comment['Description'], ), em.Column.define('Synonyms', em.builtin_types['text[]'], comment=column_comment['Synonyms'], ), em.Column.define('Owner', em.builtin_types['text'], comment=column_comment['Owner'], ), ] visible_columns = { '*': [ 'RID', 'Name', 'Description', 'ID', 'URI', ['Vocab', 'ihm_residues_not_modeled_reason_term_RCB_fkey'], ['Vocab', 'ihm_residues_not_modeled_reason_term_RMB_fkey'], 'RCT', 'RMT', ['Vocab', 'ihm_residues_not_modeled_reason_term_Owner_fkey'] ] } table_display = {'row_name': {'row_markdown_pattern': '{{{Name}}}'}} table_annotations = { chaise_tags.table_display: table_display, chaise_tags.visible_columns: visible_columns, } table_comment = 'A set of controlled vocabular terms.' table_acls = {} table_acl_bindings = { 'released_reader': { 'types': ['select'], 'scope_acl': [groups['pdb-submitter']], 'projection': ['RID'], 'projection_type': 'nonnull' }, 'self_service_group': { 'types': ['update', 'delete'], 'scope_acl': ['*'], 'projection': ['Owner'], 'projection_type': 'acl' }, 'self_service_creator': { 'types': ['update', 'delete'], 'scope_acl': ['*'], 'projection': ['RCB'], 'projection_type': 'acl' } } key_defs = [ em.Key.define( ['Name'], constraint_names=[['Vocab', 'ihm_residues_not_modeled_reason_Namekey1']], ), em.Key.define( ['RID'], constraint_names=[['Vocab', 'ihm_residues_not_modeled_reason_term_RIDkey1']], ), em.Key.define( ['ID'], constraint_names=[['Vocab', 'ihm_residues_not_modeled_reason_term_IDkey1']], ), em.Key.define( ['URI'], constraint_names=[['Vocab', 'ihm_residues_not_modeled_reason_term_URIkey1']], ), ] fkey_defs = [ em.ForeignKey.define( ['RCB'], 'public', 'ERMrest_Client', ['ID'], constraint_names=[['Vocab', 'ihm_residues_not_modeled_reason_term_RCB_fkey']], ), em.ForeignKey.define( ['RMB'], 'public', 'ERMrest_Client', ['ID'], constraint_names=[['Vocab', 'ihm_residues_not_modeled_reason_term_RMB_fkey']], ), em.ForeignKey.define( ['Owner'], 'public', 'Catalog_Group', ['ID'], constraint_names=[['Vocab', 'ihm_residues_not_modeled_reason_term_Owner_fkey']], acls={ 'insert': [groups['pdb-curator']], 'update': [groups['pdb-curator']] }, acl_bindings={ 'set_owner': { 'types': ['update', 'insert'], 'scope_acl': ['*'], 'projection': ['ID'], 'projection_type': 'acl' } }, ), ] table_def = em.Table.define( table_name, column_defs=column_defs, key_defs=key_defs, fkey_defs=fkey_defs, annotations=table_annotations, acls=table_acls, acl_bindings=table_acl_bindings, comment=table_comment, provide_system=True ) def main(catalog, mode, replace=False, really=False): updater = CatalogUpdater(catalog) table_def['column_annotations'] = column_annotations table_def['column_comment'] = column_comment updater.update_table(mode, schema_name, table_def, replace=replace, really=really) if __name__ == "__main__": host = 'pdb.isrd.isi.edu' catalog_id = 99 mode, replace, host, catalog_id = parse_args(host, catalog_id, is_table=True) catalog = ErmrestCatalog('https', host, catalog_id=catalog_id, credentials=get_credential(host)) main(catalog, mode, replace)
26604b1e653b586dcc138356474bf5459ea54e2e
604fdb2c4fa24237d206e7c8835bb2c21b0a2fb7
/ari/v1/client.py
0f438dfd979c9fed793cc6fef8f04f0b37e2bc6d
[ "Apache-2.0" ]
permissive
SibghatullahSheikh/python-ari
d8d87d213c1a52b0ed46a8ea50362b93c772325b
f4a6f870513bc74bf96606168e0d2173ed2f2ebb
refs/heads/master
2021-01-22T00:13:37.707863
2014-01-29T21:06:52
2014-01-29T21:06:52
null
0
0
null
null
null
null
UTF-8
Python
false
false
1,344
py
# -*- coding: utf-8 -*- # Copyright 2012 OpenStack LLC. # Copyright (c) 2013 PolyBeacon, 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. from ari.common import http from ari.v1 import application from ari.v1 import bridge from ari.v1 import channel from ari.v1 import devicestate from ari.v1 import endpoint from ari.v1 import sound class Client(http.HTTPClient): """Client for the ARI v1 API. """ def __init__(self, *args, **kwargs): super(Client, self).__init__(*args, **kwargs) self.applications = application.ApplicationManager(self) self.bridges = bridge.BridgeManager(self) self.channels = channel.ChannelManager(self) self.devicestates = devicestate.DeviceStateManager(self) self.endpoints = endpoint.EndpointManager(self) self.sounds = sound.SoundManager(self)
a74af5013611c1d1945d2e4250a4c532a725e0bd
6b2a8dd202fdce77c971c412717e305e1caaac51
/solutions_6404600001200128_0/Python/kawasaki/solve.py
13028d9808e7f822dbd94054186f11d1384f2212
[]
no_license
alexandraback/datacollection
0bc67a9ace00abbc843f4912562f3a064992e0e9
076a7bc7693f3abf07bfdbdac838cb4ef65ccfcf
refs/heads/master
2021-01-24T18:27:24.417992
2017-05-23T09:23:38
2017-05-23T09:23:38
84,313,442
2
4
null
null
null
null
UTF-8
Python
false
false
371
py
T = int(raw_input()) for test_index in xrange(T): N = int(raw_input()) m = map(int, raw_input().split()) y = 0 for i in xrange(N - 1): y += max(m[i] - m[i + 1], 0) d = max(max(m[i] - m[i + 1], 0) for i in xrange(N - 1)) z = 0 for i in xrange(N - 1): z += min(d, m[i]) print 'Case #{}: {} {}'.format(test_index + 1, y, z)
5d64b3ec43f8f8706fbb5bc2f4c1dea3573739ee
d6d87140d929262b5228659f89a69571c8669ec1
/airbyte-connector-builder-server/connector_builder/generated/models/stream_slicer.py
56c37db2c82d4d65076de8f3b5e19e85d772378d
[ "MIT", "Elastic-2.0" ]
permissive
gasparakos/airbyte
b2bb2246ec6a10e1f86293da9d86c61fc4a4ac65
17c77fc819ef3732fb1b20fa4c1932be258f0ee9
refs/heads/master
2023-02-22T20:42:45.400851
2023-02-09T07:43:24
2023-02-09T07:43:24
303,604,219
0
0
MIT
2020-10-13T06:18:04
2020-10-13T06:06:17
null
UTF-8
Python
false
false
527
py
# coding: utf-8 from __future__ import annotations from datetime import date, datetime # noqa: F401 import re # noqa: F401 from typing import Any, Dict, List, Optional # noqa: F401 from pydantic import AnyUrl, BaseModel, EmailStr, Field, validator # noqa: F401 class StreamSlicer(BaseModel): """NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). Do not edit the class manually. StreamSlicer - a model defined in OpenAPI """ StreamSlicer.update_forward_refs()
e5d021f764bf2a500658c2a962784f56ffc0f864
2b167e29ba07e9f577c20c54cb943861d0ccfa69
/numerical_analysis_backup/small-scale-multiobj/pod100_sa/pareto_arch2/pareto_ff/pareto8.py
c934f4633c223ab3a0093473ad66da38262a6453
[]
no_license
LiYan1988/kthOld_OFC
17aeeed21e195d1a9a3262ec2e67d6b1d3f9ff0f
b1237577ea68ad735a65981bf29584ebd889132b
refs/heads/master
2021-01-11T17:27:25.574431
2017-01-23T05:32:35
2017-01-23T05:32:35
79,773,237
0
0
null
null
null
null
UTF-8
Python
false
false
2,048
py
# -*- coding: utf-8 -*- """ Created on Thu Aug 4 15:15:10 2016 @author: li optimize both throughput and connections """ #import sys #sys.path.insert(0, '/home/li/Dropbox/KTH/numerical_analysis/ILPs') import csv from gurobipy import * import numpy as np from arch2_decomposition_new import Arch2_decompose np.random.seed(2010) num_cores=3 num_slots=80 i = 8 time_limit_routing = 1200 # 1000 time_limit_sa = 108 # 10800 filename = 'traffic_matrix__matrix_'+str(i)+'.csv' # print filename tm = [] with open(filename) as f: reader = csv.reader(f) for idx, row in enumerate(reader): if idx>11: row.pop() row = [int(u) for u in row] tm.append(row) tm = np.array(tm)*25 #%% arch2 betav1 = np.arange(0,0.105,0.005) betav2 = np.arange(0.15,1.05,0.05) betav3 = np.arange(10, 110, 10) betav = np.concatenate((betav1, betav2, betav3)) connection_ub = [] throughput_ub = [] connection_lb = [] throughput_lb = [] obj_ub = [] obj_lb = [] for beta in betav: m = Arch2_decompose(tm, num_slots=num_slots, num_cores=num_cores,alpha=1,beta=beta) m.create_model_routing(mipfocus=1,timelimit=time_limit_routing,mipgap=0.01, method=2) m.sa_heuristic(ascending1=False,ascending2=False) connection_ub.append(m.connections_ub) throughput_ub.append(m.throughput_ub) obj_ub.append(m.alpha*m.connections_ub+m.beta*m.throughput_ub) connection_lb.append(m.obj_sah_connection_) throughput_lb.append(m.obj_sah_throughput_) obj_lb.append(m.alpha*m.obj_sah_connection_+m.beta*m.obj_sah_throughput_) # print m.obj_sah_/float(m.alpha*m.connections_ub+m.beta*m.throughput_ub) result = np.array([betav,connection_ub,throughput_ub,obj_ub, connection_lb,throughput_lb,obj_lb]).T file_name = "result_pareto{}.csv".format(i) with open(file_name, 'w') as f: writer = csv.writer(f, delimiter=',') writer.writerow(['beta', 'connection_ub', 'throughput_ub', 'obj_ub', 'connection_lb', 'throughput_lb', 'obj_lb']) writer.writerows(result)
94f78ff7515cedf224519e07f552630acac3127a
a857d1911a118b8aa62ffeaa8f154c8325cdc939
/toontown/estate/DistributedFireworksCannon.py
d5691917f5a2a6d4d53e4cdd97782a58257a8ec5
[ "MIT" ]
permissive
DioExtreme/TT-CL-Edition
761d3463c829ec51f6bd2818a28b667c670c44b6
6b85ca8352a57e11f89337e1c381754d45af02ea
refs/heads/main
2023-06-01T16:37:49.924935
2021-06-24T02:25:22
2021-06-24T02:25:22
379,310,849
0
0
MIT
2021-06-22T15:07:31
2021-06-22T15:07:30
null
UTF-8
Python
false
false
4,308
py
from toontown.toonbase.ToontownGlobals import * from direct.interval.IntervalGlobal import * from direct.distributed.ClockDelta import * from HouseGlobals import * from toontown.effects import DistributedFireworkShow from toontown.toonbase import ToontownGlobals from toontown.toonbase import TTLocalizer from panda3d.core import CollisionSphere, CollisionNode import FireworksGui class DistributedFireworksCannon(DistributedFireworkShow.DistributedFireworkShow): notify = directNotify.newCategory('DistributedFireworksCannon') def __init__(self, cr): DistributedFireworkShow.DistributedFireworkShow.__init__(self, cr) self.fireworksGui = None self.load() return def generateInit(self): DistributedFireworkShow.DistributedFireworkShow.generateInit(self) self.fireworksSphereEvent = self.uniqueName('fireworksSphere') self.fireworksSphereEnterEvent = 'enter' + self.fireworksSphereEvent self.fireworksGuiDoneEvent = 'fireworksGuiDone' self.shootEvent = 'fireworkShootEvent' self.collSphere = CollisionSphere(0, 0, 0, 2.5) self.collSphere.setTangible(1) self.collNode = CollisionNode(self.fireworksSphereEvent) self.collNode.setIntoCollideMask(ToontownGlobals.WallBitmask) self.collNode.addSolid(self.collSphere) self.collNodePath = self.geom.attachNewNode(self.collNode) def generate(self): DistributedFireworkShow.DistributedFireworkShow.generate(self) def announceGenerate(self): self.notify.debug('announceGenerate') self.accept(self.fireworksSphereEnterEvent, self.__handleEnterSphere) def disable(self): self.notify.debug('disable') self.ignore(self.fireworksSphereEnterEvent) self.ignore(self.shootEvent) self.ignore(self.fireworksGuiDoneEvent) if self.fireworksGui: self.fireworksGui.destroy() self.fireworksGui = None DistributedFireworkShow.DistributedFireworkShow.disable(self) return def delete(self): self.notify.debug('delete') self.geom.removeNode() DistributedFireworkShow.DistributedFireworkShow.delete(self) def load(self): self.geom = loader.loadModel('phase_5/models/props/trashcan_TT.bam') self.geom.reparentTo(base.cr.playGame.hood.loader.geom) self.geom.setScale(0.5) def __handleEnterSphere(self, collEntry): self.notify.debug('handleEnterSphere()') self.ignore(self.fireworksSphereEnterEvent) self.sendUpdate('avatarEnter', []) def __handleFireworksDone(self): self.ignore(self.fireworksGuiDoneEvent) self.ignore(self.shootEvent) self.sendUpdate('avatarExit') self.fireworksGui.destroy() self.fireworksGui = None return def freeAvatar(self): base.localAvatar.posCamera(0, 0) base.cr.playGame.getPlace().setState('walk') self.accept(self.fireworksSphereEnterEvent, self.__handleEnterSphere) def setMovie(self, mode, avId, timestamp): timeStamp = globalClockDelta.localElapsedTime(timestamp) isLocalToon = avId == base.localAvatar.doId if mode == FIREWORKS_MOVIE_CLEAR: self.notify.debug('setMovie: clear') return elif mode == FIREWORKS_MOVIE_GUI: self.notify.debug('setMovie: gui') if isLocalToon: self.fireworksGui = FireworksGui.FireworksGui(self.fireworksGuiDoneEvent, self.shootEvent) self.accept(self.fireworksGuiDoneEvent, self.__handleFireworksDone) self.accept(self.shootEvent, self.localShootFirework) return else: self.notify.warning('unknown mode in setMovie: %s' % mode) def setPosition(self, x, y, z): self.pos = [x, y, z] self.geom.setPos(x, y, z) def localShootFirework(self, index): style = index col1, col2 = self.fireworksGui.getCurColor() amp = 30 dummy = base.localAvatar.attachNewNode('dummy') dummy.setPos(0, 100, 60) pos = dummy.getPos(render) dummy.removeNode() print 'lauFirework: %s, col=%s' % (index, col1) self.d_requestFirework(pos[0], pos[1], pos[2], style, col1, col2)
d6d0d58f05ad22c9474ef9804ec088549a68f841
5b6b2018ab45cc4710cc5146040bb917fbce985f
/200_longest-palindromic-substring/longest-palindromic-substring.py
60710ba54ef2ad0d3d20d4f30fd1db4aec65a148
[]
no_license
ultimate010/codes_and_notes
6d7c7d42dcfd84354e6fcb5a2c65c6029353a328
30aaa34cb1c840f7cf4e0f1345240ac88b8cb45c
refs/heads/master
2021-01-11T06:56:11.401869
2016-10-30T13:46:39
2016-10-30T13:46:39
72,351,982
0
0
null
null
null
null
UTF-8
Python
false
false
1,016
py
# coding:utf-8 ''' @Copyright:LintCode @Author: ultimate010 @Problem: http://www.lintcode.com/problem/longest-palindromic-substring @Language: Python @Datetime: 16-06-28 14:08 ''' class Solution: # @param {string} s input string # @return {string} the longest palindromic substring def longestPalindrome(self, s): # Write your code here n = len(s) if n <= 1: return s m = 1 ret = '' for i in range(1, 2*n): # at least 2 char if i & 1 == 1: # odd t = i / 2 j = t else: # even t = i / 2 - 1 j = t + 1 while t >= 0 and j < n and s[t] == s[j]: t -= 1 j += 1 # print t, j if t == i: pass # one char else: if j - t - 1 > m: m = j - t - 1 ret = s[t + 1: j] return ret
3fa5ddad1d1612a8b0d4168c59f4f0549f95f6ff
ca7aa979e7059467e158830b76673f5b77a0f5a3
/Python_codes/p02937/s033330652.py
6b68eb0299616b86752097386250b1b8f9320039
[]
no_license
Aasthaengg/IBMdataset
7abb6cbcc4fb03ef5ca68ac64ba460c4a64f8901
f33f1c5c3b16d0ea8d1f5a7d479ad288bb3f48d8
refs/heads/main
2023-04-22T10:22:44.763102
2021-05-13T17:27:22
2021-05-13T17:27:22
367,112,348
0
0
null
null
null
null
UTF-8
Python
false
false
473
py
import bisect s = input() t = input() n = len(s) m = len(t) indices = [[] for _ in range(26)] for i in range(n): indices[ord(s[i]) - ord('a')].append(i) for i in range(n): indices[ord(s[i]) - ord('a')].append(i + n) ans = 0 p = 0 for i in range(m): c = ord(t[i]) - ord('a') if len(indices[c]) == 0: print(-1) exit() p = indices[c][bisect.bisect_left(indices[c], p)] + 1 if p >= n: p -= n ans += n ans += p print(ans)
171918eacf53dc68cdf837f4e9b33d81ba426350
a533010ba7e74422c5c7c0193ea2d880e427cb9d
/Python_auto_operation/bin/mlogvis
69b36f81947475e66d1dde10eb0cb5c3e1d112c6
[]
no_license
gateray/learning_python
727b3effe4875f27c86c3e5e66655905f3d5d681
bc08a58f3a5c1f1db884398efa9d27834514199f
refs/heads/master
2021-01-19T06:31:01.616421
2016-06-30T07:39:23
2016-06-30T07:39:23
62,290,273
0
0
null
null
null
null
UTF-8
Python
false
false
345
#!/home/gateray/PycharmProjects/Python_auto_operation/bin/python # EASY-INSTALL-ENTRY-SCRIPT: 'mtools==1.1.9','console_scripts','mlogvis' __requires__ = 'mtools==1.1.9' import sys from pkg_resources import load_entry_point if __name__ == '__main__': sys.exit( load_entry_point('mtools==1.1.9', 'console_scripts', 'mlogvis')() )
[ "gateray.example.com" ]
gateray.example.com
32f6b9fff9acce58bdc331e9f0ec63770932d681
0a639bda0058ac76cca97d6123f6c39229f202f1
/companies/models.py
9092279495371d6cf60c4e5d5b187922621a9bb7
[]
no_license
sanchitbareja/occuhunt-web
bb86e630c2caff5815b164435464424b5cf83375
fab152e2ebae3f4dd5c8357696893065bdd30504
refs/heads/master
2020-05-21T01:15:48.973953
2015-01-13T04:03:18
2015-01-13T04:03:18
12,552,735
0
0
null
null
null
null
UTF-8
Python
false
false
3,089
py
from django.db import models import datetime # Create your models here. class CompanyType(models.Model): type = models.CharField(max_length = 256) def __unicode__(self): return self.type ORGANIZATION_TYPES_LIST = ( ('Accounting Services', 'Accounting Services'), ('Aerospace/Defense', 'Aerospace/Defense'), ('Agriculture', 'Agriculture'), ('Architecture/Planning', 'Architecture/Planning'), ('Arts and Entertainment', 'Arts and Entertainment'), ('Automotive/Transportation Manufacturing', 'Automotive/Transportation Manufacturing'), ('Biotech/Pharmaceuticals','Biotech/Pharmaceuticals'), ('Chemicals','Chemicals'), ('Computer Hardware','Computer Hardware'), ('Computer Software', 'Computer Software'), ('Consumer Products', 'Consumer Products'), ('Diversified Services', 'Diversified Services'), ('Education/Higher Education', 'Education/Higher Education'), ('Electronics and Misc. Tech', 'Electronics and Misc. Tech'), ('Energy', 'Energy'), ('Engineering', 'Engineering'), ('Financial Services', 'Financial Services'), ('Food, Beverage and Tobacco', 'Food, Beverage and Tobacco'), ('Government', 'Government'), ('Health Products and Services', 'Health Products and Services'), ('Hospital/Healthcare', 'Hospital/Healthcare'), ('Insurance', 'Insurance'), ('Law/Law Related', 'Law/Law Related'), ('Leisure and Travel', 'Leisure and Travel'), ('Materials and Construction', 'Materials and Construction'), ('Media', 'Media'), ('Metals and Mining', 'Metals and Mining'), ('Non-Profit and Social Services', 'Non-Profit and Social Services'), ('Other Manufacturing', 'Other Manufacturing'), ('Professional, Technical, and Administrative Services', 'Professional, Technical, and Administrative Services'), ('Real Estate', 'Real Estate'), ('Retail and Wholesale Trade', 'Retail and Wholesale Trade'), ('Telecommunications', 'Telecommunications'), ('Transportation Services', 'Transportation Services'), ('Utilities', 'Utilities'), ('Other', 'Other'), ) class Company(models.Model): name = models.CharField(max_length=512) founded = models.CharField(max_length=64, null=True, blank=True) funding = models.CharField(max_length=64, null=True, blank=True) website = models.URLField(max_length=512, null=True, blank=True) careers_website = models.URLField(max_length=512, null=True, blank=True) logo = models.URLField(max_length=512, null=True, blank=True) banner_image = models.URLField(max_length=512, null=True, blank=True) number_employees = models.CharField(max_length=48, null=True, blank=True) organization_type = models.CharField(max_length=512, null=True, blank=True, choices=ORGANIZATION_TYPES_LIST) company_description = models.TextField(null=True, blank=True) competitors = models.CharField(max_length=512, null=True, blank=True) avg_salary = models.CharField(max_length=64, null=True, blank=True) location = models.CharField(max_length=512, null=True, blank=True) intro_video = models.TextField(null=True, blank=True) timestamp = models.DateTimeField(auto_now=False, auto_now_add=True) def __unicode__(self): return self.name
1c165f1ccad36c215f56ef5613cea7ee2101c812
1facfd9d94b0f08ddde2834c717bda55359c2e35
/Python programming for the absolute beginner - Michael Dawson/Chapter 8 - OOP beginning/8.3.py
58bad4a7400168c26ceaa2894583a1b3bd76ba4e
[]
no_license
echpochmak/ppftab
9160383c1d34a559b039af5cd1451a18f2584549
f5747d87051d837eca431f782491ec9ba3b44626
refs/heads/master
2021-09-15T07:23:06.581750
2018-05-28T14:33:13
2018-05-28T14:33:13
261,880,781
1
0
null
2020-05-06T21:18:13
2020-05-06T21:18:13
null
UTF-8
Python
false
false
3,000
py
# The material form the book in polish # Opiekun zwierzaka # Wirtualny pupil, którym należy się opiekować class Critter(object): """Wirtualny pupil""" def __init__(self, name, hunger = 0, boredom = 0): self.name = name self.hunger = hunger self.boredom = boredom def __str__(self): rep = "The valuse of your pet:\n" rep += "The hunger = " + str(self.hunger) rep += "\nThe boredom = " + str(self.boredom) return rep def __pass_time(self): self.hunger += 1 self.boredom += 1 @property def mood(self): unhappiness = self.hunger + self.boredom if unhappiness < 5: m = "szczęśliwy" elif 5 <= unhappiness <= 10: m = "zadowolony" elif 11 <= unhappiness <= 15: m = "podenerwowany" else: m = "wściekły" return m def talk(self): print("Nazywam się", self.name, "i jestem", self.mood, "teraz.\n") self.__pass_time() def eat(self, food = 4): print(""" How much food would you like to serve to you pet? \n 1. Type 1 for one snack. \n 2. Type 2 for 2 snacks. \n 3. Type 3 for 3 snacks. \n 4. Type 4 for 4 snacks. \n 5. Type 5 for 5 snacks. """, end = " ") food = int(input("Wybierasz: ")) print("Mniam, mniam. Dziękuję.") self.hunger -= food if self.hunger < 0: self.hunger = 0 self.__pass_time() def play(self, fun = 4): print(""" How log would you like to play with your pet? \n 1. Type 1 for one minute. \n 2. Type 2 for 2 minutes. \n 3. Type 3 for 3 minutes. \n 4. Type 4 for 4 minutes. \n 5. Type 5 for 5 minutes. """, end = " ") fun = int(input("Wybierasz: ")) print("Hura!") self.boredom -= fun if self.boredom < 0: self.boredom = 0 self.__pass_time() def main(): crit_name = input("Jak chcesz nazwać swojego zwierzaka?: ") crit = Critter(crit_name) choice = None while choice != "0": print \ (""" Opiekun zwierzaka 0 - zakończ 1 - słuchaj swojego zwierzaka 2 - nakarm swojego zwierzaka 3 - pobaw się ze swoim zwierzakiem 4 - show the values of your pet """) choice = input("Wybierasz: ") print() # wyjdź z pętli if choice == "0": print("Do widzenia.") # słuchaj swojego zwierzaka elif choice == "1": crit.talk() # nakarm swojego zwierzaka elif choice == "2": crit.eat() # pobaw się ze swoim zwierzakiem elif choice == "3": crit.play() elif choice == "4": print(crit) # nieznany wybór else: print("\nNiestety,", choice, "nie jest prawidłowym wyborem.") main() input("\n\nAby zakończyć program, naciśnij klawisz Enter.")
26aa690ec62cb1867208234cd0c19ab8f7a9663a
3d19e1a316de4d6d96471c64332fff7acfaf1308
/Users/S/stefanw/kommunalverwaltung_nrw.py
aef5bdefc3a1b54035f7bc556bd8da592cd801c6
[]
no_license
BerilBBJ/scraperwiki-scraper-vault
4e98837ac3b1cc3a3edb01b8954ed00f341c8fcc
65ea6a943cc348a9caf3782b900b36446f7e137d
refs/heads/master
2021-12-02T23:55:58.481210
2013-09-30T17:02:59
2013-09-30T17:02:59
null
0
0
null
null
null
null
UTF-8
Python
false
false
5,508
py
import scraperwiki import lxml.html as lh from lxml import etree LIST_URL = 'http://www3.chamaeleon.de/komnav/kundensuchergebnis.php?Ort=&PLZ=%s&OBGM=&Bundesland=Nordrhein-Westfalen&anfrage=imnrw' DETAIL_URL = 'http://www3.chamaeleon.de/komnav/kundensuchedetail.php?schluessel=%s&anfrage=imnrw&PLZ=%s&Ort=&Bundesland=Nordrhein-Westfalen&OBGM=&single_search=' def plz_generator(): for i in (3,4,5): for j in range(10): yield "%s%s" % (i, j) kommune = [] for plz in plz_generator(): print plz content = scraperwiki.scrape(LIST_URL % plz) content = content.decode('latin1') if 'Leider keinen Datensatz gefunden' in content: continue doc = lh.fromstring(content) for row in doc.cssselect('tr'): td = row.cssselect('td') if not td: continue kommune.append({ 'name': td[0].text_content().strip(), 'plz': td[1].text_content().strip(), 'head': td[3].text_content().strip(), 'key': td[4].cssselect('a')[0].attrib['href'].split('schluessel=')[1].split('&anfrage=')[0], 'source': td[4].cssselect('a')[0].attrib['href'] }) wanted = { u'': None, u'Stadt-/Gemeinde-/Kreisname': None, u'PLZ': None, u'Bundesland': None, u'Bev\xf6lkerungsdichte Einwohner pro km\xb2': None, u'(Ober-)b\xfcrgermeisterin/Landr\xe4tin/Oberkreisdirektorinbzw.(Ober-)b\xfcrgermeister/Landrat/Oberkreisdirektor': None, u'EMail': 'email', u'Postanschrift': 'address', u'Regierungsbezirk': 'gov_area', u'Fax': 'fax', u'Telefonzentrale': 'phone', u'Hausanschrift (Verwaltungssitz)': 'address2', u'PLZ-Hausanschrift': 'plz2', u'Ausl\xe4nderanteil (in %)': 'immigrant_percentage', u'EinwohnerInnen': 'population', u'davon weiblich/m\xe4nnlich (in %)': 'female_male_percentage', u'Fl\xe4che (in km\xb2)': 'area', u'Anzahl Besch\xe4ftigte': 'employees', u'Homepage der Kommune': 'url' } print repr(wanted.keys()) for kom in kommune: for v in wanted.values(): if v is not None: kom[v] = None content = scraperwiki.scrape(DETAIL_URL % (kom['key'], kom['plz'])) content = content.decode('latin1') doc = lh.fromstring(content) for row in doc.cssselect('tr'): td = row.cssselect('td') if not td: continue key = td[0].text_content().split(':')[0].strip() if wanted.get(key, None) is not None: kom[wanted[key]] = td[1].text_content().strip() elif key not in wanted: print repr(key) print repr(kom) scraperwiki.sqlite.save(['key'], kom, table_name='nrw_kommune')import scraperwiki import lxml.html as lh from lxml import etree LIST_URL = 'http://www3.chamaeleon.de/komnav/kundensuchergebnis.php?Ort=&PLZ=%s&OBGM=&Bundesland=Nordrhein-Westfalen&anfrage=imnrw' DETAIL_URL = 'http://www3.chamaeleon.de/komnav/kundensuchedetail.php?schluessel=%s&anfrage=imnrw&PLZ=%s&Ort=&Bundesland=Nordrhein-Westfalen&OBGM=&single_search=' def plz_generator(): for i in (3,4,5): for j in range(10): yield "%s%s" % (i, j) kommune = [] for plz in plz_generator(): print plz content = scraperwiki.scrape(LIST_URL % plz) content = content.decode('latin1') if 'Leider keinen Datensatz gefunden' in content: continue doc = lh.fromstring(content) for row in doc.cssselect('tr'): td = row.cssselect('td') if not td: continue kommune.append({ 'name': td[0].text_content().strip(), 'plz': td[1].text_content().strip(), 'head': td[3].text_content().strip(), 'key': td[4].cssselect('a')[0].attrib['href'].split('schluessel=')[1].split('&anfrage=')[0], 'source': td[4].cssselect('a')[0].attrib['href'] }) wanted = { u'': None, u'Stadt-/Gemeinde-/Kreisname': None, u'PLZ': None, u'Bundesland': None, u'Bev\xf6lkerungsdichte Einwohner pro km\xb2': None, u'(Ober-)b\xfcrgermeisterin/Landr\xe4tin/Oberkreisdirektorinbzw.(Ober-)b\xfcrgermeister/Landrat/Oberkreisdirektor': None, u'EMail': 'email', u'Postanschrift': 'address', u'Regierungsbezirk': 'gov_area', u'Fax': 'fax', u'Telefonzentrale': 'phone', u'Hausanschrift (Verwaltungssitz)': 'address2', u'PLZ-Hausanschrift': 'plz2', u'Ausl\xe4nderanteil (in %)': 'immigrant_percentage', u'EinwohnerInnen': 'population', u'davon weiblich/m\xe4nnlich (in %)': 'female_male_percentage', u'Fl\xe4che (in km\xb2)': 'area', u'Anzahl Besch\xe4ftigte': 'employees', u'Homepage der Kommune': 'url' } print repr(wanted.keys()) for kom in kommune: for v in wanted.values(): if v is not None: kom[v] = None content = scraperwiki.scrape(DETAIL_URL % (kom['key'], kom['plz'])) content = content.decode('latin1') doc = lh.fromstring(content) for row in doc.cssselect('tr'): td = row.cssselect('td') if not td: continue key = td[0].text_content().split(':')[0].strip() if wanted.get(key, None) is not None: kom[wanted[key]] = td[1].text_content().strip() elif key not in wanted: print repr(key) print repr(kom) scraperwiki.sqlite.save(['key'], kom, table_name='nrw_kommune')
323a4c7eddab68f041ff6fe4f9828b26f769b0ca
525c6a69bcf924f0309b69f1d3aff341b06feb8e
/sunyata/backend/chainer/core/map/power.py
f883795e8d4b0bb7d086f28a97f498406b350ed9
[]
no_license
knighton/sunyata_2017
ba3af4f17184d92f6277d428a81802ac12ef50a4
4e9d8e7d5666d02f9bb0aa9dfbd16b7a8e97c1c8
refs/heads/master
2021-09-06T13:19:06.341771
2018-02-07T00:28:07
2018-02-07T00:28:07
null
0
0
null
null
null
null
UTF-8
Python
false
false
406
py
from chainer import functions as F from ....base.core.map.power import BasePowerAPI class ChainerPowerAPI(BasePowerAPI): def __init__(self): BasePowerAPI.__init__(self) def pow(self, x, a): return F.math.basic_math.pow(x, a) def rsqrt(self, x): return F.rsqrt(x) def sqrt(self, x): return F.sqrt(x) def square(self, x): return F.square(x)