blob_id
stringlengths 40
40
| directory_id
stringlengths 40
40
| path
stringlengths 3
616
| content_id
stringlengths 40
40
| detected_licenses
sequencelengths 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 777
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 149
values | src_encoding
stringclasses 26
values | language
stringclasses 1
value | is_vendor
bool 2
classes | is_generated
bool 2
classes | length_bytes
int64 3
10.2M
| extension
stringclasses 188
values | content
stringlengths 3
10.2M
| authors
sequencelengths 1
1
| author_id
stringlengths 1
132
|
---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
8163546f2fecc94e106eccfc43d3314cb39e1bbd | 26594819e61d1a5f290bb579c5326adbfcce0373 | /training/config.py | 25dc1f6c9a640b11046d9c9ff42d75afc367f761 | [] | no_license | overminder/fyp | 50ba90987fbfc5788d4021d943eebb2027adea45 | a9fe79a5a04589ee1866981c68ff8404cc7efeba | refs/heads/master | 2021-01-23T06:26:37.631250 | 2012-05-15T07:19:32 | 2012-05-15T07:19:32 | 1,816,661 | 0 | 1 | null | null | null | null | UTF-8 | Python | false | false | 94 | py | from util import local_path
def get_database_path():
return local_path('store.sqlite3')
| [
"[email protected]"
] | |
af5ee455cb7393efd56233ca1556032ce3b6435c | 4c68778814b938d91d184749b50940549439c0f3 | /scheme/fields/time.py | fe6e0bb58b391be8c8074c6fe7792ac82fede471 | [
"LicenseRef-scancode-warranty-disclaimer",
"BSD-3-Clause",
"LicenseRef-scancode-unknown-license-reference"
] | permissive | jordanm/scheme | 96a747258ce68de756ffe7996b37c3e8747a740c | 5a87e24b35bb2f80b474273bf2e5c5fd563214e0 | refs/heads/master | 2021-01-17T05:48:51.479427 | 2020-01-20T16:03:28 | 2020-01-20T16:03:28 | 32,604,302 | 8 | 4 | NOASSERTION | 2020-01-20T16:03:29 | 2015-03-20T20:05:12 | Python | UTF-8 | Python | false | false | 3,174 | py | from __future__ import absolute_import
from datetime import time
from time import strptime
from scheme.exceptions import *
from scheme.field import *
__all__ = ('Time',)
class Time(Field):
"""A field for time values."""
basetype = 'time'
equivalent = time
parameters = {'maximum': None, 'minimum': None}
pattern = '%H:%M:%S'
errors = [
FieldError('invalid', 'invalid value', '%(field)s must be a time value'),
FieldError('minimum', 'minimum value', '%(field)s must not occur before %(minimum)s'),
FieldError('maximum', 'maximum value', '%(field)s must not occur after %(maximum)s'),
]
def __init__(self, minimum=None, maximum=None, **params):
super(Time, self).__init__(**params)
if maximum is not None:
try:
maximum = self._unserialize_value(maximum)
except InvalidTypeError:
raise TypeError("argument 'maximum' must be either None, a datetime.time,"
" or a string in the format 'HH:MM:SS'")
if minimum is not None:
try:
minimum = self._unserialize_value(minimum)
except InvalidTypeError:
raise TypeError("argument 'minimum' must be either None, a datetime.time,"
" or a string in the format 'HH:MM:SS'")
self.maximum = maximum
self.minimum = minimum
def __repr__(self):
aspects = []
if self.minimum is not None:
aspects.append('minimum=%r' % self.minimum)
if self.maximum is not None:
aspects.append('maximum=%r' % self.maximum)
return super(Time, self).__repr__(aspects)
def describe(self, parameters=None, verbose=False):
params = {}
if self.maximum is not None:
params['maximum'] = self.maximum.strftime(self.pattern)
if self.minimum is not None:
params['minimum'] = self.minimum.strftime(self.pattern)
return super(Time, self).describe(parameters=parameters, verbose=verbose, **params)
def _serialize_value(self, value):
return value.strftime(self.pattern)
def _unserialize_value(self, value, ancestry=None):
if isinstance(value, time):
return value
try:
return time(*strptime(value, self.pattern)[3:6])
except Exception:
raise InvalidTypeError(identity=ancestry, field=self,
value=value).construct('invalid')
def _validate_value(self, value, ancestry):
if not isinstance(value, time):
raise InvalidTypeError(identity=ancestry, field=self,
value=value).construct('invalid')
minimum = self.minimum
if minimum is not None and value < minimum:
raise ValidationError(identity=ancestry, field=self, value=value).construct('minimum',
minimum=minimum.strftime(self.pattern))
maximum = self.maximum
if maximum is not None and value > maximum:
raise ValidationError(identity=ancestry, field=self, value=value).construct('maximum',
maximum=maximum.strftime(self.pattern))
| [
"[email protected]"
] | |
6885e4c483c0399abfd20154156beeadf8b508af | d048a865519b5f944e1430c6181d00399c979d9c | /gallery/gallery/urls.py | f765f9c8680d91d33f2171654643694a2b0f21ad | [] | no_license | jithinvijayan007/PaceWisdom- | 5f84261c4ba7f51e25c8c21074b48214a24cb6d2 | 1ba00814a757edb327923afcaf20fe04652efa0e | refs/heads/master | 2023-03-06T04:00:21.729404 | 2021-02-21T18:56:54 | 2021-02-21T18:56:54 | 340,974,786 | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 835 | py | """gallery URL Configuration
The `urlpatterns` list routes URLs to views. For more information please see:
https://docs.djangoproject.com/en/3.0/topics/http/urls/
Examples:
Function views
1. Add an import: from my_app import views
2. Add a URL to urlpatterns: path('', views.home, name='home')
Class-based views
1. Add an import: from other_app.views import Home
2. Add a URL to urlpatterns: path('', Home.as_view(), name='home')
Including another URLconf
1. Import the include() function: from django.urls import include, path
2. Add a URL to urlpatterns: path('blog/', include('blog.urls'))
"""
from django.contrib import admin
from django.urls import path, include
urlpatterns = [
path('admin/', admin.site.urls),
path('',include('user.urls')),
path('',include('img_gallery.urls')),
]
| [
"[email protected]"
] | |
48cd42cf70cd98648276cce423fd29d9850f9d0a | f2ab8ccda7203dd37d61facb9978cf74b781c7f1 | /tests/apps.py | 863cf58e139c91b4d865bed2d8a46b94a061f588 | [
"MIT"
] | permissive | Apkawa/easy-thumbnails-admin | 1991137224dcd117520b2c114d4012daf803776e | 9d7a38f215cdac53a663b00f1d4ff3a3c2a54eb4 | refs/heads/master | 2021-01-01T15:47:34.334792 | 2017-11-23T10:38:09 | 2017-11-23T10:38:09 | 97,703,157 | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 274 | py | try:
from django.apps import AppConfig
except ImportError:
# Early Django versions import everything in test, avoid the failure due to
# AppConfig only existing in 1.7+
AppConfig = object
class TestConfig(AppConfig):
name = 'tests'
label = 'tests'
| [
"[email protected]"
] | |
eed58a6b703faab6b504f4b3a66b4de43ae04f0a | e75521f26a9a6fdbd0b9dbe396b14a5f3c1af305 | /src/repositories/word_classifier_repository.py | 10cf90739a261923161b283cb2b1127ab1de82cd | [] | no_license | Ap3lsin4k/words-as-part-of-speech | 2636edb87d309d44d3d18add14aadd13f7810507 | e7f35d56d65a8f5033498f650265cadbd742a9de | refs/heads/master | 2023-01-31T19:01:11.007917 | 2020-12-15T10:57:20 | 2020-12-15T10:57:20 | 320,807,979 | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 1,258 | py | from bookmark_entity import Bookmark
from language_entity import LanguageEntity
from repositories.dictionary_surfer_common import DictionarySurferRepository
class WordClassifierRepository(DictionarySurferRepository):
def __init__(self, dictionary_entity: LanguageEntity):
super().__init__(dictionary_entity)
def make_response_model(self, part_of_speech, input_word):
self.result = {part_of_speech: {}}
for category_of_property, properties in self.dictionary[part_of_speech].items():
bookmark = Bookmark(part_of_speech, category_of_property)
self.__classify_word_by_property(bookmark, input_word)
if len(self.result[part_of_speech]) == 0:
self.result = None
def __save_property_of_word_to_presentable_format(self, bookmark):
self.result[bookmark.get_part_of_speech()].update({bookmark.category_name: bookmark.property_name})
def __classify_word_by_property(self, bookmark, input_word):
for bookmark.property_name in self.dictionary.get_properties(bookmark):
words_tuple = self.dictionary.get_words_for_property(bookmark)
if input_word in words_tuple:
self.__save_property_of_word_to_presentable_format(bookmark) | [
"[email protected]"
] | |
f6fece3b5719a65008ae0fbe700a817b469a7a51 | e7eff96df8160d3c238bf38068c99c7b8bd3005b | /norman/web/frontend/crops.py | 08fa8b6415e718d05231de41cdbcfc0273dddb39 | [] | no_license | sumansai14/norman | 62c3760b47f15bb474786ac045efad5aff757b95 | 43a8c4e53830d57eb552c3ecb98bf2926c9d0457 | refs/heads/master | 2021-03-16T07:57:17.076408 | 2017-05-23T07:36:37 | 2017-05-23T07:36:37 | 92,188,183 | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 170 | py | from norman.web.frontend.base import BaseAuthTemplateView
class OrganizationCropsListView(BaseAuthTemplateView):
template_name = 'norman/organization/crops_list.html'
| [
"[email protected]"
] | |
2cf1cde00eea109a46c3e5983b4906feef72866f | f0856e60a095ce99ec3497b3f27567803056ac60 | /keras2/keras66_gradient2.py | 0e0d0cc1f27912ef32b11753f760a7606dd315f8 | [] | no_license | hjuju/TF_Study-HAN | dcbac17ce8b8885f5fb7d7f554230c2948fda9ac | c0faf98380e7f220868ddf83a9aaacaa4ebd2c2a | refs/heads/main | 2023-09-04T09:13:33.212258 | 2021-10-27T08:00:49 | 2021-10-27T08:00:49 | 384,371,952 | 1 | 0 | null | null | null | null | UTF-8 | Python | false | false | 479 | py | import numpy as np
import matplotlib.pyplot as plt
f = lambda x: x**2 - 4 * x + 6
gradient = lambda x: 2*x - 4 # f 미분 -> 미분한 값이 0이 되는 지점이 가장 낮은지점 -> 우리가 찾는 지점
x0 = 0.0
MaxIter = 20
learning_rate = 0.25
print("step\tx\tf(x)")
print("{:02d}\t{:6.5f}\t{:6.5f}".format(0, x0, f(x0)))
for i in range(MaxIter):
x1 = x0 - learning_rate * gradient(x0)
x0 = x1
print("{:02d}\t{:6.5f}\t{:6.5f}".format(i+1, x0, f(x0)))
| [
"[email protected]"
] | |
fb2c64c0218df858e821204c4c485f29f4b33c74 | e0527bce5c53a196752d3a16adf50cb60754de5f | /10-How to Stop Programs Crashing Demos/3-is_square.py | 8bf01fcece7fa35279f95d25ece62fa140398965 | [] | no_license | ARWA-ALraddadi/python-tutorial-for-beginners | ddeb657f419fbc176bea273bc9fb6b88d1894191 | 21cedfc47871ca4d25c2382464c60ab0a2121205 | refs/heads/master | 2023-06-30T20:24:30.688800 | 2021-08-08T08:22:29 | 2021-08-08T08:22:29 | 193,094,651 | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 3,066 | py | ################################################################
##
## As a demonstration of a function which applies defensive
## programming in different ways, consider a predicate
## which is intended to return True if a given natural
## number (i.e., a non-negative integer) is a square of
## another natural number.
##
## From this description the function could be "misused" in
## three ways:
##
## 1) It could be given a negative number.
## 2) It could be given a floating point number.
## 3) It could be given a value which is not a number at
## all.
##
## By adding some "defensive" code we can make a naive
## implementation more robust by responding appropriately
## to each of these cases:
##
## 1) A negative number can never be a square of another
## number, so we can always return False in this case.
## Here we choose to do so "silently", not drawing
## attention to the unexpected value at all, since the
## answer returned is still "correct" mathematically.
## 2) A positive floating point number could be a square of
## a natural number so, even though we're not required
## to handle floating point numbers we can still do so,
## but choose to generate a "warning" message in this
## case.
## 3) If the function is given a non-numerical value it
## is reasonable to assume that something is seriously
## wrong with the calling code, so in this case we
## generate an "error" message and return the special
## value None.
#---------------------------------------------------------
# Return True if the given natural number is the square of
# some other natural number
def is_square(natural_number):
from math import sqrt
# Three "defensive" checks follow
## # Check that the parameter is a number
## if not (isinstance(natural_number, int) or isinstance(natural_number, float)):
## print('ERROR - parameter must be numeric, given:', repr(natural_number))
## return None
##
## # Check that the parameter is positive
## if natural_number < 0:
## return False
##
## # Check that the parameter is a natural number
## if isinstance(natural_number, float):
## print('Warning - expected natural, given float:', natural_number)
# Return True if the number's square root is a whole number
return sqrt(natural_number) % 1 == 0
#---------------------------------------------------------
# Some tests
#
# The first of these tests is a "valid" one, but the remaining
# three all provide unexpected inputs. Uncommenting the
# "defensive" checks above will cause the function to respond
# appropriately. (It will crash until the defensive code is
# uncommented. Why?)
print(is_square(36)) # expected input
print()
print(is_square(-1)) # unexpected input, but handled silently
print()
print(is_square(225.0)) # unexpected input, handled with warning
print()
print(is_square('August')) # unexpected input, handled as an error
| [
"[email protected]"
] | |
7bbfd94accf83c65ae4546356bccb460b15a900e | b8ea631aae5d132c7b0236684d5f7c12d3c222be | /Library/Graph/Dijkstra_heapq.py | 6164198b7fcd573492928ce2f82d98e051b23864 | [] | no_license | Ryushi-tech/card3 | 68c429313142e58d4722a1cd5a4acc4ab39ca41f | 883636b2f518e38343a12816c5c641b60a87c098 | refs/heads/master | 2021-07-05T22:46:33.089945 | 2020-12-12T15:31:00 | 2020-12-12T15:31:00 | 209,176,836 | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 708 | py | import heapq
def dijkstra(s):
q = []
dist[s] = 0
heapq.heappush(q, [0, s])
while q:
p, v = heapq.heappop(q)
if dist[v] < p:
continue
for i, x in g[v]:
if dist[i] > dist[v] + x:
dist[i] = dist[v] + x
heapq.heappush(q, [dist[i], i])
n = int(input())
g = [[] for _ in range(n)]
for _ in range(n - 1):
a, b, c = map(int, input().split())
a, b = a - 1, b - 1
g[a].append((b, c))
g[b].append((a, c))
inf = 10 ** 14
dist = [inf] * n
m, k = map(int, input().split())
k = k - 1
dijkstra(k)
for _ in range(m):
e, f = map(int, input().split())
res = dist[e - 1] + dist[f - 1]
print(res)
| [
"[email protected]"
] | |
c7e2d80388cbe425136e01a06bdb2ea24fa604c6 | 9e988c0dfbea15cd23a3de860cb0c88c3dcdbd97 | /sdBs/AllRun/sdssj9-10_163557.64+341427.0/sdB_sdssj9-10_163557.64+341427.0_coadd.py | 39e21f206956741881cd664d37e0bb5ecdba667f | [] | no_license | tboudreaux/SummerSTScICode | 73b2e5839b10c0bf733808f4316d34be91c5a3bd | 4dd1ffbb09e0a599257d21872f9d62b5420028b0 | refs/heads/master | 2021-01-20T18:07:44.723496 | 2016-08-08T16:49:53 | 2016-08-08T16:49:53 | 65,221,159 | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 498 | py | from gPhoton.gMap import gMap
def main():
gMap(band="NUV", skypos=[248.990167,34.240833], skyrange=[0.0333333333333,0.0333333333333], stepsz = 30., cntfile="/data2/fleming/GPHOTON_OUTPUT/LIGHTCURVES/sdBs/sdB_sdssj9-10_163557.64+341427.0/sdB_sdssj9-10_163557.64+341427.0_movie_count.fits", cntcoaddfile="/data2/fleming/GPHOTON_OUTPUT/LIGHTCURVES/sdB/sdB_sdssj9-10_163557.64+341427.0/sdB_sdssj9-10_163557.64+341427.0_count_coadd.fits", overwrite=True, verbose=3)
if __name__ == "__main__":
main()
| [
"[email protected]"
] | |
bde86714c9e9dcc484f3f18212f3921c491fe222 | e50ba4cc303d4165bef9e2917103c084cfbe0e07 | /rating_app/migrations/0016_auto_20201129_1156.py | 25f2b5ff3130d55f5d492b5c185861041cf00086 | [
"MIT"
] | permissive | Antony-me/Ratemyapp | 09049fce54d3a3ed2b256970e7840d20942e8c84 | e547fea82439a3e4f83aa78bf16f93b1ea9ab00b | refs/heads/main | 2023-01-28T16:52:58.635646 | 2020-12-01T16:49:07 | 2020-12-01T16:49:07 | 316,425,507 | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 477 | py | # Generated by Django 3.1.3 on 2020-11-29 11:56
from django.db import migrations, models
import django.db.models.deletion
class Migration(migrations.Migration):
dependencies = [
('rating_app', '0015_profilemerch'),
]
operations = [
migrations.AlterField(
model_name='profilemerch',
name='projects',
field=models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, to='rating_app.post'),
),
]
| [
"[email protected]"
] | |
f82a7850addf3773f1ce92a89e4d51f96cf3f763 | 487ce91881032c1de16e35ed8bc187d6034205f7 | /codes/CodeJamCrawler/16_0_2_neat/16_0_2_tkdkop_pancake.py | 259ec04a68548d92ceed7f438162fc6b46baa760 | [] | 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 | 286 | py | #!/usr/bin/env python
import sys
import itertools
m = sys.stdin.readline()
i = 0
for line in sys.stdin.readlines():
line = line.strip()
i += 1
out_str = "Case #%d: " % i
line += '+'
k = itertools.groupby(line)
out_str += str(len(list(k))-1)
print out_str
| [
"[[email protected]]"
] | |
4723c6f7c093e3989d133cebab10e0c13bf512a0 | ca7aa979e7059467e158830b76673f5b77a0f5a3 | /Python_codes/p03997/s926418877.py | acd277945016fcae9d48adcc8806653b1aeeec5f | [] | 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 | 58 | py | a,b,c,d=eval('['+'int(input()),'*3+'0]');print((a+b)*c//2) | [
"[email protected]"
] | |
cdaec89a7ecfa4ae8042bf31ac073b89b8a58072 | a3387fbcc918acb55d289ffb61b9fb603203dc11 | /Puzzles/2022-01/01_22_balanced_days.py | 924f5189761f280c72866b5565b743883fbda28e | [] | no_license | fbhs-cs/purdys-puzzles | 13e970ff909ff2e093b3b9d9777faac47c099913 | 1cf3f9c52677843fad781e46304e1485a91aae58 | refs/heads/master | 2023-08-17T06:28:06.659751 | 2023-08-09T14:45:43 | 2023-08-09T14:45:43 | 212,085,565 | 4 | 3 | null | null | null | null | UTF-8 | Python | false | false | 1,069 | py | from math import ceil
def is_balanced(num):
n = str(num)
first = n[:ceil(len(n)/2)]
last = n[len(n)//2:]
#print(first,last)
if sum([int(x) for x in first]) == sum([int(x) for x in last]):
return True
else:
return False
def count_balanced(n):
count = 0
for i in range(1,n):
if is_balanced(i):
count += 1
return count
def sum_balanced(n):
total = 0
for i in range(1,n):
if is_balanced(i):
#print(i)
total += i
return total
def find_balanced_dates():
months = {1:31,2:28,3:31,4:30,5:31,6:30,
7:31,8:31,9:30,10:31,11:30,12:31}
count = 0
sum = 0
for month in range(1,13):
for day in range(1,months[month]+1):
day_num = str(month) + str(day) + '2022'
if is_balanced(int(day_num)):
count += 1
sum += int(day_num)
print(day_num)
print(count)
print(sum)
find_balanced_dates()
| [
"[email protected]"
] | |
808ac7632e66327e3f8d1fe634dab41d619f065e | 786de89be635eb21295070a6a3452f3a7fe6712c | /CorAna/tags/V00-00-04/src/ConfigParametersCorAna.py | 8baf5f326ca6758d621cc3f9f8cf43ac75c28720 | [] | no_license | connectthefuture/psdmrepo | 85267cfe8d54564f99e17035efe931077c8f7a37 | f32870a987a7493e7bf0f0a5c1712a5a030ef199 | refs/heads/master | 2021-01-13T03:26:35.494026 | 2015-09-03T22:22:11 | 2015-09-03T22:22:11 | null | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 31,606 | py | #--------------------------------------------------------------------------
# File and Version Information:
# $Id$
#
# Description:
# Module ConfigParametersCorAna...
#
#------------------------------------------------------------------------
"""Is intended as a storage for configuration parameters for CorAna project.
This software was developed for the LCLS project. If you use all or
part of it, please give an appropriate acknowledgment.
@version $Id: template!python!py 4 2008-10-08 19:27:36Z salnikov $
@author Mikhail S. Dubrovin
"""
#------------------------------
# Module's version from CVS --
#------------------------------
__version__ = "$Revision: 4 $"
# $Source$
#--------------------------------
# Imports of standard modules --
#--------------------------------
import sys
import os
from copy import deepcopy
#-----------------------------
# Imports for other modules --
#-----------------------------
#import ConfigParameters as cpbase
from ConfigParameters import * # ConfigParameters
from Logger import logger
from PyQt4 import QtGui # for icons only...
import AppDataPath as apputils # for icons
#---------------------
# Class definition --
#---------------------
class ConfigParametersCorAna ( ConfigParameters ) :
"""Is intended as a storage for configuration parameters for CorAna project.
#@see BaseClass ConfigParameters
#@see OtherClass Parameters
"""
list_pars = []
def __init__ ( self, fname=None ) :
"""Constructor.
@param fname the file name with configuration parameters, if not specified then it will be set to the default value at declaration.
"""
ConfigParameters.__init__(self)
self.declareCorAnaParameters()
self.readParametersFromFile ( fname )
self.initRunTimeParameters()
self.defineStyles()
def initRunTimeParameters( self ) :
self.char_expand = u' \u25BE' # down-head triangle
self.iconsAreLoaded = False
self.plotarray_is_on = False
self.plotg2_is_on = False
self.autoRunStatus = 0 # 0=inctive, 1=split, 2=process, 3=merge
#self.plotimgspe = None
self.plotimgspe_g = None
#-----------------------------
def setIcons(self) :
if self.iconsAreLoaded : return
self.iconsAreLoaded = True
path_icon_contents = apputils.AppDataPath('CorAna/icons/contents.png').path()
path_icon_mail_forward = apputils.AppDataPath('CorAna/icons/mail-forward.png').path()
path_icon_button_ok = apputils.AppDataPath('CorAna/icons/button_ok.png').path()
path_icon_button_cancel = apputils.AppDataPath('CorAna/icons/button_cancel.png').path()
path_icon_exit = apputils.AppDataPath('CorAna/icons/exit.png').path()
path_icon_home = apputils.AppDataPath('CorAna/icons/home.png').path()
path_icon_redo = apputils.AppDataPath('CorAna/icons/redo.png').path()
path_icon_undo = apputils.AppDataPath('CorAna/icons/undo.png').path()
path_icon_reload = apputils.AppDataPath('CorAna/icons/reload.png').path()
path_icon_save = apputils.AppDataPath('CorAna/icons/save.png').path()
path_icon_save_cfg = apputils.AppDataPath('CorAna/icons/fileexport.png').path()
path_icon_edit = apputils.AppDataPath('CorAna/icons/edit.png').path()
path_icon_browser = apputils.AppDataPath('CorAna/icons/fileopen.png').path()
path_icon_monitor = apputils.AppDataPath('CorAna/icons/icon-monitor.png').path()
path_icon_unknown = apputils.AppDataPath('CorAna/icons/icon-unknown.png').path()
path_icon_logviewer = apputils.AppDataPath('CorAna/icons/logviewer.png').path()
path_icon_locked = apputils.AppDataPath('CorAna/icons/locked-icon.png').path()
path_icon_unlocked = apputils.AppDataPath('CorAna/icons/unlocked-icon.png').path()
self.icon_contents = QtGui.QIcon(path_icon_contents )
self.icon_mail_forward = QtGui.QIcon(path_icon_mail_forward)
self.icon_button_ok = QtGui.QIcon(path_icon_button_ok)
self.icon_button_cancel = QtGui.QIcon(path_icon_button_cancel)
self.icon_exit = QtGui.QIcon(path_icon_exit )
self.icon_home = QtGui.QIcon(path_icon_home )
self.icon_redo = QtGui.QIcon(path_icon_redo )
self.icon_undo = QtGui.QIcon(path_icon_undo )
self.icon_reload = QtGui.QIcon(path_icon_reload )
self.icon_save = QtGui.QIcon(path_icon_save )
self.icon_save_cfg = QtGui.QIcon(path_icon_save_cfg )
self.icon_edit = QtGui.QIcon(path_icon_edit )
self.icon_browser = QtGui.QIcon(path_icon_browser )
self.icon_monitor = QtGui.QIcon(path_icon_monitor )
self.icon_unknown = QtGui.QIcon(path_icon_unknown )
self.icon_logviewer = QtGui.QIcon(path_icon_logviewer)
self.icon_lock = QtGui.QIcon(path_icon_locked )
self.icon_unlock = QtGui.QIcon(path_icon_unlocked )
#base_dir = '/usr/share/icons/Bluecurve/24x24/'
#self.icon_contents = QtGui.QIcon(base_dir + 'actions/contents.png')
#self.icon_mail_forward = QtGui.QIcon(base_dir + '../../gnome/24x24/actions/mail-forward.png')
#self.icon_button_ok = QtGui.QIcon(base_dir + 'actions/button_ok.png')
#self.icon_button_cancel = QtGui.QIcon(base_dir + 'actions/button_cancel.png')
#self.icon_exit = QtGui.QIcon(base_dir + 'actions/exit.png')
#self.icon_home = QtGui.QIcon(base_dir + 'actions/gohome.png')
#self.icon_redo = QtGui.QIcon(base_dir + 'actions/redo.png')
#self.icon_undo = QtGui.QIcon(base_dir + 'actions/undo.png')
#self.icon_reload = QtGui.QIcon(base_dir + 'actions/reload.png')
#self.icon_stop = QtGui.QIcon(base_dir + 'actions/stop.png')
#self.icon_save_cfg = QtGui.QIcon(base_dir + 'actions/fileexport.png')
#self.icon_save = QtGui.QIcon(base_dir + 'stock/stock-save.png')
#self.icon_edit = QtGui.QIcon(base_dir + 'actions/edit.png')
#self.icon_browser = QtGui.QIcon(base_dir + 'actions/fileopen.png')
#self.icon_monitor = QtGui.QIcon(base_dir + 'apps/icon-monitor.png')
#self.icon_unknown = QtGui.QIcon(base_dir + 'apps/icon-unknown.png')
#self.icon_logviewer = QtGui.QIcon(base_dir + '../32x32/apps/logviewer.png')
self.icon_logger = self.icon_edit
self.icon_help = self.icon_unknown
self.icon_reset = self.icon_reload
#-----------------------------
def declareCorAnaParameters( self ) :
# Possible typs for declaration : 'str', 'int', 'long', 'float', 'bool'
# GUIInstrExpRun.py.py
# self.fname_cp = self.declareParameter( name='FNAME_CONFIG_PARS', val_def='confpars.txt', type='str' )
# self.fname_ped = self.declareParameter( name='FNAME_PEDESTALS', val_def='my_ped.txt', type='str' )
# self.fname_dat = self.declareParameter( name='FNAME_DATA', val_def='my_dat.txt', type='str' )
# self.instr_dir = self.declareParameter( name='INSTRUMENT_DIR', val_def='/reg/d/psdm', type='str' )
# self.instr_name = self.declareParameter( name='INSTRUMENT_NAME', val_def='XCS', type='str' )
# self.exp_name = self.declareParameter( name='EXPERIMENT_NAME', val_def='xcsi0112', type='str' )
# self.str_run_number = self.declareParameter( name='RUN_NUMBER', val_def='0015', type='str' )
# self.str_run_number_dark= self.declareParameter( name='RUN_NUMBER_DARK', val_def='0014', type='str' )
# GUIMainTB.py
# GUIMainSplit.py
self.current_tab = self.declareParameter( name='CURRENT_TAB' , val_def='Files', type='str' )
# GUILogger.py
self.log_level = self.declareParameter( name='LOG_LEVEL_OF_MSGS', val_def='info', type='str' )
# GUIFiles.py
self.current_file_tab = self.declareParameter( name='CURRENT_FILE_TAB' , val_def='Work/Results', type='str' )
# GUIRun.py
self.current_run_tab = self.declareParameter( name='CURRENT_RUN_TAB' , val_def='Input', type='str' )
# GUIWorkResDirs.py
self.dir_work = self.declareParameter( name='DIRECTORY_WORK', val_def='./work', type='str' )
self.dir_results = self.declareParameter( name='DIRECTORY_RESULTS', val_def='./results', type='str' )
self.fname_prefix = self.declareParameter( name='FILE_NAME_PREFIX', val_def='cora-', type='str' )
self.fname_prefix_cora = self.declareParameter( name='FILE_NAME_PREFIX_CORA', val_def='cora-proc', type='str' )
# GUIDark.py
self.use_dark_xtc_all = self.declareParameter( name='USE_DARK_XTC_ALL_CHUNKS', val_def=True, type='bool' )
self.in_dir_dark = self.declareParameter( name='IN_DIRECTORY_DARK', val_def='/reg/d/psdm/XCS/xcsi0112/xtc',type='str' )
self.in_file_dark = self.declareParameter( name='IN_FILE_NAME_DARK', val_def='e167-r0020-s00-c00.xtc',type='str' )
# GUIFlatField.py
self.ccdcorr_flatfield = self.declareParameter( name='CCD_CORRECTION_FLATFIELD', val_def=False, type='bool' )
self.dname_flat = self.declareParameter( name='DIRECTORY_FLAT', val_def='.',type='str' )
self.fname_flat = self.declareParameter( name='FILE_NAME_FLAT', val_def='flat_field.txt',type='str' )
#self.in_dir_flat = self.declareParameter( name='IN_DIRECTORY_FLAT', val_def='/reg/d/psdm/XCS/xcsi0112/xtc',type='str' )
#self.in_file_flat = self.declareParameter( name='IN_FILE_NAME_FLAT', val_def='e167-r0020-s00-c00.xtc',type='str' )
# GUIBlemish.py
self.ccdcorr_blemish = self.declareParameter( name='CCD_CORRECTION_BLEMISH', val_def=False, type='bool' )
self.dname_blem = self.declareParameter( name='DIRECTORY_BLEM', val_def='.',type='str' )
self.fname_blem = self.declareParameter( name='FILE_NAME_BLEM', val_def='blemish.txt',type='str' )
#self.in_dir_blem = self.declareParameter( name='IN_DIRECTORY_BLEM', val_def='/reg/d/psdm/XCS/xcsi0112/xtc',type='str' )
#self.in_file_blem = self.declareParameter( name='IN_FILE_NAME_BLEM', val_def='e167-r0020-s00-c00.xtc',type='str' )
# GUIData.py
self.use_data_xtc_all = self.declareParameter( name='USE_DATA_XTC_ALL_CHUNKS', val_def=True, type='bool' )
self.is_active_data_gui = self.declareParameter( name='IS_ACTIVE_DATA_GUI', val_def=True, type='bool' )
self.in_dir_data = self.declareParameter( name='IN_DIRECTORY_DATA', val_def='/reg/d/psdm/XCS/xcsi0112/xtc',type='str' )
self.in_file_data = self.declareParameter( name='IN_FILE_NAME_DATA', val_def='e167-r0020-s00-c00.xtc',type='str' )
# GUISetupBeamZero.py
self.x_coord_beam0 = self.declareParameter( name='X_COORDINATE_BEAM_ZERO', val_def=1234.5, type='float' )
self.y_coord_beam0 = self.declareParameter( name='Y_COORDINATE_BEAM_ZERO', val_def=1216.5, type='float' )
self.x0_pos_in_beam0 = self.declareParameter( name='X_CCD_POS_IN_BEAM_ZERO', val_def=-59, type='float' )
self.y0_pos_in_beam0 = self.declareParameter( name='Y_CCD_POS_IN_BEAM_ZERO', val_def=175, type='float' )
# GUISetupSpecular.py
self.x_coord_specular = self.declareParameter( name='X_COORDINATE_SPECULAR', val_def=-1, type='float' )
self.y_coord_specular = self.declareParameter( name='Y_COORDINATE_SPECULAR', val_def=-2, type='float' )
self.x0_pos_in_specular = self.declareParameter( name='X_CCD_POS_IN_SPECULAR', val_def=-3, type='float' )
self.y0_pos_in_specular = self.declareParameter( name='Y_CCD_POS_IN_SPECULAR', val_def=-4, type='float' )
# GUISetupData.py
self.x0_pos_in_data = self.declareParameter( name='X_CCD_POS_IN_DATA', val_def=-51, type='float' )
self.y0_pos_in_data = self.declareParameter( name='Y_CCD_POS_IN_DATA', val_def=183, type='float' )
# GUISetupInfoLeft.py
self.sample_det_dist = self.declareParameter( name='SAMPLE_TO_DETECTOR_DISTANCE', val_def=4000.1, type='float' )
self.exp_setup_geom = self.declareParameter( name='EXP_SETUP_GEOMETRY', val_def='Baem Zero', type='str' )
self.photon_energy = self.declareParameter( name='PHOTON_ENERGY', val_def=7.6543, type='float' )
self.nominal_angle = self.declareParameter( name='NOMINAL_ANGLE', val_def=-1, type='float' )
self.real_angle = self.declareParameter( name='REAL_ANGLE', val_def=-1, type='float' )
# GUIImgSizePosition.py
self.col_begin = self.declareParameter( name='IMG_COL_BEGIN', val_def=0, type='int' )
self.col_end = self.declareParameter( name='IMG_COL_END', val_def=1339, type='int' )
self.row_begin = self.declareParameter( name='IMG_ROW_BEGIN', val_def=1, type='int' )
self.row_end = self.declareParameter( name='IMG_ROW_END', val_def=1299, type='int' )
# GUIKineticMode.py
self.kin_mode = self.declareParameter( name='KINETICS_MODE', val_def='Non-Kinetics',type='str' )
self.kin_win_size = self.declareParameter( name='KINETICS_WIN_SIZE', val_def=1, type='int' )
self.kin_top_row = self.declareParameter( name='KINETICS_TOP_ROW', val_def=2, type='int' )
self.kin_slice_first = self.declareParameter( name='KINETICS_SLICE_FIRST', val_def=3, type='int' )
self.kin_slice_last = self.declareParameter( name='KINETICS_SLICE_LAST', val_def=4, type='int' )
# GUISetupPars.py
self.bat_num = self.declareParameter( name='BATCH_NUM', val_def= 1, type='int' )
self.bat_num_max = self.declareParameter( name='BATCH_NUM_MAX', val_def= 9, type='int' )
#self.bat_data_is_used = self.declareParameter( name='BATCH_DATA_IS_USED', val_def=True, type='bool' )
self.bat_data_start = self.declareParameter( name='BATCH_DATA_START', val_def= 1, type='int' )
self.bat_data_end = self.declareParameter( name='BATCH_DATA_END' , val_def=-1, type='int' )
self.bat_data_total = self.declareParameter( name='BATCH_DATA_TOTAL', val_def=-1, type='int' )
self.bat_data_time = self.declareParameter( name='BATCH_DATA_TIME' , val_def=-1.0, type='float' )
self.bat_data_dt_ave = self.declareParameter( name='BATCH_DATA_DT_AVE', val_def=-1.0, type='float' )
self.bat_data_dt_rms = self.declareParameter( name='BATCH_DATA_DT_RMS', val_def=0.0, type='float' )
self.bat_dark_is_used = self.declareParameter( name='BATCH_DARK_IS_USED', val_def=True, type='bool' )
self.bat_dark_start = self.declareParameter( name='BATCH_DARK_START', val_def= 1, type='int' )
self.bat_dark_end = self.declareParameter( name='BATCH_DARK_END' , val_def=-1, type='int' )
self.bat_dark_total = self.declareParameter( name='BATCH_DARK_TOTAL', val_def=-1, type='int' )
self.bat_dark_time = self.declareParameter( name='BATCH_DARK_TIME' , val_def=-1.0, type='float' )
self.bat_dark_dt_ave = self.declareParameter( name='BATCH_DARK_DT_AVE', val_def=-1.0, type='float' )
self.bat_dark_dt_rms = self.declareParameter( name='BATCH_DARK_DT_RMS', val_def=0.0, type='float' )
#self.bat_flat_is_used = self.declareParameter( name='BATCH_FLAT_IS_USED', val_def=True, type='bool' )
self.bat_flat_start = self.declareParameter( name='BATCH_FLAT_START', val_def= 1, type='int' )
self.bat_flat_end = self.declareParameter( name='BATCH_FLAT_END' , val_def=-1, type='int' )
self.bat_flat_total = self.declareParameter( name='BATCH_FLAT_TOTAL', val_def=-1, type='int' )
self.bat_flat_time = self.declareParameter( name='BATCH_FLAT_TIME' , val_def=-1.0, type='float' )
self.bat_queue = self.declareParameter( name='BATCH_QUEUE', val_def='psfehq', type='str' )
self.bat_det_info = self.declareParameter( name='BATCH_DET_INFO', val_def='DetInfo(:Princeton)', type='str' )
#self.bat_det_info = self.declareParameter( name='BATCH_DET_INFO', val_def='DetInfo(XcsBeamline.0:Princeton.0)', type='str' )
self.bat_img_rec_mod = self.declareParameter( name='BATCH_IMG_REC_MODULE', val_def='ImgAlgos.PrincetonImageProducer', type='str' )
# BatchLogParser.py
self.bat_img_rows = self.declareParameter( name='BATCH_IMG_ROWS', val_def= -1, type='int' )
self.bat_img_cols = self.declareParameter( name='BATCH_IMG_COLS', val_def= -1, type='int' )
self.bat_img_size = self.declareParameter( name='BATCH_IMG_SIZE', val_def= -1, type='int' )
self.bat_img_nparts = self.declareParameter( name='BATCH_IMG_NPARTS', val_def= 8, type='int' )
# GUIAnaSettingsLeft.py
self.ana_type = self.declareParameter( name='ANA_TYPE', val_def='Static',type='str' )
self.ana_stat_meth_q = self.declareParameter( name='ANA_STATIC_METHOD_Q', val_def='evenly-spaced',type='str' )
self.ana_stat_meth_phi = self.declareParameter( name='ANA_STATIC_METHOD_PHI', val_def='evenly-spaced',type='str' )
self.ana_dyna_meth_q = self.declareParameter( name='ANA_DYNAMIC_METHOD_Q', val_def='evenly-spaced',type='str' )
self.ana_dyna_meth_phi = self.declareParameter( name='ANA_DYNAMIC_METHOD_PHI', val_def='evenly-spaced',type='str' )
self.ana_stat_part_q = self.declareParameter( name='ANA_STATIC_PARTITION_Q', val_def='1',type='str' )
self.ana_stat_part_phi = self.declareParameter( name='ANA_STATIC_PARTITION_PHI', val_def='2',type='str' )
self.ana_dyna_part_q = self.declareParameter( name='ANA_DYNAMIC_PARTITION_Q', val_def='3',type='str' )
self.ana_dyna_part_phi = self.declareParameter( name='ANA_DYNAMIC_PARTITION_PHI', val_def='4',type='str' )
self.ana_mask_type = self.declareParameter( name='ANA_MASK_TYPE', val_def='no-mask',type='str' )
self.ana_mask_fname = self.declareParameter( name='ANA_MASK_FILE', val_def='./roi-mask.txt',type='str' )
self.ana_mask_dname = self.declareParameter( name='ANA_MASK_DIRECTORY', val_def='.',type='str' )
# GUIAnaSettingsRight.py
self.ana_ndelays = self.declareParameter( name='ANA_NDELAYS_PER_MTAU_LEVEL', val_def=4, type='int' )
self.ana_nslice_delays = self.declareParameter( name='ANA_NSLICE_DELAYS_PER_MTAU_LEVEL', val_def=4, type='int' )
self.ana_npix_to_smooth= self.declareParameter( name='ANA_NPIXELS_TO_SMOOTH', val_def=100, type='int' )
self.ana_smooth_norm = self.declareParameter( name='ANA_SMOOTH_SYM_NORM', val_def=False, type='bool' )
self.ana_two_corfuns = self.declareParameter( name='ANA_TWO_TIME_CORFUNS_CONTROL', val_def=False, type='bool' )
self.ana_spec_stab = self.declareParameter( name='ANA_CHECK_SPECKLE_STABILITY', val_def=False, type='bool' )
self.lld_type = self.declareParameter( name='LOW_LEVEL_DISC_TYPE', val_def='NONE',type='str' )
self.lld_adu = self.declareParameter( name='LOW_LEVEL_DISC_ADU', val_def=15, type='float' )
self.lld_rms = self.declareParameter( name='LOW_LEVEL_DISC_RMS', val_def=4, type='float' )
self.res_ascii_out = self.declareParameter( name='RES_ASCII_OUTPUT', val_def=True, type='bool' )
self.res_fit1 = self.declareParameter( name='RES_PERFORM_FIT1', val_def=False, type='bool' )
self.res_fit2 = self.declareParameter( name='RES_PERFORM_FIT1', val_def=False, type='bool' )
self.res_fit_cust = self.declareParameter( name='RES_PERFORM_FIT_CUSTOM', val_def=False, type='bool' )
self.res_png_out = self.declareParameter( name='RES_PNG_FILES', val_def=False, type='bool' )
self.res_save_log = self.declareParameter( name='RES_SAVE_LOG_FILE', val_def=False, type='bool' )
# GUILoadResults.py
self.res_load_mode = self.declareParameter( name='RES_LOAD_MODE', val_def='NONE',type='str' )
self.res_fname = self.declareParameter( name='RES_LOAD_FNAME', val_def='NONE',type='str' )
# GUISystemSettingsRight.py
self.thickness_type = self.declareParameter( name='THICKNESS_TYPE', val_def='NONORM',type='str' )
self.thickness_sample = self.declareParameter( name='THICKNESS_OF_SAMPLE', val_def=-1, type='float' )
self.thickness_attlen = self.declareParameter( name='THICKNESS_ATTENUATION_LENGTH', val_def=-2, type='float' )
self.ccd_orient = self.declareParameter( name='CCD_ORIENTATION', val_def='180', type='str' )
self.y_is_flip = self.declareParameter( name='Y_IS_FLIPPED', val_def='True', type='bool' )
# GUICCDSettings.py
self.ccdset_pixsize = self.declareParameter( name='CCD_SETTINGS_PIXEL_SIZE', val_def=0.1, type='float' )
self.ccdset_adcsatu = self.declareParameter( name='CCD_SETTINGS_ADC_SATTURATION', val_def=12345, type='int' )
self.ccdset_aduphot = self.declareParameter( name='CCD_SETTINGS_ADU_PER_PHOTON', val_def=123, type='float' )
self.ccdset_ccdeff = self.declareParameter( name='CCD_SETTINGS_EFFICIENCY', val_def=0.55, type='float' )
self.ccdset_ccdgain = self.declareParameter( name='CCD_SETTINGS_GAIN', val_def=0.8, type='float' )
# GUIELogPostingDialog.py
# GUIELogPostingFields.py
#self.elog_post_cbx_state = self.declareParameter( name='ELOG_POST_CBX_STATE', val_def=True, type='bool' )
self.elog_post_rad = self.declareParameter( name='ELOG_POST_RAD_STATE', val_def='Default', type='str' )
self.elog_post_ins = self.declareParameter( name='ELOG_POST_INSTRUMENT', val_def='AMO', type='str' )
self.elog_post_exp = self.declareParameter( name='ELOG_POST_EXPERIMENT', val_def='amodaq09', type='str' )
self.elog_post_run = self.declareParameter( name='ELOG_POST_RUN', val_def='825', type='str' )
self.elog_post_tag = self.declareParameter( name='ELOG_POST_TAG', val_def='TAG1', type='str' )
self.elog_post_res = self.declareParameter( name='ELOG_POST_RESPONCE', val_def='None', type='str' )
self.elog_post_msg = self.declareParameter( name='ELOG_POST_MESSAGE', val_def='EMPTY MSG', type='str' )
self.elog_post_att = self.declareParameter( name='ELOG_POST_ATTACHED_FILE', val_def='None', type='str' )
#GUIViewControl.py
self.vc_cbx_show_more = self.declareParameter( name='SHOW_MORE_BUTTONS', val_def=True, type='bool' )
#-----------------------------
imon_names = [ ('BldInfo(FEEGasDetEnergy)', None ,'str'), \
('BldInfo(XCS-IPM-02)', None ,'str'), \
('BldInfo(XCS-IPM-mono)', None ,'str'), \
('DetInfo(XcsBeamline.1:Ipimb.4)', None ,'str'), \
('DetInfo(XcsBeamline.1:Ipimb.5)', None ,'str') ]
self.imon_name_list = self.declareListOfPars( 'IMON_NAMES', imon_names )
#-----------------------------
imon_short_names = [ ('FEEGasDetEnergy', None ,'str'), \
('XCS-IPM-02', None ,'str'), \
('XCS-IPM-mono', None ,'str'), \
('Ipimb.4', None ,'str'), \
('Ipimb.5', None ,'str') ]
self.imon_short_name_list = self.declareListOfPars( 'IMON_SHORT_NAMES', imon_short_names )
#-----------------------------
imon_cbxs = [ (True, True ,'bool'), \
(True, True ,'bool'), \
(True, True ,'bool'), \
(True, True ,'bool'), \
(True, True ,'bool') ]
self.imon_ch1_list = self.declareListOfPars( 'IMON_CH1', deepcopy(imon_cbxs) )
self.imon_ch2_list = self.declareListOfPars( 'IMON_CH2', deepcopy(imon_cbxs) )
self.imon_ch3_list = self.declareListOfPars( 'IMON_CH3', deepcopy(imon_cbxs) )
self.imon_ch4_list = self.declareListOfPars( 'IMON_CH4', deepcopy(imon_cbxs) )
#-----------------------------
imon_norm_cbx = [ (False, False ,'bool'), \
(False, False ,'bool'), \
(False, False ,'bool'), \
(False, False ,'bool'), \
(False, False ,'bool') ]
self.imon_norm_cbx_list = self.declareListOfPars( 'IMON_NORM_CBX', imon_norm_cbx )
#-----------------------------
imon_sele_cbx = [ (False, False ,'bool'), \
(False, False ,'bool'), \
(False, False ,'bool'), \
(False, False ,'bool'), \
(False, False ,'bool') ]
self.imon_sele_cbx_list = self.declareListOfPars( 'IMON_SELE_CBX', imon_sele_cbx )
#-----------------------------
imon_sele_min = [ (-1., -1. ,'float'), \
(-1., -1. ,'float'), \
(-1., -1. ,'float'), \
(-1., -1. ,'float'), \
(-1., -1. ,'float') ]
self.imon_sele_min_list = self.declareListOfPars( 'IMON_SELE_MIN', imon_sele_min )
#-----------------------------
imon_sele_max = [ (-1., -1. ,'float'), \
(-1., -1. ,'float'), \
(-1., -1. ,'float'), \
(-1., -1. ,'float'), \
(-1., -1. ,'float') ]
self.imon_sele_max_list = self.declareListOfPars( 'IMON_SELE_MAX', imon_sele_max )
#-----------------------------
self.imon_pars_list = zip( self.imon_name_list,
self.imon_ch1_list,
self.imon_ch2_list,
self.imon_ch3_list,
self.imon_ch4_list,
self.imon_norm_cbx_list,
self.imon_sele_cbx_list,
self.imon_sele_min_list,
self.imon_sele_max_list,
self.imon_short_name_list )
#print self.imon_pars_list
#-----------------------------
def defineStyles( self ) :
self.styleYellowish = "background-color: rgb(255, 255, 220); color: rgb(0, 0, 0);" # Yellowish
self.stylePink = "background-color: rgb(255, 200, 220); color: rgb(0, 0, 0);" # Pinkish
self.styleYellowBkg = "background-color: rgb(255, 255, 120); color: rgb(0, 0, 0);" # Pinkish
self.styleGray = "background-color: rgb(230, 240, 230); color: rgb(0, 0, 0);" # Gray
self.styleGreenish = "background-color: rgb(100, 255, 200); color: rgb(0, 0, 0);" # Greenish
self.styleGreenPure = "background-color: rgb(150, 255, 150); color: rgb(0, 0, 0);" # Green
self.styleBluish = "background-color: rgb(200, 200, 255); color: rgb(0, 0, 0);" # Bluish
self.styleWhite = "background-color: rgb(255, 255, 255); color: rgb(0, 0, 0);"
self.styleRedBkgd = "background-color: rgb(255, 0, 0); color: rgb(0, 0, 0);" # Red background
#self.styleTitle = "background-color: rgb(239, 235, 231, 255); color: rgb(100, 160, 100);" # Gray bkgd
#self.styleTitle = "color: rgb(150, 160, 100);"
self.styleBlue = "color: rgb(000, 000, 255);"
self.styleBuriy = "color: rgb(150, 100, 50);"
self.styleRed = "color: rgb(255, 0, 0);"
self.styleGreen = "color: rgb(0, 150, 0);"
self.styleYellow = "color: rgb(0, 150, 150);"
self.styleBkgd = self.styleYellowish
self.styleTitle = self.styleBuriy
self.styleLabel = self.styleBlue
self.styleEdit = self.styleWhite
self.styleEditInfo = self.styleGreenish
self.styleEditBad = self.styleRedBkgd
self.styleButton = self.styleGray
self.styleButtonOn = self.styleBluish
self.styleButtonClose = self.stylePink
self.styleButtonWarning= self.styleYellowBkg
self.styleButtonGood = self.styleGreenPure
self.styleButtonBad = self.stylePink
self.styleBox = self.styleGray
self.styleCBox = self.styleYellowish
self.styleStatusGood = self.styleGreen
self.styleStatusWarning= self.styleYellow
self.styleStatusAlarm = self.styleRed
self.styleTitleBold = self.styleTitle + 'font-size: 18pt; font-family: Courier; font-weight: bold;'
self.styleWhiteFixed = self.styleWhite + 'font-family: Fixed;'
self.colorEditInfo = QtGui.QColor(100, 255, 200)
self.colorEditBad = QtGui.QColor(255, 0, 0)
self.colorEdit = QtGui.QColor('white')
def printParsDirectly( self ) :
logger.info('Direct use of parameter:' + self.fname_cp .name() + ' ' + self.fname_cp .value(), __name__ )
logger.info('Direct use of parameter:' + self.fname_ped.name() + ' ' + self.fname_ped.value(), __name__ )
logger.info('Direct use of parameter:' + self.fname_dat.name() + ' ' + self.fname_dat.value(), __name__ )
#-----------------------------
confpars = ConfigParametersCorAna (fname=getConfigFileFromInput())
#-----------------------------
#
# In case someone decides to run this module
#
if __name__ == "__main__" :
confpars.printParameters()
#confpars.printParsDirectly()
confpars.saveParametersInFile()
confpars.printListOfPars('IMON_NAMES')
sys.exit ( 'End of test for ConfigParametersCorAna' )
#-----------------------------
| [
"[email protected]@b967ad99-d558-0410-b138-e0f6c56caec7"
] | [email protected]@b967ad99-d558-0410-b138-e0f6c56caec7 |
9567422e1472a65046cf8160b1bdae8fbcf7dcd3 | 080c13cd91a073457bd9eddc2a3d13fc2e0e56ae | /MY_REPOS/awesome-4-new-developers/tensorflow-master/tensorflow/python/types/internal.py | c56c7aa6d7790b4c36d248603f2282e60af08a39 | [
"Apache-2.0"
] | permissive | Portfolio-Projects42/UsefulResourceRepo2.0 | 1dccc8961a09347f124d3ed7c27c6d73b9806189 | 75b1e23c757845b5f1894ebe53551a1cf759c6a3 | refs/heads/master | 2023-08-04T12:23:48.862451 | 2021-09-15T12:51:35 | 2021-09-15T12:51:35 | null | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 1,129 | py | # Copyright 2020 The TensorFlow Authors. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
# ==============================================================================
"""Types internal to TensorFlow.
These types should not be exported. External code should not rely on these.
"""
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
# TODO(mdan): Is this strictly needed? Only ops.py really uses it.
class NativeObject(object):
"""Types natively supported by various TF operations.
The most notable example of NativeObject is Tensor.
"""
| [
"[email protected]"
] | |
abc2e14c55f8110ca3d0bc1403c2b44d4e5fe36e | 026fee65b95206995baf1565f486ab4ed7f7cef9 | /userprofiles/admin.py | 89683d76fdacc00428bfbad69cc1e019d3f01b5e | [] | no_license | santhoshpkumar/pinclone | e8460aab355ebf3e5559d44127d7ccad22667747 | 8bf641df9a4999797731d1d2fb4ff3d78d717e10 | refs/heads/master | 2020-04-03T09:39:27.269726 | 2018-10-08T10:51:51 | 2018-10-08T10:51:51 | null | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 225 | py | from django.contrib import admin
from .models import Profile
# Register your models here.
@admin.register(Profile)
class ProfileAdmin(admin.ModelAdmin):
list_display = ('user', 'bio', 'website', 'birth_date')
| [
"[email protected]"
] | |
28e7dee0700c6fe42c004b939fcaa2b9ff69d27e | eb64b799ff1d7ef3a244bf8e6f9f4e9118d5cfcd | /homeassistant/components/trafikverket_weatherstation/const.py | 7bb53dc5356a0b8a392104982912658806275659 | [
"Apache-2.0"
] | permissive | JeffLIrion/home-assistant | 53966b81b5d5816679f12fc761f79e8777c738d6 | 8f4ec89be6c2505d8a59eee44de335abe308ac9f | refs/heads/dev | 2023-08-22T09:42:02.399277 | 2022-02-16T01:26:13 | 2022-02-16T01:26:13 | 136,679,169 | 5 | 2 | Apache-2.0 | 2023-09-13T06:59:25 | 2018-06-09T00:58:35 | Python | UTF-8 | Python | false | false | 466 | py | """Adds constants for Trafikverket Weather integration."""
from homeassistant.const import Platform
DOMAIN = "trafikverket_weatherstation"
CONF_STATION = "station"
PLATFORMS = [Platform.SENSOR]
ATTRIBUTION = "Data provided by Trafikverket"
ATTR_MEASURE_TIME = "measure_time"
ATTR_ACTIVE = "active"
NONE_IS_ZERO_SENSORS = {
"air_temp",
"road_temp",
"wind_direction",
"wind_speed",
"wind_speed_max",
"humidity",
"precipitation_amount",
}
| [
"[email protected]"
] | |
7642072e77aebda4174a74cfe093db22e6377af7 | 7bd0954e956993df19d833810f9d71b60e2ebb9a | /phasor/utilities/ipynb/hdf.py | b9f7e5b1add89064ffd726859cfe27d4415619ec | [
"Apache-2.0"
] | permissive | aa158/phasor | 5ee0cec4f816b88b0a8ac298c330ed48458ec3f2 | fe86dc6dec3740d4b6be6b88d8eef8566e2aa78d | refs/heads/master | 2021-10-22T09:48:18.556091 | 2019-03-09T18:56:05 | 2019-03-09T18:56:05 | null | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 169 | py | # -*- coding: utf-8 -*-
"""
"""
from __future__ import division, print_function, unicode_literals
import h5py
from declarative.bunch.hdf_deep_bunch import HDFDeepBunch
| [
"[email protected]"
] | |
267f5e570bff6ec85a0e60de98259cea7422da0e | edb37da2fd2d2f048df119db96a6de58fc816ddb | /jumpserver-0.4/zrd/my_blog/article/views.py | 0634c5361e1cf968ac0e81b87ea55908e18fa6b5 | [] | no_license | cucy/2017 | 88f1aa2e8df945162d8259918cf61a138a3422cf | 33bcdd5c9e0717521544e3ea41ade10fbb325c4f | refs/heads/master | 2020-05-21T15:31:39.935733 | 2017-07-10T11:04:29 | 2017-07-10T11:04:29 | 84,629,639 | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 1,766 | py | # coding:utf-8
from django.shortcuts import render
from django.shortcuts import render_to_response
# Create your views here.
from django.http import HttpResponse
from models import SSHInfo
# Create your views here.
try:
from ConfigParser import ConfigParser
except:
from configparser import ConfigParser
try:
import paramiko_client
except:
from . import paramiko_client
def home(request):
# 如果请求里有file
for key in request.FILES:
file = request.FILES[key]
config = ConfigParser() # 读取配置文件
config.readfp(file)
for section in config.sections():
print(section)
host_name = config.get(section, 'host_name')
host = config.get(section, 'host')
port = config.get(section, 'port')
usr = config.get(section, 'username')
pwd = config.get(section, 'password')
new_ssh, create = SSHInfo.objects.update_or_create(
host_name=host_name
, host=host
, port=port
, usr=usr
, pwd=pwd
)
new_ssh.save() # 保存配置信息到数据库
sshs = SSHInfo.objects.all() # 获取所有对象
if len(sshs) > 0:
return render_to_response('sshlist.html', {'sshs': sshs})
else:
return render_to_response('home_view.html')
def run_ssh_cmd(requset):
# 获取所有的信息
sshs = SSHInfo.objects.all()
cmd_res = {}
for ssh in sshs:
client = paramiko_client.ParamikoClient()
client.connect(ssh)
res = client.run_cmd('date') # 执行命令 接收返回
cmd_res[ssh.host_name] = res
return render_to_response('cmd_res.html', {'cmd_res': cmd_res})
| [
"[email protected]"
] | |
d3e3b20b1ce012f78bbc61c3eb7dc31075d016ca | c9094a4ed256260bc026514a00f93f0b09a5d60c | /tests/components/accuweather/test_system_health.py | 749f516e44c748caf05503460e8a72ec34d085d3 | [
"Apache-2.0"
] | permissive | turbokongen/home-assistant | 824bc4704906ec0057f3ebd6d92788e096431f56 | 4ab0151fb1cbefb31def23ba850e197da0a5027f | refs/heads/dev | 2023-03-12T05:49:44.508713 | 2021-02-17T14:06:16 | 2021-02-17T14:06:16 | 50,231,140 | 4 | 1 | Apache-2.0 | 2023-02-22T06:14:30 | 2016-01-23T08:55:09 | Python | UTF-8 | Python | false | false | 1,785 | py | """Test AccuWeather system health."""
import asyncio
from unittest.mock import Mock
from aiohttp import ClientError
from homeassistant.components.accuweather.const import COORDINATOR, DOMAIN
from homeassistant.setup import async_setup_component
from tests.common import get_system_health_info
async def test_accuweather_system_health(hass, aioclient_mock):
"""Test AccuWeather system health."""
aioclient_mock.get("https://dataservice.accuweather.com/", text="")
hass.config.components.add(DOMAIN)
assert await async_setup_component(hass, "system_health", {})
hass.data[DOMAIN] = {}
hass.data[DOMAIN]["0123xyz"] = {}
hass.data[DOMAIN]["0123xyz"][COORDINATOR] = Mock(
accuweather=Mock(requests_remaining="42")
)
info = await get_system_health_info(hass, DOMAIN)
for key, val in info.items():
if asyncio.iscoroutine(val):
info[key] = await val
assert info == {
"can_reach_server": "ok",
"remaining_requests": "42",
}
async def test_accuweather_system_health_fail(hass, aioclient_mock):
"""Test AccuWeather system health."""
aioclient_mock.get("https://dataservice.accuweather.com/", exc=ClientError)
hass.config.components.add(DOMAIN)
assert await async_setup_component(hass, "system_health", {})
hass.data[DOMAIN] = {}
hass.data[DOMAIN]["0123xyz"] = {}
hass.data[DOMAIN]["0123xyz"][COORDINATOR] = Mock(
accuweather=Mock(requests_remaining="0")
)
info = await get_system_health_info(hass, DOMAIN)
for key, val in info.items():
if asyncio.iscoroutine(val):
info[key] = await val
assert info == {
"can_reach_server": {"type": "failed", "error": "unreachable"},
"remaining_requests": "0",
}
| [
"[email protected]"
] | |
1b32ea37e4c7f6126f63d235f5bc196330d2dc7e | d94b6845aeeb412aac6850b70e22628bc84d1d6d | /dimensions_of_motion/geometry.py | d7a317cb08a95e69785f8cd0af032ae5db8a1f29 | [
"CC-BY-4.0",
"Apache-2.0"
] | permissive | ishine/google-research | 541aea114a68ced68736340e037fc0f8257d1ea2 | c1ae273841592fce4c993bf35cdd0a6424e73da4 | refs/heads/master | 2023-06-08T23:02:25.502203 | 2023-05-31T01:00:56 | 2023-05-31T01:06:45 | 242,478,569 | 0 | 0 | Apache-2.0 | 2020-06-23T01:55:11 | 2020-02-23T07:59:42 | Jupyter Notebook | UTF-8 | Python | false | false | 7,466 | py | # coding=utf-8
# Copyright 2023 The Google Research Authors.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
# -*- coding: utf-8 -*-
"""Functions for sampling and warping images.
We use texture coordinates to represent points and offsets in images. They go
from (0,0) in the top-left corner of an image to (1,1) in the bottom right. It
is convenient to work with these coordinates rather than counts of pixels,
because they are resolution-independent.
"""
import tensorflow as tf
import tensorflow_addons as tfa
import utils
def check_input_shape(name, tensor, axis, value):
"""Utility function for checking tensor shapes."""
shape = tensor.shape.as_list()
if shape[axis] != value:
raise ValueError('Input "%s": dimension %d should be %s. Shape = %s' %
(name, axis, value, shape))
def pixel_center_grid(height, width):
"""Produce a grid of (x,y) texture-coordinate pairs of pixel centers.
Args:
height: (integer) height, not a tensor
width: (integer) width, not a tensor
Returns:
A tensor of shape [height, width, 2] where each entry gives the (x,y)
texture coordinates of the corresponding pixel center. For example, for
pixel_center_grid(2, 3) the result is:
[[[1/6, 1/4], [3/6, 1/4], [5/6, 1/4]],
[[1/6, 3/4], [3/6, 3/4], [5/6, 3/4]]]
"""
height_float = tf.cast(height, dtype=tf.float32)
width_float = tf.cast(width, dtype=tf.float32)
ys = tf.linspace(0.5 / height_float, 1.0 - 0.5 / height_float, height)
xs = tf.linspace(0.5 / width_float, 1.0 - 0.5 / width_float, width)
xs, ys = tf.meshgrid(xs, ys)
grid = tf.stack([xs, ys], axis=-1)
assert grid.shape.as_list() == [height, width, 2]
return grid
def sample_image(image, coords):
"""Sample points from an image, using bilinear filtering.
Args:
image: [B0, ..., Bn-1, height, width, channels] image data
coords: [B0, ..., Bn-1, ..., 2] (x,y) texture coordinates
Returns:
[B0, ..., Bn-1, ..., channels] image data, in which each value is sampled
with bilinear interpolation from the image at position indicated by the
(x,y) texture coordinates. The image and coords parameters must have
matching batch dimensions B0, ..., Bn-1.
Raises:
ValueError: if shapes are incompatible.
"""
check_input_shape('coords', coords, -1, 2)
tfshape = tf.shape(image)[-3:-1]
height = tf.cast(tfshape[0], dtype=tf.float32)
width = tf.cast(tfshape[1], dtype=tf.float32)
# Resampler expects coordinates where (0,0) is the center of the top-left
# pixel and (width-1, height-1) is the center of the bottom-right pixel.
pixel_coords = coords * [width, height] - 0.5
# tfa.image.resampler only works with exactly one batch dimension, i.e. it
# expects image to be [batch, height, width, channels] and pixel_coords to be
# [batch, ..., 2]. So we need to reshape, perform the resampling, and then
# reshape back to what we had.
batch_dims = len(image.shape.as_list()) - 3
assert (image.shape.as_list()[:batch_dims] == pixel_coords.shape.as_list()
[:batch_dims])
batched_image, _ = utils.flatten_batch(image, batch_dims)
batched_coords, unflatten_coords = utils.flatten_batch(
pixel_coords, batch_dims)
resampled = tfa.image.resampler(batched_image, batched_coords)
# Convert back to the right shape to return
resampled = unflatten_coords(resampled)
return resampled
def bilinear_forward_warp(image, coords, weights=None):
"""Forward warp each point in an image using bilinear filtering.
This is a sort of reverse of sample_image, in the sense that scatter is the
reverse of gather. A new image is generated of the same size as the input, in
which each pixel has been splatted onto the 2x2 block containing the
corresponding coordinates, using bilinear weights (multiplied with the input
per-pixel weights, if supplied). Thus if two or more pixels warp to the same
point, the result will be a blend of the their values. If no pixels warp to a
location, the result at that location will be zero.
Args:
image: [B0, ..., Bn-1, height, width, channels] image data
coords: [B0, ..., Bn-1, height, width, 2] (x,y) texture coordinates
weights: [B0, ... ,Bn-1, height, width] weights for each point. If omitted,
all points are weighed equally. Use this to implement, for example, soft
z-buffering.
Returns:
[B0, ..., Bn-1, ..., channels] image data, in which each point in the
input image has been moved to the position indicated by the corresponding
(x,y) texture coordinates. The image and coords parameters must have
matching batch dimensions B0, ..., Bn-1.
"""
# Forward-warp computed using the gradient of reverse-warp. We use a dummy
# image of the right size for reverse-warping. An extra channel is used to
# accumulate the total weight for each pixel which we'll then divide by.
image_and_ones = tf.concat([image, tf.ones_like(image[Ellipsis, -1:])], axis=-1)
dummy = tf.zeros_like(image_and_ones)
if weights is None:
weighted_image = image_and_ones
else:
weighted_image = image_and_ones * weights[Ellipsis, tf.newaxis]
with tf.GradientTape(watch_accessed_variables=False) as g:
g.watch(dummy)
reverse = tf.reduce_sum(
sample_image(dummy, coords) * weighted_image, [-3, -2])
grads = g.gradient(reverse, dummy)
rgb = grads[Ellipsis, :-1]
total = grads[Ellipsis, -1:]
result = tf.math.divide_no_nan(rgb, total)
return result
def flow_warp(image, flow):
"""Warp images by resampling according to flow vectors.
Args:
image: [..., H, W, C] images
flow: [..., H, W, 2] (x, y) texture offsets
Returns:
[..., H, W, C] resampled images. Each pixel in each output image has been
bilinearly sampled from the corresponding pixel in its input image plus
the (x, y) flow vector. The flow vectors are texture coordinate offsets,
e.g. (1, 1) is an offset of the whole width and height of the image.
Sampling outside the image yields zero values.
"""
width = image.shape.as_list()[-2]
height = image.shape.as_list()[-3]
grid = pixel_center_grid(height, width)
coords = grid + flow
return sample_image(image, coords)
def flow_forward_warp(image, flow):
"""Forward-warp images according to flow vectors.
Args:
image: [..., H, W, C] images
flow: [..., H, W, 2] (x, y) texture offsets
Returns:
[..., H, W, C] warped images. Each pixel in each image is offset according
to the corresponding value in the flow, and splatted onto a 2x2 pixel block.
(See bilinear_forward_warp for details.) If no points warp to a location,
the result will be zero. The flow vectors are texture coordinate offsets,
e.g. (1, 1) is an offset of the whole width and height of the image.
"""
width = image.shape.as_list()[-2]
height = image.shape.as_list()[-3]
grid = pixel_center_grid(height, width)
coords = grid + flow
return bilinear_forward_warp(image, coords)
| [
"[email protected]"
] | |
cf4869a008091dac50e4e6d07bded0da84f85bb3 | 2bcf18252fa9144ece3e824834ac0e117ad0bdf3 | /zpt/trunk/site-packages/zpt/_pytz/zoneinfo/Asia/Ulan_Bator.py | 23ee14fe6b126706fac6097086cd541788e4110c | [
"MIT",
"ZPL-2.1"
] | permissive | chadwhitacre/public | 32f65ba8e35d38c69ed4d0edd333283a239c5e1d | 0c67fd7ec8bce1d8c56c7ff3506f31a99362b502 | refs/heads/master | 2021-05-10T14:32:03.016683 | 2010-05-13T18:24:20 | 2010-05-13T18:24:20 | null | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 5,011 | py | '''tzinfo timezone information for Asia/Ulan_Bator.'''
from zpt._pytz.tzinfo import DstTzInfo
from zpt._pytz.tzinfo import memorized_datetime as d
from zpt._pytz.tzinfo import memorized_ttinfo as i
class Ulan_Bator(DstTzInfo):
'''Asia/Ulan_Bator timezone definition. See datetime.tzinfo for details'''
zone = 'Asia/Ulan_Bator'
_utc_transition_times = [
d(1,1,1,0,0,0),
d(1905,7,31,16,52,28),
d(1977,12,31,17,0,0),
d(1983,3,31,16,0,0),
d(1983,9,30,15,0,0),
d(1984,3,31,16,0,0),
d(1984,9,29,18,0,0),
d(1985,3,30,18,0,0),
d(1985,9,28,18,0,0),
d(1986,3,29,18,0,0),
d(1986,9,27,18,0,0),
d(1987,3,28,18,0,0),
d(1987,9,26,18,0,0),
d(1988,3,26,18,0,0),
d(1988,9,24,18,0,0),
d(1989,3,25,18,0,0),
d(1989,9,23,18,0,0),
d(1990,3,24,18,0,0),
d(1990,9,29,18,0,0),
d(1991,3,30,18,0,0),
d(1991,9,28,18,0,0),
d(1992,3,28,18,0,0),
d(1992,9,26,18,0,0),
d(1993,3,27,18,0,0),
d(1993,9,25,18,0,0),
d(1994,3,26,18,0,0),
d(1994,9,24,18,0,0),
d(1995,3,25,18,0,0),
d(1995,9,23,18,0,0),
d(1996,3,30,18,0,0),
d(1996,9,28,18,0,0),
d(1997,3,29,18,0,0),
d(1997,9,27,18,0,0),
d(1998,3,28,18,0,0),
d(1998,9,26,18,0,0),
d(2001,4,27,18,0,0),
d(2001,9,28,17,0,0),
d(2002,3,29,18,0,0),
d(2002,9,27,17,0,0),
d(2003,3,28,18,0,0),
d(2003,9,26,17,0,0),
d(2004,3,26,18,0,0),
d(2004,9,24,17,0,0),
d(2005,3,25,18,0,0),
d(2005,9,23,17,0,0),
d(2006,3,24,18,0,0),
d(2006,9,29,17,0,0),
d(2007,3,30,18,0,0),
d(2007,9,28,17,0,0),
d(2008,3,28,18,0,0),
d(2008,9,26,17,0,0),
d(2009,3,27,18,0,0),
d(2009,9,25,17,0,0),
d(2010,3,26,18,0,0),
d(2010,9,24,17,0,0),
d(2011,3,25,18,0,0),
d(2011,9,23,17,0,0),
d(2012,3,30,18,0,0),
d(2012,9,28,17,0,0),
d(2013,3,29,18,0,0),
d(2013,9,27,17,0,0),
d(2014,3,28,18,0,0),
d(2014,9,26,17,0,0),
d(2015,3,27,18,0,0),
d(2015,9,25,17,0,0),
d(2016,3,25,18,0,0),
d(2016,9,23,17,0,0),
d(2017,3,24,18,0,0),
d(2017,9,29,17,0,0),
d(2018,3,30,18,0,0),
d(2018,9,28,17,0,0),
d(2019,3,29,18,0,0),
d(2019,9,27,17,0,0),
d(2020,3,27,18,0,0),
d(2020,9,25,17,0,0),
d(2021,3,26,18,0,0),
d(2021,9,24,17,0,0),
d(2022,3,25,18,0,0),
d(2022,9,23,17,0,0),
d(2023,3,24,18,0,0),
d(2023,9,29,17,0,0),
d(2024,3,29,18,0,0),
d(2024,9,27,17,0,0),
d(2025,3,28,18,0,0),
d(2025,9,26,17,0,0),
d(2026,3,27,18,0,0),
d(2026,9,25,17,0,0),
d(2027,3,26,18,0,0),
d(2027,9,24,17,0,0),
d(2028,3,24,18,0,0),
d(2028,9,29,17,0,0),
d(2029,3,30,18,0,0),
d(2029,9,28,17,0,0),
d(2030,3,29,18,0,0),
d(2030,9,27,17,0,0),
d(2031,3,28,18,0,0),
d(2031,9,26,17,0,0),
d(2032,3,26,18,0,0),
d(2032,9,24,17,0,0),
d(2033,3,25,18,0,0),
d(2033,9,23,17,0,0),
d(2034,3,24,18,0,0),
d(2034,9,29,17,0,0),
d(2035,3,30,18,0,0),
d(2035,9,28,17,0,0),
d(2036,3,28,18,0,0),
d(2036,9,26,17,0,0),
d(2037,3,27,18,0,0),
d(2037,9,25,17,0,0),
]
_transition_info = [
i(25680,0,'LMT'),
i(25200,0,'ULAT'),
i(28800,0,'ULAT'),
i(32400,3600,'ULAST'),
i(28800,0,'ULAT'),
i(32400,3600,'ULAST'),
i(28800,0,'ULAT'),
i(32400,3600,'ULAST'),
i(28800,0,'ULAT'),
i(32400,3600,'ULAST'),
i(28800,0,'ULAT'),
i(32400,3600,'ULAST'),
i(28800,0,'ULAT'),
i(32400,3600,'ULAST'),
i(28800,0,'ULAT'),
i(32400,3600,'ULAST'),
i(28800,0,'ULAT'),
i(32400,3600,'ULAST'),
i(28800,0,'ULAT'),
i(32400,3600,'ULAST'),
i(28800,0,'ULAT'),
i(32400,3600,'ULAST'),
i(28800,0,'ULAT'),
i(32400,3600,'ULAST'),
i(28800,0,'ULAT'),
i(32400,3600,'ULAST'),
i(28800,0,'ULAT'),
i(32400,3600,'ULAST'),
i(28800,0,'ULAT'),
i(32400,3600,'ULAST'),
i(28800,0,'ULAT'),
i(32400,3600,'ULAST'),
i(28800,0,'ULAT'),
i(32400,3600,'ULAST'),
i(28800,0,'ULAT'),
i(32400,3600,'ULAST'),
i(28800,0,'ULAT'),
i(32400,3600,'ULAST'),
i(28800,0,'ULAT'),
i(32400,3600,'ULAST'),
i(28800,0,'ULAT'),
i(32400,3600,'ULAST'),
i(28800,0,'ULAT'),
i(32400,3600,'ULAST'),
i(28800,0,'ULAT'),
i(32400,3600,'ULAST'),
i(28800,0,'ULAT'),
i(32400,3600,'ULAST'),
i(28800,0,'ULAT'),
i(32400,3600,'ULAST'),
i(28800,0,'ULAT'),
i(32400,3600,'ULAST'),
i(28800,0,'ULAT'),
i(32400,3600,'ULAST'),
i(28800,0,'ULAT'),
i(32400,3600,'ULAST'),
i(28800,0,'ULAT'),
i(32400,3600,'ULAST'),
i(28800,0,'ULAT'),
i(32400,3600,'ULAST'),
i(28800,0,'ULAT'),
i(32400,3600,'ULAST'),
i(28800,0,'ULAT'),
i(32400,3600,'ULAST'),
i(28800,0,'ULAT'),
i(32400,3600,'ULAST'),
i(28800,0,'ULAT'),
i(32400,3600,'ULAST'),
i(28800,0,'ULAT'),
i(32400,3600,'ULAST'),
i(28800,0,'ULAT'),
i(32400,3600,'ULAST'),
i(28800,0,'ULAT'),
i(32400,3600,'ULAST'),
i(28800,0,'ULAT'),
i(32400,3600,'ULAST'),
i(28800,0,'ULAT'),
i(32400,3600,'ULAST'),
i(28800,0,'ULAT'),
i(32400,3600,'ULAST'),
i(28800,0,'ULAT'),
i(32400,3600,'ULAST'),
i(28800,0,'ULAT'),
i(32400,3600,'ULAST'),
i(28800,0,'ULAT'),
i(32400,3600,'ULAST'),
i(28800,0,'ULAT'),
i(32400,3600,'ULAST'),
i(28800,0,'ULAT'),
i(32400,3600,'ULAST'),
i(28800,0,'ULAT'),
i(32400,3600,'ULAST'),
i(28800,0,'ULAT'),
i(32400,3600,'ULAST'),
i(28800,0,'ULAT'),
i(32400,3600,'ULAST'),
i(28800,0,'ULAT'),
i(32400,3600,'ULAST'),
i(28800,0,'ULAT'),
i(32400,3600,'ULAST'),
i(28800,0,'ULAT'),
i(32400,3600,'ULAST'),
i(28800,0,'ULAT'),
i(32400,3600,'ULAST'),
i(28800,0,'ULAT'),
i(32400,3600,'ULAST'),
i(28800,0,'ULAT'),
i(32400,3600,'ULAST'),
i(28800,0,'ULAT'),
]
Ulan_Bator = Ulan_Bator()
| [
"[email protected]"
] | |
85ef73de5c1fceffd5aff452e2b9902d1718602f | 5ca6730fa1178582d5f5875155f340ec0f406294 | /practice_problem-16.py | 44785ae4df282d5b7cc6f83173866d825eb41375 | [] | no_license | MahadiRahman262523/Python_Code_Part-1 | 9740d5ead27209d69af4497eea410f2faef50ff3 | e2f08e3d0564a003400743ae6050fd687c280639 | refs/heads/main | 2023-07-25T09:10:53.649082 | 2021-09-05T19:39:14 | 2021-09-05T19:39:14 | 403,396,706 | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 135 | py | # Write a program to count the number of zeros in the following tuple:
# a = (7,0,8,0,0,9)
a = (7,0,8,0,0,9)
print(a.count(0)) | [
"[email protected]"
] | |
1b406b2dc38004db14248af19fb7f7be9b8e7f6c | 487ce91881032c1de16e35ed8bc187d6034205f7 | /codes/BuildLinks1.10/test_input/CJ_16_1/16_1_1_FreeTShirt_a.py | 0207b362ff64f55d6e7a49f758c368374d2c5dc1 | [] | 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 | 404 | py | def argmax(s):
z = max(s)
return [(idx, c) for idx, c in enumerate(s) if c == z]
def last(s):
if len(s) <= 1:
return s
return max([s[idx]+last(s[:idx])+s[idx+1:] for idx, c in argmax(s)])
fw = open('a-o', 'w')
for idx, line in enumerate(open('A-small-i')):
if idx == 0:
continue
s = line.strip()
print(s)
fw.write('Case #{0}: {1}\n'.format(idx,last(s)))
| [
"[[email protected]]"
] | |
8732c9af3fea83ea57fa51e58d56b098749760f6 | 6561baa7ca68875e62fbf2d20c7887e4aadebe9f | /tests/cds_test_20_sf_ukmo.py | efa292077e335becd6970c33d7b3c44900ea5f35 | [
"Apache-2.0"
] | permissive | EXWEXs/cfgrib | 9057c9e5abbc38a32f113f832f1506988839ee82 | 8a1727af2c3bbcf2e17f250dfafcb4cc4e959354 | refs/heads/master | 2020-04-01T15:44:45.140700 | 2018-10-14T14:39:13 | 2018-10-14T14:39:13 | null | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 4,089 | py |
import pytest
import cfgrib
import cdscommon
TEST_FILES = {
'seasonal-original-single-levels-ukmo': [
'seasonal-original-single-levels',
{
'originating_centre': 'ukmo',
'variable': 'maximum_2m_temperature_in_the_last_24_hours',
'year': '2018',
'month': ['04', '05'],
'day': [
'01', '02', '03', '04', '05', '06', '07', '08', '09', '10', '11', '12',
'13', '14', '15', '16', '17', '18', '19', '20', '21', '22', '23', '24',
'25', '26', '27', '28', '29', '30', '31'
],
'leadtime_hour': ['24', '48'],
'grid': ['3', '3'],
'format': 'grib',
},
192,
],
'seasonal-original-pressure-levels-ukmo': [
'seasonal-original-pressure-levels',
{
'originating_centre': 'ukmo',
'variable': 'temperature',
'pressure_level': ['500', '850'],
'year': '2018',
'month': ['04', '05'],
'day': [
'01', '02', '03', '04', '05', '06', '07', '08', '09', '10', '11', '12',
'13', '14', '15', '16', '17', '18', '19', '20', '21', '22', '23', '24',
'25', '26', '27', '28', '29', '30', '31'
],
'leadtime_hour': ['24', '48'],
'grid': ['3', '3'],
'format': 'grib',
},
192,
],
'seasonal-postprocessed-single-levels-ukmo': [
'seasonal-postprocessed-single-levels',
{
'originating_centre': 'ukmo',
'variable': 'maximum_2m_temperature_in_the_last_24_hours_anomaly',
'product_type': 'monthly_mean',
'year': '2018',
'month': ['04', '05'],
'leadtime_month': ['1', '2'],
'grid': ['3', '3'],
'format': 'grib',
},
210,
],
'seasonal-monthly-single-levels-monthly_mean-ukmo': [
'seasonal-monthly-single-levels',
{
'originating_centre': 'ukmo',
'variable': 'maximum_2m_temperature_in_the_last_24_hours',
'product_type': 'monthly_mean',
'year': '2018',
'month': ['04', '05'],
'leadtime_month': ['1', '2'],
'grid': ['3', '3'],
'format': 'grib',
},
210,
],
'seasonal-monthly-single-levels-ensemble_mean-ukmo': [
'seasonal-monthly-single-levels',
{
'originating_centre': 'ukmo',
'variable': 'maximum_2m_temperature_in_the_last_24_hours',
'product_type': 'ensemble_mean',
'year': '2018',
'month': ['04', '05'],
'leadtime_month': ['1', '2'],
'grid': ['3', '3'],
'format': 'grib',
},
210,
],
'seasonal-monthly-single-levels-hindcast_climate_mean-ukmo': [
'seasonal-monthly-single-levels',
{
'originating_centre': 'ukmo',
'variable': 'maximum_2m_temperature_in_the_last_24_hours',
'product_type': 'hindcast_climate_mean',
'year': '2018',
'month': ['04', '05'],
'leadtime_month': ['1', '2'],
'grid': ['3', '3'],
'format': 'grib',
},
210,
],
}
@pytest.mark.parametrize('test_file', TEST_FILES.keys())
def test_reanalysis_Stream(test_file):
dataset, request, key_count = TEST_FILES[test_file]
path = cdscommon.ensure_data(dataset, request, name='cds-' + test_file + '-{uuid}.grib')
stream = cfgrib.FileStream(path)
leader = stream.first()
assert len(leader) == key_count
assert sum(1 for _ in stream) == leader['count']
@pytest.mark.parametrize('test_file', TEST_FILES.keys())
def test_reanalysis_Dataset(test_file):
dataset, request, key_count = TEST_FILES[test_file]
path = cdscommon.ensure_data(dataset, request, name='cds-' + test_file + '-{uuid}.grib')
res = cfgrib.xarray_store.open_dataset(path, flavour_name='cds')
res.to_netcdf(path[:-5] + '.nc')
| [
"[email protected]"
] | |
5e0bde2a16193651c22bf50efd429a326bf6f474 | 6b564e24a99b2d2c6a384d8674974f10ef9461d5 | /iptv_proxy/providers/crystalclear/data_model.py | 53c6ad0d72865ecf54ed3413a6d9df1d667e4c12 | [
"MIT"
] | permissive | Onemars/IPTVProxy | 1c1421c6962c1f7cf4cef90d8a2c98e98f5ded25 | 06d5472f49ecaa7eafb90832a1c9ac85a09cd268 | refs/heads/master | 2020-05-24T14:34:48.486177 | 2019-05-17T14:17:21 | 2019-05-17T14:17:21 | 187,311,948 | 1 | 0 | null | 2019-05-18T03:58:48 | 2019-05-18T03:58:47 | null | UTF-8 | Python | false | false | 6,858 | py | import logging
from sqlalchemy import Column
from sqlalchemy import Index
from sqlalchemy import Integer
from sqlalchemy import LargeBinary
from sqlalchemy import String
from sqlalchemy.ext.hybrid import hybrid_property
from iptv_proxy.data_model import DateTimeUTC
from iptv_proxy.providers.crystalclear.constants import CrystalClearConstants
from iptv_proxy.providers.crystalclear.db import Base
logger = logging.getLogger(__name__)
class CrystalClearChannel(Base):
_provider_name = CrystalClearConstants.PROVIDER_NAME.lower()
__tablename__ = 'channel'
_id = Column('id', String, primary_key=True, autoincrement=False)
_m3u8_group = Column('m3u8_group', String, nullable=False)
_number = Column('number', Integer, nullable=False)
_name = Column('name', String, nullable=False)
_pickle = Column('pickle', LargeBinary, nullable=False)
_complete_xmltv = Column('complete_xmltv', String, nullable=False)
_minimal_xmltv = Column('minimal_xmltv', String, nullable=False)
__table_args__ = (Index('{0}_channel_ix_id'.format(_provider_name), _id.asc()),
Index('{0}_channel_ix_m3u8_group'.format(_provider_name), _m3u8_group.asc()),
Index('{0}_channel_ix_m3u8_group_&_number'.format(_provider_name),
_m3u8_group.asc(),
_number.asc()),
Index('{0}_channel_ix_number'.format(_provider_name), _number.asc()))
def __init__(self, id_, m3u8_group, number, name, pickle, complete_xmltv, minimal_xmltv):
self._id = id_
self._m3u8_group = m3u8_group
self._number = number
self._name = name
self._pickle = pickle
self._complete_xmltv = complete_xmltv
self._minimal_xmltv = minimal_xmltv
@hybrid_property
def complete_xmltv(self):
return self._complete_xmltv
@complete_xmltv.setter
def complete_xmltv(self, complete_xmltv):
self._complete_xmltv = complete_xmltv
@hybrid_property
def id(self):
return self._id
@id.setter
def id(self, id_):
self._id = id_
@hybrid_property
def m3u8_group(self):
return self._m3u8_group
@m3u8_group.setter
def m3u8_group(self, m3u8_group):
self._m3u8_group = m3u8_group
@hybrid_property
def minimal_xmltv(self):
return self._minimal_xmltv
@minimal_xmltv.setter
def minimal_xmltv(self, minimal_xmltv):
self._minimal_xmltv = minimal_xmltv
@hybrid_property
def name(self):
return self._name
@name.setter
def name(self, name):
self._name = name
@hybrid_property
def number(self):
return self._number
@number.setter
def number(self, number):
self._number = number
@hybrid_property
def pickle(self):
return self._pickle
@pickle.setter
def pickle(self, pickle):
self._pickle = pickle
class CrystalClearProgram(Base):
_provider_name = CrystalClearConstants.PROVIDER_NAME.lower()
__tablename__ = 'program'
_id = Column('id', String, primary_key=True, autoincrement=False)
_start = Column('start', DateTimeUTC(timezone=True), nullable=False)
_stop = Column('stop', DateTimeUTC(timezone=True), nullable=False)
_channel_xmltv_id = Column('channel_xmltv_id', String, nullable=False)
_channel_number = Column('channel_number', Integer, nullable=False)
_pickle = Column('pickle', LargeBinary, nullable=False)
_complete_xmltv = Column('complete_xmltv', String, nullable=False)
_minimal_xmltv = Column('minimal_xmltv', String, nullable=False)
__table_args__ = (
Index('{0}_program_ix_id'.format(_provider_name), _id.asc()),
Index('{0}_program_ix_channel_number_&_start'.format(_provider_name), _channel_number.asc(), _start.asc()),
Index('{0}_program_ix_channel_xmltv_id_&_start'.format(_provider_name), _channel_xmltv_id.asc(), _start.asc()),
Index('{0}_program_ix_channel_xmltv_id_&_start_&_stop'.format(_provider_name),
_channel_xmltv_id.asc(),
_start.asc(),
_stop.asc()),
Index('{0}_program_ix_start'.format(_provider_name), _start.asc()))
def __init__(self,
id_,
start,
stop,
channel_xmltv_id,
channel_number,
pickle,
complete_xmltv,
minimal_xmltv):
self._id = id_
self._start = start
self._stop = stop
self._channel_xmltv_id = channel_xmltv_id
self._channel_number = channel_number
self._pickle = pickle
self._complete_xmltv = complete_xmltv
self._minimal_xmltv = minimal_xmltv
@hybrid_property
def channel_number(self):
return self._channel_number
@channel_number.setter
def channel_number(self, channel_number):
self._channel_number = channel_number
@hybrid_property
def channel_xmltv_id(self):
return self._channel_xmltv_id
@channel_xmltv_id.setter
def channel_xmltv_id(self, channel_xmltv_id):
self._channel_xmltv_id = channel_xmltv_id
@hybrid_property
def complete_xmltv(self):
return self._complete_xmltv
@complete_xmltv.setter
def complete_xmltv(self, complete_xmltv):
self._complete_xmltv = complete_xmltv
@hybrid_property
def id(self):
return self._id
@id.setter
def id(self, id_):
self._id = id_
@hybrid_property
def minimal_xmltv(self):
return self._minimal_xmltv
@minimal_xmltv.setter
def minimal_xmltv(self, minimal_xmltv):
self._minimal_xmltv = minimal_xmltv
@hybrid_property
def pickle(self):
return self._pickle
@pickle.setter
def pickle(self, pickle):
self._pickle = pickle
@hybrid_property
def start(self):
return self._start
@start.setter
def start(self, start):
self._start = start
@hybrid_property
def stop(self):
return self._stop
@stop.setter
def stop(self, stop):
self._stop = stop
class CrystalClearSetting(Base):
_provider_name = CrystalClearConstants.PROVIDER_NAME.lower()
__tablename__ = 'setting'
_name = Column('name', String, primary_key=True)
_value = Column('value', String, nullable=False)
__table_args__ = (Index('setting_ix_name', _name.asc()),)
def __init__(self, name, value):
self._name = name
self._value = value
@hybrid_property
def name(self):
return self._name
@name.setter
def name(self, name):
self._name = name
@hybrid_property
def value(self):
return self._value
@value.setter
def value(self, value):
self._value = value
| [
"[email protected]"
] | |
727c6dd5a9d6d63154d4df935778852dc73c00fa | c590571d129ead00bd1916025f854a1719d75683 | /zvt/recorders/joinquant/meta/china_stock_meta_recorder.py | fa4a0c4364dd713ab0f74d8b7829a1b6f86f10ac | [
"MIT"
] | permissive | ming123jew/zvt | f2fb8e157951e9440a6decd5ae0c08ea227a39db | de66a48ad2a3ac2c3fb22b9ea17a85f28e95cc62 | refs/heads/master | 2023-05-28T15:00:52.015084 | 2021-06-13T12:56:18 | 2021-06-13T12:56:18 | 570,070,597 | 1 | 0 | MIT | 2022-11-24T09:16:48 | 2022-11-24T09:16:47 | null | UTF-8 | Python | false | false | 5,733 | py | # -*- coding: utf-8 -*-
import pandas as pd
from jqdatapy.api import get_all_securities, run_query
from zvt.api.quote import china_stock_code_to_id, portfolio_relate_stock
from zvt.contract.api import df_to_db, get_entity_exchange, get_entity_code
from zvt.contract.recorder import Recorder, TimeSeriesDataRecorder
from zvt.domain import EtfStock, Stock, Etf, StockDetail
from zvt.recorders.joinquant.common import to_entity_id, jq_to_report_period
from zvt.utils.pd_utils import pd_is_not_null
from zvt.utils.time_utils import to_time_str
class BaseJqChinaMetaRecorder(Recorder):
provider = 'joinquant'
def __init__(self, batch_size=10, force_update=True, sleeping_time=10) -> None:
super().__init__(batch_size, force_update, sleeping_time)
def to_zvt_entity(self, df, entity_type, category=None):
df = df.set_index('code')
df.index.name = 'entity_id'
df = df.reset_index()
# 上市日期
df.rename(columns={'start_date': 'timestamp'}, inplace=True)
df['timestamp'] = pd.to_datetime(df['timestamp'])
df['list_date'] = df['timestamp']
df['end_date'] = pd.to_datetime(df['end_date'])
df['entity_id'] = df['entity_id'].apply(lambda x: to_entity_id(entity_type=entity_type, jq_code=x))
df['id'] = df['entity_id']
df['entity_type'] = entity_type
df['exchange'] = df['entity_id'].apply(lambda x: get_entity_exchange(x))
df['code'] = df['entity_id'].apply(lambda x: get_entity_code(x))
df['name'] = df['display_name']
if category:
df['category'] = category
return df
class JqChinaStockRecorder(BaseJqChinaMetaRecorder):
data_schema = Stock
def run(self):
# 抓取股票列表
df_stock = self.to_zvt_entity(get_all_securities(code='stock'), entity_type='stock')
df_to_db(df_stock, data_schema=Stock, provider=self.provider, force_update=self.force_update)
# persist StockDetail too
df_to_db(df=df_stock, data_schema=StockDetail, provider=self.provider, force_update=self.force_update)
# self.logger.info(df_stock)
self.logger.info("persist stock list success")
class JqChinaEtfRecorder(BaseJqChinaMetaRecorder):
data_schema = Etf
def run(self):
# 抓取etf列表
df_index = self.to_zvt_entity(get_all_securities(code='etf'), entity_type='etf', category='etf')
df_to_db(df_index, data_schema=Etf, provider=self.provider, force_update=self.force_update)
# self.logger.info(df_index)
self.logger.info("persist etf list success")
class JqChinaStockEtfPortfolioRecorder(TimeSeriesDataRecorder):
entity_provider = 'joinquant'
entity_schema = Etf
# 数据来自jq
provider = 'joinquant'
data_schema = EtfStock
def __init__(self, entity_type='etf', exchanges=['sh', 'sz'], entity_ids=None, codes=None, day_data=True, batch_size=10,
force_update=False, sleeping_time=5, default_size=2000, real_time=False, fix_duplicate_way='add',
start_timestamp=None, end_timestamp=None, close_hour=0, close_minute=0) -> None:
super().__init__(entity_type, exchanges, entity_ids, codes, day_data, batch_size, force_update, sleeping_time,
default_size, real_time, fix_duplicate_way, start_timestamp, end_timestamp, close_hour,
close_minute)
def record(self, entity, start, end, size, timestamps):
df = run_query(table='finance.FUND_PORTFOLIO_STOCK',
conditions=f'pub_date#>=#{to_time_str(start)}&code#=#{entity.code}',
parse_dates=None)
if pd_is_not_null(df):
# id code period_start period_end pub_date report_type_id report_type rank symbol name shares market_cap proportion
# 0 8640569 159919 2018-07-01 2018-09-30 2018-10-26 403003 第三季度 1 601318 中国平安 19869239.0 1.361043e+09 7.09
# 1 8640570 159919 2018-07-01 2018-09-30 2018-10-26 403003 第三季度 2 600519 贵州茅台 921670.0 6.728191e+08 3.50
# 2 8640571 159919 2018-07-01 2018-09-30 2018-10-26 403003 第三季度 3 600036 招商银行 18918815.0 5.806184e+08 3.02
# 3 8640572 159919 2018-07-01 2018-09-30 2018-10-26 403003 第三季度 4 601166 兴业银行 22862332.0 3.646542e+08 1.90
df['timestamp'] = pd.to_datetime(df['pub_date'])
df.rename(columns={'symbol': 'stock_code', 'name': 'stock_name'}, inplace=True)
df['proportion'] = df['proportion'] * 0.01
df = portfolio_relate_stock(df, entity)
df['stock_id'] = df['stock_code'].apply(lambda x: china_stock_code_to_id(x))
df['id'] = df[['entity_id', 'stock_id', 'pub_date', 'id']].apply(lambda x: '_'.join(x.astype(str)), axis=1)
df['report_date'] = pd.to_datetime(df['period_end'])
df['report_period'] = df['report_type'].apply(lambda x: jq_to_report_period(x))
df_to_db(df=df, data_schema=self.data_schema, provider=self.provider, force_update=self.force_update)
# self.logger.info(df.tail())
self.logger.info(f"persist etf {entity.code} portfolio success {df.iloc[-1]['pub_date']}")
return None
if __name__ == '__main__':
# JqChinaEtfRecorder().run()
JqChinaStockEtfPortfolioRecorder(codes=['510050']).run()
# the __all__ is generated
__all__ = ['BaseJqChinaMetaRecorder', 'JqChinaStockRecorder', 'JqChinaEtfRecorder', 'JqChinaStockEtfPortfolioRecorder'] | [
"[email protected]"
] | |
da4e65994020ecec1aae6923a1bd83b3951032e3 | a90ba084b85683f4c52d0e638cfb6108207ced38 | /896.py | 91ca187efe65342ba1e072994842f422f065f605 | [] | no_license | JiayuZhai/leetcode_python3 | 4a9260d00a52cde9ec37e6292e64d04161e66111 | 5755c3edd6d949af18d0247d2103379510dfab85 | refs/heads/master | 2020-04-02T21:22:42.270736 | 2019-03-29T23:28:48 | 2019-03-29T23:28:48 | 154,796,956 | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 162 | py | class Solution:
def isMonotonic(self, A: List[int]) -> bool:
sortA = sorted(A)
return (A == sortA or list(reversed(A)) == sortA)
| [
"[email protected]"
] | |
90a5ad57cf62d7082f693f949d412f2d773b647a | 844c7f8fb8d6bfab912583c71b93695167c59764 | /fixação/Seção06/51-60/Sec06Ex51v2.py | 35580169e28f8bc9bc58b28718531dd96aa9d948 | [
"Apache-2.0"
] | permissive | gugajung/guppe | 2be10656cd9aa33be6afb8e86f20df82662bcc59 | a0ee7b85e8687e8fb8243fbb509119a94bc6460f | refs/heads/main | 2023-05-28T08:08:24.963356 | 2021-06-07T16:56:11 | 2021-06-07T16:56:11 | null | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 624 | py | from datetime import date
anoAtual = 1995
salarioAtual = 2000
percentAumento = 1.5
dataAtual = date.today()
anoReal = dataAtual.year
while anoAtual <= anoReal:
salarioAtual = salarioAtual + ((salarioAtual*percentAumento)/100)
print("----------------------------------------")
print(" --- debug")
print(f" --- > Ano Atual : {anoAtual}")
print(f" --- > Salario Atual : {salarioAtual:.2f}")
print(f" --- > Percente de Aumento : {percentAumento:.4f}")
anoAtual += 1
percentAumento *= 2
print("=================================================")
print("Final de O programas") | [
"[email protected]"
] | |
d3e7e9dae606fe6dc77d9c43997e9c592fbcd477 | 982bc95ab762829c8b6913e44504415cdd77241a | /account_easy_reconcile/base_reconciliation.py | b50c06b9eed699d96da272f0fb9dd9613177c235 | [] | no_license | smart-solution/natuurpunt-finance | 6b9eb65be96a4e3261ce46d7f0c31de3589e1e0d | 6eeb48468792e09d46d61b89499467a44d67bc79 | refs/heads/master | 2021-01-23T14:42:05.017263 | 2020-11-03T15:56:35 | 2020-11-03T15:56:35 | 39,186,046 | 0 | 1 | null | 2020-11-03T15:56:37 | 2015-07-16T08:36:54 | Python | UTF-8 | Python | false | false | 7,776 | py | # -*- coding: utf-8 -*-
##############################################################################
#
# Copyright 2012-2013 Camptocamp SA (Guewen Baconnier)
# Copyright (C) 2010 Sébastien Beau
#
# 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.osv import fields, orm
from operator import itemgetter, attrgetter
class easy_reconcile_base(orm.AbstractModel):
"""Abstract Model for reconciliation methods"""
_name = 'easy.reconcile.base'
_inherit = 'easy.reconcile.options'
_columns = {
'account_id': fields.many2one(
'account.account', 'Account', required=True),
'partner_ids': fields.many2many(
'res.partner', string="Restrict on partners"),
# other columns are inherited from easy.reconcile.options
}
def automatic_reconcile(self, cr, uid, ids, context=None):
""" Reconciliation method called from the view.
:return: list of reconciled ids, list of partially reconciled items
"""
if isinstance(ids, (int, long)):
ids = [ids]
assert len(ids) == 1, "Has to be called on one id"
rec = self.browse(cr, uid, ids[0], context=context)
return self._action_rec(cr, uid, rec, context=context)
def _action_rec(self, cr, uid, rec, context=None):
""" Must be inherited to implement the reconciliation
:return: list of reconciled ids
"""
raise NotImplementedError
def _base_columns(self, rec):
""" Mandatory columns for move lines queries
An extra column aliased as ``key`` should be defined
in each query."""
aml_cols = (
'id',
'debit',
'credit',
'date',
'period_id',
'ref',
'name',
'partner_id',
'account_id',
'move_id')
return ["account_move_line.%s" % col for col in aml_cols]
def _select(self, rec, *args, **kwargs):
return "SELECT %s" % ', '.join(self._base_columns(rec))
def _from(self, rec, *args, **kwargs):
return "FROM account_move_line"
def _where(self, rec, *args, **kwargs):
where = ("WHERE account_move_line.account_id = %s "
"AND account_move_line.reconcile_id IS NULL ")
# it would be great to use dict for params
# but as we use _where_calc in _get_filter
# which returns a list, we have to
# accomodate with that
params = [rec.account_id.id]
if rec.partner_ids:
where += " AND account_move_line.partner_id IN %s"
params.append(tuple([l.id for l in rec.partner_ids]))
return where, params
def _get_filter(self, cr, uid, rec, context):
ml_obj = self.pool.get('account.move.line')
where = ''
params = []
if rec.filter:
dummy, where, params = ml_obj._where_calc(
cr, uid, eval(rec.filter), context=context).get_sql()
if where:
where = " AND %s" % where
return where, params
def _below_writeoff_limit(self, cr, uid, rec, lines,
writeoff_limit, context=None):
precision = self.pool.get('decimal.precision').precision_get(
cr, uid, 'Account')
keys = ('debit', 'credit')
sums = reduce(
lambda line, memo:
dict((key, value + memo[key])
for key, value
in line.iteritems()
if key in keys), lines)
debit, credit = sums['debit'], sums['credit']
writeoff_amount = round(debit - credit, precision)
return bool(writeoff_limit >= abs(writeoff_amount)), debit, credit
def _get_rec_date(self, cr, uid, rec, lines,
based_on='end_period_last_credit', context=None):
period_obj = self.pool.get('account.period')
def last_period(mlines):
period_ids = [ml['period_id'] for ml in mlines]
periods = period_obj.browse(
cr, uid, period_ids, context=context)
return max(periods, key=attrgetter('date_stop'))
def last_date(mlines):
return max(mlines, key=itemgetter('date'))
def credit(mlines):
return [l for l in mlines if l['credit'] > 0]
def debit(mlines):
return [l for l in mlines if l['debit'] > 0]
if based_on == 'end_period_last_credit':
return last_period(credit(lines)).date_stop
if based_on == 'end_period':
return last_period(lines).date_stop
elif based_on == 'newest':
return last_date(lines)['date']
elif based_on == 'newest_credit':
return last_date(credit(lines))['date']
elif based_on == 'newest_debit':
return last_date(debit(lines))['date']
# reconcilation date will be today
# when date is None
return None
def _reconcile_lines(self, cr, uid, rec, lines, allow_partial=False, context=None):
""" Try to reconcile given lines
:param list lines: list of dict of move lines, they must at least
contain values for : id, debit, credit
:param boolean allow_partial: if True, partial reconciliation will be
created, otherwise only Full
reconciliation will be created
:return: tuple of boolean values, first item is wether the items
have been reconciled or not,
the second is wether the reconciliation is full (True)
or partial (False)
"""
if context is None:
context = {}
ml_obj = self.pool.get('account.move.line')
writeoff = rec.write_off
line_ids = [l['id'] for l in lines]
below_writeoff, sum_debit, sum_credit = self._below_writeoff_limit(
cr, uid, rec, lines, writeoff, context=context)
date = self._get_rec_date(
cr, uid, rec, lines, rec.date_base_on, context=context)
rec_ctx = dict(context, date_p=date)
if below_writeoff:
if sum_credit < sum_debit:
writeoff_account_id = rec.account_profit_id.id
else:
writeoff_account_id = rec.account_lost_id.id
period_id = self.pool.get('account.period').find(
cr, uid, dt=date, context=context)[0]
ml_obj.reconcile(
cr, uid,
line_ids,
type='auto',
writeoff_acc_id=writeoff_account_id,
writeoff_period_id=period_id,
writeoff_journal_id=rec.journal_id.id,
context=rec_ctx)
return True, True
elif allow_partial:
ml_obj.reconcile_partial(
cr, uid,
line_ids,
type='manual',
context=rec_ctx)
return True, False
return False, False
| [
"[email protected]"
] | |
ae535fe72253b6c574f7196c75a3b64e003c3ea3 | ccb6918eff9624bc890c4318462b3d04fe01ab25 | /d02/for/for/settings.py | 763917cea83d3de15fae9c387027213bdac3fd6e | [] | no_license | shchliu/19django | 431202f3b4a71fb2614f3f113174df327a338413 | 63af6aeff279a83fb170c1b5385d0804d96fafad | refs/heads/master | 2020-08-15T08:53:36.707823 | 2019-10-16T08:26:41 | 2019-10-16T08:28:32 | null | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 3,121 | py | """
Django settings for for project.
Generated by 'django-admin startproject' using Django 2.0.
For more information on this file, see
https://docs.djangoproject.com/en/2.0/topics/settings/
For the full list of settings and their values, see
https://docs.djangoproject.com/en/2.0/ref/settings/
"""
import os
# Build paths inside the project like this: os.path.join(BASE_DIR, ...)
BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
# Quick-start development settings - unsuitable for production
# See https://docs.djangoproject.com/en/2.0/howto/deployment/checklist/
# SECURITY WARNING: keep the secret key used in production secret!
SECRET_KEY = 'n$s!ww49p_&vb4(^$4-n#s(98qsu+(61j_2w2)&7pbx+3(k_x+'
# SECURITY WARNING: don't run with debug turned on in production!
DEBUG = True
ALLOWED_HOSTS = []
# Application definition
INSTALLED_APPS = [
'django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles',
]
MIDDLEWARE = [
'django.middleware.security.SecurityMiddleware',
'django.contrib.sessions.middleware.SessionMiddleware',
'django.middleware.common.CommonMiddleware',
'django.middleware.csrf.CsrfViewMiddleware',
'django.contrib.auth.middleware.AuthenticationMiddleware',
'django.contrib.messages.middleware.MessageMiddleware',
'django.middleware.clickjacking.XFrameOptionsMiddleware',
]
ROOT_URLCONF = 'for.urls'
TEMPLATES = [
{
'BACKEND': 'django.template.backends.django.DjangoTemplates',
'DIRS': [os.path.join(BASE_DIR, 'templates')]
,
'APP_DIRS': True,
'OPTIONS': {
'context_processors': [
'django.template.context_processors.debug',
'django.template.context_processors.request',
'django.contrib.auth.context_processors.auth',
'django.contrib.messages.context_processors.messages',
],
},
},
]
WSGI_APPLICATION = 'for.wsgi.application'
# Database
# https://docs.djangoproject.com/en/2.0/ref/settings/#databases
DATABASES = {
'default': {
'ENGINE': 'django.db.backends.sqlite3',
'NAME': os.path.join(BASE_DIR, 'db.sqlite3'),
}
}
# Password validation
# https://docs.djangoproject.com/en/2.0/ref/settings/#auth-password-validators
AUTH_PASSWORD_VALIDATORS = [
{
'NAME': 'django.contrib.auth.password_validation.UserAttributeSimilarityValidator',
},
{
'NAME': 'django.contrib.auth.password_validation.MinimumLengthValidator',
},
{
'NAME': 'django.contrib.auth.password_validation.CommonPasswordValidator',
},
{
'NAME': 'django.contrib.auth.password_validation.NumericPasswordValidator',
},
]
# Internationalization
# https://docs.djangoproject.com/en/2.0/topics/i18n/
LANGUAGE_CODE = 'en-us'
TIME_ZONE = 'UTC'
USE_I18N = True
USE_L10N = True
USE_TZ = True
# Static files (CSS, JavaScript, Images)
# https://docs.djangoproject.com/en/2.0/howto/static-files/
STATIC_URL = '/static/'
| [
"[email protected]"
] | |
b6e187de710d37037dd7c0d830a50e7eaee1aa28 | 786027545626c24486753351d6e19093b261cd7d | /ghidra9.2.1_pyi/ghidra/app/util/bin/format/xcoff/XCoffSectionHeaderFlags.pyi | 43a745532a3157885655ec9c25a175e6ac3df2ec | [
"MIT"
] | permissive | kohnakagawa/ghidra_scripts | 51cede1874ef2b1fed901b802316449b4bf25661 | 5afed1234a7266c0624ec445133280993077c376 | refs/heads/main | 2023-03-25T08:25:16.842142 | 2021-03-18T13:31:40 | 2021-03-18T13:31:40 | 338,577,905 | 14 | 1 | null | null | null | null | UTF-8 | Python | false | false | 772 | pyi | import java.lang
class XCoffSectionHeaderFlags(object):
STYP_BSS: int = 128
STYP_DATA: int = 64
STYP_DEBUG: int = 8192
STYP_EXCEPT: int = 128
STYP_INFO: int = 512
STYP_LOADER: int = 4096
STYP_OVRFLO: int = 32768
STYP_PAD: int = 8
STYP_TEXT: int = 32
STYP_TYPCHK: int = 16384
def __init__(self): ...
def equals(self, __a0: object) -> bool: ...
def getClass(self) -> java.lang.Class: ...
def hashCode(self) -> int: ...
def notify(self) -> None: ...
def notifyAll(self) -> None: ...
def toString(self) -> unicode: ...
@overload
def wait(self) -> None: ...
@overload
def wait(self, __a0: long) -> None: ...
@overload
def wait(self, __a0: long, __a1: int) -> None: ...
| [
"[email protected]"
] | |
ce42ed7f15ab68df41c64c17c877f642173d66a2 | a7cca49626a3d7100e9ac5c2f343c351ecb76ac7 | /upydev/argcompleter.py | 3751c0a54657cd37a9a63de43d2f4f77ad8882e7 | [
"MIT"
] | permissive | Carglglz/upydev | 104455d77d64300074bda54d86bd791f19184975 | 529aa29f3e1acf8160383fe410b5659110dc96de | refs/heads/master | 2023-05-24T18:38:56.242500 | 2022-10-21T14:03:17 | 2022-10-21T14:03:17 | 199,335,165 | 49 | 9 | MIT | 2022-10-21T14:03:18 | 2019-07-28T20:42:00 | Python | UTF-8 | Python | false | false | 57,893 | py | import os
from upydev import __path__
UPYDEV_PATH = __path__[0]
# SHELL_CMD_PARSER
shell_commands = ['cd', 'mkdir', 'cat', 'head', 'rm', 'rmdir', 'pwd',
'run', 'mv']
custom_sh_cmd_kw = ['df', 'datetime', 'ifconfig', 'net',
'ap', 'mem', 'install', 'touch',
'exit', 'lpwd', 'lsl', 'lcd', 'put', 'get', 'ls',
'set', 'tree', 'dsync', 'reload', 'docs',
'du', 'ldu', 'upip', 'uping',
'timeit', 'i2c',
'upy-config', 'jupyterc', 'pytest', 'rssi',
'info', 'id', 'uhelp', 'modules', 'shasum', 'vim',
'update_upyutils', 'mdocs', 'ctime', 'enable_sh',
'diff', 'config', 'fw', 'mpyx', 'sd', 'uptime', 'cycles', 'play']
LS = dict(help="list files or directories",
subcmd=dict(help='indicate a file/dir or pattern to see', default=[],
metavar='file/dir/pattern', nargs='*'),
options={"-a": dict(help='list hidden files', required=False,
default=False,
action='store_true'),
"-d": dict(help='depth level', required=False,
default=0,
type=int)})
HEAD = dict(help="display first lines of a file",
subcmd=dict(help='indicate a file or pattern to see', default=[],
metavar='file/pattern', nargs='*'),
options={"-n": dict(help='number of lines to print', required=False,
default=10,
type=int)})
CAT = dict(help="concatenate and print files",
subcmd=dict(help='indicate a file or pattern to see', default=[],
metavar='file/pattern', nargs='*'),
options={"-d": dict(help='depth level', required=False,
default=0,
type=int)})
MKDIR = dict(help="make directories",
subcmd=dict(help='indicate a dir/pattern to create', default=[],
metavar='dir', nargs='*'),
options={})
CD = dict(help="change current working directory",
subcmd=dict(help='indicate a dir to change to', default='/',
metavar='dir', nargs='?'),
options={})
MV = dict(help="move/rename a file",
subcmd=dict(help='indicate a file to rename', default=[],
metavar='file', nargs=2),
options={})
PWD = dict(help="print current working directory",
subcmd={},
options={})
RM = dict(help="remove file or pattern of files",
subcmd=dict(help='indicate a file/pattern to remove', default=[],
metavar='file/dir/pattern', nargs='+'),
options={"-rf": dict(help='remove recursive force a dir or file',
required=False,
default=False,
action='store_true'),
"-d": dict(help='depth level search', required=False,
default=0,
type=int),
"-dd": dict(help='filter for directories only', required=False,
default=False,
action='store_true')})
RMDIR = dict(help="remove directories or pattern of directories",
subcmd=dict(help='indicate a dir/pattern to remove', default=[],
metavar='dir', nargs='+'),
options={"-d": dict(help='depth level search', required=False,
default=0,
type=int)})
DU = dict(help="display disk usage statistics",
subcmd=dict(help='indicate a dir to see usage', default='',
metavar='dir', nargs='?'),
options={"-d": dict(help='depth level', required=False,
default=0,
type=int),
"-p": dict(help='pattern to match', required=False,
default=[],
nargs='*')})
TREE = dict(help="list contents of directories in a tree-like format",
subcmd=dict(help='indicate a dir to see', default='',
metavar='dir', nargs='?'),
options={"-a": dict(help='list hidden files', required=False,
default=False,
action='store_true')})
DF = dict(help="display free disk space",
subcmd={},
options={})
MEM = dict(help="show ram usage info",
subcmd=dict(help='{info , dump}; default: info',
default='info',
metavar='action', choices=['info', 'dump'], nargs='?'),
options={})
EXIT = dict(help="exit upydev shell",
subcmd={},
options={"-r": dict(help='soft-reset after exit', required=False,
default=False,
action='store_true'),
"-hr": dict(help='hard-reset after exit', required=False,
default=False,
action='store_true')})
VIM = dict(help="use vim to edit files",
subcmd=dict(help='indicate a file to edit', default='',
metavar='file', nargs='?'),
options={"-rm": dict(help='remove local copy after upload', required=False,
default=False,
action='store_true'),
"-e": dict(help='execute script after upload', required=False,
default=False,
action='store_true'),
"-r": dict(help='reload script so it can run again',
required=False,
default=False,
action='store_true'),
"-o": dict(help='override local copy if present',
required=False,
default=False,
action='store_true'),
"-d": dict(help=('use vim diff between device and local files'
', if same file name device file is ~file'),
required=False,
default=[],
nargs='+')})
DIFF = dict(help=("use git diff between device's [~file/s] and local file/s"),
subcmd=dict(help='indicate files to compare or pattern', default=['*', '*'],
metavar='fileA fileB', nargs='+'),
options={"-s": dict(help='switch file comparison',
required=False,
default=False,
action='store_true')})
RUN = dict(help="run device's scripts",
subcmd=dict(help='indicate a file/script to run', default='',
metavar='file'),
options={"-r": dict(help='reload script so it can run again',
required=False,
default=False,
action='store_true'),
})
RELOAD = dict(help="reload device's scripts",
subcmd=dict(help='indicate a file/script to reload', default='',
metavar='file', nargs=1),
options={})
LCD = dict(help="change local current working directory",
subcmd=dict(help='indicate a dir to change to', default='',
metavar='dir', nargs='?'),
options={})
LSL = dict(help="list local files or directories",
subcmd=dict(help='indicate a file/dir or pattern to see', default=[],
metavar='file/dir/pattern', nargs='*'),
options={"-a": dict(help='list hidden files', required=False,
default=False,
action='store_true')})
LPWD = dict(help="print local current working directory",
subcmd={},
options={})
LDU = dict(help="display local disk usage statistics",
subcmd=dict(help='indicate a dir to see usage', default='',
metavar='dir', nargs='?'),
options={"-d": dict(help='depth level', required=False,
default=0,
type=int)})
INFO = dict(help="prints device's info",
subcmd={},
options={})
ID = dict(help="prints device's unique id",
subcmd={},
options={})
UHELP = dict(help="prints device's help info",
subcmd={},
options={})
MODULES = dict(help="prints device's frozen modules",
subcmd={},
options={})
UPING = dict(help="device send ICMP ECHO_REQUEST packets to network hosts",
subcmd=dict(help='indicate an IP address to ping; default: host IP',
default='host',
metavar='IP', nargs='?'),
options={})
RSSI = dict(help="prints device's RSSI (WiFi or BLE)",
subcmd={},
options={})
NET = dict(help="manage network station interface (STA._IF)",
desc="enable/disable station inteface, config and connect to or scan APs",
subcmd=dict(help='{status, on, off, config, scan}; default: status',
default='status',
metavar='command',
choices=['status', 'on', 'off', 'config', 'scan'],
nargs='?'),
options={"-wp": dict(help='ssid, password for config command',
required=False,
nargs=2)})
IFCONFIG = dict(help="prints network interface configuration (STA._IF)",
subcmd={},
options={"-t": dict(help='print info in table format',
required=False,
default=False,
action='store_true')})
AP = dict(help="manage network acces point interface (AP._IF)",
desc="enable/disable ap inteface, config an AP or scan connected clients",
subcmd=dict(help='{status, on, off, scan, config}; default: status',
default='status',
metavar='command',
choices=['status', 'on', 'off', 'config', 'scan'],
nargs='?'),
options={"-ap": dict(help='ssid, password for config command',
required=False,
nargs=2),
"-t": dict(help='print info in table format',
required=False,
default=False,
action='store_true')})
I2C = dict(help="manage I2C interface",
subcmd=dict(help='{config, scan}; default: config',
default='config',
metavar='action',
choices=['config', 'scan'],
nargs='?'),
options={"-i2c": dict(help='[scl] [sda] for config command',
required=False,
default=[22, 23],
nargs=2)})
SET = dict(help="set device's configuration {rtc, hostname, localname}",
subcmd=dict(help=('set parameter configuration {rtc localtime, rtc ntptime,'
' hostname, localname}; default: rtc localtime'),
default=['rtc'],
metavar='parameter', nargs='+'),
options={"-utc": dict(help='[utc] for "set ntptime" '
'command', required=False, nargs=1, type=int)},
alt_ops=['rtc', 'localtime', 'ntptime', 'hostname', 'localname'])
DATETIME = dict(help="prints device's RTC time",
subcmd={},
options={})
UPTIME = dict(help=("prints device's uptime since latest boot, "
"(requires uptime.py and uptime.settime()"
" at boot.py/main.py)"),
subcmd={},
options={})
CYCLES = dict(help=("prints device's cycle count"
"(requires cycles.py and cycles.set()"
" at boot.py/main.py)"),
subcmd={},
options={})
SHASUM = dict(help="shasum SHA-256 tool",
subcmd=dict(help='Get the hash of a file or check a shasum file',
default=[],
metavar='file/pattern',
nargs='*'),
options={"-c": dict(help='check a shasum file',
required=False,
default='')})
TOUCH = dict(help="create a new file",
subcmd=dict(help='indicate a new file/pattern to create',
default=[],
metavar='file/pattern',
nargs='*'),
options={})
UPIP = dict(help="install or manage MicroPython libs",
subcmd=dict(help='indicate a lib/module to {install, info, find}',
default=[],
metavar='file/pattern',
nargs='*'),
options={},
alt_ops=['install', 'info', 'find'])
TIMEIT = dict(help="measure execution time of a script/function",
subcmd=dict(help='indicate a script/function to measure',
default=[],
metavar='script/function',
nargs='*'),
options={})
UPDATE_UPYUTILS = dict(help="update upyutils scripts",
subcmd=dict(help=("filter to match one/multiple "
"upyutils; default: all"),
default=['*'],
nargs='*',
metavar='name/pattern'),
options={},
alt_ops=os.listdir(os.path.join(UPYDEV_PATH,
'upyutils_dir')))
ENABLE_SHELL = dict(help="upload required files so shell is fully operational",
subcmd={},
options={})
DOCS = dict(help="see upydev docs at https://upydev.readthedocs.io/en/latest/",
subcmd=dict(help='indicate a keyword to search',
metavar='keyword', nargs='?'),
options={})
MDOCS = dict(help="see MicroPython docs at docs.micropython.org",
subcmd=dict(help='indicate a keyword to search',
metavar='keyword', nargs='?'),
options={})
CTIME = dict(help="measure execution time of a shell command",
subcmd=dict(help='indicate a command to measure',
default='info',
choices=shell_commands+custom_sh_cmd_kw,
metavar='command'),
options={})
CONFIG = dict(help="set or check config (from *_config.py files)#",
desc="* needs config module\n* to set config --> [config]: "
"[parameter]=[value]",
subcmd=dict(help='indicate parameter to set or check ',
default=[],
metavar='parameter',
nargs='*'),
options={"-y": dict(help='print config in YAML format',
required=False,
default=False,
action='store_true')})
SD = dict(help="commands to manage an sd",
desc='enable an sd module, mount/unmount an sd or auto mount/unmount sd\n\n'
'* auto command needs SD_AM.py in device',
subcmd=dict(help='actions to mount/unmount sd : {enable, init, deinit, auto}',
default='enable',
choices=['enable', 'init', 'deinit', 'auto'],
metavar='command'),
options={"-po": dict(help='pin of LDO 3.3V regulator to enable',
default=15,
type=int),
"-sck": dict(help='sck pin for sd SPI',
default=5,
type=int),
"-mosi": dict(help='mosi pin for sd SPI',
default=18,
type=int),
"-miso": dict(help='miso pin for sd SPI',
default=19,
type=int),
"-cs": dict(help='cs pin for sd SPI',
default=21,
type=int)})
LOAD = dict(help="run local script in device",
desc="load a local script in device buffer and execute it.",
subcmd=dict(help='indicate a file/script to load', default='',
metavar='file',
nargs='*'),
options={})
SHELL_CMD_DICT_PARSER = {"ls": LS, "head": HEAD, "cat": CAT, "mkdir": MKDIR,
"touch": TOUCH, "cd": CD, "mv": MV, "pwd": PWD,
"rm": RM, "rmdir": RMDIR, "du": DU,
"tree": TREE, "df": DF, "mem": MEM, "exit": EXIT,
"vim": VIM, "run": RUN, "reload": RELOAD,
"info": INFO, "id": ID, "uhelp": UHELP, "modules": MODULES,
"uping": UPING, "rssi": RSSI, "net": NET, "ifconfig": IFCONFIG,
"ap": AP, "i2c": I2C, "set": SET, "datetime": DATETIME,
"shasum": SHASUM, "upip": UPIP, "timeit": TIMEIT,
"update_upyutils": UPDATE_UPYUTILS,
"lcd": LCD,
"lsl": LSL, "lpwd": LPWD, "ldu": LDU, "docs": DOCS,
"mdocs": MDOCS, "ctime": CTIME, "enable_sh": ENABLE_SHELL,
"diff": DIFF, "config": CONFIG, "sd": SD, 'uptime': UPTIME,
"cycles": CYCLES, "load": LOAD}
# DEBUGGING
PING = dict(help="ping the device to test if device is"
" reachable, CTRL-C to stop.",
desc="this sends ICMP ECHO_REQUEST packets to device",
subcmd={},
options={"-t": dict(help="device target address",
required=True),
"-p": dict(help='device password or baudrate',
required=True),
"-zt": dict(help='internal flag for zerotierone device',
required=False,
default=False,
action='store_true')})
PROBE = dict(help="to test if a device is reachable",
desc="ping, scan serial ports or ble scan depending on device type",
subcmd={},
options={"-t": dict(help="device target address",
required=True),
"-p": dict(help='device password or baudrate',
required=True),
"-zt": dict(help='internal flag for zerotierone device',
required=False,
default=False,
action='store_true'),
"-G": dict(help='internal flag for group mode',
required=False,
default=None),
"-gg": dict(help='flag for global group',
required=False,
default=False,
action='store_true'),
"-devs": dict(help='flag for filtering devs in global group',
required=False,
nargs='*')})
SCAN = dict(help="to scan for available devices, use a flag to filter for device type",
desc="\ndefault: if no flag provided will do all three scans.",
subcmd={},
options={"-sr": dict(help="scan for SerialDevice",
required=False,
default=False,
action='store_true'),
"-nt": dict(help='scan for WebSocketDevice',
required=False,
default=False,
action='store_true'),
"-bl": dict(help='scan for BleDevice',
required=False,
default=False,
action='store_true')})
RUN = dict(help="run a script in device, CTRL-C to stop",
desc="this calls 'import [script]' in device and reloads it at the end",
subcmd=dict(help=('indicate a script to run'),
metavar='script'),
options={"-t": dict(help="device target address",
required=True),
"-p": dict(help='device password or baudrate',
required=True),
"-wss": dict(help='use WebSocket Secure',
required=False,
default=False,
action='store_true'),
"-s": dict(help='indicate the path of the script if in external fs'
' e.g. an sd card.',
required=False)})
PLAY = dict(help="play custom tasks in ansible playbook style",
desc="task must be yaml file with name, hosts, tasks, name, command\n"
"structure",
subcmd=dict(help=('indicate a task file to play.'),
metavar='task',
choices=["add", "rm", "list"]),
options={"-t": dict(help="device target address",
required=True),
"-p": dict(help='device password or baudrate',
required=True),
"-wss": dict(help='use WebSocket Secure',
required=False,
default=False,
action='store_true')})
TIMEIT = dict(help="to measure execution time of a module/script",
desc="source: https://github.com/peterhinch/micropython-samples"
"/tree/master/timed_function",
subcmd=dict(help=('indicate a script to run'),
metavar='script'),
options={"-t": dict(help="device target address",
required=True),
"-p": dict(help='device password or baudrate',
required=True),
"-wss": dict(help='use WebSocket Secure',
required=False,
default=False,
action='store_true'),
"-s": dict(help='indicate the path of the script if in external'
' fs e.g. an sd card.',
required=False)})
STREAM_TEST = dict(help="to test download speed (from device to host)",
desc="default: 10 MB of random bytes are sent in chunks of 20 kB "
"and received in chunks of 32 kB.\n\n*(sync_tool.py required)",
subcmd={},
options={"-t": dict(help="device target address",
required=True),
"-p": dict(help='device password or baudrate',
required=True),
"-wss": dict(help='use WebSocket Secure',
required=False,
default=False,
action='store_true'),
"-chunk_tx": dict(help='chunk size of data packets in kB to'
' send',
required=False, default=20, type=int),
"-chunk_rx": dict(help='chunk size of data packets in kB to'
' receive',
required=False, default=32, type=int),
"-total_size": dict(help='total size of data packets in MB',
required=False, default=10, type=int)})
SYSCTL = dict(help="to start/stop a script without following the output",
desc="to follow initiate repl",
mode=dict(help='indicate a mode {start,stop}',
metavar='mode',
choices=['start', 'stop']),
subcmd=dict(help='indicate a script to start/stop',
metavar='script'),
options={"-t": dict(help="device target address",
required=True),
"-p": dict(help='device password or baudrate',
required=True),
"-wss": dict(help='use WebSocket Secure',
required=False,
default=False,
action='store_true')})
LOG = dict(help="to log the output of a script running in device",
desc="log levels (sys.stdout and file), run modes (normal, daemon) are"
"available through following options",
subcmd=dict(help=('indicate a script to run and log'),
metavar='script'),
options={"-t": dict(help="device target address",
required=True),
"-p": dict(help='device password or baudrate',
required=True),
"-wss": dict(help='use WebSocket Secure',
required=False,
default=False,
action='store_true'),
"-s": dict(help='indicate the path of the script if in external fs'
' e.g. an sd card.',
required=False),
"-dflev": dict(help='debug file mode level; default: error',
default='error',
choices=['debug', 'info', 'warning', 'error',
'critical']),
"-dslev": dict(help='debug sys.stdout mode level; default: debug',
default='debug',
choices=['debug', 'info', 'warning', 'error',
'critical']),
"-daemon": dict(help='enable "daemon mode", uses nohup so this '
'means running in background, output if any is'
' redirected to [SCRIPT_NAME]_daemon.log',
default=False, action='store_true'),
"-stopd": dict(help='To stop a log daemon script',
default=False, action='store_true'),
"-F": dict(help='To follow a daemon log script file',
action='store_true',
default=False)})
PYTEST = dict(help="run tests on device with pytest (use pytest setup first)",
subcmd=dict(help='indicate a test script to run, any optional '
'arg is passed to pytest',
default=[''],
metavar='test',
nargs='*'),
options={"-t": dict(help="device target address",
required=True),
"-p": dict(help='device password or baudrate',
required=True),
"-wss": dict(help='use WebSocket Secure',
required=False,
default=False,
action='store_true')})
DB_CMD_DICT_PARSER = {"ping": PING, "probe": PROBE, "scan": SCAN, "run": RUN,
"timeit": TIMEIT, "stream_test": STREAM_TEST, "sysctl": SYSCTL,
"log": LOG, "pytest": PYTEST, "play": PLAY}
# DEVICE MANAGEMENT
CONFIG = dict(help="to save device settings",
desc="this will allow set default device configuration or \n"
"target a specific device in a group.\n"
"\ndefault: a configuration file 'upydev_.config' is saved in\n"
"current working directory, use -[options] for custom configuration",
subcmd={},
options={"-t": dict(help="device target address"),
"-p": dict(help='device password or baudrate'),
"-g": dict(help='save configuration in global path',
required=False,
default=False,
action='store_true'),
"-gg": dict(help='save device configuration in global group',
required=False,
default=False,
action='store_true'),
"-@": dict(help='specify a device name',
required=False),
"-zt": dict(help='zerotierone device configuration',
required=False),
"-sec": dict(help='introduce password with no echo',
required=False,
default=False,
action='store_true')})
CHECK = dict(help='to check device information',
desc='shows current device information or specific device\n'
'indicated with -@ option if it is stored in the global group.',
subcmd={},
options={"-@": dict(help='specify device/s name',
required=False,
nargs='+'),
"-i": dict(help='if device is online/connected gets device info',
required=False,
default=False,
action='store_true'),
"-g": dict(help='looks for configuration in global path',
required=False,
default=False,
action='store_true'),
"-wss": dict(help='use WebSocket Secure',
required=False,
default=False,
action='store_true'),
"-G": dict(help='specify a group, default: global group',
required=False)})
SET = dict(help='to set current device configuration',
subcmd={},
options={"-@": dict(help='specify device name',
required=False),
"-g": dict(help='looks for configuration in global path',
required=False,
default=False,
action='store_true'),
"-G": dict(help='specify a group, default: global group',
required=False)})
REGISTER = dict(help='to register a device/group as a shell function so it is callable',
subcmd=dict(help='alias for device/s or group',
metavar='alias',
nargs='*'),
options={"-@": dict(help='specify device name',
required=False,
nargs='+'),
"-gg": dict(help='register a group of devices',
required=False,
default=False,
action='store_true'),
"-s": dict(help='specify a source file, default: ~/.profile',
required=False),
"-g": dict(help='looks for configuration in global path',
required=False,
default=False,
action='store_true')})
LSDEVS = dict(help='to see registered devices or groups',
desc='this also defines a shell function with the same name in the source'
' file',
subcmd={},
options={"-s": dict(help='specify a source file, default: ~/.profile',
required=False),
"-G": dict(help='specify a group, default: global group',
required=False)})
MKG = dict(help='make a group of devices',
desc='this save a config file with devices settings so they can be targeted'
' all together',
subcmd=dict(help='group name',
metavar='group'),
options={"-g": dict(help='save configuration in global path',
required=False,
default=False,
action='store_true'),
"-devs": dict(help='device configuration [name] [target] '
'[password]',
required=False,
nargs='+')})
GG = dict(help='to see global group of devices',
subcmd={},
options={"-g": dict(help='looks for configuration in global path',
required=False,
default=False,
action='store_true')})
SEE = dict(help='to see a group of devices',
subcmd=dict(help='indicate a group name',
metavar='group'),
options={"-g": dict(help='looks for configuration in global path',
required=False,
default=False,
action='store_true')})
MGG = dict(help='manage a group of devices',
desc='add/remove one or more devices to/from a group',
subcmd=dict(help='group name',
metavar='group',
default='UPY_G',
nargs='?'),
options={"-g": dict(help='looks for configuration in global path',
required=False,
default=False,
action='store_true'),
"-add": dict(help='add device/s name',
required=False,
nargs='*'),
"-rm": dict(help='remove device/s name',
required=False,
nargs='*'),
"-gg": dict(help='manage global group',
required=False,
default=False,
action='store_true')})
MKSG = dict(help='manage a subgroup of devices',
desc='make group from another group with a subset of devices',
subcmd=dict(help='group name',
metavar='group',
default='UPY_G',
nargs='?'),
sgroup=dict(help='subgroup name',
metavar='subgroup'),
options={"-g": dict(help='looks for configuration in global path',
required=False,
default=False,
action='store_true'),
"-devs": dict(help='add device/s name',
required=True,
nargs='*'),
"-gg": dict(help='manage global group',
required=False,
default=False,
action='store_true')})
DM_CMD_DICT_PARSER = {"config": CONFIG, "check": CHECK,
"register": REGISTER, "lsdevs": LSDEVS, "mkg": MKG, "gg": GG,
"see": SEE, "mgg": MGG, "mksg": MKSG}
# FW
MPYX = dict(help="freeze .py files using mpy-cross. (must be available in $PATH)",
subcmd=dict(help='indicate a file/pattern to '
'compile',
default=[],
metavar='file/pattern',
nargs='+'),
options={})
FW = dict(help="list or get available firmware from micropython.org",
subcmd=dict(help=('{list, get, update}'
'; default: list'),
default=['list'],
metavar='action', nargs='*'),
options={"-b": dict(help='to indicate device platform',
required=False),
"-n": dict(help='to indicate keyword for filter search',
required=False),
"-t": dict(help="device target address",
required=True),
"-p": dict(help='device password or baudrate',
required=True),
"-wss": dict(help='use WebSocket Secure',
required=False,
default=False,
action='store_true')},
alt_ops=['list', 'get', 'update', 'latest'])
FLASH = dict(help="to flash a firmware file using available serial tools "
"(esptool.py, pydfu.py)",
subcmd=dict(help=('indicate a firmware file to flash'),
metavar='firmware file'),
options={"-i": dict(help='to check wether device platform and '
'firmware file name match',
required=False,
action='store_true'),
"-t": dict(help="device target address",
required=True),
"-p": dict(help='device baudrate',
required=True),
})
OTA = dict(help="to flash a firmware file using OTA system (ota.py, otable.py)",
subcmd=dict(help=('indicate a firmware file to flash'),
metavar='firmware file'),
options={"-i": dict(help='to check wether device platform and '
'firmware file name match',
required=False,
action='store_true'),
"-sec": dict(help='to enable OTA TLS',
required=False,
default=False,
action='store_true'),
"-t": dict(help="device target address",
required=True),
"-p": dict(help='device password',
required=True),
"-wss": dict(help='use WebSocket Secure',
required=False,
default=False,
action='store_true'),
"-zt": dict(help='zerotierone host IP',
required=False,
default=False)})
FW_CMD_DICT_PARSER = {"mpyx": MPYX, "fwr": FW, "flash": FLASH, "ota": OTA}
# GC
RESET = dict(help="reset device",
subcmd={},
options={"-hr": dict(help='to do hard reset',
required=False,
default=False,
action='store_true')})
CONFIG = dict(help="set or check config (from *_config.py files)#",
desc="to set config --> [config]: [parameter]=[value]",
subcmd=dict(help='indicate parameter to set or check ',
default=[],
metavar='parameter',
nargs='*'),
options={"-y": dict(help='print config in YAML format',
required=False,
default=False,
action='store_true')})
KBI = dict(help="to send KeyboardInterrupt to device",
subcmd={},
options={})
UPYSH = dict(help="import upysh",
subcmd={},
options={})
GC_CMD_DICT_PARSER = {"reset": RESET, "uconfig": CONFIG, "kbi": KBI, "upysh": UPYSH}
# KG
KG = dict(help="to generate a key pair (RSA) or key & certificate (ECDSA) for ssl",
desc="generate key pair and exchange with device, or refresh WebREPL "
"password",
mode=dict(help='indicate a key {rsa, ssl, wr}',
metavar='mode',
choices=['rsa', 'ssl', 'wr'],
nargs='?'),
subcmd=dict(help='- gen: generate a ECDSA key/cert (default)'
'\n- rotate: To rotate CA key/cert pair old->new or'
' new->old'
'\n- add: add a device cert to upydev path verify location.'
'\n- export: export CA or device cert to cwd.',
metavar='subcmd',
# just for arg completion
choices=['gen', 'add', 'export', 'rotate', 'dev', 'host', 'CA',
'status'],
default='gen',
nargs='?'),
dst=dict(help='indicate a subject: {dev, host, CA}, default: dev',
metavar='dest',
choices=['dev', 'host', 'CA'],
default='dev',
nargs='?'),
options={"-t": dict(help="device target address",
required=True),
"-p": dict(help='device password or baudrate',
required=True),
"-wss": dict(help='use WebSocket Secure',
required=False,
default=False,
action='store_true'),
"-zt": dict(help='internal flag for zerotierone device',
required=False,
default=False,
action='store_true'),
"-rst": dict(help='internal flag for reset',
required=False,
default=False,
action='store_true'),
"-key_size": dict(help="RSA key size, default:2048",
default=2048,
required=False,
type=int),
"-show_key": dict(help='show generated RSA key',
required=False,
default=False,
action='store_true'),
"-tfkey": dict(help='transfer keys to device',
required=False,
default=False,
action='store_true'),
"-rkey": dict(help='option to remove private device key from host',
required=False,
default=False,
action='store_true'),
"-g": dict(help='option to store new WebREPL password globally',
required=False,
default=False,
action='store_true'),
"-to": dict(help='serial device name to upload to',
required=False),
"-f": dict(help='cert name to add to verify locations',
required=False),
"-a": dict(
help="show all devs ssl cert status",
required=False,
default=False,
action="store_true",
), })
RSA = dict(help="to perform operations with RSA key pair as sign, verify or "
"authenticate",
desc="sign files, verify signatures or authenticate devices with "
"RSA challenge\nusing device keys or host keys",
mode=dict(help='indicate an action {sign, verify, auth}',
metavar='mode',
choices=['sign', 'verify', 'auth']),
subcmd=dict(help='indicate a file to sign/verify',
metavar='file/signature',
nargs='?'),
options={"-t": dict(help="device target address",
required=True),
"-p": dict(help='device password or baudrate',
required=True),
"-wss": dict(help='use WebSocket Secure',
required=False,
default=False,
action='store_true'),
"-host": dict(help='to use host keys',
required=False,
default=False,
action='store_true'),
"-rst": dict(help='internal flag for reset',
required=False,
default=False,
action='store_true')})
KG_CMD_DICT_PARSER = {"kg": KG, "rsa": RSA}
# SHELL-REPL
SHELLREPLS = dict(help="enter shell-repl",
subcmd={},
options={"-t": dict(help="device target address",
required=True),
"-p": dict(help='device password or baudrate',
required=True),
"-wss": dict(help='use WebSocket Secure',
required=False,
default=False,
action='store_true'),
"-rkey": dict(help='generate new password after exit '
'(WebSocketDevices)',
required=False,
action='store_true'),
"-nem": dict(help='force no encryption mode'
' (WebSocketDevices)',
required=False,
action='store_true')})
SHELL_CONFIG = dict(help="configure shell prompt colors",
desc='see\nhttps://python-prompt-toolkit.readthedocs.io/en/master/'
'pages/asking_for_input.html#colors\nfor color options',
subcmd={},
options={"--userpath": dict(help='user path color; default:'
' ansimagenta bold',
required=False,
default='ansimagenta bold'),
"--username": dict(help='user name color; default:'
' ansigreen bold',
required=False,
default='ansigreen bold'),
"--at": dict(help='@ color; default: ansigreen bold',
required=False,
default='ansigreen bold'),
"--colon": dict(help='colon color; default: white',
required=False,
default='#ffffff'),
"--pound": dict(help='pound color; default: ansiblue bold',
required=False,
default='ansiblue bold'),
"--host": dict(help='host color; default: ansigreen bold',
required=False,
default='ansigreen bold'),
"--path": dict(help='path color; default: ansiblue bold',
required=False,
default='ansiblue bold')})
SET_WSS = dict(help="toggle between WebSecREPL and WebREPL",
subcmd={},
options={"-t": dict(help="device target address",
required=True),
"-p": dict(help='device password',
required=True),
"-wss": dict(help='use WebSocket Secure',
required=False,
default=False,
action='store_true'),
})
JUPYTER = dict(help="MicroPython upydevice kernel for jupyter console, CTRL-D to exit",
subcmd={},
options={})
SHELLREPL_CMD_DICT_PARSER = {"shl": SHELLREPLS, "shl-config": SHELL_CONFIG,
"set_wss": SET_WSS,
"jupyterc": JUPYTER}
# REPL
REPLS = dict(help="enter REPL",
subcmd={},
options={"-t": dict(help="device target address",
required=True),
"-p": dict(help='device password or baudrate',
required=True),
"-wss": dict(help='use WebSocket Secure',
required=False,
default=False,
action='store_true'),
"-rkey": dict(help='generate new password after exit '
'(WebSocketDevices)',
required=False,
action='store_true')})
REPL_CMD_DICT_PARSER = {"rpl": REPLS}
# FIO
PUT = dict(help="upload files to device",
subcmd=dict(help='indicate a file/pattern/dir to '
'upload',
default=[],
metavar='file/pattern/dir',
nargs='+'),
options={"-dir": dict(help='path to upload to',
required=False,
default=''),
"-rst": dict(help='to soft reset after upload',
required=False,
default=False,
action='store_true')})
GET = dict(help="download files from device",
subcmd=dict(help='indicate a file/pattern/dir to '
'download',
default=[],
metavar='file/pattern/dir',
nargs='+'),
options={"-dir": dict(help='path to download from',
required=False,
default=''),
"-d": dict(help='depth level search for pattrn', required=False,
default=0,
type=int),
"-fg": dict(help='switch off faster get method',
required=False,
default=True,
action='store_false'),
"-b": dict(help='read buffer for faster get method', required=False,
default=512,
type=int)})
DSYNC = dict(help="recursively sync a folder from/to device's filesystem",
desc="* needs shasum.py in device",
subcmd=dict(help='indicate a dir/pattern to '
'sync',
default=['.'],
metavar='dir/pattern',
nargs='*'),
options={"-rf": dict(help='remove recursive force a dir or file deleted'
' in local/device directory',
required=False,
default=False,
action='store_true'),
"-d": dict(help='sync from device to host', required=False,
default=False,
action='store_true'),
"-fg": dict(help='switch off faster get method',
required=False,
default=True,
action='store_false'),
"-b": dict(help='read buffer for faster get method',
required=False,
default=512,
type=int),
"-t": dict(help='show tree of directory to sync', required=False,
default=False,
action='store_true'),
"-f": dict(help='force sync, no hash check', required=False,
default=False,
action='store_true'),
"-p": dict(help='show diff', required=False,
default=False,
action='store_true'),
"-n": dict(help='dry-run and save stash', required=False,
default=False,
action='store_true'),
"-i": dict(help='ignore file/dir or pattern', required=False,
default=[],
nargs='*')})
UPDATE_UPYUTILS = dict(help="update upyutils scripts",
subcmd=dict(help=("filter to match one/multiple "
"upyutils; default: all"),
default=['*'],
nargs='*',
metavar='name/pattern'),
options={},
alt_ops=os.listdir(os.path.join(UPYDEV_PATH,
'upyutils_dir')))
INSTALL = dict(help="install libraries or modules with upip to ./lib",
subcmd=dict(help='indicate a lib/module to install',
metavar='module'),
options={})
FIO_CMD_DICT_PARSER = {"put": PUT, "get": GET, "dsync": DSYNC,
"update_upyutils": UPDATE_UPYUTILS, "install": INSTALL}
ALL_PARSER = {}
ALL_PARSER.update(SHELL_CMD_DICT_PARSER)
ALL_PARSER.update(DB_CMD_DICT_PARSER)
ALL_PARSER.update(DM_CMD_DICT_PARSER)
ALL_PARSER.update(FW_CMD_DICT_PARSER)
ALL_PARSER.update(GC_CMD_DICT_PARSER)
ALL_PARSER.update(KG_CMD_DICT_PARSER)
ALL_PARSER.update(SHELLREPL_CMD_DICT_PARSER)
ALL_PARSER.update(REPL_CMD_DICT_PARSER)
ALL_PARSER.update(FIO_CMD_DICT_PARSER)
def argopts_complete(option):
if option in ALL_PARSER.keys():
opt_args = []
if ALL_PARSER[option]['subcmd']:
choices = ALL_PARSER[option]['subcmd'].get('choices')
if choices:
opt_args += choices
if 'mode' in ALL_PARSER[option].keys():
choices = ALL_PARSER[option]['mode'].get('choices')
if choices:
opt_args += choices
alt_ops = ALL_PARSER[option].get('alt_ops')
if alt_ops:
opt_args += alt_ops
kw_args = ALL_PARSER[option].get('options')
if kw_args:
opt_args += list(kw_args.keys())
return opt_args
else:
return []
def get_opts_dict(option):
kw_args = ALL_PARSER[option].get('options')
if kw_args:
return kw_args
else:
return {}
| [
"[email protected]"
] | |
ac2cbb0b731b97e581da7a9f035b4ce7209d5dbf | f08336ac8b6f8040f6b2d85d0619d1a9923c9bdf | /223-rectangleArea.py | b77b9c32e8858d4b5b81adab6076c7a69ecfadeb | [] | no_license | MarshalLeeeeee/myLeetCodes | fafadcc35eef44f431a008c1be42b1188e7dd852 | 80e78b153ad2bdfb52070ba75b166a4237847d75 | refs/heads/master | 2020-04-08T16:07:47.943755 | 2019-02-21T01:43:16 | 2019-02-21T01:43:16 | 159,505,231 | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 975 | py | '''
223.Rectangle Area
Find the total area covered by two rectilinear rectangles in a 2D plane.
Each rectangle is defined by its bottom left corner and top right corner as shown in the figure.
Example:
Input: A = -3, B = 0, C = 3, D = 4, E = 0, F = -1, G = 9, H = 2
Output: 45
Note:
Assume that the total area is never beyond the maximum possible value of int.
'''
class Solution:
def computeArea(self, A, B, C, D, E, F, G, H):
"""
:type A: int
:type B: int
:type C: int
:type D: int
:type E: int
:type F: int
:type G: int
:type H: int
:rtype: int
"""
X = [[A,0],[C,0],[E,1],[G,1]]
Y = [[B,0],[D,0],[F,1],[H,1]]
X.sort(key=lambda k: k[0])
Y.sort(key=lambda k: k[0])
#print(X,Y)
common = (X[2][0]-X[1][0])*(Y[2][0]-Y[1][0]) if X[0][1] ^ X[1][1] and Y[0][1] ^ Y[1][1] else 0
return (C-A)*(D-B) + (G-E)*(H-F) - common
| [
"[email protected]"
] | |
a0e264d5e2ba260f7857655633539fe991807ccb | 99e4d9226e124215aaf66945cfaa5c42d18cc19f | /typings/aiohttp/helpers.pyi | 27b377a309d31a7788ba093977ec22ca796c313b | [
"CC0-1.0",
"LicenseRef-scancode-public-domain"
] | permissive | mathieucaroff/oxowlbot | d826423a1a4cca8a38c90383d0a71dbb40052f35 | a10c12b7c94b3e7030cef2f57c567bbd3034c8c9 | refs/heads/master | 2022-04-18T14:06:29.049957 | 2020-04-22T14:44:57 | 2020-04-22T14:44:57 | 255,177,595 | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 8,994 | pyi | """
This type stub file was generated by pyright.
"""
import asyncio
import datetime
import functools
import netrc
import os
import re
import sys
import async_timeout
import attr
from collections import namedtuple
from types import TracebackType
from typing import Any, Callable, Dict, Iterable, Iterator, Mapping, Optional, Pattern, Set, Tuple, Type, TypeVar, Union
from yarl import URL
"""Various helper functions"""
__all__ = ('BasicAuth', 'ChainMapProxy')
PY_36 = sys.version_info >= (3, 6)
PY_37 = sys.version_info >= (3, 7)
PY_38 = sys.version_info >= (3, 8)
if not PY_37:
...
def all_tasks(loop: Optional[asyncio.AbstractEventLoop] = ...) -> Set[asyncio.Task[Any]]:
...
if PY_37:
all_tasks = getattr(asyncio, 'all_tasks')
_T = TypeVar('_T')
sentinel = object()
NO_EXTENSIONS = bool(os.environ.get('AIOHTTP_NO_EXTENSIONS'))
DEBUG = getattr(sys.flags, 'dev_mode', False) or not sys.flags.ignore_environment and bool(os.environ.get('PYTHONASYNCIODEBUG'))
CHAR = set(chr(i) for i in range(0, 128))
CTL = set(chr(i) for i in range(0, 32)) | chr(127)
SEPARATORS = '(', ')', '<', '>', '@', ',', ';', ':', '\\', '"', '/', '[', ']', '?', '=', '{', '}', ' ', chr(9)
TOKEN = CHAR ^ CTL ^ SEPARATORS
coroutines = asyncio.coroutines
old_debug = coroutines._DEBUG
@asyncio.coroutine
def noop(*args, **kwargs):
...
async def noop2(*args: Any, **kwargs: Any) -> None:
...
class BasicAuth(namedtuple('BasicAuth', ['login', 'password', 'encoding'])):
"""Http basic authentication helper."""
def __new__(cls, login: str, password: str = ..., encoding: str = ...) -> BasicAuth:
...
@classmethod
def decode(cls, auth_header: str, encoding: str = ...) -> BasicAuth:
"""Create a BasicAuth object from an Authorization HTTP header."""
...
@classmethod
def from_url(cls, url: URL, *, encoding: str = ...) -> Optional[BasicAuth]:
"""Create BasicAuth from url."""
...
def encode(self) -> str:
"""Encode credentials."""
...
def strip_auth_from_url(url: URL) -> Tuple[URL, Optional[BasicAuth]]:
...
def netrc_from_env() -> Optional[netrc.netrc]:
"""Attempt to load the netrc file from the path specified by the env-var
NETRC or in the default location in the user's home directory.
Returns None if it couldn't be found or fails to parse.
"""
...
@attr.s(frozen=True, slots=True)
class ProxyInfo:
proxy = ...
proxy_auth = ...
def proxies_from_env() -> Dict[str, ProxyInfo]:
...
def current_task(loop: Optional[asyncio.AbstractEventLoop] = ...) -> asyncio.Task:
...
def get_running_loop(loop: Optional[asyncio.AbstractEventLoop] = ...) -> asyncio.AbstractEventLoop:
...
def isasyncgenfunction(obj: Any) -> bool:
...
@attr.s(frozen=True, slots=True)
class MimeType:
type = ...
subtype = ...
suffix = ...
parameters = ...
@functools.lru_cache(maxsize=56)
def parse_mimetype(mimetype: str) -> MimeType:
"""Parses a MIME type into its components.
mimetype is a MIME type string.
Returns a MimeType object.
Example:
>>> parse_mimetype('text/html; charset=utf-8')
MimeType(type='text', subtype='html', suffix='',
parameters={'charset': 'utf-8'})
"""
...
def guess_filename(obj: Any, default: Optional[str] = ...) -> Optional[str]:
...
def content_disposition_header(disptype: str, quote_fields: bool = ..., **params: str) -> str:
"""Sets ``Content-Disposition`` header.
disptype is a disposition type: inline, attachment, form-data.
Should be valid extension token (see RFC 2183)
params is a dict with disposition params.
"""
...
class reify:
"""Use as a class method decorator. It operates almost exactly like
the Python `@property` decorator, but it puts the result of the
method it decorates into the instance dict after the first call,
effectively replacing the function it decorates with an instance
variable. It is, in Python parlance, a data descriptor.
"""
def __init__(self, wrapped: Callable[..., Any]) -> None:
self.wrapped = ...
self.__doc__ = ...
self.name = ...
def __get__(self, inst: Any, owner: Any) -> Any:
...
def __set__(self, inst: Any, value: Any) -> None:
...
reify_py = reify
_ipv4_pattern = r'^(?:(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.){3}' r'(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)$'
_ipv6_pattern = r'^(?:(?:(?:[A-F0-9]{1,4}:){6}|(?=(?:[A-F0-9]{0,4}:){0,6}' r'(?:[0-9]{1,3}\.){3}[0-9]{1,3}$)(([0-9A-F]{1,4}:){0,5}|:)' r'((:[0-9A-F]{1,4}){1,5}:|:)|::(?:[A-F0-9]{1,4}:){5})' r'(?:(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9]?[0-9])\.){3}' r'(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9]?[0-9])|(?:[A-F0-9]{1,4}:){7}' r'[A-F0-9]{1,4}|(?=(?:[A-F0-9]{0,4}:){0,7}[A-F0-9]{0,4}$)' r'(([0-9A-F]{1,4}:){1,7}|:)((:[0-9A-F]{1,4}){1,7}|:)|(?:[A-F0-9]{1,4}:){7}' r':|:(:[A-F0-9]{1,4}){7})$'
_ipv4_regex = re.compile(_ipv4_pattern)
_ipv6_regex = re.compile(_ipv6_pattern, flags=re.IGNORECASE)
_ipv4_regexb = re.compile(_ipv4_pattern.encode('ascii'))
_ipv6_regexb = re.compile(_ipv6_pattern.encode('ascii'), flags=re.IGNORECASE)
def _is_ip_address(regex: Pattern[str], regexb: Pattern[bytes], host: Optional[Union[str, bytes]]) -> bool:
...
is_ipv4_address = functools.partial(_is_ip_address, _ipv4_regex, _ipv4_regexb)
is_ipv6_address = functools.partial(_is_ip_address, _ipv6_regex, _ipv6_regexb)
def is_ip_address(host: Optional[Union[str, bytes, bytearray, memoryview]]) -> bool:
...
def next_whole_second() -> datetime.datetime:
"""Return current time rounded up to the next whole second."""
...
_cached_current_datetime = None
_cached_formatted_datetime = ""
def rfc822_formatted_time() -> str:
...
def _weakref_handle(info):
...
def weakref_handle(ob, name, timeout, loop, ceil_timeout: bool = ...):
...
def call_later(cb, timeout, loop):
...
class TimeoutHandle:
""" Timeout handle """
def __init__(self, loop: asyncio.AbstractEventLoop, timeout: Optional[float]) -> None:
...
def register(self, callback: Callable[..., None], *args: Any, **kwargs: Any) -> None:
...
def close(self) -> None:
...
def start(self) -> Optional[asyncio.Handle]:
...
def timer(self) -> BaseTimerContext:
...
def __call__(self) -> None:
...
class BaseTimerContext(ContextManager['BaseTimerContext']):
...
class TimerNoop(BaseTimerContext):
def __enter__(self) -> BaseTimerContext:
...
def __exit__(self, exc_type: Optional[Type[BaseException]], exc_val: Optional[BaseException], exc_tb: Optional[TracebackType]) -> Optional[bool]:
...
class TimerContext(BaseTimerContext):
""" Low resolution timeout context manager """
def __init__(self, loop: asyncio.AbstractEventLoop) -> None:
...
def __enter__(self) -> BaseTimerContext:
...
def __exit__(self, exc_type: Optional[Type[BaseException]], exc_val: Optional[BaseException], exc_tb: Optional[TracebackType]) -> Optional[bool]:
...
def timeout(self) -> None:
...
class CeilTimeout(async_timeout.timeout):
def __enter__(self) -> async_timeout.timeout:
...
class HeadersMixin:
ATTRS = ...
_content_type = ...
_content_dict = ...
_stored_content_type = ...
def _parse_content_type(self, raw: str) -> None:
...
@property
def content_type(self) -> str:
"""The value of content part for Content-Type HTTP header."""
...
@property
def charset(self) -> Optional[str]:
"""The value of charset part for Content-Type HTTP header."""
...
@property
def content_length(self) -> Optional[int]:
"""The value of Content-Length HTTP header."""
...
def set_result(fut: asyncio.Future[_T], result: _T) -> None:
...
def set_exception(fut: asyncio.Future[_T], exc: BaseException) -> None:
...
class ChainMapProxy(Mapping[str, Any]):
__slots__ = ...
def __init__(self, maps: Iterable[Mapping[str, Any]]) -> None:
...
def __init_subclass__(cls) -> None:
...
def __getitem__(self, key: str) -> Any:
...
def get(self, key: str, default: Any = ...) -> Any:
...
def __len__(self) -> int:
...
def __iter__(self) -> Iterator[str]:
...
def __contains__(self, key: object) -> bool:
...
def __bool__(self) -> bool:
...
def __repr__(self) -> str:
...
| [
"[email protected]"
] | |
5575a34bb47b7f44bc2177357c0b7f8fb5fef18c | 6260fd806b3bf82a601c86c8a903b49c983d9dda | /w3resource/7.py | 03955a8d513c09e32bafc6d84f5fc6e5dfef3e0a | [] | no_license | skybohannon/python | 6162077e4f18d0ed273d47c342620942e531031b | b78ac8ff1758826d9dd9c969096fb1f10783a4be | refs/heads/master | 2021-09-05T07:09:23.844665 | 2018-01-25T02:58:59 | 2018-01-25T02:58:59 | 106,215,285 | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 300 | py | # 7. Write a Python program to accept a filename from the user and print the extension of that. Go to the editor
# Sample filename : abc.java
# Output : java
user_file = input("Please enter a filename: ")
user_ext = user_file.split(".")
print("The file extension is .{}".format(repr(user_ext[-1]))) | [
"[email protected]"
] | |
84f43b493da4922aa43b8e092c662bce4e358e7d | 1ba59e2cf087fc270dd32b24ac1d76e4b309afcc | /config.py | 1b8fab6b06225fad9e290177b7e86c43413ce3c7 | [
"MIT"
] | permissive | yangtong1989/Deep-Residual-Matting | 2d96ce737b2b89859695e6f4f052c8984eba96bb | 24bd5342b862e447fb7f4dec7edebdd73221db18 | refs/heads/master | 2020-08-31T23:48:39.028571 | 2019-10-18T10:12:45 | 2019-10-18T10:12:45 | null | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 1,143 | py | import torch
device = torch.device('cuda' if torch.cuda.is_available() else 'cpu') # sets device for model and PyTorch tensors
im_size = 320
unknown_code = 128
epsilon = 1e-6
epsilon_sqr = epsilon ** 2
num_classes = 256
num_samples = 43100
num_train = 34480
# num_samples - num_train_samples
num_valid = 8620
# Training parameters
num_workers = 1 # for data-loading; right now, only 1 works with h5py
grad_clip = 5. # clip gradients at an absolute value of
print_freq = 100 # print training/validation stats every __ batches
checkpoint = None # path to checkpoint, None if none
##############################################################
# Set your paths here
# path to provided foreground images
fg_path = 'data/fg/'
# path to provided alpha mattes
a_path = 'data/mask/'
# Path to background images (MSCOCO)
bg_path = 'data/bg/'
# Path to folder where you want the composited images to go
out_path = 'data/merged/'
max_size = 1600
fg_path_test = 'data/fg_test/'
a_path_test = 'data/mask_test/'
bg_path_test = 'data/bg_test/'
out_path_test = 'data/merged_test/'
##############################################################
| [
"[email protected]"
] | |
2b05aafb513ea6ad66865aaa00981d7ff30884e1 | 163bbb4e0920dedd5941e3edfb2d8706ba75627d | /Code/CodeRecords/2733/40186/320060.py | 85feba17c1b35b4a3536d8fcea4725c382ec5d13 | [] | 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 | 438 | py | inp=input()
a=input()
if inp=='8 3' and a=='10 7 9 3 4 5 8 17':
print(10)
print(17)
print(9)
elif a=='5 27 1 3 4 2 8 17':
print(5)
print(27)
print(5)
elif a=='105 2 9 3 8 5 7 7':
print(2)
print(8)
print(9)
print(105)
print(7)
elif inp=='101011':
print(18552)
elif inp=='10101101010111110100110100101010110001010010101001':
print(322173207)
else:
print(inp)
print(a)
print(b) | [
"[email protected]"
] | |
8edcd266e14b62bb5053d6369487e7c9726e0dda | 38c10c01007624cd2056884f25e0d6ab85442194 | /chrome/chrome_resources.gyp | 492536ca0787a392f82c67762f4eb395a3eb7c79 | [
"BSD-3-Clause"
] | permissive | zenoalbisser/chromium | 6ecf37b6c030c84f1b26282bc4ef95769c62a9b2 | e71f21b9b4b9b839f5093301974a45545dad2691 | refs/heads/master | 2022-12-25T14:23:18.568575 | 2016-07-14T21:49:52 | 2016-07-23T08:02:51 | 63,980,627 | 0 | 2 | BSD-3-Clause | 2022-12-12T12:43:41 | 2016-07-22T20:14:04 | null | UTF-8 | Python | false | false | 25,319 | gyp | # Copyright (c) 2012 The Chromium Authors. All rights reserved.
# Use of this source code is governed by a BSD-style license that can be
# found in the LICENSE file.
{
'variables': {
'grit_out_dir': '<(SHARED_INTERMEDIATE_DIR)/chrome',
'additional_modules_list_file': '<(SHARED_INTERMEDIATE_DIR)/chrome/browser/internal/additional_modules_list.txt',
},
'targets': [
{
# GN version: //chrome:extra_resources
'target_name': 'chrome_extra_resources',
'type': 'none',
# These resources end up in resources.pak because they are resources
# used by internal pages. Putting them in a separate pak file makes
# it easier for us to reference them internally.
'actions': [
{
# GN version: //chrome/browser/resources:memory_internals_resources
'action_name': 'generate_memory_internals_resources',
'variables': {
'grit_grd_file': 'browser/resources/memory_internals_resources.grd',
},
'includes': [ '../build/grit_action.gypi' ],
},
{
# GN version: //chrome/browser/resources:net_internals_resources
'action_name': 'generate_net_internals_resources',
'variables': {
'grit_grd_file': 'browser/resources/net_internals_resources.grd',
},
'includes': [ '../build/grit_action.gypi' ],
},
{
# GN version: //chrome/browser/resources:invalidations_resources
'action_name': 'generate_invalidations_resources',
'variables': {
'grit_grd_file': 'browser/resources/invalidations_resources.grd',
},
'includes': ['../build/grit_action.gypi' ],
},
{
# GN version: //chrome/browser/resources:password_manager_internals_resources
'action_name': 'generate_password_manager_internals_resources',
'variables': {
'grit_grd_file': 'browser/resources/password_manager_internals_resources.grd',
},
'includes': [ '../build/grit_action.gypi' ],
},
{
# GN version: //chrome/browser/resources:signin_internals_resources
'action_name': 'generate_signin_internals_resources',
'variables': {
'grit_grd_file': 'browser/resources/signin_internals_resources.grd',
},
'includes': ['../build/grit_action.gypi' ],
},
{
# GN version: //chrome/browser/resources:translate_internals_resources
'action_name': 'generate_translate_internals_resources',
'variables': {
'grit_grd_file': 'browser/resources/translate_internals_resources.grd',
},
'includes': [ '../build/grit_action.gypi' ],
},
],
'includes': [ '../build/grit_target.gypi' ],
'conditions': [
['OS != "ios"', {
'dependencies': [
'../components/components_resources.gyp:components_resources',
'../content/browser/devtools/devtools_resources.gyp:devtools_resources',
'../content/browser/tracing/tracing_resources.gyp:tracing_resources',
'browser/devtools/webrtc_device_provider_resources.gyp:webrtc_device_provider_resources',
],
'actions': [
{
# GN version: //chrome/browser/resources:component_extension_resources
'action_name': 'generate_component_extension_resources',
'variables': {
'grit_grd_file': 'browser/resources/component_extension_resources.grd',
},
'includes': [ '../build/grit_action.gypi' ],
},
{
# GN version: //chrome/browser/resources:options_resources
'action_name': 'generate_options_resources',
'variables': {
'grit_grd_file': 'browser/resources/options_resources.grd',
},
'includes': [ '../build/grit_action.gypi' ],
},
{
# GN version: //chrome/browser/resources:settings_resources
'action_name': 'generate_settings_resources',
'variables': {
'grit_grd_file': 'browser/resources/settings/settings_resources.grd',
},
'includes': [ '../build/grit_action.gypi' ],
},
],
'copies': [
{
# GN version: //chrome/browser/resources:extension_resource_demo
'destination': '<(PRODUCT_DIR)/resources/extension/demo',
'files': [
'browser/resources/extension_resource/demo/library.js',
],
},
],
}],
['chromeos==1 and disable_nacl==0 and disable_nacl_untrusted==0', {
'dependencies': [
'browser/resources/chromeos/chromevox/chromevox.gyp:chromevox',
],
}],
['enable_extensions==1', {
'actions': [
{
# GN version: //chrome/browser/resources:quota_internals_resources
'action_name': 'generate_quota_internals_resources',
'variables': {
'grit_grd_file': 'browser/resources/quota_internals_resources.grd',
},
'includes': [ '../build/grit_action.gypi' ],
},
{
# GN version: //chrome/browser/resources:sync_file_system_internals_resources
'action_name': 'generate_sync_file_system_internals_resources',
'variables': {
'grit_grd_file': 'browser/resources/sync_file_system_internals_resources.grd',
},
'includes': [ '../build/grit_action.gypi' ],
},
],
}],
],
},
{
# GN version: //chrome/browser:chrome_internal_resources_gen
'target_name': 'chrome_internal_resources_gen',
'type': 'none',
'conditions': [
['branding=="Chrome"', {
'actions': [
{
'action_name': 'generate_transform_additional_modules_list',
'variables': {
'additional_modules_input_path':
'browser/internal/resources/additional_modules_list.input',
'additional_modules_py_path':
'browser/internal/transform_additional_modules_list.py',
},
'inputs': [
'<(additional_modules_input_path)',
],
'outputs': [
'<(additional_modules_list_file)',
],
'action': [
'python',
'<(additional_modules_py_path)',
'<(additional_modules_input_path)',
'<@(_outputs)',
],
'message': 'Transforming additional modules list',
}
],
}],
],
},
{
# TODO(mark): It would be better if each static library that needed
# to run grit would list its own .grd files, but unfortunately some
# of the static libraries currently have circular dependencies among
# generated headers.
#
# GN version: //chrome:resources
'target_name': 'chrome_resources',
'type': 'none',
'dependencies': [
'chrome_internal_resources_gen',
'chrome_web_ui_mojo_bindings.gyp:web_ui_mojo_bindings',
],
'actions': [
{
# GN version: //chrome/browser:resources
'action_name': 'generate_browser_resources',
'variables': {
'grit_grd_file': 'browser/browser_resources.grd',
'grit_additional_defines': [
'-E', 'additional_modules_list_file=<(additional_modules_list_file)',
'-E', 'root_gen_dir=<(SHARED_INTERMEDIATE_DIR)',
],
},
'includes': [ '../build/grit_action.gypi' ],
},
{
# GN version: //chrome/common:resources
'action_name': 'generate_common_resources',
'variables': {
'grit_grd_file': 'common/common_resources.grd',
},
'includes': [ '../build/grit_action.gypi' ],
},
{
# GN version: //chrome/renderer:resources
'action_name': 'generate_renderer_resources',
'variables': {
'grit_grd_file': 'renderer/resources/renderer_resources.grd',
},
'includes': [ '../build/grit_action.gypi' ],
},
],
'conditions': [
['enable_extensions==1', {
'actions': [
{
# GN version: //chrome/common:extensions_api_resources
'action_name': 'generate_extensions_api_resources',
'variables': {
'grit_grd_file': 'common/extensions_api_resources.grd',
},
'includes': [ '../build/grit_action.gypi' ],
}
],
}],
],
'includes': [ '../build/grit_target.gypi' ],
},
{
# TODO(mark): It would be better if each static library that needed
# to run grit would list its own .grd files, but unfortunately some
# of the static libraries currently have circular dependencies among
# generated headers.
#
# GN version: //chrome:strings
'target_name': 'chrome_strings',
'type': 'none',
'actions': [
{
# GN version: //chrome/app/resources:locale_settings
'action_name': 'generate_locale_settings',
'variables': {
'grit_grd_file': 'app/resources/locale_settings.grd',
},
'includes': [ '../build/grit_action.gypi' ],
},
{
# GN version: //chrome/app:chromium_strings
'action_name': 'generate_chromium_strings',
'variables': {
'grit_grd_file': 'app/chromium_strings.grd',
},
'includes': [ '../build/grit_action.gypi' ],
},
{
# GN version: //chrome/app:generated_resources
'action_name': 'generate_generated_resources',
'variables': {
'grit_grd_file': 'app/generated_resources.grd',
},
'includes': [ '../build/grit_action.gypi' ],
},
{
# GN version: //chrome/app:google_chrome_strings
'action_name': 'generate_google_chrome_strings',
'variables': {
'grit_grd_file': 'app/google_chrome_strings.grd',
},
'includes': [ '../build/grit_action.gypi' ],
},
{
# GN version: //chrome/app:settings_strings
'action_name': 'generate_settings_strings',
'variables': {
'grit_grd_file': 'app/settings_strings.grd',
},
'includes': [ '../build/grit_action.gypi' ],
},
{
# GN version: //chrome/app:settings_chromium_strings
'action_name': 'generate_settings_chromium_strings',
'variables': {
'grit_grd_file': 'app/settings_chromium_strings.grd',
},
'includes': [ '../build/grit_action.gypi' ],
},
{
# GN version: //chrome/app:settings_google_chrome_strings
'action_name': 'generate_settings_google_chrome_strings',
'variables': {
'grit_grd_file': 'app/settings_google_chrome_strings.grd',
},
'includes': [ '../build/grit_action.gypi' ],
},
],
},
{
# GN version: //chrome/browser/metrics/variations:chrome_ui_string_overrider_factory_gen_sources
'target_name': 'make_chrome_ui_string_overrider_factory',
'type': 'none',
'hard_dependency': 1,
'dependencies': [ 'chrome_strings', ],
'actions': [
{
'action_name': 'generate_ui_string_overrider',
'inputs': [
'../components/variations/service/generate_ui_string_overrider.py',
'<(grit_out_dir)/grit/generated_resources.h'
],
'outputs': [
'<(SHARED_INTERMEDIATE_DIR)/chrome/browser/metrics/variations/ui_string_overrider_factory.cc',
'<(SHARED_INTERMEDIATE_DIR)/chrome/browser/metrics/variations/ui_string_overrider_factory.h',
],
'action': [
'python',
'../components/variations/service/generate_ui_string_overrider.py',
'-N', 'chrome_variations',
'-o', '<(SHARED_INTERMEDIATE_DIR)',
'-S', 'chrome/browser/metrics/variations/ui_string_overrider_factory.cc',
'-H', 'chrome/browser/metrics/variations/ui_string_overrider_factory.h',
'<(grit_out_dir)/grit/generated_resources.h',
],
'message': 'Generating generated resources map.',
}
],
},
{
# GN version: //chrome/browser/metrics/variations:chrome_ui_string_overrider_factory
'target_name': 'chrome_ui_string_overrider_factory',
'type': 'static_library',
'dependencies': [
'../components/components.gyp:variations_service',
'make_chrome_ui_string_overrider_factory',
],
'sources': [
'<(SHARED_INTERMEDIATE_DIR)/chrome/browser/metrics/variations/ui_string_overrider_factory.cc',
'<(SHARED_INTERMEDIATE_DIR)/chrome/browser/metrics/variations/ui_string_overrider_factory.h',
],
},
{
# GN version: //chrome/app/resources:platform_locale_settings
'target_name': 'platform_locale_settings',
'type': 'none',
'variables': {
'conditions': [
['OS=="win"', {
'platform_locale_settings_grd':
'app/resources/locale_settings_win.grd',
},],
['OS=="linux"', {
'conditions': [
['chromeos==1', {
'platform_locale_settings_grd':
'app/resources/locale_settings_<(branding_path_component)os.grd',
}, { # chromeos==0
'platform_locale_settings_grd':
'app/resources/locale_settings_linux.grd',
}],
],
},],
['os_posix == 1 and OS != "mac" and OS != "ios" and OS != "linux"', {
'platform_locale_settings_grd':
'app/resources/locale_settings_linux.grd',
},],
['OS == "mac" or OS == "ios"', {
'platform_locale_settings_grd':
'app/resources/locale_settings_mac.grd',
}],
], # conditions
}, # variables
'actions': [
{
'action_name': 'generate_platform_locale_settings',
'variables': {
'grit_grd_file': '<(platform_locale_settings_grd)',
},
'includes': [ '../build/grit_action.gypi' ],
},
],
'includes': [ '../build/grit_target.gypi' ],
},
{
# GN version: //chrome/app/theme:theme_resources
'target_name': 'theme_resources',
'type': 'none',
'dependencies': [
'../ui/resources/ui_resources.gyp:ui_resources',
'chrome_unscaled_resources',
],
'actions': [
{
'action_name': 'generate_theme_resources',
'variables': {
'grit_grd_file': 'app/theme/theme_resources.grd',
},
'includes': [ '../build/grit_action.gypi' ],
},
],
'includes': [ '../build/grit_target.gypi' ],
},
{
# GN version: //chrome:packed_extra_resources
'target_name': 'packed_extra_resources',
'type': 'none',
'dependencies': [
'chrome_extra_resources',
'packed_resources',
],
'actions': [
{
'includes': ['chrome_repack_resources.gypi']
},
],
'conditions': [
['OS != "mac" and OS != "ios"', {
# We'll install the resource files to the product directory. The Mac
# copies the results over as bundle resources in its own special way.
'copies': [
{
'destination': '<(PRODUCT_DIR)',
'files': [
'<(SHARED_INTERMEDIATE_DIR)/repack/resources.pak'
],
},
],
}],
],
},
{
# GN version: //chrome:packed_resources
'target_name': 'packed_resources',
'type': 'none',
'dependencies': [ # Update duplicate logic in repack_locales.py
# MSVS needs the dependencies explictly named, Make is able to
# derive the dependencies from the output files.
'chrome_resources',
'chrome_strings',
'platform_locale_settings',
'theme_resources',
'<(DEPTH)/components/components_strings.gyp:components_strings',
'<(DEPTH)/net/net.gyp:net_resources',
'<(DEPTH)/ui/resources/ui_resources.gyp:ui_resources',
'<(DEPTH)/ui/strings/ui_strings.gyp:ui_strings',
],
'actions': [
{
# GN version: //chrome:repack_locales_pack
'action_name': 'repack_locales_pack',
'variables': {
'pak_locales': '<(locales)',
},
'includes': ['chrome_repack_locales.gypi']
},
{
# GN version: //chrome:repack_pseudo_locales_pack
'action_name': 'repack_pseudo_locales_pack',
'variables': {
'pak_locales': '<(pseudo_locales)',
},
'includes': ['chrome_repack_locales.gypi']
},
{
'includes': ['chrome_repack_chrome_100_percent.gypi']
},
{
'includes': ['chrome_repack_chrome_200_percent.gypi']
},
{
'includes': ['chrome_repack_chrome_material_100_percent.gypi']
},
{
'includes': ['chrome_repack_chrome_material_200_percent.gypi']
},
],
'conditions': [ # GN version: chrome_repack_locales.gni template("_repack_one_locale")
['OS != "ios"', {
'dependencies': [ # Update duplicate logic in repack_locales.py
'<(DEPTH)/content/app/resources/content_resources.gyp:content_resources',
'<(DEPTH)/content/app/strings/content_strings.gyp:content_strings',
'<(DEPTH)/device/bluetooth/bluetooth_strings.gyp:bluetooth_strings',
'<(DEPTH)/third_party/WebKit/public/blink_resources.gyp:blink_resources',
],
}, { # else
'dependencies': [ # Update duplicate logic in repack_locales.py
'<(DEPTH)/ios/chrome/ios_chrome_resources.gyp:ios_strings_gen',
],
'actions': [
{
'includes': ['chrome_repack_chrome_300_percent.gypi']
},
],
}],
['use_ash==1', {
'dependencies': [ # Update duplicate logic in repack_locales.py
'<(DEPTH)/ash/ash_resources.gyp:ash_resources',
'<(DEPTH)/ash/ash_strings.gyp:ash_strings',
],
}],
['toolkit_views==1', {
'dependencies': [
'<(DEPTH)/ui/views/resources/views_resources.gyp:views_resources',
],
}],
['chromeos==1', {
'dependencies': [ # Update duplicate logic in repack_locales.py
'<(DEPTH)/remoting/remoting.gyp:remoting_resources',
'<(DEPTH)/ui/chromeos/ui_chromeos.gyp:ui_chromeos_resources',
'<(DEPTH)/ui/chromeos/ui_chromeos.gyp:ui_chromeos_strings',
],
}],
['enable_autofill_dialog==1 and OS!="android"', {
'dependencies': [ # Update duplicate logic in repack_locales.py
'<(DEPTH)/third_party/libaddressinput/libaddressinput.gyp:libaddressinput_strings',
],
}],
['enable_extensions==1', {
'dependencies': [ # Update duplicate logic in repack_locales.py
'<(DEPTH)/extensions/extensions_strings.gyp:extensions_strings',
],
}],
['enable_app_list==1', {
'dependencies': [
'<(DEPTH)/ui/app_list/resources/app_list_resources.gyp:app_list_resources',
],
}],
['OS != "mac" and OS != "ios"', {
# Copy pak files to the product directory. These files will be picked
# up by the following installer scripts:
# - Windows: chrome/installer/mini_installer/chrome.release
# - Linux: chrome/installer/linux/internal/common/installer.include
# Ensure that the above scripts are updated when adding or removing
# pak files.
# Copying files to the product directory is not needed on the Mac
# since the framework build phase will copy them into the framework
# bundle directly.
'copies': [
{
'destination': '<(PRODUCT_DIR)',
'files': [
'<(SHARED_INTERMEDIATE_DIR)/repack/chrome_100_percent.pak'
],
},
{
'destination': '<(PRODUCT_DIR)/locales',
'files': [
'<!@pymod_do_main(repack_locales -o -p <(OS) -g <(grit_out_dir) -s <(SHARED_INTERMEDIATE_DIR) -x <(SHARED_INTERMEDIATE_DIR) <(locales))'
],
},
{
'destination': '<(PRODUCT_DIR)/pseudo_locales',
'files': [
'<!@pymod_do_main(repack_locales -o -p <(OS) -g <(grit_out_dir) -s <(SHARED_INTERMEDIATE_DIR) -x <(SHARED_INTERMEDIATE_DIR) <(pseudo_locales))'
],
},
],
'conditions': [
['branding=="Chrome"', {
'copies': [
{
# This location is for the Windows and Linux builds. For
# Windows, the chrome.release file ensures that these files
# are copied into the installer. Note that we have a separate
# section in chrome_dll.gyp to copy these files for Mac, as it
# needs to be dropped inside the framework.
'destination': '<(PRODUCT_DIR)/default_apps',
'files': ['<@(default_apps_list)']
},
],
}],
['enable_hidpi == 1', {
'copies': [
{
'destination': '<(PRODUCT_DIR)',
'files': [
'<(SHARED_INTERMEDIATE_DIR)/repack/chrome_200_percent.pak',
],
},
],
}],
['enable_topchrome_md == 1', {
'copies': [
{
'destination': '<(PRODUCT_DIR)',
'files': [
'<(SHARED_INTERMEDIATE_DIR)/repack/chrome_material_100_percent.pak',
],
},
],
}],
['enable_hidpi == 1 and enable_topchrome_md == 1', {
'copies': [
{
'destination': '<(PRODUCT_DIR)',
'files': [
'<(SHARED_INTERMEDIATE_DIR)/repack/chrome_material_200_percent.pak',
],
},
],
}],
], # conditions
}], # end OS != "mac" and OS != "ios"
], # conditions
},
{
# GN version: //chrome/app/theme:chrome_unscaled_resources
'target_name': 'chrome_unscaled_resources',
'type': 'none',
'actions': [
{
'action_name': 'generate_chrome_unscaled_resources',
'variables': {
'grit_grd_file': 'app/theme/chrome_unscaled_resources.grd',
},
'includes': [ '../build/grit_action.gypi' ],
},
],
'includes': [ '../build/grit_target.gypi' ],
},
{
# GN version: //chrome/browser/resources:options_test_resources
'target_name': 'options_test_resources',
'type': 'none',
'actions': [
{
'action_name': 'generate_options_test_resources',
'variables': {
'grit_grd_file': 'browser/resources/options_test_resources.grd',
},
'includes': [ '../build/grit_action.gypi' ],
},
],
'includes': [ '../build/grit_target.gypi' ],
},
{
# GN version: //chrome/test/data/resources:webui_test_resources
'target_name': 'webui_test_resources',
'type': 'none',
'actions': [
{
'action_name': 'generate_webui_test_resources',
'variables': {
'grit_grd_file': 'test/data/webui_test_resources.grd',
},
'includes': [ '../build/grit_action.gypi' ],
},
],
'includes': [ '../build/grit_target.gypi' ],
},
{
# GN version: //chrome:browser_tests_pak
'target_name': 'browser_tests_pak',
'type': 'none',
'dependencies': [
'options_test_resources',
'webui_test_resources',
],
'actions': [
{
'action_name': 'repack_browser_tests_pak',
'variables': {
'pak_inputs': [
'<(SHARED_INTERMEDIATE_DIR)/chrome/options_test_resources.pak',
'<(SHARED_INTERMEDIATE_DIR)/chrome/webui_test_resources.pak',
],
'pak_output': '<(PRODUCT_DIR)/browser_tests.pak',
},
'includes': [ '../build/repack_action.gypi' ],
},
],
},
], # targets
}
| [
"[email protected]"
] | |
0d4ab487c9de86cce3e199c7f5a4c2c87e57c607 | 2612f336d667a087823234daf946f09b40d8ca3d | /python/lib/Lib/site-packages/django/contrib/gis/tests/geoapp/models.py | 89027eedfbc919466ac7c1335c42dfb57aea547a | [
"Apache-2.0"
] | permissive | tnorbye/intellij-community | df7f181861fc5c551c02c73df3b00b70ab2dd589 | f01cf262fc196bf4dbb99e20cd937dee3705a7b6 | refs/heads/master | 2021-04-06T06:57:57.974599 | 2018-03-13T17:37:00 | 2018-03-13T17:37:00 | 125,079,130 | 2 | 0 | Apache-2.0 | 2018-03-13T16:09:41 | 2018-03-13T16:09:41 | null | UTF-8 | Python | false | false | 1,546 | py | from django.contrib.gis.db import models
from django.contrib.gis.tests.utils import mysql, spatialite
# MySQL spatial indices can't handle NULL geometries.
null_flag = not mysql
class Country(models.Model):
name = models.CharField(max_length=30)
mpoly = models.MultiPolygonField() # SRID, by default, is 4326
objects = models.GeoManager()
def __unicode__(self): return self.name
class City(models.Model):
name = models.CharField(max_length=30)
point = models.PointField()
objects = models.GeoManager()
def __unicode__(self): return self.name
# This is an inherited model from City
class PennsylvaniaCity(City):
county = models.CharField(max_length=30)
objects = models.GeoManager() # TODO: This should be implicitly inherited.
class State(models.Model):
name = models.CharField(max_length=30)
poly = models.PolygonField(null=null_flag) # Allowing NULL geometries here.
objects = models.GeoManager()
def __unicode__(self): return self.name
class Track(models.Model):
name = models.CharField(max_length=30)
line = models.LineStringField()
objects = models.GeoManager()
def __unicode__(self): return self.name
if not spatialite:
class Feature(models.Model):
name = models.CharField(max_length=20)
geom = models.GeometryField()
objects = models.GeoManager()
def __unicode__(self): return self.name
class MinusOneSRID(models.Model):
geom = models.PointField(srid=-1) # Minus one SRID.
objects = models.GeoManager()
| [
"[email protected]"
] | |
33877bf7341e29b7edab2e7b7919f5bd03bfdc76 | 9507ff9e9bca2ca8104369c9e25acd74d308e9b3 | /sta8100_upload/upload.py | 6d962eeda6a0d7bd66233d1d52e6df9d0cd024bf | [] | no_license | yangkang411/python_tool | 03e483c7ec7e1e76284f93cf5b9086fdf98af826 | 713071a9fbabfabcbc3c16ce58d1382c410a7ea3 | refs/heads/master | 2023-03-17T16:14:03.332332 | 2020-09-10T02:37:05 | 2020-09-10T02:37:05 | null | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 231 | py | #!/usr/bin/python
import os
if __name__ == '__main__':
cmd = "TeseoProgrammer_v2.9.0.exe program -f t5 -i sta.bin -o log.txt -c com53 -b 230400 -m SQI -d 0x10000400 -e TRUE -r TRUE";
print ("cmd = %s" % cmd);
os.system(cmd)
| [
"[email protected]"
] | |
3bacf127b039262cc40bb14e97fd4da50cac4c40 | 1c19db866110afddb04d2e9715b49909c7fbb3d4 | /tests/test_user_locale.py | 4635899202d226e926f9194aa81e0dcb4a0fc936 | [
"BSD-2-Clause"
] | permissive | shane-kerr/peeringdb | 505dd5087abe29c9d6013e81b5322d7259a97106 | 5f189631a4d60d3fde662743508784affc6fa22a | refs/heads/master | 2020-09-14T16:25:33.442466 | 2019-11-21T13:54:32 | 2019-11-21T13:54:32 | 223,183,848 | 0 | 0 | NOASSERTION | 2019-11-21T13:54:34 | 2019-11-21T13:44:59 | null | UTF-8 | Python | false | false | 2,541 | py | import pytest
import json
from django.test import Client, TestCase, RequestFactory
from django.contrib.auth.models import Group
import peeringdb_server.models as models
#from django.template import Context, Template
#from django.utils import translation
class UserLocaleTests(TestCase):
"""
Test peeringdb_server.models.User functions
"""
@classmethod
def setUpTestData(cls):
user_group = Group.objects.create(name="user")
for name in ["user_undef", "user_en", "user_pt"]:
setattr(cls, name,
models.User.objects.create_user(
name, "%s@localhost" % name, first_name=name,
last_name=name, password=name))
cls.user_en.set_locale('en')
cls.user_pt.set_locale('pt')
user_group.user_set.add(cls.user_en)
user_group.user_set.add(cls.user_pt)
user_group.user_set.add(cls.user_undef)
cls.user_undef.save()
cls.user_en.save()
cls.user_pt.save()
def setUp(self):
self.factory = RequestFactory()
def test_user_locale(self):
"""
Tests if user profile page has the right language
Note: Don't use Client.login(...) since it will miss language setting in the session
"""
#t = Template("{% load i18n %}{% get_current_language as LANGUAGE_CODE %}{{ LANGUAGE_CODE }}")
#print(t.render(Context({})))
#translation.activate('pt')
#print(t.render(Context({})))
#u_pt = models.User.objects.get(username="user_pt")
#print(u_pt.get_locale())
c = Client()
resp = c.get("/profile", follow=True)
data = {
"next": "/profile",
"username": "user_en",
"password": "user_en"
}
resp = c.post("/auth", data, follow=True)
self.assertGreater(
resp.content.find('<!-- Current language: en -->'), -1)
c.logout()
data = {
"next": "/profile",
"username": "user_pt",
"password": "user_pt"
}
resp = c.post("/auth", data, follow=True)
self.assertGreater(
resp.content.find('<!-- Current language: pt -->'), -1)
c.logout()
data = {
"next": "/profile",
"username": "user_undef",
"password": "user_undef"
}
resp = c.post("/auth", data, follow=True)
self.assertGreater(
resp.content.find('<!-- Current language: en -->'), -1)
| [
"[email protected]"
] | |
a7f8d8f49b6809525e29121763627e7f50f9f9f7 | ab8a34e5b821dde7b09abe37c838de046846484e | /twilio/sample-code-master/notify/v1/user/read-default/read-default.6.x.py | 21a1ceb49f9637120f11fe5bf78cba619a151b3e | [] | no_license | sekharfly/twilio | 492b599fff62618437c87e05a6c201d6de94527a | a2847e4c79f9fbf5c53f25c8224deb11048fe94b | refs/heads/master | 2020-03-29T08:39:00.079997 | 2018-09-21T07:20:24 | 2018-09-21T07:20:24 | 149,721,431 | 0 | 1 | null | null | null | null | UTF-8 | Python | false | false | 467 | py | # Download the helper library from https://www.twilio.com/docs/python/install
from twilio.rest import Client
# Your Account Sid and Auth Token from twilio.com/console
account_sid = 'ACXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX'
auth_token = 'your_auth_token'
client = Client(account_sid, auth_token)
users = client.notify.services('ISXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX') \
.users \
.list()
for record in users:
print(record.sid)
| [
"[email protected]"
] | |
cb28e85295b024bb0498aa6b4989914be951cfa0 | 7963f09b4002249e73496c6cbf271fd6921b3d22 | /tests/test_cpy.py | 7b453154c26e92a9cf985753289721778c504e43 | [] | no_license | thales-angelino/py6502emulator | 6df908fc02f29b41fad550c8b773723a7b63c414 | 1cea28489d51d77d2dec731ab98a6fe8a515a2a8 | refs/heads/master | 2023-03-19T14:46:17.393466 | 2021-03-08T04:10:45 | 2021-03-08T04:10:45 | 345,754,473 | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 4,773 | py | import unittest
from emulator_6502 import emulator_6502 as emulator
from emulator_6502.instructions import cpy
class TestCPX(unittest.TestCase):
def setUp(self):
self.memory = emulator.Memory()
self.cpu = emulator.CPU(self.memory)
self.cpu.reset()
def test_cpy_scenario_1(self):
operand = 0x10
expected_zero = 0
expected_negative = 0
expected_carry = 1
self.cpu.y = 0x50
self.cpu.cpy(operand)
self.assertEqual(self.cpu.processor_status['carry'], expected_carry, "CPU Carry flag should be %d" % expected_carry)
self.assertEqual(self.cpu.processor_status['zero'], expected_zero, "CPU zero flag should be %d" % expected_zero)
self.assertEqual(self.cpu.processor_status['negative'], expected_negative, "CPU negative flag should be %d" % expected_negative)
def test_cpy_scenario_2(self):
operand = 0x50
expected_zero = 1
expected_negative = 0
expected_carry = 1
self.cpu.y = 0x50
self.cpu.cpy(operand)
self.assertEqual(self.cpu.processor_status['carry'], expected_carry, "CPU Carry flag should be %d" % expected_carry)
self.assertEqual(self.cpu.processor_status['zero'], expected_zero, "CPU zero flag should be %d" % expected_zero)
self.assertEqual(self.cpu.processor_status['negative'], expected_negative, "CPU negative flag should be %d" % expected_negative)
def test_cpy_scenario_3(self):
operand = 0x60
expected_zero = 0
expected_negative = 1
expected_carry = 0
self.cpu.y = 0x50
self.cpu.cpy(operand)
self.assertEqual(self.cpu.processor_status['carry'], expected_carry, "CPU Carry flag should be %d" % expected_carry)
self.assertEqual(self.cpu.processor_status['zero'], expected_zero, "CPU zero flag should be %d" % expected_zero)
self.assertEqual(self.cpu.processor_status['negative'], expected_negative, "CPU negative flag should be %d" % expected_negative)
def test_cpy_immediate(self):
expected_cycles = 2
value = 0x10
self.cpu.y = 0x50
expected_zero = 0
expected_negative = 0
expected_carry = 1
self.memory.memory[emulator.START_ADDRESS] = cpy.CPY_IMMEDIATE_OPCODE
self.memory.memory[emulator.START_ADDRESS + 1] = value
self.cpu.execute(1)
self.assertEqual(self.cpu.cycles, expected_cycles, "CPU cycles should be %d" % expected_cycles)
self.assertEqual(self.cpu.processor_status['carry'], expected_carry, "CPU Carry flag should be %d" % expected_carry)
self.assertEqual(self.cpu.processor_status['zero'], expected_zero, "CPU zero flag should be %d" % expected_zero)
self.assertEqual(self.cpu.processor_status['negative'], expected_negative, "CPU negative flag should be %d" % expected_negative)
def test_cpy_absolute(self):
expected_cycles = 4
value = 0x10
self.cpu.y = 0x50
expected_zero = 0
expected_negative = 0
expected_carry = 1
self.memory.memory[emulator.START_ADDRESS] = cpy.CPY_ABSOLUTE_OPCODE
self.memory.memory[emulator.START_ADDRESS + 1] = 0xff # LSB FIRST!!!
self.memory.memory[emulator.START_ADDRESS + 2] = 0x02
self.memory.memory[0x02ff] = value
self.cpu.execute(1)
self.assertEqual(self.cpu.cycles, expected_cycles, "CPU cycles should be %d" % expected_cycles)
self.assertEqual(self.cpu.processor_status['carry'], expected_carry, "CPU Carry flag should be %d" % expected_carry)
self.assertEqual(self.cpu.processor_status['zero'], expected_zero, "CPU zero flag should be %d" % expected_zero)
self.assertEqual(self.cpu.processor_status['negative'], expected_negative, "CPU negative flag should be %d" % expected_negative)
def test_cpy_zeropage(self):
expected_cycles = 3
value = 0x10
self.cpu.y = 0x50
expected_zero = 0
expected_negative = 0
expected_carry = 1
self.memory.memory[emulator.START_ADDRESS] = cpy.CPY_ZEROPAGE_OPCODE
self.memory.memory[emulator.START_ADDRESS + 1] = 0xff
self.memory.memory[0x00ff] = value
self.cpu.execute(1)
self.assertEqual(self.cpu.cycles, expected_cycles, "CPU cycles should be %d" % expected_cycles)
self.assertEqual(self.cpu.processor_status['carry'], expected_carry, "CPU Carry flag should be %d" % expected_carry)
self.assertEqual(self.cpu.processor_status['zero'], expected_zero, "CPU zero flag should be %d" % expected_zero)
self.assertEqual(self.cpu.processor_status['negative'], expected_negative, "CPU negative flag should be %d" % expected_negative)
if __name__ == '__main__':
unittest.main() | [
"[email protected]"
] | |
738b4c2e8ea71aa1374de72bcbdaff282bbe4f37 | 8ace8be98c5fb7baac267ca7f83c8085e5cad35c | /26_two_sum_unique_pairs.py | def053f435def022e8e58082e3376b6e647929d4 | [] | no_license | cyberbono3/amazon-oa-python | c063eb275a4d311e58f148c0300c7e19b0f03bea | 7ce502bbe3a30b1d6052a46e7a28b724a327b5ae | refs/heads/master | 2023-01-20T16:23:00.241012 | 2020-11-22T03:49:25 | 2020-11-22T03:49:25 | 293,693,115 | 1 | 1 | null | null | null | null | UTF-8 | Python | false | false | 416 | py | """
Input: nums = [1, 1, 2, 45, 46, 46], target = 47
1, 1
"""
class Solution:
def unique_pairs(self, nums, target):
s = set()
dic = {}
for i,x in enumerate(nums):
if target - x in s:
dic[target-x] = x
else:
s.add(x)
print(dic)
return len(dic)
sol = Solution()
print(sol.unique_pairs([1, 1, 2, 45, 46, 46], 47)) | [
"[email protected]"
] | |
cb07a323abf8740806bebc941c841ab0e659081b | e6ad1014aacaa92643f42952c278469177defc15 | /napalm_ansible/napalm_diff_yang.py | d134e9bb1a69665bbfabcb13f326bcf956c8cb1d | [
"Apache-2.0"
] | permissive | cspeidel/napalm-ansible | d290ee7cc1abd9dd7d11044d5ddc542bd6658906 | 8ad4badb38d79ec5efd96faa666c71f7438dfa28 | refs/heads/develop | 2022-02-09T05:40:10.302690 | 2017-11-06T20:51:58 | 2017-11-06T20:51:58 | 110,727,639 | 0 | 0 | Apache-2.0 | 2022-01-31T16:25:25 | 2017-11-14T18:18:35 | Python | UTF-8 | Python | false | false | 3,409 | py | #!/usr/bin/python
# -*- coding: utf-8 -*-
"""
(c) 2017 David Barroso <[email protected]>
This file is part of Ansible
Ansible is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
Ansible 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 General Public License for more details.
You should have received a copy of the GNU General Public License
along with Ansible. If not, see <http://www.gnu.org/licenses/>.
"""
from ansible.module_utils.basic import AnsibleModule
try:
import napalm_yang
except ImportError:
napalm_yang = None
DOCUMENTATION = '''
---
module: napalm_diff_yang
author: "David Barroso (@dbarrosop)"
version_added: "0.0"
short_description: "Return diff of two YANG objects"
description:
- "Create two YANG objects from dictionaries and runs mehtod"
- "napalm_yang.utils.diff on them."
requirements:
- napalm-yang
options:
models:
description:
- List of models to parse
required: True
first:
description:
- Dictionary with the data to load into the first YANG object
required: True
second:
description:
- Dictionary with the data to load into the second YANG object
required: True
'''
EXAMPLES = '''
napalm_diff_yang:
first: "{{ candidate.yang_model }}"
second: "{{ running_config.yang_model }}"
models:
- models.openconfig_interfaces
register: diff
'''
RETURN = '''
diff:
description: "Same output as the method napalm_yang.utils.diff"
returned: always
type: dict
sample: {
"interfaces": {
"interface": {
"both": {
"Port-Channel1": {
"config": {
"description": {
"first": "blah",
"second": "Asadasd"
}
}
}
}
}
}
'''
def get_root_object(models):
"""
Read list of models and returns a Root object with the proper models added.
"""
root = napalm_yang.base.Root()
for model in models:
current = napalm_yang
for p in model.split("."):
current = getattr(current, p)
root.add_model(current)
return root
def main():
module = AnsibleModule(
argument_spec=dict(
models=dict(type="list", required=True),
first=dict(type='dict', required=True),
second=dict(type='dict', required=True),
),
supports_check_mode=True
)
if not napalm_yang:
module.fail_json(msg="the python module napalm-yang is required")
first = get_root_object(module.params["models"])
first.load_dict(module.params["first"])
second = get_root_object(module.params["models"])
second.load_dict(module.params["second"])
diff = napalm_yang.utils.diff(first, second)
module.exit_json(yang_diff=diff)
if __name__ == '__main__':
main()
| [
"[email protected]"
] | |
fe4155275d3a9240634ebe2b2de50705201231ac | a140a7ca1bc5f0af773cb3d22081b4bb75138cfa | /234_palindromLinkedList.py | b1b3a195574aefe83cc26bf49500c32c48a8a3b2 | [] | no_license | YeahHuang/Leetcode | d02bc99d2e890ed0e829515b6f85c4ca6394a1a1 | 78d36486ad4ec2bfb88fd35a5fd7fd4f0003ee97 | refs/heads/master | 2021-07-14T01:53:06.701325 | 2020-06-22T03:01:46 | 2020-06-22T03:01:46 | 166,235,118 | 1 | 0 | null | null | null | null | UTF-8 | Python | false | false | 585 | py | class Solution:
def isPalindrome(self, head: ListNode) -> bool:
rev = None
slow = fast = head
while fast and fast.next:
fast = fast.next.next
rev, rev.next, slow = slow, rev, slow.next
if fast:
# fast is at the end, move slow one step further for comparison(cross middle one)
slow = slow.next
while rev and rev.val == slow.val:
slow = slow.next
rev = rev.next
# if equivalent then rev become None, return True; otherwise return False
return not rev | [
"[email protected]"
] | |
eecaffdbe17ebf356d4729447b601c155f4a4f9d | 209c876b1e248fd67bd156a137d961a6610f93c7 | /python/paddle/metric/metrics.py | aeec4022e218424eb20183b6917aa2f39a17d588 | [
"Apache-2.0"
] | permissive | Qengineering/Paddle | 36e0dba37d29146ebef4fba869490ecedbf4294e | 591456c69b76ee96d04b7d15dca6bb8080301f21 | refs/heads/develop | 2023-01-24T12:40:04.551345 | 2022-10-06T10:30:56 | 2022-10-06T10:30:56 | 544,837,444 | 0 | 0 | Apache-2.0 | 2022-10-03T10:12:54 | 2022-10-03T10:12:54 | null | UTF-8 | Python | false | false | 28,411 | py | # Copyright (c) 2020 PaddlePaddle Authors. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
import six
import abc
import numpy as np
from ..fluid.data_feeder import check_variable_and_dtype
from ..fluid.layer_helper import LayerHelper
from ..fluid.framework import core, _varbase_creator, _non_static_mode, _in_legacy_dygraph
import paddle
from paddle import _C_ops, _legacy_C_ops
__all__ = []
def _is_numpy_(var):
return isinstance(var, (np.ndarray, np.generic))
@six.add_metaclass(abc.ABCMeta)
class Metric(object):
r"""
Base class for metric, encapsulates metric logic and APIs
Usage:
.. code-block:: text
m = SomeMetric()
for prediction, label in ...:
m.update(prediction, label)
m.accumulate()
Advanced usage for :code:`compute`:
Metric calculation can be accelerated by calculating metric states
from model outputs and labels by build-in operators not by Python/NumPy
in :code:`compute`, metric states will be fetched as NumPy array and
call :code:`update` with states in NumPy format.
Metric calculated as follows (operations in Model and Metric are
indicated with curly brackets, while data nodes not):
.. code-block:: text
inputs & labels || ------------------
| ||
{model} ||
| ||
outputs & labels ||
| || tensor data
{Metric.compute} ||
| ||
metric states(tensor) ||
| ||
{fetch as numpy} || ------------------
| ||
metric states(numpy) || numpy data
| ||
{Metric.update} \/ ------------------
Examples:
For :code:`Accuracy` metric, which takes :code:`pred` and :code:`label`
as inputs, we can calculate the correct prediction matrix between
:code:`pred` and :code:`label` in :code:`compute`.
For examples, prediction results contains 10 classes, while :code:`pred`
shape is [N, 10], :code:`label` shape is [N, 1], N is mini-batch size,
and we only need to calculate accurary of top-1 and top-5, we could
calculate the correct prediction matrix of the top-5 scores of the
prediction of each sample like follows, while the correct prediction
matrix shape is [N, 5].
.. code-block:: text
def compute(pred, label):
# sort prediction and slice the top-5 scores
pred = paddle.argsort(pred, descending=True)[:, :5]
# calculate whether the predictions are correct
correct = pred == label
return paddle.cast(correct, dtype='float32')
With the :code:`compute`, we split some calculations to OPs (which
may run on GPU devices, will be faster), and only fetch 1 tensor with
shape as [N, 5] instead of 2 tensors with shapes as [N, 10] and [N, 1].
:code:`update` can be define as follows:
.. code-block:: text
def update(self, correct):
accs = []
for i, k in enumerate(self.topk):
num_corrects = correct[:, :k].sum()
num_samples = len(correct)
accs.append(float(num_corrects) / num_samples)
self.total[i] += num_corrects
self.count[i] += num_samples
return accs
"""
def __init__(self):
pass
@abc.abstractmethod
def reset(self):
"""
Reset states and result
"""
raise NotImplementedError(
"function 'reset' not implemented in {}.".format(
self.__class__.__name__))
@abc.abstractmethod
def update(self, *args):
"""
Update states for metric
Inputs of :code:`update` is the outputs of :code:`Metric.compute`,
if :code:`compute` is not defined, the inputs of :code:`update`
will be flatten arguments of **output** of mode and **label** from data:
:code:`update(output1, output2, ..., label1, label2,...)`
see :code:`Metric.compute`
"""
raise NotImplementedError(
"function 'update' not implemented in {}.".format(
self.__class__.__name__))
@abc.abstractmethod
def accumulate(self):
"""
Accumulates statistics, computes and returns the metric value
"""
raise NotImplementedError(
"function 'accumulate' not implemented in {}.".format(
self.__class__.__name__))
@abc.abstractmethod
def name(self):
"""
Returns metric name
"""
raise NotImplementedError(
"function 'name' not implemented in {}.".format(
self.__class__.__name__))
def compute(self, *args):
"""
This API is advanced usage to accelerate metric calculating, calulations
from outputs of model to the states which should be updated by Metric can
be defined here, where Paddle OPs is also supported. Outputs of this API
will be the inputs of "Metric.update".
If :code:`compute` is defined, it will be called with **outputs**
of model and **labels** from data as arguments, all outputs and labels
will be concatenated and flatten and each filed as a separate argument
as follows:
:code:`compute(output1, output2, ..., label1, label2,...)`
If :code:`compute` is not defined, default behaviour is to pass
input to output, so output format will be:
:code:`return output1, output2, ..., label1, label2,...`
see :code:`Metric.update`
"""
return args
class Accuracy(Metric):
"""
Encapsulates accuracy metric logic.
Args:
topk (list[int]|tuple[int]): Number of top elements to look at
for computing accuracy. Default is (1,).
name (str, optional): String name of the metric instance. Default
is `acc`.
Example by standalone:
.. code-block:: python
import numpy as np
import paddle
x = paddle.to_tensor(np.array([
[0.1, 0.2, 0.3, 0.4],
[0.1, 0.4, 0.3, 0.2],
[0.1, 0.2, 0.4, 0.3],
[0.1, 0.2, 0.3, 0.4]]))
y = paddle.to_tensor(np.array([[0], [1], [2], [3]]))
m = paddle.metric.Accuracy()
correct = m.compute(x, y)
m.update(correct)
res = m.accumulate()
print(res) # 0.75
Example with Model API:
.. code-block:: python
import paddle
from paddle.static import InputSpec
import paddle.vision.transforms as T
from paddle.vision.datasets import MNIST
input = InputSpec([None, 1, 28, 28], 'float32', 'image')
label = InputSpec([None, 1], 'int64', 'label')
transform = T.Compose([T.Transpose(), T.Normalize([127.5], [127.5])])
train_dataset = MNIST(mode='train', transform=transform)
model = paddle.Model(paddle.vision.models.LeNet(), input, label)
optim = paddle.optimizer.Adam(
learning_rate=0.001, parameters=model.parameters())
model.prepare(
optim,
loss=paddle.nn.CrossEntropyLoss(),
metrics=paddle.metric.Accuracy())
model.fit(train_dataset, batch_size=64)
"""
def __init__(self, topk=(1, ), name=None, *args, **kwargs):
super(Accuracy, self).__init__(*args, **kwargs)
self.topk = topk
self.maxk = max(topk)
self._init_name(name)
self.reset()
def compute(self, pred, label, *args):
"""
Compute the top-k (maximum value in `topk`) indices.
Args:
pred (Tensor): The predicted value is a Tensor with dtype
float32 or float64. Shape is [batch_size, d0, ..., dN].
label (Tensor): The ground truth value is Tensor with dtype
int64. Shape is [batch_size, d0, ..., 1], or
[batch_size, d0, ..., num_classes] in one hot representation.
Return:
Tensor: Correct mask, a tensor with shape [batch_size, d0, ..., topk].
"""
pred = paddle.argsort(pred, descending=True)
pred = paddle.slice(pred,
axes=[len(pred.shape) - 1],
starts=[0],
ends=[self.maxk])
if (len(label.shape) == 1) or \
(len(label.shape) == 2 and label.shape[-1] == 1):
# In static mode, the real label data shape may be different
# from shape defined by paddle.static.InputSpec in model
# building, reshape to the right shape.
label = paddle.reshape(label, (-1, 1))
elif label.shape[-1] != 1:
# one-hot label
label = paddle.argmax(label, axis=-1, keepdim=True)
correct = pred == label
return paddle.cast(correct, dtype='float32')
def update(self, correct, *args):
"""
Update the metrics states (correct count and total count), in order to
calculate cumulative accuracy of all instances. This function also
returns the accuracy of current step.
Args:
correct: Correct mask, a tensor with shape [batch_size, d0, ..., topk].
Return:
Tensor: the accuracy of current step.
"""
if isinstance(correct, (paddle.Tensor, paddle.fluid.core.eager.Tensor)):
correct = correct.numpy()
num_samples = np.prod(np.array(correct.shape[:-1]))
accs = []
for i, k in enumerate(self.topk):
num_corrects = correct[..., :k].sum()
accs.append(float(num_corrects) / num_samples)
self.total[i] += num_corrects
self.count[i] += num_samples
accs = accs[0] if len(self.topk) == 1 else accs
return accs
def reset(self):
"""
Resets all of the metric state.
"""
self.total = [0.] * len(self.topk)
self.count = [0] * len(self.topk)
def accumulate(self):
"""
Computes and returns the accumulated metric.
"""
res = []
for t, c in zip(self.total, self.count):
r = float(t) / c if c > 0 else 0.
res.append(r)
res = res[0] if len(self.topk) == 1 else res
return res
def _init_name(self, name):
name = name or 'acc'
if self.maxk != 1:
self._name = ['{}_top{}'.format(name, k) for k in self.topk]
else:
self._name = [name]
def name(self):
"""
Return name of metric instance.
"""
return self._name
class Precision(Metric):
"""
Precision (also called positive predictive value) is the fraction of
relevant instances among the retrieved instances. Refer to
https://en.wikipedia.org/wiki/Evaluation_of_binary_classifiers
Noted that this class manages the precision score only for binary
classification task.
Args:
name (str, optional): String name of the metric instance.
Default is `precision`.
Example by standalone:
.. code-block:: python
import numpy as np
import paddle
x = np.array([0.1, 0.5, 0.6, 0.7])
y = np.array([0, 1, 1, 1])
m = paddle.metric.Precision()
m.update(x, y)
res = m.accumulate()
print(res) # 1.0
Example with Model API:
.. code-block:: python
import numpy as np
import paddle
import paddle.nn as nn
class Data(paddle.io.Dataset):
def __init__(self):
super(Data, self).__init__()
self.n = 1024
self.x = np.random.randn(self.n, 10).astype('float32')
self.y = np.random.randint(2, size=(self.n, 1)).astype('float32')
def __getitem__(self, idx):
return self.x[idx], self.y[idx]
def __len__(self):
return self.n
model = paddle.Model(nn.Sequential(
nn.Linear(10, 1),
nn.Sigmoid()
))
optim = paddle.optimizer.Adam(
learning_rate=0.001, parameters=model.parameters())
model.prepare(
optim,
loss=nn.BCELoss(),
metrics=paddle.metric.Precision())
data = Data()
model.fit(data, batch_size=16)
"""
def __init__(self, name='precision', *args, **kwargs):
super(Precision, self).__init__(*args, **kwargs)
self.tp = 0 # true positive
self.fp = 0 # false positive
self._name = name
def update(self, preds, labels):
"""
Update the states based on the current mini-batch prediction results.
Args:
preds (numpy.ndarray): The prediction result, usually the output
of two-class sigmoid function. It should be a vector (column
vector or row vector) with data type: 'float64' or 'float32'.
labels (numpy.ndarray): The ground truth (labels),
the shape should keep the same as preds.
The data type is 'int32' or 'int64'.
"""
if isinstance(preds, (paddle.Tensor, paddle.fluid.core.eager.Tensor)):
preds = preds.numpy()
elif not _is_numpy_(preds):
raise ValueError("The 'preds' must be a numpy ndarray or Tensor.")
if isinstance(labels, (paddle.Tensor, paddle.fluid.core.eager.Tensor)):
labels = labels.numpy()
elif not _is_numpy_(labels):
raise ValueError("The 'labels' must be a numpy ndarray or Tensor.")
sample_num = labels.shape[0]
preds = np.floor(preds + 0.5).astype("int32")
for i in range(sample_num):
pred = preds[i]
label = labels[i]
if pred == 1:
if pred == label:
self.tp += 1
else:
self.fp += 1
def reset(self):
"""
Resets all of the metric state.
"""
self.tp = 0
self.fp = 0
def accumulate(self):
"""
Calculate the final precision.
Returns:
A scaler float: results of the calculated precision.
"""
ap = self.tp + self.fp
return float(self.tp) / ap if ap != 0 else .0
def name(self):
"""
Returns metric name
"""
return self._name
class Recall(Metric):
"""
Recall (also known as sensitivity) is the fraction of
relevant instances that have been retrieved over the
total amount of relevant instances
Refer to:
https://en.wikipedia.org/wiki/Precision_and_recall
Noted that this class manages the recall score only for
binary classification task.
Args:
name (str, optional): String name of the metric instance.
Default is `recall`.
Example by standalone:
.. code-block:: python
import numpy as np
import paddle
x = np.array([0.1, 0.5, 0.6, 0.7])
y = np.array([1, 0, 1, 1])
m = paddle.metric.Recall()
m.update(x, y)
res = m.accumulate()
print(res) # 2.0 / 3.0
Example with Model API:
.. code-block:: python
import numpy as np
import paddle
import paddle.nn as nn
class Data(paddle.io.Dataset):
def __init__(self):
super(Data, self).__init__()
self.n = 1024
self.x = np.random.randn(self.n, 10).astype('float32')
self.y = np.random.randint(2, size=(self.n, 1)).astype('float32')
def __getitem__(self, idx):
return self.x[idx], self.y[idx]
def __len__(self):
return self.n
model = paddle.Model(nn.Sequential(
nn.Linear(10, 1),
nn.Sigmoid()
))
optim = paddle.optimizer.Adam(
learning_rate=0.001, parameters=model.parameters())
model.prepare(
optim,
loss=nn.BCELoss(),
metrics=[paddle.metric.Precision(), paddle.metric.Recall()])
data = Data()
model.fit(data, batch_size=16)
"""
def __init__(self, name='recall', *args, **kwargs):
super(Recall, self).__init__(*args, **kwargs)
self.tp = 0 # true positive
self.fn = 0 # false negative
self._name = name
def update(self, preds, labels):
"""
Update the states based on the current mini-batch prediction results.
Args:
preds(numpy.array): prediction results of current mini-batch,
the output of two-class sigmoid function.
Shape: [batch_size, 1]. Dtype: 'float64' or 'float32'.
labels(numpy.array): ground truth (labels) of current mini-batch,
the shape should keep the same as preds.
Shape: [batch_size, 1], Dtype: 'int32' or 'int64'.
"""
if isinstance(preds, (paddle.Tensor, paddle.fluid.core.eager.Tensor)):
preds = preds.numpy()
elif not _is_numpy_(preds):
raise ValueError("The 'preds' must be a numpy ndarray or Tensor.")
if isinstance(labels, (paddle.Tensor, paddle.fluid.core.eager.Tensor)):
labels = labels.numpy()
elif not _is_numpy_(labels):
raise ValueError("The 'labels' must be a numpy ndarray or Tensor.")
sample_num = labels.shape[0]
preds = np.rint(preds).astype("int32")
for i in range(sample_num):
pred = preds[i]
label = labels[i]
if label == 1:
if pred == label:
self.tp += 1
else:
self.fn += 1
def accumulate(self):
"""
Calculate the final recall.
Returns:
A scaler float: results of the calculated Recall.
"""
recall = self.tp + self.fn
return float(self.tp) / recall if recall != 0 else .0
def reset(self):
"""
Resets all of the metric state.
"""
self.tp = 0
self.fn = 0
def name(self):
"""
Returns metric name
"""
return self._name
class Auc(Metric):
"""
The auc metric is for binary classification.
Refer to https://en.wikipedia.org/wiki/Receiver_operating_characteristic#Area_under_the_curve.
Please notice that the auc metric is implemented with python, which may be a little bit slow.
The `auc` function creates four local variables, `true_positives`,
`true_negatives`, `false_positives` and `false_negatives` that are used to
compute the AUC. To discretize the AUC curve, a linearly spaced set of
thresholds is used to compute pairs of recall and precision values. The area
under the ROC-curve is therefore computed using the height of the recall
values by the false positive rate, while the area under the PR-curve is the
computed using the height of the precision values by the recall.
Args:
curve (str): Specifies the mode of the curve to be computed,
'ROC' or 'PR' for the Precision-Recall-curve. Default is 'ROC'.
num_thresholds (int): The number of thresholds to use when
discretizing the roc curve. Default is 4095.
'ROC' or 'PR' for the Precision-Recall-curve. Default is 'ROC'.
name (str, optional): String name of the metric instance. Default
is `auc`.
"NOTE: only implement the ROC curve type via Python now."
Example by standalone:
.. code-block:: python
import numpy as np
import paddle
m = paddle.metric.Auc()
n = 8
class0_preds = np.random.random(size = (n, 1))
class1_preds = 1 - class0_preds
preds = np.concatenate((class0_preds, class1_preds), axis=1)
labels = np.random.randint(2, size = (n, 1))
m.update(preds=preds, labels=labels)
res = m.accumulate()
Example with Model API:
.. code-block:: python
import numpy as np
import paddle
import paddle.nn as nn
class Data(paddle.io.Dataset):
def __init__(self):
super(Data, self).__init__()
self.n = 1024
self.x = np.random.randn(self.n, 10).astype('float32')
self.y = np.random.randint(2, size=(self.n, 1)).astype('int64')
def __getitem__(self, idx):
return self.x[idx], self.y[idx]
def __len__(self):
return self.n
model = paddle.Model(nn.Sequential(
nn.Linear(10, 2), nn.Softmax())
)
optim = paddle.optimizer.Adam(
learning_rate=0.001, parameters=model.parameters())
def loss(x, y):
return nn.functional.nll_loss(paddle.log(x), y)
model.prepare(
optim,
loss=loss,
metrics=paddle.metric.Auc())
data = Data()
model.fit(data, batch_size=16)
"""
def __init__(self,
curve='ROC',
num_thresholds=4095,
name='auc',
*args,
**kwargs):
super(Auc, self).__init__(*args, **kwargs)
self._curve = curve
self._num_thresholds = num_thresholds
_num_pred_buckets = num_thresholds + 1
self._stat_pos = np.zeros(_num_pred_buckets)
self._stat_neg = np.zeros(_num_pred_buckets)
self._name = name
def update(self, preds, labels):
"""
Update the auc curve with the given predictions and labels.
Args:
preds (numpy.array): An numpy array in the shape of
(batch_size, 2), preds[i][j] denotes the probability of
classifying the instance i into the class j.
labels (numpy.array): an numpy array in the shape of
(batch_size, 1), labels[i] is either o or 1,
representing the label of the instance i.
"""
if isinstance(labels, (paddle.Tensor, paddle.fluid.core.eager.Tensor)):
labels = labels.numpy()
elif not _is_numpy_(labels):
raise ValueError("The 'labels' must be a numpy ndarray or Tensor.")
if isinstance(preds, (paddle.Tensor, paddle.fluid.core.eager.Tensor)):
preds = preds.numpy()
elif not _is_numpy_(preds):
raise ValueError("The 'preds' must be a numpy ndarray or Tensor.")
for i, lbl in enumerate(labels):
value = preds[i, 1]
bin_idx = int(value * self._num_thresholds)
assert bin_idx <= self._num_thresholds
if lbl:
self._stat_pos[bin_idx] += 1.0
else:
self._stat_neg[bin_idx] += 1.0
@staticmethod
def trapezoid_area(x1, x2, y1, y2):
return abs(x1 - x2) * (y1 + y2) / 2.0
def accumulate(self):
"""
Return the area (a float score) under auc curve
Return:
float: the area under auc curve
"""
tot_pos = 0.0
tot_neg = 0.0
auc = 0.0
idx = self._num_thresholds
while idx >= 0:
tot_pos_prev = tot_pos
tot_neg_prev = tot_neg
tot_pos += self._stat_pos[idx]
tot_neg += self._stat_neg[idx]
auc += self.trapezoid_area(tot_neg, tot_neg_prev, tot_pos,
tot_pos_prev)
idx -= 1
return auc / tot_pos / tot_neg if tot_pos > 0.0 and tot_neg > 0.0 else 0.0
def reset(self):
"""
Reset states and result
"""
_num_pred_buckets = self._num_thresholds + 1
self._stat_pos = np.zeros(_num_pred_buckets)
self._stat_neg = np.zeros(_num_pred_buckets)
def name(self):
"""
Returns metric name
"""
return self._name
def accuracy(input, label, k=1, correct=None, total=None, name=None):
"""
accuracy layer.
Refer to the https://en.wikipedia.org/wiki/Precision_and_recall
This function computes the accuracy using the input and label.
If the correct label occurs in top k predictions, then correct will increment by one.
Note: the dtype of accuracy is determined by input. the input and label dtype can be different.
Args:
input(Tensor): The input of accuracy layer, which is the predictions of network. A Tensor with type float32,float64.
The shape is ``[sample_number, class_dim]`` .
label(Tensor): The label of dataset. Tensor with type int64 or int32. The shape is ``[sample_number, 1]`` .
k(int, optional): The top k predictions for each class will be checked. Data type is int64 or int32.
correct(Tensor, optional): The correct predictions count. A Tensor with type int64 or int32.
total(Tensor, optional): The total entries count. A tensor with type int64 or int32.
name(str, optional): The default value is None. Normally there is no need for
user to set this property. For more information, please refer to :ref:`api_guide_Name`
Returns:
Tensor, the correct rate. A Tensor with type float32.
Examples:
.. code-block:: python
import paddle
predictions = paddle.to_tensor([[0.2, 0.1, 0.4, 0.1, 0.1], [0.2, 0.3, 0.1, 0.15, 0.25]], dtype='float32')
label = paddle.to_tensor([[2], [0]], dtype="int64")
result = paddle.metric.accuracy(input=predictions, label=label, k=1)
# [0.5]
"""
if label.dtype == paddle.int32:
label = paddle.cast(label, paddle.int64)
if _non_static_mode():
if correct is None:
correct = _varbase_creator(dtype="int32")
if total is None:
total = _varbase_creator(dtype="int32")
topk_out, topk_indices = paddle.topk(input, k=k)
_acc, _, _ = _legacy_C_ops.accuracy(topk_out, topk_indices, label,
correct, total)
return _acc
helper = LayerHelper("accuracy", **locals())
check_variable_and_dtype(input, 'input', ['float16', 'float32', 'float64'],
'accuracy')
topk_out, topk_indices = paddle.topk(input, k=k)
acc_out = helper.create_variable_for_type_inference(dtype="float32")
if correct is None:
correct = helper.create_variable_for_type_inference(dtype="int32")
if total is None:
total = helper.create_variable_for_type_inference(dtype="int32")
helper.append_op(type="accuracy",
inputs={
"Out": [topk_out],
"Indices": [topk_indices],
"Label": [label]
},
outputs={
"Accuracy": [acc_out],
"Correct": [correct],
"Total": [total],
})
return acc_out
| [
"[email protected]"
] | |
f50a62262f8a5fd229e3a174e46c8c9fedf3c950 | cef09d1e6d5e7cd335387d0829211ffb0da18f48 | /tests2/tests/wedge100/test_psumuxmon.py | 73784296b42bf03dd786c25cca01bc61c37967ce | [] | no_license | theopolis/openbmc | a1ef2e3335efd19bf750117d79c1477d47948ff3 | 1784748ba29ee89bccacb2019a0bb86bd181c651 | refs/heads/master | 2020-12-14T07:20:40.273681 | 2019-04-20T05:25:17 | 2019-04-20T05:25:17 | 43,323,632 | 0 | 1 | null | 2015-09-28T19:56:24 | 2015-09-28T19:56:24 | null | UTF-8 | Python | false | false | 2,143 | py | #!/usr/bin/env python
#
# Copyright 2018-present Facebook. All Rights Reserved.
#
# This program file is free software; you can redistribute it and/or modify it
# under the terms of the GNU General Public License as published by the
# Free Software Foundation; version 2 of the License.
#
# 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 General Public License
# for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program in a file named COPYING; if not, write to the
# Free Software Foundation, Inc.,
# 51 Franklin Street, Fifth Floor,
# Boston, MA 02110-1301 USA
#
import unittest
import os
import re
from utils.shell_util import run_shell_cmd
from utils.cit_logger import Logger
class PsumuxmonTest(unittest.TestCase):
def setUp(self):
Logger.start(name=__name__)
def tearDown(self):
Logger.info("Finished logging for {}".format(self._testMethodName))
pass
def test_psumuxmon_runit_sv_status(self):
cmd = ["/usr/bin/sv status psumuxmon"]
data = run_shell_cmd(cmd)
self.assertIn("run", data, "psumuxmon process not running")
def get_ltc_hwmon_path(self, path):
pcard_vin = None
result = re.split("hwmon", path)
if os.path.isdir(result[0]):
construct_hwmon_path = result[0] + "hwmon"
x = None
for x in os.listdir(construct_hwmon_path):
if x.startswith('hwmon'):
construct_hwmon_path = construct_hwmon_path + "/" + x + "/" + result[2].split("/")[1]
return construct_hwmon_path
return None
def test_psumuxmon_ltc_sensor_path_exists(self):
# Based on lab device deployment, sensor data might not be accessible.
# Verify that path exists
cmd = "/sys/bus/i2c/devices/7-006f/hwmon/hwmon*/in1_input"
self.assertTrue(os.path.exists(self.get_ltc_hwmon_path(cmd)),
"psumuxmon LTC sensor path accessible")
| [
"[email protected]"
] | |
0b122012c36b3cd5dad4e207579418712c3535ca | 642e8d6d8cd8d08a73bdcf82ae9689a09284025c | /celery/worker/__init__.py | 96b994779744ff87efee9a3dcbecee7745c8b868 | [
"BSD-3-Clause"
] | permissive | abecciu/celery | 941f29c033b54b766166f17aa8c5e4be05df08b9 | f0c399e34d56c7a2a14cb42bfb2b6455c68ef0c0 | refs/heads/master | 2021-01-14T12:57:11.230199 | 2009-09-10T13:44:51 | 2009-09-10T13:44:51 | null | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 10,215 | py | """
The Multiprocessing Worker Server
Documentation for this module is in ``docs/reference/celery.worker.rst``.
"""
from carrot.connection import DjangoBrokerConnection, AMQPConnectionException
from celery.worker.controllers import Mediator, PeriodicWorkController
from celery.worker.job import TaskWrapper
from celery.exceptions import NotRegistered
from celery.messaging import get_consumer_set
from celery.conf import DAEMON_CONCURRENCY, DAEMON_LOG_FILE
from celery.conf import AMQP_CONNECTION_RETRY, AMQP_CONNECTION_MAX_RETRIES
from celery.log import setup_logger
from celery.pool import TaskPool
from celery.utils import retry_over_time
from celery.datastructures import SharedCounter
from Queue import Queue
import traceback
import logging
import socket
class AMQPListener(object):
"""Listen for messages received from the AMQP broker and
move them the the bucket queue for task processing.
:param bucket_queue: See :attr:`bucket_queue`.
:param hold_queue: See :attr:`hold_queue`.
.. attribute:: bucket_queue
The queue that holds tasks ready for processing immediately.
.. attribute:: hold_queue
The queue that holds paused tasks. Reasons for being paused include
a countdown/eta or that it's waiting for retry.
.. attribute:: logger
The logger used.
"""
def __init__(self, bucket_queue, hold_queue, logger,
initial_prefetch_count=2):
self.amqp_connection = None
self.task_consumer = None
self.bucket_queue = bucket_queue
self.hold_queue = hold_queue
self.logger = logger
self.prefetch_count = SharedCounter(initial_prefetch_count)
def start(self):
"""Start the consumer.
If the connection is lost, it tries to re-establish the connection
over time and restart consuming messages.
"""
while True:
self.reset_connection()
try:
self.consume_messages()
except (socket.error, AMQPConnectionException):
self.logger.error("AMQPListener: Connection to broker lost. "
+ "Trying to re-establish connection...")
def consume_messages(self):
"""Consume messages forever (or until an exception is raised)."""
task_consumer = self.task_consumer
self.logger.debug("AMQPListener: Starting message consumer...")
it = task_consumer.iterconsume(limit=None)
self.logger.debug("AMQPListener: Ready to accept tasks!")
while True:
self.task_consumer.qos(prefetch_count=int(self.prefetch_count))
it.next()
def stop(self):
"""Stop processing AMQP messages and close the connection
to the broker."""
self.close_connection()
def receive_message(self, message_data, message):
"""The callback called when a new message is received.
If the message has an ``eta`` we move it to the hold queue,
otherwise we move it the bucket queue for immediate processing.
"""
try:
task = TaskWrapper.from_message(message, message_data,
logger=self.logger)
except NotRegistered, exc:
self.logger.error("Unknown task ignored: %s" % (exc))
return
eta = message_data.get("eta")
if eta:
self.prefetch_count.increment()
self.logger.info("Got task from broker: %s[%s] eta:[%s]" % (
task.task_name, task.task_id, eta))
self.hold_queue.put((task, eta, self.prefetch_count.decrement))
else:
self.logger.info("Got task from broker: %s[%s]" % (
task.task_name, task.task_id))
self.bucket_queue.put(task)
def close_connection(self):
"""Close the AMQP connection."""
if self.task_consumer:
self.task_consumer.close()
self.task_consumer = None
if self.amqp_connection:
self.logger.debug(
"AMQPListener: Closing connection to the broker...")
self.amqp_connection.close()
self.amqp_connection = None
def reset_connection(self):
"""Reset the AMQP connection, and reinitialize the
:class:`carrot.messaging.ConsumerSet` instance.
Resets the task consumer in :attr:`task_consumer`.
"""
self.logger.debug(
"AMQPListener: Re-establishing connection to the broker...")
self.close_connection()
self.amqp_connection = self._open_connection()
self.task_consumer = get_consumer_set(connection=self.amqp_connection)
self.task_consumer.register_callback(self.receive_message)
def _open_connection(self):
"""Retries connecting to the AMQP broker over time.
See :func:`celery.utils.retry_over_time`.
"""
def _connection_error_handler(exc, interval):
"""Callback handler for connection errors."""
self.logger.error("AMQP Listener: Connection Error: %s. " % exc
+ "Trying again in %d seconds..." % interval)
def _establish_connection():
"""Establish a connection to the AMQP broker."""
conn = DjangoBrokerConnection()
connected = conn.connection # Connection is established lazily.
return conn
if not AMQP_CONNECTION_RETRY:
return _establish_connection()
conn = retry_over_time(_establish_connection, socket.error,
errback=_connection_error_handler,
max_retries=AMQP_CONNECTION_MAX_RETRIES)
self.logger.debug("AMQPListener: Connection Established.")
return conn
class WorkController(object):
"""Executes tasks waiting in the task queue.
:param concurrency: see :attr:`concurrency`.
:param logfile: see :attr:`logfile`.
:param loglevel: see :attr:`loglevel`.
.. attribute:: concurrency
The number of simultaneous processes doing work (default:
:const:`celery.conf.DAEMON_CONCURRENCY`)
.. attribute:: loglevel
The loglevel used (default: :const:`logging.INFO`)
.. attribute:: logfile
The logfile used, if no logfile is specified it uses ``stderr``
(default: :const:`celery.conf.DAEMON_LOG_FILE`).
.. attribute:: logger
The :class:`logging.Logger` instance used for logging.
.. attribute:: is_detached
Flag describing if the worker is running as a daemon or not.
.. attribute:: pool
The :class:`multiprocessing.Pool` instance used.
.. attribute:: bucket_queue
The :class:`Queue.Queue` that holds tasks ready for immediate
processing.
.. attribute:: hold_queue
The :class:`Queue.Queue` that holds paused tasks. Reasons for holding
back the task include waiting for ``eta`` to pass or the task is being
retried.
.. attribute:: periodic_work_controller
Instance of :class:`celery.worker.controllers.PeriodicWorkController`.
.. attribute:: mediator
Instance of :class:`celery.worker.controllers.Mediator`.
.. attribute:: amqp_listener
Instance of :class:`AMQPListener`.
"""
loglevel = logging.ERROR
concurrency = DAEMON_CONCURRENCY
logfile = DAEMON_LOG_FILE
_state = None
def __init__(self, concurrency=None, logfile=None, loglevel=None,
is_detached=False):
# Options
self.loglevel = loglevel or self.loglevel
self.concurrency = concurrency or self.concurrency
self.logfile = logfile or self.logfile
self.is_detached = is_detached
self.logger = setup_logger(loglevel, logfile)
# Queues
self.bucket_queue = Queue()
self.hold_queue = Queue()
self.logger.debug("Instantiating thread components...")
# Threads+Pool
self.periodic_work_controller = PeriodicWorkController(
self.bucket_queue,
self.hold_queue)
self.pool = TaskPool(self.concurrency, logger=self.logger)
self.amqp_listener = AMQPListener(self.bucket_queue, self.hold_queue,
logger=self.logger,
initial_prefetch_count=concurrency)
self.mediator = Mediator(self.bucket_queue, self.safe_process_task)
# The order is important here;
# the first in the list is the first to start,
# and they must be stopped in reverse order.
self.components = [self.pool,
self.mediator,
self.periodic_work_controller,
self.amqp_listener]
def start(self):
"""Starts the workers main loop."""
self._state = "RUN"
try:
for component in self.components:
self.logger.debug("Starting thread %s..." % \
component.__class__.__name__)
component.start()
finally:
self.stop()
def safe_process_task(self, task):
"""Same as :meth:`process_task`, but catches all exceptions
the task raises and log them as errors, to make sure the
worker doesn't die."""
try:
try:
self.process_task(task)
except Exception, exc:
self.logger.critical("Internal error %s: %s\n%s" % (
exc.__class__, exc, traceback.format_exc()))
except (SystemExit, KeyboardInterrupt):
self.stop()
def process_task(self, task):
"""Process task by sending it to the pool of workers."""
task.execute_using_pool(self.pool, self.loglevel, self.logfile)
def stop(self):
"""Gracefully shutdown the worker server."""
# shut down the periodic work controller thread
if self._state != "RUN":
return
[component.stop() for component in reversed(self.components)]
self._state = "STOP"
| [
"[email protected]"
] | |
34bb012d42ec90f93b307b447f5c5cd8c6a26646 | c7a1c1ae40e9d95dfb92251dcfbf3c5010e6ba81 | /sensehat/pi_surveillance_py.py | 260dc24e20057985e9e1a46675745b948e2da882 | [] | no_license | pranavlathigara/Raspberry-Pi-DIY-Projects | efd18e2e5b9b8369bb1a5f5418782480cf9bc729 | 0c14c316898d4d06015912ac4a8cb7b71a3980c0 | refs/heads/master | 2021-04-06T09:14:28.088223 | 2018-02-19T00:15:22 | 2018-02-19T00:15:22 | 124,649,553 | 1 | 2 | null | 2018-03-10T11:30:59 | 2018-03-10T11:30:59 | null | UTF-8 | Python | false | false | 3,605 | py | from pyimagesearch.tempimage import TempImage
import dropbox as dbx
from picamera.array import PiRGBArray
from picamera import PiCamera
import warnings
import datetime
import imutils
import json
import time
import cv2
# filter warnings, load the configuration and initialize the Dropbox
# client
warnings.filterwarnings("ignore")
client = None
# Put your token here:
db = dbx.Dropbox("YOUR_TOKEN_HERE")
# initialize the camera and grab a reference to the raw camera capture
camera = PiCamera()
camera.resolution = (640,480)
camera.framerate = 16
rawCapture = PiRGBArray(camera, size=(640,480))
# allow the camera to warmup, then initialize the average frame, last
# uploaded timestamp, and frame motion counter
print "[INFO] warming up..."
time.sleep(2.5)
avg = None
lastUploaded = datetime.datetime.now()
motionCounter = 0
# capture frames from the camera
for f in camera.capture_continuous(rawCapture, format="bgr", use_video_port=True):
# grab the raw NumPy array representing the image and initialize
# the timestamp and occupied/unoccupied text
frame = f.array
timestamp = datetime.datetime.now()
# resize the frame, convert it to grayscale, and blur it
frame = imutils.resize(frame, width=500)
gray = cv2.cvtColor(frame, cv2.COLOR_BGR2GRAY)
gray = cv2.GaussianBlur(gray, (21, 21), 0)
# if the average frame is None, initialize it
if avg is None:
print "[INFO] starting background model..."
avg = gray.copy().astype("float")
rawCapture.truncate(0)
continue
# accumulate the weighted average between the current frame and
# previous frames, then compute the difference between the current
# frame and running average
cv2.accumulateWeighted(gray, avg, 0.5)
frameDelta = cv2.absdiff(gray, cv2.convertScaleAbs(avg))
# threshold the delta image, dilate the thresholded image to fill
# in holes, then find contours on thresholded image
thresh = cv2.threshold(frameDelta, 5, 255,
cv2.THRESH_BINARY)[1]
thresh = cv2.dilate(thresh, None, iterations=2)
(cnts, _) = cv2.findContours(thresh.copy(), cv2.RETR_EXTERNAL,
cv2.CHAIN_APPROX_SIMPLE)
# loop over the contours
for c in cnts:
# if the contour is too small, ignore it
if cv2.contourArea(c) < 5000:
continue
# compute the bounding box for the contour, draw it on the frame,
# and update the text
(x, y, w, h) = cv2.boundingRect(c)
cv2.rectangle(frame, (x, y), (x + w, y + h), (0, 255, 0), 2)
text = "!"
# draw the text and timestamp on the frame
ts = timestamp.strftime("%A %d %B %Y %I:%M:%S%p")
cv2.putText(frame, "{}".format(ts), (10, 20),
cv2.FONT_HERSHEY_SIMPLEX, 0.5, (0, 0, 255), 2)
# check to see if the room is occupied
if text == "!":
# check to see if enough time has passed between uploads
if (timestamp - lastUploaded).seconds >= 3.0:
# increment the motion counter
motionCounter += 1
# check to see if the number of frames with consistent motion is
# high enough
if motionCounter >= 8:
# write the image to temporary file
t = TempImage()
cv2.imwrite(t.path, frame)
print "[UPLOAD] {}".format(ts)
path = "{base_path}/{timestamp}.jpg".format(base_path="/", timestamp=ts)
client.put_file(open(t.path, "rb").read(), path)
t.cleanup()
# update the last uploaded timestamp and reset the motion
# counter
lastUploaded = timestamp
motionCounter = 0
# otherwise, the room is not occupied
else:
motionCounter = 0
# clear the stream in preparation for the next frame
rawCapture.truncate(0) | [
"[email protected]"
] | |
a9edbeaf88bade93d05aedb3c436f9b864421475 | 5139e63dfbc2b01a10b20bdd283005bfb64bc3e1 | /api/api.py | 998d101f9f00203f1225a882ce89d54334c0ff78 | [] | no_license | Merevoli-DatLuu/SGUInfo | 121098a67128d3ede72ce9f9f51955637c22fb9c | 501d676ad1e02f00573cc879fbba6c44ab1b0ffb | refs/heads/master | 2023-05-26T08:50:41.899513 | 2021-01-11T16:11:45 | 2021-01-11T16:11:45 | 281,350,587 | 4 | 1 | null | 2023-05-22T23:38:11 | 2020-07-21T09:13:00 | Python | UTF-8 | Python | false | false | 1,848 | py | from flask import Flask, render_template, request, jsonify
import sys
sys.path.append("..")
from sguinfo import sguinfo
app = Flask(__name__)
@app.route("/api/v1/students", methods=['GET'])
def get_student_list():
sgu = sguinfo()
if "from_id" in request.args and "to_id" in request.args and "id_list" not in request.args:
from_id = request.args['from_id']
to_id = request.args['to_id']
if sgu.validate_range_mssv(from_id, to_id):
data = []
for d in sgu.find_range_info(from_id, to_id):
data.append(sgu.change_to_eng_info(d))
return jsonify(data)
else:
return jsonify({})
elif "from_id" not in request.args and "to_id" not in request.args and "id_list" in request.args:
list_id = request.args['id_list'].split(",")
data = []
for id in list_id:
if sgu.validate_mssv(id):
data.append(sgu.change_to_eng_info(sgu.find_info(id)))
return jsonify(data)
else:
return jsonify({})
@app.route("/api/v1/students/<id>", methods = ['GET'])
def get_a_student(id):
sgu = sguinfo()
if sgu.validate_mssv(id):
return jsonify(sgu.change_to_eng_info(sgu.find_info(id)))
else:
return jsonify({})
@app.route("/api/v1/students/<id>/<param>", methods = ['GET'])
def get_a_student_with_param(id, param):
sgu = sguinfo()
if sgu.validate_mssv(id):
data = sgu.change_to_eng_info(sgu.find_info(id))
if param in data.keys():
return jsonify(data[param])
else:
return jsonify({})
else:
return jsonify({})
@app.route("/test")
def tessst():
return request.args
if __name__ == '__main__':
app.config['JSON_AS_ASCII'] = False
app.config['JSON_SORT_KEYS'] = False
app.run(debug = True) | [
"[email protected]"
] | |
33f504c5e1c391f90e11226e1c15be67091ee79f | 0124528676ee3bbaec60df5d6950b408e6da37c8 | /Projects/QTPy/circuitpython-community-bundle-7.x-mpy-20220601/examples/animation/main.py | ee50a4f811bdd29fdf5d3d51de532f353ba0b5a1 | [
"LicenseRef-scancode-warranty-disclaimer"
] | no_license | land-boards/lb-boards | 8127658dc537dcfde0bb59a5018ab75c3f0087f6 | eeb98cc2003dac1924845d949f6f5bd387376568 | refs/heads/master | 2023-06-07T15:44:46.110742 | 2023-06-02T22:53:24 | 2023-06-02T22:53:24 | 4,847,305 | 10 | 12 | null | null | null | null | UTF-8 | Python | false | false | 1,421 | py | import board
import dotstar_featherwing
wing = dotstar_featherwing.DotstarFeatherwing(board.D13, board.D11)
xmas_colors = {'w': ( 32, 32, 32),
'W': (255, 255, 255),
'G': ( 0, 32, 0),
'y': ( 32, 32, 0),
'Y': (255, 255, 0)}
xmas_animation = [["..y.w......w",
"..G.....w...",
"..G..w....w.",
".GGG...w....",
"GGGGG.......",
"wwwwwwwwwwww"],
["..y.........",
"..G.W......w",
"..G.....w...",
".GGG.w....W.",
"GGGGG..w....",
"wwwwwwwwwwww"],
["..Y....W....",
"..G.........",
"..G.w......w",
".GGG....w...",
"GGGGGw....W.",
"wwwwwwwwwwww"],
["..y..w....w.",
"..G....W....",
"..G.........",
".GGGW......w",
"GGGGG...w...",
"wwwwwwwwwwww"],
["..Y.....w...",
"..G..w....W.",
"..G....w....",
".GGG........",
"GGGGG......W",
"wwwwwwwwwwww"]]
wing.display_animation(xmas_animation, xmas_colors, 10000, 0.05)
| [
"[email protected]"
] | |
997a2a9aa16da7c874e599ae181d4bd45503f1e8 | f82757475ea13965581c2147ff57123b361c5d62 | /gi-stubs/repository/EDataServer/SourceCredentialsProviderImpl.py | 281ee12030f4bf3eeecff51d446fa85a2b655621 | [] | no_license | ttys3/pygobject-stubs | 9b15d1b473db06f47e5ffba5ad0a31d6d1becb57 | d0e6e93399212aada4386d2ce80344eb9a31db48 | refs/heads/master | 2022-09-23T12:58:44.526554 | 2020-06-06T04:15:00 | 2020-06-06T04:15:00 | 269,693,287 | 8 | 2 | null | 2020-06-05T15:57:54 | 2020-06-05T15:57:54 | null | UTF-8 | Python | false | false | 17,806 | py | # encoding: utf-8
# module gi.repository.EDataServer
# from /usr/lib64/girepository-1.0/EDataServer-1.2.typelib
# by generator 1.147
"""
An object which wraps an introspection typelib.
This wrapping creates a python module like representation of the typelib
using gi repository as a foundation. Accessing attributes of the module
will dynamically pull them in and create wrappers for the members.
These members are then cached on this introspection module.
"""
# imports
import gi as __gi
import gi.overrides.GObject as __gi_overrides_GObject
import gi.repository.Gio as __gi_repository_Gio
import gi.repository.GObject as __gi_repository_GObject
import gi.repository.Soup as __gi_repository_Soup
import gobject as __gobject
from .Extension import Extension
class SourceCredentialsProviderImpl(Extension):
"""
:Constructors:
::
SourceCredentialsProviderImpl(**properties)
"""
def bind_property(self, *args, **kwargs): # real signature unknown
pass
def bind_property_full(self, *args, **kargs): # reliably restored by inspect
# no doc
pass
def can_process(self, source): # real signature unknown; restored from __doc__
""" can_process(self, source:EDataServer.Source) -> bool """
return False
def can_prompt(self): # real signature unknown; restored from __doc__
""" can_prompt(self) -> bool """
return False
def can_store(self): # real signature unknown; restored from __doc__
""" can_store(self) -> bool """
return False
def chain(self, *args, **kwargs): # real signature unknown
pass
def compat_control(self, *args, **kargs): # reliably restored by inspect
# no doc
pass
def connect(self, *args, **kwargs): # real signature unknown
pass
def connect_after(self, *args, **kwargs): # real signature unknown
pass
def connect_data(self, detailed_signal, handler, *data, **kwargs): # reliably restored by inspect
"""
Connect a callback to the given signal with optional user data.
:param str detailed_signal:
A detailed signal to connect to.
:param callable handler:
Callback handler to connect to the signal.
:param *data:
Variable data which is passed through to the signal handler.
:param GObject.ConnectFlags connect_flags:
Flags used for connection options.
:returns:
A signal id which can be used with disconnect.
"""
pass
def connect_object(self, *args, **kwargs): # real signature unknown
pass
def connect_object_after(self, *args, **kwargs): # real signature unknown
pass
def delete_sync(self, source, cancellable=None): # real signature unknown; restored from __doc__
""" delete_sync(self, source:EDataServer.Source, cancellable:Gio.Cancellable=None) -> bool """
return False
def disconnect(*args, **kwargs): # reliably restored by inspect
""" signal_handler_disconnect(instance:GObject.Object, handler_id:int) """
pass
def disconnect_by_func(self, *args, **kwargs): # real signature unknown
pass
def do_can_process(self, *args, **kwargs): # real signature unknown
""" can_process(self, source:EDataServer.Source) -> bool """
pass
def do_can_prompt(self, *args, **kwargs): # real signature unknown
""" can_prompt(self) -> bool """
pass
def do_can_store(self, *args, **kwargs): # real signature unknown
""" can_store(self) -> bool """
pass
def do_delete_sync(self, *args, **kwargs): # real signature unknown
""" delete_sync(self, source:EDataServer.Source, cancellable:Gio.Cancellable=None) -> bool """
pass
def do_lookup_sync(self, *args, **kwargs): # real signature unknown
""" lookup_sync(self, source:EDataServer.Source, cancellable:Gio.Cancellable=None) -> bool, out_credentials:EDataServer.NamedParameters """
pass
def do_store_sync(self, *args, **kwargs): # real signature unknown
""" store_sync(self, source:EDataServer.Source, credentials:EDataServer.NamedParameters, permanently:bool, cancellable:Gio.Cancellable=None) -> bool """
pass
def emit(self, *args, **kwargs): # real signature unknown
pass
def emit_stop_by_name(self, detailed_signal): # reliably restored by inspect
""" Deprecated, please use stop_emission_by_name. """
pass
def find_property(self, property_name): # real signature unknown; restored from __doc__
""" find_property(self, property_name:str) -> GObject.ParamSpec """
pass
def force_floating(self, *args, **kargs): # reliably restored by inspect
# no doc
pass
def freeze_notify(self): # reliably restored by inspect
"""
Freezes the object's property-changed notification queue.
:returns:
A context manager which optionally can be used to
automatically thaw notifications.
This will freeze the object so that "notify" signals are blocked until
the thaw_notify() method is called.
.. code-block:: python
with obj.freeze_notify():
pass
"""
pass
def getv(self, names, values): # real signature unknown; restored from __doc__
""" getv(self, names:list, values:list) """
pass
def get_data(self, *args, **kargs): # reliably restored by inspect
# no doc
pass
def get_extensible(self): # real signature unknown; restored from __doc__
""" get_extensible(self) -> EDataServer.Extensible """
pass
def get_properties(self, *args, **kwargs): # real signature unknown
pass
def get_property(self, *args, **kwargs): # real signature unknown
pass
def get_provider(self): # real signature unknown; restored from __doc__
""" get_provider(self) """
pass
def get_qdata(self, *args, **kargs): # reliably restored by inspect
# no doc
pass
def handler_block(obj, handler_id): # reliably restored by inspect
"""
Blocks the signal handler from being invoked until
handler_unblock() is called.
:param GObject.Object obj:
Object instance to block handlers for.
:param int handler_id:
Id of signal to block.
:returns:
A context manager which optionally can be used to
automatically unblock the handler:
.. code-block:: python
with GObject.signal_handler_block(obj, id):
pass
"""
pass
def handler_block_by_func(self, *args, **kwargs): # real signature unknown
pass
def handler_disconnect(*args, **kwargs): # reliably restored by inspect
""" signal_handler_disconnect(instance:GObject.Object, handler_id:int) """
pass
def handler_is_connected(*args, **kwargs): # reliably restored by inspect
""" signal_handler_is_connected(instance:GObject.Object, handler_id:int) -> bool """
pass
def handler_unblock(*args, **kwargs): # reliably restored by inspect
""" signal_handler_unblock(instance:GObject.Object, handler_id:int) """
pass
def handler_unblock_by_func(self, *args, **kwargs): # real signature unknown
pass
def install_properties(self, pspecs): # real signature unknown; restored from __doc__
""" install_properties(self, pspecs:list) """
pass
def install_property(self, property_id, pspec): # real signature unknown; restored from __doc__
""" install_property(self, property_id:int, pspec:GObject.ParamSpec) """
pass
def interface_find_property(self, *args, **kargs): # reliably restored by inspect
# no doc
pass
def interface_install_property(self, *args, **kargs): # reliably restored by inspect
# no doc
pass
def interface_list_properties(self, *args, **kargs): # reliably restored by inspect
# no doc
pass
def is_floating(self): # real signature unknown; restored from __doc__
""" is_floating(self) -> bool """
return False
def list_properties(self): # real signature unknown; restored from __doc__
""" list_properties(self) -> list, n_properties:int """
return []
def lookup_sync(self, source, cancellable=None): # real signature unknown; restored from __doc__
""" lookup_sync(self, source:EDataServer.Source, cancellable:Gio.Cancellable=None) -> bool, out_credentials:EDataServer.NamedParameters """
return False
def newv(self, object_type, parameters): # real signature unknown; restored from __doc__
""" newv(object_type:GType, parameters:list) -> GObject.Object """
pass
def notify(self, property_name): # real signature unknown; restored from __doc__
""" notify(self, property_name:str) """
pass
def notify_by_pspec(self, *args, **kargs): # reliably restored by inspect
# no doc
pass
def override_property(self, property_id, name): # real signature unknown; restored from __doc__
""" override_property(self, property_id:int, name:str) """
pass
def ref(self, *args, **kargs): # reliably restored by inspect
# no doc
pass
def ref_sink(self, *args, **kargs): # reliably restored by inspect
# no doc
pass
def replace_data(self, *args, **kargs): # reliably restored by inspect
# no doc
pass
def replace_qdata(self, *args, **kargs): # reliably restored by inspect
# no doc
pass
def run_dispose(self, *args, **kargs): # reliably restored by inspect
# no doc
pass
def set_data(self, *args, **kargs): # reliably restored by inspect
# no doc
pass
def set_properties(self, *args, **kwargs): # real signature unknown
pass
def set_property(self, *args, **kwargs): # real signature unknown
pass
def steal_data(self, *args, **kargs): # reliably restored by inspect
# no doc
pass
def steal_qdata(self, *args, **kargs): # reliably restored by inspect
# no doc
pass
def stop_emission(self, detailed_signal): # reliably restored by inspect
""" Deprecated, please use stop_emission_by_name. """
pass
def stop_emission_by_name(*args, **kwargs): # reliably restored by inspect
""" signal_stop_emission_by_name(instance:GObject.Object, detailed_signal:str) """
pass
def store_sync(self, source, credentials, permanently, cancellable=None): # real signature unknown; restored from __doc__
""" store_sync(self, source:EDataServer.Source, credentials:EDataServer.NamedParameters, permanently:bool, cancellable:Gio.Cancellable=None) -> bool """
return False
def thaw_notify(self): # real signature unknown; restored from __doc__
""" thaw_notify(self) """
pass
def unref(self, *args, **kargs): # reliably restored by inspect
# no doc
pass
def watch_closure(self, *args, **kargs): # reliably restored by inspect
# no doc
pass
def weak_ref(self, *args, **kwargs): # real signature unknown
pass
def _force_floating(self, *args, **kwargs): # real signature unknown
""" force_floating(self) """
pass
def _ref(self, *args, **kwargs): # real signature unknown
""" ref(self) -> GObject.Object """
pass
def _ref_sink(self, *args, **kwargs): # real signature unknown
""" ref_sink(self) -> GObject.Object """
pass
def _unref(self, *args, **kwargs): # real signature unknown
""" unref(self) """
pass
def _unsupported_data_method(self, *args, **kargs): # reliably restored by inspect
# no doc
pass
def _unsupported_method(self, *args, **kargs): # reliably restored by inspect
# no doc
pass
def __copy__(self, *args, **kwargs): # real signature unknown
pass
def __deepcopy__(self, *args, **kwargs): # real signature unknown
pass
def __delattr__(self, *args, **kwargs): # real signature unknown
""" Implement delattr(self, name). """
pass
def __dir__(self, *args, **kwargs): # real signature unknown
""" Default dir() implementation. """
pass
def __eq__(self, *args, **kwargs): # real signature unknown
""" Return self==value. """
pass
def __format__(self, *args, **kwargs): # real signature unknown
""" Default object formatter. """
pass
def __getattribute__(self, *args, **kwargs): # real signature unknown
""" Return getattr(self, name). """
pass
def __ge__(self, *args, **kwargs): # real signature unknown
""" Return self>=value. """
pass
def __gt__(self, *args, **kwargs): # real signature unknown
""" Return self>value. """
pass
def __hash__(self, *args, **kwargs): # real signature unknown
""" Return hash(self). """
pass
def __init_subclass__(self, *args, **kwargs): # real signature unknown
"""
This method is called when a class is subclassed.
The default implementation does nothing. It may be
overridden to extend subclasses.
"""
pass
def __init__(self, **properties): # real signature unknown; restored from __doc__
pass
def __le__(self, *args, **kwargs): # real signature unknown
""" Return self<=value. """
pass
def __lt__(self, *args, **kwargs): # real signature unknown
""" Return self<value. """
pass
@staticmethod # known case of __new__
def __new__(*args, **kwargs): # real signature unknown
""" Create and return a new object. See help(type) for accurate signature. """
pass
def __ne__(self, *args, **kwargs): # real signature unknown
""" Return self!=value. """
pass
def __reduce_ex__(self, *args, **kwargs): # real signature unknown
""" Helper for pickle. """
pass
def __reduce__(self, *args, **kwargs): # real signature unknown
""" Helper for pickle. """
pass
def __repr__(self, *args, **kwargs): # real signature unknown
""" Return repr(self). """
pass
def __setattr__(self, *args, **kwargs): # real signature unknown
""" Implement setattr(self, name, value). """
pass
def __sizeof__(self, *args, **kwargs): # real signature unknown
""" Size of object in memory, in bytes. """
pass
def __str__(self, *args, **kwargs): # real signature unknown
""" Return str(self). """
pass
def __subclasshook__(self, *args, **kwargs): # real signature unknown
"""
Abstract classes can override this to customize issubclass().
This is invoked early on by abc.ABCMeta.__subclasscheck__().
It should return True, False or NotImplemented. If it returns
NotImplemented, the normal algorithm is used. Otherwise, it
overrides the normal algorithm (and the outcome is cached).
"""
pass
g_type_instance = property(lambda self: object(), lambda self, v: None, lambda self: None) # default
parent = property(lambda self: object(), lambda self, v: None, lambda self: None) # default
priv = property(lambda self: object(), lambda self, v: None, lambda self: None) # default
qdata = property(lambda self: object(), lambda self, v: None, lambda self: None) # default
ref_count = property(lambda self: object(), lambda self, v: None, lambda self: None) # default
__gpointer__ = property(lambda self: object(), lambda self, v: None, lambda self: None) # default
__grefcount__ = property(lambda self: object(), lambda self, v: None, lambda self: None) # default
props = None # (!) real value is '<gi._gi.GProps object at 0x7f626e8ec550>'
__class__ = None # (!) real value is "<class 'gi.types.GObjectMeta'>"
__dict__ = None # (!) real value is "mappingproxy({'__info__': ObjectInfo(SourceCredentialsProviderImpl), '__module__': 'gi.repository.EDataServer', '__gtype__': <GType ESourceCredentialsProviderImpl (94877537146240)>, '__doc__': None, '__gsignals__': {}, 'can_process': gi.FunctionInfo(can_process), 'can_prompt': gi.FunctionInfo(can_prompt), 'can_store': gi.FunctionInfo(can_store), 'delete_sync': gi.FunctionInfo(delete_sync), 'get_provider': gi.FunctionInfo(get_provider), 'lookup_sync': gi.FunctionInfo(lookup_sync), 'store_sync': gi.FunctionInfo(store_sync), 'do_can_process': gi.VFuncInfo(can_process), 'do_can_prompt': gi.VFuncInfo(can_prompt), 'do_can_store': gi.VFuncInfo(can_store), 'do_delete_sync': gi.VFuncInfo(delete_sync), 'do_lookup_sync': gi.VFuncInfo(lookup_sync), 'do_store_sync': gi.VFuncInfo(store_sync), 'parent': <property object at 0x7f626e926e00>, 'priv': <property object at 0x7f626e926ef0>})"
__gdoc__ = 'Object ESourceCredentialsProviderImpl\n\nProperties from EExtension:\n extensible -> EExtensible: Extensible Object\n The object being extended\n\nSignals from GObject:\n notify (GParam)\n\n'
__gsignals__ = {}
__gtype__ = None # (!) real value is '<GType ESourceCredentialsProviderImpl (94877537146240)>'
__info__ = ObjectInfo(SourceCredentialsProviderImpl)
| [
"[email protected]"
] | |
4ffcafc58e0e171a78a295d77ad213c80a5bb0e5 | 5d2404f62e58d5fd1f6112744ff32c3166183ac7 | /Exercicios/ex036.py | 6fc9f4561d2c0ecd7c5e81514824facf4042177e | [] | no_license | Leownhart/My_Course_of_python | 236cfc84d841c5883e5aa1cc0c0730e7a9a83c40 | 5abb21f8cdad91ab54247a007d40bf9ecd2cff8c | refs/heads/master | 2020-08-28T15:04:33.628086 | 2020-08-24T19:25:39 | 2020-08-24T19:25:39 | 217,733,877 | 1 | 0 | null | null | null | null | UTF-8 | Python | false | false | 536 | py | valorcasa = float(input('Informe o valor da imovel: R$ '))
salcom = float(input('Informe o sálario do comprador: R$ '))
anos = int(input('Informe o tempo de financiamento em anos: '))
valpresta = (valorcasa / anos) / 12 # casa / (anos / * 12)
porcent = salcom * 30.0 / 100
print('Para pagar uma casa de R${:.2f} em {} anos a '
'prestação será de R${:.2f} mensais'.format(valorcasa, anos, valpresta))
if valpresta > porcent:
print('\033[31mEmpréstimo NEGADO!\033[m')
else:
print('\033[32mEmpréstimo APROVADO!\033[m')
| [
"[email protected]"
] | |
9f6ac6ecefb20871f98905fe6225b28a48eaf51d | f0d713996eb095bcdc701f3fab0a8110b8541cbb | /9szPm9Mg5D2vJyTvf_14.py | c4b1eb7103a2e128742d7e447be9653582eade63 | [] | no_license | daniel-reich/turbo-robot | feda6c0523bb83ab8954b6d06302bfec5b16ebdf | a7a25c63097674c0a81675eed7e6b763785f1c41 | refs/heads/main | 2023-03-26T01:55:14.210264 | 2021-03-23T16:08:01 | 2021-03-23T16:08:01 | 350,773,815 | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 681 | py | """
Write a function that takes three arguments `(x, y, z)` and returns a list
containing `x` sublists (e.g. `[[], [], []]`), each containing `y` number of
item `z`.
* `x` Number of sublists contained within the main list.
* `y` Number of items contained within each sublist.
* `z` Item contained within each sublist.
### Examples
matrix(3, 2, 3) ➞ [[3, 3], [3, 3], [3, 3]]
matrix(2, 1, "edabit") ➞ [["edabit"], ["edabit"]]
matrix(3, 2, 0) ➞ [[0, 0], [0, 0], [0, 0]]
### Notes
* The first two arguments will always be integers.
* The third argument is either a string or an integer.
"""
def matrix(x, y, z):
return [[z] * y] * x
| [
"[email protected]"
] | |
d5cd7cfe45515f1a0899cf0344254ae70d9a69c6 | 8ef8e6818c977c26d937d09b46be0d748022ea09 | /cv/3d_detection/pointnet2/pytorch/mmdetection3d/mmdet/version.py | 0e03a9d35749aef5d396e532d5ab8c5a0bae223f | [
"Apache-2.0"
] | permissive | Deep-Spark/DeepSparkHub | eb5996607e63ccd2c706789f64b3cc0070e7f8ef | 9d643e88946fc4a24f2d4d073c08b05ea693f4c5 | refs/heads/master | 2023-09-01T11:26:49.648759 | 2023-08-25T01:50:18 | 2023-08-25T01:50:18 | 534,133,249 | 7 | 6 | Apache-2.0 | 2023-03-28T02:54:59 | 2022-09-08T09:07:01 | Python | UTF-8 | Python | false | false | 529 | py | # Copyright (c) OpenMMLab. All rights reserved.
__version__ = '2.24.0'
short_version = __version__
def parse_version_info(version_str):
version_info = []
for x in version_str.split('.'):
if x.isdigit():
version_info.append(int(x))
elif x.find('rc') != -1:
patch_version = x.split('rc')
version_info.append(int(patch_version[0]))
version_info.append(f'rc{patch_version[1]}')
return tuple(version_info)
version_info = parse_version_info(__version__)
| [
"[email protected]"
] | |
a8694b72dc9f4ac269b718d8c743574a18cfc288 | 1fc45a47f0e540941c87b04616f3b4019da9f9a0 | /tests/sentry/api/endpoints/test_commit_filechange.py | 49eefdcd009d8d4020c56be8b1609185bc95f982 | [
"BSD-2-Clause"
] | permissive | seukjung/sentry-8.15.0 | febc11864a74a68ddb97b146cc1d2438ef019241 | fd3cab65c64fcbc32817885fa44df65534844793 | refs/heads/master | 2022-10-28T06:39:17.063333 | 2018-01-17T12:31:55 | 2018-01-17T12:31:55 | 117,833,103 | 0 | 0 | BSD-3-Clause | 2022-10-05T18:09:54 | 2018-01-17T12:28:13 | Python | UTF-8 | Python | false | false | 2,225 | py | from __future__ import absolute_import
from django.core.urlresolvers import reverse
from sentry.models import Commit, CommitFileChange, Release, ReleaseCommit, Repository
from sentry.testutils import APITestCase
class CommitFileChangeTest(APITestCase):
def test_simple(self):
project = self.create_project(
name='foo',
)
release = Release.objects.create(
organization_id=project.organization_id,
version='1',
)
release.add_project(project)
repo = Repository.objects.create(
organization_id=project.organization_id,
name=project.name,
)
commit = Commit.objects.create(
organization_id=project.organization_id,
repository_id=repo.id,
key='a' * 40,
)
commit2 = Commit.objects.create(
organization_id=project.organization_id,
repository_id=repo.id,
key='b' * 40,
)
ReleaseCommit.objects.create(
organization_id=project.organization_id,
release=release,
commit=commit,
order=1,
)
ReleaseCommit.objects.create(
organization_id=project.organization_id,
release=release,
commit=commit2,
order=0,
)
CommitFileChange.objects.create(
organization_id=project.organization_id,
commit=commit,
filename='.gitignore',
type='M'
)
CommitFileChange.objects.create(
organization_id=project.organization_id,
commit=commit2,
filename='/static/js/widget.js',
type='A'
)
url = reverse('sentry-api-0-release-commitfilechange', kwargs={
'organization_slug': project.organization.slug,
'version': release.version,
})
self.login_as(user=self.user)
response = self.client.get(url)
assert response.status_code == 200, response.content
assert len(response.data) == 2
assert response.data[0]['filename'] == '.gitignore'
assert response.data[1]['filename'] == '/static/js/widget.js'
| [
"[email protected]"
] | |
63e3fa0e7d86c5133e69ba329a533e4edfdc34c1 | 0d4ec25fb2819de88a801452f176500ccc269724 | /sub_two_binaries.py | d4f6682fa6bf8cad577240ddabce0a9eaa7818a1 | [] | no_license | zopepy/leetcode | 7f4213764a6a079f58402892bd0ede0514e06fcf | 3bfee704adb1d94efc8e531b732cf06c4f8aef0f | refs/heads/master | 2022-01-09T16:13:09.399620 | 2019-05-29T20:00:11 | 2019-05-29T20:00:11 | null | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 596 | py | class Solution:
def addBinary(self, a, b):
"""
:type a: str
:type b: str
:rtype: str
"""
s = ""
a,b = a[::-1], b[::-1]
la,lb = len(a), len(b)
l = max(la, lb)
i = 0
carry = 0
while i<l or carry==1:
b1 = int(a[i] if i<la else 0)
b2 = int(b[i] if i<lb else 0)
curbit = b1^b2^carry
carry = (b1&b2)|(carry&(b1|b2))
s += str(curbit)
# print(curbit, carry)
i+=1
return s[::-1]
a,b="000", "000000"
print(Solution().addBinary(a,b))
| [
"[email protected]"
] | |
cc5695f1470140f25b2cb77800818102059fa4d6 | f0d713996eb095bcdc701f3fab0a8110b8541cbb | /kdhgEC2ECXAfoXWQP_1.py | 18cfc39baa91a8ce324e7628429be8a4c0702226 | [] | no_license | daniel-reich/turbo-robot | feda6c0523bb83ab8954b6d06302bfec5b16ebdf | a7a25c63097674c0a81675eed7e6b763785f1c41 | refs/heads/main | 2023-03-26T01:55:14.210264 | 2021-03-23T16:08:01 | 2021-03-23T16:08:01 | 350,773,815 | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 1,119 | py | """
In this challenge, you have to obtain a sentence from the elements of a given
matrix. In the matrix, each word of the sentence follows a columnar order from
the top to the bottom, instead of the usual left-to-right order: it's time for
**transposition**!
Given a matrix `mtx`, implement a function that returns the complete sentence
as a string, with the words separated by a space between them.
### Examples
transpose_matrix([
["Enter"],
["the"],
["Matrix!"]
]) ➞ "Enter the Matrix!"
transpose_matrix([
["The", "are"],
["columns", "rows."]
]) ➞ "The columns are rows."
transpose_matrix([
["You", "the"],
["must", "table"],
["transpose", "order."]
]) ➞ "You must transpose the table order."
### Notes
* All given matrices are regular, as to say that each column has the same length.
* Punctuation is already given, you just have to add the spaces in the returned string.
"""
def transpose_matrix(mtx):
result = ""
for i in range(len(mtx[0])):
for j in mtx:
result += j[i]+" "
return result[:-1]
| [
"[email protected]"
] | |
3da334d08f98f8cf06aa4794ea35ab1bdecc8c8a | 8c8159691382ab8759ec637a97ef107ba898ad4c | /Recursive/removeInvalidParentheses.py | 44953cd000adfcd6e1707c07b5da6c12c0038303 | [] | no_license | windhaunting/Coding_practices | 3c89cddaeb13bfe36eab7ff664d6e16d0e86d46f | 8375988ac391376159438877b6729bb94340106b | refs/heads/master | 2021-02-05T21:40:07.858445 | 2020-02-28T19:25:29 | 2020-02-28T19:25:29 | 243,836,816 | 0 | 1 | null | null | null | null | UTF-8 | Python | false | false | 690 | py | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Tue Jan 16 16:43:09 2018
@author: fubao
"""
#301. Remove Invalid Parentheses
'''
Remove the minimum number of invalid parentheses in order to make the input string valid. Return all possible results.
Note: The input string may contain letters other than the parentheses ( and ).
Examples:
"()())()" -> ["()()()", "(())()"]
"(a)())()" -> ["(a)()()", "(a())()"]
")(" -> [""]
'''
#reference: http://zxi.mytechroad.com/blog/searching/leetcode-301-remove-invalid-parentheses/
class Solution(object):
def removeInvalidParentheses(self, s):
"""
:type s: str
:rtype: List[str]
"""
| [
"[email protected]"
] | |
6017ff5d62258b8bdc613d2deb7b6f19177ac641 | d01fa1b6668c66236405b799e39e529d1492af7c | /{{cookiecutter.project_slug}}/pages/migrations/0016_sitebranding.py | 9068f89e8055a2b76d16b1f85251befee436df7b | [
"MIT",
"BSD-3-Clause",
"LicenseRef-scancode-free-unknown",
"Apache-2.0"
] | permissive | chrisdev/wagtail-cookiecutter-foundation | 426ffd974aa08ab10e4b0e44d5003476c597f2e4 | e7d56ee01eb5976588129d7bd4d5fc6dab2d794a | refs/heads/master | 2023-08-31T06:05:43.999253 | 2022-03-31T18:44:37 | 2022-03-31T18:44:37 | 33,870,540 | 189 | 72 | MIT | 2023-09-14T03:30:34 | 2015-04-13T13:36:50 | Python | UTF-8 | Python | false | false | 1,105 | py | # -*- coding: utf-8 -*-
# Generated by Django 1.11.6 on 2017-10-10 14:02
from __future__ import unicode_literals
from django.db import migrations, models
import django.db.models.deletion
class Migration(migrations.Migration):
dependencies = [
('wagtailimages', '0019_delete_filter'),
('wagtailcore', '0040_page_draft_title'),
('pages', '0015_advert_button_text'),
]
operations = [
migrations.CreateModel(
name='SiteBranding',
fields=[
('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),
('site_name', models.CharField(blank=True, max_length=250, null=True)),
('logo', models.ForeignKey(blank=True, null=True, on_delete=django.db.models.deletion.SET_NULL, related_name='+', to='wagtailimages.Image')),
('site', models.OneToOneField(editable=False, on_delete=django.db.models.deletion.CASCADE, to='wagtailcore.Site')),
],
options={
'abstract': False,
},
),
]
| [
"[email protected]"
] | |
0b4285bff2df5cd19b3e3e2f31c78b854999b8f5 | de24f83a5e3768a2638ebcf13cbe717e75740168 | /moodledata/vpl_data/65/usersdata/185/34920/submittedfiles/investimento.py | c02de528254c4d919d01652089a4c2aa1ade2813 | [] | no_license | rafaelperazzo/programacao-web | 95643423a35c44613b0f64bed05bd34780fe2436 | 170dd5440afb9ee68a973f3de13a99aa4c735d79 | refs/heads/master | 2021-01-12T14:06:25.773146 | 2017-12-22T16:05:45 | 2017-12-22T16:05:45 | 69,566,344 | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 515 | py | # -*- coding: utf-8 -*-
from __future__ import division
i0=float(input('digite o valor do investimesnto:'))
taxa=float(input('digite o valor da taxa:'))
i1=(i0+(i0*taxa))
i2=(i1+(i1*taxa))
i3=(i2+(i2*taxa))
i4=(i3+(i3*taxa))
i5=(i4+(i4*taxa))
i6=(i5+(i5*taxa))
i7=(i6+(i6*taxa))
i8=(i7+(i7*taxa))
i9=(i8+(i8*taxa))
i10=(i9+(i9*taxa))
print('%.2f' %i1)
print('%.2f' %i2)
print('%.2f' %i3)
print('%.2f' %i4)
print('%.2f' %i5)
print('%.2f' %i6)
print('%.2f' %i7)
print('%.2f' %i8)
print('%.2f' %i9)
print('%.2f' %i10) | [
"[email protected]"
] | |
bd21f9f9fa89f4649931f3c82b4fec92d0236194 | f085db42060d1616fcd4e1808cd1b8d6dc0fc913 | /beluga/continuation/ContinuationSolution.py | 32fe96a3d4e0a8b98ab3036cb4d04465fed94bec | [
"MIT"
] | permissive | thomasantony/beluga | 415aabc955a3ff08639e275f70a3608d0371b6b8 | 070c39476e07a6d5e900a2f9b3cd21c0ae7f9fe7 | refs/heads/master | 2021-09-04T20:13:40.757066 | 2018-01-22T02:40:34 | 2018-01-22T02:40:34 | 118,074,853 | 3 | 1 | null | 2018-01-19T04:00:09 | 2018-01-19T04:00:09 | null | UTF-8 | Python | false | false | 43 | py | class ContinuationSolution(list):
pass
| [
"[email protected]"
] | |
adf6af0524df6ab886504be487d226bb8e2ea86d | eb9c3dac0dca0ecd184df14b1fda62e61cc8c7d7 | /google/ads/googleads/v4/googleads-py/tests/unit/gapic/googleads.v4/services/test_ad_parameter_service.py | 738eff76504f6163898c0336379da593536d1d5b | [
"Apache-2.0"
] | permissive | Tryweirder/googleapis-gen | 2e5daf46574c3af3d448f1177eaebe809100c346 | 45d8e9377379f9d1d4e166e80415a8c1737f284d | refs/heads/master | 2023-04-05T06:30:04.726589 | 2021-04-13T23:35:20 | 2021-04-13T23:35:20 | null | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 34,565 | py | # -*- coding: utf-8 -*-
# Copyright 2020 Google LLC
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
#
import os
from unittest import mock
import grpc
import math
import pytest
from proto.marshal.rules.dates import DurationRule, TimestampRule
from google import auth
from google.ads.googleads.v4.resources.types import ad_parameter
from google.ads.googleads.v4.services.services.ad_parameter_service import AdParameterServiceClient
from google.ads.googleads.v4.services.services.ad_parameter_service import transports
from google.ads.googleads.v4.services.types import ad_parameter_service
from google.api_core import client_options
from google.api_core import gapic_v1
from google.api_core import grpc_helpers
from google.auth import credentials
from google.auth.exceptions import MutualTLSChannelError
from google.oauth2 import service_account
from google.protobuf import field_mask_pb2 as field_mask # type: ignore
from google.protobuf import wrappers_pb2 as wrappers # type: ignore
from google.rpc import status_pb2 as status # type: ignore
def client_cert_source_callback():
return b"cert bytes", b"key bytes"
# If default endpoint is localhost, then default mtls endpoint will be the same.
# This method modifies the default endpoint so the client can produce a different
# mtls endpoint for endpoint testing purposes.
def modify_default_endpoint(client):
return "foo.googleapis.com" if ("localhost" in client.DEFAULT_ENDPOINT) else client.DEFAULT_ENDPOINT
def test__get_default_mtls_endpoint():
api_endpoint = "example.googleapis.com"
api_mtls_endpoint = "example.mtls.googleapis.com"
sandbox_endpoint = "example.sandbox.googleapis.com"
sandbox_mtls_endpoint = "example.mtls.sandbox.googleapis.com"
non_googleapi = "api.example.com"
assert AdParameterServiceClient._get_default_mtls_endpoint(None) is None
assert AdParameterServiceClient._get_default_mtls_endpoint(api_endpoint) == api_mtls_endpoint
assert AdParameterServiceClient._get_default_mtls_endpoint(api_mtls_endpoint) == api_mtls_endpoint
assert AdParameterServiceClient._get_default_mtls_endpoint(sandbox_endpoint) == sandbox_mtls_endpoint
assert AdParameterServiceClient._get_default_mtls_endpoint(sandbox_mtls_endpoint) == sandbox_mtls_endpoint
assert AdParameterServiceClient._get_default_mtls_endpoint(non_googleapi) == non_googleapi
def test_ad_parameter_service_client_from_service_account_info():
creds = credentials.AnonymousCredentials()
with mock.patch.object(service_account.Credentials, 'from_service_account_info') as factory:
factory.return_value = creds
info = {"valid": True}
client = AdParameterServiceClient.from_service_account_info(info)
assert client.transport._credentials == creds
assert client.transport._host == 'googleads.googleapis.com:443'
def test_ad_parameter_service_client_from_service_account_file():
creds = credentials.AnonymousCredentials()
with mock.patch.object(service_account.Credentials, 'from_service_account_file') as factory:
factory.return_value = creds
client = AdParameterServiceClient.from_service_account_file("dummy/file/path.json")
assert client.transport._credentials == creds
client = AdParameterServiceClient.from_service_account_json("dummy/file/path.json")
assert client.transport._credentials == creds
assert client.transport._host == 'googleads.googleapis.com:443'
def test_ad_parameter_service_client_get_transport_class():
transport = AdParameterServiceClient.get_transport_class()
assert transport == transports.AdParameterServiceGrpcTransport
transport = AdParameterServiceClient.get_transport_class("grpc")
assert transport == transports.AdParameterServiceGrpcTransport
@mock.patch.object(AdParameterServiceClient, "DEFAULT_ENDPOINT", modify_default_endpoint(AdParameterServiceClient))
def test_ad_parameter_service_client_client_options():
# Check that if channel is provided we won't create a new one.
with mock.patch('google.ads.googleads.v4.services.services.ad_parameter_service.AdParameterServiceClient.get_transport_class') as gtc:
transport = transports.AdParameterServiceGrpcTransport(
credentials=credentials.AnonymousCredentials()
)
client = AdParameterServiceClient(transport=transport)
gtc.assert_not_called()
# Check that if channel is provided via str we will create a new one.
with mock.patch('google.ads.googleads.v4.services.services.ad_parameter_service.AdParameterServiceClient.get_transport_class') as gtc:
client = AdParameterServiceClient(transport="grpc")
gtc.assert_called()
# Check the case api_endpoint is provided.
options = client_options.ClientOptions(api_endpoint="squid.clam.whelk")
with mock.patch('google.ads.googleads.v4.services.services.ad_parameter_service.transports.AdParameterServiceGrpcTransport.__init__') as grpc_transport:
grpc_transport.return_value = None
client = AdParameterServiceClient(client_options=options)
grpc_transport.assert_called_once_with(
ssl_channel_credentials=None,
credentials=None,
host="squid.clam.whelk",
client_info=transports.base.DEFAULT_CLIENT_INFO,
)
# Check the case api_endpoint is not provided and GOOGLE_API_USE_MTLS_ENDPOINT
# is "never".
with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "never"}):
with mock.patch('google.ads.googleads.v4.services.services.ad_parameter_service.transports.AdParameterServiceGrpcTransport.__init__') as grpc_transport:
grpc_transport.return_value = None
client = AdParameterServiceClient()
grpc_transport.assert_called_once_with(
ssl_channel_credentials=None,
credentials=None,
host=client.DEFAULT_ENDPOINT,
client_info=transports.base.DEFAULT_CLIENT_INFO,
)
# Check the case api_endpoint is not provided and GOOGLE_API_USE_MTLS_ENDPOINT is
# "always".
with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "always"}):
with mock.patch('google.ads.googleads.v4.services.services.ad_parameter_service.transports.AdParameterServiceGrpcTransport.__init__') as grpc_transport:
grpc_transport.return_value = None
client = AdParameterServiceClient()
grpc_transport.assert_called_once_with(
ssl_channel_credentials=None,
credentials=None,
host=client.DEFAULT_MTLS_ENDPOINT,
client_info=transports.base.DEFAULT_CLIENT_INFO,
)
# Check the case api_endpoint is not provided and GOOGLE_API_USE_MTLS_ENDPOINT has
# unsupported value.
with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "Unsupported"}):
with pytest.raises(MutualTLSChannelError):
client = AdParameterServiceClient()
# Check the case GOOGLE_API_USE_CLIENT_CERTIFICATE has unsupported value.
with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "Unsupported"}):
with pytest.raises(ValueError):
client = AdParameterServiceClient()
@mock.patch.object(AdParameterServiceClient, "DEFAULT_ENDPOINT", modify_default_endpoint(AdParameterServiceClient))
@mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "auto"})
@pytest.mark.parametrize("use_client_cert_env", ["true", "false"])
def test_ad_parameter_service_client_mtls_env_auto(use_client_cert_env):
# This tests the endpoint autoswitch behavior. Endpoint is autoswitched to the default
# mtls endpoint, if GOOGLE_API_USE_CLIENT_CERTIFICATE is "true" and client cert exists.
# Check the case client_cert_source is provided. Whether client cert is used depends on
# GOOGLE_API_USE_CLIENT_CERTIFICATE value.
with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": use_client_cert_env}):
options = client_options.ClientOptions(client_cert_source=client_cert_source_callback)
with mock.patch('google.ads.googleads.v4.services.services.ad_parameter_service.transports.AdParameterServiceGrpcTransport.__init__') as grpc_transport:
ssl_channel_creds = mock.Mock()
with mock.patch('grpc.ssl_channel_credentials', return_value=ssl_channel_creds):
grpc_transport.return_value = None
client = AdParameterServiceClient(client_options=options)
if use_client_cert_env == "false":
expected_ssl_channel_creds = None
expected_host = client.DEFAULT_ENDPOINT
else:
expected_ssl_channel_creds = ssl_channel_creds
expected_host = client.DEFAULT_MTLS_ENDPOINT
grpc_transport.assert_called_once_with(
ssl_channel_credentials=expected_ssl_channel_creds,
credentials=None,
host=expected_host,
client_info=transports.base.DEFAULT_CLIENT_INFO,
)
# Check the case ADC client cert is provided. Whether client cert is used depends on
# GOOGLE_API_USE_CLIENT_CERTIFICATE value.
with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": use_client_cert_env}):
with mock.patch('google.ads.googleads.v4.services.services.ad_parameter_service.transports.AdParameterServiceGrpcTransport.__init__') as grpc_transport:
with mock.patch('google.auth.transport.grpc.SslCredentials.__init__', return_value=None):
with mock.patch('google.auth.transport.grpc.SslCredentials.is_mtls', new_callable=mock.PropertyMock) as is_mtls_mock:
with mock.patch('google.auth.transport.grpc.SslCredentials.ssl_credentials', new_callable=mock.PropertyMock) as ssl_credentials_mock:
if use_client_cert_env == "false":
is_mtls_mock.return_value = False
ssl_credentials_mock.return_value = None
expected_host = client.DEFAULT_ENDPOINT
expected_ssl_channel_creds = None
else:
is_mtls_mock.return_value = True
ssl_credentials_mock.return_value = mock.Mock()
expected_host = client.DEFAULT_MTLS_ENDPOINT
expected_ssl_channel_creds = ssl_credentials_mock.return_value
grpc_transport.return_value = None
client = AdParameterServiceClient()
grpc_transport.assert_called_once_with(
ssl_channel_credentials=expected_ssl_channel_creds,
credentials=None,
host=expected_host,
client_info=transports.base.DEFAULT_CLIENT_INFO,
)
# Check the case client_cert_source and ADC client cert are not provided.
with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": use_client_cert_env}):
with mock.patch('google.ads.googleads.v4.services.services.ad_parameter_service.transports.AdParameterServiceGrpcTransport.__init__') as grpc_transport:
with mock.patch('google.auth.transport.grpc.SslCredentials.__init__', return_value=None):
with mock.patch('google.auth.transport.grpc.SslCredentials.is_mtls', new_callable=mock.PropertyMock) as is_mtls_mock:
is_mtls_mock.return_value = False
grpc_transport.return_value = None
client = AdParameterServiceClient()
grpc_transport.assert_called_once_with(
ssl_channel_credentials=None,
credentials=None,
host=client.DEFAULT_ENDPOINT,
client_info=transports.base.DEFAULT_CLIENT_INFO,
)
def test_ad_parameter_service_client_client_options_from_dict():
with mock.patch('google.ads.googleads.v4.services.services.ad_parameter_service.transports.AdParameterServiceGrpcTransport.__init__') as grpc_transport:
grpc_transport.return_value = None
client = AdParameterServiceClient(
client_options={'api_endpoint': 'squid.clam.whelk'}
)
grpc_transport.assert_called_once_with(
ssl_channel_credentials=None,
credentials=None,
host="squid.clam.whelk",
client_info=transports.base.DEFAULT_CLIENT_INFO,
)
def test_get_ad_parameter(transport: str = 'grpc', request_type=ad_parameter_service.GetAdParameterRequest):
client = AdParameterServiceClient(
credentials=credentials.AnonymousCredentials(),
transport=transport,
)
# Everything is optional in proto3 as far as the runtime is concerned,
# and we are mocking out the actual API, so just send an empty request.
request = request_type()
# Mock the actual call within the gRPC stub, and fake the request.
with mock.patch.object(
type(client.transport.get_ad_parameter),
'__call__') as call:
# Designate an appropriate return value for the call.
call.return_value = ad_parameter.AdParameter(
resource_name='resource_name_value',
)
response = client.get_ad_parameter(request)
# Establish that the underlying gRPC stub method was called.
assert len(call.mock_calls) == 1
_, args, _ = call.mock_calls[0]
assert args[0] == ad_parameter_service.GetAdParameterRequest()
# Establish that the response is the type that we expect.
assert isinstance(response, ad_parameter.AdParameter)
assert response.resource_name == 'resource_name_value'
def test_get_ad_parameter_from_dict():
test_get_ad_parameter(request_type=dict)
def test_get_ad_parameter_field_headers():
client = AdParameterServiceClient(
credentials=credentials.AnonymousCredentials(),
)
# Any value that is part of the HTTP/1.1 URI should be sent as
# a field header. Set these to a non-empty value.
request = ad_parameter_service.GetAdParameterRequest()
request.resource_name = 'resource_name/value'
# Mock the actual call within the gRPC stub, and fake the request.
with mock.patch.object(
type(client.transport.get_ad_parameter),
'__call__') as call:
call.return_value = ad_parameter.AdParameter()
client.get_ad_parameter(request)
# Establish that the underlying gRPC stub method was called.
assert len(call.mock_calls) == 1
_, args, _ = call.mock_calls[0]
assert args[0] == request
# Establish that the field header was sent.
_, _, kw = call.mock_calls[0]
assert (
'x-goog-request-params',
'resource_name=resource_name/value',
) in kw['metadata']
def test_get_ad_parameter_flattened():
client = AdParameterServiceClient(
credentials=credentials.AnonymousCredentials(),
)
# Mock the actual call within the gRPC stub, and fake the request.
with mock.patch.object(
type(client.transport.get_ad_parameter),
'__call__') as call:
# Designate an appropriate return value for the call.
call.return_value = ad_parameter.AdParameter()
# Call the method with a truthy value for each flattened field,
# using the keyword arguments to the method.
client.get_ad_parameter(
resource_name='resource_name_value',
)
# Establish that the underlying call was made with the expected
# request object values.
assert len(call.mock_calls) == 1
_, args, _ = call.mock_calls[0]
assert args[0].resource_name == 'resource_name_value'
def test_get_ad_parameter_flattened_error():
client = AdParameterServiceClient(
credentials=credentials.AnonymousCredentials(),
)
# Attempting to call a method with both a request object and flattened
# fields is an error.
with pytest.raises(ValueError):
client.get_ad_parameter(
ad_parameter_service.GetAdParameterRequest(),
resource_name='resource_name_value',
)
def test_mutate_ad_parameters(transport: str = 'grpc', request_type=ad_parameter_service.MutateAdParametersRequest):
client = AdParameterServiceClient(
credentials=credentials.AnonymousCredentials(),
transport=transport,
)
# Everything is optional in proto3 as far as the runtime is concerned,
# and we are mocking out the actual API, so just send an empty request.
request = request_type()
# Mock the actual call within the gRPC stub, and fake the request.
with mock.patch.object(
type(client.transport.mutate_ad_parameters),
'__call__') as call:
# Designate an appropriate return value for the call.
call.return_value = ad_parameter_service.MutateAdParametersResponse(
)
response = client.mutate_ad_parameters(request)
# Establish that the underlying gRPC stub method was called.
assert len(call.mock_calls) == 1
_, args, _ = call.mock_calls[0]
assert args[0] == ad_parameter_service.MutateAdParametersRequest()
# Establish that the response is the type that we expect.
assert isinstance(response, ad_parameter_service.MutateAdParametersResponse)
def test_mutate_ad_parameters_from_dict():
test_mutate_ad_parameters(request_type=dict)
def test_mutate_ad_parameters_field_headers():
client = AdParameterServiceClient(
credentials=credentials.AnonymousCredentials(),
)
# Any value that is part of the HTTP/1.1 URI should be sent as
# a field header. Set these to a non-empty value.
request = ad_parameter_service.MutateAdParametersRequest()
request.customer_id = 'customer_id/value'
# Mock the actual call within the gRPC stub, and fake the request.
with mock.patch.object(
type(client.transport.mutate_ad_parameters),
'__call__') as call:
call.return_value = ad_parameter_service.MutateAdParametersResponse()
client.mutate_ad_parameters(request)
# Establish that the underlying gRPC stub method was called.
assert len(call.mock_calls) == 1
_, args, _ = call.mock_calls[0]
assert args[0] == request
# Establish that the field header was sent.
_, _, kw = call.mock_calls[0]
assert (
'x-goog-request-params',
'customer_id=customer_id/value',
) in kw['metadata']
def test_mutate_ad_parameters_flattened():
client = AdParameterServiceClient(
credentials=credentials.AnonymousCredentials(),
)
# Mock the actual call within the gRPC stub, and fake the request.
with mock.patch.object(
type(client.transport.mutate_ad_parameters),
'__call__') as call:
# Designate an appropriate return value for the call.
call.return_value = ad_parameter_service.MutateAdParametersResponse()
# Call the method with a truthy value for each flattened field,
# using the keyword arguments to the method.
client.mutate_ad_parameters(
customer_id='customer_id_value',
operations=[ad_parameter_service.AdParameterOperation(update_mask=field_mask.FieldMask(paths=['paths_value']))],
)
# Establish that the underlying call was made with the expected
# request object values.
assert len(call.mock_calls) == 1
_, args, _ = call.mock_calls[0]
assert args[0].customer_id == 'customer_id_value'
assert args[0].operations == [ad_parameter_service.AdParameterOperation(update_mask=field_mask.FieldMask(paths=['paths_value']))]
def test_mutate_ad_parameters_flattened_error():
client = AdParameterServiceClient(
credentials=credentials.AnonymousCredentials(),
)
# Attempting to call a method with both a request object and flattened
# fields is an error.
with pytest.raises(ValueError):
client.mutate_ad_parameters(
ad_parameter_service.MutateAdParametersRequest(),
customer_id='customer_id_value',
operations=[ad_parameter_service.AdParameterOperation(update_mask=field_mask.FieldMask(paths=['paths_value']))],
)
def test_credentials_transport_error():
# It is an error to provide credentials and a transport instance.
transport = transports.AdParameterServiceGrpcTransport(
credentials=credentials.AnonymousCredentials(),
)
with pytest.raises(ValueError):
client = AdParameterServiceClient(
credentials=credentials.AnonymousCredentials(),
transport=transport,
)
def test_transport_instance():
# A client may be instantiated with a custom transport instance.
transport = transports.AdParameterServiceGrpcTransport(
credentials=credentials.AnonymousCredentials(),
)
client = AdParameterServiceClient(transport=transport)
assert client.transport is transport
def test_transport_get_channel():
# A client may be instantiated with a custom transport instance.
transport = transports.AdParameterServiceGrpcTransport(
credentials=credentials.AnonymousCredentials(),
)
channel = transport.grpc_channel
assert channel
def test_transport_grpc_default():
# A client should use the gRPC transport by default.
client = AdParameterServiceClient(
credentials=credentials.AnonymousCredentials(),
)
assert isinstance(
client.transport,
transports.AdParameterServiceGrpcTransport,
)
@pytest.mark.parametrize("transport_class", [
transports.AdParameterServiceGrpcTransport,
])
def test_transport_adc(transport_class):
# Test default credentials are used if not provided.
with mock.patch.object(auth, 'default') as adc:
adc.return_value = (credentials.AnonymousCredentials(), None)
transport_class()
adc.assert_called_once()
def test_ad_parameter_service_base_transport():
# Instantiate the base transport.
with mock.patch('google.ads.googleads.v4.services.services.ad_parameter_service.transports.AdParameterServiceTransport.__init__') as Transport:
Transport.return_value = None
transport = transports.AdParameterServiceTransport(
credentials=credentials.AnonymousCredentials(),
)
# Every method on the transport should just blindly
# raise NotImplementedError.
methods = (
'get_ad_parameter',
'mutate_ad_parameters',
)
for method in methods:
with pytest.raises(NotImplementedError):
getattr(transport, method)(request=object())
def test_ad_parameter_service_base_transport_with_adc():
# Test the default credentials are used if credentials and credentials_file are None.
with mock.patch.object(auth, 'default') as adc, mock.patch('google.ads.googleads.v4.services.services.ad_parameter_service.transports.AdParameterServiceTransport._prep_wrapped_messages') as Transport:
Transport.return_value = None
adc.return_value = (credentials.AnonymousCredentials(), None)
transport = transports.AdParameterServiceTransport()
adc.assert_called_once()
def test_ad_parameter_service_auth_adc():
# If no credentials are provided, we should use ADC credentials.
with mock.patch.object(auth, 'default') as adc:
adc.return_value = (credentials.AnonymousCredentials(), None)
AdParameterServiceClient()
adc.assert_called_once_with(scopes=(
'https://www.googleapis.com/auth/adwords',
))
def test_ad_parameter_service_transport_auth_adc():
# If credentials and host are not provided, the transport class should use
# ADC credentials.
with mock.patch.object(auth, 'default') as adc:
adc.return_value = (credentials.AnonymousCredentials(), None)
transports.AdParameterServiceGrpcTransport(host="squid.clam.whelk")
adc.assert_called_once_with(scopes=(
'https://www.googleapis.com/auth/adwords',
))
def test_ad_parameter_service_host_no_port():
client = AdParameterServiceClient(
credentials=credentials.AnonymousCredentials(),
client_options=client_options.ClientOptions(api_endpoint='googleads.googleapis.com'),
)
assert client.transport._host == 'googleads.googleapis.com:443'
def test_ad_parameter_service_host_with_port():
client = AdParameterServiceClient(
credentials=credentials.AnonymousCredentials(),
client_options=client_options.ClientOptions(api_endpoint='googleads.googleapis.com:8000'),
)
assert client.transport._host == 'googleads.googleapis.com:8000'
def test_ad_parameter_service_grpc_transport_channel():
channel = grpc.insecure_channel('http://localhost/')
# Check that channel is used if provided.
transport = transports.AdParameterServiceGrpcTransport(
host="squid.clam.whelk",
channel=channel,
)
assert transport.grpc_channel == channel
assert transport._host == "squid.clam.whelk:443"
assert transport._ssl_channel_credentials == None
@pytest.mark.parametrize("transport_class", [transports.AdParameterServiceGrpcTransport])
def test_ad_parameter_service_transport_channel_mtls_with_client_cert_source(
transport_class
):
with mock.patch("grpc.ssl_channel_credentials", autospec=True) as grpc_ssl_channel_cred:
with mock.patch.object(transport_class, "create_channel", autospec=True) as grpc_create_channel:
mock_ssl_cred = mock.Mock()
grpc_ssl_channel_cred.return_value = mock_ssl_cred
mock_grpc_channel = mock.Mock()
grpc_create_channel.return_value = mock_grpc_channel
cred = credentials.AnonymousCredentials()
with pytest.warns(DeprecationWarning):
with mock.patch.object(auth, 'default') as adc:
adc.return_value = (cred, None)
transport = transport_class(
host="squid.clam.whelk",
api_mtls_endpoint="mtls.squid.clam.whelk",
client_cert_source=client_cert_source_callback,
)
adc.assert_called_once()
grpc_ssl_channel_cred.assert_called_once_with(
certificate_chain=b"cert bytes", private_key=b"key bytes"
)
grpc_create_channel.assert_called_once_with(
"mtls.squid.clam.whelk:443",
credentials=cred,
credentials_file=None,
scopes=(
'https://www.googleapis.com/auth/adwords',
),
ssl_credentials=mock_ssl_cred,
quota_project_id=None,
options=[
("grpc.max_send_message_length", -1),
("grpc.max_receive_message_length", -1),
],
)
assert transport.grpc_channel == mock_grpc_channel
assert transport._ssl_channel_credentials == mock_ssl_cred
@pytest.mark.parametrize("transport_class", [transports.AdParameterServiceGrpcTransport,])
def test_ad_parameter_service_transport_channel_mtls_with_adc(
transport_class
):
mock_ssl_cred = mock.Mock()
with mock.patch.multiple(
"google.auth.transport.grpc.SslCredentials",
__init__=mock.Mock(return_value=None),
ssl_credentials=mock.PropertyMock(return_value=mock_ssl_cred),
):
with mock.patch.object(transport_class, "create_channel", autospec=True) as grpc_create_channel:
mock_grpc_channel = mock.Mock()
grpc_create_channel.return_value = mock_grpc_channel
mock_cred = mock.Mock()
with pytest.warns(DeprecationWarning):
transport = transport_class(
host="squid.clam.whelk",
credentials=mock_cred,
api_mtls_endpoint="mtls.squid.clam.whelk",
client_cert_source=None,
)
grpc_create_channel.assert_called_once_with(
"mtls.squid.clam.whelk:443",
credentials=mock_cred,
credentials_file=None,
scopes=(
'https://www.googleapis.com/auth/adwords',
),
ssl_credentials=mock_ssl_cred,
quota_project_id=None,
options=[
("grpc.max_send_message_length", -1),
("grpc.max_receive_message_length", -1),
],
)
assert transport.grpc_channel == mock_grpc_channel
def test_ad_group_criterion_path():
customer = "squid"
ad_group_criterion = "clam"
expected = "customers/{customer}/adGroupCriteria/{ad_group_criterion}".format(customer=customer, ad_group_criterion=ad_group_criterion, )
actual = AdParameterServiceClient.ad_group_criterion_path(customer, ad_group_criterion)
assert expected == actual
def test_parse_ad_group_criterion_path():
expected = {
"customer": "whelk",
"ad_group_criterion": "octopus",
}
path = AdParameterServiceClient.ad_group_criterion_path(**expected)
# Check that the path construction is reversible.
actual = AdParameterServiceClient.parse_ad_group_criterion_path(path)
assert expected == actual
def test_ad_parameter_path():
customer = "oyster"
ad_parameter = "nudibranch"
expected = "customers/{customer}/adParameters/{ad_parameter}".format(customer=customer, ad_parameter=ad_parameter, )
actual = AdParameterServiceClient.ad_parameter_path(customer, ad_parameter)
assert expected == actual
def test_parse_ad_parameter_path():
expected = {
"customer": "cuttlefish",
"ad_parameter": "mussel",
}
path = AdParameterServiceClient.ad_parameter_path(**expected)
# Check that the path construction is reversible.
actual = AdParameterServiceClient.parse_ad_parameter_path(path)
assert expected == actual
def test_common_billing_account_path():
billing_account = "winkle"
expected = "billingAccounts/{billing_account}".format(billing_account=billing_account, )
actual = AdParameterServiceClient.common_billing_account_path(billing_account)
assert expected == actual
def test_parse_common_billing_account_path():
expected = {
"billing_account": "nautilus",
}
path = AdParameterServiceClient.common_billing_account_path(**expected)
# Check that the path construction is reversible.
actual = AdParameterServiceClient.parse_common_billing_account_path(path)
assert expected == actual
def test_common_folder_path():
folder = "scallop"
expected = "folders/{folder}".format(folder=folder, )
actual = AdParameterServiceClient.common_folder_path(folder)
assert expected == actual
def test_parse_common_folder_path():
expected = {
"folder": "abalone",
}
path = AdParameterServiceClient.common_folder_path(**expected)
# Check that the path construction is reversible.
actual = AdParameterServiceClient.parse_common_folder_path(path)
assert expected == actual
def test_common_organization_path():
organization = "squid"
expected = "organizations/{organization}".format(organization=organization, )
actual = AdParameterServiceClient.common_organization_path(organization)
assert expected == actual
def test_parse_common_organization_path():
expected = {
"organization": "clam",
}
path = AdParameterServiceClient.common_organization_path(**expected)
# Check that the path construction is reversible.
actual = AdParameterServiceClient.parse_common_organization_path(path)
assert expected == actual
def test_common_project_path():
project = "whelk"
expected = "projects/{project}".format(project=project, )
actual = AdParameterServiceClient.common_project_path(project)
assert expected == actual
def test_parse_common_project_path():
expected = {
"project": "octopus",
}
path = AdParameterServiceClient.common_project_path(**expected)
# Check that the path construction is reversible.
actual = AdParameterServiceClient.parse_common_project_path(path)
assert expected == actual
def test_common_location_path():
project = "oyster"
location = "nudibranch"
expected = "projects/{project}/locations/{location}".format(project=project, location=location, )
actual = AdParameterServiceClient.common_location_path(project, location)
assert expected == actual
def test_parse_common_location_path():
expected = {
"project": "cuttlefish",
"location": "mussel",
}
path = AdParameterServiceClient.common_location_path(**expected)
# Check that the path construction is reversible.
actual = AdParameterServiceClient.parse_common_location_path(path)
assert expected == actual
def test_client_withDEFAULT_CLIENT_INFO():
client_info = gapic_v1.client_info.ClientInfo()
with mock.patch.object(transports.AdParameterServiceTransport, '_prep_wrapped_messages') as prep:
client = AdParameterServiceClient(
credentials=credentials.AnonymousCredentials(),
client_info=client_info,
)
prep.assert_called_once_with(client_info)
with mock.patch.object(transports.AdParameterServiceTransport, '_prep_wrapped_messages') as prep:
transport_class = AdParameterServiceClient.get_transport_class()
transport = transport_class(
credentials=credentials.AnonymousCredentials(),
client_info=client_info,
)
prep.assert_called_once_with(client_info)
| [
"bazel-bot-development[bot]@users.noreply.github.com"
] | bazel-bot-development[bot]@users.noreply.github.com |
7e29e532d2f1285cd50e39b2cb2212b658e5b9a8 | 149db911cd5b9f404e5d74fd6c8ed047482d2c22 | /backend/menu/migrations/0001_initial.py | 2c07fd16d8ed613c8286821c487d80336fef03b4 | [] | no_license | crowdbotics-apps/bigbitesgrill-22907 | 45814458930ad7aed64a1f4941aabd930f1f2587 | 6cd1b7b663de21c7587cdbce1612c4807e2cc5f6 | refs/heads/master | 2023-01-14T05:10:18.129338 | 2020-11-23T03:27:17 | 2020-11-23T03:27:17 | 315,189,727 | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 3,144 | py | # Generated by Django 2.2.17 on 2020-11-23 03:26
from django.db import migrations, models
import django.db.models.deletion
class Migration(migrations.Migration):
initial = True
dependencies = [
('delivery_user_profile', '0001_initial'),
]
operations = [
migrations.CreateModel(
name='Category',
fields=[
('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),
('name', models.CharField(max_length=255)),
('description', models.TextField()),
('image', models.URLField()),
('icon', models.URLField()),
],
),
migrations.CreateModel(
name='Country',
fields=[
('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),
('name', models.CharField(max_length=255)),
('description', models.TextField()),
('prefix', models.CharField(max_length=8)),
('flag', models.URLField()),
],
),
migrations.CreateModel(
name='Item',
fields=[
('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),
('name', models.CharField(max_length=255)),
('description', models.TextField()),
('image', models.URLField()),
('category', models.ForeignKey(blank=True, null=True, on_delete=django.db.models.deletion.SET_NULL, related_name='item_category', to='menu.Category')),
],
),
migrations.CreateModel(
name='Review',
fields=[
('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),
('rating', models.FloatField()),
('review_text', models.TextField()),
('timestamp_created', models.DateTimeField(auto_now_add=True)),
('item', models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, related_name='review_item', to='menu.Item')),
('profile', models.ForeignKey(blank=True, null=True, on_delete=django.db.models.deletion.SET_NULL, related_name='review_profile', to='delivery_user_profile.Profile')),
],
),
migrations.CreateModel(
name='ItemVariant',
fields=[
('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),
('name', models.CharField(max_length=255)),
('description', models.TextField()),
('price', models.FloatField()),
('image', models.URLField()),
('country', models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, related_name='itemvariant_country', to='menu.Country')),
('item', models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, related_name='itemvariant_item', to='menu.Item')),
],
),
]
| [
"[email protected]"
] | |
512cccdff042b753e66c88811c3fe1daaa5ce10b | d488f052805a87b5c4b124ca93494bc9b78620f7 | /google-cloud-sdk/lib/googlecloudsdk/command_lib/accesscontextmanager/zones.py | 7769f86c280257e290b19cd283c994d3d59183d5 | [
"MIT",
"LicenseRef-scancode-unknown-license-reference",
"Apache-2.0"
] | permissive | PacktPublishing/DevOps-Fundamentals | 5ce1fc938db66b420691aa8106ecfb3f9ceb1ace | 60597e831e08325c7e51e8557591917f7c417275 | refs/heads/master | 2023-02-02T04:48:15.346907 | 2023-01-30T08:33:35 | 2023-01-30T08:33:35 | 131,293,311 | 13 | 19 | null | null | null | null | UTF-8 | Python | false | false | 7,142 | py | # Copyright 2017 Google Inc. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
"""Command line processing utilities for access zones."""
from googlecloudsdk.api_lib.accesscontextmanager import util
from googlecloudsdk.calliope.concepts import concepts
from googlecloudsdk.command_lib.accesscontextmanager import common
from googlecloudsdk.command_lib.accesscontextmanager import levels
from googlecloudsdk.command_lib.accesscontextmanager import policies
from googlecloudsdk.command_lib.util.apis import arg_utils
from googlecloudsdk.command_lib.util.args import repeated
from googlecloudsdk.command_lib.util.concepts import concept_parsers
from googlecloudsdk.core import resources
REGISTRY = resources.REGISTRY
def AddAccessLevels(ref, args, req):
if args.IsSpecified('access_levels'):
access_levels = []
for access_level in args.access_levels:
level_ref = resources.REGISTRY.Create(
'accesscontextmanager.accessPolicies.accessLevels',
accessLevelsId=access_level, **ref.Parent().AsDict())
access_levels.append(level_ref.RelativeName())
req.accessZone.accessLevels = access_levels
return req
def AddImplicitServiceWildcard(ref, args, req):
"""Add an implicit wildcard for services if they are modified.
If either restricted services or unrestricted services is given, the other
must also be provided as a wildcard (`*`).
If neither is given, this is a no-op.
Args:
ref: resources.Resource, the (unused) resource
args: argparse namespace, the parse arguments
req: AccesscontextmanagerAccessPoliciesAccessZonesCreateRequest
Returns:
The modified request.
"""
del ref # Unused in AddImplicitServiceWildcard
if args.IsSpecified('restricted_services'):
req.accessZone.unrestrictedServices = ['*']
elif args.IsSpecified('unrestricted_services'):
req.accessZone.restrictedServices = ['*']
return req
def _GetAttributeConfig():
return concepts.ResourceParameterAttributeConfig(
name='zone',
help_text='The ID of the access zone.'
)
def _GetResourceSpec():
return concepts.ResourceSpec(
'accesscontextmanager.accessPolicies.accessZones',
resource_name='zone',
accessPoliciesId=policies.GetAttributeConfig(),
accessZonesId=_GetAttributeConfig())
def AddResourceArg(parser, verb):
"""Add a resource argument for an access zone.
NOTE: Must be used only if it's the only resource arg in the command.
Args:
parser: the parser for the command.
verb: str, the verb to describe the resource, such as 'to update'.
"""
concept_parsers.ConceptParser.ForResource(
'zone',
_GetResourceSpec(),
'The access zone {}.'.format(verb),
required=True).AddToParser(parser)
def GetTypeEnumMapper():
return arg_utils.ChoiceEnumMapper(
'--type',
util.GetMessages().AccessZone.ZoneTypeValueValuesEnum,
custom_mappings={
'ZONE_TYPE_REGULAR': 'regular',
'ZONE_TYPE_BRIDGE': 'bridge'
},
required=False,
help_str="""\
Type of the zone.
A *regular* zone allows resources within this access zone to import
and export data amongst themselves. A project may belong to at most
one regular access zone.
A *bridge* access zone allows resources in different regular access
zones to import and export data between each other. A project may
belong to multiple bridge access zones (only if it also belongs to a
regular access zone). Both restricted and unrestricted service lists,
as well as access level lists, must be empty.
""",
)
def AddZoneUpdateArgs(parser):
"""Add args for zones update command."""
args = [
common.GetDescriptionArg('access zone'),
common.GetTitleArg('access zone'),
GetTypeEnumMapper().choice_arg
]
for arg in args:
arg.AddToParser(parser)
_AddResources(parser)
_AddUnrestrictedServices(parser)
_AddRestrictedServices(parser)
_AddLevelsUpdate(parser)
def _AddResources(parser):
repeated.AddPrimitiveArgs(
parser, 'zone', 'resources', 'resources',
additional_help=('Resources must be projects, in the form '
'`project/<projectnumber>`.'))
def ParseResources(args, zone_result):
return repeated.ParsePrimitiveArgs(
args, 'resources', zone_result.GetAttrThunk('resources'))
def _AddUnrestrictedServices(parser):
repeated.AddPrimitiveArgs(
parser, 'zone', 'unrestricted-services', 'unrestricted services',
metavar='SERVICE',
additional_help=(
'The zone boundary DOES NOT apply to these services (for example, '
'`storage.googleapis.com`). A wildcard (```*```) may be given to '
'denote all services.\n\n'
'If restricted services are set, unrestricted services must be a '
'wildcard.'))
def ParseUnrestrictedServices(args, zone_result):
return repeated.ParsePrimitiveArgs(
args, 'unrestricted_services',
zone_result.GetAttrThunk('unrestrictedServices'))
def _AddRestrictedServices(parser):
repeated.AddPrimitiveArgs(
parser, 'zone', 'restricted-services', 'restricted services',
metavar='SERVICE',
additional_help=(
'The zone boundary DOES apply to these services (for example, '
'`storage.googleapis.com`). A wildcard (```*```) may be given to '
'denote all services.\n\n'
'If unrestricted services are set, restricted services must be a '
'wildcard.'))
def ParseRestrictedServices(args, zone_result):
return repeated.ParsePrimitiveArgs(
args, 'restricted_services',
zone_result.GetAttrThunk('restrictedServices'))
def _AddLevelsUpdate(parser):
repeated.AddPrimitiveArgs(
parser, 'zone', 'access-levels', 'access levels',
metavar='LEVEL',
additional_help=(
'An intra-zone request must satisfy these access levels (for '
'example, `MY_LEVEL`; must be in the same access policy as this '
'zone) to be allowed.'))
def _GetLevelIdFromLevelName(level_name):
return REGISTRY.Parse(level_name, collection=levels.COLLECTION).accessLevelsId
def ParseLevels(args, zone_result, policy_id):
level_ids = repeated.ParsePrimitiveArgs(
args, 'access_levels',
zone_result.GetAttrThunk('accessLevels',
transform=_GetLevelIdFromLevelName))
if level_ids is None:
return None
return [REGISTRY.Create(levels.COLLECTION,
accessPoliciesId=policy_id,
accessLevelsId=l) for l in level_ids]
| [
"[email protected]"
] | |
f42b24eb133af9fb0d043daae02623831e534124 | c17ca7a7824056f7ad58d0f71abc25670b20c1fc | /cenet/populations_xml.py | 50514b7f8ab3d1c783e713a36c3b795c93d91dae | [
"Apache-2.0"
] | permissive | Si-elegans/Web-based_GUI_Tools | cd35b72e80aa400105593c5c819355437e204a81 | 58a9b7a76bc46467554192a38ff5329a94e2b627 | refs/heads/master | 2023-01-11T09:11:21.896172 | 2017-07-18T11:10:31 | 2017-07-18T11:10:31 | 97,445,306 | 3 | 1 | Apache-2.0 | 2022-12-26T20:14:59 | 2017-07-17T07:03:13 | JavaScript | UTF-8 | Python | false | false | 67,096 | py | POPULATIONS_TEMPLATE =\
"""
<population id="ADAL" component="" type="populationList">
<instance id="0">
<location y="8.65" x="-239.25" z="31.050000000000001"/>
</instance>
</population>
<population id="ADAR" component="" type="populationList">
<instance id="0">
<location y="-12.9" x="-239.25" z="31.050000000000001"/>
</instance>
</population>
<population id="ADEL" component="" type="populationList">
<instance id="0">
<location y="11." x="-242.375" z="32.450000000000003"/>
</instance>
</population>
<population id="ADER" component="" type="populationList">
<instance id="0">
<location y="-15.299999" x="-242.375" z="32.450000000000003"/>
</instance>
</population>
<population id="ADFL" component="" type="populationList">
<instance id="0">
<location y="3.7250001" x="-267.899999999999977" z="41.600002000000003"/>
</instance>
</population>
<population id="ADFR" component="" type="populationList">
<instance id="0">
<location y="-8." x="-267.899999999999977" z="41.600002000000003"/>
</instance>
</population>
<population id="ADLL" component="" type="populationList">
<instance id="0">
<location y="2.7" x="-265.75" z="47.549999999999997"/>
</instance>
</population>
<population id="ADLR" component="" type="populationList">
<instance id="0">
<location y="-6.95" x="-265.75" z="47.549999999999997"/>
</instance>
</population>
<population id="AFDL" component="" type="populationList">
<instance id="0">
<location y="4.5" x="-268.375" z="43.5"/>
</instance>
</population>
<population id="AFDR" component="" type="populationList">
<instance id="0">
<location y="-8.75" x="-268.375" z="43.5"/>
</instance>
</population>
<population id="AIAL" component="" type="populationList">
<instance id="0">
<location y="0.8" x="-264.149999999999977" z="35.550002999999997"/>
</instance>
</population>
<population id="AIAR" component="" type="populationList">
<instance id="0">
<location y="-5.1" x="-264.149999999999977" z="35.550002999999997"/>
</instance>
</population>
<population id="AIBL" component="" type="populationList">
<instance id="0">
<location y="2.7" x="-266.199979999999982" z="37."/>
</instance>
</population>
<population id="AIBR" component="" type="populationList">
<instance id="0">
<location y="-6.8999996" x="-266.199979999999982" z="37."/>
</instance>
</population>
<population id="AIML" component="" type="populationList">
<instance id="0">
<location y="9.25" x="-253.449980000000011" z="28.400002000000001"/>
</instance>
</population>
<population id="AIMR" component="" type="populationList">
<instance id="0">
<location y="-13.500000999999999" x="-253.449980000000011" z="28.400002000000001"/>
</instance>
</population>
<population id="AINL" component="" type="populationList">
<instance id="0">
<location y="-1.4499999" x="-269.541999999999973" z="39.357998000000002"/>
</instance>
</population>
<population id="AINR" component="" type="populationList">
<instance id="0">
<location y="-3.067" x="-269.541999999999973" z="39.357998000000002"/>
</instance>
</population>
<population id="AIYL" component="" type="populationList">
<instance id="0">
<location y="7.4500003" x="-252.500020000000006" z="28.949999999999999"/>
</instance>
</population>
<population id="AIYR" component="" type="populationList">
<instance id="0">
<location y="-11.699999999999999" x="-252.500020000000006" z="28.949999999999999"/>
</instance>
</population>
<population id="AIZL" component="" type="populationList">
<instance id="0">
<location y="5.6000004" x="-258.75" z="37.450000000000003"/>
</instance>
</population>
<population id="AIZR" component="" type="populationList">
<instance id="0">
<location y="-9.949999999999999" x="-258.75" z="37.450000000000003"/>
</instance>
</population>
<population id="ALA" component="" type="populationList">
<instance id="0">
<location y="-1.35" x="-271." z="50.850000000000001"/>
</instance>
</population>
<population id="ALML" component="" type="populationList">
<instance id="0">
<location y="22.675000000000001" x="-60.75" z="-37.149997999999997"/>
</instance>
</population>
<population id="ALMR" component="" type="populationList">
<instance id="0">
<location y="-24.149999999999999" x="-60.75" z="-37.149997999999997"/>
</instance>
</population>
<population id="ALNL" component="" type="populationList">
<instance id="0">
<location y="0.32500002" x="406.699979999999982" z="12.375"/>
</instance>
</population>
<population id="ALNR" component="" type="populationList">
<instance id="0">
<location y="-2.925" x="406.699979999999982" z="12.375"/>
</instance>
</population>
<population id="AQR" component="" type="populationList">
<instance id="0">
<location y="-14.800000000000001" x="-243.050000000000011" z="33.950000000000003"/>
</instance>
</population>
<population id="AS1" component="" type="populationList">
<instance id="0">
<location y="-0.275" x="-229.038000000000011" z="4.738"/>
</instance>
</population>
<population id="AS10" component="" type="populationList">
<instance id="0">
<location y="-1.9" x="278.25" z="-24."/>
</instance>
</population>
<population id="AS11" component="" type="populationList">
<instance id="0">
<location y="-1.8750001" x="315.699999999999989" z="-26.124998000000001"/>
</instance>
</population>
<population id="AS2" component="" type="populationList">
<instance id="0">
<location y="-1.8750001" x="-203.875" z="-12.725"/>
</instance>
</population>
<population id="AS3" component="" type="populationList">
<instance id="0">
<location y="-1.9" x="-151.400010000000009" z="-45.649997999999997"/>
</instance>
</population>
<population id="AS4" component="" type="populationList">
<instance id="0">
<location y="-1.8750001" x="-90.200005000000004" z="-65.375"/>
</instance>
</population>
<population id="AS5" component="" type="populationList">
<instance id="0">
<location y="-1.8750001" x="-3.7500002" z="-52.524999999999999"/>
</instance>
</population>
<population id="AS6" component="" type="populationList">
<instance id="0">
<location y="-1.9" x="28.25" z="-34.25"/>
</instance>
</population>
<population id="AS7" component="" type="populationList">
<instance id="0">
<location y="-1.9" x="119.900000000000006" z="3.9500003"/>
</instance>
</population>
<population id="AS8" component="" type="populationList">
<instance id="0">
<location y="-1.9" x="181.849999999999994" z="-1.7750001"/>
</instance>
</population>
<population id="AS9" component="" type="populationList">
<instance id="0">
<location y="-1.8750001" x="228.924990000000008" z="-14.5"/>
</instance>
</population>
<population id="ASEL" component="" type="populationList">
<instance id="0">
<location y="4.125" x="-263.675000000000011" z="40.049999999999997"/>
</instance>
</population>
<population id="ASER" component="" type="populationList">
<instance id="0">
<location y="-8.375" x="-263.675000000000011" z="40.049999999999997"/>
</instance>
</population>
<population id="ASGL" component="" type="populationList">
<instance id="0">
<location y="3.7" x="-265.350000000000023" z="45.424999999999997"/>
</instance>
</population>
<population id="ASGR" component="" type="populationList">
<instance id="0">
<location y="-8." x="-265.350000000000023" z="45.424999999999997"/>
</instance>
</population>
<population id="ASHL" component="" type="populationList">
<instance id="0">
<location y="5.55" x="-265.625" z="41."/>
</instance>
</population>
<population id="ASHR" component="" type="populationList">
<instance id="0">
<location y="-9.800000000000001" x="-265.625" z="41."/>
</instance>
</population>
<population id="ASIL" component="" type="populationList">
<instance id="0">
<location y="2.6499999" x="-263.699999999999989" z="46.875"/>
</instance>
</population>
<population id="ASIR" component="" type="populationList">
<instance id="0">
<location y="-6.8999996" x="-263.699999999999989" z="46.875"/>
</instance>
</population>
<population id="ASJL" component="" type="populationList">
<instance id="0">
<location y="2.9750001" x="-263." z="37.475000000000001"/>
</instance>
</population>
<population id="ASJR" component="" type="populationList">
<instance id="0">
<location y="-7.25" x="-263." z="37.475000000000001"/>
</instance>
</population>
<population id="ASKL" component="" type="populationList">
<instance id="0">
<location y="3.7" x="-268.024999999999977" z="46.399997999999997"/>
</instance>
</population>
<population id="ASKR" component="" type="populationList">
<instance id="0">
<location y="-8." x="-268.024999999999977" z="46.399997999999997"/>
</instance>
</population>
<population id="AUAL" component="" type="populationList">
<instance id="0">
<location y="4.5" x="-263.975000000000023" z="37.475000000000001"/>
</instance>
</population>
<population id="AUAR" component="" type="populationList">
<instance id="0">
<location y="-8.800000000000001" x="-263.975000000000023" z="37.475000000000001"/>
</instance>
</population>
<population id="AVAL" component="" type="populationList">
<instance id="0">
<location y="-0.55" x="-271.5" z="37.982999999999997"/>
</instance>
</population>
<population id="AVAR" component="" type="populationList">
<instance id="0">
<location y="-3.5" x="-271.5" z="37.982999999999997"/>
</instance>
</population>
<population id="AVBL" component="" type="populationList">
<instance id="0">
<location y="0.225" x="-269.793999999999983" z="37.863002999999999"/>
</instance>
</population>
<population id="AVBR" component="" type="populationList">
<instance id="0">
<location y="-4.581" x="-269.793999999999983" z="37.863002999999999"/>
</instance>
</population>
<population id="AVDL" component="" type="populationList">
<instance id="0">
<location y="-0.167" x="-268.699999999999989" z="37.299999999999997"/>
</instance>
</population>
<population id="AVDR" component="" type="populationList">
<instance id="0">
<location y="-4.033" x="-268.682999999999993" z="37.283000000000001"/>
</instance>
</population>
<population id="AVEL" component="" type="populationList">
<instance id="0">
<location y="2.75" x="-269.350000000000023" z="40.649999999999999"/>
</instance>
</population>
<population id="AVER" component="" type="populationList">
<instance id="0">
<location y="-8.4" x="-269.350000000000023" z="40.649999999999999"/>
</instance>
</population>
<population id="AVFL" component="" type="populationList">
<instance id="0">
<location y="2.1" x="-246.400000000000006" z="18.600000000000001"/>
</instance>
</population>
<population id="AVFR" component="" type="populationList">
<instance id="0">
<location y="-6.5" x="-246.400000000000006" z="18.600000000000001"/>
</instance>
</population>
<population id="AVG" component="" type="populationList">
<instance id="0">
<location y="-2." x="-237.099999999999994" z="12.85"/>
</instance>
</population>
<population id="AVHL" component="" type="populationList">
<instance id="0">
<location y="4.1499996" x="-264.399999999999977" z="45."/>
</instance>
</population>
<population id="AVHR" component="" type="populationList">
<instance id="0">
<location y="-8.900001" x="-264.399999999999977" z="45."/>
</instance>
</population>
<population id="AVJL" component="" type="populationList">
<instance id="0">
<location y="0.2" x="-264.899999999999977" z="47.549999999999997"/>
</instance>
</population>
<population id="AVJR" component="" type="populationList">
<instance id="0">
<location y="-4.75" x="-264.899999999999977" z="47.549999999999997"/>
</instance>
</population>
<population id="AVKL" component="" type="populationList">
<instance id="0">
<location y="1.65" x="-255." z="22.574999999999999"/>
</instance>
</population>
<population id="AVKR" component="" type="populationList">
<instance id="0">
<location y="-4.583" x="-246.950009999999992" z="19."/>
</instance>
</population>
<population id="AVL" component="" type="populationList">
<instance id="0">
<location y="-7.5000005" x="-263.449999999999989" z="36.350000000000001"/>
</instance>
</population>
<population id="AVM" component="" type="populationList">
<instance id="0">
<location y="-20.5" x="-55.649999999999999" z="-44.600002000000003"/>
</instance>
</population>
<population id="AWAL" component="" type="populationList">
<instance id="0">
<location y="3.9" x="-265.875" z="42.75"/>
</instance>
</population>
<population id="AWAR" component="" type="populationList">
<instance id="0">
<location y="-8.199999999999999" x="-265.875" z="42.75"/>
</instance>
</population>
<population id="AWBL" component="" type="populationList">
<instance id="0">
<location y="5.5" x="-266.225000000000023" z="43.100000000000001"/>
</instance>
</population>
<population id="AWBR" component="" type="populationList">
<instance id="0">
<location y="-9.75" x="-266.225000000000023" z="43.100000000000001"/>
</instance>
</population>
<population id="AWCL" component="" type="populationList">
<instance id="0">
<location y="3.8" x="-267.949999999999989" z="38.950000000000003"/>
</instance>
</population>
<population id="AWCR" component="" type="populationList">
<instance id="0">
<location y="-8.1" x="-267.949999999999989" z="38.950000000000003"/>
</instance>
</population>
<population id="BAGL" component="" type="populationList">
<instance id="0">
<location y="4.675" x="-277.099980000000016" z="44.975002000000003"/>
</instance>
</population>
<population id="BAGR" component="" type="populationList">
<instance id="0">
<location y="-9." x="-277.099980000000016" z="44.975002000000003"/>
</instance>
</population>
<population id="BDUL" component="" type="populationList">
<instance id="0">
<location y="15.35" x="-187.150000000000006" z="-0.2"/>
</instance>
</population>
<population id="BDUR" component="" type="populationList">
<instance id="0">
<location y="-19.649999999999999" x="-187.150000000000006" z="-0.2"/>
</instance>
</population>
<population id="CANL" component="" type="populationList">
<instance id="0">
<location y="25.350002" x="47.950000000000003" z="1.65"/>
</instance>
</population>
<population id="CANR" component="" type="populationList">
<instance id="0">
<location y="-27.25" x="47.950000000000003" z="1.65"/>
</instance>
</population>
<population id="CEPDL" component="" type="populationList">
<instance id="0">
<location y="1.35" x="-275.025019999999984" z="54.075004999999997"/>
</instance>
</population>
<population id="CEPDR" component="" type="populationList">
<instance id="0">
<location y="-5.625" x="-275.025019999999984" z="54.075004999999997"/>
</instance>
</population>
<population id="CEPVL" component="" type="populationList">
<instance id="0">
<location y="0.70000005" x="-277.125" z="39.924999999999997"/>
</instance>
</population>
<population id="CEPVR" component="" type="populationList">
<instance id="0">
<location y="-4.95" x="-277.125" z="39.924999999999997"/>
</instance>
</population>
<population id="DA1" component="" type="populationList">
<instance id="0">
<location y="-0.75" x="-227.075009999999992" z="3.425"/>
</instance>
</population>
<population id="DA2" component="" type="populationList">
<instance id="0">
<location y="-1.9" x="-190.75" z="-21.675000000000001"/>
</instance>
</population>
<population id="DA3" component="" type="populationList">
<instance id="0">
<location y="-1.65" x="-123.650000000000006" z="-58.350002000000003"/>
</instance>
</population>
<population id="DA4" component="" type="populationList">
<instance id="0">
<location y="-1.7" x="-32.399999999999999" z="-61.75"/>
</instance>
</population>
<population id="DA5" component="" type="populationList">
<instance id="0">
<location y="-1.65" x="84.200000000000003" z="-3.15"/>
</instance>
</population>
<population id="DA6" component="" type="populationList">
<instance id="0">
<location y="-1.65" x="198.675000000000011" z="-6.3500004"/>
</instance>
</population>
<population id="DA7" component="" type="populationList">
<instance id="0">
<location y="-1.65" x="281.600000000000023" z="-24.949999999999999"/>
</instance>
</population>
<population id="DA8" component="" type="populationList">
<instance id="0">
<location y="1.275" x="376.800000000000011" z="-10.925000000000001"/>
</instance>
</population>
<population id="DA9" component="" type="populationList">
<instance id="0">
<location y="-4.6" x="376.800000000000011" z="-10.925000000000001"/>
</instance>
</population>
<population id="DB1" component="" type="populationList">
<instance id="0">
<location y="-1.9" x="-230.349989999999991" z="6.85"/>
</instance>
</population>
<population id="DB2" component="" type="populationList">
<instance id="0">
<location y="-0.2" x="-244.5" z="15.787000000000001"/>
</instance>
</population>
<population id="DB3" component="" type="populationList">
<instance id="0">
<location y="-1.85" x="-195.275000000000006" z="-18.524999999999999"/>
</instance>
</population>
<population id="DB4" component="" type="populationList">
<instance id="0">
<location y="-1.8750001" x="-96.275000000000006" z="-64.650000000000006"/>
</instance>
</population>
<population id="DB5" component="" type="populationList">
<instance id="0">
<location y="-4.05" x="35.25" z="-30.449999999999999"/>
</instance>
</population>
<population id="DB6" component="" type="populationList">
<instance id="0">
<location y="-1.8249999" x="178.099999999999994" z="-0.2"/>
</instance>
</population>
<population id="DB7" component="" type="populationList">
<instance id="0">
<location y="-1.85" x="267.75" z="-22.625"/>
</instance>
</population>
<population id="DD1" component="" type="populationList">
<instance id="0">
<location y="-0.9" x="-231.949999999999989" z="6.85"/>
</instance>
</population>
<population id="DD2" component="" type="populationList">
<instance id="0">
<location y="-1.85" x="-156.474989999999991" z="-42.850000000000001"/>
</instance>
</population>
<population id="DD3" component="" type="populationList">
<instance id="0">
<location y="-1.9" x="-28.600002" z="-60.524999999999999"/>
</instance>
</population>
<population id="DD4" component="" type="populationList">
<instance id="0">
<location y="-1.8750001" x="122.899994000000007" z="4.5499997"/>
</instance>
</population>
<population id="DD5" component="" type="populationList">
<instance id="0">
<location y="-1.8750001" x="234.050019999999989" z="-15.775"/>
</instance>
</population>
<population id="DD6" component="" type="populationList">
<instance id="0">
<location y="-1.9" x="365.774999999999977" z="-16.475000000000001"/>
</instance>
</population>
<population id="DVA" component="" type="populationList">
<instance id="0">
<location y="-2.345" x="394.600000000000023" z="3.678"/>
</instance>
</population>
<population id="DVB" component="" type="populationList">
<instance id="0">
<location y="-0.75" x="394.5" z="4."/>
</instance>
</population>
<population id="DVC" component="" type="populationList">
<instance id="0">
<location y="-0.116" x="395.432979999999986" z="5.992"/>
</instance>
</population>
<population id="FLPL" component="" type="populationList">
<instance id="0">
<location y="10.875" x="-246.300000000000011" z="31.050000000000001"/>
</instance>
</population>
<population id="FLPR" component="" type="populationList">
<instance id="0">
<location y="-15.050000000000001" x="-246.300000000000011" z="31.050000000000001"/>
</instance>
</population>
<population id="HSNL" component="" type="populationList">
<instance id="0">
<location y="17.449999999999999" x="61.049999999999997" z="6.95"/>
</instance>
</population>
<population id="HSNR" component="" type="populationList">
<instance id="0">
<location y="-21.649999999999999" x="61.049999999999997" z="6.95"/>
</instance>
</population>
<population id="I1L" component="" type="populationList">
<instance id="0">
<location y="2.8999999" x="-300.350000000000023" z="53.149997999999997"/>
</instance>
</population>
<population id="I1R" component="" type="populationList">
<instance id="0">
<location y="-7.1500006" x="-300.350000000000023" z="53.149997999999997"/>
</instance>
</population>
<population id="I2L" component="" type="populationList">
<instance id="0">
<location y="1.55" x="-311.649999999999977" z="54.450000000000003"/>
</instance>
</population>
<population id="I2R" component="" type="populationList">
<instance id="0">
<location y="-5.7999997" x="-311.649999999999977" z="54.450000000000003"/>
</instance>
</population>
<population id="I3" component="" type="populationList">
<instance id="0">
<location y="-2.05" x="-296.550020000000018" z="58.25"/>
</instance>
</population>
<population id="I4" component="" type="populationList">
<instance id="0">
<location y="-2.05" x="-253.900010000000009" z="43.100000000000001"/>
</instance>
</population>
<population id="I5" component="" type="populationList">
<instance id="0">
<location y="-2.1" x="-247.849989999999991" z="30.675000000000001"/>
</instance>
</population>
<population id="I6" component="" type="populationList">
<instance id="0">
<location y="1.7" x="-251.650000000000006" z="43.049999999999997"/>
</instance>
</population>
<population id="IL1DL" component="" type="populationList">
<instance id="0">
<location y="2.825" x="-282.762999999999977" z="52.762996999999999"/>
</instance>
</population>
<population id="IL1DR" component="" type="populationList">
<instance id="0">
<location y="-7.0620003" x="-282.762999999999977" z="52.762996999999999"/>
</instance>
</population>
<population id="IL1L" component="" type="populationList">
<instance id="0">
<location y="3.8" x="-282.675020000000018" z="47.850002000000003"/>
</instance>
</population>
<population id="IL1R" component="" type="populationList">
<instance id="0">
<location y="-8.075001" x="-282.675020000000018" z="47.850002000000003"/>
</instance>
</population>
<population id="IL1VL" component="" type="populationList">
<instance id="0">
<location y="2.25" x="-279.5" z="41."/>
</instance>
</population>
<population id="IL1VR" component="" type="populationList">
<instance id="0">
<location y="-6.5499997" x="-279.5" z="41."/>
</instance>
</population>
<population id="IL2DL" component="" type="populationList">
<instance id="0">
<location y="7.1000004" x="-287.474980000000016" z="57.125003999999997"/>
</instance>
</population>
<population id="IL2DR" component="" type="populationList">
<instance id="0">
<location y="-11.35" x="-287.474980000000016" z="57.125003999999997"/>
</instance>
</population>
<population id="IL2L" component="" type="populationList">
<instance id="0">
<location y="6.7500005" x="-285." z="49.350000000000001"/>
</instance>
</population>
<population id="IL2R" component="" type="populationList">
<instance id="0">
<location y="-11." x="-285." z="49.350000000000001"/>
</instance>
</population>
<population id="IL2VL" component="" type="populationList">
<instance id="0">
<location y="3.3" x="-288.875" z="42.950000000000003"/>
</instance>
</population>
<population id="IL2VR" component="" type="populationList">
<instance id="0">
<location y="-7.6" x="-288.875" z="42.950000000000003"/>
</instance>
</population>
<population id="LUAL" component="" type="populationList">
<instance id="0">
<location y="1.35" x="403.800020000000018" z="4.1"/>
</instance>
</population>
<population id="LUAR" component="" type="populationList">
<instance id="0">
<location y="-3.85" x="403.800020000000018" z="4.1"/>
</instance>
</population>
<population id="M1" component="" type="populationList">
<instance id="0">
<location y="-0.86700004" x="-252.134999999999991" z="44.420001999999997"/>
</instance>
</population>
<population id="M2L" component="" type="populationList">
<instance id="0">
<location y="3.7" x="-254.349989999999991" z="38.649999999999999"/>
</instance>
</population>
<population id="M2R" component="" type="populationList">
<instance id="0">
<location y="-8." x="-254.349989999999991" z="38.649999999999999"/>
</instance>
</population>
<population id="M3L" component="" type="populationList">
<instance id="0">
<location y="3.7500002" x="-295.399999999999977" z="48.149999999999999"/>
</instance>
</population>
<population id="M3R" component="" type="populationList">
<instance id="0">
<location y="-8.050000000000001" x="-295.399999999999977" z="48.149999999999999"/>
</instance>
</population>
<population id="M4" component="" type="populationList">
<instance id="0">
<location y="-2.033" x="-288.932979999999986" z="57.582999999999998"/>
</instance>
</population>
<population id="M5" component="" type="populationList">
<instance id="0">
<location y="-2.2" x="-241.449999999999989" z="41.800002999999997"/>
</instance>
</population>
<population id="MCL" component="" type="populationList">
<instance id="0">
<location y="3.2" x="-296.149999999999977" z="52.299999999999997"/>
</instance>
</population>
<population id="MCR" component="" type="populationList">
<instance id="0">
<location y="-7.25" x="-296.149999999999977" z="52.299999999999997"/>
</instance>
</population>
<population id="MI" component="" type="populationList">
<instance id="0">
<location y="-2.1539998" x="-293.512020000000007" z="56.707000000000001"/>
</instance>
</population>
<population id="NSML" component="" type="populationList">
<instance id="0">
<location y="2.6000001" x="-292.25" z="51.799999999999997"/>
</instance>
</population>
<population id="NSMR" component="" type="populationList">
<instance id="0">
<location y="-6.3500004" x="-292.25" z="51.799999999999997"/>
</instance>
</population>
<population id="OLLL" component="" type="populationList">
<instance id="0">
<location y="4.4" x="-283.899999999999977" z="50.024997999999997"/>
</instance>
</population>
<population id="OLLR" component="" type="populationList">
<instance id="0">
<location y="-8.65" x="-283.899999999999977" z="50.024997999999997"/>
</instance>
</population>
<population id="OLQDL" component="" type="populationList">
<instance id="0">
<location y="2.775" x="-280." z="53.425002999999997"/>
</instance>
</population>
<population id="OLQDR" component="" type="populationList">
<instance id="0">
<location y="-7.0249996" x="-280." z="53.425002999999997"/>
</instance>
</population>
<population id="OLQVL" component="" type="populationList">
<instance id="0">
<location y="4.2" x="-279.25" z="43.924999999999997"/>
</instance>
</population>
<population id="OLQVR" component="" type="populationList">
<instance id="0">
<location y="-8.474999" x="-279.25" z="43.924999999999997"/>
</instance>
</population>
<population id="PDA" component="" type="populationList">
<instance id="0">
<location y="-2.95" x="387.25" z="-5.5"/>
</instance>
</population>
<population id="PDB" component="" type="populationList">
<instance id="0">
<location y="-3.3" x="384.649999999999977" z="-7.75"/>
</instance>
</population>
<population id="PDEL" component="" type="populationList">
<instance id="0">
<location y="25.75" x="143.800000000000011" z="25.600000000000001"/>
</instance>
</population>
<population id="PDER" component="" type="populationList">
<instance id="0">
<location y="-27.350000000000001" x="143.800000000000011" z="25.600000000000001"/>
</instance>
</population>
<population id="PHAL" component="" type="populationList">
<instance id="0">
<location y="1.2" x="402.899999999999977" z="4.1"/>
</instance>
</population>
<population id="PHAR" component="" type="populationList">
<instance id="0">
<location y="-3.8" x="402.899999999999977" z="4.1"/>
</instance>
</population>
<population id="PHBL" component="" type="populationList">
<instance id="0">
<location y="1.2" x="405.600039999999979" z="5.475"/>
</instance>
</population>
<population id="PHBR" component="" type="populationList">
<instance id="0">
<location y="-3.7250001" x="405.600039999999979" z="5.475"/>
</instance>
</population>
<population id="PHCL" component="" type="populationList">
<instance id="0">
<location y="0.75" x="408.774999999999977" z="7.275"/>
</instance>
</population>
<population id="PHCR" component="" type="populationList">
<instance id="0">
<location y="-3.425" x="408.774999999999977" z="7.275"/>
</instance>
</population>
<population id="PLML" component="" type="populationList">
<instance id="0">
<location y="2.5" x="410.149999999999977" z="8.175000000000001"/>
</instance>
</population>
<population id="PLMR" component="" type="populationList">
<instance id="0">
<location y="-3.675" x="410.149999999999977" z="8.175000000000001"/>
</instance>
</population>
<population id="PLNL" component="" type="populationList">
<instance id="0">
<location y="4.225" x="402.300000000000011" z="6.8999996"/>
</instance>
</population>
<population id="PLNR" component="" type="populationList">
<instance id="0">
<location y="-6.225" x="402.300000000000011" z="6.8999996"/>
</instance>
</population>
<population id="PQR" component="" type="populationList">
<instance id="0">
<location y="-0.32500002" x="407.300000000000011" z="7.6499996"/>
</instance>
</population>
<population id="PVCL" component="" type="populationList">
<instance id="0">
<location y="0.85" x="404.150019999999984" z="5.5"/>
</instance>
</population>
<population id="PVCR" component="" type="populationList">
<instance id="0">
<location y="-3.4499998" x="404.150019999999984" z="5.5"/>
</instance>
</population>
<population id="PVDL" component="" type="populationList">
<instance id="0">
<location y="24.748999999999999" x="175.15100000000001" z="24.952000000000002"/>
</instance>
</population>
<population id="PVDR" component="" type="populationList">
<instance id="0">
<location y="-26.113997999999999" x="175.15100000000001" z="24.952000000000002"/>
</instance>
</population>
<population id="PVM" component="" type="populationList">
<instance id="0">
<location y="24.850000000000001" x="188.800000000000011" z="20.550001000000002"/>
</instance>
</population>
<population id="PVNL" component="" type="populationList">
<instance id="0">
<location y="0.55" x="410." z="8.900001"/>
</instance>
</population>
<population id="PVNR" component="" type="populationList">
<instance id="0">
<location y="-3.25" x="409.949999999999989" z="8.900001"/>
</instance>
</population>
<population id="PVPL" component="" type="populationList">
<instance id="0">
<location y="-0.1" x="366.650019999999984" z="-14.699999999999999"/>
</instance>
</population>
<population id="PVPR" component="" type="populationList">
<instance id="0">
<location y="-0.15" x="356.550000000000011" z="-16.649999999999999"/>
</instance>
</population>
<population id="PVQL" component="" type="populationList">
<instance id="0">
<location y="0.85" x="402.400019999999984" z="5.15"/>
</instance>
</population>
<population id="PVQR" component="" type="populationList">
<instance id="0">
<location y="-3.3" x="402.400019999999984" z="5.15"/>
</instance>
</population>
<population id="PVR" component="" type="populationList">
<instance id="0">
<location y="-1.85" x="407.350000000000023" z="7.7"/>
</instance>
</population>
<population id="PVT" component="" type="populationList">
<instance id="0">
<location y="-0.1" x="358.75" z="-17.5"/>
</instance>
</population>
<population id="PVWL" component="" type="populationList">
<instance id="0">
<location y="0.8" x="405.399999999999977" z="6.8"/>
</instance>
</population>
<population id="PVWR" component="" type="populationList">
<instance id="0">
<location y="-3.4" x="405.399999999999977" z="6.8"/>
</instance>
</population>
<population id="RIAL" component="" type="populationList">
<instance id="0">
<location y="4." x="-270.25" z="45."/>
</instance>
</population>
<population id="RIAR" component="" type="populationList">
<instance id="0">
<location y="-8.199999999999999" x="-270.25" z="45."/>
</instance>
</population>
<population id="RIBL" component="" type="populationList">
<instance id="0">
<location y="5.5" x="-264.350000000000023" z="38."/>
</instance>
</population>
<population id="RIBR" component="" type="populationList">
<instance id="0">
<location y="-9.800000000000001" x="-264.350000000000023" z="38."/>
</instance>
</population>
<population id="RICL" component="" type="populationList">
<instance id="0">
<location y="-0.737" x="-267.062999999999988" z="38.087000000000003"/>
</instance>
</population>
<population id="RICR" component="" type="populationList">
<instance id="0">
<location y="-3.563" x="-267.062999999999988" z="38.087000000000003"/>
</instance>
</population>
<population id="RID" component="" type="populationList">
<instance id="0">
<location y="-1.225" x="-272.350000000000023" z="54.938000000000002"/>
</instance>
</population>
<population id="RIFL" component="" type="populationList">
<instance id="0">
<location y="0." x="-239.849989999999991" z="18.350000000000001"/>
</instance>
</population>
<population id="RIFR" component="" type="populationList">
<instance id="0">
<location y="-5.15" x="-245.5" z="23.899999999999999"/>
</instance>
</population>
<population id="RIGL" component="" type="populationList">
<instance id="0">
<location y="0." x="-233.25" z="16.350000000000001"/>
</instance>
</population>
<population id="RIGR" component="" type="populationList">
<instance id="0">
<location y="-4.7" x="-241.950009999999992" z="20.649999999999999"/>
</instance>
</population>
<population id="RIH" component="" type="populationList">
<instance id="0">
<location y="-2." x="-267.350000000000023" z="35.950000000000003"/>
</instance>
</population>
<population id="RIML" component="" type="populationList">
<instance id="0">
<location y="3.5" x="-260.899999999999977" z="39."/>
</instance>
</population>
<population id="RIMR" component="" type="populationList">
<instance id="0">
<location y="-7.75" x="-260.899999999999977" z="39."/>
</instance>
</population>
<population id="RIPL" component="" type="populationList">
<instance id="0">
<location y="3.3750002" x="-278.574979999999982" z="48.824997000000003"/>
</instance>
</population>
<population id="RIPR" component="" type="populationList">
<instance id="0">
<location y="-7.625" x="-278.574979999999982" z="48.824997000000003"/>
</instance>
</population>
<population id="RIR" component="" type="populationList">
<instance id="0">
<location y="-11.599999" x="-265.899999999999977" z="36.649997999999997"/>
</instance>
</population>
<population id="RIS" component="" type="populationList">
<instance id="0">
<location y="-4.8250003" x="-262.163000000000011" z="33.637999999999998"/>
</instance>
</population>
<population id="RIVL" component="" type="populationList">
<instance id="0">
<location y="4.5" x="-265.300020000000018" z="50.350000000000001"/>
</instance>
</population>
<population id="RIVR" component="" type="populationList">
<instance id="0">
<location y="-8.75" x="-265.300020000000018" z="50.350000000000001"/>
</instance>
</population>
<population id="RMDDL" component="" type="populationList">
<instance id="0">
<location y="3.6" x="-269.074979999999982" z="37.649999999999999"/>
</instance>
</population>
<population id="RMDDR" component="" type="populationList">
<instance id="0">
<location y="-7.75" x="-269.074979999999982" z="37.649999999999999"/>
</instance>
</population>
<population id="RMDL" component="" type="populationList">
<instance id="0">
<location y="3.1" x="-271." z="41.200000000000003"/>
</instance>
</population>
<population id="RMDR" component="" type="populationList">
<instance id="0">
<location y="-7.4" x="-271." z="41.200000000000003"/>
</instance>
</population>
<population id="RMDVL" component="" type="populationList">
<instance id="0">
<location y="4.8500004" x="-271.199979999999982" z="44.399999999999999"/>
</instance>
</population>
<population id="RMDVR" component="" type="populationList">
<instance id="0">
<location y="-9.049999" x="-271.199979999999982" z="44.399999999999999"/>
</instance>
</population>
<population id="RMED" component="" type="populationList">
<instance id="0">
<location y="-1.5" x="-275.75" z="58.499996000000003"/>
</instance>
</population>
<population id="RMEL" component="" type="populationList">
<instance id="0">
<location y="4.65" x="-274.399999999999977" z="46.987000000000002"/>
</instance>
</population>
<population id="RMER" component="" type="populationList">
<instance id="0">
<location y="-8.900001" x="-274.399999999999977" z="46.987000000000002"/>
</instance>
</population>
<population id="RMEV" component="" type="populationList">
<instance id="0">
<location y="-2.033" x="-272.966999999999985" z="35.667000000000002"/>
</instance>
</population>
<population id="RMFL" component="" type="populationList">
<instance id="0">
<location y="1.1" x="-265.050020000000018" z="34.100000000000001"/>
</instance>
</population>
<population id="RMFR" component="" type="populationList">
<instance id="0">
<location y="-5.4" x="-265.050020000000018" z="34.100000000000001"/>
</instance>
</population>
<population id="RMGL" component="" type="populationList">
<instance id="0">
<location y="8.25" x="-238.299990000000008" z="32.700000000000003"/>
</instance>
</population>
<population id="RMGR" component="" type="populationList">
<instance id="0">
<location y="-12.5" x="-238.299990000000008" z="32.700000000000003"/>
</instance>
</population>
<population id="RMHL" component="" type="populationList">
<instance id="0">
<location y="1.1" x="-265.899999999999977" z="35.700000000000003"/>
</instance>
</population>
<population id="RMHR" component="" type="populationList">
<instance id="0">
<location y="-5.2999997" x="-265.899999999999977" z="35.700000000000003"/>
</instance>
</population>
<population id="SAADL" component="" type="populationList">
<instance id="0">
<location y="-4.6879997" x="-270.168999999999983" z="42.131"/>
</instance>
</population>
<population id="SAADR" component="" type="populationList">
<instance id="0">
<location y="0.531" x="-270.168999999999983" z="42.131"/>
</instance>
</population>
<population id="SAAVL" component="" type="populationList">
<instance id="0">
<location y="3.9" x="-270.900019999999984" z="45.424999999999997"/>
</instance>
</population>
<population id="SAAVR" component="" type="populationList">
<instance id="0">
<location y="-8.175000000000001" x="-270.900019999999984" z="45.424999999999997"/>
</instance>
</population>
<population id="SABD" component="" type="populationList">
<instance id="0">
<location y="-3.2" x="-234.800000000000011" z="14.925000000000001"/>
</instance>
</population>
<population id="SABVL" component="" type="populationList">
<instance id="0">
<location y="3.325" x="-249.25" z="24.349997999999999"/>
</instance>
</population>
<population id="SABVR" component="" type="populationList">
<instance id="0">
<location y="-8.1" x="-249.25" z="24.349997999999999"/>
</instance>
</population>
<population id="SDQL" component="" type="populationList">
<instance id="0">
<location y="21.399999999999999" x="222.799990000000008" z="19.199999999999999"/>
</instance>
</population>
<population id="SDQR" component="" type="populationList">
<instance id="0">
<location y="-14.200001" x="-131.75" z="-10.550000000000001"/>
</instance>
</population>
<population id="SIADL" component="" type="populationList">
<instance id="0">
<location y="-3.958" x="-267.658000000000015" z="43.966999999999999"/>
</instance>
</population>
<population id="SIADR" component="" type="populationList">
<instance id="0">
<location y="-0.38300002" x="-269.199979999999982" z="43.649999999999999"/>
</instance>
</population>
<population id="SIAVL" component="" type="populationList">
<instance id="0">
<location y="5.9500003" x="-259.800020000000018" z="32.25"/>
</instance>
</population>
<population id="SIAVR" component="" type="populationList">
<instance id="0">
<location y="-10.199999999999999" x="-259.800020000000018" z="32.25"/>
</instance>
</population>
<population id="SIBDL" component="" type="populationList">
<instance id="0">
<location y="-5.2669997" x="-269.132999999999981" z="45.799999999999997"/>
</instance>
</population>
<population id="SIBDR" component="" type="populationList">
<instance id="0">
<location y="0.96699995" x="-269.132999999999981" z="45.799999999999997"/>
</instance>
</population>
<population id="SIBVL" component="" type="populationList">
<instance id="0">
<location y="-2.667" x="-269.867000000000019" z="35.408000000000001"/>
</instance>
</population>
<population id="SIBVR" component="" type="populationList">
<instance id="0">
<location y="-2.767" x="-269.867000000000019" z="35.408000000000001"/>
</instance>
</population>
<population id="SMBDL" component="" type="populationList">
<instance id="0">
<location y="3.1" x="-264.300000000000011" z="33.100000000000001"/>
</instance>
</population>
<population id="SMBDR" component="" type="populationList">
<instance id="0">
<location y="-7." x="-264.300000000000011" z="33.100000000000001"/>
</instance>
</population>
<population id="SMBVL" component="" type="populationList">
<instance id="0">
<location y="0.425" x="-263.449999999999989" z="33.049999999999997"/>
</instance>
</population>
<population id="SMBVR" component="" type="populationList">
<instance id="0">
<location y="-4.6" x="-263.449999999999989" z="33.049999999999997"/>
</instance>
</population>
<population id="SMDDL" component="" type="populationList">
<instance id="0">
<location y="3.25" x="-266.25" z="34.100000000000001"/>
</instance>
</population>
<population id="SMDDR" component="" type="populationList">
<instance id="0">
<location y="-7.4500003" x="-266.25" z="34.100000000000001"/>
</instance>
</population>
<population id="SMDVL" component="" type="populationList">
<instance id="0">
<location y="4.7" x="-270.949999999999989" z="46.649999999999999"/>
</instance>
</population>
<population id="SMDVR" component="" type="populationList">
<instance id="0">
<location y="-8.900001" x="-270.949999999999989" z="46.649999999999999"/>
</instance>
</population>
<population id="URADL" component="" type="populationList">
<instance id="0">
<location y="5." x="-284.649999999999977" z="52.200000000000003"/>
</instance>
</population>
<population id="URADR" component="" type="populationList">
<instance id="0">
<location y="-9.300000000000001" x="-284.649999999999977" z="52.200000000000003"/>
</instance>
</population>
<population id="URAVL" component="" type="populationList">
<instance id="0">
<location y="0.32500002" x="-279.600000000000023" z="41.399999999999999"/>
</instance>
</population>
<population id="URAVR" component="" type="populationList">
<instance id="0">
<location y="-4.575" x="-279.600000000000023" z="41.399999999999999"/>
</instance>
</population>
<population id="URBL" component="" type="populationList">
<instance id="0">
<location y="5.05" x="-279.949999999999989" z="47.549999999999997"/>
</instance>
</population>
<population id="URBR" component="" type="populationList">
<instance id="0">
<location y="-9.324999999999999" x="-279.949999999999989" z="47.549999999999997"/>
</instance>
</population>
<population id="URXL" component="" type="populationList">
<instance id="0">
<location y="3.05" x="-269.875" z="48.274999999999999"/>
</instance>
</population>
<population id="URXR" component="" type="populationList">
<instance id="0">
<location y="-7.35" x="-269.875" z="48.274999999999999"/>
</instance>
</population>
<population id="URYDL" component="" type="populationList">
<instance id="0">
<location y="4.125" x="-281.425000000000011" z="51.899997999999997"/>
</instance>
</population>
<population id="URYDR" component="" type="populationList">
<instance id="0">
<location y="-8.4" x="-281.425000000000011" z="51.899997999999997"/>
</instance>
</population>
<population id="URYVL" component="" type="populationList">
<instance id="0">
<location y="3.4" x="-280.925020000000018" z="45.350000000000001"/>
</instance>
</population>
<population id="URYVR" component="" type="populationList">
<instance id="0">
<location y="-7.7" x="-280.925020000000018" z="45.350000000000001"/>
</instance>
</population>
<population id="VA1" component="" type="populationList">
<instance id="0">
<location y="-1.35" x="-235.550000000000011" z="11.75"/>
</instance>
</population>
<population id="VA10" component="" type="populationList">
<instance id="0">
<location y="-1.85" x="254.625020000000006" z="-21.25"/>
</instance>
</population>
<population id="VA11" component="" type="populationList">
<instance id="0">
<location y="-1.55" x="312.350000000000023" z="-26.249998000000001"/>
</instance>
</population>
<population id="VA12" component="" type="populationList">
<instance id="0">
<location y="-0.1" x="362.449999999999989" z="-18.149999999999999"/>
</instance>
</population>
<population id="VA2" component="" type="populationList">
<instance id="0">
<location y="-1.85" x="-217.099999999999994" z="-3.9500003"/>
</instance>
</population>
<population id="VA3" component="" type="populationList">
<instance id="0">
<location y="-1.475" x="-184.099989999999991" z="-26.374998000000001"/>
</instance>
</population>
<population id="VA4" component="" type="populationList">
<instance id="0">
<location y="-1.85" x="-119.500010000000003" z="-58.700000000000003"/>
</instance>
</population>
<population id="VA5" component="" type="populationList">
<instance id="0">
<location y="-1.85" x="-54.299999999999997" z="-66.049994999999996"/>
</instance>
</population>
<population id="VA6" component="" type="populationList">
<instance id="0">
<location y="-1.85" x="21.550000000000001" z="-41.149999999999999"/>
</instance>
</population>
<population id="VA7" component="" type="populationList">
<instance id="0">
<location y="-1.85" x="98.049994999999996" z="1.175"/>
</instance>
</population>
<population id="VA8" component="" type="populationList">
<instance id="0">
<location y="-1.8" x="150.300000000000011" z="3.4"/>
</instance>
</population>
<population id="VA9" component="" type="populationList">
<instance id="0">
<location y="-1.8" x="208.824999999999989" z="-9.049999"/>
</instance>
</population>
<population id="VB1" component="" type="populationList">
<instance id="0">
<location y="-1.55" x="-246.449999999999989" z="16.399999999999999"/>
</instance>
</population>
<population id="VB10" component="" type="populationList">
<instance id="0">
<location y="-1.85" x="218.074980000000011" z="-11.4"/>
</instance>
</population>
<population id="VB11" component="" type="populationList">
<instance id="0">
<location y="-1.8249999" x="262.324999999999989" z="-21.949999999999999"/>
</instance>
</population>
<population id="VB2" component="" type="populationList">
<instance id="0">
<location y="-2." x="-253.300000000000011" z="19.850000000000001"/>
</instance>
</population>
<population id="VB3" component="" type="populationList">
<instance id="0">
<location y="-1.85" x="-210.224999999999994" z="-8.725"/>
</instance>
</population>
<population id="VB4" component="" type="populationList">
<instance id="0">
<location y="-2." x="-173.25" z="-33.5"/>
</instance>
</population>
<population id="VB5" component="" type="populationList">
<instance id="0">
<location y="-1.85" x="-109.549999999999997" z="-62.149999999999999"/>
</instance>
</population>
<population id="VB6" component="" type="populationList">
<instance id="0">
<location y="-1.85" x="-36.575000000000003" z="-62.699997000000003"/>
</instance>
</population>
<population id="VB7" component="" type="populationList">
<instance id="0">
<location y="-9.675000000000001" x="41.450000000000003" z="-24.361999999999998"/>
</instance>
</population>
<population id="VB8" component="" type="populationList">
<instance id="0">
<location y="-1.8249999" x="108.799999999999997" z="2.875"/>
</instance>
</population>
<population id="VB9" component="" type="populationList">
<instance id="0">
<location y="-1.85" x="159.550000000000011" z="3.2"/>
</instance>
</population>
<population id="VC1" component="" type="populationList">
<instance id="0">
<location y="-0.72499996" x="-170.025010000000009" z="-35.75"/>
</instance>
</population>
<population id="VC2" component="" type="populationList">
<instance id="0">
<location y="-0.625" x="-105.325000000000003" z="-63.399999999999999"/>
</instance>
</population>
<population id="VC3" component="" type="populationList">
<instance id="0">
<location y="-1.4499999" x="-6.45" z="-54.000003999999997"/>
</instance>
</population>
<population id="VC4" component="" type="populationList">
<instance id="0">
<location y="-1.15" x="43.850000000000001" z="-24.199999999999999"/>
</instance>
</population>
<population id="VC5" component="" type="populationList">
<instance id="0">
<location y="-1.15" x="66.549994999999996" z="-12.5"/>
</instance>
</population>
<population id="VC6" component="" type="populationList">
<instance id="0">
<location y="-1.8249999" x="174.175000000000011" z="1."/>
</instance>
</population>
<population id="VD1" component="" type="populationList">
<instance id="0">
<location y="-0.70000005" x="-228.599999999999994" z="4.05"/>
</instance>
</population>
<population id="VD10" component="" type="populationList">
<instance id="0">
<location y="-0.75" x="236.099999999999994" z="-16.5"/>
</instance>
</population>
<population id="VD11" component="" type="populationList">
<instance id="0">
<location y="-0.8" x="283.800020000000018" z="-24.800000000000001"/>
</instance>
</population>
<population id="VD12" component="" type="populationList">
<instance id="0">
<location y="-0.75" x="345.5" z="-23.149999999999999"/>
</instance>
</population>
<population id="VD13" component="" type="populationList">
<instance id="0">
<location y="-0.75" x="379.850000000000023" z="-10.75"/>
</instance>
</population>
<population id="VD2" component="" type="populationList">
<instance id="0">
<location y="-0.65000004" x="-226.049990000000008" z="2.35"/>
</instance>
</population>
<population id="VD3" component="" type="populationList">
<instance id="0">
<location y="-0.8" x="-188.099999999999994" z="-23.449999999999999"/>
</instance>
</population>
<population id="VD4" component="" type="populationList">
<instance id="0">
<location y="-0.8" x="-137.199999999999989" z="-52.700000000000003"/>
</instance>
</population>
<population id="VD5" component="" type="populationList">
<instance id="0">
<location y="-0.75" x="-68.299999999999997" z="-66.75"/>
</instance>
</population>
<population id="VD6" component="" type="populationList">
<instance id="0">
<location y="-0.70000005" x="-1.4000001" z="-52.149997999999997"/>
</instance>
</population>
<population id="VD7" component="" type="populationList">
<instance id="0">
<location y="-12.349999" x="57.950000000000003" z="-14.200001"/>
</instance>
</population>
<population id="VD8" component="" type="populationList">
<instance id="0">
<location y="-0.75" x="135.099989999999991" z="3.9500003"/>
</instance>
</population>
<population id="VD9" component="" type="populationList">
<instance id="0">
<location y="-0.8" x="191.5" z="-3.8"/>
</instance>
</population>
"""
| [
"[email protected]"
] | |
46420d6d79533b4847126b91595955ff96211153 | 0a46b027e8e610b8784cb35dbad8dd07914573a8 | /scripts/venv/lib/python2.7/site-packages/cogent/maths/stats/information_criteria.py | ead8f6417df1dd2fa2049a479c7f9aa4b4de1829 | [
"MIT"
] | permissive | sauloal/cnidaria | bb492fb90a0948751789938d9ec64677052073c3 | fe6f8c8dfed86d39c80f2804a753c05bb2e485b4 | refs/heads/master | 2021-01-17T13:43:17.307182 | 2016-10-05T14:14:46 | 2016-10-05T14:14:46 | 33,726,643 | 3 | 0 | null | null | null | null | UTF-8 | Python | false | false | 1,145 | py | from __future__ import division
import numpy
__author__ = "Gavin Huttley"
__copyright__ = "Copyright 2007-2012, The Cogent Project"
__credits__ = ["Gavin Huttley"]
__license__ = "GPL"
__version__ = "1.5.3"
__maintainer__ = "Gavin Huttley"
__email__ = "[email protected]"
__status__ = "Production"
def aic(lnL, nfp, sample_size=None):
"""returns Aikake Information Criterion
Arguments:
- lnL: the maximum log-likelihood of a model
- nfp: the number of free parameters in the model
- sample_size: if provided, the second order AIC is returned
"""
if sample_size is None:
correction = 1
else:
assert sample_size > 0, "Invalid sample_size %s" % sample_size
correction = sample_size / (sample_size - nfp - 1)
return -2* lnL + 2 * nfp * correction
def bic(lnL, nfp, sample_size):
"""returns Bayesian Information Criterion
Arguments:
- lnL: the maximum log-likelihood of a model
- nfp: the number of free parameters in the model
- sample_size: size of the sample
"""
return -2* lnL + nfp * numpy.log(sample_size)
| [
"[email protected]"
] | |
b254df743e617dfd1390743f0e04bbe4d12cb542 | ca7aa979e7059467e158830b76673f5b77a0f5a3 | /Python_codes/p03227/s922156594.py | 3367f99a10180d83d75fbea989fb7e0b5a810cdd | [] | 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 | 173 | py | import sys
def input(): return sys.stdin.readline().rstrip()
def main():
s=input()
if len(s)==2:print(s)
else:print(s[::-1])
if __name__=='__main__':
main() | [
"[email protected]"
] | |
ae180e8cf37b46499f5232dd71f2789e8e56b342 | a16691abb472e2d57cf417cc671e7574f97aaf23 | /src/13_millas.py | 785d28eea60a685a38043e0f43f552b1e14265d4 | [
"MIT"
] | permissive | agomusa/oop-algorithms-python-platzi | fbb16208b68e822c6232ffb944c414c176004ac1 | 56e5f636c9243fbd81148a6e6e8405034f362c70 | refs/heads/main | 2023-06-19T21:38:19.925134 | 2021-07-07T20:49:09 | 2021-07-07T20:49:09 | null | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 733 | py | class Millas:
def __init__(self):
self._distancia = 0
# Función para obtener el valor de _distancia
def obtener_distancia(self):
print("Llamada al método getter...")
return self._distancia
# Función para definir el valor de _distancia
def definir_distancia(self, recorrido):
print("Llamada al método setter...")
self._distancia = recorrido
# Función para eliminar el atributo _distancia
def eliminar_distancia(self):
del self._distancia
distancia = property(obtener_distancia, definir_distancia, eliminar_distancia)
if __name__ == '__main__':
avion = Millas()
avion.distancia = int(input('¿Cuantas millas vas a viajar? '))
print('Vas a viajar '+str(avion.distancia*1.609344)+' Kilometros')
| [
"[email protected]"
] | |
5c713e71b6d36c733a3c7071ffaec82c80094caa | f8826a479f2b9d2f28993ceea7a7d0e3847aaf3d | /apps/requestlogger/models.py | 9fa6f370798fdbd62b4484b8acf1d332f55c10a0 | [] | no_license | icomms/wqmanager | bec6792ada11af0ff55dc54fd9b9ba49242313b7 | f683b363443e1c0be150656fd165e07a75693f55 | refs/heads/master | 2021-01-20T11:59:42.299351 | 2012-02-20T15:28:40 | 2012-02-20T15:28:40 | 2,154,449 | 1 | 1 | null | null | null | null | UTF-8 | Python | false | false | 2,869 | py | from django.db import models
from django.contrib.auth.models import User
from domain.models import Domain
import os
import logging
import settings
# this is a really bad place for this class to live, but reference it here for now
from scheduler.fields import PickledObjectField
from datetime import datetime
from django.utils.translation import ugettext_lazy as _
from django.core.urlresolvers import reverse
REQUEST_TYPES = (
('GET', 'Get'),
('POST', 'Post'),
('PUT', 'Put'),
)
class RequestLog(models.Model):
'''Keeps track of incoming requests'''
# Lots of stuff here is replicated in Submission.
# They should ultimately point here, but that's a data migration
# problem.
method = models.CharField(max_length=4, choices=REQUEST_TYPES)
url = models.CharField(max_length=200)
time = models.DateTimeField(_('Request Time'), default = datetime.now)
ip = models.IPAddressField(_('Submitting IP Address'), null=True, blank=True)
is_secure = models.BooleanField(default=False)
# The logged in user
user = models.ForeignKey(User, null=True, blank=True)
# Some pickled fields for having access to the raw info
headers = PickledObjectField(_('Request Headers'))
parameters = PickledObjectField(_('Request Parameters'))
def __unicode__(self):
return "%s to %s at %s from %s" % (self.method, self.url,
self.time, self.ip)
@classmethod
def from_request(cls, request):
'''Creates an instance of a RequestLog from a standard
django HttpRequest object.
'''
log = RequestLog()
log.method = request.method
log.url = request.build_absolute_uri(request.path)
log.time = datetime.now()
log.is_secure = request.is_secure()
if request.META.has_key('REMOTE_ADDR') and request.META['REMOTE_ADDR']:
log.ip = request.META['REMOTE_ADDR']
elif request.META.has_key('REMOTE_HOST') and request.META['REMOTE_HOST']:
log.ip = request.META['REMOTE_HOST']
# if request.user != User, then user is anonymous
if isinstance(request.user, User):
log.user = request.user
def _convert_to_dict(obj):
# converts a django-querydict to a true python dict
# and converts any values to strings. This could result
# in a loss of information
to_return = {}
for key, value in obj.items():
to_return[key] = str(value)
return to_return
log.headers = _convert_to_dict(request.META)
if request.method == "GET":
log.parameters = _convert_to_dict(request.GET)
else:
log.parameters = _convert_to_dict(request.POST)
return log | [
"[email protected]"
] | |
ba11fe85c801d07e0e7c25b58d3aee09665d8952 | 77a7508c3a647711191b924959db80fb6d2bd146 | /src/gamesbyexample/worms.py | 2bea231d0dbdaeacc62cad083fcc56fafc920fb4 | [
"MIT"
] | permissive | surlydev/PythonStdioGames | ff7edb4c8c57a5eb6e2036e2b6ebc7e23ec994e0 | d54c2509c12a5b1858eda275fd07d0edd456f23f | refs/heads/master | 2021-05-22T21:01:15.529159 | 2020-03-26T07:34:10 | 2020-03-26T07:34:10 | null | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 5,750 | py | """Worm animation, by Al Sweigart [email protected]
A screensaver of multicolor worms moving around.
NOTE: Do not resize the terminal window while this program is running.
Tags: large, artistic, simulation, bext"""
__version__ = 0
import random, shutil, sys, time
try:
import bext
except ImportError:
print('''This program requires the bext module, which you can
install by opening a Terminal window (on macOS & Linux) and running:
python3 -m pip install --user bext
or a Command Prompt window (on Windows) and running:
python -m pip install --user bext''')
sys.exit()
# Set up the constants:
PAUSE_LENGTH = 0.1
# Get the size of the terminal window:
WIDTH, HEIGHT = shutil.get_terminal_size()
# We can't print to the last column on Windows without it adding a
# newline automatically, so reduce the width by one:
WIDTH -= 1
WIDTH //= 2
NUMBER_OF_WORMS = 12 # (!) Try changing this value.
MIN_WORM_LENGTH = 6 # (!) Try changing this value.
MAX_WORM_LENGTH = 16 # (!) Try changing this value.
ALL_COLORS = bext.ALL_COLORS
NORTH = 'north'
SOUTH = 'south'
EAST = 'east'
WEST = 'west'
BLOCK = chr(9608) # Character 9608 is '█'
def main():
# Generate worm data structures:
worms = []
for i in range(NUMBER_OF_WORMS):
worms.append(Worm())
bext.clear()
while True: # Main simulation loop.
# Draw quit message.
bext.fg('white')
bext.goto(0, 0)
print('Ctrl-C to quit.', end='')
for worm in worms:
worm.display()
for worm in worms:
worm.moveRandom()
sys.stdout.flush()
time.sleep(PAUSE_LENGTH)
class Worm:
def __init__(self):
self.length = random.randint(MIN_WORM_LENGTH, MAX_WORM_LENGTH)
coloration = random.choice(['solid', 'stripe', 'random'])
if coloration == 'solid':
self.colors = [random.choice(ALL_COLORS)] * self.length
elif coloration == 'stripe':
color1 = random.choice(ALL_COLORS)
color2 = random.choice(ALL_COLORS)
self.colors = []
for i in range(self.length):
self.colors.append((color1, color2)[i % 2])
elif coloration == 'random':
self.colors = []
for i in range(self.length):
self.colors.append(random.choice(ALL_COLORS))
x = random.randint(0, WIDTH - 1)
y = random.randint(0, HEIGHT - 1)
self.body = []
for i in range(self.length):
self.body.append((x, y))
x, y = getRandomNeighbor(x, y)
def moveNorth(self):
headx, heady = self.body[0]
if self.isBlocked(NORTH):
return False
self.body.insert(0, (headx, heady - 1))
self._eraseLastBodySegment()
return True
def moveSouth(self):
headx, heady = self.body[0]
if self.isBlocked(SOUTH):
return False
self.body.insert(0, (headx, heady + 1))
self._eraseLastBodySegment()
return True
def moveEast(self):
headx, heady = self.body[0]
if self.isBlocked(EAST):
return False
self.body.insert(0, (headx + 1, heady))
self._eraseLastBodySegment()
return True
def moveWest(self):
headx, heady = self.body[0]
if self.isBlocked(WEST):
return False
self.body.insert(0, (headx - 1, heady))
self._eraseLastBodySegment()
return True
def isBlocked(self, direction):
headx, heady = self.body[0]
if direction == NORTH:
return heady == 0 or (headx, heady - 1) in self.body
elif direction == SOUTH:
return heady == HEIGHT - 1 or (headx, heady + 1) in self.body
elif direction == EAST:
return headx == WIDTH - 1 or (headx + 1, heady) in self.body
elif direction == WEST:
return headx == 0 or (headx - 1, heady) in self.body
def moveRandom(self):
if self.isBlocked(NORTH) and self.isBlocked(SOUTH) and self.isBlocked(EAST) and self.isBlocked(WEST):
self.body.reverse()
if self.isBlocked(NORTH) and self.isBlocked(SOUTH) and self.isBlocked(EAST) and self.isBlocked(WEST):
return False
hasMoved = False
while not hasMoved:
direction = random.choice([NORTH, SOUTH, EAST, WEST])
if direction == NORTH:
hasMoved = self.moveNorth()
elif direction == SOUTH:
hasMoved = self.moveSouth()
elif direction == EAST:
hasMoved = self.moveEast()
elif direction == WEST:
hasMoved = self.moveWest()
def _eraseLastBodySegment(self):
# Erase the last body segment:
bext.goto(self.body[-1][0] * 2, self.body[-1][1])
print(' ', end='')
self.body.pop() # Delete the last (x, y) tuple in self.body.
def display(self):
for i, (x, y) in enumerate(self.body):
bext.goto(x * 2, y)
bext.fg(self.colors[i])
print(BLOCK + BLOCK, end='')
def getRandomNeighbor(x, y):
while True:
direction = random.choice((NORTH, SOUTH, EAST, WEST))
if direction == NORTH and y != 0:
return (x, y - 1)
elif direction == SOUTH and y != HEIGHT - 1:
return (x, y + 1)
elif direction == EAST and x != WIDTH - 1:
return (x + 1, y)
elif direction == WEST and x != 0:
return (x - 1, y)
# If this program was run (instead of imported), run the game:
if __name__ == '__main__':
try:
main()
except KeyboardInterrupt:
sys.exit() # When Ctrl-C is pressed, end the program.
| [
"[email protected]"
] | |
11cd4d65d01665c0d10e4866ca5ef1b2c881800c | be9d18c3ac86921e8899a830ec42d35edd440919 | /moztrap/view/runtests/finders.py | 233321205408e7918ea9601274a03b83139b0057 | [
"BSD-2-Clause"
] | permissive | AlinT/moztrap | abcbf74893d10f7bcf77b4ed44fa77bd017353d6 | 13927ae3f156b27e4dd064ea37f2feae14728398 | refs/heads/master | 2021-01-18T08:21:52.894687 | 2012-09-26T19:54:57 | 2012-09-26T19:54:57 | null | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 906 | py | """
Finder for running tests.
"""
from django.core.urlresolvers import reverse
from ... import model
from ..lists import finder
class RunTestsFinder(finder.Finder):
template_base = "runtests/finder"
columns = [
finder.Column(
"products",
"_products.html",
model.Product.objects.order_by("name"),
),
finder.Column(
"productversions",
"_productversions.html",
model.ProductVersion.objects.all(),
),
finder.Column(
"runs",
"_runs.html",
model.Run.objects.filter(status=model.Run.STATUS.active),
),
]
def child_query_url(self, obj):
if isinstance(obj, model.Run):
return reverse("runtests_environment", kwargs={"run_id": obj.id})
return super(RunTestsFinder, self).child_query_url(obj)
| [
"[email protected]"
] | |
b2c759567b93cac768c610e6337ebe2ca19626e0 | 735a315ea82893f2acd5ac141f1a9b8be89f5cb9 | /pylib/v6.1.84/mdsscalar.py | 7cf7fe6e0ba174ecd9dc55b37dbdca77b5786088 | [] | no_license | drsmith48/pppl-mdsplus-python | 5ce6f7ccef4a23ea4b8296aa06f51f3a646dd36f | 0fb5100e6718c8c10f04c3aac120558f521f9a59 | refs/heads/master | 2021-07-08T02:29:59.069616 | 2017-10-04T20:17:32 | 2017-10-04T20:17:32 | 105,808,853 | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 7,108 | py | if '__package__' not in globals() or __package__ is None or len(__package__)==0:
def _mimport(name,level):
return __import__(name,globals())
else:
def _mimport(name,level):
return __import__(name,globals(),{},[],level)
import numpy,copy
_dtypes=_mimport('_mdsdtypes',1)
_data=_mimport('mdsdata',1)
def makeScalar(value):
if isinstance(value,str):
return String(value)
if isinstance(value,Scalar):
return copy.deepcopy(value)
if isinstance(value,numpy.generic):
if isinstance(value,numpy.string_):
return String(value)
try:
if isinstance(value,numpy.bytes_):
return String(str(value,encoding='utf8'))
except:
pass
if isinstance(value,numpy.bool_):
return makeScalar(int(value))
return globals()[value.__class__.__name__.capitalize()](value)
try:
if isinstance(value,long):
return Int64(value)
if isinstance(value,int):
return Int32(value)
except:
if isinstance(value,int):
return Int64(value)
if isinstance(value,float):
return Float32(value)
if isinstance(value,str):
return String(value)
if isinstance(value,bytes):
return String(value.decode())
if isinstance(value,bool):
return Int8(int(value))
if isinstance(value,complex):
return Complex128(numpy.complex128(value))
if isinstance(value,numpy.complex64):
return Complex64(value)
if isinstance(value,numpy.complex128):
return Complex128(value)
raise TypeError('Cannot make Scalar out of '+str(type(value)))
class Scalar(_data.Data):
def __new__(cls,value=0):
try:
import numpy
_array=_mimport('mdsarray',1)
if (isinstance(value,_array.Array)) or isinstance(value,list) or isinstance(value,numpy.ndarray):
return _array.__dict__[cls.__name__+'Array'](value)
except:
pass
return super(Scalar,cls).__new__(cls)
def __init__(self,value=0):
if self.__class__.__name__ == 'Scalar':
raise TypeError("cannot create 'Scalar' instances")
if self.__class__.__name__ == 'String':
self._value=numpy.string_(value)
return
self._value=numpy.__dict__[self.__class__.__name__.lower()](value)
def __getattr__(self,name):
return self._value.__getattribute__(name)
def _getValue(self):
"""Return the numpy scalar representation of the scalar"""
return self._value
value=property(_getValue)
def __str__(self):
formats={'Int8':'%dB','Int16':'%dW','Int32':'%d','Int64':'0X%0xQ',
'Uint8':'%uBU','Uint16':'%uWU','Uint32':'%uLU','Uint64':'0X%0xQU',
'Float32':'%g'}
ans=formats[self.__class__.__name__] % (self._value,)
if ans=='nan':
ans="$ROPRAND"
elif isinstance(self,Float32) and ans.find('.')==-1:
ans=ans+"."
return ans
def decompile(self):
return str(self)
def __int__(self):
"""Integer: x.__int__() <==> int(x)
@rtype: int"""
return self._value.__int__()
def __long__(self):
"""Long: x.__long__() <==> long(x)
@rtype: int"""
return self.__value.__long__()
def _unop(self,op):
return _data.makeData(getattr(self.value,op)())
def _binop(self,op,y):
try:
y=y.value
except AttributeError:
pass
ans=getattr(self.value,op)(y)
return _data.makeData(ans)
def _triop(self,op,y,z):
try:
y=y.value
except AttributeError:
pass
try:
z=z.value
except AttributeError:
pass
return _data.makeData(getattr(self.value,op)(y,z))
def _getMdsDtypeNum(self):
return {'Uint8':DTYPE_BU,'Uint16':DTYPE_WU,'Uint32':DTYPE_LU,'Uint64':DTYPE_QU,
'Int8':DTYPE_B,'Int16':DTYPE_W,'Int32':DTYPE_L,'Int64':DTYPE_Q,
'String':DTYPE_T,
'Float32':DTYPE_FS,
'Float64':DTYPE_FT,'Complex64':DTYPE_FSC,'Complex128':DTYPE_FTC}[self.__class__.__name__]
mdsdtype=property(_getMdsDtypeNum)
def all(self):
return self._unop('all')
def any(self):
return self._unop('any')
def argmax(self,*axis):
if axis:
return self._binop('argmax',axis[0])
else:
return self._unop('argmax')
def argmin(self,*axis):
if axis:
return self._binop('argmin',axis[0])
else:
return self._unop('argmin')
def argsort(self,axis=-1,kind='quicksort',order=None):
return _data.makeData(self.value.argsort(axis,kind,order))
def astype(self,type):
return _data.makeData(self.value.astype(type))
def byteswap(self):
return self._unop('byteswap')
def clip(self,y,z):
return self._triop('clip',y,z)
class Int8(Scalar):
"""8-bit signed number"""
class Int16(Scalar):
"""16-bit signed number"""
class Int32(Scalar):
"""32-bit signed number"""
class Int64(Scalar):
"""64-bit signed number"""
class Uint8(Scalar):
"""8-bit unsigned number"""
class Uint16(Scalar):
"""16-bit unsigned number"""
class Uint32(Scalar):
"""32-bit unsigned number"""
class Uint64(Scalar):
"""64-bit unsigned number"""
def _getDate(self):
return _data.Data.execute('date_time($)',self)
date=property(_getDate)
class Float32(Scalar):
"""32-bit floating point number"""
class Complex64(Scalar):
"""32-bit complex number"""
def __str__(self):
return "Cmplx(%g,%g)" % (self._value.real,self._value.imag)
class Float64(Scalar):
"""64-bit floating point number"""
def __str__(self):
return ("%E" % self._value).replace("E","D")
class Complex128(Scalar):
"""64-bit complex number"""
def __str__(self):
return "Cmplx(%s,%s)" % (str(Float64(self._value.real)),str(Float64(self._value.imag)))
class String(Scalar):
"""String"""
def __radd__(self,y):
"""Reverse add: x.__radd__(y) <==> y+x
@rtype: Data"""
return self.execute('$//$',y,self)
def __add__(self,y):
"""Add: x.__add__(y) <==> x+y
@rtype: Data"""
return self.execute('$//$',self,y)
def __str__(self):
"""String: x.__str__() <==> str(x)
@rtype: String"""
if len(self._value) > 0:
return str(self.value.tostring().decode())
else:
return ''
def __len__(self):
return len(str(self))
def decompile(self):
if len(self._value) > 0:
return repr(self._value.tostring())
else:
return "''"
class Int128(Scalar):
"""128-bit number"""
def __init__(self):
raise TypeError("Int128 is not yet supported")
class Uint128(Scalar):
"""128-bit unsigned number"""
def __init__(self):
raise TypeError("Uint128 is not yet supported")
| [
"[email protected]"
] | |
4dceb544e9e5cb1d823f903dc4ef905e43deca34 | 264ff719d21f2f57451f322e9296b2f55b473eb2 | /gvsoc/gvsoc/models/pulp/fll/fll_v1.py | 4bba0a37a2e965a05864f2ac8ec5e53627d4f934 | [
"Apache-2.0"
] | permissive | knmcguire/gap_sdk | 06c9537c16fa45dea6b7f5c6b162b53953262915 | 7b0a09a353ab6f0550793d40bd46e98051f4a3d7 | refs/heads/master | 2020-12-20T06:51:19.580497 | 2020-01-21T14:52:28 | 2020-01-21T14:52:28 | 235,992,961 | 0 | 0 | Apache-2.0 | 2020-01-24T11:45:59 | 2020-01-24T11:45:58 | null | UTF-8 | Python | false | false | 772 | py | #
# Copyright (C) 2018 ETH Zurich and University of Bologna
#
# 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.
#
# Authors: Germain Haugou, ETH ([email protected])
import vp_core as vp
class component(vp.component):
implementation = 'pulp.fll.fll_v1_impl'
| [
"[email protected]"
] | |
f0714282ca1bed1a0bc706dfd5e96c9a2e87dc47 | a94770c70704c22590c72d7a90f38e3a7d2e3e5c | /Algo/Leetcode/123BestTimeToBuyAndSellStockIII.py | 2a292d28fef14431391bc62620bd69b4e46bf158 | [] | no_license | lawy623/Algorithm_Interview_Prep | 00d8a1c0ac1f47e149e95f8655d52be1efa67743 | ca8b2662330776d14962532ed8994dfeedadef70 | refs/heads/master | 2023-03-22T16:19:12.382081 | 2023-03-21T02:42:05 | 2023-03-21T02:42:05 | 180,056,076 | 2 | 0 | null | null | null | null | UTF-8 | Python | false | false | 409 | py | class Solution(object):
def maxProfit(self, prices):
"""
:type prices: List[int]
:rtype: int
"""
buy1 = -2**31
buy2 = -2**31
sell1 = 0
sell2 = 0
for p in prices:
buy1 = max(buy1, -p)
sell1 = max(sell1, buy1+p)
buy2 = max(buy2, sell1-p)
sell2 = max(sell2, buy2+p)
return sell2 | [
"[email protected]"
] | |
8cb57215a38cae611c55923ca5e461bd7f9fed84 | 44b87d9faad99d542914c35410ba7d354d5ba9cd | /1/EXAM 2/start a following num end in b.py | 6fdd809b6c2423f47c4a8dc46bc3723b23095a91 | [] | no_license | append-knowledge/pythondjango | 586292d1c7d0ddace3630f0d77ca53f442667e54 | 0e5dab580e8cc48e9940fb93a71bcd36e8e6a84e | refs/heads/master | 2023-06-24T07:24:53.374998 | 2021-07-13T05:55:25 | 2021-07-13T05:55:25 | 385,247,677 | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 141 | py | import re
x='[a]\d+[b]'
input=input('enter ')
match=re.fullmatch(x,input)
if match is not None:
print('VALID')
else:
print('INVALID') | [
"[email protected]"
] | |
b7e335ec5f9b7c481858b08725dd834ca4d73b3b | 917d4f67f6033a0cc01ba2b3b7b07dab94dcffdf | /property/pages/views.py | 6104059f52839acc79ba33851e228e4120171433 | [] | no_license | hghimanshu/Django | 011156c484e6710a379be3fb7faf6ab814bde02c | 75bef769e615df2719b213884f7269a56b7ccb7b | refs/heads/master | 2023-02-19T08:49:35.691196 | 2022-03-21T09:03:58 | 2022-03-21T09:03:58 | 242,301,089 | 0 | 0 | null | 2023-02-15T18:19:31 | 2020-02-22T07:43:13 | CSS | UTF-8 | Python | false | false | 856 | py | from django.shortcuts import render
from django.http import HttpResponse
from listings.models import Listing
from realtors.models import Realtor
from listings.choices import price_choices, bedroom_choices, state_choices
# Create your views here.
def index(request):
listings = Listing.objects.order_by('-list_date').filter(is_published=True)[:3]
context = {
'listings': listings,
'state_choices': state_choices,
'bedroom_choices': bedroom_choices,
'price_choices': price_choices
}
return render(request, 'pages/index.html', context)
def about(request):
realtors = Realtor.objects.order_by('-hire_date')
mvp_realtors = Realtor.objects.all().filter(is_mvp=True)
context = {
'realtors': realtors,
'mvp': mvp_realtors
}
return render(request, 'pages/about.html', context)
| [
"[email protected]"
] | |
780073cc16c8f338f3195e45934b88dd0709ef5b | f777b5e4a98c40f4bfc5c5c9e326faa09beb2d53 | /projects/DensePose/densepose/modeling/cse/utils.py | 18480db5e485dec3bd0daf3cae69263a6abdde4f | [
"Apache-2.0"
] | permissive | alekseynp/detectron2 | 04ae9a47d950ea4c737715b5f2aa7637d3742264 | 2409af0bf0d4bdcc685feb6d2c7fd659828acac4 | refs/heads/master | 2022-05-30T09:13:26.438077 | 2022-04-11T20:59:40 | 2022-04-11T20:59:40 | 254,280,315 | 0 | 1 | Apache-2.0 | 2020-04-09T05:34:15 | 2020-04-09T05:34:14 | null | UTF-8 | Python | false | false | 3,538 | py | # Copyright (c) Facebook, Inc. and its affiliates. All Rights Reserved
import torch
from torch.nn import functional as F
def squared_euclidean_distance_matrix(pts1: torch.Tensor, pts2: torch.Tensor) -> torch.Tensor:
"""
Get squared Euclidean Distance Matrix
Computes pairwise squared Euclidean distances between points
Args:
pts1: Tensor [M x D], M is the number of points, D is feature dimensionality
pts2: Tensor [N x D], N is the number of points, D is feature dimensionality
Return:
Tensor [M, N]: matrix of squared Euclidean distances; at index (m, n)
it contains || pts1[m] - pts2[n] ||^2
"""
edm = torch.mm(-2 * pts1, pts2.t())
edm += (pts1 * pts1).sum(1, keepdim=True) + (pts2 * pts2).sum(1, keepdim=True).t()
return edm.contiguous()
def normalize_embeddings(embeddings: torch.Tensor, epsilon: float = 1e-6) -> torch.Tensor:
"""
Normalize N D-dimensional embedding vectors arranged in a tensor [N, D]
Args:
embeddings (tensor [N, D]): N D-dimensional embedding vectors
epsilon (float): minimum value for a vector norm
Return:
Normalized embeddings (tensor [N, D]), such that L2 vector norms are all equal to 1.
"""
return embeddings / torch.clamp(
embeddings.norm(p=None, dim=1, keepdim=True), min=epsilon # pyre-ignore[6]
)
def get_closest_vertices_mask_from_ES(
E: torch.Tensor,
S: torch.Tensor,
h: int,
w: int,
mesh_vertex_embeddings: torch.Tensor,
device: torch.device,
):
"""
Interpolate Embeddings and Segmentations to the size of a given bounding box,
and compute closest vertices and the segmentation mask
Args:
E (tensor [1, D, H, W]): D-dimensional embedding vectors for every point of the
default-sized box
S (tensor [1, 2, H, W]): 2-dimensional segmentation mask for every point of the
default-sized box
h (int): height of the target bounding box
w (int): width of the target bounding box
mesh_vertex_embeddings (tensor [N, D]): vertex embeddings for a chosen mesh
N is the number of vertices in the mesh, D is feature dimensionality
device (torch.device): device to move the tensors to
Return:
Closest Vertices (tensor [h, w]), int, for every point of the resulting box
Segmentation mask (tensor [h, w]), boolean, for every point of the resulting box
"""
# pyre-fixme[6]: Expected `Optional[int]` for 2nd param but got `Tuple[int, int]`.
embedding_resized = F.interpolate(E, size=(h, w), mode="bilinear")[0].to(device)
# pyre-fixme[6]: Expected `Optional[int]` for 2nd param but got `Tuple[int, int]`.
coarse_segm_resized = F.interpolate(S, size=(h, w), mode="bilinear")[0].to(device)
mask = coarse_segm_resized.argmax(0) > 0
closest_vertices = torch.zeros(mask.shape, dtype=torch.long, device=device)
all_embeddings = embedding_resized[:, mask].t()
size_chunk = 10_000 # Chunking to avoid possible OOM
edm = []
if len(all_embeddings) == 0:
return closest_vertices, mask
for chunk in range((len(all_embeddings) - 1) // size_chunk + 1):
chunk_embeddings = all_embeddings[size_chunk * chunk : size_chunk * (chunk + 1)]
edm.append(
torch.argmin(
squared_euclidean_distance_matrix(chunk_embeddings, mesh_vertex_embeddings), dim=1
)
)
closest_vertices[mask] = torch.cat(edm)
return closest_vertices, mask
| [
"[email protected]"
] | |
68c3596f7b0719e22f39a5bb9add3cf40d285973 | 893f83189700fefeba216e6899d42097cc0bec70 | /bioinformatics/photoscan-pro/python/lib/python3.5/site-packages/qtconsole/jupyter_widget.py | c2a8969866d3d2b0203d59d00013fe1e00dc58b6 | [
"GPL-3.0-only",
"Apache-2.0",
"MIT",
"Python-2.0"
] | permissive | pseudoPixels/SciWorCS | 79249198b3dd2a2653d4401d0f028f2180338371 | e1738c8b838c71b18598ceca29d7c487c76f876b | refs/heads/master | 2021-06-10T01:08:30.242094 | 2018-12-06T18:53:34 | 2018-12-06T18:53:34 | 140,774,351 | 0 | 1 | MIT | 2021-06-01T22:23:47 | 2018-07-12T23:33:53 | Python | UTF-8 | Python | false | false | 22,144 | py | """A FrontendWidget that emulates a repl for a Jupyter kernel.
This supports the additional functionality provided by Jupyter kernel.
"""
# Copyright (c) Jupyter Development Team.
# Distributed under the terms of the Modified BSD License.
from collections import namedtuple
import os.path
import re
from subprocess import Popen
import sys
import time
from textwrap import dedent
from qtconsole.qt import QtCore, QtGui
from qtconsole import __version__
from traitlets import Bool, Unicode
from .frontend_widget import FrontendWidget
from . import styles
#-----------------------------------------------------------------------------
# Constants
#-----------------------------------------------------------------------------
# Default strings to build and display input and output prompts (and separators
# in between)
default_in_prompt = 'In [<span class="in-prompt-number">%i</span>]: '
default_out_prompt = 'Out[<span class="out-prompt-number">%i</span>]: '
default_input_sep = '\n'
default_output_sep = ''
default_output_sep2 = ''
# Base path for most payload sources.
zmq_shell_source = 'ipykernel.zmqshell.ZMQInteractiveShell'
if sys.platform.startswith('win'):
default_editor = 'notepad'
else:
default_editor = ''
#-----------------------------------------------------------------------------
# JupyterWidget class
#-----------------------------------------------------------------------------
class IPythonWidget(FrontendWidget):
"""Dummy class for config inheritance. Destroyed below."""
class JupyterWidget(IPythonWidget):
"""A FrontendWidget for a Jupyter kernel."""
# If set, the 'custom_edit_requested(str, int)' signal will be emitted when
# an editor is needed for a file. This overrides 'editor' and 'editor_line'
# settings.
custom_edit = Bool(False)
custom_edit_requested = QtCore.Signal(object, object)
editor = Unicode(default_editor, config=True,
help="""
A command for invoking a system text editor. If the string contains a
{filename} format specifier, it will be used. Otherwise, the filename
will be appended to the end the command.
""")
editor_line = Unicode(config=True,
help="""
The editor command to use when a specific line number is requested. The
string should contain two format specifiers: {line} and {filename}. If
this parameter is not specified, the line number option to the %edit
magic will be ignored.
""")
style_sheet = Unicode(config=True,
help="""
A CSS stylesheet. The stylesheet can contain classes for:
1. Qt: QPlainTextEdit, QFrame, QWidget, etc
2. Pygments: .c, .k, .o, etc. (see PygmentsHighlighter)
3. QtConsole: .error, .in-prompt, .out-prompt, etc
""")
syntax_style = Unicode(config=True,
help="""
If not empty, use this Pygments style for syntax highlighting.
Otherwise, the style sheet is queried for Pygments style
information.
""")
# Prompts.
in_prompt = Unicode(default_in_prompt, config=True)
out_prompt = Unicode(default_out_prompt, config=True)
input_sep = Unicode(default_input_sep, config=True)
output_sep = Unicode(default_output_sep, config=True)
output_sep2 = Unicode(default_output_sep2, config=True)
# JupyterWidget protected class variables.
_PromptBlock = namedtuple('_PromptBlock', ['block', 'length', 'number'])
_payload_source_edit = 'edit_magic'
_payload_source_exit = 'ask_exit'
_payload_source_next_input = 'set_next_input'
_payload_source_page = 'page'
_retrying_history_request = False
_starting = False
#---------------------------------------------------------------------------
# 'object' interface
#---------------------------------------------------------------------------
def __init__(self, *args, **kw):
super(JupyterWidget, self).__init__(*args, **kw)
# JupyterWidget protected variables.
self._payload_handlers = {
self._payload_source_edit : self._handle_payload_edit,
self._payload_source_exit : self._handle_payload_exit,
self._payload_source_page : self._handle_payload_page,
self._payload_source_next_input : self._handle_payload_next_input }
self._previous_prompt_obj = None
self._keep_kernel_on_exit = None
# Initialize widget styling.
if self.style_sheet:
self._style_sheet_changed()
self._syntax_style_changed()
else:
self.set_default_style()
#---------------------------------------------------------------------------
# 'BaseFrontendMixin' abstract interface
#
# For JupyterWidget, override FrontendWidget methods which implement the
# BaseFrontend Mixin abstract interface
#---------------------------------------------------------------------------
def _handle_complete_reply(self, rep):
"""Support Jupyter's improved completion machinery.
"""
self.log.debug("complete: %s", rep.get('content', ''))
cursor = self._get_cursor()
info = self._request_info.get('complete')
if info and info.id == rep['parent_header']['msg_id'] and \
info.pos == cursor.position():
content = rep['content']
matches = content['matches']
start = content['cursor_start']
end = content['cursor_end']
start = max(start, 0)
end = max(end, start)
# Move the control's cursor to the desired end point
cursor_pos = self._get_input_buffer_cursor_pos()
if end < cursor_pos:
cursor.movePosition(QtGui.QTextCursor.Left,
n=(cursor_pos - end))
elif end > cursor_pos:
cursor.movePosition(QtGui.QTextCursor.Right,
n=(end - cursor_pos))
# This line actually applies the move to control's cursor
self._control.setTextCursor(cursor)
offset = end - start
# Move the local cursor object to the start of the match and
# complete.
cursor.movePosition(QtGui.QTextCursor.Left, n=offset)
self._complete_with_items(cursor, matches)
def _handle_execute_reply(self, msg):
"""Support prompt requests.
"""
msg_id = msg['parent_header'].get('msg_id')
info = self._request_info['execute'].get(msg_id)
if info and info.kind == 'prompt':
content = msg['content']
if content['status'] == 'aborted':
self._show_interpreter_prompt()
else:
number = content['execution_count'] + 1
self._show_interpreter_prompt(number)
self._request_info['execute'].pop(msg_id)
else:
super(JupyterWidget, self)._handle_execute_reply(msg)
def _handle_history_reply(self, msg):
""" Handle history tail replies, which are only supported
by Jupyter kernels.
"""
content = msg['content']
if 'history' not in content:
self.log.error("History request failed: %r"%content)
if content.get('status', '') == 'aborted' and \
not self._retrying_history_request:
# a *different* action caused this request to be aborted, so
# we should try again.
self.log.error("Retrying aborted history request")
# prevent multiple retries of aborted requests:
self._retrying_history_request = True
# wait out the kernel's queue flush, which is currently timed at 0.1s
time.sleep(0.25)
self.kernel_client.history(hist_access_type='tail',n=1000)
else:
self._retrying_history_request = False
return
# reset retry flag
self._retrying_history_request = False
history_items = content['history']
self.log.debug("Received history reply with %i entries", len(history_items))
items = []
last_cell = u""
for _, _, cell in history_items:
cell = cell.rstrip()
if cell != last_cell:
items.append(cell)
last_cell = cell
self._set_history(items)
def _insert_other_input(self, cursor, content):
"""Insert function for input from other frontends"""
cursor.beginEditBlock()
start = cursor.position()
n = content.get('execution_count', 0)
cursor.insertText('\n')
self._insert_html(cursor, self._make_in_prompt(n))
cursor.insertText(content['code'])
self._highlighter.rehighlightBlock(cursor.block())
cursor.endEditBlock()
def _handle_execute_input(self, msg):
"""Handle an execute_input message"""
self.log.debug("execute_input: %s", msg.get('content', ''))
if self.include_output(msg):
self._append_custom(self._insert_other_input, msg['content'], before_prompt=True)
def _handle_execute_result(self, msg):
"""Handle an execute_result message"""
if self.include_output(msg):
self.flush_clearoutput()
content = msg['content']
prompt_number = content.get('execution_count', 0)
data = content['data']
if 'text/plain' in data:
self._append_plain_text(self.output_sep, True)
self._append_html(self._make_out_prompt(prompt_number), True)
text = data['text/plain']
# If the repr is multiline, make sure we start on a new line,
# so that its lines are aligned.
if "\n" in text and not self.output_sep.endswith("\n"):
self._append_plain_text('\n', True)
self._append_plain_text(text + self.output_sep2, True)
def _handle_display_data(self, msg):
"""The base handler for the ``display_data`` message."""
# For now, we don't display data from other frontends, but we
# eventually will as this allows all frontends to monitor the display
# data. But we need to figure out how to handle this in the GUI.
if self.include_output(msg):
self.flush_clearoutput()
data = msg['content']['data']
metadata = msg['content']['metadata']
# In the regular JupyterWidget, we simply print the plain text
# representation.
if 'text/plain' in data:
text = data['text/plain']
self._append_plain_text(text, True)
# This newline seems to be needed for text and html output.
self._append_plain_text(u'\n', True)
def _handle_kernel_info_reply(self, rep):
"""Handle kernel info replies."""
content = rep['content']
self.kernel_banner = content.get('banner', '')
if self._starting:
# finish handling started channels
self._starting = False
super(JupyterWidget, self)._started_channels()
def _started_channels(self):
"""Make a history request"""
self._starting = True
self.kernel_client.kernel_info()
self.kernel_client.history(hist_access_type='tail', n=1000)
#---------------------------------------------------------------------------
# 'FrontendWidget' protected interface
#---------------------------------------------------------------------------
def _process_execute_error(self, msg):
"""Handle an execute_error message"""
content = msg['content']
traceback = '\n'.join(content['traceback']) + '\n'
if False:
# FIXME: For now, tracebacks come as plain text, so we can't use
# the html renderer yet. Once we refactor ultratb to produce
# properly styled tracebacks, this branch should be the default
traceback = traceback.replace(' ', ' ')
traceback = traceback.replace('\n', '<br/>')
ename = content['ename']
ename_styled = '<span class="error">%s</span>' % ename
traceback = traceback.replace(ename, ename_styled)
self._append_html(traceback)
else:
# This is the fallback for now, using plain text with ansi escapes
self._append_plain_text(traceback)
def _process_execute_payload(self, item):
""" Reimplemented to dispatch payloads to handler methods.
"""
handler = self._payload_handlers.get(item['source'])
if handler is None:
# We have no handler for this type of payload, simply ignore it
return False
else:
handler(item)
return True
def _show_interpreter_prompt(self, number=None):
""" Reimplemented for IPython-style prompts.
"""
# If a number was not specified, make a prompt number request.
if number is None:
msg_id = self.kernel_client.execute('', silent=True)
info = self._ExecutionRequest(msg_id, 'prompt')
self._request_info['execute'][msg_id] = info
return
# Show a new prompt and save information about it so that it can be
# updated later if the prompt number turns out to be wrong.
self._prompt_sep = self.input_sep
self._show_prompt(self._make_in_prompt(number), html=True)
block = self._control.document().lastBlock()
length = len(self._prompt)
self._previous_prompt_obj = self._PromptBlock(block, length, number)
# Update continuation prompt to reflect (possibly) new prompt length.
self._set_continuation_prompt(
self._make_continuation_prompt(self._prompt), html=True)
def _show_interpreter_prompt_for_reply(self, msg):
""" Reimplemented for IPython-style prompts.
"""
# Update the old prompt number if necessary.
content = msg['content']
# abort replies do not have any keys:
if content['status'] == 'aborted':
if self._previous_prompt_obj:
previous_prompt_number = self._previous_prompt_obj.number
else:
previous_prompt_number = 0
else:
previous_prompt_number = content['execution_count']
if self._previous_prompt_obj and \
self._previous_prompt_obj.number != previous_prompt_number:
block = self._previous_prompt_obj.block
# Make sure the prompt block has not been erased.
if block.isValid() and block.text():
# Remove the old prompt and insert a new prompt.
cursor = QtGui.QTextCursor(block)
cursor.movePosition(QtGui.QTextCursor.Right,
QtGui.QTextCursor.KeepAnchor,
self._previous_prompt_obj.length)
prompt = self._make_in_prompt(previous_prompt_number)
self._prompt = self._insert_html_fetching_plain_text(
cursor, prompt)
# When the HTML is inserted, Qt blows away the syntax
# highlighting for the line, so we need to rehighlight it.
self._highlighter.rehighlightBlock(cursor.block())
self._previous_prompt_obj = None
# Show a new prompt with the kernel's estimated prompt number.
self._show_interpreter_prompt(previous_prompt_number + 1)
#---------------------------------------------------------------------------
# 'JupyterWidget' interface
#---------------------------------------------------------------------------
def set_default_style(self, colors='lightbg'):
""" Sets the widget style to the class defaults.
Parameters
----------
colors : str, optional (default lightbg)
Whether to use the default light background or dark
background or B&W style.
"""
colors = colors.lower()
if colors=='lightbg':
self.style_sheet = styles.default_light_style_sheet
self.syntax_style = styles.default_light_syntax_style
elif colors=='linux':
self.style_sheet = styles.default_dark_style_sheet
self.syntax_style = styles.default_dark_syntax_style
elif colors=='nocolor':
self.style_sheet = styles.default_bw_style_sheet
self.syntax_style = styles.default_bw_syntax_style
else:
raise KeyError("No such color scheme: %s"%colors)
#---------------------------------------------------------------------------
# 'JupyterWidget' protected interface
#---------------------------------------------------------------------------
def _edit(self, filename, line=None):
""" Opens a Python script for editing.
Parameters
----------
filename : str
A path to a local system file.
line : int, optional
A line of interest in the file.
"""
if self.custom_edit:
self.custom_edit_requested.emit(filename, line)
elif not self.editor:
self._append_plain_text('No default editor available.\n'
'Specify a GUI text editor in the `JupyterWidget.editor` '
'configurable to enable the %edit magic')
else:
try:
filename = '"%s"' % filename
if line and self.editor_line:
command = self.editor_line.format(filename=filename,
line=line)
else:
try:
command = self.editor.format()
except KeyError:
command = self.editor.format(filename=filename)
else:
command += ' ' + filename
except KeyError:
self._append_plain_text('Invalid editor command.\n')
else:
try:
Popen(command, shell=True)
except OSError:
msg = 'Opening editor with command "%s" failed.\n'
self._append_plain_text(msg % command)
def _make_in_prompt(self, number):
""" Given a prompt number, returns an HTML In prompt.
"""
try:
body = self.in_prompt % number
except TypeError:
# allow in_prompt to leave out number, e.g. '>>> '
from xml.sax.saxutils import escape
body = escape(self.in_prompt)
return '<span class="in-prompt">%s</span>' % body
def _make_continuation_prompt(self, prompt):
""" Given a plain text version of an In prompt, returns an HTML
continuation prompt.
"""
end_chars = '...: '
space_count = len(prompt.lstrip('\n')) - len(end_chars)
body = ' ' * space_count + end_chars
return '<span class="in-prompt">%s</span>' % body
def _make_out_prompt(self, number):
""" Given a prompt number, returns an HTML Out prompt.
"""
try:
body = self.out_prompt % number
except TypeError:
# allow out_prompt to leave out number, e.g. '<<< '
from xml.sax.saxutils import escape
body = escape(self.out_prompt)
return '<span class="out-prompt">%s</span>' % body
#------ Payload handlers --------------------------------------------------
# Payload handlers with a generic interface: each takes the opaque payload
# dict, unpacks it and calls the underlying functions with the necessary
# arguments.
def _handle_payload_edit(self, item):
self._edit(item['filename'], item['line_number'])
def _handle_payload_exit(self, item):
self._keep_kernel_on_exit = item['keepkernel']
self.exit_requested.emit(self)
def _handle_payload_next_input(self, item):
self.input_buffer = item['text']
def _handle_payload_page(self, item):
# Since the plain text widget supports only a very small subset of HTML
# and we have no control over the HTML source, we only page HTML
# payloads in the rich text widget.
data = item['data']
if 'text/html' in data and self.kind == 'rich':
self._page(data['text/html'], html=True)
else:
self._page(data['text/plain'], html=False)
#------ Trait change handlers --------------------------------------------
def _style_sheet_changed(self):
""" Set the style sheets of the underlying widgets.
"""
self.setStyleSheet(self.style_sheet)
if self._control is not None:
self._control.document().setDefaultStyleSheet(self.style_sheet)
bg_color = self._control.palette().window().color()
self._ansi_processor.set_background_color(bg_color)
if self._page_control is not None:
self._page_control.document().setDefaultStyleSheet(self.style_sheet)
def _syntax_style_changed(self):
""" Set the style for the syntax highlighter.
"""
if self._highlighter is None:
# ignore premature calls
return
if self.syntax_style:
self._highlighter.set_style(self.syntax_style)
else:
self._highlighter.set_style_sheet(self.style_sheet)
#------ Trait default initializers -----------------------------------------
def _banner_default(self):
return "Jupyter QtConsole {version}\n".format(version=__version__)
# clobber IPythonWidget above:
class IPythonWidget(JupyterWidget):
"""Deprecated class. Use JupyterWidget"""
def __init__(self, *a, **kw):
warn("IPythonWidget is deprecated, use JupyterWidget")
super(IPythonWidget, self).__init__(*a, **kw)
| [
"[email protected]"
] | |
af73d519f490016f2e04c80e9be69b7f30392f9c | 329d80ba2b792864aef583fa9ba0f8579ed96f46 | /src/timeslice/viz.py | 726ce7cae1fbce19cf716bf10cd873b63aeecab0 | [
"MIT"
] | permissive | spencerzhang91/GSPNet | fce229b11b23597375abbbe5a8e8bffaa4310551 | ff165de95ec0f258ba444ff343d18d812a066b8f | refs/heads/master | 2022-01-14T15:47:29.409475 | 2019-06-17T03:01:24 | 2019-06-17T03:01:24 | null | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 1,078 | py | '''
Copyright <2019> <COPYRIGHT Pingcheng Zhang>
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.
'''
| [
"[email protected]"
] | |
b605974ab6d3d89ba69d3248a135c89cc71111ec | 5ca02343c366662b60966e060e50e9d6960c0531 | /TX/TX/settings.py | 45f686302330fb2cfde0ecc003da2686115a362c | [] | no_license | yyzhu0817/scrapy | eff5cc68ab25c89fe01c62e2c94e5511dad3fc34 | 9186b127bf49450850028c76142262c6f2c935da | refs/heads/master | 2020-12-10T01:00:34.924969 | 2020-01-20T02:54:58 | 2020-01-20T02:54:58 | 233,465,772 | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 3,174 | py | # -*- coding: utf-8 -*-
# Scrapy settings for TX project
#
# For simplicity, this file contains only settings considered important or
# commonly used. You can find more settings consulting the documentation:
#
# https://docs.scrapy.org/en/latest/topics/settings.html
# https://docs.scrapy.org/en/latest/topics/downloader-middleware.html
# https://docs.scrapy.org/en/latest/topics/spider-middleware.html
BOT_NAME = 'TX'
SPIDER_MODULES = ['TX.spiders']
NEWSPIDER_MODULE = 'TX.spiders'
# Crawl responsibly by identifying yourself (and your website) on the user-agent
#USER_AGENT = 'TX (+http://www.yourdomain.com)'
# Obey robots.txt rules
ROBOTSTXT_OBEY = False
# Configure maximum concurrent requests performed by Scrapy (default: 16)
#CONCURRENT_REQUESTS = 32
# Configure a delay for requests for the same website (default: 0)
# See https://docs.scrapy.org/en/latest/topics/settings.html#download-delay
# See also autothrottle settings and docs
#DOWNLOAD_DELAY = 3
# The download delay setting will honor only one of:
#CONCURRENT_REQUESTS_PER_DOMAIN = 16
#CONCURRENT_REQUESTS_PER_IP = 16
# Disable cookies (enabled by default)
#COOKIES_ENABLED = False
# Disable Telnet Console (enabled by default)
#TELNETCONSOLE_ENABLED = False
# Override the default request headers:
DEFAULT_REQUEST_HEADERS = {
'Accept': 'text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8',
'Accept-Language': 'en',
'User-Agent':'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_2) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/79.0.3945.88 Safari/537.36',
}
# Enable or disable spider middlewares
# See https://docs.scrapy.org/en/latest/topics/spider-middleware.html
#SPIDER_MIDDLEWARES = {
# 'TX.middlewares.TxSpiderMiddleware': 543,
#}
# Enable or disable downloader middlewares
# See https://docs.scrapy.org/en/latest/topics/downloader-middleware.html
#DOWNLOADER_MIDDLEWARES = {
# 'TX.middlewares.TxDownloaderMiddleware': 543,
#}
# Enable or disable extensions
# See https://docs.scrapy.org/en/latest/topics/extensions.html
#EXTENSIONS = {
# 'scrapy.extensions.telnet.TelnetConsole': None,
#}
# Configure item pipelines
# See https://docs.scrapy.org/en/latest/topics/item-pipeline.html
# ITEM_PIPELINES = {
# 'TX.pipelines.TxPipeline': 300,
# }
# Enable and configure the AutoThrottle extension (disabled by default)
# See https://docs.scrapy.org/en/latest/topics/autothrottle.html
#AUTOTHROTTLE_ENABLED = True
# The initial download delay
#AUTOTHROTTLE_START_DELAY = 5
# The maximum download delay to be set in case of high latencies
#AUTOTHROTTLE_MAX_DELAY = 60
# The average number of requests Scrapy should be sending in parallel to
# each remote server
#AUTOTHROTTLE_TARGET_CONCURRENCY = 1.0
# Enable showing throttling stats for every response received:
#AUTOTHROTTLE_DEBUG = False
# Enable and configure HTTP caching (disabled by default)
# See https://docs.scrapy.org/en/latest/topics/downloader-middleware.html#httpcache-middleware-settings
#HTTPCACHE_ENABLED = True
#HTTPCACHE_EXPIRATION_SECS = 0
#HTTPCACHE_DIR = 'httpcache'
#HTTPCACHE_IGNORE_HTTP_CODES = []
#HTTPCACHE_STORAGE = 'scrapy.extensions.httpcache.FilesystemCacheStorage'
| [
"[email protected]"
] | |
de41515bdfe3faa82c3ce8ed5c220f24b123aac9 | 3712a929d1124f514ea7af1ac0d4a1de03bb6773 | /开班笔记/pythonMongoDB部分/day39/code/mongo1.py | 5b9aef2d4d0dc19f114aaca150810694bc086161 | [] | no_license | jiyabing/learning | abd82aa3fd37310b4a98b11ea802c5b0e37b7ad9 | 6059006b0f86aee9a74cfc116d2284eb44173f41 | refs/heads/master | 2020-04-02T20:47:33.025331 | 2018-10-26T05:46:10 | 2018-10-26T05:46:10 | 154,779,387 | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 990 | py | #coding:utf8
#索引和聚合操作
from pymongo import MongoClient,IndexModel
conn = MongoClient('localhost',27017)
db = conn.stu
my_set = db.class4
#创建索引,并且将索引名返回
#index = my_set.ensure_index('name')
#print(index)
#复合索引
#index = my_set.ensure_index([('name',1),('king',-1)])
#print(index)
#唯一索引和稀疏索引
cls = db.class0
#唯一索引
#index = cls.ensure_index('name',unique=True)
#稀疏索引
#index = my_set.ensure_index('king_name',sparse=True)
#删除索引
#my_set.drop_index('name_1')
#my_set.drop_indexes() #删除所有索引
#同时创建多个索引
#index1 = IndexModel([('name',1),('king',-1)])
#index2 = IndexModel([('king_name',1)])
#indexes = my_set.create_indexes([index1,index2])
#查看一个集合中的索引
#for i in my_set.list_indexes():
# print(i)
#聚合管道
l = [{'$group':{'_id':'$king','count':{'$sum':1}}},{'$match':{'count':{'$gt':1}}}]
cursor = my_set.aggregate(l)
for i in cursor:
print(i)
| [
"[email protected]"
] | |
9e8e5607a62fa19a162b1026aab6e20e14275de9 | 1a2bf34d7fc1d227ceebf05edf00287de74259c5 | /Django/Test/LuZhenNan/APP/views.py | 7e131b7ef59abef0102ca853aada9b3ad236a88c | [] | no_license | lzn9423362/Django- | de69fee75160236e397b3bbc165281eadbe898f0 | 8c1656d20dcc4dfc29fb942b2db54ec07077e3ae | refs/heads/master | 2020-03-29T18:03:47.323734 | 2018-11-28T12:07:12 | 2018-11-28T12:07:12 | 150,192,771 | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 2,187 | py | import hashlib
from django.http import HttpResponse, JsonResponse
from django.shortcuts import render, redirect
from django.urls import reverse
from .models import *
# Create your views here.
def index(request):
username = request.session.get('username')
users = User.objects.filter(username=username)
user = users.first()
girl = Girl.objects.all()
man = Man.objects.all()
if users.exists():
user = users.first()
return render(request, 'index.html', {'user': user, 'girl1': girl[0:1], 'girl2':girl[1:6], 'man1': man[0:2], 'man2': man[2:11]
})
else:
return render(request, 'index.html', {'user':user, 'girl1': girl[0:1], 'girl2':girl[1:6], 'man1': man[0:2], 'man2': man[2:11]
})
# 'girl1': girl[0:2], 'girl2':girl[2:7], 'man1': Man[0:2], 'man2': Man[2:11]
def register(request):
return render(request, 'register.html')
def registerhandle(request):
if request.method == 'POST':
username = request.POST.get('username')
password = request.POST.get('password')
email = request.POST.get('email')
User.objects.create(username=username, password=password, email=email)
return redirect(reverse('APP:login'))
def login(request):
return render(request, 'login.html')
def loginhandle(request):
if request.method == 'POST':
username = request.POST.get('phone')
password = request.POST.get('password')
users = User.objects.filter(username=username, password=password)
if users.exists():
request.session['username'] = users.first().username
return redirect(reverse('APP:index'))
else:
return HttpResponse('账号密码错误')
else:
return HttpResponse('请求方式错误')
def logout(request):
request.session.clear()
return redirect(reverse("APP:index"))
def loginajax(request):
username = request.POST.get('value')
try:
user = User.objects.get(username=username)
return JsonResponse({'status': 0})
except:
return JsonResponse({'status': 1})
def my_md5(string):
m = hashlib.md5()
m.update(string.encode())
return m.hexdigest()
| [
"[email protected]"
] | |
caa0850988b9faedb6726b682fb5a8154116b383 | ddd4edc45481e6a7c7141b93e47b974634506d2d | /tradgram/relations/admin.py | 4dbfea14ffdda1239afd8dbc98f9c3eba2c6aaf4 | [
"MIT"
] | permissive | didils/tradgram | 407de9d05d01bc840c5c165155d370f092d82f0d | 4868ca082ab78a1b5b96f25ee9f958567bd1bb1e | refs/heads/master | 2021-11-19T02:47:02.224088 | 2019-04-05T08:19:14 | 2019-04-05T08:19:14 | 148,162,588 | 0 | 0 | MIT | 2021-09-08T00:57:43 | 2018-09-10T13:49:57 | Python | UTF-8 | Python | false | false | 439 | py | from django.contrib import admin
from . import models
# Register your models here.
@admin.register(models.Relation)
class RelationAdmin(admin.ModelAdmin):
search_fields =(
'product1',
'product2',
)
list_filter = (
'product1',
'product2',
'count',
'created_at'
)
list_display = (
'product1',
'product2',
'count',
'created_at'
) | [
"[email protected]"
] | |
d7cab272034def647cc8d74d213a5bd61f80a1cd | 3f5a1ef51620fd8c35ef38064ca5aa00776ab6f4 | /full_speed_educative/dictionary/defination.py | e920f8dbd52c14cb5029ac0ed167f195ae926aff | [] | no_license | poojagmahajan/python_exercises | 1b290a5c0689f703538caf89bca5bc6c1fdb392a | 65539cf31c5b2ad5768d652ed5fe95054ce5f63f | refs/heads/master | 2022-11-12T03:52:13.533781 | 2020-07-04T20:50:29 | 2020-07-04T20:54:46 | 263,151,942 | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 1,814 | py |
### Dictionaries are data structures that index values by a given key (key-value pairs).
ages = {
"purvansh" : 3,
"Pooja" : 28,
"Gaurav" : 30,
"swarit" : 1 ,
"meet" : 10,
"ishan" : 6
}
print("print age of any one -")
print (ages ["purvansh"])
print(ages["Gaurav"])
print("\n print ages of all -")
for name,age in ages.items() :
print(name,age)
address = {} #Call dictionary with no parameters using the empty {}
pincode = dict() #Call dictionary with no parameters using the dict keyword
address["pooja"] = "pune" ## fill to empty dictionary
address["purvansh"] = "chinchwad"
for name,address in address.items() :
print("\n", name,address)
d = { ## dictionary keys can be immutable object and don’t necessarily need to be strings
0: [0, 0, 0],
1: [1, 1, 1],
2: [2, 2, 2],
}
print ( d[2] )
##You can create an ordered dictionary which preserves the order in which the keys are inserted.
# This is done by importing the OrderedDictionary from the collections library, and call the OrderedDictionary() built-in method.
from collections import OrderedDict
ages = OrderedDict()
ages["ram"] = 20
ages["sham"] = 40
for key, value in ages.items():
print(key, value)
#####Loop to Get All Keys
for key in ages: #for name in ages
print(key)
####or
print(ages.keys())
##### Loop to Get All Values
for age in ages : # for value in ages :
print(ages[age])
#### or
print (ages.values())
######################################
Dict1 = {
"FruitName": "Mango",
"season": "Spring",
}
Dict1.pop("season") ## pop delete value
print(Dict1.values())
print (Dict1) ## print whole dictionary
print (Dict1.values())
print(Dict1.keys())
Dict1.clear() # delete Dict
print(Dict1) # will print empty paranthesis {}
| [
"[email protected]"
] | |
806e3cd0e19b3608d616b002a8bb2b876ca9e51a | d564c1dcde3a139960e441a732f308dee7bac268 | /code/run5All_Content_PlainUD.py | 517e77577c22a0ae492044444a377776233b03a6 | [] | no_license | m-hahn/left-right-asymmetries | 9b5142dcf822194068feea2ccc0e8cc3b0573bbe | 45e5b40a145e2a9d51c12617dc76be5a49ddf43e | refs/heads/master | 2020-04-26T11:47:57.781431 | 2019-03-22T01:00:48 | 2019-03-22T01:00:48 | 173,528,908 | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 355 | py | from ud_languages import languages
import subprocess
languages = sorted(languages, reverse=True)
for language in languages:
for model in ["REAL_REAL", "REVERSE"]: #, "GROUND"] + (["RANDOM_BY_TYPE"] * 5):
command = ["./python27", "testLeftRightEntUniHDCond3FilterMIWord5_Content_PlainUD_Bugfix.py", language, model]
subprocess.call(command)
| [
"[email protected]"
] | |
95612c8e2207355469ab70ff6f985fb9fef74ba0 | d6ca0b326f1bd0ce381c6db611f6331096bf4187 | /pypet/tests/_atworema.py | 5862c910f1aa08c6ff96162a56510430111ec8f6 | [
"BSD-3-Clause"
] | permissive | SmokinCaterpillar/pypet | aa35355d70e8f44be015313494376d993f645d80 | 3d454ac65f89e7833baaf89510f73c546e90d8f6 | refs/heads/develop | 2023-08-08T16:01:54.087819 | 2023-02-14T14:59:32 | 2023-02-14T14:59:32 | 12,901,526 | 89 | 22 | BSD-3-Clause | 2023-07-24T00:46:12 | 2013-09-17T17:06:00 | Python | UTF-8 | Python | false | false | 352 | py | __author__ = 'Robert Meyer'
from pypet.tests.testutils.ioutils import run_suite, discover_tests, TEST_IMPORT_ERROR
if __name__ == '__main__':
suite = discover_tests(predicate= lambda class_name, test_name, tags:
class_name != TEST_IMPORT_ERROR)
run_suite(remove=False, folder=None, suite=suite) | [
"[email protected]"
] | |
12f14216b2b4a57ff01c2b1c049c8688d0d4cbf8 | 34ed92a9593746ccbcb1a02630be1370e8524f98 | /lib/pints/pints/plot.py | e915a7b2d7e282f5c1642e4f76e9500005a923c2 | [
"LicenseRef-scancode-unknown-license-reference",
"BSD-3-Clause"
] | permissive | HOLL95/Cytochrome_SV | 87b7a680ed59681230f79e1de617621680ea0fa0 | d02b3469f3ee5a4c85d756053bc87651093abea1 | refs/heads/master | 2022-08-01T05:58:16.161510 | 2021-02-01T16:09:31 | 2021-02-01T16:09:31 | 249,424,867 | 0 | 0 | null | 2022-06-22T04:09:11 | 2020-03-23T12:29:29 | Jupyter Notebook | UTF-8 | Python | false | false | 28,013 | py | #
# Quick diagnostic plots.
#
# This file is part of PINTS.
# Copyright (c) 2017-2018, University of Oxford.
# For licensing information, see the LICENSE file distributed with the PINTS
# software package.
#
from __future__ import absolute_import, division
from __future__ import print_function, unicode_literals
def function(f, x, lower=None, upper=None, evaluations=20):
"""
Creates 1d plots of a :class:`LogPDF` or a :class:`ErrorMeasure` around a
point `x` (i.e. a 1-dimensional plot in each direction).
Returns a ``matplotlib`` figure object and axes handle.
Parameters
----------
f
A :class:`pints.LogPDF` or :class:`pints.ErrorMeasure` to plot.
x
A point in the function's input space.
lower
Optional lower bounds for each parameter, used to specify the lower
bounds of the plot.
upper
Optional upper bounds for each parameter, used to specify the upper
bounds of the plot.
evaluations
The number of evaluations to use in each plot.
"""
import matplotlib.pyplot as plt
import numpy as np
import pints
# Check function and get n_parameters
if not (isinstance(f, pints.LogPDF) or isinstance(f, pints.ErrorMeasure)):
raise ValueError(
'Given function must be pints.LogPDF or pints.ErrorMeasure.')
n_param = f.n_parameters()
# Check point
x = pints.vector(x)
if len(x) != n_param:
raise ValueError(
'Given point `x` must have same number of parameters as function.')
# Check boundaries
if lower is None:
# Guess boundaries based on point x
lower = x * 0.95
lower[lower == 0] = -1
else:
lower = pints.vector(lower)
if len(lower) != n_param:
raise ValueError('Lower bounds must have same number of'
+ ' parameters as function.')
if upper is None:
# Guess boundaries based on point x
upper = x * 1.05
upper[upper == 0] = 1
else:
upper = pints.vector(upper)
if len(upper) != n_param:
raise ValueError('Upper bounds must have same number of'
+ ' parameters as function.')
# Check number of evaluations
evaluations = int(evaluations)
if evaluations < 1:
raise ValueError('Number of evaluations must be greater than zero.')
# Create points to plot
xs = np.tile(x, (n_param * evaluations, 1))
for j in range(n_param):
i1 = j * evaluations
i2 = i1 + evaluations
xs[i1:i2, j] = np.linspace(lower[j], upper[j], evaluations)
# Evaluate points
fs = pints.evaluate(f, xs, parallel=False)
# Create figure
fig, axes = plt.subplots(n_param, 1, figsize=(6, 2 * n_param))
if n_param == 1:
axes = np.asarray([axes], dtype=object)
for j, p in enumerate(x):
i1 = j * evaluations
i2 = i1 + evaluations
axes[j].plot(xs[i1:i2, j], fs[i1:i2], c='green', label='Function')
axes[j].axvline(p, c='blue', label='Value')
axes[j].set_xlabel('Parameter ' + str(1 + j))
axes[j].legend()
plt.tight_layout()
return fig, axes
def function_between_points(f, point_1, point_2, padding=0.25, evaluations=20):
"""
Creates and returns a plot of a function between two points in parameter
space.
Returns a ``matplotlib`` figure object and axes handle.
Parameters
----------
f
A :class:`pints.LogPDF` or :class:`pints.ErrorMeasure` to plot.
point_1
The first point in parameter space. The method will find a line from
``point_1`` to ``point_2`` and plot ``f`` at several points along it.
point_2
The second point.
padding
Specifies the amount of padding around the line segment
``[point_1, point_2]`` that will be shown in the plot.
evaluations
The number of evaluation along the line in parameter space.
"""
import matplotlib.pyplot as plt
import numpy as np
import pints
# Check function and get n_parameters
if not (isinstance(f, pints.LogPDF) or isinstance(f, pints.ErrorMeasure)):
raise ValueError(
'Given function must be pints.LogPDF or pints.ErrorMeasure.')
n_param = f.n_parameters()
# Check points
point_1 = pints.vector(point_1)
point_2 = pints.vector(point_2)
if not (len(point_1) == len(point_2) == n_param):
raise ValueError('Both points must have the same number of parameters'
+ ' as the given function.')
# Check padding
padding = float(padding)
if padding < 0:
raise ValueError('Padding cannot be negative.')
# Check evaluation
evaluations = int(evaluations)
if evaluations < 3:
raise ValueError('The number of evaluations must be 3 or greater.')
# Figure setting
fig, axes = plt.subplots(1, 1, figsize=(6, 4))
axes.set_xlabel('Point 1 to point 2')
axes.set_ylabel('Function')
# Generate some x-values near the given parameters
s = np.linspace(-padding, 1 + padding, evaluations)
# Direction
r = point_2 - point_1
# Calculate function with other parameters fixed
x = [point_1 + sj * r for sj in s]
y = pints.evaluate(f, x, parallel=False)
# Plot
axes.plot(s, y, color='green')
axes.axvline(0, color='#1f77b4', label='Point 1')
axes.axvline(1, color='#7f7f7f', label='Point 2')
axes.legend()
return fig, axes
def histogram(samples, ref_parameters=None, n_percentiles=None):
"""
Takes one or more markov chains or lists of samples as input and creates
and returns a plot showing histograms for each chain or list of samples.
Returns a ``matplotlib`` figure object and axes handle.
Parameters
----------
samples
A list of lists of samples, with shape
``(n_lists, n_samples, n_parameters)``, where ``n_lists`` is the
number of lists of samples, ``n_samples`` is the number of samples in
one list and ``n_parameters`` is the number of parameters.
ref_parameters
A set of parameters for reference in the plot. For example, if true
values of parameters are known, they can be passed in for plotting.
n_percentiles
Shows only the middle n-th percentiles of the distribution.
Default shows all samples in ``samples``.
"""
import matplotlib.pyplot as plt
import numpy as np
# If we switch to Python3 exclusively, bins and alpha can be keyword-only
# arguments
bins = 40
alpha = 0.5
n_list = len(samples)
_, n_param = samples[0].shape
# Check number of parameters
for samples_j in samples:
if n_param != samples_j.shape[1]:
raise ValueError(
'All samples must have the same number of parameters.'
)
# Check reference parameters
if ref_parameters is not None:
if len(ref_parameters) != n_param:
raise ValueError(
'Length of `ref_parameters` must be same as number of'
' parameters.')
# Set up figure
fig, axes = plt.subplots(
n_param, 1, figsize=(6, 2 * n_param),
squeeze=False, # Tell matlab to always return a 2d axes object
)
# Plot first samples
for i in range(n_param):
for j_list, samples_j in enumerate(samples):
# Add histogram subplot
axes[i, 0].set_xlabel('Parameter ' + str(i + 1))
axes[i, 0].set_ylabel('Frequency')
if n_percentiles is None:
xmin = np.min(samples_j[:, i])
xmax = np.max(samples_j[:, i])
else:
xmin = np.percentile(samples_j[:, i],
50 - n_percentiles / 2.)
xmax = np.percentile(samples_j[:, i],
50 + n_percentiles / 2.)
xbins = np.linspace(xmin, xmax, bins)
axes[i, 0].hist(
samples_j[:, i], bins=xbins, alpha=alpha,
label='Samples ' + str(1 + j_list))
# Add reference parameters if given
if ref_parameters is not None:
# For histogram subplot
ymin_tv, ymax_tv = axes[i, 0].get_ylim()
axes[i, 0].plot(
[ref_parameters[i], ref_parameters[i]],
[0.0, ymax_tv],
'--', c='k')
if n_list > 1:
axes[0, 0].legend()
plt.tight_layout()
return fig, axes[:, 0]
def trace(samples, ref_parameters=None, n_percentiles=None):
"""
Takes one or more markov chains or lists of samples as input and creates
and returns a plot showing histograms and traces for each chain or list of
samples.
Returns a ``matplotlib`` figure object and axes handle.
Parameters
----------
samples
A list of lists of samples, with shape
``(n_lists, n_samples, n_parameters)``, where ``n_lists`` is the
number of lists of samples, ``n_samples`` is the number of samples in
one list and ``n_parameters`` is the number of parameters.
ref_parameters
A set of parameters for reference in the plot. For example, if true
values of parameters are known, they can be passed in for plotting.
n_percentiles
Shows only the middle n-th percentiles of the distribution.
Default shows all samples in ``samples``.
"""
import matplotlib.pyplot as plt
import numpy as np
# If we switch to Python3 exclusively, bins and alpha can be keyword-only
# arguments
bins = 40
alpha = 0.5
n_list = len(samples)
_, n_param = samples[0].shape
# Check number of parameters
for samples_j in samples:
if n_param != samples_j.shape[1]:
raise ValueError(
'All samples must have the same number of parameters.'
)
# Check reference parameters
if ref_parameters is not None:
if len(ref_parameters) != n_param:
raise ValueError(
'Length of `ref_parameters` must be same as number of'
' parameters.')
# Set up figure
fig, axes = plt.subplots(
n_param, 2, figsize=(12, 2 * n_param),
# Tell matplotlib to return 2d, even if n_param is 1
squeeze=False,
)
# Plot first samples
for i in range(n_param):
ymin_all, ymax_all = np.inf, -np.inf
for j_list, samples_j in enumerate(samples):
# Add histogram subplot
axes[i, 0].set_xlabel('Parameter ' + str(i + 1))
axes[i, 0].set_ylabel('Frequency')
if n_percentiles is None:
xmin = np.min(samples_j[:, i])
xmax = np.max(samples_j[:, i])
else:
xmin = np.percentile(samples_j[:, i],
50 - n_percentiles / 2.)
xmax = np.percentile(samples_j[:, i],
50 + n_percentiles / 2.)
xbins = np.linspace(xmin, xmax, bins)
axes[i, 0].hist(samples_j[:, i], bins=xbins, alpha=alpha,
label='Samples ' + str(1 + j_list))
# Add trace subplot
axes[i, 1].set_xlabel('Iteration')
axes[i, 1].set_ylabel('Parameter ' + str(i + 1))
axes[i, 1].plot(samples_j[:, i], alpha=alpha)
# Set ylim
ymin_all = ymin_all if ymin_all < xmin else xmin
ymax_all = ymax_all if ymax_all > xmax else xmax
axes[i, 1].set_ylim([ymin_all, ymax_all])
# Add reference parameters if given
if ref_parameters is not None:
# For histogram subplot
ymin_tv, ymax_tv = axes[i, 0].get_ylim()
axes[i, 0].plot(
[ref_parameters[i], ref_parameters[i]],
[0.0, ymax_tv],
'--', c='k')
# For trace subplot
xmin_tv, xmax_tv = axes[i, 1].get_xlim()
axes[i, 1].plot(
[0.0, xmax_tv],
[ref_parameters[i], ref_parameters[i]],
'--', c='k')
if n_list > 1:
axes[0, 0].legend()
plt.tight_layout()
return fig, axes
def autocorrelation(samples, max_lags=100):
"""
Creates and returns an autocorrelation plot for a given markov chain or
list of `samples`.
Returns a ``matplotlib`` figure object and axes handle.
Parameters
----------
samples
A list of samples, with shape ``(n_samples, n_parameters)``, where
``n_samples`` is the number of samples in the list and ``n_parameters``
is the number of parameters.
max_lags
The maximum autocorrelation lag to plot.
"""
import matplotlib.pyplot as plt
import numpy as np
# Check samples size
try:
n_sample, n_param = samples.shape
except ValueError:
raise ValueError('`samples` must be of shape (n_sample,'
+ ' n_parameters).')
fig, axes = plt.subplots(n_param, 1, sharex=True, figsize=(6, 2 * n_param))
if n_param == 1:
axes = np.asarray([axes], dtype=object)
for i in range(n_param):
axes[i].acorr(samples[:, i] - np.mean(samples[:, i]), maxlags=max_lags)
axes[i].set_xlim(-0.5, max_lags + 0.5)
axes[i].legend(['Parameter ' + str(1 + i)], loc='upper right')
# Add x-label to final plot only
axes[i].set_xlabel('Lag')
# Add vertical y-label to middle plot
# fig.text(0.04, 0.5, 'Autocorrelation', va='center', rotation='vertical')
axes[int(i / 2)].set_ylabel('Autocorrelation')
plt.tight_layout()
return fig, axes
def series(samples, problem, ref_parameters=None, thinning=None):
"""
Creates and returns a plot of predicted time series for a given list of
``samples`` and a single-output or multi-output ``problem``.
Because this method runs simulations, it can take a considerable time to
run.
Returns a ``matplotlib`` figure object and axes handle.
Parameters
----------
samples
A list of samples, with shape ``(n_samples, n_parameters)``, where
`n_samples` is the number of samples in the list and ``n_parameters``
is the number of parameters.
problem
A :class:``pints.SingleOutputProblem`` or
:class:``pints.MultiOutputProblem`` of a n_parameters equal to or
greater than the ``n_parameters`` of the `samples`. Any extra
parameters present in the chain but not accepted by the
``SingleOutputProblem`` or ``MultiOutputProblem`` (for example
parameters added by a noise model) will be ignored.
ref_parameters
A set of parameters for reference in the plot. For example,
if true values of parameters are known, they can be passed in for
plotting.
thinning
An integer greater than zero. If specified, only every
n-th sample (with ``n = thinning``) in the samples will be used. If
left at the default value ``None``, a value will be chosen so that
200 to 400 predictions are shown.
"""
import matplotlib.pyplot as plt
import numpy as np
# Check samples size
try:
n_sample, n_param = samples.shape
except ValueError:
raise ValueError('`samples` must be of shape (n_sample,'
+ ' n_parameters).')
# Get problem n_parameters
n_parameters = problem.n_parameters()
# Check reference parameters
if ref_parameters is not None:
if len(ref_parameters) != n_param and \
len(ref_parameters) != n_parameters:
raise ValueError(
'Length of `ref_parameters` must be same as number of'
' parameters.')
ref_series = problem.evaluate(ref_parameters[:n_parameters])
# Get number of problem output
n_outputs = problem.n_outputs()
# Get thinning rate
if thinning is None:
thinning = max(1, int(n_sample / 200))
else:
thinning = int(thinning)
if thinning < 1:
raise ValueError(
'Thinning rate must be `None` or an integer greater than'
' zero.')
# Get times
times = problem.times()
# Evaluate the model for all parameter sets in the samples
i = 0
predicted_values = []
for params in samples[::thinning, :n_parameters]:
predicted_values.append(problem.evaluate(params))
i += 1
predicted_values = np.array(predicted_values)
mean_values = np.mean(predicted_values, axis=0)
# Guess appropriate alpha (0.05 worked for 1000 plots)
alpha = max(0.05 * (1000 / (n_sample / thinning)), 0.5)
# Plot prediction
fig, axes = plt.subplots(n_outputs, 1, figsize=(8, np.sqrt(n_outputs) * 3),
sharex=True)
if n_outputs == 1:
plt.xlabel('Time')
plt.ylabel('Value')
plt.plot(
times, problem.values(), 'x', color='#7f7f7f', ms=6.5, alpha=0.5,
label='Original data')
plt.plot(
times, predicted_values[0], color='#1f77b4',
label='Inferred series')
for v in predicted_values[1:]:
plt.plot(times, v, color='#1f77b4', alpha=alpha)
plt.plot(times, mean_values, 'k:', lw=2,
label='Mean of inferred series')
# Add reference series if given
if ref_parameters is not None:
plt.plot(times, ref_series, color='#d62728', ls='--',
label='Reference series')
plt.legend()
elif n_outputs > 1:
# Remove horizontal space between axes and set common xlabel
fig.subplots_adjust(hspace=0)
axes[-1].set_xlabel('Time')
# Go through each output
for i_output in range(n_outputs):
axes[i_output].set_ylabel('Output %d' % (i_output + 1))
axes[i_output].plot(
times, problem.values()[:, i_output], 'x', color='#7f7f7f',
ms=6.5, alpha=0.5, label='Original data')
axes[i_output].plot(
times, predicted_values[0][:, i_output], color='#1f77b4',
label='Inferred series')
for v in predicted_values[1:]:
axes[i_output].plot(times, v[:, i_output], color='#1f77b4',
alpha=alpha)
axes[i_output].plot(times, mean_values[:, i_output], 'k:', lw=2,
label='Mean of inferred series')
# Add reference series if given
if ref_parameters is not None:
axes[i_output].plot(times, ref_series[:, i_output],
color='#d62728', ls='--',
label='Reference series')
axes[0].legend()
plt.tight_layout()
return fig, axes
def pairwise(samples,
kde=False,
heatmap=False,
opacity=None,
ref_parameters=None,
n_percentiles=None):
"""
Takes a markov chain or list of ``samples`` and creates a set of pairwise
scatterplots for all parameters (p1 versus p2, p1 versus p3, p2 versus p3,
etc.).
The returned plot is in a 'matrix' form, with histograms of each individual
parameter on the diagonal, and scatter plots of parameters ``i`` and ``j``
on each entry ``(i, j)`` below the diagonal.
Returns a ``matplotlib`` figure object and axes handle.
Parameters
----------
samples
A list of samples, with shape ``(n_samples, n_parameters)``, where
``n_samples`` is the number of samples in the list and ``n_parameters``
is the number of parameters.
kde
Set to ``True`` to use kernel-density estimation for the
histograms and scatter plots. Cannot use together with ``heatmap``.
heatmap
Set to ``True`` to plot heatmap for the pairwise plots.
Cannot be used together with ``kde``.
Opacity
This value can be used to manually set the opacity of the
points in the scatter plots (when ``kde=False`` and ``heatmap=False``
only).
ref_parameters
A set of parameters for reference in the plot. For example,
if true values of parameters are known, they can be passed in for
plotting.
n_percentiles
Shows only the middle n-th percentiles of the distribution.
Default shows all samples in ``samples``.
"""
import matplotlib
import matplotlib.pyplot as plt
import numpy as np
import scipy.stats as stats
import warnings
from distutils.version import LooseVersion
# Check matplotlib version
use_old_matplotlib = LooseVersion(matplotlib.__version__) \
< LooseVersion("2.2")
# Check options kde and heatmap
if kde and heatmap:
raise ValueError('Cannot use `kde` and `heatmap` together.')
# Check samples size
try:
n_sample, n_param = samples.shape
except ValueError:
raise ValueError('`samples` must be of shape (n_sample,'
+ ' n_parameters).')
# Check number of parameters
if n_param < 2:
raise ValueError('Number of parameters must be larger than 2.')
# Check reference parameters
if ref_parameters is not None:
if len(ref_parameters) != n_param:
raise ValueError(
'Length of `ref_parameters` must be same as number of'
' parameters.')
# Create figure
fig_size = (3 * n_param, 3 * n_param)
fig, axes = plt.subplots(n_param, n_param, figsize=fig_size)
bins = 25
for i in range(n_param):
for j in range(n_param):
if i == j:
# Diagonal: Plot a histogram
if n_percentiles is None:
xmin, xmax = np.min(samples[:, i]), np.max(samples[:, i])
else:
xmin = np.percentile(samples[:, i],
50 - n_percentiles / 2.)
xmax = np.percentile(samples[:, i],
50 + n_percentiles / 2.)
xbins = np.linspace(xmin, xmax, bins)
axes[i, j].set_xlim(xmin, xmax)
if use_old_matplotlib: # pragma: no cover
axes[i, j].hist(samples[:, i], bins=xbins, normed=True)
else:
axes[i, j].hist(samples[:, i], bins=xbins, density=True)
# Add kde plot
if kde:
x = np.linspace(xmin, xmax, 100)
axes[i, j].plot(x, stats.gaussian_kde(samples[:, i])(x))
# Add reference parameters if given
if ref_parameters is not None:
ymin_tv, ymax_tv = axes[i, j].get_ylim()
axes[i, j].plot(
[ref_parameters[i], ref_parameters[i]],
[0.0, ymax_tv],
'--', c='k')
elif i < j:
# Top-right: no plot
axes[i, j].axis('off')
else:
# Lower-left: Plot the samples as density map
if n_percentiles is None:
xmin, xmax = np.min(samples[:, j]), np.max(samples[:, j])
ymin, ymax = np.min(samples[:, i]), np.max(samples[:, i])
else:
xmin = np.percentile(samples[:, j],
50 - n_percentiles / 2.)
xmax = np.percentile(samples[:, j],
50 + n_percentiles / 2.)
ymin = np.percentile(samples[:, i],
50 - n_percentiles / 2.)
ymax = np.percentile(samples[:, i],
50 + n_percentiles / 2.)
axes[i, j].set_xlim(xmin, xmax)
axes[i, j].set_ylim(ymin, ymax)
if not kde and not heatmap:
# Create scatter plot
# Determine point opacity
num_points = len(samples[:, i])
if opacity is None:
if num_points < 10:
opacity = 1.0
else:
opacity = 1.0 / np.log10(num_points)
# Scatter points
axes[i, j].scatter(
samples[:, j], samples[:, i], alpha=opacity, s=0.1)
elif kde:
# Create a KDE-based plot
# Plot values
values = np.vstack([samples[:, j], samples[:, i]])
axes[i, j].imshow(
np.rot90(values), cmap=plt.cm.Blues,
extent=[xmin, xmax, ymin, ymax])
# Create grid
xx, yy = np.mgrid[xmin:xmax:100j, ymin:ymax:100j]
positions = np.vstack([xx.ravel(), yy.ravel()])
# Get kernel density estimate and plot contours
kernel = stats.gaussian_kde(values)
f = np.reshape(kernel(positions).T, xx.shape)
axes[i, j].contourf(xx, yy, f, cmap='Blues')
axes[i, j].contour(xx, yy, f, colors='k')
# Force equal aspect ratio
# Matplotlib raises a warning here (on 2.7 at least)
# We can't do anything about it, so no other option than
# to suppress it at this stage...
with warnings.catch_warnings():
warnings.simplefilter('ignore', UnicodeWarning)
axes[i, j].set_aspect((xmax - xmin) / (ymax - ymin))
elif heatmap:
# Create a heatmap-based plot
# Create bins
xbins = np.linspace(xmin, xmax, bins)
ybins = np.linspace(ymin, ymax, bins)
# Plot heatmap
axes[i, j].hist2d(samples[:, j], samples[:, i],
bins=(xbins, ybins), cmap=plt.cm.Blues)
# Force equal aspect ratio
# Matplotlib raises a warning here (on 2.7 at least)
# We can't do anything about it, so no other option than
# to suppress it at this stage...
with warnings.catch_warnings():
warnings.simplefilter('ignore', UnicodeWarning)
axes[i, j].set_aspect((xmax - xmin) / (ymax - ymin))
# Add reference parameters if given
if ref_parameters is not None:
axes[i, j].plot(
[ref_parameters[j], ref_parameters[j]],
[ymin, ymax],
'--', c='k')
axes[i, j].plot(
[xmin, xmax],
[ref_parameters[i], ref_parameters[i]],
'--', c='k')
# Set tick labels
if i < n_param - 1:
# Only show x tick labels for the last row
axes[i, j].set_xticklabels([])
else:
# Rotate the x tick labels to fit in the plot
for tl in axes[i, j].get_xticklabels():
tl.set_rotation(45)
if j > 0:
# Only show y tick labels for the first column
axes[i, j].set_yticklabels([])
# Set axis labels
axes[-1, i].set_xlabel('Parameter %d' % (i + 1))
if i == 0:
# The first one is not a parameter
axes[i, 0].set_ylabel('Frequency')
else:
axes[i, 0].set_ylabel('Parameter %d' % (i + 1))
return fig, axes
| [
"[email protected]"
] | |
72ff753a9ba4196f39464a93290728c75816d6aa | 5623771414b26c021be54facaaaefbd9314b389d | /week7/DS/DP/Min_sum_path.py | ae37aa64e4f0f1e20de2069fd94641db8a4796da | [] | no_license | saxenasamarth/BootCamp_PythonLearning | 36b705b83c7f0e297931bb8d75cb541088690248 | d5b8fe2d6fcfe54c5a7393f218414b1122f3e49e | refs/heads/master | 2023-04-17T15:29:05.402863 | 2019-08-29T08:46:34 | 2019-08-29T08:46:34 | null | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 664 | py | # Given a m x n grid filled with non-negative numbers, find a path from top left to bottom right which minimizes the sum of all numbers along its path.
def find_min_sum_path(matrix):
out = [[0 for i in range(len(matrix[0]))] for j in range(len(matrix))]
out[0][0] = matrix[0][0]
for i in range(1, len(matrix)):
out[i][0] = out[i-1][0]+matrix[i][0]
for i in range(1, len(matrix[0])):
out[0][i] = out[0][i-1]+matrix[0][i]
for i in range(1, len(matrix)):
for j in range(1, len(matrix[0])):
out[i][j] = matrix[i][j] + min(out[i-1][j], out[i][j-1])
return out[-1][-1]
matrix = [[1,3,1],[1,5,1],[4,2,1]]
print(find_min_sum_path(matrix)) | [
"[email protected]"
] | |
0d5fb3722a72d746607b18d92434d47ef39879d8 | c6f15aa103de030f7eea6c1aaf6e7ad0ec88dbc1 | /add/AppMcsv/storage/volume/Volume.py | b21fe01e6712fe2709429c0d0eb031b3f2a0eedd | [] | no_license | sysdeep/dcat | 6f3478348113b0d1206f82456f5bd80431282daf | f8c801173ace4447018c3034c56254ab1a6d4089 | refs/heads/master | 2023-05-03T16:04:28.027335 | 2023-04-17T15:04:04 | 2023-04-17T15:04:04 | 320,551,696 | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 2,453 | py | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
import gzip
from enum import Enum
import time
DET = "-"*10
class Sections(Enum):
header = 0
body = 1
class Record(object):
def __init__(self):
self.name = ""
self.uuid = ""
self.parent = ""
self.childrens = []
def append(self, ch):
self.childrens.append(ch)
def parse_record(line: str) -> Record:
try:
fields = line.split("|")
except Exception as e:
print(e)
return None
r = Record()
r.name = fields[0]
r.uuid = fields[10]
r.parent = fields[9]
return r
class Volume(object):
def __init__(self, full_path):
self.path = full_path
self.name = "undefined"
self.__tree = []
self.__tmap = {}
self.__roots = []
def read_header(self):
fd = gzip.open(self.path, "rt", encoding="utf-8")
sheader = []
section = Sections.header
c = 1000
while True:
line = fd.readline().strip()
if not line:
print("null line")
break
if section == Sections.header:
if line == DET:
break
else:
sheader.append(line)
c -= 1
if c < 0:
print("emerg")
break
fd.close()
for line in sheader:
print(line)
chunks = line.split(":")
if chunks[0] == "name":
self.name = chunks[1]
break
def read_body(self):
self.__tree = []
self.__tmap = {}
fd = gzip.open(self.path, "rt", encoding="utf-8")
t1 = time.time()
section = Sections.header
c = 10000000000
while True:
line = fd.readline().strip()
if not line:
print("null line")
break
if section == Sections.header:
if line == DET:
section = Sections.body
else:
# pass header
pass
elif section == Sections.body:
# print(line)
record = parse_record(line)
# self.__tree.append(record)
self.__tmap[record.uuid] = record
if record.parent == "0":
self.__roots.append(record)
else:
pass
c -= 1
if c < 0:
print("emerg")
break
print("*"*20)
print("files: ", c)
print("*"*20)
fd.close()
t2 = time.time()
print("parse body time: ", t2-t1)
self.__link()
def __link(self):
for r in self.__tmap.values():
if r.parent == "0":
continue
parent_node = self.__tmap.get(r.parent)
if parent_node:
parent_node.append(r)
def get_root(self) -> list:
# return [r for r in self.__tree if r.parent == "0"]
return self.__roots
| [
"[email protected]"
] | |
a4cce41e3df9414b4d0faa27cb4e7dc024befcb8 | 4c5328381f53d8b77b56a597cc39a32b55a0c4c2 | /Cura/gui/view3D/printableObjectRenderer.py | 88a57fe5161dce1651e1ffc756679a55a1b9d57a | [] | no_license | sanyaade-iot/Cura2 | 47fc18a8886dcc8537439b699cdb201d92e68683 | b8655a20ca4a03acaa2ada555f57fe415264d944 | refs/heads/master | 2021-01-16T20:06:18.885340 | 2014-06-06T12:51:10 | 2014-06-06T12:51:10 | null | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 3,207 | py | __author__ = 'Jaime van Kessel'
from OpenGL.GL import *
from Cura.gui import openGLUtils
from Cura.resources import getMesh
from Cura.gui.view3D.renderer import Renderer
class PrintableObjectRenderer(Renderer):
def __init__(self):
super(PrintableObjectRenderer,self).__init__()
self._shader = openGLUtils.GLShader(filename='objectShader.glsl')
def render(self):
self._shader.bind()
for obj in self.scene.getObjects():
mesh = obj.getMesh()
glPushMatrix()
offset = obj.getDrawOffset()
glTranslatef(obj.getPosition()[0], obj.getPosition()[1], obj.getSize()[2] / 2.0)
openGLUtils.glMultiplyMatrix(obj.getTempMatrix())
glTranslatef(offset[0], offset[1], offset[2] - obj.getSize()[2] / 2.0)
openGLUtils.glMultiplyMatrix(obj.getMatrix())
colorStrength = 0.8
if obj.isSelected():
colorStrength = 1.0
if mesh is not None:
for v in mesh.getVolumes():
if 'VertexRenderer' not in v.metaData:
v.metaData['VertexRenderer'] = openGLUtils.VertexRenderer(GL_TRIANGLES, v.vertexData)
glColor3f(1 * colorStrength, 0.5 * colorStrength, 1 * colorStrength)
v.metaData['VertexRenderer'].render()
else:
mesh = getMesh('loading_mesh.stl')
for v in mesh.getVolumes():
if 'VertexRenderer' not in v.metaData:
v.metaData['VertexRenderer'] = openGLUtils.VertexRenderer(GL_TRIANGLES, v.vertexData)
glColor3f(0.5 * colorStrength, 0.5 * colorStrength, 0.5 * colorStrength)
v.metaData['VertexRenderer'].render()
glPopMatrix()
self._shader.unbind()
def focusRender(self):
objIdx = 0
for obj in self.scene.getObjects():
glPushMatrix()
offset = obj.getDrawOffset()
glTranslatef(obj.getPosition()[0], obj.getPosition()[1], obj.getSize()[2] / 2.0)
openGLUtils.glMultiplyMatrix(obj.getTempMatrix())
glTranslatef(offset[0], offset[1], offset[2] - obj.getSize()[2] / 2.0)
openGLUtils.glMultiplyMatrix(obj.getMatrix())
self.setCurrentFocusRenderObject(obj)
mesh = obj.getMesh()
if mesh is not None:
volumeIdx = 0
for v in mesh.getVolumes():
if 'VertexRenderer' not in v.metaData:
v.metaData['VertexRenderer'] = openGLUtils.VertexRenderer(GL_TRIANGLES, v.vertexData)
v.metaData['VertexRenderer'].render()
volumeIdx += 1
else:
volumeIdx = 0
mesh = getMesh('loading_mesh.stl')
for v in mesh.getVolumes():
if 'VertexRenderer' not in v.metaData:
v.metaData['VertexRenderer'] = openGLUtils.VertexRenderer(GL_TRIANGLES, v.vertexData)
v.metaData['VertexRenderer'].render()
volumeIdx += 1
objIdx += 1
glPopMatrix()
| [
"[email protected]"
] | |
d3ed2e74b0e9dba9944dd11ca896b5016acd263d | 154fd16fe7828cb6925ca8f90e049b754ce06413 | /lino_book/projects/lydia/tests/dumps/18.12.0/teams_team.py | e3d2d31af2866296e853ea6765cf5e65fe6a2a6c | [
"BSD-2-Clause"
] | permissive | lino-framework/book | 68de2f8d130266bd9d9de7576d30597b3cde1c91 | 4eab916832cd8f48ff1b9fc8c2789f0b437da0f8 | refs/heads/master | 2021-03-27T16:16:55.403940 | 2021-03-15T02:53:50 | 2021-03-15T02:53:50 | 58,830,342 | 3 | 9 | BSD-2-Clause | 2021-03-09T13:11:27 | 2016-05-14T21:02:17 | Python | UTF-8 | Python | false | false | 254 | py | # -*- coding: UTF-8 -*-
logger.info("Loading 2 objects to table teams_team...")
# fields: id, ref, name
loader.save(create_teams_team(1,u'E',['Eupen', '', '']))
loader.save(create_teams_team(2,u'S',['St. Vith', '', '']))
loader.flush_deferred_objects()
| [
"[email protected]"
] | |
99a64502bc4d3c80b07c903df53770314112a9ed | df7f13ec34591fe1ce2d9aeebd5fd183e012711a | /hata/discord/user/thread_profile/tests/test__ThreadProfile__magic.py | 62df5d60ace156b75fde3936db52d10717f48aed | [
"LicenseRef-scancode-warranty-disclaimer"
] | permissive | HuyaneMatsu/hata | 63e2f6a2d7a7539fd8f18498852d9d3fe5c41d2e | 53f24fdb38459dc5a4fd04f11bdbfee8295b76a4 | refs/heads/master | 2023-08-20T15:58:09.343044 | 2023-08-20T13:09:03 | 2023-08-20T13:09:03 | 163,677,173 | 3 | 3 | Apache-2.0 | 2019-12-18T03:46:12 | 2018-12-31T14:59:47 | Python | UTF-8 | Python | false | false | 1,575 | py | from datetime import datetime as DateTime
import vampytest
from ..flags import ThreadProfileFlag
from ..thread_profile import ThreadProfile
def test__ThreadProfile__repr():
"""
Tests whether ``ThreadProfile.__repr__`` works as intended.
"""
flags = ThreadProfileFlag(2)
joined_at = DateTime(2016, 5, 15)
thread_profile = ThreadProfile(
flags = flags,
joined_at = joined_at,
)
vampytest.assert_instance(repr(thread_profile), str)
def test__ThreadProfile__hash():
"""
Tests whether ``ThreadProfile.__hash__`` works as intended.
"""
flags = ThreadProfileFlag(2)
joined_at = DateTime(2016, 5, 15)
thread_profile = ThreadProfile(
flags = flags,
joined_at = joined_at,
)
vampytest.assert_instance(hash(thread_profile), int)
def test__ThreadProfile__eq():
"""
Tests whether ``ThreadProfile.__eq__`` works as intended.
"""
flags = ThreadProfileFlag(2)
joined_at = DateTime(2016, 5, 15)
keyword_parameters = {
'flags': flags,
'joined_at': joined_at,
}
thread_profile = ThreadProfile(**keyword_parameters)
vampytest.assert_eq(thread_profile, thread_profile)
vampytest.assert_ne(thread_profile, object())
for field_name, field_value in (
('flags', ThreadProfileFlag(4)),
('joined_at', None),
):
test_thread_profile = ThreadProfile(**{**keyword_parameters, field_name: field_value})
vampytest.assert_ne(thread_profile, test_thread_profile)
| [
"[email protected]"
] | |
099b882a7057d5cd24e0b98ae5aa752f70f5f128 | 30a8b69bd2e0a3f3c2c1c88fb3bd8a28e6fc4cd0 | /Part1/load_shapefile.py | 5f31c2a37d32ed6c638bb6a4a1c85920628b25c3 | [] | no_license | llord1/Mining-Georeferenced-Data | d49108f443922f02b90431ad7a9626ea17fd0554 | c71f2e151ccfc4a1a9c07b5fcf4e95b7f7ba70e9 | refs/heads/master | 2021-05-30T13:27:57.663015 | 2015-12-29T09:10:08 | 2015-12-29T09:10:08 | null | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 542 | py | #!/usr/bin/env python
import sys
import shapefile
from shapely.geometry import shape
shp = shapefile.Reader(sys.argv[1])
print "Found", shp.numRecords, "records:"
pos = None
count = 0
for record in shp.records():
print " ", record[1]
if record[1] == sys.argv[2]:
pos = count
count += 1
if pos is None:
print >> sys.stderr, sys.argv[2], "not found in shapefile"
sys.exit()
print >> sys.stderr, "Using", sys.argv[2], "..."
manhattan = shape(shp.shapes()[pos])
print manhattan.contains(manhattan.centroid)
| [
"[email protected]"
] | |
b4158282f6e90ee810904eb5e6be6f5e5f95435d | 1fad121fea752aa3aee03f7665917ce9563e0d08 | /src/form/panel/VmdPanel.py | e75138d37ae45d096b8a52074f7f82a941f91b1f | [
"MIT"
] | permissive | JerryAJIAN/vmd_sizing | 0d382b9b94cdc3878e9d9a1c03f2c9c5f285ac6a | baad81eb40a21c9fa864344fbbf75cdab887c9c6 | refs/heads/master | 2022-11-18T03:57:57.111852 | 2020-07-06T15:10:27 | 2020-07-06T15:10:27 | null | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 7,450 | py | # -*- coding: utf-8 -*-
#
import wx
import wx.lib.newevent
import sys
from form.panel.BasePanel import BasePanel
from form.parts.BaseFilePickerCtrl import BaseFilePickerCtrl
from form.parts.ConsoleCtrl import ConsoleCtrl
from form.worker.VmdWorkerThread import VmdWorkerThread
from module.MMath import MRect, MVector3D, MVector4D, MQuaternion, MMatrix4x4 # noqa
from utils import MFormUtils, MFileUtils # noqa
from utils.MLogger import MLogger # noqa
logger = MLogger(__name__)
# イベント定義
(VmdThreadEvent, EVT_VMD_THREAD) = wx.lib.newevent.NewEvent()
class VmdPanel(BasePanel):
def __init__(self, frame: wx.Frame, parent: wx.Notebook, tab_idx: int):
super().__init__(frame, parent, tab_idx)
self.convert_vmd_worker = None
self.description_txt = wx.StaticText(self, wx.ID_ANY, "指定されたCSVファイル(ボーン+モーフ or カメラ)を、VMDファイルとして出力します。\n" \
+ "モデルモーション(ボーン・モーフ)とカメラモーション(カメラ)は別々に出力できます。\n" \
+ "CSVのフォーマットは、CSVタブで出力したデータと同じものを定義してください。", wx.DefaultPosition, wx.DefaultSize, 0)
self.sizer.Add(self.description_txt, 0, wx.ALL, 5)
self.static_line = wx.StaticLine(self, wx.ID_ANY, wx.DefaultPosition, wx.DefaultSize, wx.LI_HORIZONTAL)
self.sizer.Add(self.static_line, 0, wx.EXPAND | wx.ALL, 5)
# CSVファイルコントロール(ボーン)
self.bone_csv_file_ctrl = BaseFilePickerCtrl(frame, self, u"CSVファイル(ボーン)", u"CSVファイルを選択してください", ("csv"), wx.FLP_DEFAULT_STYLE, \
u"VMDに変換したいボーンモーションのファイルパスを指定してください。", \
is_aster=False, is_save=False, set_no=0, required=False)
self.sizer.Add(self.bone_csv_file_ctrl.sizer, 0, wx.EXPAND | wx.ALL, 0)
# CSVファイルコントロール(モーフ)
self.morph_csv_file_ctrl = BaseFilePickerCtrl(frame, self, u"CSVファイル(モーフ)", u"CSVファイルを選択してください", ("csv"), wx.FLP_DEFAULT_STYLE, \
u"VMDに変換したいモーフモーションのファイルパスを指定してください。", \
is_aster=False, is_save=False, set_no=0, required=False)
self.sizer.Add(self.morph_csv_file_ctrl.sizer, 0, wx.EXPAND | wx.ALL, 0)
self.static_line2 = wx.StaticLine(self, wx.ID_ANY, wx.DefaultPosition, wx.DefaultSize, wx.LI_HORIZONTAL)
self.sizer.Add(self.static_line2, 0, wx.EXPAND | wx.ALL, 5)
# CSVファイルコントロール(カメラ)
self.camera_csv_file_ctrl = BaseFilePickerCtrl(frame, self, u"CSVファイル(カメラ)", u"CSVファイルを選択してください", ("csv"), wx.FLP_DEFAULT_STYLE, \
u"VMDに変換したいカメラモーションのファイルパスを指定してください。", \
is_aster=False, is_save=False, set_no=0, required=False)
self.sizer.Add(self.camera_csv_file_ctrl.sizer, 0, wx.EXPAND | wx.ALL, 0)
btn_sizer = wx.BoxSizer(wx.HORIZONTAL)
# VMD変換実行ボタン
self.vmd_btn_ctrl = wx.Button(self, wx.ID_ANY, u"VMD変換実行", wx.DefaultPosition, wx.Size(200, 50), 0)
self.vmd_btn_ctrl.SetToolTip(u"CSVをVMDに変換します。")
self.vmd_btn_ctrl.Bind(wx.EVT_BUTTON, self.on_convert_vmd)
btn_sizer.Add(self.vmd_btn_ctrl, 0, wx.ALL, 5)
self.sizer.Add(btn_sizer, 0, wx.ALIGN_CENTER | wx.SHAPED, 5)
# コンソール
self.console_ctrl = ConsoleCtrl(self, wx.ID_ANY, wx.EmptyString, wx.DefaultPosition, wx.Size(-1, 420), \
wx.TE_MULTILINE | wx.TE_READONLY | wx.BORDER_NONE | wx.HSCROLL | wx.VSCROLL | wx.WANTS_CHARS)
self.console_ctrl.SetBackgroundColour(wx.SystemSettings.GetColour(wx.SYS_COLOUR_3DLIGHT))
self.console_ctrl.Bind(wx.EVT_CHAR, lambda event: MFormUtils.on_select_all(event, self.console_ctrl))
self.sizer.Add(self.console_ctrl, 1, wx.ALL | wx.EXPAND, 5)
# ゲージ
self.gauge_ctrl = wx.Gauge(self, wx.ID_ANY, 100, wx.DefaultPosition, wx.DefaultSize, wx.GA_HORIZONTAL)
self.gauge_ctrl.SetValue(0)
self.sizer.Add(self.gauge_ctrl, 0, wx.ALL | wx.EXPAND, 5)
self.fit()
# フレームに変換完了処理バインド
self.frame.Bind(EVT_VMD_THREAD, self.on_convert_vmd_result)
# フォーム無効化
def disable(self):
self.bone_csv_file_ctrl.disable()
self.morph_csv_file_ctrl.disable()
self.camera_csv_file_ctrl.disable()
self.vmd_btn_ctrl.Disable()
# フォーム無効化
def enable(self):
self.bone_csv_file_ctrl.enable()
self.morph_csv_file_ctrl.enable()
self.camera_csv_file_ctrl.enable()
self.vmd_btn_ctrl.Enable()
# VMD変換
def on_convert_vmd(self, event: wx.Event):
# フォーム無効化
self.disable()
# タブ固定
self.fix_tab()
# コンソールクリア
self.console_ctrl.Clear()
# 出力先をVMDパネルのコンソールに変更
sys.stdout = self.console_ctrl
wx.GetApp().Yield()
self.elapsed_time = 0
result = True
result = self.bone_csv_file_ctrl.is_valid() and result
if not result:
# 終了音
self.frame.sound_finish()
# タブ移動可
self.release_tab()
# フォーム有効化
self.enable()
# 出力先をデフォルトに戻す
sys.stdout = self.frame.file_panel_ctrl.console_ctrl
return result
# VMD変換開始
if self.convert_vmd_worker:
logger.error("まだ処理が実行中です。終了してから再度実行してください。", decoration=MLogger.DECORATION_BOX)
else:
# 別スレッドで実行
self.convert_vmd_worker = VmdWorkerThread(self.frame, VmdThreadEvent)
self.convert_vmd_worker.start()
return result
event.Skip()
# VMD変換完了処理
def on_convert_vmd_result(self, event: wx.Event):
self.elapsed_time = event.elapsed_time
# 終了音
self.frame.sound_finish()
# タブ移動可
self.release_tab()
# フォーム有効化
self.enable()
# ワーカー終了
self.convert_vmd_worker = None
# プログレス非表示
self.gauge_ctrl.SetValue(0)
if not event.result:
logger.error("VMD変換処理に失敗しました。", decoration=MLogger.DECORATION_BOX)
event.Skip()
return False
logger.info("VMD変換が完了しました", decoration=MLogger.DECORATION_BOX, title="OK")
# 出力先をデフォルトに戻す
sys.stdout = self.frame.file_panel_ctrl.console_ctrl
| [
"[email protected]"
] | |
93ea71308e6fd5d365bda5609b169c4f773ce234 | 2a3157ccb5376ffb03b13df4721afa405fbfc95d | /bin/virtualenv | 851dd46bb411994b649306face43a5dd104c9557 | [] | no_license | bopopescu/DemoDjango | 694501259322590d2959ef65cb6231ba1b1cf128 | b5ea252f0293ea63905a72045703b50815fbd673 | refs/heads/master | 2022-11-20T23:25:41.737807 | 2018-09-17T09:49:28 | 2018-09-17T09:49:28 | 282,543,262 | 0 | 0 | null | 2020-07-25T23:44:16 | 2020-07-25T23:44:16 | null | UTF-8 | Python | false | false | 241 | #!/home/jinesh/Documents/djangoproj/bin/python
# -*- coding: utf-8 -*-
import re
import sys
from virtualenv import main
if __name__ == '__main__':
sys.argv[0] = re.sub(r'(-script\.pyw?|\.exe)?$', '', sys.argv[0])
sys.exit(main())
| [
"[email protected]"
] | ||
dca2f3644310a1e7c67b6ae89b9eb9ea3a0c23db | 781e2692049e87a4256320c76e82a19be257a05d | /all_data/exercism_data/python/bob/b4037f9e2f47429f9d3e6ac8ed0fa8bf.py | 1a70ecf442bfba0ffa267c895ed7411ce53dcf4a | [] | no_license | itsolutionscorp/AutoStyle-Clustering | 54bde86fe6dbad35b568b38cfcb14c5ffaab51b0 | be0e2f635a7558f56c61bc0b36c6146b01d1e6e6 | refs/heads/master | 2020-12-11T07:27:19.291038 | 2016-03-16T03:18:00 | 2016-03-16T03:18:42 | 59,454,921 | 4 | 0 | null | 2016-05-23T05:40:56 | 2016-05-23T05:40:56 | null | UTF-8 | Python | false | false | 515 | py | class Bob:
def hey(self, ask):
conversation = Identify(ask)
if conversation.question():
return "Sure."
elif conversation.yell():
return "Woah, chill out!"
elif conversation.anything():
return "Fine. Be that way!"
else:
return "Whatever."
class Identify:
def __init__(self, ask):
self.ask = ask or ""
def question(self):
return self.ask.endswith("?")
def yell(self):
return self.ask == self.ask.upper()
def anything(self):
return self.ask.replace(" ","") == self.ask.split()
| [
"[email protected]"
] |
Subsets and Splits
No saved queries yet
Save your SQL queries to embed, download, and access them later. Queries will appear here once saved.