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
|
---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
3f0fffecb61d68c200b0497141ba08152cbf23ab | 77b3ef4cae52a60181dfdf34ee594afc7a948925 | /mediation/dags/cm_sub_dag_import_huawei_2g_files.py | 65d0e712174d52e4a419c52213345d1decc65dd8 | [
"Apache-2.0"
] | permissive | chandusekhar/bts-ce | 4cb6d1734efbda3503cb5fe75f0680c03e4cda15 | ad546dd06ca3c89d0c96ac8242302f4678ca3ee3 | refs/heads/master | 2021-07-15T02:44:27.646683 | 2020-07-26T08:32:33 | 2020-07-26T08:32:33 | 183,961,877 | 0 | 0 | Apache-2.0 | 2020-07-26T08:32:34 | 2019-04-28T21:42:29 | Python | UTF-8 | Python | false | false | 2,517 | py | import sys
import os
from airflow.models import DAG
from airflow.operators.bash_operator import BashOperator
from airflow.operators.python_operator import PythonOperator
from airflow.operators.python_operator import BranchPythonOperator
from airflow.operators.dummy_operator import DummyOperator
# sys.path.append('/mediation/packages');
#
# from bts import NetworkBaseLine, Utils, ProcessCMData;
#
# bts_utils = Utils();
def import_huawei_2g_parsed_csv(parent_dag_name, child_dag_name, start_date, schedule_interval):
"""
Parse huawei 2g cm files.
:param parent_dag_name:
:param child_dag_name:
:param start_date:
:param schedule_interval:
:return:
"""
dag = DAG(
'%s.%s' % (parent_dag_name, child_dag_name),
schedule_interval=schedule_interval,
start_date=start_date,
)
t23 = DummyOperator( task_id='branch_huawei_2g_importer', dag=dag)
import_mml_csv = BashOperator(
task_id='import_huawei_2g_mml_data',
bash_command='python /mediation/bin/load_cm_data_into_db.py huawei_mml_gsm /mediation/data/cm/huawei/parsed/mml_gsm ',
dag=dag)
import_nbi_csv = BashOperator(
task_id='import_huawei_2g_nbi_data',
bash_command='python /mediation/bin/load_cm_data_into_db.py huawei_nbi_gsm /mediation/data/cm/huawei/parsed/nbi_gsm ',
dag=dag)
import_nbi_csv = BashOperator(
task_id='import_huawei_2g_gexport_data',
bash_command='python /mediation/bin/load_cm_data_into_db.py huawei_gexport_gsm /mediation/data/cm/huawei/parsed/gexport_gsm ',
dag=dag)
t_join = DummyOperator(
task_id='join_huawei_2g_importer',
dag=dag,
)
t_run_huawei_gexport_gsm_insert_queries = BashOperator(
task_id='run_huawei_gexport_gsm_insert_queries',
bash_command='python /mediation/bin/run_cm_load_insert_queries.py huawei_gexport_gsm',
dag=dag)
dag.set_dependency('branch_huawei_2g_importer', 'import_huawei_2g_mml_data')
dag.set_dependency('branch_huawei_2g_importer', 'import_huawei_2g_nbi_data')
dag.set_dependency('branch_huawei_2g_importer', 'import_huawei_2g_gexport_data')
dag.set_dependency('import_huawei_2g_gexport_data', 'run_huawei_gexport_gsm_insert_queries')
dag.set_dependency('import_huawei_2g_mml_data', 'join_huawei_2g_importer')
dag.set_dependency('import_huawei_2g_nbi_data', 'join_huawei_2g_importer')
dag.set_dependency('run_huawei_gexport_gsm_insert_queries', 'join_huawei_2g_importer')
return dag | [
"[email protected]"
] | |
7f1d778988aaa8410b69aaff2a859853bb5d7817 | 97eac4a05c77e1b6898b84c9606afa13428e45df | /024_Lexicographic_permutations.py | 80fe8dd1ef24fad7bc08caf50d061bf609d82710 | [] | no_license | ryanmcg86/Euler_Answers | 8f71b93ea15fceeeeb6b661d7401e40b760a38e6 | 28374025448b16aab9ed1dd801aafc3d602f7da8 | refs/heads/master | 2022-08-11T13:31:11.038918 | 2022-07-28T00:35:11 | 2022-07-28T00:35:11 | 190,278,288 | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 1,682 | py | '''A permutation is an ordered arrangement of objects.
For example, 3124 is one possible permutation of the digits 1, 2, 3 and 4.
If all of the permutations are listed numerically or alphabetically, we call it lexicographic order.
The lexicographic permutations of 0, 1 and 2 are:
012 021 102 120 201 210
What is the millionth lexicographic permutation of the digits 0, 1, 2, 3, 4, 5, 6, 7, 8 and 9?
Link: https://projecteuler.net/problem=24'''
#Imports
import time
#Build a factorial function
def fact(n):
ans = 1
for i in range(1, n + 1):
ans *= i
return ans
#Build a suffix function
def buildSuffix(num):
suff = 'th'
begin = len(str(num)) - 2
end = begin + 1
suffixes = [[1, 'st'], [2, 'nd'], [3, 'rd']]
if str(num)[begin:end] != '1':
for i in range(0, len(suffixes)):
if int(str(num)[-1]) == suffixes[i][0]
suff = suffixes[i][1]
return suff
#Build a perm function
def perm(n, s):
if len(s) == 1: return s
q, r = divmod(n, fact(len(s) - 1))
return s[q] + perm(r, s[:q] + s[q + 1:])
#Build a lexigraphic permutation function
#that returns the nth lexigraphic permutation
#of a given input of numbers
def lexiPermutation(digits, permCount):
start = time.time()
num = perm(permCount - 1, digits)
suff = buildSuffix(permCount)
permCount = str(permCount) + suff
print 'The ' + permCount + ' lexicographic permutation of the given digits is ' + str(num) + '.'
print 'This took ' + str(time.time() - start) + ' seconds to calculate.'
#Run the program
digits = '0123456789'
permCount = 1000000
lexiPermutation(digits, permCount)
| [
"[email protected]"
] | |
a725d5a7921317bce3d96785f012f2976cfb7fb9 | 8b69984781bffb117f4adb5fbff2a75c0b31294f | /userinfo/migrations/0001_initial.py | 00ca6e3e7e58e40c8ac5de8eb3367407d2448966 | [] | no_license | kkamagwi/childOfChange | 899c5ee035090f9ab2d176a9d39cd58a48f01d39 | 8041cbfbda75e74ef1ae2470586abf45d4d431e9 | refs/heads/main | 2023-07-14T10:21:49.981455 | 2021-08-13T13:44:32 | 2021-08-13T13:44:32 | null | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 594 | py | # Generated by Django 3.2.5 on 2021-07-05 08:45
from django.db import migrations, models
class Migration(migrations.Migration):
initial = True
dependencies = [
]
operations = [
migrations.CreateModel(
name='UserContacts',
fields=[
('id', models.BigAutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),
('name', models.CharField(max_length=30)),
('phone', models.IntegerField()),
('question', models.TextField()),
],
),
]
| [
"[email protected]"
] | |
986e36d2846558b181df26b7503d003c0c9797cc | f02fe8cd0506695e56570ecbb5be6e28cda55a2e | /course_tracker/hu_authz_handler/views.py | dadcfb04f4361a45d7dc7c4b3fd37b406983f917 | [] | no_license | raprasad/Course-Tracker | 71ec045024d3adc7ef061857696b3751452ce8c6 | dc5107b923c73fb73bea84dfc2df4c989c7fe231 | refs/heads/master | 2021-01-25T08:28:18.743834 | 2014-11-11T15:51:02 | 2014-11-11T15:51:02 | null | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 3,336 | py | from django.http import HttpResponse, Http404, HttpResponseRedirect
from django.template import RequestContext
from django.shortcuts import render_to_response
from django.core.urlresolvers import reverse
from django.contrib.auth import authenticate, login
from django.contrib.auth import logout
from django.core.mail import send_mail
from hu_authzproxy.authzproxy_login_handler import AuthZProxyLoginHandler
from hu_authzproxy.authz_proxy_validation_info import AuthZProxyValidationInfo
from django.conf import settings
#import logging
#logger = logging.getLogger(__name__)
def view_handle_authz_callback(request):
"""View to handle pin callback
If authentication is succesful:
- go to a specified 'next' link
- or default to the django admin index page
"""
#
if request.GET and request.GET.get('next', None) is not None:
next = request.GET.get('next')
else:
next = reverse('admin:index', args={})
#next = reverse('admin:index', args={})
# How Django handles authentication after pin is verfied.
# See "pin_login_handler.PinLoginHandler" class handler for more info
# This allows anyone with a harvard pin to log in
access_settings = { 'restrict_to_existing_users':True \
, 'restrict_to_active_users':True \
, 'restrict_to_staff':True \
, 'restrict_to_superusers':False}
authz_validation_info = AuthZProxyValidationInfo(request=request\
,app_names=settings.HU_PIN_LOGIN_APP_NAMES\
, gnupghome=settings.GNUPG_HOME
, gpg_passphrase=settings.GPG_PASSPHRASE
, is_debug=settings.DEBUG)
authz_pin_login_handler = AuthZProxyLoginHandler(authz_validation_info\
, **access_settings)
if authz_pin_login_handler.did_login_succeed():
login(request, authz_pin_login_handler.get_user())
return HttpResponseRedirect(next)
# Errors while logging in!
#
# Retrieve error messages from the AuthZProxyLoginHandler
error_messages = []
authz_errs = authz_pin_login_handler.get_err_msgs()
if not authz_errs is None:
error_messages += authz_errs
# Retrieve error flags from the AuthZProxyLoginHandler
err_dict = authz_pin_login_handler.get_error_dict() # get error lookup for use
for k,v in err_dict.iteritems():
if v is True:
error_messages.append(' %s -> [%s]' % (k,v))
print ' %s -> [%s]' % (k,v)
# add the user IP address
error_messages.append('user IP address: %s' % request.META.get('REMOTE_ADDR', None))
# send email message to the admins
try:
admin_emails = map(lambda x: x[1], settings.ADMINS)
except:
admin_emails = None
#print admin_emails
if admin_emails and len(admin_emails) > 0:
send_mail('Course database log in fail info', 'Here is the message. %s' % ('\n'.join(error_messages)), admin_emails[0], admin_emails,fail_silently=False)
# send the error flags to the template
return render_to_response('hu_authz_handler/view_authz_login_failed.html', err_dict, context_instance=RequestContext(request))
| [
"[email protected]"
] | |
6da90b055be7beefd62289bc89d91a7ab8de662d | 53c157cca69d6ae719cb71d4917ee2f53a10b8e6 | /mobile_balance/mts.py | 515a21723e044c6650f8cf528223bc05c1027c56 | [] | no_license | Ksardos/mobile-balance | 03fdb072a364dee7f0c470f7069672c7b64ffa61 | 0f13d6be36c58abf401cb382fc85a75542adcdd5 | refs/heads/master | 2021-01-15T10:50:47.417407 | 2016-06-07T12:12:13 | 2016-06-07T12:12:13 | 78,822,827 | 0 | 0 | null | 2017-01-13T06:40:07 | 2017-01-13T06:40:07 | null | UTF-8 | Python | false | false | 1,516 | py | #!/usr/bin/env python
import requests
import re
from .exceptions import BadResponse
from .utils import check_status_code
def get_balance(number, password):
session = requests.Session()
response = session.get('https://login.mts.ru/amserver/UI/Login')
check_status_code(response, 401)
csrf_token = re.search(r'name="csrf.sign" value="(.*?)"', response.content)
if csrf_token is None:
raise BadResponse('CSRF token not found', response)
csrf_token = csrf_token.group(1)
response = session.post('https://login.mts.ru/amserver/UI/Login?service=lk&goto=https://lk.ssl.mts.ru/',
data={'IDToken1': number,
'IDToken2': password,
'csrf.sign': csrf_token,
},
headers={
'Accept-Language': 'ru,en;q=0.8',
})
check_status_code(response, 200)
response = session.get('https://oauth.mts.ru/webapi-1.4/customers/@me')
check_status_code(response, 200)
data = response.json()
relations = data['genericRelations']
targets = [rel['target'] for rel in relations]
accounts = [target for target in targets if target['@c'] == '.Account']
if not accounts:
raise RuntimeError('Account not found in the data response')
balance = accounts[0].get('balance')
if balance is None:
raise BadResponse('Unable to get balance from JSON', response)
return float(balance)
| [
"[email protected]"
] | |
cd7f0aec7365a9256571957d2a9db176a2b39101 | 6fa701cdaa0d83caa0d3cbffe39b40e54bf3d386 | /google/cloud/recommender/v1beta1/recommender-v1beta1-py/google/cloud/recommender_v1beta1/services/recommender/pagers.py | ab7b2b40c3da808480faecb7fcee88dfb5ce681c | [
"Apache-2.0"
] | permissive | oltoco/googleapis-gen | bf40cfad61b4217aca07068bd4922a86e3bbd2d5 | 00ca50bdde80906d6f62314ef4f7630b8cdb6e15 | refs/heads/master | 2023-07-17T22:11:47.848185 | 2021-08-29T20:39:47 | 2021-08-29T20:39:47 | null | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 11,307 | 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.
#
from typing import Any, AsyncIterable, Awaitable, Callable, Iterable, Sequence, Tuple, Optional
from google.cloud.recommender_v1beta1.types import insight
from google.cloud.recommender_v1beta1.types import recommendation
from google.cloud.recommender_v1beta1.types import recommender_service
class ListInsightsPager:
"""A pager for iterating through ``list_insights`` requests.
This class thinly wraps an initial
:class:`google.cloud.recommender_v1beta1.types.ListInsightsResponse` object, and
provides an ``__iter__`` method to iterate through its
``insights`` field.
If there are more pages, the ``__iter__`` method will make additional
``ListInsights`` requests and continue to iterate
through the ``insights`` field on the
corresponding responses.
All the usual :class:`google.cloud.recommender_v1beta1.types.ListInsightsResponse`
attributes are available on the pager. If multiple requests are made, only
the most recent response is retained, and thus used for attribute lookup.
"""
def __init__(self,
method: Callable[..., recommender_service.ListInsightsResponse],
request: recommender_service.ListInsightsRequest,
response: recommender_service.ListInsightsResponse,
*,
metadata: Sequence[Tuple[str, str]] = ()):
"""Instantiate the pager.
Args:
method (Callable): The method that was originally called, and
which instantiated this pager.
request (google.cloud.recommender_v1beta1.types.ListInsightsRequest):
The initial request object.
response (google.cloud.recommender_v1beta1.types.ListInsightsResponse):
The initial response object.
metadata (Sequence[Tuple[str, str]]): Strings which should be
sent along with the request as metadata.
"""
self._method = method
self._request = recommender_service.ListInsightsRequest(request)
self._response = response
self._metadata = metadata
def __getattr__(self, name: str) -> Any:
return getattr(self._response, name)
@property
def pages(self) -> Iterable[recommender_service.ListInsightsResponse]:
yield self._response
while self._response.next_page_token:
self._request.page_token = self._response.next_page_token
self._response = self._method(self._request, metadata=self._metadata)
yield self._response
def __iter__(self) -> Iterable[insight.Insight]:
for page in self.pages:
yield from page.insights
def __repr__(self) -> str:
return '{0}<{1!r}>'.format(self.__class__.__name__, self._response)
class ListInsightsAsyncPager:
"""A pager for iterating through ``list_insights`` requests.
This class thinly wraps an initial
:class:`google.cloud.recommender_v1beta1.types.ListInsightsResponse` object, and
provides an ``__aiter__`` method to iterate through its
``insights`` field.
If there are more pages, the ``__aiter__`` method will make additional
``ListInsights`` requests and continue to iterate
through the ``insights`` field on the
corresponding responses.
All the usual :class:`google.cloud.recommender_v1beta1.types.ListInsightsResponse`
attributes are available on the pager. If multiple requests are made, only
the most recent response is retained, and thus used for attribute lookup.
"""
def __init__(self,
method: Callable[..., Awaitable[recommender_service.ListInsightsResponse]],
request: recommender_service.ListInsightsRequest,
response: recommender_service.ListInsightsResponse,
*,
metadata: Sequence[Tuple[str, str]] = ()):
"""Instantiates the pager.
Args:
method (Callable): The method that was originally called, and
which instantiated this pager.
request (google.cloud.recommender_v1beta1.types.ListInsightsRequest):
The initial request object.
response (google.cloud.recommender_v1beta1.types.ListInsightsResponse):
The initial response object.
metadata (Sequence[Tuple[str, str]]): Strings which should be
sent along with the request as metadata.
"""
self._method = method
self._request = recommender_service.ListInsightsRequest(request)
self._response = response
self._metadata = metadata
def __getattr__(self, name: str) -> Any:
return getattr(self._response, name)
@property
async def pages(self) -> AsyncIterable[recommender_service.ListInsightsResponse]:
yield self._response
while self._response.next_page_token:
self._request.page_token = self._response.next_page_token
self._response = await self._method(self._request, metadata=self._metadata)
yield self._response
def __aiter__(self) -> AsyncIterable[insight.Insight]:
async def async_generator():
async for page in self.pages:
for response in page.insights:
yield response
return async_generator()
def __repr__(self) -> str:
return '{0}<{1!r}>'.format(self.__class__.__name__, self._response)
class ListRecommendationsPager:
"""A pager for iterating through ``list_recommendations`` requests.
This class thinly wraps an initial
:class:`google.cloud.recommender_v1beta1.types.ListRecommendationsResponse` object, and
provides an ``__iter__`` method to iterate through its
``recommendations`` field.
If there are more pages, the ``__iter__`` method will make additional
``ListRecommendations`` requests and continue to iterate
through the ``recommendations`` field on the
corresponding responses.
All the usual :class:`google.cloud.recommender_v1beta1.types.ListRecommendationsResponse`
attributes are available on the pager. If multiple requests are made, only
the most recent response is retained, and thus used for attribute lookup.
"""
def __init__(self,
method: Callable[..., recommender_service.ListRecommendationsResponse],
request: recommender_service.ListRecommendationsRequest,
response: recommender_service.ListRecommendationsResponse,
*,
metadata: Sequence[Tuple[str, str]] = ()):
"""Instantiate the pager.
Args:
method (Callable): The method that was originally called, and
which instantiated this pager.
request (google.cloud.recommender_v1beta1.types.ListRecommendationsRequest):
The initial request object.
response (google.cloud.recommender_v1beta1.types.ListRecommendationsResponse):
The initial response object.
metadata (Sequence[Tuple[str, str]]): Strings which should be
sent along with the request as metadata.
"""
self._method = method
self._request = recommender_service.ListRecommendationsRequest(request)
self._response = response
self._metadata = metadata
def __getattr__(self, name: str) -> Any:
return getattr(self._response, name)
@property
def pages(self) -> Iterable[recommender_service.ListRecommendationsResponse]:
yield self._response
while self._response.next_page_token:
self._request.page_token = self._response.next_page_token
self._response = self._method(self._request, metadata=self._metadata)
yield self._response
def __iter__(self) -> Iterable[recommendation.Recommendation]:
for page in self.pages:
yield from page.recommendations
def __repr__(self) -> str:
return '{0}<{1!r}>'.format(self.__class__.__name__, self._response)
class ListRecommendationsAsyncPager:
"""A pager for iterating through ``list_recommendations`` requests.
This class thinly wraps an initial
:class:`google.cloud.recommender_v1beta1.types.ListRecommendationsResponse` object, and
provides an ``__aiter__`` method to iterate through its
``recommendations`` field.
If there are more pages, the ``__aiter__`` method will make additional
``ListRecommendations`` requests and continue to iterate
through the ``recommendations`` field on the
corresponding responses.
All the usual :class:`google.cloud.recommender_v1beta1.types.ListRecommendationsResponse`
attributes are available on the pager. If multiple requests are made, only
the most recent response is retained, and thus used for attribute lookup.
"""
def __init__(self,
method: Callable[..., Awaitable[recommender_service.ListRecommendationsResponse]],
request: recommender_service.ListRecommendationsRequest,
response: recommender_service.ListRecommendationsResponse,
*,
metadata: Sequence[Tuple[str, str]] = ()):
"""Instantiates the pager.
Args:
method (Callable): The method that was originally called, and
which instantiated this pager.
request (google.cloud.recommender_v1beta1.types.ListRecommendationsRequest):
The initial request object.
response (google.cloud.recommender_v1beta1.types.ListRecommendationsResponse):
The initial response object.
metadata (Sequence[Tuple[str, str]]): Strings which should be
sent along with the request as metadata.
"""
self._method = method
self._request = recommender_service.ListRecommendationsRequest(request)
self._response = response
self._metadata = metadata
def __getattr__(self, name: str) -> Any:
return getattr(self._response, name)
@property
async def pages(self) -> AsyncIterable[recommender_service.ListRecommendationsResponse]:
yield self._response
while self._response.next_page_token:
self._request.page_token = self._response.next_page_token
self._response = await self._method(self._request, metadata=self._metadata)
yield self._response
def __aiter__(self) -> AsyncIterable[recommendation.Recommendation]:
async def async_generator():
async for page in self.pages:
for response in page.recommendations:
yield response
return async_generator()
def __repr__(self) -> str:
return '{0}<{1!r}>'.format(self.__class__.__name__, self._response)
| [
"bazel-bot-development[bot]@users.noreply.github.com"
] | bazel-bot-development[bot]@users.noreply.github.com |
e249bf31e6d80f504123b489d1b4661300a67e75 | 393a393bb593ec5813aa16a96384a62128eed643 | /ocr/src/processor/utility/ocr.py | 6417fd2b6fb153a7ef29d964039a5a6bf6ad8bff | [] | no_license | normanyahq/kejinyan | 4b0d40559b0f6b715107aa38fe800539ba485f27 | 486403fcf393077fefb441cb64c217a2289aaf3e | refs/heads/master | 2023-06-24T13:43:52.740419 | 2017-10-09T04:29:50 | 2017-10-09T04:29:50 | 84,788,246 | 7 | 6 | null | null | null | null | UTF-8 | Python | false | false | 16,963 | py | from __future__ import division, print_function
import cv2
import wand.image
import PIL.Image
import numpy as np
import subprocess
import re
import time
from .common import getSquareDist
# from PyPDF2 import PdfFileReader
from ..utility.common import timeit
#timeit
def binarizeImage(gray_image):
'''
Given an grayscale image,
return the inversed binary image.
the main idea is:
OSTU threshold with gamma correction
'''
# gamma correction
# learned from university physics
# many students failed in the final test
# and the instructor, Shan Qiao, did it twice
# and saved most (all?) of us
rescale = lambda x: (25.5 * np.sqrt(x / 2.55))
gray_image = cv2.GaussianBlur(gray_image, (3, 3), 0)
ret3, th3 = cv2.threshold(gray_image, 0, 255, cv2.THRESH_BINARY_INV + cv2.THRESH_OTSU)
ret3, th3 = cv2.threshold(gray_image, rescale(ret3), 255, cv2.THRESH_BINARY_INV)
return th3
def getPDFPageNum(file_path):
'''
This is a fast version to get PDF Page Number
reutrn 0 for malformated PDF
'''
# command example:
# gs -dNODISPLAY -dBATCH -dNOPAUSE -o /dev/null ./half_a4.pdf \
# | grep -e '^Page \d+$'\
# | wc -l
params = ["gs",
"-dNOPAUSE",
"-sDEVICE=nullpage", # this is a must, otherwise it will hang
"-o/dev/null",
"-dBATCH",
file_path]
result = subprocess.check_output(params)
return len(re.findall("Page\s\d+", result))
# deprecated, will hang when the malformated file
# is relatively large
def _getPDFPageNum(file_path):
'''
given a file path, return the number of pages of pdf
if the pdf file is invalid, return 0
'''
try:
pdf = PdfFileReader(open(file_path, 'rb'))
return pdf.getNumPages()
except:
import traceback
traceback.print_exc()
return 0
def pdf2jpg(file_path, resolution=300, save_path=None):
'''
convert pdf into jpg.
if the pdf file, for example, a.pdf has more than one pages,
the output filenames will be named as:
a-00000.jpg, a-00001.jpg, a-00002.jpg, ...
'''
save_path = file_path.replace(".pdf", "")
# command example:
# gs -dNOPAUSE -q -sDEVICE=jpeg -dBATCH -r300 -sOutputFile=a-%05d.jpg half.pdf
params = ["gs",
"-dNOPAUSE",
"-sDEVICE=jpeg",
"-dBATCH",
"-q", # run silently
"-r{}".format(resolution),
"-sOutputFile={}-%05d.jpg".format(save_path),
file_path]
subprocess.call(params)
# deprecated, 10x slower than current version
# remain for potential use in AWS lambda
def _pdf2jpg(file_path, resolution=300, save_path=None):
'''
convert pdf into jpg.
if the pdf file, for example, a.pdf has more than one pages,
the output filenames will be named as:
a-0.jpg, a-1.jpg, a-2.jpg, ...
'''
with wand.image.Image(filename=file_path, resolution=resolution) as img:
if not save_path:
save_path = file_path.replace(".pdf", ".jpg")
print ('Save file to:', save_path)
img.save(filename=save_path)
def getLastCorner(centers):
'''
Given the centers of 3 corners, return the 4th corner.
Note: We assume that the image is already in correct orientation,
and centers are stored in following order:
topleft(p1) -> bottomleft(p2) -> topright(p3)
so we use vector v(p1->p2) + v(p1->p3) to predict the 4th corner
'''
assert len(centers) == 3
p1, p2, p3 = centers[:]
return (p2[0]+p3[0]-p1[0], p2[1]+p3[1]-p1[1],)
#timeit
def rotateImage(gray_image, degree, expand=True):
'''
rotate the image clockwise by given degrees using pillow library
'''
im = PIL.Image.fromarray(gray_image)
return np.asarray(im.rotate(degree, expand=expand))
def getPixelListCenter(pixels):
'''
given a list of pixels, return a tuple of their center
'''
return tuple(np.mean(pixels, axis=0).astype('uint32')[0])
#timeit
def getQRCornerContours(gray_image, t=False):
'''
given binary image, return the pixel lists of their contours:
'''
#timeit
def getContourDepth(hierarchy):
result = dict()
def _getDepth(hierarchy, i):
if i in result:
return result[i]
Next, Previous, First_Child, Parent = 0, 1, 2, 3
cur_index = hierarchy[i][First_Child]
children_indexes = list()
while cur_index != -1:
children_indexes.append(cur_index)
cur_index = hierarchy[cur_index][Next]
if children_indexes:
result[i] = max(map(lambda x: _getDepth(hierarchy, x), children_indexes)) + 1
else:
result[i] = 1
return result[i]
for i in range(len(hierarchy)):
if i not in result:
result[i] = _getDepth(hierarchy, i)
return result
#timeit
def filter_with_shape(contours, err_t=1.5):
'''
remove squares whose min bouding rect is not like square
'''
ratios = list()
for i in range(len(contours)):
rect = cv2.boundingRect(contours[i])
ratios.append(max(rect[3], rect[2]) / min(rect[3], rect[2]))
# print (sorted(ratios))
valid_index = filter(lambda i: ratios[i] <=err_t, range(len(contours)))
contours = [contours[i] for i in valid_index]
return contours
#timeit
def filter_with_positions(contours, err_t=0.1):
'''
find all contours triplets whose centers are most similar to a right
triangle:
abs(sqrt(a^2 + b^2) - c) < err_t
and pick the triplet which forms the larget triangle
'''
centers = list(map(lambda c: getPixelListCenter(c), contours))
i, j, k = 0, 1, 2
min_err = float('inf')
triplets = list()
while i+2 != len(contours):
j = i + 1
while j+1 != len(contours):
k = j + 1
while k != len(contours):
tri_edge_sqr = [getSquareDist(centers[i], centers[k]),
getSquareDist(centers[i], centers[j]),
getSquareDist(centers[j], centers[k])]
tri_edge_sqr.sort()
err = abs(tri_edge_sqr[0] + tri_edge_sqr[1] - tri_edge_sqr[2]) / tri_edge_sqr[2]
if err < err_t:
triplets.append((i, j, k, tri_edge_sqr[2]))
k += 1
j += 1
i += 1
triplets.sort(key=lambda x: x[3]) # sort with the largest edge
best_triplet = triplets[-1]
contours = [contours[best_triplet[0]], contours[best_triplet[1]], contours[best_triplet[2]]]
return contours
#timeit
def rearrange_contours(contours):
'''
use polar coordinates to rearrange contours in counter-clockwise order,
and the contour on right angle is the first element in rearranged array
'''
centers = list(map(lambda c: getPixelListCenter(c), contours))
triangle_center = np.mean(np.array(centers), axis=0)
std_centers = list(map(lambda (x, y): (x-triangle_center[0], triangle_center[1]) - y, centers))
theta_index = zip(map(lambda (x, y): np.arctan2(y, x), std_centers), range(len(contours)))
theta_index.sort()
contours = [contours[i] for theta, i in theta_index]
centers = [centers[i] for theta, i in theta_index]
min_err = float('inf')
right_angle_index = 0
for t1 in range(len(contours)):
t2 = (t1 + 1) % len(contours)
t3 = (t2 + 1) % len(contours)
diff = abs(getSquareDist(centers[t1], centers[t2])
+ getSquareDist(centers[t1], centers[t3])
- getSquareDist(centers[t2], centers[t3]))
if min_err > diff:
min_err = diff
right_angle_index = t1
t = [i % len(contours) for i in range(right_angle_index, right_angle_index+len(contours))]
contours = [contours[i] for i in t]
centers = [getPixelListCenter(c) for c in contours]
return contours
image_edge = cv2.Canny(gray_image, 100, 200)
kernel = np.ones((3,3),np.uint8)
image_edge = cv2.dilate(image_edge, kernel, iterations=1)
_, contours, hierarchy = cv2.findContours(image_edge.copy(), cv2.RETR_TREE, cv2.CHAIN_APPROX_NONE)
contours_depth = getContourDepth(hierarchy[0])
valid_index = filter(lambda x: contours_depth[x] == 6, range(len(contours)))
contours = [contours[i] for i in valid_index]
contours = filter_with_shape(contours)
# print("number of contour before filter of positions: {}".format(len(contours)))
# Find best triplet which can form a right triangle
if len(contours) > 3:
contours = filter_with_positions(contours)
contours = rearrange_contours(contours)
return contours
#timeit
def adjustOrientation(binary_image, original_image, save_path=None):
'''
given an answer sheet, return an copy which is rotated to the correct orientation,
contours of three corner blocks and four corner positions in (col, row) tuple
'''
#timeit
def rotateCoordinate(x, y, w, h, degree, paper_orientation_changed=False):
_x, _y = x - w // 2, h // 2 - y
angle = degree / 180 * np.pi
# print ("_x:{}, _y:{}, angle:{}".format(_x, _y, angle))
if not paper_orientation_changed:
r_x = int(_x * np.cos(angle) - _y * np.sin(angle)) + w // 2
r_y = h // 2 - int(_y * np.cos(angle) + _x * np.sin(angle))
else:
r_x = int(_x * np.cos(angle) - _y * np.sin(angle)) + h // 2
r_y = w // 2 - int(_y * np.cos(angle) + _x * np.sin(angle))
return (r_x, r_y)
#timeit
def rotateContour(contour, w, h, degree, paper_orientation_changed=False):
# print ("before:{}".format(contour[:10]))
# print ("contour: {}".format(contour))
# weird storage format
result = np.array([[list(rotateCoordinate(c[0][0], c[0][1], w, h, degree, paper_orientation_changed))] \
for c in contour])
# result = np.array(list(map(lambda c: [list(rotateCoordinate)], contour)))
# print ("after:{}".format(result[:10]))
return result
def getAdjustDegree(centers):
x = [int(c[0]) for c in centers]
y = [int(c[1]) for c in centers]
d1 = np.arctan2(y[0]-y[1], x[1]-x[0]) + np.pi / 2
d2 = np.arctan2(y[0]-y[3], x[3]-x[0])
# print ("d1: {}, d2: {}, Adjust Degree: {}".format(d1, d2, (d1 + d2) / 2 / np.pi * 180))
return -(d1 + d2) / 2 / np.pi * 180
contours = getQRCornerContours(binary_image)
centers = list(map(lambda c: getPixelListCenter(c), contours))
# append the 4th corner according to the other 3
centers.insert(2, getLastCorner(centers))
# print ("centers: {}".format(centers))
h, w = binary_image.shape
x, y = centers[0][0] - w//2, h//2 - centers[0][1]
# print ("orientation test: x={}, y={}".format(x, y))
degree = 0
paper_orientation_changed = False # landscape <-> portrait
if x > 0 and y > 0:
degree = 90
paper_orientation_changed = True
elif x > 0 and y < 0:
degree = 180
elif x < 0 and y < 0:
degree = 270
paper_orientation_changed = True
# slightly adjust orientation, making the edges vertical and horizontal
if degree:
centers = [rotateCoordinate(x, y, w, h, degree, paper_orientation_changed) for x, y in centers]
binary_image = rotateImage(binary_image, degree)
original_image = rotateImage(original_image, degree)
# contours = [rotateContour(contour, w, h, degree, paper_orientation_changed) for contour in contours]
# print ("rotate degree: {}, centers: {}".format(degree, centers))
# cv2.imshow('xx', gray_image)
# cv2.waitKey(0)
delta_degree = getAdjustDegree(centers)
if delta_degree:
binary_image = rotateImage(binary_image, delta_degree, expand=False)
original_image = rotateImage(original_image, delta_degree, expand=False)
centers = [rotateCoordinate(x, y, w, h, delta_degree) for x, y in centers]
# contours = [rotateContour(contour, w, h, delta_degree) for contour in contours]
# Expand should be false, otherwise, we should shift centers a bit
######################################
# TODO: Affine Transform if needed #
######################################
# After rotation, the image is no longer binary image
# thus, we need to do it again
_, binary_image = cv2.threshold(binary_image, 0, 255,
cv2.THRESH_BINARY + cv2.THRESH_OTSU)
# return gray_image, contours, centers
return binary_image, original_image, centers,
def _separateGrides(stripe):
'''
given a stripe on image, calculate the position of gridlines
corner block should not be included
'''
# if it's vertical stripe, transpose it to horizontal
if stripe.shape[0] > stripe.shape[1]:
stripe = stripe.transpose()
h, w = stripe.shape
bw_line = (np.sum(stripe > 128, axis=0)) > (h // 2)
#### Smooth
# t = 0
# while bw_line[t] == True:
# bw_line[t] = False
# t += 1
for i in range(1, w-1):
if bw_line[i] != bw_line[i+1] and bw_line[i] != bw_line[i-1] and bw_line[i-1] == bw_line[i+1]:
bw_line[i] = bw_line[i-1]
### Smooth
cur_state = bw_line[0]
result = list()
for i in range(1, w):
if cur_state != bw_line[i]:
cur_state = bw_line[i]
result.append(i)
return result
def getGridlinePositions(binary_image, contours, centers):
'''
calculate the horizontal and vertical gridline positions
'''
# print (len(contours))
bounding_rects = list(map(cv2.boundingRect, contours))
# print ("bounding rects: {}".format(bounding_rects))
x, y, w, h = bounding_rects[1]
# print (x, y, w, h, centers)
stripe = binary_image[y + int(0.3*h) : y + int(0.7*h), x+w : centers[2][0]]
# print ("stripe.shape:{}".format(stripe.shape))
vertical = list(map(lambda c: c+x+w, _separateGrides(stripe)))
# x1, y1, w1, h1 = bounding_rects[0]
# x2, y2, w2, h2 = bounding_rects[1]
# considering the topleft, bottomleft corners have block,
# we use right and bottom lines to locate grids
# so that there's no conflict between corner block and black grids
x1, y1, w1, h1 = bounding_rects[2]
x2, y2, w2, h2 = x1, y, w, h # use approximates here.
stripe = binary_image[y1+h1: y2-1, x1+int(0.15*(w1+w2)) : x1+int(0.35*(w1+w2))]
horizontal = list(map(lambda r: r+y1+h1, _separateGrides(stripe)))
# print ("stripe.shape:{}".format(stripe.shape))
# print ("horizontal:{}\nvertical:{}".format(horizontal, vertical))
return horizontal, vertical
# count = 0
def getBlackRatio(grid, padding_ratio = 0.2):
'''
return the ratio of black pixels
Track only 36% (60% * 60%) area in the center
'''
h, w = grid.shape
dh, dw = int(h * padding_ratio), int(w * padding_ratio)
grid = grid[dh:h-dh, dw:w-dw]
# global count
# cv2.imwrite("tmp/{}_{}.jpg".format(count, np.sum((grid>128).flatten()) / grid.size), grid)
# count += 1
return np.sum((grid>128).flatten()) / grid.size
def extractGrids(binary_image, horizontal_pos, vertical_pos, r, c, h, w):
'''
given a binary image, return the rectangular area of grids in
from ROW_r -> ROW_{r+h}, COLUMN_c -> COLUMN_{c+w}
'''
y1, y2 = horizontal_pos[r], horizontal_pos[r + h]
x1, x2 = vertical_pos[c], vertical_pos[c + w]
return binary_image[y1:y2, x1:x2]
def getRatioFromStripe(stripe, num_choice=5):
'''
given stripe, and number of choice, return the black pixel ratio sequence
of the stripe
'''
if stripe.shape[0] > stripe.shape[1]:
stripe = stripe.transpose()
h, w = stripe.shape
grid_len = w // num_choice
result = list()
for i in range(num_choice):
grid = stripe[:, i*grid_len : (i+1)*grid_len]
result.append(getBlackRatio(grid))
return result
def getDigitFromSequence(sequence, T=0.5):
'''
given sequence array, return argmax(sequence) if a value
larger than threshold T exists
'''
return str(np.argmax(sequence)) if np.max(sequence) > T else "-"
def getAnswerFromSequence(sequence, T=0.5):
'''
given sequence array, return all index i's which ratio_i's are
larger than threshold T
'''
# print (max(sequence), min(sequence), sequence)
Choices = "ABCDEFGHIJK"
result = "".join([Choices[i] for i in range(len(sequence)) if sequence[i] > T])
return result if result else "-"
| [
"[email protected]"
] | |
a465a6c6bfb2e0461cae260d9295a33bb90d79f2 | d974256fed39a5583012b17fd9c371121271814b | /charpter_04/test/client.py | 7bf183d5b1b86c1fceee40195c7030cf02fc7bf8 | [] | no_license | gbkuce/spider-courses | 18ce88beb120641eae19c01f331ddd53adc4105a | 3364b651149da600c51ed8d0d93a7e0cb4bc5211 | refs/heads/master | 2021-01-20T13:56:31.879419 | 2017-04-08T03:38:35 | 2017-04-08T03:38:35 | null | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 178 | py | import socket
import sys
sock = socket.create_connection(('localhost', 20012))
sock.send('Client Request')
data = sock.recv(1024)
print 'data received: ' + data
sock.close() | [
"[email protected]"
] | |
9f89fa1d231e02e7f8019130872c5211bbff275e | c8453f83242cd525a98606f665d9f5d9e84c6335 | /lib/surface/ml_engine/models/versions/__init__.py | a3bb6c9eb55744d44db8b31ff3c5dab8a13ea4d1 | [
"LicenseRef-scancode-unknown-license-reference",
"Apache-2.0"
] | permissive | paulfoley/GCP-Cloud_SDK | 5188a04d8d80a2709fa3dba799802d57c7eb66a1 | bec7106686e99257cb91a50f2c1b1a374a4fc66f | refs/heads/master | 2021-06-02T09:49:48.309328 | 2017-07-02T18:26:47 | 2017-07-02T18:26:47 | 96,041,222 | 1 | 1 | NOASSERTION | 2020-07-26T22:40:49 | 2017-07-02T18:19:52 | Python | UTF-8 | Python | false | false | 901 | py | # Copyright 2016 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 group for ml-engine models versions."""
from googlecloudsdk.calliope import base
# This group should remain in BETA only because all commands within it are
# deprecated.
@base.ReleaseTracks(base.ReleaseTrack.BETA)
class Versions(base.Group):
"""Cloud ML Engine Versions commands."""
pass
| [
"[email protected]"
] | |
b7c5b0a0bd0c73406067db7c8d978a348d299ee3 | 5b188a06f9b615b8a4541074fc50eeb1bfac5d97 | /链表/reverseKGroup.py | 82d64ffbfca37579083481a2d75302347af73f4c | [] | no_license | yinyinyin123/algorithm | 3a8cf48a48bd2758c1e156c8f46161fe3697342f | b53f030ea3a4e2f6451c18d43336ff9c5d7433af | refs/heads/master | 2021-01-07T20:07:12.544539 | 2020-08-31T05:16:44 | 2020-08-31T05:16:44 | 241,807,608 | 5 | 2 | null | null | null | null | UTF-8 | Python | false | false | 1,227 | py |
### 2020/06/01
### leetcode 25 K个一组翻转链表
### one code one day
# Definition for singly-linked list.
# class ListNode:
# def __init__(self, x):
# self.val = x
# self.next = None
class Solution:
def reverseKGroup(self, head: ListNode, k: int) -> ListNode:
### 反转链表
def reverse(start, end):
prev = None
pcur = start
end.next = None
while(pcur):
temp = pcur.next
pcur.next = prev
prev = pcur
pcur = temp
return prev, start
start = end = head
connect = res = None
step = 0
while(end):
step += 1
if(step == k):
temp = end.next
subhead, subtail = reverse(start, end)
if(res):
connect.next = subhead
else:
res = subhead
connect = subtail
start = end = temp
step = 0
else:
end = end.next
if(start == head):
return head
elif(start):
connect.next = start
return res
| [
"[email protected]"
] | |
276efbcd6b20cba653bfd60fa8fb2c22d660d55c | 48f7750776fbd4ba7e71dd3832cf1159222f759e | /tests/trailing_whitespace_fixer_test.py | 1c57b10ee1cf8c58b4da84c30418537434bdfa6e | [
"MIT"
] | permissive | exKAZUu/pre-commit-hooks | 9718bd44aa84ba7a4ab21c34d9f33b628c0b7807 | b85d7ac38f392a8f8b98732c61005d55c892577b | refs/heads/master | 2021-01-20T10:51:20.996895 | 2014-12-22T00:52:16 | 2014-12-22T03:46:11 | null | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 824 | py | from plumbum import local
from pre_commit_hooks.trailing_whitespace_fixer import fix_trailing_whitespace
def test_fixes_trailing_whitespace(tmpdir):
with local.cwd(tmpdir.strpath):
for filename, contents in (
('foo.py', 'foo \nbar \n'),
('bar.py', 'bar\t\nbaz\t\n'),
):
with open(filename, 'w') as f:
f.write(contents) # pragma: no cover (python 2.6 coverage bug)
ret = fix_trailing_whitespace(['foo.py', 'bar.py'])
assert ret == 1
for filename, after_contents in (
('foo.py', 'foo\nbar\n'),
('bar.py', 'bar\nbaz\n'),
):
assert open(filename).read() == after_contents
def test_returns_zero_for_no_changes():
assert fix_trailing_whitespace([__file__]) == 0
| [
"[email protected]"
] | |
116b0018982e3810edfd8a850cd43d84bac97cff | 9fc768c541145c1996f2bdb8a5d62d523f24215f | /code/Examples/ch5/E_5_11.py | 1ef351797adac178ddaba4e92fb9cfee5488d852 | [] | no_license | jumbokh/pyclass | 3b624101a8e43361458130047b87865852f72734 | bf2d5bcca4fff87cb695c8cec17fa2b1bbdf2ce5 | refs/heads/master | 2022-12-25T12:15:38.262468 | 2020-09-26T09:08:46 | 2020-09-26T09:08:46 | 283,708,159 | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 265 | py | # E_5_11 功能:重覆產生亂數(0至9的整數)直到產生的值是零時結束。
import random as rd
num=rd.randint(0,9)
count=1
while num!=0:
print(num)
count+=1
num=rd.randint(0,9)
print(num)
print('%s%d%s' %('共產生亂數',count,'次')) | [
"[email protected]"
] | |
e73cbc2e1ed90e881b52a090b01e5ab3a5a0d057 | 54156856a1822a4cd6a7e9305369b5fa33b503ac | /python/machine-learning/recommendation/collaborative_filter.py | c3be7244ae6f685fe36a376371e9018e7cc9fb31 | [] | no_license | takasashi/sandbox | cafd903e7e376485c7fec05f0b4293078147c09f | a23d85258b5525498b57672993b25d54fa08f189 | refs/heads/master | 2023-07-09T04:37:28.532448 | 2021-08-09T06:11:30 | 2021-08-09T06:11:30 | null | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 4,978 | py | from recommendation_data import dataset
from math import sqrt
print(("山田さんのカレーの評価 : {}".format(
dataset['山田']['カレー'])))
print(("山田さんのうどんの評価 : {}\n".format(
dataset['山田']['うどん'])))
print(("佐藤さんのカレーの評価: {}".format(
dataset['佐藤']['カレー'])))
print(("佐藤さんのうどんの評価: {}\n".format(
dataset['佐藤']['うどん'])))
print("鈴木さんのレーティング: {}\n".format((dataset['鈴木'])))
# 協調フィルタリングの実装
def similarity_score(person1, person2):
# 戻り値は person1 と person2 のユークリッド距離
both_viewed = {} # 双方に共通のアイテムを取得
for item in dataset[person1]:
if item in dataset[person2]:
both_viewed[item] = 1
# 共通のアイテムを持っていなければ 0 を返す
if len(both_viewed) == 0:
return 0
# ユークリッド距離の計算
sum_of_eclidean_distance = []
for item in dataset[person1]:
if item in dataset[person2]:
sum_of_eclidean_distance.append(
pow(dataset[person1][item] - dataset[person2][item], 2))
total_of_eclidean_distance = sum(sum_of_eclidean_distance)
return 1 / (1 + sqrt(total_of_eclidean_distance))
print("山田さんと鈴木さんの類似度 (ユークリッド距離)",
similarity_score('山田', '鈴木'))
def pearson_correlation(person1, person2):
# 両方のアイテムを取得
both_rated = {}
for item in dataset[person1]:
if item in dataset[person2]:
both_rated[item] = 1
number_of_ratings = len(both_rated)
# 共通のアイテムがあるかチェック、無ければ 0 を返す
if number_of_ratings == 0:
return 0
# 各ユーザーのすべての付リファレンスを追加
person1_preferences_sum = sum(
[dataset[person1][item] for item in both_rated])
person2_preferences_sum = sum(
[dataset[person2][item] for item in both_rated])
# 各ユーザーの嗜好の二乗を計算
person1_square_preferences_sum = sum(
[pow(dataset[person1][item], 2) for item in both_rated])
person2_square_preferences_sum = sum(
[pow(dataset[person2][item], 2) for item in both_rated])
# 商品の価値を算出して合計
product_sum_of_both_users = sum(
[dataset[person1][item] * dataset[person2][item] for item in both_rated])
# ピアソンスコアの計算
numerator_value = product_sum_of_both_users - \
(person1_preferences_sum * person2_preferences_sum / number_of_ratings)
denominator_value = sqrt((person1_square_preferences_sum - pow(person1_preferences_sum, 2) / number_of_ratings) * (
person2_square_preferences_sum - pow(person2_preferences_sum, 2) / number_of_ratings))
if denominator_value == 0:
return 0
else:
r = numerator_value / denominator_value
return r
print("山田さんと田中さんの類似度 (ピアソン相関係数)",
(pearson_correlation('山田', '田中')))
def most_similar_users(person, number_of_users):
# 似たユーザーとその類似度を返す
scores = [(pearson_correlation(person, other_person), other_person)
for other_person in dataset if other_person != person]
# 最高の類似度の人物が最初になるようにソートする
scores.sort()
scores.reverse()
return scores[0:number_of_users]
print("山田さんに似た人ベスト 3",
most_similar_users('山田', 3))
def user_reommendations(person):
# 他のユーザーの加重平均によるランキングから推薦を求める
totals = {}
simSums = {}
# rankings_list = []
for other in dataset:
# 自分自身は比較しない
if other == person:
continue
sim = pearson_correlation(person, other)
# print ">>>>>>>",sim
# ゼロ以下のスコアは無視する
if sim <= 0:
continue
for item in dataset[other]:
# まだ所持していないアイテムのスコア
if item not in dataset[person] or dataset[person][item] == 0:
# Similrity * スコア
totals.setdefault(item, 0)
totals[item] += dataset[other][item] * sim
# 類似度の和
simSums.setdefault(item, 0)
simSums[item] += sim
# 正規化されたリストを作成
rankings = [(total / simSums[item], item)
for item, total in list(totals.items())]
rankings.sort()
rankings.reverse()
# 推薦アイテムを返す
recommendataions_list = [
recommend_item for score, recommend_item in rankings]
return recommendataions_list
print("下林さんにおすすめのメニュー",
user_reommendations('下林'))
| [
"[email protected]"
] | |
987121413b17f4207dd02018f8528d8c260df6d6 | e15e3bba52180f86d7769a0b5ffd97f2b640777e | /tests/api-with-examples/api_with_examples/common/types.py | c15e02213215c2af34bb781b04b5fb4c5e3c2adb | [
"MIT"
] | permissive | stjordanis/openapi-client-generator | 06237ab4489c296aec0c3c5d3c811f8c2a310023 | a058af4ec28a1e53809273a662fb8cba0157695e | refs/heads/master | 2023-03-16T10:04:38.122121 | 2021-02-27T22:36:18 | 2021-02-27T22:36:18 | null | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 638 | py | from enum import Enum
from typing import Optional, Sequence, Any, NamedTuple, Mapping, Union, Tuple, Type
import inflection
from typeit import TypeConstructor, flags
generate_constructor_and_serializer = TypeConstructor
class AttrStyle(Enum):
CAMELIZED = "camelized"
DASHERIZED = "dasherized"
UNDERSCORED = "underscored"
camelized = TypeConstructor & flags.GlobalNameOverride(
lambda x: inflection.camelize(x, uppercase_first_letter=False)
)
dasherized = TypeConstructor & flags.GlobalNameOverride(inflection.dasherize)
underscored = TypeConstructor
AttrOverrides = Mapping[Union[property, Tuple[Type, str]], str]
| [
"[email protected]"
] | |
58a7b1b4074ce5b68a3fb001fdc46c305921fcfd | 04e26128954d47f4937168d569f800f12cef686d | /gnuradio/python/bitErrorRate.py | 744934e74420d9dd4e07ffc434c01ffb83ae4e8f | [] | no_license | franchenstein/tcc | 02ed9f2666823610c0d025c4b64960813a227bc3 | b2ec6c2206628672edf004f09c09b68d115bf436 | refs/heads/master | 2021-01-13T12:56:30.315840 | 2015-02-10T10:22:34 | 2015-02-10T10:22:34 | 18,018,315 | 2 | 0 | null | null | null | null | UTF-8 | Python | false | false | 3,090 | py | #!/usr/bin/env python
##################################################
# Gnuradio Python Flow Graph
# Title: Bit Error Rate
# Author: Daniel Franch
# Description: Calculates the BER based on the known original message and the final received message.
# Generated: Fri Aug 1 12:30:06 2014
##################################################
from gnuradio import blocks
from gnuradio import gr
from gnuradio.filter import firdes
import ConfigParser
class bitErrorRate(gr.hier_block2):
def __init__(self):
gr.hier_block2.__init__(
self, "Bit Error Rate",
gr.io_signaturev(2, 2, [gr.sizeof_char*1, gr.sizeof_char*1]),
gr.io_signature(1, 1, gr.sizeof_float*1),
)
##################################################
# Variables
##################################################
self._msgLength_config = ConfigParser.ConfigParser()
self._msgLength_config.read("./configs/sdrConfig.txt")
try: msgLength = self._msgLength_config.getint("main", "key")
except: msgLength = 10000
self.msgLength = msgLength
self._bits_per_byte_config = ConfigParser.ConfigParser()
self._bits_per_byte_config.read("./configs/sdrConfig.txt")
try: bits_per_byte = self._bits_per_byte_config.getint("main", "key")
except: bits_per_byte = 8
self.bits_per_byte = bits_per_byte
intdecim = 100000
if msgLength < intdecim:
intdecim = msgLength
##################################################
# Blocks
##################################################
self.blocks_xor_xx_0 = blocks.xor_bb()
self.blocks_unpack_k_bits_bb_0 = blocks.unpack_k_bits_bb(bits_per_byte)
self.blocks_uchar_to_float_0 = blocks.uchar_to_float()
self.blocks_multiply_const_vxx_0 = blocks.multiply_const_vff((1.0/msgLength, ))
self.blocks_integrate_xx_0 = blocks.integrate_ff(intdecim)
##################################################
# Connections
##################################################
self.connect((self.blocks_integrate_xx_0, 0), (self.blocks_multiply_const_vxx_0, 0))
self.connect((self, 1), (self.blocks_xor_xx_0, 1))
self.connect((self, 0), (self.blocks_xor_xx_0, 0))
self.connect((self.blocks_multiply_const_vxx_0, 0), (self, 0))
self.connect((self.blocks_xor_xx_0, 0), (self.blocks_unpack_k_bits_bb_0, 0))
self.connect((self.blocks_unpack_k_bits_bb_0, 0), (self.blocks_uchar_to_float_0, 0))
self.connect((self.blocks_uchar_to_float_0, 0), (self.blocks_integrate_xx_0, 0))
# QT sink close method reimplementation
def get_msgLength(self):
return self.msgLength
def set_msgLength(self, msgLength):
self.msgLength = msgLength
self.blocks_multiply_const_vxx_0.set_k((1.0/self.msgLength, ))
def get_bits_per_byte(self):
return self.bits_per_byte
def set_bits_per_byte(self, bits_per_byte):
self.bits_per_byte = bits_per_byte
| [
"ubuntu@ubuntu.(none)"
] | ubuntu@ubuntu.(none) |
86ffd25edee54a08e13df6afc30a3a3348a9b725 | 6bd3ad4389995d6acd5870a8a010d657d5a91b4c | /src/adminactions/templatetags/aa_compat.py | e3f6ace17242bea3bf45ce0154899e8a7fa1961b | [
"LicenseRef-scancode-warranty-disclaimer",
"MIT"
] | permissive | timgates42/django-adminactions | aa0fa47812c8518ad0a996cac1b52eecc8e47ffb | af19dc557811e148b8f74d2a6effcf64afc8e0df | refs/heads/master | 2023-03-16T12:03:40.024049 | 2022-06-26T16:35:03 | 2022-06-26T16:35:03 | 249,811,327 | 0 | 0 | NOASSERTION | 2020-03-24T20:31:02 | 2020-03-24T20:31:01 | null | UTF-8 | Python | false | false | 185 | py | from django.template import Library
register = Library()
@register.tag
def url(parser, token):
from django.template.defaulttags import url as _url
return _url(parser, token)
| [
"[email protected]"
] | |
d853928d83b1bb7774836966374126863002bfec | 02e23da0431623db86c8138bda350a1d526d4185 | /Archivos Python Documentos/Graficas/.history/tierras_20200222162818.py | 074ccb95c2262981a0f5e2bffc88e7ea5bad045c | [] | no_license | Jaamunozr/Archivos-python | d9996d3d10ff8429cd1b4c2b396016a3a5482889 | 1f0af9ba08f12ac27e111fcceed49bbcf3b39657 | refs/heads/master | 2022-08-05T14:49:45.178561 | 2022-07-13T13:44:39 | 2022-07-13T13:44:39 | 244,073,267 | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 2,036 | py | import os
import pylab as pl
from mpl_toolkits.mplot3d import Axes3D
import matplotlib.pyplot as plt
from matplotlib import cm
from matplotlib.ticker import LinearLocator, FormatStrFormatter
import numpy as np
os.system("clear")
fig = pl.figure()
axx = Axes3D(fig)
raiz=np.sqrt
ln=np.log
X = np.arange(-2, 12, 1)
Y = np.arange(-2, 12, 1)
#X, Y = np.meshgrid(X, Y)
print (np.count_nonzero(X))
l = 2
rho= 100
ik=25
Electrodos=8
E=Electrodos-1
P=np.array([
[0.55, 0.55], #Posicion electrodo A
[4.55, 0.55], #Posicion electrodo B
[8.55, 0.55], #Posicion electrodo C
[0.55, 4.55], #Posicion electrodo D
[8.55, 4.55], #Posicion electrodo E
[0.55, 8.55], #Posicion electrodo F
[4.55, 8.55], #Posicion electrodo G
[8.55, 8.55] #Posicion electrodo H
])
m=np.zeros((Electrodos,0))
V=np.zeros((Electrodos,0))
print(V)
i=0
t=0
while t<=np.count_nonzero(X):
while i<=E:
m[i][0] =raiz((14-(P[i][0]))**2+(14-(P[i][1]))**2)
V[i][0] =ln((l+raiz((m[i][0])**2+l**2))/(m[i][0]))
i += 1
print (V)
print (E)
"""
ma=raiz((X-ax)**2+(Y-ay)**2)
mb=raiz((X-bx)**2+(Y-by)**2)
mc=raiz((X-cx)**2+(Y-cy)**2)
md=raiz((X-dx)**2+(Y-dy)**2)
me=raiz((X-ex)**2+(Y-ey)**2)
mf=raiz((X-fx)**2+(Y-fy)**2)
mg=raiz((X-gx)**2+(Y-gy)**2)
mh=raiz((X-hx)**2+(Y-hy)**2)
va=ln((l+raiz(ma**2+l**2))/ma)
vb=ln((l+raiz(mb**2+l**2))/mb)
vc=ln((l+raiz(mc**2+l**2))/mc)
vd=ln((l+raiz(md**2+l**2))/md)
ve=ln((l+raiz(me**2+l**2))/me)
vf=ln((l+raiz(mf**2+l**2))/mf)
vg=ln((l+raiz(mg**2+l**2))/mg)
vh=ln((l+raiz(mh**2+l**2))/mh)
Vt=((rho*ik)/(2*np.pi))*(va+vb+vc+vd+ve+vf+vg+vh)
print (Vt[::].max())
#print(Vt)
x = X.flatten()
y = Y.flatten()
z = Vt.flatten()
surf = axx.plot_surface(X, Y, Vt, cmap = cm.coolwarm, linewidth=0, antialiased=False)
# Customize the z axis.
axx.set_zlim(300, 3000)
axx.zaxis.set_major_locator(LinearLocator(10))
axx.zaxis.set_major_formatter(FormatStrFormatter('%.02f'))
# Add a color bar which maps values to colors.
fig.colorbar(surf, shrink=0.5, aspect=5)
plt.show()
""" | [
"[email protected]"
] | |
56af12c570c20f68f2ed9f868404b19006bdf490 | 70e970ce9ec131449b0888388f65f0bb55f098cd | /ClosureTests/test/localConfig_2016DEFGH_Tau.py | cbb6b9333a4223c9dcec00481c778ed32476b89d | [] | no_license | OSU-CMS/DisappTrks | 53b790cc05cc8fe3a9f7fbd097284c5663e1421d | 1d1c076863a9f8dbd3f0c077d5821a8333fc5196 | refs/heads/master | 2023-09-03T15:10:16.269126 | 2023-05-25T18:37:40 | 2023-05-25T18:37:40 | 13,272,469 | 5 | 12 | null | 2023-09-13T12:15:49 | 2013-10-02T13:58:51 | Python | UTF-8 | Python | false | false | 503 | py | from DisappTrks.StandardAnalysis.localConfig import *
config_file = "config_2016DEFGH_cfg.py"
intLumi = lumi["HLT_LooseIsoPFTau50_Trk30_eta2p1_v*"]["Tau_2016DEFGH"]
datasetsData = [
'Tau_2016D',
'Tau_2016E',
'Tau_2016F',
'Tau_2016G',
'Tau_2016H',
]
datasets = datasetsBkgd + datasetsData + datasetsSig
#setNJobs (datasets, composite_dataset_definitions, nJobs, 500)
#setDatasetType (datasets, composite_dataset_definitions, types, "bgMC")
#InputCondorArguments["hold"] = "True"
| [
"[email protected]"
] | |
956f70049baed530b16840b562c15c44f1075815 | 619f28995e61afc6277c6b1ad8a19d08f948bbd9 | /CrashCourseInPython/test_name_function.py | c1e18007364f282be06666ff19699ae17252873e | [] | no_license | danhagg/python_bits | cb407624d48a52d4fceacd2c4fca762abe3dd1ef | c5844fe464c6e896b1597d95f5a89b2cf66dc605 | refs/heads/master | 2020-03-18T13:16:53.014910 | 2018-09-17T16:26:06 | 2018-09-17T16:26:06 | 134,773,305 | 1 | 0 | null | 2018-07-11T22:23:09 | 2018-05-24T22:03:08 | Python | UTF-8 | Python | false | false | 774 | py | import unittest
from name_function import get_formatted_name
# following class inherits from class unittest.TestCase
class NamesTestCase(unittest.TestCase):
"""Tests for 'name_function.py'."""
# method to verify names with 1st and last formatted correctly
# method must start with "test"
def test_first_last_name(self):
"""Do names like 'Janis Joplin' work?"""
formatted_name = get_formatted_name('janis', 'joplin')
self.assertEqual(formatted_name, 'Janis Joplin')
def test_first_last_middle_name(self):
"""Do names like 'Wolfgnag Amadeus Mozart' work"""
formatted_name = get_formatted_name(
'wolfgang', 'mozart', 'amadeus')
self.assertEqual(formatted_name, 'Wolfgang Amadeus Mozart')
unittest.main()
| [
"[email protected]"
] | |
c5d84ee44df35183938e7658a8aebaef5e4731ad | db575f3401a5e25494e30d98ec915158dd7e529b | /BIO_Stocks/AVEO.py | 2c70d486a632cd0540110768b8144b09fb08d86a | [] | no_license | andisc/StockWebScraping | b10453295b4b16f065064db6a1e3bbcba0d62bad | 41db75e941cfccaa7043a53b0e23ba6e5daa958a | refs/heads/main | 2023-08-08T01:33:33.495541 | 2023-07-22T21:41:08 | 2023-07-22T21:41:08 | 355,332,230 | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 2,074 | py | import requests
from lxml import html
from bs4 import BeautifulSoup
import os
from datetime import date, datetime
from ValidationTools import validateday
from Database_Connections import InsertData, Insert_Logging
def main(id_control):
try:
url = 'https://investor.aveooncology.com/press-releases'
headers = {'User-Agent': 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_11_5) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/50.0.2661.102 Safari/537.36'}
result = requests.get(url, headers=headers)
#print(result.content.decode())
html_content = result.content.decode()
soup = BeautifulSoup(html_content, 'html.parser')
#print(soup)
table = soup.find('table', attrs={'class':'nirtable collapse-wide'})
#print(table)
table_body = table.find('tbody')
rows = table_body.find_all('tr')
FIRST_ROW_columns = rows[0].find_all('td')
v_article_date = FIRST_ROW_columns[0].text.lstrip().rstrip()
article_desc = FIRST_ROW_columns[1]
#if the process find any article with the today date
istoday, v_art_date = validateday(v_article_date)
if (istoday == True):
v_ticker = os.path.basename(__file__).replace(".py", "")
v_url = article_desc.a.get('href')
v_description = article_desc.text.lstrip().rstrip()
now = datetime.now()
print("URL: " + v_url)
print("DESCRIPTION: " + v_description)
print("ARTICLE_DATE: " + str(now))
# Insert articles
if "https://" in v_url:
InsertData(v_ticker, v_description, v_url, v_art_date)
else:
InsertData(v_ticker, v_description, url, v_art_date)
except Exception:
error_message = "Entrou na excepção ao tratar " + os.path.basename(__file__) + "..."
print(error_message)
Insert_Logging(id_control, 'Detail', error_message)
pass
if __name__ == "__main__":
main()
| [
"[email protected]"
] | |
0f189006b7427ff0c47c6218323a7613f0be1eea | 6aee8ef9efcc43a611d1f6d8ebc9ba5c9234d0c7 | /xml/sample1.py | 7f3bb35ab48bcab97514ea1ba485832420509784 | [] | no_license | huython/python_tutorialspoint | 276bbaba341229d4c2f1b71a4865b8bd7e50b72b | dff9e0e53c68403af034a98ba299d75588481293 | refs/heads/master | 2020-03-29T15:35:29.202894 | 2018-09-24T08:02:43 | 2018-09-24T08:02:43 | 150,071,077 | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 1,999 | py | #!/usr/bin/python
import xml.sax
class MovieHandler( xml.sax.ContentHandler ):
def __init__(self):
self.CurrentData = ""
self.type = ""
self.format = ""
self.year = ""
self.rating = ""
self.stars = ""
self.description = ""
# Call when an element starts
def startElement(self, tag, attributes):
self.CurrentData = tag
if tag == "movie":
print("*****Movie*****")
title = attributes["title"]
print("Title:", title)
# Call when an elements ends
def endElement(self, tag):
if self.CurrentData == "type":
print("Type:", self.type)
elif self.CurrentData == "format":
print("Format:", self.format)
elif self.CurrentData == "year":
print("Year:", self.year)
elif self.CurrentData == "rating":
print("Rating:", self.rating)
elif self.CurrentData == "stars":
print("Stars:", self.stars)
elif self.CurrentData == "description":
print("Description:", self.description)
self.CurrentData = ""
# Call when a character is read
def characters(self, content):
if self.CurrentData == "type":
self.type = content
elif self.CurrentData == "format":
self.format = content
elif self.CurrentData == "year":
self.year = content
elif self.CurrentData == "rating":
self.rating = content
elif self.CurrentData == "stars":
self.stars = content
elif self.CurrentData == "description":
self.description = content
if ( __name__ == "__main__"):
# create an XMLReader
parser = xml.sax.make_parser()
# turn off namepsaces
parser.setFeature(xml.sax.handler.feature_namespaces, 0)
# override the default ContextHandler
Handler = MovieHandler()
parser.setContentHandler( Handler )
parser.parse("./xml/movies.xml") | [
"[email protected]"
] | |
43524050673b775d0d91efafd58f41dfb3e062a8 | b6d8570a6ad4891858f475481bd2b7faa9db3df6 | /avg bg.py | da5c282b8c462e864eea2da5d1d0b73d43ed4f82 | [] | no_license | Mayank-Bhatt-450/mpl-can-jump-bot | 9c0738f4a9395ecdc3cf61960cac586141ced723 | 1d13bf1fd49e7455c15dbf97d2f28b3882ea5660 | refs/heads/main | 2022-12-26T01:47:40.504723 | 2020-10-07T14:44:41 | 2020-10-07T14:44:41 | 302,066,853 | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 1,385 | py | import pyautogui,time
from PIL import Image
import math,PIL
'''
img = pyautogui.screenshot()
img.save('new.jpg')
k=time.time()'''
#8 100
u=[0,0,0]
l=[112,194,127]
def dis(pt1,pt2=(2,35,47)):
#pt1=[170,10,154]
#pt2=(145,35,43)#(145,144,143)#(145,35,43)
distance=math.sqrt(((pt1[0]-pt2[0])**2)+((pt1[1]-pt2[1])**2)+((pt1[2]-pt2[2])**2))
return(distance)
img = Image.open("000.png")#PIL.ImageGrab.grab()#
distance=[]
no=[(254, 231, 94), (254, 208, 100), (254, 186, 108), (254, 163, 115), (254, 147, 119), (254, 117, 129), (254, 94, 135), (254, 71, 143)]
h=0
for y in range(100,900,100):
print(y)
g=[]
k=0
pix=[0,0,0]
pixno=0
for i in range(100):
for x in range(497,505):#,943):
if y>800:
print(x,y+i)
d=img.getpixel((x,y+i))
#print(d)
if d[1]>10 and d[0]>10:#dis(d,[170,10,154])>10 and
pixno+=1
pix[0]+=d[0]
pix[1]+=d[1]
pix[2]+=d[2]
fr=dis(d,no[h])
if k<fr :
k=fr
print(d,',')
distance.append(k)
#no.append((round(pix[0]/pixno),round(pix[1]/pixno),round(pix[2]/pixno)))
#print(k,pix[0],pixno,pix[1],pixno,pix[2],pixno)
print(k,pix[0]/pixno,pix[1]/pixno,pix[2]/pixno)
h+=1
print (no)
print (distance)
| [
"[email protected]"
] | |
ee65724f760436a1ddd06deee521690fd06da96f | 906579c9bb9330d0b35644f2cd45f7cd53881234 | /test.py | 968e828b5fcb6089889c756cd9cf3e2128580fb9 | [] | no_license | albert100121/Stereo-LiDAR-CCVNorm | cda767518684ff769c2c4507bed58fe5431ad152 | c40b09e08c6416ad9f7959aec8ed1160ca216bec | refs/heads/master | 2020-09-05T19:50:33.806036 | 2019-06-21T20:49:33 | 2019-06-21T20:49:33 | null | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 6,615 | py | """
Testing process.
Usage:
# For KITTI Depth Completion
>> python test.py --model_cfg exp/test/test_options.py --model_path exp/test/ckpt/\[ep-00\]giter-0.ckpt \
--dataset kitti2017 --rgb_dir ./data/kitti2017/rgb --depth_dir ./data/kitti2015/depth
# For KITTI Stereo
>> python test.py --model_cfg exp/test/test_options.py --model_path exp/test/ckpt/\[ep-00\]giter-0.ckpt \
--dataset kitti2015 --root_dir ./data/kitti_stereo/data_scene_flow
"""
import os
import sys
import time
import argparse
import importlib
import random
import numpy as np
from tqdm import tqdm
import torch
from torch.utils.data import DataLoader
import torch.backends.cudnn as cudnn
from misc import utils
from misc import metric
from dataset.dataset_kitti2017 import DatasetKITTI2017
from dataset.dataset_kitti2015 import DatasetKITTI2015
DISP_METRIC_FIELD = ['err_3px', 'err_2px', 'err_1px', 'rmse', 'mae']
DEPTH_METRIC_FIELD = ['rmse', 'mae', 'mre', 'irmse', 'imae']
SEED = 100
random.seed(SEED)
np.random.seed(seed=SEED)
cudnn.deterministic = True
cudnn.benchmark = False
torch.manual_seed(SEED)
torch.cuda.manual_seed_all(SEED)
def parse_arg():
parser = argparse.ArgumentParser(description='Sparse-Depth-Stereo testing')
parser.add_argument('--model_cfg', dest='model_cfg', type=str, default=None,
help='Configuration file (options.py) of the trained model.')
parser.add_argument('--model_path', dest='model_path', type=str, default=None,
help='Path to weight of the trained model.')
parser.add_argument('--dataset', dest='dataset', type=str, default='kitti2017',
help='Dataset used: kitti2015 / kitti2017')
parser.add_argument('--rgb_dir', dest='rgb_dir', type=str, default='./data/kitti2017/rgb',
help='Directory of RGB data for kitti2017.')
parser.add_argument('--depth_dir', dest='depth_dir', type=str, default='./data/kitti2017/depth',
help='Directory of depth data for kitti2015.')
parser.add_argument('--root_dir', dest='root_dir', type=str, default='./data/kitti_stereo/data_scene_flow',
help='Root directory for kitti2015')
parser.add_argument('--random_sampling', dest='random_sampling', type=float, default=None,
help='Perform random sampling on ground truth to obtain sparse disparity map; Only used in kitti2015')
parser.add_argument('--no_cuda', dest='no_cuda', action='store_true',
help='Don\'t use gpu')
parser.set_defaults(no_cuda=False)
args = parser.parse_args()
return args
def main():
# Parse arguments
args = parse_arg()
# Import configuration file
sys.path.append('/'.join((args.model_cfg).split('/')[:-1]))
options = importlib.import_module(((args.model_cfg).split('/')[-1]).split('.')[0])
cfg = options.get_config()
# Define model and load
model = options.get_model(cfg.model_name)
if not args.no_cuda:
model = model.cuda()
train_ep, train_step = utils.load_checkpoint(model, None, None, args.model_path, True)
# Define testing dataset (NOTE: currently using validation set)
if args.dataset == 'kitti2017':
dataset = DatasetKITTI2017(args.rgb_dir, args.depth_dir, 'my_test',
(256, 1216), to_disparity=cfg.to_disparity, # NOTE: set image size to 256x1216
fix_random_seed=True)
elif args.dataset == 'kitti2015':
dataset = DatasetKITTI2015(args.root_dir, 'training', (352, 1216), # NOTE: set image size to 352x1216
args.random_sampling, fix_random_seed=True)
loader = DataLoader(dataset, batch_size=1, shuffle=False, pin_memory=True,
num_workers=4)
# Perform testing
model.eval()
pbar = tqdm(loader)
pbar.set_description('Testing')
disp_meters = metric.Metrics(DISP_METRIC_FIELD)
disp_avg_meters = metric.MovingAverageEstimator(DISP_METRIC_FIELD)
depth_meters = metric.Metrics(DEPTH_METRIC_FIELD)
depth_avg_meters = metric.MovingAverageEstimator(DEPTH_METRIC_FIELD)
infer_time = 0
with torch.no_grad():
for it, data in enumerate(pbar):
# Pack data
if not args.no_cuda:
for k in data.keys():
data[k] = data[k].cuda()
inputs = dict()
inputs['left_rgb'] = data['left_rgb']
inputs['right_rgb'] = data['right_rgb']
if cfg.to_disparity:
inputs['left_sd'] = data['left_sdisp']
inputs['right_sd'] = data['right_sdisp']
else:
inputs['left_sd'] = data['left_sd']
inputs['right_sd'] = data['right_sd']
if args.dataset == 'kitti2017':
target_d = data['left_d']
target_disp = data['left_disp']
img_w = data['width'].item()
# Inference
end = time.time()
pred = model(inputs)
if cfg.to_disparity:
pred_d = utils.disp2depth(pred, img_w)
pred_disp = pred
else:
raise NotImplementedError
infer_time += (time.time() - end)
# Measure performance
if cfg.to_disparity:
# disparity
pred_disp_np = pred_disp.data.cpu().numpy()
target_disp_np = target_disp.data.cpu().numpy()
disp_results = disp_meters.compute(pred_disp_np, target_disp_np)
disp_avg_meters.update(disp_results)
if args.dataset == 'kitti2017':
# depth
pred_d_np = pred_d.data.cpu().numpy()
target_d_np = target_d.data.cpu().numpy()
depth_results = depth_meters.compute(pred_d_np, target_d_np)
depth_avg_meters.update(depth_results)
else:
raise NotImplementedError
infer_time /= len(loader)
if cfg.to_disparity:
disp_avg_results = disp_avg_meters.compute()
print('Disparity metric:')
for key, val in disp_avg_results.items():
print('- {}: {}'.format(key, val))
if args.dataset == 'kitti2017':
depth_avg_results = depth_avg_meters.compute()
print('Depth metric:')
for key, val in depth_avg_results.items():
print('- {}: {}'.format(key, val))
print('Average infer time: {}'.format(infer_time))
if __name__ == '__main__':
main()
| [
"[email protected]"
] | |
73b312b68b541356d85fb0d14bea0e3ef11466ee | d7c9e5b45128c06997358987c8563fba1387c483 | /Modules/SortingLists.py | bbae23b5e4c47d487e64d78f3928e61214747808 | [] | no_license | Shadow073180/pythonPractice | 1ed389d448d82c91e796951f15c5ce81fbedb73e | 52d4f77109b0ffdaf8eab8094fe90b0dbab5a595 | refs/heads/main | 2023-03-28T06:01:00.090517 | 2021-03-17T19:56:58 | 2021-03-17T19:56:58 | 348,491,204 | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 324 | py |
# Given a list with pairs, sort on the first element.
def sort_list_with_pairs_on_first_element(collection):
collection.sort(key=lambda x:x[0])
print(collection)
# Now sort on the second element
def sort_list_with_pairs_on_second_element(collection):
collection.sort(key=lambda x: x[1])
print(collection) | [
"[email protected]"
] | |
8519415c25b3fb42b6fabb878d849032a11561a9 | de24f83a5e3768a2638ebcf13cbe717e75740168 | /moodledata/vpl_data/131/usersdata/260/38306/submittedfiles/al10.py | cf5bced616d8a83beddc4f52cebb3f6fea0b85b8 | [] | 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 | 278 | py | # -*- coding: utf-8 -*-
#NÃO APAGUE A LINHA ACIMA. COMECE ABAIXO DESTA LINHA
n=int(input("digite o número de termos desejado:"))
produto=1
for i in range (1,n+1,2):
if n%2 == 0
produto=produto*((i)/(i+1))
else
produto=produto*((i+1)/(i))
print(produto) | [
"[email protected]"
] | |
b422f5580abaf8f49648efea46f5591864331eb3 | e262e64415335060868e9f7f73ab8701e3be2f7b | /.history/pyexcel_20201111161453.py | 9ea777441d71ece291b7eaecf8bd2f954d7a1fdc | [] | no_license | Allison001/developer_test | 6e211f1e2bd4287ee26fd2b33baf1c6a8d80fc63 | b8e04b4b248b0c10a35e93128a5323165990052c | refs/heads/master | 2023-06-18T08:46:40.202383 | 2021-07-23T03:31:54 | 2021-07-23T03:31:54 | 322,807,303 | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 777 | py | from openpyxl import Workbook
from openpyxl.utils import get_column_letter
wb = Workbook()
dest_filename = 'empty_book.xlsx'
ws1 = wb.active
ws1.title = "range names"
for row in range(1, 40):
ws1.append(range(600))
ws2 = wb.create_sheet(title="Pi")
ws2['F5'] = 3.14
ws3 = wb.create_sheet(title="Data")
for row in range(10, 20):
for col in range(27, 54):
_ = ws3.cell(column=col, row=row, value="{0}".format(get_column_letter(col)))
print(ws3['AA10'].value)
ws4 = wb.create_sheet(title="test")
title1 = ("用例编号","用例模块","用例标题","用例级别","测试环境","测试输入","执行操作","预期结果","验证结果","备注")
for i in range(1,11):
ws4.cell(column=i,row=1).value="用例编号"
wb.save(filename = dest_filename) | [
"[email protected]"
] | |
ab888ea5d10530619540dd87dcd6a094a9ab20c1 | 8b957ec62991c367dfc6c9247ada90860077b457 | /test/functional/p2p_invalid_block.py | 5d51372d2d6595212073953a66767b2570a5c199 | [
"MIT"
] | permissive | valuero-org/valuero | 113f29046bd63c8b93160604452a99ed51367942 | c0a8d40d377c39792e5a79d4a67f00bc592aef87 | refs/heads/master | 2020-05-24T17:44:46.409378 | 2019-09-09T10:18:59 | 2019-09-09T10:18:59 | 187,392,499 | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 4,470 | py | #!/usr/bin/env python3
# Copyright (c) 2018-2019 The Bitcoin Core developers
# Copyright (c) 2017-2019 The Raven Core developers
# Copyright (c) 2018-2019 The Rito Core developers
# Copyright (c) 2019 The Valuero developers
# Distributed under the MIT software license, see the accompanying
# file COPYING or http://www.opensource.org/licenses/mit-license.php.
"""Test node responses to invalid blocks.
In this test we connect to one node over p2p, and test block requests:
1) Valid blocks should be requested and become chain tip.
2) Invalid block with duplicated transaction should be re-requested.
3) Invalid block with bad coinbase value should be rejected and not
re-requested.
"""
from test_framework.test_framework import ComparisonTestFramework
from test_framework.util import *
from test_framework.comptool import TestManager, TestInstance, RejectResult
from test_framework.blocktools import *
import copy
import time
# Use the ComparisonTestFramework with 1 node: only use --testbinary.
class InvalidBlockRequestTest(ComparisonTestFramework):
''' Can either run this test as 1 node with expected answers, or two and compare them.
Change the "outcome" variable from each TestInstance object to only do the comparison. '''
def set_test_params(self):
self.num_nodes = 1
self.setup_clean_chain = True
def run_test(self):
test = TestManager(self, self.options.tmpdir)
test.add_all_connections(self.nodes)
self.tip = None
self.block_time = None
NetworkThread().start() # Start up network handling in another thread
test.run()
def get_tests(self):
if self.tip is None:
self.tip = int("0x" + self.nodes[0].getbestblockhash(), 0)
self.block_time = int(time.time())+1
'''
Create a new block with an anyone-can-spend coinbase
'''
height = 1
block = create_block(self.tip, create_coinbase(height), self.block_time)
self.block_time += 1
block.solve()
# Save the coinbase for later
self.block1 = block
self.tip = block.sha256
height += 1
yield TestInstance([[block, True]])
'''
Now we need that block to mature so we can spend the coinbase.
'''
test = TestInstance(sync_every_block=False)
for i in range(100):
block = create_block(self.tip, create_coinbase(height), self.block_time)
block.solve()
self.tip = block.sha256
self.block_time += 1
test.blocks_and_transactions.append([block, True])
height += 1
yield test
'''
Now we use merkle-root malleability to generate an invalid block with
same blockheader.
Manufacture a block with 3 transactions (coinbase, spend of prior
coinbase, spend of that spend). Duplicate the 3rd transaction to
leave merkle root and blockheader unchanged but invalidate the block.
'''
block2 = create_block(self.tip, create_coinbase(height), self.block_time)
self.block_time += 1
# b'0x51' is OP_TRUE
tx1 = create_transaction(self.block1.vtx[0], 0, b'\x51', 5000 * COIN)
tx2 = create_transaction(tx1, 0, b'\x51', 5000 * COIN)
block2.vtx.extend([tx1, tx2])
block2.hashMerkleRoot = block2.calc_merkle_root()
block2.rehash()
block2.solve()
orig_hash = block2.sha256
block2_orig = copy.deepcopy(block2)
# Mutate block 2
block2.vtx.append(tx2)
assert_equal(block2.hashMerkleRoot, block2.calc_merkle_root())
assert_equal(orig_hash, block2.rehash())
assert(block2_orig.vtx != block2.vtx)
self.tip = block2.sha256
yield TestInstance([[block2, RejectResult(16, b'bad-txns-duplicate')], [block2_orig, True]])
height += 1
'''
Make sure that a totally screwed up block is not valid.
'''
block3 = create_block(self.tip, create_coinbase(height), self.block_time)
self.block_time += 1
block3.vtx[0].vout[0].nValue = 100 * COIN # Too high!
block3.vtx[0].sha256=None
block3.vtx[0].calc_sha256()
block3.hashMerkleRoot = block3.calc_merkle_root()
block3.rehash()
block3.solve()
yield TestInstance([[block3, RejectResult(16, b'bad-cb-amount')]])
if __name__ == '__main__':
InvalidBlockRequestTest().main()
| [
"[email protected]"
] | |
9eb08f431cf298b8b27f7172649332e4b16c0adf | e1c5b001b7031d1ff204d4b7931a85366dd0ce9c | /tW/plot_noNvtx/input_plot.py | 165ac1fe02f2853f312ff113bcbe0a9783810261 | [] | no_license | fdzyffff/IIHE_code | b9ff96b5ee854215e88aec43934368af11a1f45d | e93a84777afad69a7e63a694393dca59b01c070b | refs/heads/master | 2020-12-30T16:03:39.237693 | 2020-07-13T03:06:53 | 2020-07-13T03:06:53 | 90,961,889 | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 30,738 | py | import sys
try:
sys.path.append("C:/root_v5.34.30/bin")
except:
pass
import ROOT
import time
from math import *
from array import array
import os
isUpdate = True
isUpdate = False
#~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
def getP4(pt, eta, phi, isE, isMu):
p4 = ROOT.TLorentzVector()
if isE:
p4.SetPtEtaPhiM(pt,eta,phi,0.000511)
else:
p4.SetPtEtaPhiM(pt,eta,phi,0.10566)
return p4
def getbinwidth(x,x1):
for i in range(len(x1)):
if x < x1[i] and i>0:
return (x1[i]-x1[i-1])
elif x < x1[i]:
return -1.0
return -1.0
def map_value(path, event, h1, tmp_value_dic, event_weight_factor):
bin_weight = 1.0
pi = 3.1415926
if path == "new_leading_pt" or path == "new_sub_leading_pt":
for value in tmp_value_dic:
exec 'passed = (%s)'%(tmp_value_dic[value])
if not passed: continue
if getattr(event,value) < 149:
h1.Fill(getattr(event,value),event_weight_factor)
else:
h1.Fill(149,event_weight_factor)
elif path == "new_M_ll":
for value in tmp_value_dic:
exec 'passed = (%s)'%(tmp_value_dic[value])
if not passed: continue
if getattr(event,value) < 299:
h1.Fill(getattr(event,value),event_weight_factor)
else:
h1.Fill(299,event_weight_factor)
elif path == "Pt_ll":
tmp_leading_p4 = getP4(getattr(event,"leading_pt"),getattr(event,"leading_eta"),getattr(event,"leading_phi"),getattr(event,"leading_isE"),getattr(event,"leading_isMu"))
tmp_subleading_p4 = getP4(getattr(event,"sub_leading_pt"),getattr(event,"sub_leading_eta"),getattr(event,"sub_leading_phi"),getattr(event,"sub_leading_isE"),getattr(event,"sub_leading_isMu"))
tmp_pt = (tmp_leading_p4 + tmp_subleading_p4).Pt()
#print tmp_pt
if tmp_pt < 259:
h1.Fill(tmp_pt,event_weight_factor)
else:
h1.Fill(259,event_weight_factor)
elif path == "phi_ll":
tmp_leading_p4 = getP4(getattr(event,"leading_pt"),getattr(event,"leading_eta"),getattr(event,"leading_phi"),getattr(event,"leading_isE"),getattr(event,"leading_isMu"))
tmp_subleading_p4 = getP4(getattr(event,"sub_leading_pt"),getattr(event,"sub_leading_eta"),getattr(event,"sub_leading_phi"),getattr(event,"sub_leading_isE"),getattr(event,"sub_leading_isMu"))
tmp_phi = (tmp_leading_p4 + tmp_subleading_p4).Phi()
h1.Fill(tmp_phi,event_weight_factor)
elif path == "deltaR_ll":
tmp_leading_p4 = getP4(getattr(event,"leading_pt"),getattr(event,"leading_eta"),getattr(event,"leading_phi"),getattr(event,"leading_isE"),getattr(event,"leading_isMu"))
tmp_subleading_p4 = getP4(getattr(event,"sub_leading_pt"),getattr(event,"sub_leading_eta"),getattr(event,"sub_leading_phi"),getattr(event,"sub_leading_isE"),getattr(event,"sub_leading_isMu"))
tmp_dR = tmp_leading_p4.DeltaR(tmp_subleading_p4)
h1.Fill(tmp_dR,event_weight_factor)
elif path == "rapidity_ll":
tmp_leading_p4 = getP4(getattr(event,"leading_pt"),getattr(event,"leading_eta"),getattr(event,"leading_phi"),getattr(event,"leading_isE"),getattr(event,"leading_isMu"))
tmp_subleading_p4 = getP4(getattr(event,"sub_leading_pt"),getattr(event,"sub_leading_eta"),getattr(event,"sub_leading_phi"),getattr(event,"sub_leading_isE"),getattr(event,"sub_leading_isMu"))
tmp_rapidity = (tmp_leading_p4 + tmp_subleading_p4).Rapidity()
h1.Fill(tmp_rapidity,event_weight_factor)
elif path == "Z_MET_delta_phi":
tmp_leading_p4 = getP4(getattr(event,"leading_pt"),getattr(event,"leading_eta"),getattr(event,"leading_phi"),getattr(event,"leading_isE"),getattr(event,"leading_isMu"))
tmp_subleading_p4 = getP4(getattr(event,"sub_leading_pt"),getattr(event,"sub_leading_eta"),getattr(event,"sub_leading_phi"),getattr(event,"sub_leading_isE"),getattr(event,"sub_leading_isMu"))
tmp_phi = (tmp_leading_p4 + tmp_subleading_p4).Phi()
delta_phi = fabs(tmp_phi - getattr(event,"MET_phi"))
if delta_phi > pi:delta_phi = 2*pi - delta_phi
h1.Fill(fabs(delta_phi),event_weight_factor)
elif path == "Z_MET_T1Txy_delta_phi":
tmp_leading_p4 = getP4(getattr(event,"leading_pt"),getattr(event,"leading_eta"),getattr(event,"leading_phi"),getattr(event,"leading_isE"),getattr(event,"leading_isMu"))
tmp_subleading_p4 = getP4(getattr(event,"sub_leading_pt"),getattr(event,"sub_leading_eta"),getattr(event,"sub_leading_phi"),getattr(event,"sub_leading_isE"),getattr(event,"sub_leading_isMu"))
tmp_phi = (tmp_leading_p4 + tmp_subleading_p4).Phi()
delta_phi = fabs(tmp_phi - getattr(event,"MET_T1Txy_phi"))
if delta_phi > pi:delta_phi = 2*pi - delta_phi
h1.Fill(fabs(delta_phi),event_weight_factor)
elif path == "n_jet_bjet":
n_jet = getattr(event,"n_jet")
n_bjet = getattr(event,"n_bjet")
if n_jet <=4:
h1.Fill(n_jet_bjet_dic["(%s,%s)"%(n_jet,n_bjet)][0],event_weight_factor)
else:
h1.Fill(n_jet_bjet_dic["(>4,n)"][0],event_weight_factor)
elif path == "n_bjet2":
tmp_n_bjet = 0
jet_pt_vector = getattr(event,"jet_pt")
jet_eta_vector = getattr(event,"jet_eta")
jet_ID_vector = getattr(event,"jet_IDLoose")
jet_CSVv2_vector = getattr(event,"jet_CSVv2")
for i in range(len(jet_pt_vector)):
if jet_pt_vector[i] > 20 and jet_pt_vector[i] < 30 and fabs(jet_eta_vector[i])<2.4 and jet_ID_vector[i] and jet_CSVv2_vector[i] > 0.8484:
tmp_n_bjet += 1
h1.Fill(tmp_n_bjet,event_weight_factor)
elif path == "n_fjet1":
tmp_n_fjet = 0
jet_pt_vector = getattr(event,"jet_pt")
jet_eta_vector = getattr(event,"jet_eta")
jet_ID_vector = getattr(event,"jet_IDLoose")
jet_CSVv2_vector = getattr(event,"jet_CSVv2")
for i in range(len(jet_pt_vector)):
if jet_pt_vector[i] > 30 and fabs(jet_eta_vector[i])>2.4 and fabs(jet_eta_vector[i])<5.2 and jet_ID_vector[i]:
tmp_n_fjet += 1
h1.Fill(tmp_n_fjet,event_weight_factor)
elif path == "n_fjet2":
tmp_n_fjet = 0
jet_pt_vector = getattr(event,"jet_pt")
jet_eta_vector = getattr(event,"jet_eta")
jet_ID_vector = getattr(event,"jet_IDLoose")
jet_CSVv2_vector = getattr(event,"jet_CSVv2")
for i in range(len(jet_pt_vector)):
if jet_pt_vector[i] > 40 and fabs(jet_eta_vector[i])>2.4 and fabs(jet_eta_vector[i])<5.2 and jet_ID_vector[i]:
tmp_n_fjet += 1
h1.Fill(tmp_n_fjet,event_weight_factor)
elif path == "MET_pt_new":
px = getattr(event,"leading_px") + getattr(event,"sub_leading_px") - getattr(event,"leading_2nd_px") - getattr(event,"sub_leading_2nd_px")
py = getattr(event,"leading_py") + getattr(event,"sub_leading_py") - getattr(event,"leading_2nd_py") - getattr(event,"sub_leading_2nd_py")
MET_x = getattr(event,"MET_Et") * cos(getattr(event,"MET_phi")) + px
MET_y = getattr(event,"MET_Et") * sin(getattr(event,"MET_phi")) + py
MET_new = sqrt(MET_x * MET_x + MET_y * MET_y)
h1.Fill(MET_new,event_weight_factor)
elif path == "MET_T1Txy_pt_new":
px = getattr(event,"leading_px") + getattr(event,"sub_leading_px") - getattr(event,"leading_2nd_px") - getattr(event,"sub_leading_2nd_px")
py = getattr(event,"leading_py") + getattr(event,"sub_leading_py") - getattr(event,"leading_2nd_py") - getattr(event,"sub_leading_2nd_py")
MET_x = getattr(event,"MET_T1Txy_Pt") * cos(getattr(event,"MET_T1Txy_phi")) + px
MET_y = getattr(event,"MET_T1Txy_Pt") * sin(getattr(event,"MET_T1Txy_phi")) + py
MET_new = sqrt(MET_x * MET_x + MET_y * MET_y)
h1.Fill(MET_new,event_weight_factor)
elif path == "HT":
tmp_HT = 0
jet_pt_vector = getattr(event,"jet_pt")
jet_eta_vector = getattr(event,"jet_eta")
jet_ID_vector = getattr(event,"jet_IDLoose")
for i in range(len(jet_pt_vector)):
if jet_pt_vector[i] > 30 and fabs(jet_eta_vector[i])<2.4 and jet_ID_vector[i]:
tmp_HT += jet_pt_vector[i]
#if tmp_HT == 0:return
if tmp_HT > 500:
h1.Fill(499,event_weight_factor)
else:
h1.Fill(tmp_HT,event_weight_factor)
elif path == "sys_HT":
tmp_HT = 0
jet_pt_vector = getattr(event,"jet_pt")
jet_eta_vector = getattr(event,"jet_eta")
jet_ID_vector = getattr(event,"jet_IDLoose")
for i in range(len(jet_pt_vector)):
if jet_pt_vector[i] > 30 and fabs(jet_eta_vector[i])<2.4 and jet_ID_vector[i]:
tmp_HT += jet_pt_vector[i]
tmp_HT += getattr(event,"leading_pt") + getattr(event,"sub_leading_pt")
#if tmp_HT == 0:return
if tmp_HT > 500:
h1.Fill(499,event_weight_factor)
else:
h1.Fill(tmp_HT,event_weight_factor)
else:
for value in tmp_value_dic:
exec 'passed = (%s)'%(tmp_value_dic[value])
if not passed: continue
#print "passed"
bin_weight = 1.0
if value_dic[path]["use_array"]:
bin_weight = 1.0/getbinwidth(getattr(event,value),value_dic[path]["hist_para"][1])
total_weight = event_weight_factor * bin_weight
h1.Fill(getattr(event,value),total_weight)
#~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
x_emu_new = array('f')
n_index = 0
x_emu_new.append(50)
for i in range(55,120,5):
x_emu_new.append(i)
n_index += 1
for i in range(120,150,5):
x_emu_new.append(i)
n_index += 1
for i in range(150,200,10):
x_emu_new.append(i)
n_index += 1
for i in range(200,600,20):
x_emu_new.append(i)
n_index += 1
for i in range(600,900,30):
x_emu_new.append(i)
n_index += 1
for i in range(900,1250,50):
x_emu_new.append(i)
n_index += 1
for i in range(1250,1610,60):
x_emu_new.append(i)
n_index += 1
for i in range(1610,1890,70):
x_emu_new.append(i)
n_index += 1
for i in range(1890,3890,80):
x_emu_new.append(i)
n_index += 1
x_emu_new.append(4000)
n_index += 1
#~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
x_emu = array('f')
for i in range(31,64):
x_emu.append(1.14**i)
x_emu2 = array('f')
for i in range(83,166):
x_emu2.append(1.05**i)
x_pt = array('f')
for i in range(34,65):
x_pt.append(1.12**i)
mass_bin = array('f')
mass_bin.append(0)
mass_bin.append(500)
mass_bin.append(1000)
mass_bin.append(1500)
mass_bin.append(2500)
#~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
#{njet, nbjet):[value, ith bin, label]
n_jet_bjet_dic = {
"(0,0)":[0,1,"(0,0)"],
"(1,0)":[1,2,"(1,0)"],
"(1,1)":[2,3,"(1,1)"],
"(2,0)":[3,4,"(2,0)"],
"(2,1)":[4,5,"(2,1)"],
"(2,2)":[5,6,"(2,2)"],
"(3,0)":[6,7,"(3,0)"],
"(3,1)":[7,8,"(3,1)"],
"(3,2)":[8,9,"(3,2)"],
"(3,3)":[9,10,"(3,3)"],
"(4,0)":[10,11,"(4,0)"],
"(4,1)":[11,12,"(4,1)"],
"(4,2)":[12,13,"(4,2)"],
"(4,3)":[13,14,"(4,3)"],
"(4,4)":[14,15,"(4,4)"],
"(>4,n)":[15,16,"(>4,n)"],
}
value_dic={
#'key':[[['branch1 name','branch2 name'],'hist name','hist title','nbin','array of bin','start bin','end bin','min x','max x'],['x label',x label size,'y label',y label size,pad1 legend x drift,y drift],[if x log,if y log, if userdefined x axis][if PU reweighted]],
"M_ll":{
"Data_value_dic":{"M_ll":True},
"MC_value_dic":{"M_ll":True},
"hist_name":"M_ll",
"hist_title":"Invirant mass(Di-lepton)",
"use_array":False,
"PU_reweight":True,
"hist_para":[60,x_emu_new,0,600],
"y_axis":["null","null"],
"x_label":['M_{ll} (GeV/c^{2})',0.1],
"y_label":['Event / 10 GeV',0.05],
"x_log":False,
"y_log":False,
"lenend":{
"useLegend":True,
"position":[],
},
},
"new_M_ll":{
"Data_value_dic":{"M_ll":True},
"MC_value_dic":{"M_ll":True},
"hist_name":"new_M_ll",
"hist_title":"Invirant mass(Di-lepton)",
"use_array":False,
"PU_reweight":True,
"hist_para":[60,x_emu_new,0,300],
"y_axis":["null","null"],
"x_label":['M_{ll} (GeV/c^{2})',0.1],
"y_label":['Event / 5 GeV',0.05],
"x_log":False,
"y_log":False,
"lenend":{
"useLegend":True,
"position":[],
},
},
"M_ll_zmass":{
"Data_value_dic":{"M_ll":True},
"MC_value_dic":{"M_ll":True},
"hist_name":"M_ll_zmass",
"hist_title":"Invirant mass(Di-lepton)",
"use_array":False,
"PU_reweight":True,
"hist_para":[60,x_emu_new,60,120],
"y_axis":["null","null"],
"x_label":['M_{ll} (GeV/c^{2})',0.1],
"y_label":['Event / 1 GeV',0.05],
"x_log":False,
"y_log":False,
"lenend":{
"useLegend":True,
"position":[],
},
},
"Pt_ll":{
"Data_value_dic":{"M_ll":True},
"MC_value_dic":{"M_ll":True},
"hist_name":"Pt_ll",
"hist_title":"Pt (Di-lepton)",
"use_array":False,
"PU_reweight":True,
"hist_para":[48,x_emu_new,20,260],
"y_axis":["null","null"],
"x_label":['P_{T}^{ll} (GeV/c^{2})',0.1],
"y_label":['Event / 5 GeV',0.05],
"x_log":False,
"y_log":False,
"lenend":{
"useLegend":True,
"position":[],
},
},
"phi_ll":{
"Data_value_dic":{"":True},
"MC_value_dic":{"":True},
"hist_name":"phi_ll",
"hist_title":"Pt (Di-lepton)",
"use_array":False,
"PU_reweight":True,
"hist_para":[35,x_emu_new,-3.5,3.5],
"y_axis":["null","null"],
"x_label":['#phi^{ll} ',0.1],
"y_label":['Event / 0.2',0.05],
"x_log":False,
"y_log":False,
"lenend":{
"useLegend":True,
"position":[],
},
},
"deltaR_ll":{
"Data_value_dic":{"":True},
"MC_value_dic":{"":True},
"hist_name":"deltaR_ll",
"hist_title":"Pt (Di-lepton)",
"use_array":False,
"PU_reweight":True,
"hist_para":[120,x_emu_new,0,6],
"y_axis":["null","null"],
"x_label":['#Delta R(l,l)',0.1],
"y_label":['Event / 0.05',0.05],
"x_log":False,
"y_log":False,
"lenend":{
"useLegend":True,
"position":[],
},
},
"rapidity_ll":{
"Data_value_dic":{"":True},
"MC_value_dic":{"":True},
"hist_name":"rapidity_ll",
"hist_title":"Pt (Di-lepton)",
"use_array":False,
"PU_reweight":True,
"hist_para":[80,x_emu_new,-4,4],
"y_axis":["null","null"],
"x_label":['Rapidity^{ll}',0.1],
"y_label":['Event / 1',0.05],
"x_log":False,
"y_log":False,
"lenend":{
"useLegend":True,
"position":[],
},
},
"leading_pt":{
"Data_value_dic":{"leading_pt":True},
"MC_value_dic":{"leading_pt":True},
"hist_name":"leading_pt",
"hist_title":"Leading Lepton Pt",
"use_array":False,
"PU_reweight":True,
"hist_para":[60,x_emu_new,0,300],
"y_axis":["null","null"],
"x_label":['P_{T}^{leading lep} (GeV/c)',0.1],
"y_label":['Event / 5 GeV',0.05],
"x_log":False,
"y_log":False,
"lenend":{
"useLegend":True,
"position":[],
},
},
"new_leading_pt":{
"Data_value_dic":{"leading_pt":True},
"MC_value_dic":{"leading_pt":True},
"hist_name":"new_leading_pt",
"hist_title":"Leading Lepton Pt",
"use_array":False,
"PU_reweight":True,
"hist_para":[30,x_emu_new,0,150],
"y_axis":["null","null"],
"x_label":['P_{T}^{leading lep} (GeV/c)',0.1],
"y_label":['Event / 5 GeV',0.05],
"x_log":False,
"y_log":False,
"lenend":{
"useLegend":True,
"position":[],
},
},
"leading_eta":{
"Data_value_dic":{"leading_eta":True},
"MC_value_dic":{"leading_eta":True},
"hist_name":"leading_eta",
"hist_title":"Leading Lepton #eta",
"use_array":False,
"PU_reweight":True,
"hist_para":[51,x_emu_new,-2.55,2.55],
"y_axis":["null","null"],
"x_label":['#eta^{leading lepton}',0.1],
"y_label":['Event / 0.1',0.05],
"x_log":False,
"y_log":False,
"lenend":{
"useLegend":True,
"position":[],
},
},
"leading_phi":{
"Data_value_dic":{"leading_phi":True},
"MC_value_dic":{"leading_phi":True},
"hist_name":"leading_phi",
"hist_title":"Leading Lepton #phi",
"use_array":False,
"PU_reweight":True,
"hist_para":[35,x_emu_new,-3.5,3.5],
"y_axis":["null","null"],
"x_label":['#phi^{leading lepton}',0.1],
"y_label":['Event / 0.2',0.05],
"x_log":False,
"y_log":False,
"lenend":{
"useLegend":True,
"position":[],
},
},
"sub_leading_pt":{
"Data_value_dic":{"sub_leading_pt":True},
"MC_value_dic":{"sub_leading_pt":True},
"hist_name":"sub_leading_pt",
"hist_title":"Sub-Leading Lepton Pt",
"use_array":False,
"PU_reweight":True,
"hist_para":[60,x_emu_new,0,300],
"y_axis":["null","null"],
"x_label":['P_{T}^{subleading lepton} (GeV/c)',0.1],
"y_label":['Event / 5 GeV',0.05],
"x_log":False,
"y_log":False,
"lenend":{
"useLegend":True,
"position":[],
},
},
"new_sub_leading_pt":{
"Data_value_dic":{"sub_leading_pt":True},
"MC_value_dic":{"sub_leading_pt":True},
"hist_name":"new_sub_leading_pt",
"hist_title":"Sub-Leading Lepton Pt",
"use_array":False,
"PU_reweight":True,
"hist_para":[30,x_emu_new,0,150],
"y_axis":["null","null"],
"x_label":['P_{T}^{subleading lepton} (GeV/c)',0.1],
"y_label":['Event / 5 GeV',0.05],
"x_log":False,
"y_log":False,
"lenend":{
"useLegend":True,
"position":[],
},
},
"sub_leading_eta":{
"Data_value_dic":{"sub_leading_eta":True},
"MC_value_dic":{"sub_leading_eta":True},
"hist_name":"sub_leading_eta",
"hist_title":"sub_Leading Lepton #eta",
"use_array":False,
"PU_reweight":True,
"hist_para":[51,x_emu_new,-2.55,2.55],
"y_axis":["null","null"],
"x_label":['#eta^{subleading lepton}',0.1],
"y_label":['Event / 0.1',0.05],
"x_log":False,
"y_log":False,
"lenend":{
"useLegend":True,
"position":[],
},
},
"sub_leading_phi":{
"Data_value_dic":{"sub_leading_phi":True},
"MC_value_dic":{"sub_leading_phi":True},
"hist_name":"sub_leading_phi",
"hist_title":"sub-Leading Lepton #phi",
"use_array":False,
"PU_reweight":True,
"hist_para":[35,x_emu_new,-3.5,3.5],
"y_axis":["null","null"],
"x_label":['#phi^{subleading lepton}',0.1],
"y_label":['Event / 0.2',0.05],
"x_log":False,
"y_log":False,
"lenend":{
"useLegend":True,
"position":[],
},
},
"MET_pt":{
"Data_value_dic":{"MET_Et":True},
"MC_value_dic":{"MET_Et":True},
"hist_name":"MET_Et",
"hist_title":"MET Pt",
"use_array":False,
"PU_reweight":True,
"hist_para":[20,x_emu_new,0,200],
"y_axis":["null","null"],
"x_label":['MET (GeV/c)',0.1],
"y_label":['Event / 10 GeV',0.05],
"x_log":False,
"y_log":False,
"lenend":{
"useLegend":True,
"position":[],
},
},
#"MET_pt_new":{
# "Data_value_dic":{"MET_Et":True},
# "MC_value_dic":{"MET_Et":True},
# "hist_name":"MET_Et_new",
# "hist_title":"MET Pt",
# "use_array":False,
# "PU_reweight":True,
# "hist_para":[20,x_emu_new,0,200],
# "y_axis":["null","null"],
# "x_label":['MET_{new} (GeV/c)',0.1],
# "y_label":['Event / 10 GeV',0.05],
# "x_log":False,
# "y_log":False,
# "lenend":{
# "useLegend":True,
# "position":[],
# },
# },
"MET_phi":{
"Data_value_dic":{"MET_phi":True},
"MC_value_dic":{"MET_phi":True},
"hist_name":"MET_phi",
"hist_title":"MET #phi",
"use_array":False,
"PU_reweight":True,
"hist_para":[35,x_emu_new,-3.5,3.5],
"y_axis":["null","null"],
"x_label":['MET_{#phi}',0.1],
"y_label":['Event / 0.2',0.05],
"x_log":False,
"y_log":False,
"lenend":{
"useLegend":True,
"position":[],
},
},
"Z_MET_delta_phi":{
"Data_value_dic":{"":True},
"MC_value_dic":{"":True},
"hist_name":"Z_MET_delta_phi",
"hist_title":"MET #phi",
"use_array":False,
"PU_reweight":True,
"hist_para":[35,x_emu_new,0,3.5],
"y_axis":["null","null"],
"x_label":['#delta #phi(MET,ll)',0.1],
"y_label":['Event / 0.2',0.05],
"x_log":False,
"y_log":False,
"lenend":{
"useLegend":True,
"position":[],
},
},
"MET_significance":{
"Data_value_dic":{"MET_significance":True},
"MC_value_dic":{"MET_significance":True},
"hist_name":"MET_significance",
"hist_title":"MET significance",
"use_array":False,
"PU_reweight":True,
"hist_para":[40,x_emu_new,0,20],
"y_axis":["null","null"],
"x_label":['MET_{significance}',0.1],
"y_label":['Event / 0.5',0.05],
"x_log":False,
"y_log":False,
"lenend":{
"useLegend":True,
"position":[],
},
},
"MET_T1Txy_pt":{
"Data_value_dic":{"MET_T1Txy_Pt":True},
"MC_value_dic":{"MET_T1Txy_Pt":True},
"hist_name":"MET_T1Txy_Pt",
"hist_title":"MET T1Txy Pt",
"use_array":False,
"PU_reweight":True,
"hist_para":[20,x_emu_new,0,200],
"y_axis":["null","null"],
"x_label":['MET^{T1Txy} (GeV/c)',0.1],
"y_label":['Event / 10 GeV',0.05],
"x_log":False,
"y_log":False,
"lenend":{
"useLegend":True,
"position":[],
},
},
#"MET_T1Txy_pt_new":{
# "Data_value_dic":{"MET_T1Txy_Pt":True},
# "MC_value_dic":{"MET_T1Txy_Pt":True},
# "hist_name":"MET_T1Txy_Pt_new",
# "hist_title":"MET T1Txy Pt",
# "use_array":False,
# "PU_reweight":True,
# "hist_para":[20,x_emu_new,0,200],
# "y_axis":["null","null"],
# "x_label":['MET^{T1Txy}_{new} (GeV/c)',0.1],
# "y_label":['Event / 10 GeV',0.05],
# "x_log":False,
# "y_log":False,
# "lenend":{
# "useLegend":True,
# "position":[],
# },
# },
"MET_T1Txy_phi":{
"Data_value_dic":{"MET_T1Txy_phi":True},
"MC_value_dic":{"MET_T1Txy_phi":True},
"hist_name":"MET_T1Txy_phi",
"hist_title":"MET T1Txy #phi",
"use_array":False,
"PU_reweight":True,
"hist_para":[35,x_emu_new,-3.5,3.5],
"y_axis":["null","null"],
"x_label":['MET^{T1Txy}_{#phi}',0.1],
"y_label":['Event / 0.2',0.05],
"x_log":False,
"y_log":False,
"lenend":{
"useLegend":True,
"position":[],
},
},
"Z_MET_T1Txy_delta_phi":{
"Data_value_dic":{"MET_T1Txy_phi":True},
"MC_value_dic":{"MET_T1Txy_phi":True},
"hist_name":"Z_MET_T1Txy_delta_phi",
"hist_title":"MET T1Txy #phi",
"use_array":False,
"PU_reweight":True,
"hist_para":[35,x_emu_new,0,3.5],
"y_axis":["null","null"],
"x_label":['#delta #phi(MET^{T1Txy},ll)',0.1],
"y_label":['Event / 0.2',0.05],
"x_log":False,
"y_log":False,
"lenend":{
"useLegend":True,
"position":[],
},
},
"MET_T1Txy_significance":{
"Data_value_dic":{"MET_T1Txy_significance":True},
"MC_value_dic":{"MET_T1Txy_significance":True},
"hist_name":"MET_T1Txy_significance",
"hist_title":"MET T1Txy significance",
"use_array":False,
"PU_reweight":True,
"hist_para":[40,x_emu_new,0,20],
"y_axis":["null","null"],
"x_label":['MET^{T1Txy}_{significance}',0.1],
"y_label":['Event / 0.5',0.05],
"x_log":False,
"y_log":False,
"lenend":{
"useLegend":True,
"position":[],
},
},
"rho":{
"Data_value_dic":{"ev_fixedGridRhoAll":True},
"MC_value_dic":{"ev_fixedGridRhoAll":True},
"hist_name":"rho_all",
"hist_title":"ev_fixedGridRhoAll",
"use_array":False,
"PU_reweight":True,
"hist_para":[100,x_emu_new,0,50],
"y_axis":["null","null"],
"x_label":['#rho',0.1],
"y_label":['Event / 0.5',0.05],
"x_log":False,
"y_log":False,
"lenend":{
"useLegend":True,
"position":[],
},
},
"n_jet":{
"Data_value_dic":{"n_jet":True},
"MC_value_dic":{"n_jet":True},
"hist_name":"n_jet",
"hist_title":"Jet Multiplicity",
"use_array":False,
"PU_reweight":True,
"hist_para":[10,x_emu_new,0,10],
"y_axis":["null","null"],
"x_label":['N_{jet}',0.1],
"y_label":['Event / 1',0.05],
"x_log":False,
"y_log":False,
"lenend":{
"useLegend":True,
"position":[],
},
},
"n_bjet":{
"Data_value_dic":{"n_bjet":True},
"MC_value_dic":{"n_bjet":True},
"hist_name":"n_bjet",
"hist_title":"Jet Multiplicity",
"use_array":False,
"PU_reweight":True,
"hist_para":[10,x_emu_new,0,10],
"y_axis":["null","null"],
"x_label":['N_{b jet}',0.1],
"y_label":['Event / 1',0.05],
"x_log":False,
"y_log":False,
"lenend":{
"useLegend":True,
"position":[],
},
},
"n_bjet2":{
"Data_value_dic":{"":True},
"MC_value_dic":{"":True},
"hist_name":"n_bjet2",
"hist_title":"Jet Multiplicity",
"use_array":False,
"PU_reweight":True,
"hist_para":[10,x_emu_new,0,10],
"y_axis":["null","null"],
"x_label":['N_{b jet} (p_{T} in [20,30])',0.1],
"y_label":['Event / 1',0.05],
"x_log":False,
"y_log":False,
"lenend":{
"useLegend":True,
"position":[],
},
},
"n_fjet1":{
"Data_value_dic":{"":True},
"MC_value_dic":{"":True},
"hist_name":"n_fjet1",
"hist_title":"Jet Multiplicity",
"use_array":False,
"PU_reweight":True,
"hist_para":[10,x_emu_new,0,10],
"y_axis":["null","null"],
"x_label":['N_{jet} (p_{T} > 30, |#eta| in [2.4,5.2])',0.1],
"y_label":['Event / 1',0.05],
"x_log":False,
"y_log":False,
"lenend":{
"useLegend":True,
"position":[],
},
},
"n_fjet2":{
"Data_value_dic":{"":True},
"MC_value_dic":{"":True},
"hist_name":"n_fjet2",
"hist_title":"Jet Multiplicity",
"use_array":False,
"PU_reweight":True,
"hist_para":[10,x_emu_new,0,10],
"y_axis":["null","null"],
"x_label":['N_{jet} (p_{T} > 40, |#eta| in [2.4,5.2])',0.1],
"y_label":['Event / 1',0.05],
"x_log":False,
"y_log":False,
"lenend":{
"useLegend":True,
"position":[],
},
},
"n_jet_bjet":{
"Data_value_dic":{"n_bjet":True},
"MC_value_dic":{"n_bjet":True},
"hist_name":"n_jet_bjet",
"hist_title":"Jet Multiplicity",
"use_array":False,
"PU_reweight":True,
"hist_para":[16,x_emu_new,0,16],
"y_axis":["null","null"],
"x_label":['N_{(jet, b jet)}',0.1],
"y_label":['Event / 1',0.05],
"x_log":False,
"y_log":False,
"lenend":{
"useLegend":True,
"position":[],
},
},
"HT":{
"Data_value_dic":{"":True},
"MC_value_dic":{"":True},
"hist_name":"Ht",
"hist_title":"Ht",
"use_array":False,
"PU_reweight":True,
"hist_para":[49,x_emu_new,10,500],
"y_axis":["null","null"],
"x_label":['HT (GeV)',0.1],
"y_label":['Event / 10 GeV',0.05],
"x_log":False,
"y_log":False,
"lenend":{
"useLegend":True,
"position":[],
},
},
"sys_HT":{
"Data_value_dic":{"":True},
"MC_value_dic":{"":True},
"hist_name":"sys_Ht",
"hist_title":"sys Ht",
"use_array":False,
"PU_reweight":True,
"hist_para":[49,x_emu_new,10,500],
"y_axis":["null","null"],
"x_label":['HT^{jets+leptons} (GeV)',0.1],
"y_label":['Event / 10 GeV',0.05],
"x_log":False,
"y_log":False,
"lenend":{
"useLegend":True,
"position":[],
},
},
"pv_n":{
"Data_value_dic":{"pv_n":True},
"MC_value_dic":{"pv_n":True},
"hist_name":"N_vtx_PU",
"hist_title":"Number of vertex (with PU reweight)",
"use_array":False,
"PU_reweight":True,
"hist_para":[50,'null',0,50],
"y_axis":["null","null"],
"x_label":['N_{vtx}',0.1],
"y_label":['Event ',0.05],
"x_log":False,
"y_log":False,
"lenend":{
"useLegend":True,
"position":[],
},
},
"pv_n_noPU":{
"Data_value_dic":{"pv_n":True},
"MC_value_dic":{"pv_n":True},
"hist_name":"N_vtx_noPU",
"hist_title":"Number of vertex (without PU reweight)",
"use_array":False,
"PU_reweight":False,
"hist_para":[50,'null',0,50],
"y_axis":["null","null"],
"x_label":['N_{vtx}^{no PU}',0.1],
"y_label":['Event ',0.05],
"x_log":False,
"y_log":False,
"lenend":{
"useLegend":True,
"position":[],
},
},
"mass_err_stat":{
"Data_value_dic":{"pv_n":True},
"MC_value_dic":{"pv_n":True},
"hist_name":"N_stat",
"hist_title":"",
"use_array":False,
"PU_reweight":True,
"hist_para":[1,mass_bin,0,100],
"y_axis":["null","null"],
"x_label":['N_stat',0.1],
"y_label":['Event ',0.05],
"x_log":False,
"y_log":True,
"lenend":{
"useLegend":True,
"position":[],
},
},
}
| [
"[email protected]"
] | |
a817828844765fa43ba5993b23bb82b037a2711f | b4fd46f1f9c7b7d3f78df723d8aa34c8a65edb1a | /src/hupper/watchman.py | 00b923fe217e9791afe2f80e24cfb82858ff3c69 | [
"MIT"
] | permissive | ProstoMaxim/hupper | b0bf6123c58b96eb6d97b5797fc57e390efbf513 | 46a46af2c459fb82884b205a47211b587aa05749 | refs/heads/master | 2020-03-29T19:50:51.316020 | 2018-09-25T15:14:43 | 2018-09-25T15:14:43 | 150,283,612 | 0 | 0 | MIT | 2018-09-25T14:57:55 | 2018-09-25T14:57:55 | null | UTF-8 | Python | false | false | 4,130 | py | # check ``hupper.utils.is_watchman_supported`` before using this module
import json
import os
import socket
import threading
import time
from .compat import PY2
from .interfaces import IFileMonitor
from .utils import get_watchman_sockpath
class WatchmanFileMonitor(threading.Thread, IFileMonitor):
"""
An :class:`hupper.interfaces.IFileMonitor` that uses Facebook's
``watchman`` daemon to detect changes.
``callback`` is a callable that accepts a path to a changed file.
"""
def __init__(
self,
callback,
logger,
sockpath=None,
binpath='watchman',
timeout=1.0,
**kw
):
super(WatchmanFileMonitor, self).__init__()
self.callback = callback
self.logger = logger
self.paths = set()
self.dirpaths = set()
self.lock = threading.Lock()
self.enabled = True
self.sockpath = sockpath
self.binpath = binpath
self.timeout = timeout
def add_path(self, path):
with self.lock:
dirpath = os.path.dirname(path)
if dirpath not in self.dirpaths:
self._schedule(dirpath)
self.dirpaths.add(dirpath)
if path not in self.paths:
self.paths.add(path)
def start(self):
sockpath = self._resolve_sockpath()
sock = socket.socket(socket.AF_UNIX, socket.SOCK_STREAM)
sock.settimeout(self.timeout)
sock.connect(sockpath)
self._sock = sock
self._recvbufs = []
self._send(['version'])
result = self._recv()
self.logger.debug('Connected to watchman v' + result['version'] + '.')
super(WatchmanFileMonitor, self).start()
def join(self):
try:
return super(WatchmanFileMonitor, self).join()
finally:
self._sock.close()
self._sock = None
def run(self):
while self.enabled:
try:
result = self._recv()
if 'error' in result:
self.logger.error('watchman error=' + result['error'])
elif 'subscription' in result:
root = result['root']
files = result['files']
with self.lock:
for f in files:
path = os.path.join(root, f)
if path in self.paths:
self.callback(path)
except socket.timeout:
pass
def stop(self):
self.enabled = False
def _resolve_sockpath(self):
if self.sockpath:
return self.sockpath
return get_watchman_sockpath(self.binpath)
def _schedule(self, dirpath):
self._send([
'subscribe',
dirpath,
dirpath,
{
# +1 second because we don't want any buffered changes
# if the daemon is already watching the folder
'since': int(time.time() + 1),
'expression': [
'type', 'f',
],
'fields': ['name'],
},
])
def _readline(self):
# buffer may already have a line
if len(self._recvbufs) == 1 and b'\n' in self._recvbufs[0]:
line, b = self._recvbufs[0].split(b'\n', 1)
self._recvbufs = [b]
return line
while True:
b = self._sock.recv(4096)
if not b:
raise RuntimeError('lost connection to watchman')
if b'\n' in b:
result = b''.join(self._recvbufs)
line, b = b.split(b'\n', 1)
self.buf = [b]
return result + line
self._recvbufs.append(b)
def _recv(self):
line = self._readline()
if not PY2:
line = line.decode('utf8')
return json.loads(line)
def _send(self, msg):
cmd = json.dumps(msg)
if not PY2:
cmd = cmd.encode('ascii')
self._sock.sendall(cmd + b'\n')
| [
"[email protected]"
] | |
17fe14c4e6fa06e9f9f2562f8672e56c946a0ac6 | 5ca85847885c6fd6f9728b0b2dffb66e96a81a1d | /hemlock/app/routes/base_routing.py | c31895ffe2bf37417fd7aa109647fcf91a13ebb4 | [] | no_license | syfreed/hemlock_test2 | 682d843636883a6a2b883932cd7282e9b865ebcd | 61933fd17630ddd1bb46d8f2090b1b039a3b4e99 | refs/heads/master | 2020-08-03T11:21:18.460905 | 2019-09-29T22:36:36 | 2019-09-29T22:36:36 | 211,733,895 | 0 | 0 | null | 2019-10-22T14:21:27 | 2019-09-29T22:25:30 | Python | UTF-8 | Python | false | false | 1,489 | py | """Base routing functions"""
from hemlock.app.factory import bp, db, login_manager
from hemlock.database.models import Participant, Navbar, Brand, Navitem, Dropdownitem
from hemlock.database.private import DataStore
from flask import current_app, url_for
@login_manager.user_loader
def load_user(id):
return Participant.query.get(int(id))
@bp.before_app_first_request
def init_app():
"""Create database tables and initialize data storage models
Additionally, set a scheduler job to log the status periodically.
"""
db.create_all()
if not DataStore.query.first():
DataStore()
if not Navbar.query.filter_by(name='researcher_navbar').first():
create_researcher_navbar()
db.session.commit()
current_app.apscheduler.add_job(
func=log_current_status, trigger='interval',
seconds=current_app.status_log_period.seconds,
args=[current_app._get_current_object()], id='log_status'
)
def create_researcher_navbar():
navbar = Navbar(name='researcher_navbar')
Brand(bar=navbar, label='Hemlock')
Navitem(
bar=navbar, url=url_for('hemlock.participants'), label='Participants')
Navitem(bar=navbar, url=url_for('hemlock.download'), label='Download')
Navitem(bar=navbar, url=url_for('hemlock.logout'), label='Logout')
return navbar
def log_current_status(app):
with app.app_context():
ds = DataStore.query.first()
ds.log_status()
db.session.commit() | [
"[email protected]"
] | |
80d23caed9eb691e211165bc984de9bfe7b6c3d1 | da9ce50833e5292d27e14d31ee90c5bcc410d71b | /survol/sources_types/CIM_Process/wbem_process_info.py | a51c26e47d53d0bdf1863f69b2a7c8f529808775 | [] | no_license | Tiancheng-Luo/survol | 10367b6b923f7095574436bb44fd5189b1e49160 | 30c7f771010462cd865480986abfe1045429f021 | refs/heads/master | 2022-11-26T16:02:46.852058 | 2020-07-25T07:28:34 | 2020-07-25T07:28:34 | null | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 2,277 | py | #!/usr/bin/env python
"""
WBEM CIM_Process information.
"""
import sys
import lib_util
import lib_common
import lib_wbem
from lib_properties import pc
Usable = lib_util.UsableLinux
CanProcessRemote = True
def Main():
# TODO: can_process_remote should be suppressed because it duplicates CanProcessRemote
cgiEnv = lib_common.CgiEnv(can_process_remote=True)
pid = int(cgiEnv.GetId())
machine_name = cgiEnv.GetHost()
grph = cgiEnv.GetGraph()
cimom_url = lib_wbem.HostnameToWbemServer(machine_name)
DEBUG("wbem_process_info.py currentHostname=%s pid=%d machine_name=%s cimom_url=%s",
lib_util.currentHostname, pid, machine_name, cimom_url)
conn_wbem = lib_wbem.WbemConnection(cimom_url)
name_space = "root/cimv2"
try:
inst_lists = conn_wbem.ExecQuery("WQL", 'select * from CIM_Process where Handle="%s"' % pid, name_space)
except:
lib_common.ErrorMessageHtml("Error:" + str(sys.exc_info()))
class_name = "CIM_Process"
dict_props = {"Handle": pid}
root_node = lib_util.EntityClassNode(class_name, name_space, cimom_url, "WBEM")
# There should be only one object, hopefully.
for an_inst in inst_lists:
dict_inst = dict(an_inst)
host_only = lib_util.EntHostToIp(cimom_url)
if lib_util.IsLocalAddress(host_only):
uri_inst = lib_common.gUriGen.UriMakeFromDict(class_name, dict_props)
else:
uri_inst = lib_common.RemoteBox(host_only).UriMakeFromDict(class_name, dict_props)
grph.add((root_node, lib_common.MakeProp(class_name), uri_inst))
url_namespace = lib_wbem.NamespaceUrl(name_space, cimom_url, class_name)
nod_namespace = lib_common.NodeUrl(url_namespace)
grph.add((root_node, pc.property_cim_subnamespace, nod_namespace))
# None properties are not printed.
for iname_key in dict_inst:
iname_val = dict_inst[iname_key]
# TODO: If this is a reference, create a Node !!!!!!!
if not iname_val is None:
grph.add((uri_inst, lib_common.MakeProp(iname_key), lib_common.NodeLiteral(iname_val)))
# TODO: Call the method Associators(). Idem References().
cgiEnv.OutCgiRdf()
if __name__ == '__main__':
Main()
| [
"[email protected]"
] | |
6ce9270ac0a7bc5542a7cd5fc4ade24fab776cb6 | 907b3bbd44c95be1542a36feaadb6a71b724579f | /files/usr/tmp/pip-build-nyxh8e0k/google-cloud-vision/google/cloud/vision/likelihood.py | 6239efe18251f74ee337f3573ab128b3df84470d | [] | no_license | vo0doO/com.termux | 2d8f536c1a5dbd7a091be0baf181e51f235fb941 | c97dd7b906e5ef3ec157581fd0bcadd3e3fc220e | refs/heads/master | 2020-12-24T09:40:30.612130 | 2016-11-21T07:47:25 | 2016-11-21T07:47:25 | 73,282,539 | 2 | 2 | null | 2020-07-24T21:33:03 | 2016-11-09T12:33:01 | Python | UTF-8 | Python | false | false | 1,000 | py | # Copyright 2016 Google Inc.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
"""Likelihood constants returned from Vision API."""
class Likelihood(object):
"""A representation of likelihood to give stable results across upgrades.
See:
https://cloud.google.com/vision/reference/rest/v1/images/annotate#likelihood
"""
UNKNOWN = 'UNKNOWN'
VERY_UNLIKELY = 'VERY_UNLIKELY'
UNLIKELY = 'UNLIKELY'
POSSIBLE = 'POSSIBLE'
LIKELY = 'LIKELY'
VERY_LIKELY = 'VERY_LIKELY'
| [
"[email protected]"
] | |
8c7ad5f66748615cb686a259ce6d73faa3931d90 | 59636b143a2ab189145b17a7ea9a38de5af1f7a5 | /All/interface_all/interface_zonghe_Requests/case/test/test_old.py | 74f16785031844698fd834d569676835d9f989e4 | [] | no_license | woshichenya/hezi | 880a70c34cc61b6b6bcf1ccb65fa54989595fb71 | 4211ff8ef78f5d15d8fc8065247f916dfe9d305d | refs/heads/master | 2020-04-28T21:46:02.664025 | 2019-05-14T08:47:33 | 2019-05-14T08:47:33 | 175,593,966 | 1 | 0 | null | null | null | null | UTF-8 | Python | false | false | 9,149 | py | import re
c={
"appKey":"app_key",
"uuid":"用户唯一标示",
"openId":"用户openid",
"ufo":"用户信息",
"wayScene":"路径+参数场景值(小程序show回调返回的参数)",
"userMarker":"session标识(入口token)",
"time":"开始的时间",
"pointName":"事件名称(自定义事件埋点事件名称)",
"eventName":"埋点的事件类型",
"SDKVersion":"sdk版本",
"dr":"",
"currentPage":"当前页面的路径",
"network":"网络类型",
"phoneModel":"手机型号",
"life":"小程序生命周期",
"shareCount":"分享当前页面的次数",
"errorCount":"错误数量",
"eventTime":"当前请求的时间",
"pixelRatio":"像素点",
"winW":"屏幕宽度",
"winH":"屏幕高度",
"lang":"浏览器语言",
"wxVersion":"微信版本号",
"lat":"经度",
"lng":"纬度",
"speed":"速度",
"system":"系统版本",
"platform":"客户端平台",
"pc":"page_count",
"fp":"first_page",
"lastPage":"上个页面的路径",
"is_first_page":"是不是第一个页面",
"ln":"location_name",
"ct":"",
"sr":"",
"qr":"",
"usr":"",
"la_c":"",
"as_c":"",
"ah_c":"",
"rq_c":"第几次请求",
"ag":"当前页面的参数",
"avatarUrl":"用户微信头像地址",
"city":"市",
"country":"国家",
"gender":"性别( 0:未知、1:男、2:女)",
"language":"语言",
"nickName":"微信昵称",
"province":"省",
"rq_c":"第几次请求",
"uuid":"用户唯一标示",
"openid":"用户openid",
}
a={
"took": 2,
"timed_out": "false",
"_shards": {
"total": 5,
"successful": 5,
"skipped": 0,
"failed": 0
},
"hits": {
"total": 4,
"max_score": 1,
"hits": [
{
"_index": "logstash-1-536-page-2019-03-15",
"_type": "doc",
"_id": "0AsCf2kBiZy68uZC3zlL",
"_score": 1,
"_source": {
"eventTime": 1552614086255,
"@version": "1",
"@timestamp": "2019-03-15T09:41:26.000Z",
"system": "iOS 10.0.1",
"platform": "devtools",
"ty": 1,
"logtime": "2019-03-15 17:41:26",
"winH": 555,
"pixelRatio": 2,
"time": 1552614086202,
"dr": 0,
"userMarker": "15526140862112049640",
"fp": 0,
"winW": 375,
"lang": "zh",
"la_c": 2,
"phoneModel": "iPhone 6",
"pc": 1,
"wsdk": "1.9.97",
"ah_c": 0,
"ev": "app",
"errorCount": 0,
"rq_c": 2,
"life": "launch",
"ufo": {},
"uuid": "15517525665583054408",
"wayScene": {},
"appKey": "536",
"SDKVersion": "6.1.2",
"eventName": "page",
"as_c": 0
}
},
{
"_index": "logstash-1-536-page-2019-03-15",
"_type": "doc",
"_id": "VwUCf2kBQ3rQFs4b8kdM",
"_score": 1,
"_source": {
"@version": "1",
"@timestamp": "2019-03-15T09:41:33.000Z",
"ct": 1,
"logtime": "2019-03-15 17:41:33",
"ty": 1,
"winH": 555,
"pixelRatio": 2,
"wxVersion": "6.6.3",
"network": "2g",
"time": 1552614093268,
"lang": "zh",
"userMarker": "15526140862112049640",
"winW": 375,
"phoneModel": "iPhone 6",
"ev": "event",
"rq_c": 5,
"pointName": "vdong_reachbottom",
"ufo": {
"language": "zh_CN",
"province": "北京",
"uuid": "15517525665583054408",
"country": "中国",
"nickName": "都是佚名",
"city": "昌平",
"avatarUrl": "https://wx.qlogo.cn/mmopen/vi_32/Q0j4TwGTfTIRdRic7Jujz7fibvLrk4QYh5tVatpNicfLWg96YsicG1fPhCt01ZyL4NpXmG5RK1TjRCqtLR2bZeWlzg/132",
"gender": 2
},
"openId": "osX135I4GC6M8n2a-6hsPaWDBreA",
"uuid": "15517525665583054408",
"wayScene": {},
"appKey": "536",
"eventName": "page",
"SDKVersion": "6.1.2"
}
},
{
"_index": "logstash-1-536-page-2019-03-15",
"_type": "doc",
"_id": "0QsCf2kBiZy68uZC3zlL",
"_score": 1,
"_source": {
"@version": "1",
"@timestamp": "2019-03-15T09:41:27.000Z",
"system": "iOS 10.0.1",
"platform": "devtools",
"ty": 1,
"logtime": "2019-03-15 17:41:27",
"winH": 555,
"pixelRatio": 2,
"wxVersion": "6.6.3",
"isFirstPage": "true",
"network": "2g",
"time": 1552614087170,
"dr": 3,
"userMarker": "15526140862112049640",
"winW": 375,
"lang": "zh",
"phoneModel": "iPhone 6",
"wsdk": "1.9.97",
"ev": "page",
"errorCount": 0,
"currentPage": "pages/index/index",
"rq_c": 3,
"life": "show",
"ufo": {
"language": "zh_CN",
"province": "北京",
"uuid": "15517525665583054408",
"country": "中国",
"nickName": "都是佚名",
"city": "昌平",
"avatarUrl": "https://wx.qlogo.cn/mmopen/vi_32/Q0j4TwGTfTIRdRic7Jujz7fibvLrk4QYh5tVatpNicfLWg96YsicG1fPhCt01ZyL4NpXmG5RK1TjRCqtLR2bZeWlzg/132",
"gender": 2
},
"uuid": "15517525665583054408",
"wayScene": {},
"appKey": "536",
"eventName": "page",
"SDKVersion": "6.1.2"
}
},
{
"_index": "logstash-1-536-page-2019-03-15",
"_type": "doc",
"_id": "0wsCf2kBiZy68uZC5jlr",
"_score": 1,
"_source": {
"@version": "1",
"@timestamp": "2019-03-15T09:41:30.000Z",
"system": "iOS 10.0.1",
"platform": "devtools",
"ty": 1,
"logtime": "2019-03-15 17:41:30",
"winH": 555,
"pixelRatio": 2,
"wxVersion": "6.6.3",
"network": "2g",
"time": 1552614090166,
"dr": 20,
"userMarker": "15526140862112049640",
"winW": 375,
"lang": "zh",
"ag": {
"id": "410"
},
"phoneModel": "iPhone 6",
"wsdk": "1.9.97",
"lastPage": "pages/index/index",
"ev": "page",
"errorCount": 0,
"currentPage": "pages/goods/detail/index",
"rq_c": 4,
"life": "show",
"ufo": {
"language": "zh_CN",
"province": "北京",
"uuid": "15517525665583054408",
"country": "中国",
"nickName": "都是佚名",
"city": "昌平",
"avatarUrl": "https://wx.qlogo.cn/mmopen/vi_32/Q0j4TwGTfTIRdRic7Jujz7fibvLrk4QYh5tVatpNicfLWg96YsicG1fPhCt01ZyL4NpXmG5RK1TjRCqtLR2bZeWlzg/132",
"gender": 2
},
"uuid": "15517525665583054408",
"wayScene": {},
"appKey": "536",
"eventName": "page",
"SDKVersion": "6.1.2"
}
}
]
}
}
b={"uuid":"1550210850540313295","userMarker":"15506252426373527013","wayScene":{},"appKey":"80d114e0c97f848e79ecef61a489a940","eventName":"page","time":1550631026378,"dr":2,"currentPage":"pages/goods/detail/index","life":"show","errorCount":0,"network":"wifi","phoneModel":"iPhone 5","pixelRatio":2,"winW":320,"winH":456,"lang":"zh","wxVersion":"6.6.3","SDKVersion":"6.1.2","wsdk":"1.9.97","system":"iOS 10.0.1","platform":"devtools","lastPage":"pages/index/index","ag":{"id":"251"},"rq_c":4,"ufo":{"nickName":"陈雅","gender":1,"language":"zh_CN","city":"","province":"","country":"中国","avatarUrl":"https://wx.qlogo.cn/mmopen/vi_32/g358vshZe0FNr19Q1e7M2hq5VyFGmISUkuBGibzrjzvrDQjMxCBYRqkCX9dLExMRvf7yZmcMSYD7RN1rUaic4z0w/132","uuid":"1550210850540313295"}}
print("数据采集系统收到的值有%s个"%len(a))
print("埋点上传的值有%s个"%len(b))
print("*"*200)
sum = 0
sum2=0
for x in a :
if x in b :
sum +=1
else:
if x in c:
sum2+=1
try:
print("数据采集系统中是:", x, ":", a[x],"埋点上传的内容是",x,":",b[x])
except:
try:
print("数据采集系统中是:",x,":",a[x])
except:
print("数据采集系统中没有",x)
try:
print("埋点上传的内容是",x,":",b[x])
except:
print("埋点上传中没有", x)
print("*" * 200)
print("后台和埋点数据不一致的有%s个"%(len(a)-sum))
print("不一致且不在表格中的有%s个"%sum2)
print("*" * 200)
sum=0
for ss in c :
if ss not in b:
if ss not in b["ufo"]:
sum+=1
print("缺少字段",ss,"-----翻译:",c[ss])
print("埋点没有上传的数据有%s个"%sum)
s=str(a)
print(s)
sss=re.findall("\'openId\':\ '(.*?)\'",s)
print(sss)
print(len(sss))
sy=set(sss)
print(sy) | [
"[email protected]"
] | |
36a4c65f338f64a2110e2fa46d3df6253e111776 | c0a991791d4033b07d2ae39bd383498e1c5b74f4 | /gluon/gluoncv2/models/shufflenetv2b.py | 15dd163cd3fb08fb095887360aa7d32269f04134 | [
"MIT"
] | permissive | guanlongtianzi/imgclsmob | c9a84955be3d011a1d604f28068682d65ca0c455 | c77029aca04f32fefeae3e292d08ecfc35af1de8 | refs/heads/master | 2020-04-03T09:08:03.201015 | 2018-10-29T03:47:38 | 2018-10-29T03:47:38 | null | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 16,347 | py | """
ShuffleNet V2, implemented in Gluon. The alternative version.
Original paper: 'ShuffleNet V2: Practical Guidelines for Efficient CNN Architecture Design,'
https://arxiv.org/abs/1807.11164.
"""
__all__ = ['ShuffleNetV2b', 'shufflenetv2b_wd2', 'shufflenetv2b_w1', 'shufflenetv2b_w3d2', 'shufflenetv2b_w2',
'shufflenetv2c_wd2']
import os
from mxnet import cpu
from mxnet.gluon import nn, HybridBlock
from .common import ChannelShuffle, ChannelShuffle2, SEBlock
class ShuffleConv(HybridBlock):
"""
ShuffleNetV2(b) specific convolution block.
Parameters:
----------
in_channels : int
Number of input channels.
out_channels : int
Number of output channels.
kernel_size : int or tuple/list of 2 int
Convolution window size.
strides : int or tuple/list of 2 int
Strides of the convolution.
padding : int or tuple/list of 2 int
Padding value for convolution layer.
"""
def __init__(self,
in_channels,
out_channels,
kernel_size,
strides,
padding,
**kwargs):
super(ShuffleConv, self).__init__(**kwargs)
with self.name_scope():
self.conv = nn.Conv2D(
channels=out_channels,
kernel_size=kernel_size,
strides=strides,
padding=padding,
use_bias=False,
in_channels=in_channels)
self.bn = nn.BatchNorm(
in_channels=out_channels)
self.activ = nn.Activation('relu')
def hybrid_forward(self, F, x):
x = self.conv(x)
x = self.bn(x)
x = self.activ(x)
return x
def shuffle_conv1x1(in_channels,
out_channels):
"""
1x1 version of the ShuffleNetV2(b) specific convolution block.
Parameters:
----------
in_channels : int
Number of input channels.
out_channels : int
Number of output channels.
"""
return ShuffleConv(
in_channels=in_channels,
out_channels=out_channels,
kernel_size=1,
strides=1,
padding=0)
class ShuffleDwConv3x3(HybridBlock):
"""
ShuffleNetV2(b) specific depthwise convolution 3x3 layer.
Parameters:
----------
channels : int
Number of input/output channels.
strides : int or tuple/list of 2 int
Strides of the convolution.
"""
def __init__(self,
channels,
strides,
**kwargs):
super(ShuffleDwConv3x3, self).__init__(**kwargs)
with self.name_scope():
self.conv = nn.Conv2D(
channels=channels,
kernel_size=3,
strides=strides,
padding=1,
groups=channels,
use_bias=False,
in_channels=channels)
self.bn = nn.BatchNorm(
in_channels=channels)
def hybrid_forward(self, F, x):
x = self.conv(x)
x = self.bn(x)
return x
class ShuffleUnit(HybridBlock):
"""
ShuffleNetV2(b) unit.
Parameters:
----------
in_channels : int
Number of input channels.
out_channels : int
Number of output channels.
downsample : bool
Whether do downsample.
use_se : bool
Whether to use SE block.
use_residual : bool
Whether to use residual connection.
shuffle_group_first : bool
Whether to use channel shuffle in group first mode.
"""
def __init__(self,
in_channels,
out_channels,
downsample,
use_se,
use_residual,
shuffle_group_first,
**kwargs):
super(ShuffleUnit, self).__init__(**kwargs)
self.downsample = downsample
self.use_se = use_se
self.use_residual = use_residual
mid_channels = out_channels // 2
in_channels2 = in_channels // 2
assert (in_channels % 2 == 0)
y2_in_channels = (in_channels if downsample else in_channels2)
y2_out_channels = out_channels - y2_in_channels
with self.name_scope():
self.conv1 = shuffle_conv1x1(
in_channels=y2_in_channels,
out_channels=mid_channels)
self.dconv = ShuffleDwConv3x3(
channels=mid_channels,
strides=(2 if self.downsample else 1))
self.conv2 = shuffle_conv1x1(
in_channels=mid_channels,
out_channels=y2_out_channels)
if self.use_se:
self.se = SEBlock(channels=y2_out_channels)
if downsample:
self.shortcut_dconv = ShuffleDwConv3x3(
channels=in_channels,
strides=2)
self.shortcut_conv = shuffle_conv1x1(
in_channels=in_channels,
out_channels=in_channels)
if shuffle_group_first:
self.c_shuffle = ChannelShuffle(
channels=out_channels,
groups=2)
else:
self.c_shuffle = ChannelShuffle2(
channels=out_channels,
groups=2)
def hybrid_forward(self, F, x):
if self.downsample:
y1 = self.shortcut_dconv(x)
y1 = self.shortcut_conv(y1)
x2 = x
else:
y1, x2 = F.split(x, axis=1, num_outputs=2)
y2 = self.conv1(x2)
y2 = self.dconv(y2)
y2 = self.conv2(y2)
if self.use_se:
y2 = self.se(y2)
if self.use_residual and not self.downsample:
y2 = y2 + x2
x = F.concat(y1, y2, dim=1)
x = self.c_shuffle(x)
return x
class ShuffleInitBlock(HybridBlock):
"""
ShuffleNetV2(b) specific initial block.
Parameters:
----------
in_channels : int
Number of input channels.
out_channels : int
Number of output channels.
"""
def __init__(self,
in_channels,
out_channels,
**kwargs):
super(ShuffleInitBlock, self).__init__(**kwargs)
with self.name_scope():
self.conv = ShuffleConv(
in_channels=in_channels,
out_channels=out_channels,
kernel_size=3,
strides=2,
padding=1)
self.pool = nn.MaxPool2D(
pool_size=3,
strides=2,
padding=1,
ceil_mode=False)
def hybrid_forward(self, F, x):
x = self.conv(x)
x = self.pool(x)
return x
class ShuffleNetV2b(HybridBlock):
"""
ShuffleNetV2(b) model from 'ShuffleNet V2: Practical Guidelines for Efficient CNN Architecture Design,'
https://arxiv.org/abs/1807.11164.
Parameters:
----------
channels : list of list of int
Number of output channels for each unit.
init_block_channels : int
Number of output channels for the initial unit.
final_block_channels : int
Number of output channels for the final block of the feature extractor.
use_se : bool, default False
Whether to use SE block.
use_residual : bool, default False
Whether to use residual connections.
shuffle_group_first : bool, default True
Whether to use channel shuffle in group first mode.
in_channels : int, default 3
Number of input channels.
classes : int, default 1000
Number of classification classes.
"""
def __init__(self,
channels,
init_block_channels,
final_block_channels,
use_se=False,
use_residual=False,
shuffle_group_first=True,
in_channels=3,
classes=1000,
**kwargs):
super(ShuffleNetV2b, self).__init__(**kwargs)
with self.name_scope():
self.features = nn.HybridSequential(prefix='')
self.features.add(ShuffleInitBlock(
in_channels=in_channels,
out_channels=init_block_channels))
in_channels = init_block_channels
for i, channels_per_stage in enumerate(channels):
stage = nn.HybridSequential(prefix='stage{}_'.format(i + 1))
with stage.name_scope():
for j, out_channels in enumerate(channels_per_stage):
downsample = (j == 0)
stage.add(ShuffleUnit(
in_channels=in_channels,
out_channels=out_channels,
downsample=downsample,
use_se=use_se,
use_residual=use_residual,
shuffle_group_first=shuffle_group_first))
in_channels = out_channels
self.features.add(stage)
self.features.add(shuffle_conv1x1(
in_channels=in_channels,
out_channels=final_block_channels))
in_channels = final_block_channels
self.features.add(nn.AvgPool2D(
pool_size=7,
strides=1))
self.output = nn.HybridSequential(prefix='')
self.output.add(nn.Flatten())
self.output.add(nn.Dense(
units=classes,
in_units=in_channels))
def hybrid_forward(self, F, x):
x = self.features(x)
x = self.output(x)
return x
def get_shufflenetv2b(width_scale,
shuffle_group_first=True,
model_name=None,
pretrained=False,
ctx=cpu(),
root=os.path.join('~', '.mxnet', 'models'),
**kwargs):
"""
Create ShuffleNetV2(b) model with specific parameters.
Parameters:
----------
width_scale : float
Scale factor for width of layers.
shuffle_group_first : bool, default True
Whether to use channel shuffle in group first mode.
model_name : str or None, default None
Model name for loading pretrained model.
pretrained : bool, default False
Whether to load the pretrained weights for model.
ctx : Context, default CPU
The context in which to load the pretrained weights.
root : str, default '~/.mxnet/models'
Location for keeping the model parameters.
"""
init_block_channels = 24
final_block_channels = 1024
layers = [4, 8, 4]
channels_per_layers = [116, 232, 464]
channels = [[ci] * li for (ci, li) in zip(channels_per_layers, layers)]
if width_scale != 1.0:
channels = [[int(cij * width_scale) for cij in ci] for ci in channels]
if width_scale > 1.5:
final_block_channels = int(final_block_channels * width_scale)
net = ShuffleNetV2b(
channels=channels,
init_block_channels=init_block_channels,
final_block_channels=final_block_channels,
shuffle_group_first=shuffle_group_first,
**kwargs)
if pretrained:
if (model_name is None) or (not model_name):
raise ValueError("Parameter `model_name` should be properly initialized for loading pretrained model.")
from .model_store import get_model_file
net.load_parameters(
filename=get_model_file(
model_name=model_name,
local_model_store_dir_path=root),
ctx=ctx)
return net
def shufflenetv2b_wd2(**kwargs):
"""
ShuffleNetV2(b) 0.5x model from 'ShuffleNet V2: Practical Guidelines for Efficient CNN Architecture Design,'
https://arxiv.org/abs/1807.11164.
Parameters:
----------
pretrained : bool, default False
Whether to load the pretrained weights for model.
ctx : Context, default CPU
The context in which to load the pretrained weights.
root : str, default '~/.mxnet/models'
Location for keeping the model parameters.
"""
return get_shufflenetv2b(
width_scale=(12.0 / 29.0),
shuffle_group_first=False,
model_name="shufflenetv2_wd2",
**kwargs)
def shufflenetv2b_w1(**kwargs):
"""
ShuffleNetV2(b) 1x model from 'ShuffleNet V2: Practical Guidelines for Efficient CNN Architecture Design,'
https://arxiv.org/abs/1807.11164.
Parameters:
----------
pretrained : bool, default False
Whether to load the pretrained weights for model.
ctx : Context, default CPU
The context in which to load the pretrained weights.
root : str, default '~/.mxnet/models'
Location for keeping the model parameters.
"""
return get_shufflenetv2b(
width_scale=1.0,
shuffle_group_first=False,
model_name="shufflenetv2_w1",
**kwargs)
def shufflenetv2b_w3d2(**kwargs):
"""
ShuffleNetV2(b) 1.5x model from 'ShuffleNet V2: Practical Guidelines for Efficient CNN Architecture Design,'
https://arxiv.org/abs/1807.11164.
Parameters:
----------
pretrained : bool, default False
Whether to load the pretrained weights for model.
ctx : Context, default CPU
The context in which to load the pretrained weights.
root : str, default '~/.mxnet/models'
Location for keeping the model parameters.
"""
return get_shufflenetv2b(
width_scale=(44.0 / 29.0),
shuffle_group_first=False,
model_name="shufflenetv2_w3d2",
**kwargs)
def shufflenetv2b_w2(**kwargs):
"""
ShuffleNetV2(b) 2x model from 'ShuffleNet V2: Practical Guidelines for Efficient CNN Architecture Design,'
https://arxiv.org/abs/1807.11164.
Parameters:
----------
pretrained : bool, default False
Whether to load the pretrained weights for model.
ctx : Context, default CPU
The context in which to load the pretrained weights.
root : str, default '~/.mxnet/models'
Location for keeping the model parameters.
"""
return get_shufflenetv2b(
width_scale=(61.0 / 29.0),
shuffle_group_first=False,
model_name="shufflenetv2_w2",
**kwargs)
def shufflenetv2c_wd2(**kwargs):
"""
ShuffleNetV2(c) 0.5x model from 'ShuffleNet V2: Practical Guidelines for Efficient CNN Architecture Design,'
https://arxiv.org/abs/1807.11164.
Parameters:
----------
pretrained : bool, default False
Whether to load the pretrained weights for model.
ctx : Context, default CPU
The context in which to load the pretrained weights.
root : str, default '~/.mxnet/models'
Location for keeping the model parameters.
"""
return get_shufflenetv2b(
width_scale=(12.0 / 29.0),
shuffle_group_first=True,
model_name="shufflenetv2_wd2",
**kwargs)
def _test():
import numpy as np
import mxnet as mx
pretrained = False
models = [
shufflenetv2b_wd2,
shufflenetv2b_w1,
shufflenetv2b_w3d2,
shufflenetv2b_w2,
shufflenetv2c_wd2,
]
for model in models:
net = model(pretrained=pretrained)
ctx = mx.cpu()
if not pretrained:
net.initialize(ctx=ctx)
# net.hybridize()
net_params = net.collect_params()
weight_count = 0
for param in net_params.values():
if (param.shape is None) or (not param._differentiable):
continue
weight_count += np.prod(param.shape)
print("m={}, {}".format(model.__name__, weight_count))
assert (model != shufflenetv2b_wd2 or weight_count == 1366792)
assert (model != shufflenetv2b_w1 or weight_count == 2279760)
assert (model != shufflenetv2b_w3d2 or weight_count == 4410194)
assert (model != shufflenetv2b_w2 or weight_count == 7611290)
assert (model != shufflenetv2c_wd2 or weight_count == 1366792)
x = mx.nd.zeros((1, 3, 224, 224), ctx=ctx)
y = net(x)
assert (y.shape == (1, 1000))
if __name__ == "__main__":
_test()
| [
"[email protected]"
] | |
4dd509a2a70827664579c9c6793d408263d2abd3 | 2c5101623d0e12e66afac57a5599e9b45c0e65f9 | /groupchat/venv/lib/python3.5/site-packages/django_eventstream/utils.py | ba6393f92d586c4bd344bd993ef41d2e8409420c | [] | no_license | shushantkumar/chatapp-django-channels | bc40aa600a6a59c379d6f5b987ddfae71abb5dad | 6ec71d87134615769025ec9cc18da9d614d1d499 | refs/heads/master | 2020-03-17T23:10:36.280696 | 2018-05-24T05:08:06 | 2018-05-24T05:08:06 | 134,034,469 | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 3,775 | py | import json
import threading
import importlib
import six
from werkzeug.http import parse_options_header
from django.conf import settings
from django.http import HttpResponse
from django.core.serializers.json import DjangoJSONEncoder
from gripcontrol import HttpStreamFormat
from django_grip import publish
try:
from urllib import quote
except ImportError:
from urllib.parse import quote
tlocal = threading.local()
# return dict of (channel, last-id)
def parse_grip_last(s):
parsed = parse_options_header(s, multiple=True)
out = {}
for n in range(0, len(parsed), 2):
channel = parsed[n]
params = parsed[n + 1]
last_id = params.get('last-id')
if last_id is None:
raise ValueError('channel "%s" has no last-id param' % channel)
out[channel] = last_id
return out
# return dict of (channel, last-id)
def parse_last_event_id(s):
out = {}
parts = s.split(',')
for part in parts:
channel, last_id = part.split(':')
out[channel] = last_id
return out
def make_id(ids):
id_parts = []
for channel, id in six.iteritems(ids):
enc_channel = quote(channel)
id_parts.append('%s:%s' % (enc_channel, id))
return ','.join(id_parts)
def build_id_escape(s):
out = ''
for c in s:
if c == '%':
out += '%%'
else:
out += c
return out
def sse_encode_event(event_type, data, event_id=None, escape=False):
data_str = json.dumps(data, cls=DjangoJSONEncoder)
if escape:
event_type = build_id_escape(event_type)
data_str = build_id_escape(data_str)
out = 'event: %s\n' % event_type
if event_id:
out += 'id: %s\n' % event_id
out += 'data: %s\n\n' % data_str
return out
def sse_error_response(condition, text, extra={}):
data = {'condition': condition, 'text': text}
for k, v in six.iteritems(extra):
data[k] = v
body = sse_encode_event('stream-error', data, event_id='error')
return HttpResponse(body, content_type='text/event-stream')
def publish_event(channel, event_type, data, pub_id, pub_prev_id,
skip_user_ids=[]):
content_filters = []
if pub_id:
event_id = '%I'
content_filters.append('build-id')
else:
event_id = None
content = sse_encode_event(event_type, data, event_id=event_id, escape=bool(pub_id))
meta = {}
if skip_user_ids:
meta['skip_users'] = ','.join(skip_user_ids)
publish(
'events-%s' % quote(channel),
HttpStreamFormat(content, content_filters=content_filters),
id=pub_id,
prev_id=pub_prev_id,
meta=meta)
def publish_kick(user_id, channel):
msg = 'Permission denied to channels: %s' % channel
data = {'condition': 'forbidden', 'text': msg, 'channels': [channel]}
content = sse_encode_event('stream-error', data, event_id='error')
meta = {'require_sub': 'events-%s' % channel}
publish(
'user-%s' % user_id,
HttpStreamFormat(content),
id='kick-1',
meta=meta)
publish(
'user-%s' % user_id,
HttpStreamFormat(close=True),
id='kick-2',
prev_id='kick-1',
meta=meta)
def load_class(name):
at = name.rfind('.')
if at == -1:
raise ValueError('class name contains no \'.\'')
module_name = name[0:at]
class_name = name[at + 1:]
return getattr(importlib.import_module(module_name), class_name)()
# load and keep in thread local storage
def get_class(name):
if not hasattr(tlocal, 'loaded'):
tlocal.loaded = {}
c = tlocal.loaded.get(name)
if c is None:
c = load_class(name)
tlocal.loaded[name] = c
return c
def get_class_from_setting(setting_name, default=None):
if hasattr(settings, setting_name):
return get_class(getattr(settings, setting_name))
elif default:
return get_class(default)
else:
return None
def get_storage():
return get_class_from_setting('EVENTSTREAM_STORAGE_CLASS')
def get_channelmanager():
return get_class_from_setting(
'EVENTSTREAM_CHANNELMANAGER_CLASS',
'django_eventstream.channelmanager.DefaultChannelManager')
| [
"[email protected]"
] | |
84a39c8aaf12aacc8a293f5f75b629488250d112 | 2f585ef7bc7293ea5f8652e1ebdf4c2f337dfa61 | /analysis/scripts/make_table.py | a0f1441aa8f897dae02dfd2279c7f69cb6764a76 | [
"LicenseRef-scancode-unknown-license-reference",
"MIT"
] | permissive | pedogski/TCPDBench | fe874faeb3dca355a766a425e8a78abb53a91456 | 83c992bf510291dc2cb21ca82fca4642afda9fb7 | refs/heads/master | 2023-08-17T13:06:54.417192 | 2021-10-12T09:21:53 | 2021-10-12T09:21:53 | null | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 13,043 | py | #!/usr/bin/env python
# -*- coding: utf-8 -*-
"""
Script to generate tables from summary files
Metrics, experiments, methods, and datasets are hard-coded as a means of
validation.
For the "best" experiment, the RBOCPDMS method is excluded because it fails too
often. For the other experiments, datasets with incomplete results are removed.
Author: G.J.J. van den Burg
Copyright (c) 2020 - The Alan Turing Institute
License: See the LICENSE file.
"""
import argparse
import colorama
import json
import os
import sys
import termcolor
from enum import Enum
from typing import Optional
# from pydantic.dataclasses import dataclass
from dataclasses import dataclass
from latex import build_latex_table
colorama.init()
class Metric(Enum):
f1 = "f1"
cover = "cover"
precision = "precision"
recall = "recall"
class Experiment(Enum):
default = "default"
best = "best"
class Dataset(Enum):
apple = "apple"
bank = "bank"
bee_waggle_6 = "bee_waggle_6"
bitcoin = "bitcoin"
brent_spot = "brent_spot"
businv = "businv"
centralia = "centralia"
children_per_woman = "children_per_woman"
co2_canada = "co2_canada"
construction = "construction"
debt_ireland = "debt_ireland"
gdp_argentina = "gdp_argentina"
gdp_croatia = "gdp_croatia"
gdp_iran = "gdp_iran"
gdp_japan = "gdp_japan"
global_co2 = "global_co2"
homeruns = "homeruns"
iceland_tourism = "iceland_tourism"
jfk_passengers = "jfk_passengers"
lga_passengers = "lga_passengers"
nile = "nile"
occupancy = "occupancy"
ozone = "ozone"
quality_control_1 = "quality_control_1"
quality_control_2 = "quality_control_2"
quality_control_3 = "quality_control_3"
quality_control_4 = "quality_control_4"
quality_control_5 = "quality_control_5"
rail_lines = "rail_lines"
ratner_stock = "ratner_stock"
robocalls = "robocalls"
run_log = "run_log"
scanline_126007 = "scanline_126007"
scanline_42049 = "scanline_42049"
seatbelts = "seatbelts"
shanghai_license = "shanghai_license"
uk_coal_employ = "uk_coal_employ"
measles = "measles"
unemployment_nl = "unemployment_nl"
us_population = "us_population"
usd_isk = "usd_isk"
well_log = "well_log"
class Method(Enum):
amoc = "amoc"
binseg = "binseg"
bocpd = "bocpd"
bocpdms = "bocpdms"
cpnp = "cpnp"
ecp = "ecp"
kcpa = "kcpa"
pelt = "pelt"
prophet = "prophet"
rbocpdms = "rbocpdms"
rfpop = "rfpop"
segneigh = "segneigh"
wbs = "wbs"
zero = "zero"
# Methods that support multidimensional datasets
MULTIMETHODS = [
Method.bocpd,
Method.bocpdms,
Method.ecp,
Method.kcpa,
Method.rbocpdms,
Method.zero,
]
# Multidimensional datasets
MULTIDATASETS = [
Dataset.apple,
Dataset.bee_waggle_6,
Dataset.occupancy,
Dataset.run_log,
]
# Datasets with missing values
MISSING_DATASETS = [Dataset.uk_coal_employ]
# Methods that handle missing values
MISSING_METHODS = [
Method.bocpdms,
Method.ecp,
Method.kcpa,
Method.prophet,
Method.zero,
]
@dataclass
class Result:
dataset: Dataset
experiment: Experiment
is_multidim: bool
method: Method
metric: Metric
score: Optional[float]
summary_file: str
placeholder: Optional[str]
def parse_args():
parser = argparse.ArgumentParser()
parser.add_argument(
"-s",
"--summary-dir",
help="Directory with summary files",
required=True,
)
parser.add_argument(
"-m",
"--metric",
help="Metric to use for the table",
choices=["f1", "cover", "precision", "recall"],
required=True,
)
parser.add_argument(
"-e",
"--experiment",
help="Experiment to make table for",
choices=["best", "default"],
required=True,
)
parser.add_argument(
"-d",
"--dim",
help="Dimensionality",
choices=["uni", "multi", "combined"],
required=True,
)
parser.add_argument(
"-f",
"--format",
help="Output format",
choices=["json", "tex"],
required=True,
)
parser.add_argument(
"-t",
"--type",
help="Type of table to make",
choices=["avg", "full"],
required=True,
)
return parser.parse_args()
def warning(msg):
termcolor.cprint(msg, "yellow", file=sys.stderr)
def load_summary(filename):
with open(filename, "r") as fp:
data = json.load(fp)
return data
def extract_score(method_results, metric=None, experiment=None):
"""Extract a single numeric score from a list of dictionaries"""
if not isinstance(metric, Metric):
raise ValueError("Unknown metric: %s" % metric)
if not experiment in ["default", "best"]:
raise ValueError("Unknown experiment: %s" % experiment)
# Collect all values for the chosen metric
scores = []
for result in method_results:
if not result["status"] == "SUCCESS":
continue
scores.append(result["scores"][metric.name])
if len(scores) == 0:
return None
# check that we have only one score for the 'default' experiment
if experiment == "default":
if len(scores) > 1:
raise ValueError("Default experiment with more than one score!")
return scores[0]
return max(scores)
def collect_results(summary_dir=None, metric=None, experiment=None):
"""Collect the results for the experiment on the specified metric.
Returns a list of Result objects.
"""
if not isinstance(metric, Metric):
raise ValueError("Unknown metric: %s" % metric)
if not experiment in ["default", "best"]:
raise ValueError("Unknown experiment: %s" % experiment)
if not os.path.isdir(summary_dir):
raise FileNotFoundError(summary_dir)
results = []
for fname in sorted(os.listdir(summary_dir)):
path = os.path.join(summary_dir, fname)
summary_data = load_summary(path)
dataset_name = summary_data["dataset"]
summary_results = summary_data["results"]
is_multi = summary_data["dataset_ndim"] > 1
for method in summary_results:
# method names are prefixed with the experiment type, so we skip
# the ones we don't want
if not method.startswith(experiment + "_"):
continue
# extract the metric score for this experiment from the summary
# results for the method
score = extract_score(
summary_results[method], metric=metric, experiment=experiment
)
# strip the experiment from the method name
method_name = method[len(experiment + "_") :]
# determine the placeholder value if there is no score.
placeholder = set()
if score is None:
if (Dataset(dataset_name) in MISSING_DATASETS) and (
not Method(method_name) in MISSING_METHODS
):
# dataset has missing values and method can't handle it
placeholder.add("M")
else:
for result in summary_results[method]:
if result["status"] == "FAIL":
placeholder.add("F")
elif result["status"] == "TIMEOUT":
placeholder.add("T")
placeholder = "/".join(sorted(placeholder))
# create a Result object
res = Result(
dataset=Dataset(dataset_name),
experiment=Experiment(experiment),
is_multidim=is_multi,
method=Method(method_name),
metric=Metric(metric),
score=score,
summary_file=fname,
placeholder=placeholder or None,
)
results.append(res)
return results
def average_results(results):
"""Average the results
NOTE: This function filters out some methods/datasets for which we have
insufficient results.
"""
experiment = list(set(r.experiment for r in results))[0]
# determine if we're dealing with multidimensional datasets
is_multi = all(r.is_multidim for r in results)
expected_methods = MULTIMETHODS if is_multi else list(Method)
# keep only expected methods
results = list(filter(lambda r: r.method in expected_methods, results))
# remove RBOCPDMS for 'best', because it fails too often
if experiment == Experiment.best:
warning(
"\nWarning: Removing RBOCPDMS (experiment = %s) due to insufficient results\n"
% experiment
)
results = list(filter(lambda r: r.method != Method.rbocpdms, results))
expected_methods.remove(Method.rbocpdms)
# remove datasets for which we do not have complete results
to_remove = []
for dataset in set(r.dataset for r in results):
dset_results = filter(lambda r: r.dataset == dataset, results)
if any(r.score is None for r in dset_results):
to_remove.append(dataset)
if to_remove:
warning(
"\nWarning: Filtering out datasets: %r due to incomplete results for some detectors.\n"
% to_remove
)
results = list(filter(lambda r: not r.dataset in to_remove, results))
# check that we are now complete: for all datasets and all methods in the
# remaining results, we have a non-None score.
assert all(r.score is not None for r in results)
# compute the average per method
methods = set(r.method for r in results)
avg = {}
for method in methods:
method_scores = [r.score for r in results if r.method == method]
avg_score = sum(method_scores) / len(method_scores)
avg[method.name] = avg_score
return avg
def write_json(results, is_avg=None):
if not is_avg in [True, False]:
raise ValueError("is_avg should be either True or False")
output = {}
if is_avg:
output = results
else:
datasets = set(r.dataset for r in results)
methods = set(r.method for r in results)
for d in datasets:
output[d.name] = {}
for m in methods:
r = next(
(r for r in results if r.dataset == d and r.method == m),
None,
)
# intended to fail if r is None, because that shouldn't happen
output[d.name][m.name] = r.score
print(json.dumps(output, indent="\t", sort_keys=True))
def write_latex(results, dim=None, is_avg=None):
if is_avg:
raise NotImplementedError(
"write_latex is not supported for is_avg = True"
)
methods = sorted(set(r.method.name for r in results))
datasets = sorted(set(r.dataset.name for r in results))
if dim == "combined":
uni_datasets = [
d.name for d in list(Dataset) if not d in MULTIDATASETS
]
multi_datasets = [d.name for d in MULTIDATASETS]
datasets = sorted(uni_datasets) + sorted(multi_datasets)
first_multi = sorted(multi_datasets)[0]
textsc = lambda m: "\\textsc{%s}" % m
verb = lambda m: "\\verb+%s+" % m
headers = ["Dataset"] + list(map(textsc, methods))
table = []
for dataset in datasets:
row = [verb(dataset)]
d = Dataset(dataset)
for method in methods:
m = Method(method)
r = next((r for r in results if r.method == m and r.dataset == d))
row.append(r.placeholder if r.score is None else r.score)
table.append(row)
spec = "l" + "c" * len(methods)
tex = build_latex_table(table, headers, floatfmt=".3f", table_spec=spec)
if dim == "combined":
# add a horizontal line for these datasets
lines = tex.split("\n")
newlines = []
for line in lines:
if line.startswith(verb(first_multi)):
newlines.append("\\hline")
newlines.append(line)
tex = "\n".join(newlines)
print(tex)
def main():
args = parse_args()
if args.type == "avg" and args.dim == "combined":
raise ValueError("Using 'avg' and 'combined' is not supported.")
results = collect_results(
summary_dir=args.summary_dir,
metric=Metric(args.metric),
experiment=args.experiment,
)
if args.dim == "uni":
# filter out multi
results = list(filter(lambda r: not r.is_multidim, results))
elif args.dim == "multi":
# filter out uni
results = list(filter(lambda r: r.is_multidim, results))
if args.type == "avg":
results = average_results(results)
if args.format == "json":
write_json(results, is_avg=args.type == "avg")
else:
write_latex(results, args.dim, is_avg=args.type == "avg")
if __name__ == "__main__":
main()
| [
"[email protected]"
] | |
bb92a4fbe5cfa6ba62e826caf72954a732bb9e22 | 9743d5fd24822f79c156ad112229e25adb9ed6f6 | /xai/brain/wordbase/otherforms/_emasculates.py | a1b9e9f4cad8bf9f0e90f0b93fdf68dd57c412e6 | [
"MIT"
] | permissive | cash2one/xai | de7adad1758f50dd6786bf0111e71a903f039b64 | e76f12c9f4dcf3ac1c7c08b0cc8844c0b0a104b6 | refs/heads/master | 2021-01-19T12:33:54.964379 | 2017-01-28T02:00:50 | 2017-01-28T02:00:50 | null | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 238 | py |
#calss header
class _EMASCULATES():
def __init__(self,):
self.name = "EMASCULATES"
self.definitions = emasculate
self.parents = []
self.childen = []
self.properties = []
self.jsondata = {}
self.basic = ['emasculate']
| [
"[email protected]"
] | |
af77c1523d4d9b222680e0262c87780f066ae5fe | cabdd862b94cb37924c9b73bdab3a7a6f72f3506 | /bin/annex-passport | 369183ab4d99e6308eb46bf51615549b2ce55766 | [
"Unlicense"
] | permissive | umeboshi2/dotfiles | 313114284e300f552a5e77b1ef8c9bb34833caae | 8aa56f93bd4efc1beaa56762d286450a453a9e58 | refs/heads/master | 2023-01-14T03:51:51.055141 | 2021-02-17T23:40:37 | 2021-02-17T23:40:37 | 18,471,913 | 0 | 2 | Unlicense | 2022-12-26T21:34:27 | 2014-04-05T17:18:31 | Emacs Lisp | UTF-8 | Python | false | false | 1,421 | #!/usr/bin/env python
import os, sys
import subprocess
import argparse
# a simple script to mount and unmount removable passport
# drive in annex chroot.
passport_mediapath = 'media/umeboshi/passport'
annex_chroot = '/var/lib/schroot/mount/annex'
main_mntpt = os.path.join('/', passport_mediapath)
annex_passport = os.path.join(annex_chroot, passport_mediapath)
def is_passport_mounted():
return annex_passport in file('/proc/mounts').read()
def mount_passport():
if is_passport_mounted():
raise RuntimeError, "Passport already mounted"
cmd = ['sudo', 'mount', '--bind', main_mntpt, annex_passport]
subprocess.check_call(cmd)
def umount_passport():
if not is_passport_mounted():
raise RuntimeError, "Passport not mounted"
cmd = ['sudo', 'umount', annex_passport]
subprocess.check_call(cmd)
if is_passport_mounted():
raise RuntimeError, "Passport still mounted"
parser = argparse.ArgumentParser()
parser.add_argument('command', default=None, nargs="?")
args = parser.parse_args()
ACTIONFUN = dict(mount=mount_passport, umount=umount_passport)
command = args.command
if command is None:
if is_passport_mounted():
command = 'umount'
else:
command = 'mount'
if command not in ACTIONFUN:
raise RuntimeError, "Unknown command: %s" % command
#print "command", command
ACTIONFUN[command]()
print "Annex %sed." % command
| [
"[email protected]"
] | ||
5c5af60f08a45be2f0a6f513e183bbdc40939bc8 | e49b42e65ba76397833c6f3ba839871a8d05a5ac | /xbmc-mocks/xbmcgui.py | 8601840cbf172be2bed060dacb15983b9aa6bf6e | [] | no_license | HenrikDK/xbmc-simple-downloader | f4af2ab94ade858256131f893c988b5d2c19866b | 3189d75c615f3ddbe1d02c29159fc6d31ca51fde | refs/heads/master | 2020-04-27T23:02:14.181932 | 2013-01-18T00:13:55 | 2013-01-18T00:13:55 | 7,434,903 | 1 | 2 | null | 2022-09-07T19:29:38 | 2013-01-04T03:53:20 | Python | UTF-8 | Python | false | false | 183,257 | py | class Action:
"""Action class.
For backwards compatibility reasons the == operator is extended so that itcan compare an action with other actions and action.GetID() with numbers example: (action == ACTION_MOVE_LEFT)
"""
def __delattr__(*args):
"""x.__delattr__('name') <==> del x.name
"""
def __eq__(*args):
"""x.__eq__(y) <==> x==y
"""
def __format__(*args):
"""default object formatter
"""
def __ge__(*args):
"""x.__ge__(y) <==> x>=y
"""
def __getattribute__(*args):
"""x.__getattribute__('name') <==> x.name
"""
def __gt__(*args):
"""x.__gt__(y) <==> x>y
"""
def __hash__(*args):
"""x.__hash__() <==> hash(x)
"""
def __init__(*args):
"""x.__init__(...) initializes x; see x.__class__.__doc__ for signature
"""
def __le__(*args):
"""x.__le__(y) <==> x<=y
"""
def __lt__(*args):
"""x.__lt__(y) <==> x<y
"""
def __ne__(*args):
"""x.__ne__(y) <==> x!=y
"""
def __new__(*args):
"""T.__new__(S, ...) -> a new object with type S, a subtype of T
"""
def __reduce__(*args):
"""helper for pickle
"""
def __reduce_ex__(*args):
"""helper for pickle
"""
def __repr__(*args):
"""x.__repr__() <==> repr(x)
"""
def __setattr__(*args):
"""x.__setattr__('name', value) <==> x.name = value
"""
def __sizeof__(*args):
"""__sizeof__() -> size of object in memory, in bytes
"""
def __str__(*args):
"""x.__str__() <==> str(x)
"""
def __subclasshook__(*args):
"""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).
"""
def getAmount1(*args):
"""getAmount1() -- Returns the first amount of force applied to the thumbstick n.
"""
def getAmount2(*args):
"""getAmount2() -- Returns the second amount of force applied to the thumbstick n.
"""
def getButtonCode(*args):
"""getButtonCode() -- Returns the button code for this action.
"""
def getId(*args):
"""getId() -- Returns the action's current id as a long or 0 if no action is mapped in the xml's.
"""
class ControlButton:
"""ControlButton class.
ControlButton(x, y, width, height, label[, focusTexture, noFocusTexture, textOffsetX, textOffsetY,
alignment, font, textColor, disabledColor, angle, shadowColor, focusedColor])
x : integer - x coordinate of control.
y : integer - y coordinate of control.
width : integer - width of control.
height : integer - height of control.
label : string or unicode - text string.
focusTexture : [opt] string - filename for focus texture.
noFocusTexture : [opt] string - filename for no focus texture.
textOffsetX : [opt] integer - x offset of label.
textOffsetY : [opt] integer - y offset of label.
alignment : [opt] integer - alignment of label - *Note, see xbfont.h
font : [opt] string - font used for label text. (e.g. 'font13')
textColor : [opt] hexstring - color of enabled button's label. (e.g. '0xFFFFFFFF')
disabledColor : [opt] hexstring - color of disabled button's label. (e.g. '0xFFFF3300')
angle : [opt] integer - angle of control. (+ rotates CCW, - rotates CW)
shadowColor : [opt] hexstring - color of button's label's shadow. (e.g. '0xFF000000')
focusedColor : [opt] hexstring - color of focused button's label. (e.g. '0xFF00FFFF')
*Note, You can use the above as keywords for arguments and skip certain optional arguments.
Once you use a keyword, all following arguments require the keyword.
After you create the control, you need to add it to the window with addControl().
example:
- self.button = xbmcgui.ControlButton(100, 250, 200, 50, 'Status', font='font14')
"""
def __cmp__(*args):
"""x.__cmp__(y) <==> cmp(x,y)
"""
def __delattr__(*args):
"""x.__delattr__('name') <==> del x.name
"""
def __format__(*args):
"""default object formatter
"""
def __getattribute__(*args):
"""x.__getattribute__('name') <==> x.name
"""
def __hash__(*args):
"""x.__hash__() <==> hash(x)
"""
def __init__(*args):
"""x.__init__(...) initializes x; see x.__class__.__doc__ for signature
"""
def __new__(*args):
"""T.__new__(S, ...) -> a new object with type S, a subtype of T
"""
def __reduce__(*args):
"""helper for pickle
"""
def __reduce_ex__(*args):
"""helper for pickle
"""
def __repr__(*args):
"""x.__repr__() <==> repr(x)
"""
def __setattr__(*args):
"""x.__setattr__('name', value) <==> x.name = value
"""
def __sizeof__(*args):
"""__sizeof__() -> size of object in memory, in bytes
"""
def __str__(*args):
"""x.__str__() <==> str(x)
"""
def __subclasshook__(*args):
"""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).
"""
def controlDown(*args):
"""controlDown(control) -- Set's the controls down navigation.
control : control object - control to navigate to on down.
*Note, You can also use setNavigation(). Set to self to disable navigation.
Throws: TypeError, if one of the supplied arguments is not a control type.
ReferenceError, if one of the controls is not added to a window.
example:
- self.button.controlDown(self.button1)
"""
def controlLeft(*args):
"""controlLeft(control) -- Set's the controls left navigation.
control : control object - control to navigate to on left.
*Note, You can also use setNavigation(). Set to self to disable navigation.
Throws: TypeError, if one of the supplied arguments is not a control type.
ReferenceError, if one of the controls is not added to a window.
example:
- self.button.controlLeft(self.button1)
"""
def controlRight(*args):
"""controlRight(control) -- Set's the controls right navigation.
control : control object - control to navigate to on right.
*Note, You can also use setNavigation(). Set to self to disable navigation.
Throws: TypeError, if one of the supplied arguments is not a control type.
ReferenceError, if one of the controls is not added to a window.
example:
- self.button.controlRight(self.button1)
"""
def controlUp(*args):
"""controlUp(control) -- Set's the controls up navigation.
control : control object - control to navigate to on up.
*Note, You can also use setNavigation(). Set to self to disable navigation.
Throws: TypeError, if one of the supplied arguments is not a control type.
ReferenceError, if one of the controls is not added to a window.
example:
- self.button.controlUp(self.button1)
"""
def getHeight(*args):
"""getHeight() -- Returns the control's current height as an integer.
example:
- height = self.button.getHeight()
"""
def getId(*args):
"""getId() -- Returns the control's current id as an integer.
example:
- id = self.button.getId()
"""
def getLabel(*args):
"""getLabel() -- Returns the buttons label as a unicode string.
example:
- label = self.button.getLabel()
"""
def getLabel2(*args):
"""getLabel2() -- Returns the buttons label2 as a unicode string.
example:
- label = self.button.getLabel2()
"""
def getPosition(*args):
"""getPosition() -- Returns the control's current position as a x,y integer tuple.
example:
- pos = self.button.getPosition()
"""
def getWidth(*args):
"""getWidth() -- Returns the control's current width as an integer.
example:
- width = self.button.getWidth()
"""
def setAnimations(*args):
"""setAnimations([(event, attr,)*]) -- Set's the control's animations.
[(event,attr,)*] : list - A list of tuples consisting of event and attributes pairs.
- event : string - The event to animate.
- attr : string - The whole attribute string separated by spaces.
Animating your skin - http://wiki.xbmc.org/?title=Animating_Your_Skin
example:
- self.button.setAnimations([('focus', 'effect=zoom end=90,247,220,56 time=0',)])
"""
def setDisabledColor(*args):
"""setDisabledColor(disabledColor) -- Set's this buttons disabled color.
disabledColor : hexstring - color of disabled button's label. (e.g. '0xFFFF3300')
example:
- self.button.setDisabledColor('0xFFFF3300')
"""
def setEnableCondition(*args):
"""setEnableCondition(enable) -- Set's the control's enabled condition.
Allows XBMC to control the enabled status of the control.
enable : string - Enable condition.
List of Conditions - http://wiki.xbmc.org/index.php?title=List_of_Boolean_Conditions
example:
- self.button.setEnableCondition('System.InternetState')
"""
def setEnabled(*args):
"""setEnabled(enabled) -- Set's the control's enabled/disabled state.
enabled : bool - True=enabled / False=disabled.
example:
- self.button.setEnabled(False)
"""
def setHeight(*args):
"""setHeight(height) -- Set's the controls height.
height : integer - height of control.
example:
- self.image.setHeight(100)
"""
def setLabel(*args):
"""setLabel([label, font, textColor, disabledColor, shadowColor, focusedColor]) -- Set's this buttons text attributes.
label : [opt] string or unicode - text string.
font : [opt] string - font used for label text. (e.g. 'font13')
textColor : [opt] hexstring - color of enabled button's label. (e.g. '0xFFFFFFFF')
disabledColor : [opt] hexstring - color of disabled button's label. (e.g. '0xFFFF3300')
shadowColor : [opt] hexstring - color of button's label's shadow. (e.g. '0xFF000000')
focusedColor : [opt] hexstring - color of focused button's label. (e.g. '0xFFFFFF00')
label2 : [opt] string or unicode - text string.
*Note, You can use the above as keywords for arguments and skip certain optional arguments.
Once you use a keyword, all following arguments require the keyword.
example:
- self.button.setLabel('Status', 'font14', '0xFFFFFFFF', '0xFFFF3300', '0xFF000000')
"""
def setNavigation(*args):
"""setNavigation(up, down, left, right) -- Set's the controls navigation.
up : control object - control to navigate to on up.
down : control object - control to navigate to on down.
left : control object - control to navigate to on left.
right : control object - control to navigate to on right.
*Note, Same as controlUp(), controlDown(), controlLeft(), controlRight().
Set to self to disable navigation for that direction.
Throws: TypeError, if one of the supplied arguments is not a control type.
ReferenceError, if one of the controls is not added to a window.
example:
- self.button.setNavigation(self.button1, self.button2, self.button3, self.button4)
"""
def setPosition(*args):
"""setPosition(x, y) -- Set's the controls position.
x : integer - x coordinate of control.
y : integer - y coordinate of control.
*Note, You may use negative integers. (e.g sliding a control into view)
example:
- self.button.setPosition(100, 250)
"""
def setVisible(*args):
"""setVisible(visible) -- Set's the control's visible/hidden state.
visible : bool - True=visible / False=hidden.
example:
- self.button.setVisible(False)
"""
def setVisibleCondition(*args):
"""setVisibleCondition(visible[,allowHiddenFocus]) -- Set's the control's visible condition.
Allows XBMC to control the visible status of the control.
visible : string - Visible condition.
allowHiddenFocus : bool - True=gains focus even if hidden.
List of Conditions - http://wiki.xbmc.org/index.php?title=List_of_Boolean_Conditions
example:
- self.button.setVisibleCondition('[Control.IsVisible(41) + !Control.IsVisible(12)]', True)
"""
def setWidth(*args):
"""setWidth(width) -- Set's the controls width.
width : integer - width of control.
example:
- self.image.setWidth(100)
"""
class ControlCheckMark:
"""ControlCheckMark class.
ControlCheckMark(x, y, width, height, label[, focusTexture, noFocusTexture,
checkWidth, checkHeight, alignment, font, textColor, disabledColor])
x : integer - x coordinate of control.
y : integer - y coordinate of control.
width : integer - width of control.
height : integer - height of control.
label : string or unicode - text string.
focusTexture : [opt] string - filename for focus texture.
noFocusTexture : [opt] string - filename for no focus texture.
checkWidth : [opt] integer - width of checkmark.
checkHeight : [opt] integer - height of checkmark.
alignment : [opt] integer - alignment of label - *Note, see xbfont.h
font : [opt] string - font used for label text. (e.g. 'font13')
textColor : [opt] hexstring - color of enabled checkmark's label. (e.g. '0xFFFFFFFF')
disabledColor : [opt] hexstring - color of disabled checkmark's label. (e.g. '0xFFFF3300')
*Note, You can use the above as keywords for arguments and skip certain optional arguments.
Once you use a keyword, all following arguments require the keyword.
After you create the control, you need to add it to the window with addControl().
example:
- self.checkmark = xbmcgui.ControlCheckMark(100, 250, 200, 50, 'Status', font='font14')
"""
def __cmp__(*args):
"""x.__cmp__(y) <==> cmp(x,y)
"""
def __delattr__(*args):
"""x.__delattr__('name') <==> del x.name
"""
def __format__(*args):
"""default object formatter
"""
def __getattribute__(*args):
"""x.__getattribute__('name') <==> x.name
"""
def __hash__(*args):
"""x.__hash__() <==> hash(x)
"""
def __init__(*args):
"""x.__init__(...) initializes x; see x.__class__.__doc__ for signature
"""
def __new__(*args):
"""T.__new__(S, ...) -> a new object with type S, a subtype of T
"""
def __reduce__(*args):
"""helper for pickle
"""
def __reduce_ex__(*args):
"""helper for pickle
"""
def __repr__(*args):
"""x.__repr__() <==> repr(x)
"""
def __setattr__(*args):
"""x.__setattr__('name', value) <==> x.name = value
"""
def __sizeof__(*args):
"""__sizeof__() -> size of object in memory, in bytes
"""
def __str__(*args):
"""x.__str__() <==> str(x)
"""
def __subclasshook__(*args):
"""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).
"""
def controlDown(*args):
"""controlDown(control) -- Set's the controls down navigation.
control : control object - control to navigate to on down.
*Note, You can also use setNavigation(). Set to self to disable navigation.
Throws: TypeError, if one of the supplied arguments is not a control type.
ReferenceError, if one of the controls is not added to a window.
example:
- self.button.controlDown(self.button1)
"""
def controlLeft(*args):
"""controlLeft(control) -- Set's the controls left navigation.
control : control object - control to navigate to on left.
*Note, You can also use setNavigation(). Set to self to disable navigation.
Throws: TypeError, if one of the supplied arguments is not a control type.
ReferenceError, if one of the controls is not added to a window.
example:
- self.button.controlLeft(self.button1)
"""
def controlRight(*args):
"""controlRight(control) -- Set's the controls right navigation.
control : control object - control to navigate to on right.
*Note, You can also use setNavigation(). Set to self to disable navigation.
Throws: TypeError, if one of the supplied arguments is not a control type.
ReferenceError, if one of the controls is not added to a window.
example:
- self.button.controlRight(self.button1)
"""
def controlUp(*args):
"""controlUp(control) -- Set's the controls up navigation.
control : control object - control to navigate to on up.
*Note, You can also use setNavigation(). Set to self to disable navigation.
Throws: TypeError, if one of the supplied arguments is not a control type.
ReferenceError, if one of the controls is not added to a window.
example:
- self.button.controlUp(self.button1)
"""
def getHeight(*args):
"""getHeight() -- Returns the control's current height as an integer.
example:
- height = self.button.getHeight()
"""
def getId(*args):
"""getId() -- Returns the control's current id as an integer.
example:
- id = self.button.getId()
"""
def getPosition(*args):
"""getPosition() -- Returns the control's current position as a x,y integer tuple.
example:
- pos = self.button.getPosition()
"""
def getSelected(*args):
"""getSelected() -- Returns the selected status for this checkmark as a bool.
example:
- selected = self.checkmark.getSelected()
"""
def getWidth(*args):
"""getWidth() -- Returns the control's current width as an integer.
example:
- width = self.button.getWidth()
"""
def setAnimations(*args):
"""setAnimations([(event, attr,)*]) -- Set's the control's animations.
[(event,attr,)*] : list - A list of tuples consisting of event and attributes pairs.
- event : string - The event to animate.
- attr : string - The whole attribute string separated by spaces.
Animating your skin - http://wiki.xbmc.org/?title=Animating_Your_Skin
example:
- self.button.setAnimations([('focus', 'effect=zoom end=90,247,220,56 time=0',)])
"""
def setDisabledColor(*args):
"""setDisabledColor(disabledColor) -- Set's this controls disabled color.
disabledColor : hexstring - color of disabled checkmark's label. (e.g. '0xFFFF3300')
example:
- self.checkmark.setDisabledColor('0xFFFF3300')
"""
def setEnableCondition(*args):
"""setEnableCondition(enable) -- Set's the control's enabled condition.
Allows XBMC to control the enabled status of the control.
enable : string - Enable condition.
List of Conditions - http://wiki.xbmc.org/index.php?title=List_of_Boolean_Conditions
example:
- self.button.setEnableCondition('System.InternetState')
"""
def setEnabled(*args):
"""setEnabled(enabled) -- Set's the control's enabled/disabled state.
enabled : bool - True=enabled / False=disabled.
example:
- self.button.setEnabled(False)
"""
def setHeight(*args):
"""setHeight(height) -- Set's the controls height.
height : integer - height of control.
example:
- self.image.setHeight(100)
"""
def setLabel(*args):
"""setLabel(label[, font, textColor, disabledColor]) -- Set's this controls text attributes.
label : string or unicode - text string.
font : [opt] string - font used for label text. (e.g. 'font13')
textColor : [opt] hexstring - color of enabled checkmark's label. (e.g. '0xFFFFFFFF')
disabledColor : [opt] hexstring - color of disabled checkmark's label. (e.g. '0xFFFF3300')
example:
- self.checkmark.setLabel('Status', 'font14', '0xFFFFFFFF', '0xFFFF3300')
"""
def setNavigation(*args):
"""setNavigation(up, down, left, right) -- Set's the controls navigation.
up : control object - control to navigate to on up.
down : control object - control to navigate to on down.
left : control object - control to navigate to on left.
right : control object - control to navigate to on right.
*Note, Same as controlUp(), controlDown(), controlLeft(), controlRight().
Set to self to disable navigation for that direction.
Throws: TypeError, if one of the supplied arguments is not a control type.
ReferenceError, if one of the controls is not added to a window.
example:
- self.button.setNavigation(self.button1, self.button2, self.button3, self.button4)
"""
def setPosition(*args):
"""setPosition(x, y) -- Set's the controls position.
x : integer - x coordinate of control.
y : integer - y coordinate of control.
*Note, You may use negative integers. (e.g sliding a control into view)
example:
- self.button.setPosition(100, 250)
"""
def setSelected(*args):
"""setSelected(isOn) -- Sets this checkmark status to on or off.
isOn : bool - True=selected (on) / False=not selected (off)
example:
- self.checkmark.setSelected(True)
"""
def setVisible(*args):
"""setVisible(visible) -- Set's the control's visible/hidden state.
visible : bool - True=visible / False=hidden.
example:
- self.button.setVisible(False)
"""
def setVisibleCondition(*args):
"""setVisibleCondition(visible[,allowHiddenFocus]) -- Set's the control's visible condition.
Allows XBMC to control the visible status of the control.
visible : string - Visible condition.
allowHiddenFocus : bool - True=gains focus even if hidden.
List of Conditions - http://wiki.xbmc.org/index.php?title=List_of_Boolean_Conditions
example:
- self.button.setVisibleCondition('[Control.IsVisible(41) + !Control.IsVisible(12)]', True)
"""
def setWidth(*args):
"""setWidth(width) -- Set's the controls width.
width : integer - width of control.
example:
- self.image.setWidth(100)
"""
class ControlFadeLabel:
"""ControlFadeLabel class.
Control that scroll's lables
ControlFadeLabel(x, y, width, height[, font, textColor, alignment])
x : integer - x coordinate of control.
y : integer - y coordinate of control.
width : integer - width of control.
height : integer - height of control.
font : [opt] string - font used for label text. (e.g. 'font13')
textColor : [opt] hexstring - color of fadelabel's labels. (e.g. '0xFFFFFFFF')
alignment : [opt] integer - alignment of label - *Note, see xbfont.h
*Note, You can use the above as keywords for arguments and skip certain optional arguments.
Once you use a keyword, all following arguments require the keyword.
After you create the control, you need to add it to the window with addControl().
example:
- self.fadelabel = xbmcgui.ControlFadeLabel(100, 250, 200, 50, textColor='0xFFFFFFFF')
"""
def __cmp__(*args):
"""x.__cmp__(y) <==> cmp(x,y)
"""
def __delattr__(*args):
"""x.__delattr__('name') <==> del x.name
"""
def __format__(*args):
"""default object formatter
"""
def __getattribute__(*args):
"""x.__getattribute__('name') <==> x.name
"""
def __hash__(*args):
"""x.__hash__() <==> hash(x)
"""
def __init__(*args):
"""x.__init__(...) initializes x; see x.__class__.__doc__ for signature
"""
def __new__(*args):
"""T.__new__(S, ...) -> a new object with type S, a subtype of T
"""
def __reduce__(*args):
"""helper for pickle
"""
def __reduce_ex__(*args):
"""helper for pickle
"""
def __repr__(*args):
"""x.__repr__() <==> repr(x)
"""
def __setattr__(*args):
"""x.__setattr__('name', value) <==> x.name = value
"""
def __sizeof__(*args):
"""__sizeof__() -> size of object in memory, in bytes
"""
def __str__(*args):
"""x.__str__() <==> str(x)
"""
def __subclasshook__(*args):
"""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).
"""
def addLabel(*args):
"""addLabel(label) -- Add a label to this control for scrolling.
label : string or unicode - text string.
example:
- self.fadelabel.addLabel('This is a line of text that can scroll.')
"""
def controlDown(*args):
"""controlDown(control) -- Set's the controls down navigation.
control : control object - control to navigate to on down.
*Note, You can also use setNavigation(). Set to self to disable navigation.
Throws: TypeError, if one of the supplied arguments is not a control type.
ReferenceError, if one of the controls is not added to a window.
example:
- self.button.controlDown(self.button1)
"""
def controlLeft(*args):
"""controlLeft(control) -- Set's the controls left navigation.
control : control object - control to navigate to on left.
*Note, You can also use setNavigation(). Set to self to disable navigation.
Throws: TypeError, if one of the supplied arguments is not a control type.
ReferenceError, if one of the controls is not added to a window.
example:
- self.button.controlLeft(self.button1)
"""
def controlRight(*args):
"""controlRight(control) -- Set's the controls right navigation.
control : control object - control to navigate to on right.
*Note, You can also use setNavigation(). Set to self to disable navigation.
Throws: TypeError, if one of the supplied arguments is not a control type.
ReferenceError, if one of the controls is not added to a window.
example:
- self.button.controlRight(self.button1)
"""
def controlUp(*args):
"""controlUp(control) -- Set's the controls up navigation.
control : control object - control to navigate to on up.
*Note, You can also use setNavigation(). Set to self to disable navigation.
Throws: TypeError, if one of the supplied arguments is not a control type.
ReferenceError, if one of the controls is not added to a window.
example:
- self.button.controlUp(self.button1)
"""
def getHeight(*args):
"""getHeight() -- Returns the control's current height as an integer.
example:
- height = self.button.getHeight()
"""
def getId(*args):
"""getId() -- Returns the control's current id as an integer.
example:
- id = self.button.getId()
"""
def getPosition(*args):
"""getPosition() -- Returns the control's current position as a x,y integer tuple.
example:
- pos = self.button.getPosition()
"""
def getWidth(*args):
"""getWidth() -- Returns the control's current width as an integer.
example:
- width = self.button.getWidth()
"""
def reset(*args):
"""reset() -- Clears this fadelabel.
example:
- self.fadelabel.reset()
"""
def setAnimations(*args):
"""setAnimations([(event, attr,)*]) -- Set's the control's animations.
[(event,attr,)*] : list - A list of tuples consisting of event and attributes pairs.
- event : string - The event to animate.
- attr : string - The whole attribute string separated by spaces.
Animating your skin - http://wiki.xbmc.org/?title=Animating_Your_Skin
example:
- self.button.setAnimations([('focus', 'effect=zoom end=90,247,220,56 time=0',)])
"""
def setEnableCondition(*args):
"""setEnableCondition(enable) -- Set's the control's enabled condition.
Allows XBMC to control the enabled status of the control.
enable : string - Enable condition.
List of Conditions - http://wiki.xbmc.org/index.php?title=List_of_Boolean_Conditions
example:
- self.button.setEnableCondition('System.InternetState')
"""
def setEnabled(*args):
"""setEnabled(enabled) -- Set's the control's enabled/disabled state.
enabled : bool - True=enabled / False=disabled.
example:
- self.button.setEnabled(False)
"""
def setHeight(*args):
"""setHeight(height) -- Set's the controls height.
height : integer - height of control.
example:
- self.image.setHeight(100)
"""
def setNavigation(*args):
"""setNavigation(up, down, left, right) -- Set's the controls navigation.
up : control object - control to navigate to on up.
down : control object - control to navigate to on down.
left : control object - control to navigate to on left.
right : control object - control to navigate to on right.
*Note, Same as controlUp(), controlDown(), controlLeft(), controlRight().
Set to self to disable navigation for that direction.
Throws: TypeError, if one of the supplied arguments is not a control type.
ReferenceError, if one of the controls is not added to a window.
example:
- self.button.setNavigation(self.button1, self.button2, self.button3, self.button4)
"""
def setPosition(*args):
"""setPosition(x, y) -- Set's the controls position.
x : integer - x coordinate of control.
y : integer - y coordinate of control.
*Note, You may use negative integers. (e.g sliding a control into view)
example:
- self.button.setPosition(100, 250)
"""
def setVisible(*args):
"""setVisible(visible) -- Set's the control's visible/hidden state.
visible : bool - True=visible / False=hidden.
example:
- self.button.setVisible(False)
"""
def setVisibleCondition(*args):
"""setVisibleCondition(visible[,allowHiddenFocus]) -- Set's the control's visible condition.
Allows XBMC to control the visible status of the control.
visible : string - Visible condition.
allowHiddenFocus : bool - True=gains focus even if hidden.
List of Conditions - http://wiki.xbmc.org/index.php?title=List_of_Boolean_Conditions
example:
- self.button.setVisibleCondition('[Control.IsVisible(41) + !Control.IsVisible(12)]', True)
"""
def setWidth(*args):
"""setWidth(width) -- Set's the controls width.
width : integer - width of control.
example:
- self.image.setWidth(100)
"""
class ControlGroup:
"""ControlGroup class.
ControlGroup(x, y, width, height
x : integer - x coordinate of control.
y : integer - y coordinate of control.
width : integer - width of control.
height : integer - height of control.
example:
- self.group = xbmcgui.ControlGroup(100, 250, 125, 75)
"""
def __cmp__(*args):
"""x.__cmp__(y) <==> cmp(x,y)
"""
def __delattr__(*args):
"""x.__delattr__('name') <==> del x.name
"""
def __format__(*args):
"""default object formatter
"""
def __getattribute__(*args):
"""x.__getattribute__('name') <==> x.name
"""
def __hash__(*args):
"""x.__hash__() <==> hash(x)
"""
def __init__(*args):
"""x.__init__(...) initializes x; see x.__class__.__doc__ for signature
"""
def __new__(*args):
"""T.__new__(S, ...) -> a new object with type S, a subtype of T
"""
def __reduce__(*args):
"""helper for pickle
"""
def __reduce_ex__(*args):
"""helper for pickle
"""
def __repr__(*args):
"""x.__repr__() <==> repr(x)
"""
def __setattr__(*args):
"""x.__setattr__('name', value) <==> x.name = value
"""
def __sizeof__(*args):
"""__sizeof__() -> size of object in memory, in bytes
"""
def __str__(*args):
"""x.__str__() <==> str(x)
"""
def __subclasshook__(*args):
"""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).
"""
def controlDown(*args):
"""controlDown(control) -- Set's the controls down navigation.
control : control object - control to navigate to on down.
*Note, You can also use setNavigation(). Set to self to disable navigation.
Throws: TypeError, if one of the supplied arguments is not a control type.
ReferenceError, if one of the controls is not added to a window.
example:
- self.button.controlDown(self.button1)
"""
def controlLeft(*args):
"""controlLeft(control) -- Set's the controls left navigation.
control : control object - control to navigate to on left.
*Note, You can also use setNavigation(). Set to self to disable navigation.
Throws: TypeError, if one of the supplied arguments is not a control type.
ReferenceError, if one of the controls is not added to a window.
example:
- self.button.controlLeft(self.button1)
"""
def controlRight(*args):
"""controlRight(control) -- Set's the controls right navigation.
control : control object - control to navigate to on right.
*Note, You can also use setNavigation(). Set to self to disable navigation.
Throws: TypeError, if one of the supplied arguments is not a control type.
ReferenceError, if one of the controls is not added to a window.
example:
- self.button.controlRight(self.button1)
"""
def controlUp(*args):
"""controlUp(control) -- Set's the controls up navigation.
control : control object - control to navigate to on up.
*Note, You can also use setNavigation(). Set to self to disable navigation.
Throws: TypeError, if one of the supplied arguments is not a control type.
ReferenceError, if one of the controls is not added to a window.
example:
- self.button.controlUp(self.button1)
"""
def getHeight(*args):
"""getHeight() -- Returns the control's current height as an integer.
example:
- height = self.button.getHeight()
"""
def getId(*args):
"""getId() -- Returns the control's current id as an integer.
example:
- id = self.button.getId()
"""
def getPosition(*args):
"""getPosition() -- Returns the control's current position as a x,y integer tuple.
example:
- pos = self.button.getPosition()
"""
def getWidth(*args):
"""getWidth() -- Returns the control's current width as an integer.
example:
- width = self.button.getWidth()
"""
def setAnimations(*args):
"""setAnimations([(event, attr,)*]) -- Set's the control's animations.
[(event,attr,)*] : list - A list of tuples consisting of event and attributes pairs.
- event : string - The event to animate.
- attr : string - The whole attribute string separated by spaces.
Animating your skin - http://wiki.xbmc.org/?title=Animating_Your_Skin
example:
- self.button.setAnimations([('focus', 'effect=zoom end=90,247,220,56 time=0',)])
"""
def setEnableCondition(*args):
"""setEnableCondition(enable) -- Set's the control's enabled condition.
Allows XBMC to control the enabled status of the control.
enable : string - Enable condition.
List of Conditions - http://wiki.xbmc.org/index.php?title=List_of_Boolean_Conditions
example:
- self.button.setEnableCondition('System.InternetState')
"""
def setEnabled(*args):
"""setEnabled(enabled) -- Set's the control's enabled/disabled state.
enabled : bool - True=enabled / False=disabled.
example:
- self.button.setEnabled(False)
"""
def setHeight(*args):
"""setHeight(height) -- Set's the controls height.
height : integer - height of control.
example:
- self.image.setHeight(100)
"""
def setNavigation(*args):
"""setNavigation(up, down, left, right) -- Set's the controls navigation.
up : control object - control to navigate to on up.
down : control object - control to navigate to on down.
left : control object - control to navigate to on left.
right : control object - control to navigate to on right.
*Note, Same as controlUp(), controlDown(), controlLeft(), controlRight().
Set to self to disable navigation for that direction.
Throws: TypeError, if one of the supplied arguments is not a control type.
ReferenceError, if one of the controls is not added to a window.
example:
- self.button.setNavigation(self.button1, self.button2, self.button3, self.button4)
"""
def setPosition(*args):
"""setPosition(x, y) -- Set's the controls position.
x : integer - x coordinate of control.
y : integer - y coordinate of control.
*Note, You may use negative integers. (e.g sliding a control into view)
example:
- self.button.setPosition(100, 250)
"""
def setVisible(*args):
"""setVisible(visible) -- Set's the control's visible/hidden state.
visible : bool - True=visible / False=hidden.
example:
- self.button.setVisible(False)
"""
def setVisibleCondition(*args):
"""setVisibleCondition(visible[,allowHiddenFocus]) -- Set's the control's visible condition.
Allows XBMC to control the visible status of the control.
visible : string - Visible condition.
allowHiddenFocus : bool - True=gains focus even if hidden.
List of Conditions - http://wiki.xbmc.org/index.php?title=List_of_Boolean_Conditions
example:
- self.button.setVisibleCondition('[Control.IsVisible(41) + !Control.IsVisible(12)]', True)
"""
def setWidth(*args):
"""setWidth(width) -- Set's the controls width.
width : integer - width of control.
example:
- self.image.setWidth(100)
"""
class ControlImage:
"""ControlImage class.
ControlImage(x, y, width, height, filename[, colorKey, aspectRatio, colorDiffuse])
x : integer - x coordinate of control.
y : integer - y coordinate of control.
width : integer - width of control.
height : integer - height of control.
filename : string - image filename.
colorKey : [opt] hexString - (example, '0xFFFF3300')
aspectRatio : [opt] integer - (values 0 = stretch (default), 1 = scale up (crops), 2 = scale down (black bars)colorDiffuse : hexString - (example, '0xC0FF0000' (red tint))
*Note, You can use the above as keywords for arguments and skip certain optional arguments.
Once you use a keyword, all following arguments require the keyword.
After you create the control, you need to add it to the window with addControl().
example:
- self.image = xbmcgui.ControlImage(100, 250, 125, 75, aspectRatio=2)
"""
def __cmp__(*args):
"""x.__cmp__(y) <==> cmp(x,y)
"""
def __delattr__(*args):
"""x.__delattr__('name') <==> del x.name
"""
def __format__(*args):
"""default object formatter
"""
def __getattribute__(*args):
"""x.__getattribute__('name') <==> x.name
"""
def __hash__(*args):
"""x.__hash__() <==> hash(x)
"""
def __init__(*args):
"""x.__init__(...) initializes x; see x.__class__.__doc__ for signature
"""
def __new__(*args):
"""T.__new__(S, ...) -> a new object with type S, a subtype of T
"""
def __reduce__(*args):
"""helper for pickle
"""
def __reduce_ex__(*args):
"""helper for pickle
"""
def __repr__(*args):
"""x.__repr__() <==> repr(x)
"""
def __setattr__(*args):
"""x.__setattr__('name', value) <==> x.name = value
"""
def __sizeof__(*args):
"""__sizeof__() -> size of object in memory, in bytes
"""
def __str__(*args):
"""x.__str__() <==> str(x)
"""
def __subclasshook__(*args):
"""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).
"""
def controlDown(*args):
"""controlDown(control) -- Set's the controls down navigation.
control : control object - control to navigate to on down.
*Note, You can also use setNavigation(). Set to self to disable navigation.
Throws: TypeError, if one of the supplied arguments is not a control type.
ReferenceError, if one of the controls is not added to a window.
example:
- self.button.controlDown(self.button1)
"""
def controlLeft(*args):
"""controlLeft(control) -- Set's the controls left navigation.
control : control object - control to navigate to on left.
*Note, You can also use setNavigation(). Set to self to disable navigation.
Throws: TypeError, if one of the supplied arguments is not a control type.
ReferenceError, if one of the controls is not added to a window.
example:
- self.button.controlLeft(self.button1)
"""
def controlRight(*args):
"""controlRight(control) -- Set's the controls right navigation.
control : control object - control to navigate to on right.
*Note, You can also use setNavigation(). Set to self to disable navigation.
Throws: TypeError, if one of the supplied arguments is not a control type.
ReferenceError, if one of the controls is not added to a window.
example:
- self.button.controlRight(self.button1)
"""
def controlUp(*args):
"""controlUp(control) -- Set's the controls up navigation.
control : control object - control to navigate to on up.
*Note, You can also use setNavigation(). Set to self to disable navigation.
Throws: TypeError, if one of the supplied arguments is not a control type.
ReferenceError, if one of the controls is not added to a window.
example:
- self.button.controlUp(self.button1)
"""
def getHeight(*args):
"""getHeight() -- Returns the control's current height as an integer.
example:
- height = self.button.getHeight()
"""
def getId(*args):
"""getId() -- Returns the control's current id as an integer.
example:
- id = self.button.getId()
"""
def getPosition(*args):
"""getPosition() -- Returns the control's current position as a x,y integer tuple.
example:
- pos = self.button.getPosition()
"""
def getWidth(*args):
"""getWidth() -- Returns the control's current width as an integer.
example:
- width = self.button.getWidth()
"""
def setAnimations(*args):
"""setAnimations([(event, attr,)*]) -- Set's the control's animations.
[(event,attr,)*] : list - A list of tuples consisting of event and attributes pairs.
- event : string - The event to animate.
- attr : string - The whole attribute string separated by spaces.
Animating your skin - http://wiki.xbmc.org/?title=Animating_Your_Skin
example:
- self.button.setAnimations([('focus', 'effect=zoom end=90,247,220,56 time=0',)])
"""
def setColorDiffuse(*args):
"""setColorDiffuse(colorDiffuse) -- Changes the images color.
colorDiffuse : hexString - (example, '0xC0FF0000' (red tint))
example:
- self.image.setColorDiffuse('0xC0FF0000')
"""
def setEnableCondition(*args):
"""setEnableCondition(enable) -- Set's the control's enabled condition.
Allows XBMC to control the enabled status of the control.
enable : string - Enable condition.
List of Conditions - http://wiki.xbmc.org/index.php?title=List_of_Boolean_Conditions
example:
- self.button.setEnableCondition('System.InternetState')
"""
def setEnabled(*args):
"""setEnabled(enabled) -- Set's the control's enabled/disabled state.
enabled : bool - True=enabled / False=disabled.
example:
- self.button.setEnabled(False)
"""
def setHeight(*args):
"""setHeight(height) -- Set's the controls height.
height : integer - height of control.
example:
- self.image.setHeight(100)
"""
def setImage(*args):
"""setImage(filename, colorKey) -- Changes the image.
filename : string - image filename.
example:
- self.image.setImage('special://home/scripts/test.png')
"""
def setNavigation(*args):
"""setNavigation(up, down, left, right) -- Set's the controls navigation.
up : control object - control to navigate to on up.
down : control object - control to navigate to on down.
left : control object - control to navigate to on left.
right : control object - control to navigate to on right.
*Note, Same as controlUp(), controlDown(), controlLeft(), controlRight().
Set to self to disable navigation for that direction.
Throws: TypeError, if one of the supplied arguments is not a control type.
ReferenceError, if one of the controls is not added to a window.
example:
- self.button.setNavigation(self.button1, self.button2, self.button3, self.button4)
"""
def setPosition(*args):
"""setPosition(x, y) -- Set's the controls position.
x : integer - x coordinate of control.
y : integer - y coordinate of control.
*Note, You may use negative integers. (e.g sliding a control into view)
example:
- self.button.setPosition(100, 250)
"""
def setVisible(*args):
"""setVisible(visible) -- Set's the control's visible/hidden state.
visible : bool - True=visible / False=hidden.
example:
- self.button.setVisible(False)
"""
def setVisibleCondition(*args):
"""setVisibleCondition(visible[,allowHiddenFocus]) -- Set's the control's visible condition.
Allows XBMC to control the visible status of the control.
visible : string - Visible condition.
allowHiddenFocus : bool - True=gains focus even if hidden.
List of Conditions - http://wiki.xbmc.org/index.php?title=List_of_Boolean_Conditions
example:
- self.button.setVisibleCondition('[Control.IsVisible(41) + !Control.IsVisible(12)]', True)
"""
def setWidth(*args):
"""setWidth(width) -- Set's the controls width.
width : integer - width of control.
example:
- self.image.setWidth(100)
"""
class ControlLabel:
"""ControlLabel class.
ControlLabel(x, y, width, height, label[, font, textColor,
disabledColor, alignment, hasPath, angle])
x : integer - x coordinate of control.
y : integer - y coordinate of control.
width : integer - width of control.
height : integer - height of control.
label : string or unicode - text string.
font : [opt] string - font used for label text. (e.g. 'font13')
textColor : [opt] hexstring - color of enabled label's label. (e.g. '0xFFFFFFFF')
disabledColor : [opt] hexstring - color of disabled label's label. (e.g. '0xFFFF3300')
alignment : [opt] integer - alignment of label - *Note, see xbfont.h
hasPath : [opt] bool - True=stores a path / False=no path.
angle : [opt] integer - angle of control. (+ rotates CCW, - rotates CW)
*Note, You can use the above as keywords for arguments and skip certain optional arguments.
Once you use a keyword, all following arguments require the keyword.
After you create the control, you need to add it to the window with addControl().
example:
- self.label = xbmcgui.ControlLabel(100, 250, 125, 75, 'Status', angle=45)
"""
def __cmp__(*args):
"""x.__cmp__(y) <==> cmp(x,y)
"""
def __delattr__(*args):
"""x.__delattr__('name') <==> del x.name
"""
def __format__(*args):
"""default object formatter
"""
def __getattribute__(*args):
"""x.__getattribute__('name') <==> x.name
"""
def __hash__(*args):
"""x.__hash__() <==> hash(x)
"""
def __init__(*args):
"""x.__init__(...) initializes x; see x.__class__.__doc__ for signature
"""
def __new__(*args):
"""T.__new__(S, ...) -> a new object with type S, a subtype of T
"""
def __reduce__(*args):
"""helper for pickle
"""
def __reduce_ex__(*args):
"""helper for pickle
"""
def __repr__(*args):
"""x.__repr__() <==> repr(x)
"""
def __setattr__(*args):
"""x.__setattr__('name', value) <==> x.name = value
"""
def __sizeof__(*args):
"""__sizeof__() -> size of object in memory, in bytes
"""
def __str__(*args):
"""x.__str__() <==> str(x)
"""
def __subclasshook__(*args):
"""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).
"""
def controlDown(*args):
"""controlDown(control) -- Set's the controls down navigation.
control : control object - control to navigate to on down.
*Note, You can also use setNavigation(). Set to self to disable navigation.
Throws: TypeError, if one of the supplied arguments is not a control type.
ReferenceError, if one of the controls is not added to a window.
example:
- self.button.controlDown(self.button1)
"""
def controlLeft(*args):
"""controlLeft(control) -- Set's the controls left navigation.
control : control object - control to navigate to on left.
*Note, You can also use setNavigation(). Set to self to disable navigation.
Throws: TypeError, if one of the supplied arguments is not a control type.
ReferenceError, if one of the controls is not added to a window.
example:
- self.button.controlLeft(self.button1)
"""
def controlRight(*args):
"""controlRight(control) -- Set's the controls right navigation.
control : control object - control to navigate to on right.
*Note, You can also use setNavigation(). Set to self to disable navigation.
Throws: TypeError, if one of the supplied arguments is not a control type.
ReferenceError, if one of the controls is not added to a window.
example:
- self.button.controlRight(self.button1)
"""
def controlUp(*args):
"""controlUp(control) -- Set's the controls up navigation.
control : control object - control to navigate to on up.
*Note, You can also use setNavigation(). Set to self to disable navigation.
Throws: TypeError, if one of the supplied arguments is not a control type.
ReferenceError, if one of the controls is not added to a window.
example:
- self.button.controlUp(self.button1)
"""
def getHeight(*args):
"""getHeight() -- Returns the control's current height as an integer.
example:
- height = self.button.getHeight()
"""
def getId(*args):
"""getId() -- Returns the control's current id as an integer.
example:
- id = self.button.getId()
"""
def getLabel(*args):
"""getLabel() -- Returns the text value for this label.
example:
- label = self.label.getLabel()
"""
def getPosition(*args):
"""getPosition() -- Returns the control's current position as a x,y integer tuple.
example:
- pos = self.button.getPosition()
"""
def getWidth(*args):
"""getWidth() -- Returns the control's current width as an integer.
example:
- width = self.button.getWidth()
"""
def setAnimations(*args):
"""setAnimations([(event, attr,)*]) -- Set's the control's animations.
[(event,attr,)*] : list - A list of tuples consisting of event and attributes pairs.
- event : string - The event to animate.
- attr : string - The whole attribute string separated by spaces.
Animating your skin - http://wiki.xbmc.org/?title=Animating_Your_Skin
example:
- self.button.setAnimations([('focus', 'effect=zoom end=90,247,220,56 time=0',)])
"""
def setEnableCondition(*args):
"""setEnableCondition(enable) -- Set's the control's enabled condition.
Allows XBMC to control the enabled status of the control.
enable : string - Enable condition.
List of Conditions - http://wiki.xbmc.org/index.php?title=List_of_Boolean_Conditions
example:
- self.button.setEnableCondition('System.InternetState')
"""
def setEnabled(*args):
"""setEnabled(enabled) -- Set's the control's enabled/disabled state.
enabled : bool - True=enabled / False=disabled.
example:
- self.button.setEnabled(False)
"""
def setHeight(*args):
"""setHeight(height) -- Set's the controls height.
height : integer - height of control.
example:
- self.image.setHeight(100)
"""
def setLabel(*args):
"""setLabel(label) -- Set's text for this label.
label : string or unicode - text string.
example:
- self.label.setLabel('Status')
"""
def setNavigation(*args):
"""setNavigation(up, down, left, right) -- Set's the controls navigation.
up : control object - control to navigate to on up.
down : control object - control to navigate to on down.
left : control object - control to navigate to on left.
right : control object - control to navigate to on right.
*Note, Same as controlUp(), controlDown(), controlLeft(), controlRight().
Set to self to disable navigation for that direction.
Throws: TypeError, if one of the supplied arguments is not a control type.
ReferenceError, if one of the controls is not added to a window.
example:
- self.button.setNavigation(self.button1, self.button2, self.button3, self.button4)
"""
def setPosition(*args):
"""setPosition(x, y) -- Set's the controls position.
x : integer - x coordinate of control.
y : integer - y coordinate of control.
*Note, You may use negative integers. (e.g sliding a control into view)
example:
- self.button.setPosition(100, 250)
"""
def setVisible(*args):
"""setVisible(visible) -- Set's the control's visible/hidden state.
visible : bool - True=visible / False=hidden.
example:
- self.button.setVisible(False)
"""
def setVisibleCondition(*args):
"""setVisibleCondition(visible[,allowHiddenFocus]) -- Set's the control's visible condition.
Allows XBMC to control the visible status of the control.
visible : string - Visible condition.
allowHiddenFocus : bool - True=gains focus even if hidden.
List of Conditions - http://wiki.xbmc.org/index.php?title=List_of_Boolean_Conditions
example:
- self.button.setVisibleCondition('[Control.IsVisible(41) + !Control.IsVisible(12)]', True)
"""
def setWidth(*args):
"""setWidth(width) -- Set's the controls width.
width : integer - width of control.
example:
- self.image.setWidth(100)
"""
class ControlList:
"""ControlList class.
ControlList(x, y, width, height[, font, textColor, buttonTexture, buttonFocusTexture,
selectedColor, imageWidth, imageHeight, itemTextXOffset, itemTextYOffset,
itemHeight, space, alignmentY])
x : integer - x coordinate of control.
y : integer - y coordinate of control.
width : integer - width of control.
height : integer - height of control.
font : [opt] string - font used for items label. (e.g. 'font13')
textColor : [opt] hexstring - color of items label. (e.g. '0xFFFFFFFF')
buttonTexture : [opt] string - filename for focus texture.
buttonFocusTexture : [opt] string - filename for no focus texture.
selectedColor : [opt] integer - x offset of label.
imageWidth : [opt] integer - width of items icon or thumbnail.
imageHeight : [opt] integer - height of items icon or thumbnail.
itemTextXOffset : [opt] integer - x offset of items label.
itemTextYOffset : [opt] integer - y offset of items label.
itemHeight : [opt] integer - height of items.
space : [opt] integer - space between items.
alignmentY : [opt] integer - Y-axis alignment of items label - *Note, see xbfont.h
*Note, You can use the above as keywords for arguments and skip certain optional arguments.
Once you use a keyword, all following arguments require the keyword.
After you create the control, you need to add it to the window with addControl().
example:
- self.cList = xbmcgui.ControlList(100, 250, 200, 250, 'font14', space=5)
"""
def __cmp__(*args):
"""x.__cmp__(y) <==> cmp(x,y)
"""
def __delattr__(*args):
"""x.__delattr__('name') <==> del x.name
"""
def __format__(*args):
"""default object formatter
"""
def __getattribute__(*args):
"""x.__getattribute__('name') <==> x.name
"""
def __hash__(*args):
"""x.__hash__() <==> hash(x)
"""
def __init__(*args):
"""x.__init__(...) initializes x; see x.__class__.__doc__ for signature
"""
def __new__(*args):
"""T.__new__(S, ...) -> a new object with type S, a subtype of T
"""
def __reduce__(*args):
"""helper for pickle
"""
def __reduce_ex__(*args):
"""helper for pickle
"""
def __repr__(*args):
"""x.__repr__() <==> repr(x)
"""
def __setattr__(*args):
"""x.__setattr__('name', value) <==> x.name = value
"""
def __sizeof__(*args):
"""__sizeof__() -> size of object in memory, in bytes
"""
def __str__(*args):
"""x.__str__() <==> str(x)
"""
def __subclasshook__(*args):
"""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).
"""
def addItem(*args):
"""addItem(item) -- Add a new item to this list control.
item : string, unicode or ListItem - item to add.
example:
- cList.addItem('Reboot XBMC')
"""
def addItems(*args):
"""addItems(items) -- Adds a list of listitems or strings to this list control.
items : List - list of strings, unicode objects or ListItems to add.
*Note, You can use the above as keywords for arguments.
Large lists benefit considerably, than using the standard addItem()
example:
- cList.addItems(items=listitems)
"""
def controlDown(*args):
"""controlDown(control) -- Set's the controls down navigation.
control : control object - control to navigate to on down.
*Note, You can also use setNavigation(). Set to self to disable navigation.
Throws: TypeError, if one of the supplied arguments is not a control type.
ReferenceError, if one of the controls is not added to a window.
example:
- self.button.controlDown(self.button1)
"""
def controlLeft(*args):
"""controlLeft(control) -- Set's the controls left navigation.
control : control object - control to navigate to on left.
*Note, You can also use setNavigation(). Set to self to disable navigation.
Throws: TypeError, if one of the supplied arguments is not a control type.
ReferenceError, if one of the controls is not added to a window.
example:
- self.button.controlLeft(self.button1)
"""
def controlRight(*args):
"""controlRight(control) -- Set's the controls right navigation.
control : control object - control to navigate to on right.
*Note, You can also use setNavigation(). Set to self to disable navigation.
Throws: TypeError, if one of the supplied arguments is not a control type.
ReferenceError, if one of the controls is not added to a window.
example:
- self.button.controlRight(self.button1)
"""
def controlUp(*args):
"""controlUp(control) -- Set's the controls up navigation.
control : control object - control to navigate to on up.
*Note, You can also use setNavigation(). Set to self to disable navigation.
Throws: TypeError, if one of the supplied arguments is not a control type.
ReferenceError, if one of the controls is not added to a window.
example:
- self.button.controlUp(self.button1)
"""
def getHeight(*args):
"""getHeight() -- Returns the control's current height as an integer.
example:
- height = self.button.getHeight()
"""
def getId(*args):
"""getId() -- Returns the control's current id as an integer.
example:
- id = self.button.getId()
"""
def getItemHeight(*args):
"""getItemHeight() -- Returns the control's current item height as an integer.
example:
- item_height = self.cList.getItemHeight()
"""
def getListItem(*args):
"""getListItem(index) -- Returns a given ListItem in this List.
index : integer - index number of item to return.
*Note, throws a ValueError if index is out of range.
example:
- listitem = cList.getListItem(6)
"""
def getPosition(*args):
"""getPosition() -- Returns the control's current position as a x,y integer tuple.
example:
- pos = self.button.getPosition()
"""
def getSelectedItem(*args):
"""getSelectedItem() -- Returns the selected item as a ListItem object.
*Note, Same as getSelectedPosition(), but instead of an integer a ListItem object
is returned. Returns None for empty lists.
See windowexample.py on how to use this.
example:
- item = cList.getSelectedItem()
"""
def getSelectedPosition(*args):
"""getSelectedPosition() -- Returns the position of the selected item as an integer.
*Note, Returns -1 for empty lists.
example:
- pos = cList.getSelectedPosition()
"""
def getSpace(*args):
"""getSpace() -- Returns the control's space between items as an integer.
example:
- gap = self.cList.getSpace()
"""
def getSpinControl(*args):
"""getSpinControl() -- returns the associated ControlSpin object.
*Note, Not working completely yet -
After adding this control list to a window it is not possible to change
the settings of this spin control.
example:
- ctl = cList.getSpinControl()
"""
def getWidth(*args):
"""getWidth() -- Returns the control's current width as an integer.
example:
- width = self.button.getWidth()
"""
def reset(*args):
"""reset() -- Clear all ListItems in this control list.
example:
- cList.reset()
"""
def selectItem(*args):
"""selectItem(item) -- Select an item by index number.
item : integer - index number of the item to select.
example:
- cList.selectItem(12)
"""
def setAnimations(*args):
"""setAnimations([(event, attr,)*]) -- Set's the control's animations.
[(event,attr,)*] : list - A list of tuples consisting of event and attributes pairs.
- event : string - The event to animate.
- attr : string - The whole attribute string separated by spaces.
Animating your skin - http://wiki.xbmc.org/?title=Animating_Your_Skin
example:
- self.button.setAnimations([('focus', 'effect=zoom end=90,247,220,56 time=0',)])
"""
def setEnableCondition(*args):
"""setEnableCondition(enable) -- Set's the control's enabled condition.
Allows XBMC to control the enabled status of the control.
enable : string - Enable condition.
List of Conditions - http://wiki.xbmc.org/index.php?title=List_of_Boolean_Conditions
example:
- self.button.setEnableCondition('System.InternetState')
"""
def setEnabled(*args):
"""setEnabled(enabled) -- Set's the control's enabled/disabled state.
enabled : bool - True=enabled / False=disabled.
example:
- self.button.setEnabled(False)
"""
def setHeight(*args):
"""setHeight(height) -- Set's the controls height.
height : integer - height of control.
example:
- self.image.setHeight(100)
"""
def setImageDimensions(*args):
"""setImageDimensions(imageWidth, imageHeight) -- Sets the width/height of items icon or thumbnail.
imageWidth : [opt] integer - width of items icon or thumbnail.
imageHeight : [opt] integer - height of items icon or thumbnail.
example:
- cList.setImageDimensions(18, 18)
"""
def setItemHeight(*args):
"""setItemHeight(itemHeight) -- Sets the height of items.
itemHeight : integer - height of items.
example:
- cList.setItemHeight(25)
"""
def setNavigation(*args):
"""setNavigation(up, down, left, right) -- Set's the controls navigation.
up : control object - control to navigate to on up.
down : control object - control to navigate to on down.
left : control object - control to navigate to on left.
right : control object - control to navigate to on right.
*Note, Same as controlUp(), controlDown(), controlLeft(), controlRight().
Set to self to disable navigation for that direction.
Throws: TypeError, if one of the supplied arguments is not a control type.
ReferenceError, if one of the controls is not added to a window.
example:
- self.button.setNavigation(self.button1, self.button2, self.button3, self.button4)
"""
def setPageControlVisible(*args):
"""setPageControlVisible(visible) -- Sets the spin control's visible/hidden state.
visible : boolean - True=visible / False=hidden.
example:
- cList.setPageControlVisible(True)
"""
def setPosition(*args):
"""setPosition(x, y) -- Set's the controls position.
x : integer - x coordinate of control.
y : integer - y coordinate of control.
*Note, You may use negative integers. (e.g sliding a control into view)
example:
- self.button.setPosition(100, 250)
"""
def setSpace(*args):
"""setSpace(space) -- Set's the space between items.
space : [opt] integer - space between items.
example:
- cList.setSpace(5)
"""
def setStaticContent(*args):
"""setStaticContent(items) -- Fills a static list with a list of listitems.
items : List - list of listitems to add.
*Note, You can use the above as keywords for arguments.
example:
- cList.setStaticContent(items=listitems)
"""
def setVisible(*args):
"""setVisible(visible) -- Set's the control's visible/hidden state.
visible : bool - True=visible / False=hidden.
example:
- self.button.setVisible(False)
"""
def setVisibleCondition(*args):
"""setVisibleCondition(visible[,allowHiddenFocus]) -- Set's the control's visible condition.
Allows XBMC to control the visible status of the control.
visible : string - Visible condition.
allowHiddenFocus : bool - True=gains focus even if hidden.
List of Conditions - http://wiki.xbmc.org/index.php?title=List_of_Boolean_Conditions
example:
- self.button.setVisibleCondition('[Control.IsVisible(41) + !Control.IsVisible(12)]', True)
"""
def setWidth(*args):
"""setWidth(width) -- Set's the controls width.
width : integer - width of control.
example:
- self.image.setWidth(100)
"""
def size(*args):
"""size() -- Returns the total number of items in this list control as an integer.
example:
- cnt = cList.size()
"""
class ControlProgress:
"""ControlProgress class.
ControlProgress(x, y, width, height[, texturebg, textureleft, texturemid, textureright, textureoverlay])
x : integer - x coordinate of control.
y : integer - y coordinate of control.
width : integer - width of control.
height : integer - height of control.
texturebg : [opt] string - image filename.
textureleft : [opt] string - image filename.
texturemid : [opt] string - image filename.
textureright : [opt] string - image filename.
textureoverlay : [opt] string - image filename.
*Note, You can use the above as keywords for arguments and skip certain optional arguments.
Once you use a keyword, all following arguments require the keyword.
After you create the control, you need to add it to the window with addControl().
example:
- self.progress = xbmcgui.ControlProgress(100, 250, 125, 75)
"""
def __cmp__(*args):
"""x.__cmp__(y) <==> cmp(x,y)
"""
def __delattr__(*args):
"""x.__delattr__('name') <==> del x.name
"""
def __format__(*args):
"""default object formatter
"""
def __getattribute__(*args):
"""x.__getattribute__('name') <==> x.name
"""
def __hash__(*args):
"""x.__hash__() <==> hash(x)
"""
def __init__(*args):
"""x.__init__(...) initializes x; see x.__class__.__doc__ for signature
"""
def __new__(*args):
"""T.__new__(S, ...) -> a new object with type S, a subtype of T
"""
def __reduce__(*args):
"""helper for pickle
"""
def __reduce_ex__(*args):
"""helper for pickle
"""
def __repr__(*args):
"""x.__repr__() <==> repr(x)
"""
def __setattr__(*args):
"""x.__setattr__('name', value) <==> x.name = value
"""
def __sizeof__(*args):
"""__sizeof__() -> size of object in memory, in bytes
"""
def __str__(*args):
"""x.__str__() <==> str(x)
"""
def __subclasshook__(*args):
"""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).
"""
def controlDown(*args):
"""controlDown(control) -- Set's the controls down navigation.
control : control object - control to navigate to on down.
*Note, You can also use setNavigation(). Set to self to disable navigation.
Throws: TypeError, if one of the supplied arguments is not a control type.
ReferenceError, if one of the controls is not added to a window.
example:
- self.button.controlDown(self.button1)
"""
def controlLeft(*args):
"""controlLeft(control) -- Set's the controls left navigation.
control : control object - control to navigate to on left.
*Note, You can also use setNavigation(). Set to self to disable navigation.
Throws: TypeError, if one of the supplied arguments is not a control type.
ReferenceError, if one of the controls is not added to a window.
example:
- self.button.controlLeft(self.button1)
"""
def controlRight(*args):
"""controlRight(control) -- Set's the controls right navigation.
control : control object - control to navigate to on right.
*Note, You can also use setNavigation(). Set to self to disable navigation.
Throws: TypeError, if one of the supplied arguments is not a control type.
ReferenceError, if one of the controls is not added to a window.
example:
- self.button.controlRight(self.button1)
"""
def controlUp(*args):
"""controlUp(control) -- Set's the controls up navigation.
control : control object - control to navigate to on up.
*Note, You can also use setNavigation(). Set to self to disable navigation.
Throws: TypeError, if one of the supplied arguments is not a control type.
ReferenceError, if one of the controls is not added to a window.
example:
- self.button.controlUp(self.button1)
"""
def getHeight(*args):
"""getHeight() -- Returns the control's current height as an integer.
example:
- height = self.button.getHeight()
"""
def getId(*args):
"""getId() -- Returns the control's current id as an integer.
example:
- id = self.button.getId()
"""
def getPercent(*args):
"""getPercent() -- Returns a float of the percent of the progress.
example:
- print self.progress.getValue()
"""
def getPosition(*args):
"""getPosition() -- Returns the control's current position as a x,y integer tuple.
example:
- pos = self.button.getPosition()
"""
def getWidth(*args):
"""getWidth() -- Returns the control's current width as an integer.
example:
- width = self.button.getWidth()
"""
def setAnimations(*args):
"""setAnimations([(event, attr,)*]) -- Set's the control's animations.
[(event,attr,)*] : list - A list of tuples consisting of event and attributes pairs.
- event : string - The event to animate.
- attr : string - The whole attribute string separated by spaces.
Animating your skin - http://wiki.xbmc.org/?title=Animating_Your_Skin
example:
- self.button.setAnimations([('focus', 'effect=zoom end=90,247,220,56 time=0',)])
"""
def setEnableCondition(*args):
"""setEnableCondition(enable) -- Set's the control's enabled condition.
Allows XBMC to control the enabled status of the control.
enable : string - Enable condition.
List of Conditions - http://wiki.xbmc.org/index.php?title=List_of_Boolean_Conditions
example:
- self.button.setEnableCondition('System.InternetState')
"""
def setEnabled(*args):
"""setEnabled(enabled) -- Set's the control's enabled/disabled state.
enabled : bool - True=enabled / False=disabled.
example:
- self.button.setEnabled(False)
"""
def setHeight(*args):
"""setHeight(height) -- Set's the controls height.
height : integer - height of control.
example:
- self.image.setHeight(100)
"""
def setNavigation(*args):
"""setNavigation(up, down, left, right) -- Set's the controls navigation.
up : control object - control to navigate to on up.
down : control object - control to navigate to on down.
left : control object - control to navigate to on left.
right : control object - control to navigate to on right.
*Note, Same as controlUp(), controlDown(), controlLeft(), controlRight().
Set to self to disable navigation for that direction.
Throws: TypeError, if one of the supplied arguments is not a control type.
ReferenceError, if one of the controls is not added to a window.
example:
- self.button.setNavigation(self.button1, self.button2, self.button3, self.button4)
"""
def setPercent(*args):
"""setPercent(percent) -- Sets the percentage of the progressbar to show.
percent : float - percentage of the bar to show.
*Note, valid range for percent is 0-100
example:
- self.progress.setPercent(60)
"""
def setPosition(*args):
"""setPosition(x, y) -- Set's the controls position.
x : integer - x coordinate of control.
y : integer - y coordinate of control.
*Note, You may use negative integers. (e.g sliding a control into view)
example:
- self.button.setPosition(100, 250)
"""
def setVisible(*args):
"""setVisible(visible) -- Set's the control's visible/hidden state.
visible : bool - True=visible / False=hidden.
example:
- self.button.setVisible(False)
"""
def setVisibleCondition(*args):
"""setVisibleCondition(visible[,allowHiddenFocus]) -- Set's the control's visible condition.
Allows XBMC to control the visible status of the control.
visible : string - Visible condition.
allowHiddenFocus : bool - True=gains focus even if hidden.
List of Conditions - http://wiki.xbmc.org/index.php?title=List_of_Boolean_Conditions
example:
- self.button.setVisibleCondition('[Control.IsVisible(41) + !Control.IsVisible(12)]', True)
"""
def setWidth(*args):
"""setWidth(width) -- Set's the controls width.
width : integer - width of control.
example:
- self.image.setWidth(100)
"""
class ControlRadioButton:
"""ControlRadioButton class.
ControlRadioButton(x, y, width, height, label[, focusTexture, noFocusTexture, textOffsetX, textOffsetY,
alignment, font, textColor, disabledColor, angle, shadowColor, focusedColor,
radioFocusTexture, noRadioFocusTexture])
x : integer - x coordinate of control.
y : integer - y coordinate of control.
width : integer - width of control.
height : integer - height of control.
label : string or unicode - text string.
focusTexture : [opt] string - filename for focus texture.
noFocusTexture : [opt] string - filename for no focus texture.
textOffsetX : [opt] integer - x offset of label.
textOffsetY : [opt] integer - y offset of label.
alignment : [opt] integer - alignment of label - *Note, see xbfont.h
font : [opt] string - font used for label text. (e.g. 'font13')
textColor : [opt] hexstring - color of enabled radio button's label. (e.g. '0xFFFFFFFF')
disabledColor : [opt] hexstring - color of disabled radio button's label. (e.g. '0xFFFF3300')
angle : [opt] integer - angle of control. (+ rotates CCW, - rotates CW)
shadowColor : [opt] hexstring - color of radio button's label's shadow. (e.g. '0xFF000000')
focusedColor : [opt] hexstring - color of focused radio button's label. (e.g. '0xFF00FFFF')
radioFocusTexture : [opt] string - filename for radio focus texture.
noRadioFocusTexture : [opt] string - filename for radio no focus texture.
*Note, You can use the above as keywords for arguments and skip certain optional arguments.
Once you use a keyword, all following arguments require the keyword.
After you create the control, you need to add it to the window with addControl().
example:
- self.radiobutton = xbmcgui.ControlRadioButton(100, 250, 200, 50, 'Status', font='font14')
"""
def __cmp__(*args):
"""x.__cmp__(y) <==> cmp(x,y)
"""
def __delattr__(*args):
"""x.__delattr__('name') <==> del x.name
"""
def __format__(*args):
"""default object formatter
"""
def __getattribute__(*args):
"""x.__getattribute__('name') <==> x.name
"""
def __hash__(*args):
"""x.__hash__() <==> hash(x)
"""
def __init__(*args):
"""x.__init__(...) initializes x; see x.__class__.__doc__ for signature
"""
def __new__(*args):
"""T.__new__(S, ...) -> a new object with type S, a subtype of T
"""
def __reduce__(*args):
"""helper for pickle
"""
def __reduce_ex__(*args):
"""helper for pickle
"""
def __repr__(*args):
"""x.__repr__() <==> repr(x)
"""
def __setattr__(*args):
"""x.__setattr__('name', value) <==> x.name = value
"""
def __sizeof__(*args):
"""__sizeof__() -> size of object in memory, in bytes
"""
def __str__(*args):
"""x.__str__() <==> str(x)
"""
def __subclasshook__(*args):
"""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).
"""
def controlDown(*args):
"""controlDown(control) -- Set's the controls down navigation.
control : control object - control to navigate to on down.
*Note, You can also use setNavigation(). Set to self to disable navigation.
Throws: TypeError, if one of the supplied arguments is not a control type.
ReferenceError, if one of the controls is not added to a window.
example:
- self.button.controlDown(self.button1)
"""
def controlLeft(*args):
"""controlLeft(control) -- Set's the controls left navigation.
control : control object - control to navigate to on left.
*Note, You can also use setNavigation(). Set to self to disable navigation.
Throws: TypeError, if one of the supplied arguments is not a control type.
ReferenceError, if one of the controls is not added to a window.
example:
- self.button.controlLeft(self.button1)
"""
def controlRight(*args):
"""controlRight(control) -- Set's the controls right navigation.
control : control object - control to navigate to on right.
*Note, You can also use setNavigation(). Set to self to disable navigation.
Throws: TypeError, if one of the supplied arguments is not a control type.
ReferenceError, if one of the controls is not added to a window.
example:
- self.button.controlRight(self.button1)
"""
def controlUp(*args):
"""controlUp(control) -- Set's the controls up navigation.
control : control object - control to navigate to on up.
*Note, You can also use setNavigation(). Set to self to disable navigation.
Throws: TypeError, if one of the supplied arguments is not a control type.
ReferenceError, if one of the controls is not added to a window.
example:
- self.button.controlUp(self.button1)
"""
def getHeight(*args):
"""getHeight() -- Returns the control's current height as an integer.
example:
- height = self.button.getHeight()
"""
def getId(*args):
"""getId() -- Returns the control's current id as an integer.
example:
- id = self.button.getId()
"""
def getPosition(*args):
"""getPosition() -- Returns the control's current position as a x,y integer tuple.
example:
- pos = self.button.getPosition()
"""
def getWidth(*args):
"""getWidth() -- Returns the control's current width as an integer.
example:
- width = self.button.getWidth()
"""
def isSelected(*args):
"""isSelected() -- Returns the radio buttons's selected status.
example:
- is = self.radiobutton.isSelected()
"""
def setAnimations(*args):
"""setAnimations([(event, attr,)*]) -- Set's the control's animations.
[(event,attr,)*] : list - A list of tuples consisting of event and attributes pairs.
- event : string - The event to animate.
- attr : string - The whole attribute string separated by spaces.
Animating your skin - http://wiki.xbmc.org/?title=Animating_Your_Skin
example:
- self.button.setAnimations([('focus', 'effect=zoom end=90,247,220,56 time=0',)])
"""
def setEnableCondition(*args):
"""setEnableCondition(enable) -- Set's the control's enabled condition.
Allows XBMC to control the enabled status of the control.
enable : string - Enable condition.
List of Conditions - http://wiki.xbmc.org/index.php?title=List_of_Boolean_Conditions
example:
- self.button.setEnableCondition('System.InternetState')
"""
def setEnabled(*args):
"""setEnabled(enabled) -- Set's the control's enabled/disabled state.
enabled : bool - True=enabled / False=disabled.
example:
- self.button.setEnabled(False)
"""
def setHeight(*args):
"""setHeight(height) -- Set's the controls height.
height : integer - height of control.
example:
- self.image.setHeight(100)
"""
def setLabel(*args):
"""setLabel(label[, font, textColor, disabledColor, shadowColor, focusedColor]) -- Set's the radio buttons text attributes.
label : string or unicode - text string.
font : [opt] string - font used for label text. (e.g. 'font13')
textColor : [opt] hexstring - color of enabled radio button's label. (e.g. '0xFFFFFFFF')
disabledColor : [opt] hexstring - color of disabled radio button's label. (e.g. '0xFFFF3300')
shadowColor : [opt] hexstring - color of radio button's label's shadow. (e.g. '0xFF000000')
focusedColor : [opt] hexstring - color of focused radio button's label. (e.g. '0xFFFFFF00')
*Note, You can use the above as keywords for arguments and skip certain optional arguments.
Once you use a keyword, all following arguments require the keyword.
example:
- self.radiobutton.setLabel('Status', 'font14', '0xFFFFFFFF', '0xFFFF3300', '0xFF000000')
"""
def setNavigation(*args):
"""setNavigation(up, down, left, right) -- Set's the controls navigation.
up : control object - control to navigate to on up.
down : control object - control to navigate to on down.
left : control object - control to navigate to on left.
right : control object - control to navigate to on right.
*Note, Same as controlUp(), controlDown(), controlLeft(), controlRight().
Set to self to disable navigation for that direction.
Throws: TypeError, if one of the supplied arguments is not a control type.
ReferenceError, if one of the controls is not added to a window.
example:
- self.button.setNavigation(self.button1, self.button2, self.button3, self.button4)
"""
def setPosition(*args):
"""setPosition(x, y) -- Set's the controls position.
x : integer - x coordinate of control.
y : integer - y coordinate of control.
*Note, You may use negative integers. (e.g sliding a control into view)
example:
- self.button.setPosition(100, 250)
"""
def setRadioDimension(*args):
"""setRadioDimension(x, y, width, height) -- Sets the radio buttons's radio texture's position and size.
x : integer - x coordinate of radio texture.
y : integer - y coordinate of radio texture.
width : integer - width of radio texture.
height : integer - height of radio texture.
*Note, You can use the above as keywords for arguments and skip certain optional arguments.
Once you use a keyword, all following arguments require the keyword.
example:
- self.radiobutton.setRadioDimension(x=100, y=5, width=20, height=20)
"""
def setSelected(*args):
"""setSelected(selected) -- Sets the radio buttons's selected status.
selected : bool - True=selected (on) / False=not selected (off)
*Note, You can use the above as keywords for arguments and skip certain optional arguments.
Once you use a keyword, all following arguments require the keyword.
example:
- self.radiobutton.setSelected(True)
"""
def setVisible(*args):
"""setVisible(visible) -- Set's the control's visible/hidden state.
visible : bool - True=visible / False=hidden.
example:
- self.button.setVisible(False)
"""
def setVisibleCondition(*args):
"""setVisibleCondition(visible[,allowHiddenFocus]) -- Set's the control's visible condition.
Allows XBMC to control the visible status of the control.
visible : string - Visible condition.
allowHiddenFocus : bool - True=gains focus even if hidden.
List of Conditions - http://wiki.xbmc.org/index.php?title=List_of_Boolean_Conditions
example:
- self.button.setVisibleCondition('[Control.IsVisible(41) + !Control.IsVisible(12)]', True)
"""
def setWidth(*args):
"""setWidth(width) -- Set's the controls width.
width : integer - width of control.
example:
- self.image.setWidth(100)
"""
class ControlSlider:
"""ControlSlider class.
ControlSlider(x, y, width, height[, textureback, texture, texturefocus])
x : integer - x coordinate of control.
y : integer - y coordinate of control.
width : integer - width of control.
height : integer - height of control.
textureback : [opt] string - image filename.
texture : [opt] string - image filename.
texturefocus : [opt] string - image filename.
*Note, You can use the above as keywords for arguments and skip certain optional arguments.
Once you use a keyword, all following arguments require the keyword.
After you create the control, you need to add it to the window with addControl().
example:
- self.slider = xbmcgui.ControlSlider(100, 250, 350, 40)
"""
def __cmp__(*args):
"""x.__cmp__(y) <==> cmp(x,y)
"""
def __delattr__(*args):
"""x.__delattr__('name') <==> del x.name
"""
def __format__(*args):
"""default object formatter
"""
def __getattribute__(*args):
"""x.__getattribute__('name') <==> x.name
"""
def __hash__(*args):
"""x.__hash__() <==> hash(x)
"""
def __init__(*args):
"""x.__init__(...) initializes x; see x.__class__.__doc__ for signature
"""
def __new__(*args):
"""T.__new__(S, ...) -> a new object with type S, a subtype of T
"""
def __reduce__(*args):
"""helper for pickle
"""
def __reduce_ex__(*args):
"""helper for pickle
"""
def __repr__(*args):
"""x.__repr__() <==> repr(x)
"""
def __setattr__(*args):
"""x.__setattr__('name', value) <==> x.name = value
"""
def __sizeof__(*args):
"""__sizeof__() -> size of object in memory, in bytes
"""
def __str__(*args):
"""x.__str__() <==> str(x)
"""
def __subclasshook__(*args):
"""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).
"""
def controlDown(*args):
"""controlDown(control) -- Set's the controls down navigation.
control : control object - control to navigate to on down.
*Note, You can also use setNavigation(). Set to self to disable navigation.
Throws: TypeError, if one of the supplied arguments is not a control type.
ReferenceError, if one of the controls is not added to a window.
example:
- self.button.controlDown(self.button1)
"""
def controlLeft(*args):
"""controlLeft(control) -- Set's the controls left navigation.
control : control object - control to navigate to on left.
*Note, You can also use setNavigation(). Set to self to disable navigation.
Throws: TypeError, if one of the supplied arguments is not a control type.
ReferenceError, if one of the controls is not added to a window.
example:
- self.button.controlLeft(self.button1)
"""
def controlRight(*args):
"""controlRight(control) -- Set's the controls right navigation.
control : control object - control to navigate to on right.
*Note, You can also use setNavigation(). Set to self to disable navigation.
Throws: TypeError, if one of the supplied arguments is not a control type.
ReferenceError, if one of the controls is not added to a window.
example:
- self.button.controlRight(self.button1)
"""
def controlUp(*args):
"""controlUp(control) -- Set's the controls up navigation.
control : control object - control to navigate to on up.
*Note, You can also use setNavigation(). Set to self to disable navigation.
Throws: TypeError, if one of the supplied arguments is not a control type.
ReferenceError, if one of the controls is not added to a window.
example:
- self.button.controlUp(self.button1)
"""
def getHeight(*args):
"""getHeight() -- Returns the control's current height as an integer.
example:
- height = self.button.getHeight()
"""
def getId(*args):
"""getId() -- Returns the control's current id as an integer.
example:
- id = self.button.getId()
"""
def getPercent(*args):
"""getPercent() -- Returns a float of the percent of the slider.
example:
- print self.slider.getPercent()
"""
def getPosition(*args):
"""getPosition() -- Returns the control's current position as a x,y integer tuple.
example:
- pos = self.button.getPosition()
"""
def getWidth(*args):
"""getWidth() -- Returns the control's current width as an integer.
example:
- width = self.button.getWidth()
"""
def setAnimations(*args):
"""setAnimations([(event, attr,)*]) -- Set's the control's animations.
[(event,attr,)*] : list - A list of tuples consisting of event and attributes pairs.
- event : string - The event to animate.
- attr : string - The whole attribute string separated by spaces.
Animating your skin - http://wiki.xbmc.org/?title=Animating_Your_Skin
example:
- self.button.setAnimations([('focus', 'effect=zoom end=90,247,220,56 time=0',)])
"""
def setEnableCondition(*args):
"""setEnableCondition(enable) -- Set's the control's enabled condition.
Allows XBMC to control the enabled status of the control.
enable : string - Enable condition.
List of Conditions - http://wiki.xbmc.org/index.php?title=List_of_Boolean_Conditions
example:
- self.button.setEnableCondition('System.InternetState')
"""
def setEnabled(*args):
"""setEnabled(enabled) -- Set's the control's enabled/disabled state.
enabled : bool - True=enabled / False=disabled.
example:
- self.button.setEnabled(False)
"""
def setHeight(*args):
"""setHeight(height) -- Set's the controls height.
height : integer - height of control.
example:
- self.image.setHeight(100)
"""
def setNavigation(*args):
"""setNavigation(up, down, left, right) -- Set's the controls navigation.
up : control object - control to navigate to on up.
down : control object - control to navigate to on down.
left : control object - control to navigate to on left.
right : control object - control to navigate to on right.
*Note, Same as controlUp(), controlDown(), controlLeft(), controlRight().
Set to self to disable navigation for that direction.
Throws: TypeError, if one of the supplied arguments is not a control type.
ReferenceError, if one of the controls is not added to a window.
example:
- self.button.setNavigation(self.button1, self.button2, self.button3, self.button4)
"""
def setPercent(*args):
"""setPercent(50) -- Sets the percent of the slider.
example:
self.slider.setPercent(50)
"""
def setPosition(*args):
"""setPosition(x, y) -- Set's the controls position.
x : integer - x coordinate of control.
y : integer - y coordinate of control.
*Note, You may use negative integers. (e.g sliding a control into view)
example:
- self.button.setPosition(100, 250)
"""
def setVisible(*args):
"""setVisible(visible) -- Set's the control's visible/hidden state.
visible : bool - True=visible / False=hidden.
example:
- self.button.setVisible(False)
"""
def setVisibleCondition(*args):
"""setVisibleCondition(visible[,allowHiddenFocus]) -- Set's the control's visible condition.
Allows XBMC to control the visible status of the control.
visible : string - Visible condition.
allowHiddenFocus : bool - True=gains focus even if hidden.
List of Conditions - http://wiki.xbmc.org/index.php?title=List_of_Boolean_Conditions
example:
- self.button.setVisibleCondition('[Control.IsVisible(41) + !Control.IsVisible(12)]', True)
"""
def setWidth(*args):
"""setWidth(width) -- Set's the controls width.
width : integer - width of control.
example:
- self.image.setWidth(100)
"""
class ControlTextBox:
"""ControlTextBox class.
ControlTextBox(x, y, width, height[, font, textColor])
x : integer - x coordinate of control.
y : integer - y coordinate of control.
width : integer - width of control.
height : integer - height of control.
font : [opt] string - font used for text. (e.g. 'font13')
textColor : [opt] hexstring - color of textbox's text. (e.g. '0xFFFFFFFF')
*Note, You can use the above as keywords for arguments and skip certain optional arguments.
Once you use a keyword, all following arguments require the keyword.
After you create the control, you need to add it to the window with addControl().
example:
- self.textbox = xbmcgui.ControlTextBox(100, 250, 300, 300, textColor='0xFFFFFFFF')
"""
def __cmp__(*args):
"""x.__cmp__(y) <==> cmp(x,y)
"""
def __delattr__(*args):
"""x.__delattr__('name') <==> del x.name
"""
def __format__(*args):
"""default object formatter
"""
def __getattribute__(*args):
"""x.__getattribute__('name') <==> x.name
"""
def __hash__(*args):
"""x.__hash__() <==> hash(x)
"""
def __init__(*args):
"""x.__init__(...) initializes x; see x.__class__.__doc__ for signature
"""
def __new__(*args):
"""T.__new__(S, ...) -> a new object with type S, a subtype of T
"""
def __reduce__(*args):
"""helper for pickle
"""
def __reduce_ex__(*args):
"""helper for pickle
"""
def __repr__(*args):
"""x.__repr__() <==> repr(x)
"""
def __setattr__(*args):
"""x.__setattr__('name', value) <==> x.name = value
"""
def __sizeof__(*args):
"""__sizeof__() -> size of object in memory, in bytes
"""
def __str__(*args):
"""x.__str__() <==> str(x)
"""
def __subclasshook__(*args):
"""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).
"""
def controlDown(*args):
"""controlDown(control) -- Set's the controls down navigation.
control : control object - control to navigate to on down.
*Note, You can also use setNavigation(). Set to self to disable navigation.
Throws: TypeError, if one of the supplied arguments is not a control type.
ReferenceError, if one of the controls is not added to a window.
example:
- self.button.controlDown(self.button1)
"""
def controlLeft(*args):
"""controlLeft(control) -- Set's the controls left navigation.
control : control object - control to navigate to on left.
*Note, You can also use setNavigation(). Set to self to disable navigation.
Throws: TypeError, if one of the supplied arguments is not a control type.
ReferenceError, if one of the controls is not added to a window.
example:
- self.button.controlLeft(self.button1)
"""
def controlRight(*args):
"""controlRight(control) -- Set's the controls right navigation.
control : control object - control to navigate to on right.
*Note, You can also use setNavigation(). Set to self to disable navigation.
Throws: TypeError, if one of the supplied arguments is not a control type.
ReferenceError, if one of the controls is not added to a window.
example:
- self.button.controlRight(self.button1)
"""
def controlUp(*args):
"""controlUp(control) -- Set's the controls up navigation.
control : control object - control to navigate to on up.
*Note, You can also use setNavigation(). Set to self to disable navigation.
Throws: TypeError, if one of the supplied arguments is not a control type.
ReferenceError, if one of the controls is not added to a window.
example:
- self.button.controlUp(self.button1)
"""
def getHeight(*args):
"""getHeight() -- Returns the control's current height as an integer.
example:
- height = self.button.getHeight()
"""
def getId(*args):
"""getId() -- Returns the control's current id as an integer.
example:
- id = self.button.getId()
"""
def getPosition(*args):
"""getPosition() -- Returns the control's current position as a x,y integer tuple.
example:
- pos = self.button.getPosition()
"""
def getWidth(*args):
"""getWidth() -- Returns the control's current width as an integer.
example:
- width = self.button.getWidth()
"""
def reset(*args):
"""reset() -- Clear's this textbox.
example:
- self.textbox.reset()
"""
def scroll(*args):
"""scroll(position) -- Scrolls to the given position.
id : integer - position to scroll to.
example:
- self.textbox.scroll(10)
"""
def setAnimations(*args):
"""setAnimations([(event, attr,)*]) -- Set's the control's animations.
[(event,attr,)*] : list - A list of tuples consisting of event and attributes pairs.
- event : string - The event to animate.
- attr : string - The whole attribute string separated by spaces.
Animating your skin - http://wiki.xbmc.org/?title=Animating_Your_Skin
example:
- self.button.setAnimations([('focus', 'effect=zoom end=90,247,220,56 time=0',)])
"""
def setEnableCondition(*args):
"""setEnableCondition(enable) -- Set's the control's enabled condition.
Allows XBMC to control the enabled status of the control.
enable : string - Enable condition.
List of Conditions - http://wiki.xbmc.org/index.php?title=List_of_Boolean_Conditions
example:
- self.button.setEnableCondition('System.InternetState')
"""
def setEnabled(*args):
"""setEnabled(enabled) -- Set's the control's enabled/disabled state.
enabled : bool - True=enabled / False=disabled.
example:
- self.button.setEnabled(False)
"""
def setHeight(*args):
"""setHeight(height) -- Set's the controls height.
height : integer - height of control.
example:
- self.image.setHeight(100)
"""
def setNavigation(*args):
"""setNavigation(up, down, left, right) -- Set's the controls navigation.
up : control object - control to navigate to on up.
down : control object - control to navigate to on down.
left : control object - control to navigate to on left.
right : control object - control to navigate to on right.
*Note, Same as controlUp(), controlDown(), controlLeft(), controlRight().
Set to self to disable navigation for that direction.
Throws: TypeError, if one of the supplied arguments is not a control type.
ReferenceError, if one of the controls is not added to a window.
example:
- self.button.setNavigation(self.button1, self.button2, self.button3, self.button4)
"""
def setPosition(*args):
"""setPosition(x, y) -- Set's the controls position.
x : integer - x coordinate of control.
y : integer - y coordinate of control.
*Note, You may use negative integers. (e.g sliding a control into view)
example:
- self.button.setPosition(100, 250)
"""
def setText(*args):
"""setText(text) -- Set's the text for this textbox.
text : string or unicode - text string.
example:
- self.textbox.setText('This is a line of text that can wrap.')
"""
def setVisible(*args):
"""setVisible(visible) -- Set's the control's visible/hidden state.
visible : bool - True=visible / False=hidden.
example:
- self.button.setVisible(False)
"""
def setVisibleCondition(*args):
"""setVisibleCondition(visible[,allowHiddenFocus]) -- Set's the control's visible condition.
Allows XBMC to control the visible status of the control.
visible : string - Visible condition.
allowHiddenFocus : bool - True=gains focus even if hidden.
List of Conditions - http://wiki.xbmc.org/index.php?title=List_of_Boolean_Conditions
example:
- self.button.setVisibleCondition('[Control.IsVisible(41) + !Control.IsVisible(12)]', True)
"""
def setWidth(*args):
"""setWidth(width) -- Set's the controls width.
width : integer - width of control.
example:
- self.image.setWidth(100)
"""
class Dialog:
"""Dialog class.
"""
def __delattr__(*args):
"""x.__delattr__('name') <==> del x.name
"""
def __format__(*args):
"""default object formatter
"""
def __getattribute__(*args):
"""x.__getattribute__('name') <==> x.name
"""
def __hash__(*args):
"""x.__hash__() <==> hash(x)
"""
def __init__(*args):
"""x.__init__(...) initializes x; see x.__class__.__doc__ for signature
"""
def __new__(*args):
"""T.__new__(S, ...) -> a new object with type S, a subtype of T
"""
def __reduce__(*args):
"""helper for pickle
"""
def __reduce_ex__(*args):
"""helper for pickle
"""
def __repr__(*args):
"""x.__repr__() <==> repr(x)
"""
def __setattr__(*args):
"""x.__setattr__('name', value) <==> x.name = value
"""
def __sizeof__(*args):
"""__sizeof__() -> size of object in memory, in bytes
"""
def __str__(*args):
"""x.__str__() <==> str(x)
"""
def __subclasshook__(*args):
"""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).
"""
def browse(*args):
"""browse(type, heading, shares[, mask, useThumbs, treatAsFolder, default, enableMultiple]) -- Show a 'Browse' dialog.
type : integer - the type of browse dialog.
heading : string or unicode - dialog heading.
shares : string or unicode - from sources.xml. (i.e. 'myprograms')
mask : [opt] string or unicode - '|' separated file mask. (i.e. '.jpg|.png')
useThumbs : [opt] boolean - if True autoswitch to Thumb view if files exist.
treatAsFolder : [opt] boolean - if True playlists and archives act as folders.
default : [opt] string - default path or file.
enableMultiple : [opt] boolean - if True multiple file selection is enabled.
Types:
0 : ShowAndGetDirectory
1 : ShowAndGetFile
2 : ShowAndGetImage
3 : ShowAndGetWriteableDirectory
*Note, If enableMultiple is False (default): returns filename and/or path as a string
to the location of the highlighted item, if user pressed 'Ok' or a masked item
was selected. Returns the default value if dialog was canceled.
If enableMultiple is True: returns tuple of marked filenames as a string, if user pressed 'Ok' or a masked item was selected. Returns empty tuple if dialog was canceled.
If type is 0 or 3 the enableMultiple parameter is ignored.
example:
- dialog = xbmcgui.Dialog()
- fn = dialog.browse(3, 'XBMC', 'files', '', False, False, False, 'special://masterprofile/script_data/XBMC Lyrics')
"""
def numeric(*args):
"""numeric(type, heading[, default]) -- Show a 'Numeric' dialog.
type : integer - the type of numeric dialog.
heading : string or unicode - dialog heading.
default : [opt] string - default value.
Types:
0 : ShowAndGetNumber (default format: #)
1 : ShowAndGetDate (default format: DD/MM/YYYY)
2 : ShowAndGetTime (default format: HH:MM)
3 : ShowAndGetIPAddress (default format: #.#.#.#)
*Note, Returns the entered data as a string.
Returns the default value if dialog was canceled.
example:
- dialog = xbmcgui.Dialog()
- d = dialog.numeric(1, 'Enter date of birth')
"""
def ok(*args):
"""ok(heading, line1[, line2, line3]) -- Show a dialog 'OK'.
heading : string or unicode - dialog heading.
line1 : string or unicode - line #1 text.
line2 : [opt] string or unicode - line #2 text.
line3 : [opt] string or unicode - line #3 text.
*Note, Returns True if 'Ok' was pressed, else False.
example:
- dialog = xbmcgui.Dialog()
- ok = dialog.ok('XBMC', 'There was an error.')
"""
def select(*args):
"""select(heading, list) -- Show a select dialog.
heading : string or unicode - dialog heading.
list : string list - list of items.
autoclose : [opt] integer - milliseconds to autoclose dialog. (default=do not autoclose)
*Note, Returns the position of the highlighted item as an integer.
example:
- dialog = xbmcgui.Dialog()
- ret = dialog.select('Choose a playlist', ['Playlist #1', 'Playlist #2, 'Playlist #3'])
"""
def yesno(*args):
"""yesno(heading, line1[, line2, line3]) -- Show a dialog 'YES/NO'.
heading : string or unicode - dialog heading.
line1 : string or unicode - line #1 text.
line2 : [opt] string or unicode - line #2 text.
line3 : [opt] string or unicode - line #3 text.
nolabel : [opt] label to put on the no button.
yeslabel : [opt] label to put on the yes button.
*Note, Returns True if 'Yes' was pressed, else False.
example:
- dialog = xbmcgui.Dialog()
- ret = dialog.yesno('XBMC', 'Do you want to exit this script?')
"""
class DialogProgress:
"""DialogProgress class.
"""
def __delattr__(*args):
"""x.__delattr__('name') <==> del x.name
"""
def __format__(*args):
"""default object formatter
"""
def __getattribute__(*args):
"""x.__getattribute__('name') <==> x.name
"""
def __hash__(*args):
"""x.__hash__() <==> hash(x)
"""
def __init__(*args):
"""x.__init__(...) initializes x; see x.__class__.__doc__ for signature
"""
def __new__(*args):
"""T.__new__(S, ...) -> a new object with type S, a subtype of T
"""
def __reduce__(*args):
"""helper for pickle
"""
def __reduce_ex__(*args):
"""helper for pickle
"""
def __repr__(*args):
"""x.__repr__() <==> repr(x)
"""
def __setattr__(*args):
"""x.__setattr__('name', value) <==> x.name = value
"""
def __sizeof__(*args):
"""__sizeof__() -> size of object in memory, in bytes
"""
def __str__(*args):
"""x.__str__() <==> str(x)
"""
def __subclasshook__(*args):
"""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).
"""
def close(*args):
"""close() -- Close the progress dialog.
example:
- pDialog.close()
"""
def create(*args):
"""create(heading[, line1, line2, line3]) -- Create and show a progress dialog.
heading : string or unicode - dialog heading.
line1 : string or unicode - line #1 text.
line2 : [opt] string or unicode - line #2 text.
line3 : [opt] string or unicode - line #3 text.
*Note, Use update() to update lines and progressbar.
example:
- pDialog = xbmcgui.DialogProgress()
- ret = pDialog.create('XBMC', 'Initializing script...')
"""
def iscanceled(*args):
"""iscanceled() -- Returns True if the user pressed cancel.
example:
- if (pDialog.iscanceled()): return
"""
def update(*args):
"""update(percent[, line1, line2, line3]) -- Update's the progress dialog.
percent : integer - percent complete. (0:100)
line1 : [opt] string or unicode - line #1 text.
line2 : [opt] string or unicode - line #2 text.
line3 : [opt] string or unicode - line #3 text.
*Note, If percent == 0, the progressbar will be hidden.
example:
- pDialog.update(25, 'Importing modules...')
"""
ICON_OVERLAY_HAS_TRAINER = int
ICON_OVERLAY_HD = int
ICON_OVERLAY_LOCKED = int
ICON_OVERLAY_NONE = int
ICON_OVERLAY_RAR = int
ICON_OVERLAY_TRAINED = int
ICON_OVERLAY_UNWATCHED = int
ICON_OVERLAY_WATCHED = int
ICON_OVERLAY_ZIP = int
class ListItem:
"""ListItem class.
ListItem([label, label2, iconImage, thumbnailImage, path]) -- Creates a new ListItem.
label : [opt] string or unicode - label1 text.
label2 : [opt] string or unicode - label2 text.
iconImage : [opt] string - icon filename.
thumbnailImage : [opt] string - thumbnail filename.
path : [opt] string or unicode - listitem's path.
*Note, You can use the above as keywords for arguments and skip certain optional arguments.
Once you use a keyword, all following arguments require the keyword.
example:
- listitem = xbmcgui.ListItem('Casino Royale', '[PG-13]', 'blank-poster.tbn', 'poster.tbn', path='f:\\movies\\casino_royale.mov')
"""
def __delattr__(*args):
"""x.__delattr__('name') <==> del x.name
"""
def __format__(*args):
"""default object formatter
"""
def __getattribute__(*args):
"""x.__getattribute__('name') <==> x.name
"""
def __hash__(*args):
"""x.__hash__() <==> hash(x)
"""
def __init__(*args):
"""x.__init__(...) initializes x; see x.__class__.__doc__ for signature
"""
def __new__(*args):
"""T.__new__(S, ...) -> a new object with type S, a subtype of T
"""
def __reduce__(*args):
"""helper for pickle
"""
def __reduce_ex__(*args):
"""helper for pickle
"""
def __repr__(*args):
"""x.__repr__() <==> repr(x)
"""
def __setattr__(*args):
"""x.__setattr__('name', value) <==> x.name = value
"""
def __sizeof__(*args):
"""__sizeof__() -> size of object in memory, in bytes
"""
def __str__(*args):
"""x.__str__() <==> str(x)
"""
def __subclasshook__(*args):
"""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).
"""
def addContextMenuItems(*args):
"""addContextMenuItems([(label, action,)*], replaceItems) -- Adds item(s) to the context menu for media lists.
items : list - [(label, action,)*] A list of tuples consisting of label and action pairs.
- label : string or unicode - item's label.
- action : string or unicode - any built-in function to perform.
replaceItems : [opt] bool - True=only your items will show/False=your items will be added to context menu(Default).
List of functions - http://wiki.xbmc.org/?title=List_of_Built_In_Functions
*Note, You can use the above as keywords for arguments and skip certain optional arguments.
Once you use a keyword, all following arguments require the keyword.
example:
- listitem.addContextMenuItems([('Theater Showtimes', 'XBMC.RunScript(special://home/scripts/showtimes/default.py,Iron Man)',)])
"""
def getLabel(*args):
"""getLabel() -- Returns the listitem label.
example:
- label = self.list.getSelectedItem().getLabel()
"""
def getLabel2(*args):
"""getLabel2() -- Returns the listitem's second label.
example:
- label2 = self.list.getSelectedItem().getLabel2()
"""
def getProperty(*args):
"""getProperty(key) -- Returns a listitem property as a string, similar to an infolabel.
key : string - property name.
*Note, Key is NOT case sensitive.
You can use the above as keywords for arguments and skip certain optional arguments.
Once you use a keyword, all following arguments require the keyword.
example:
- AspectRatio = self.list.getSelectedItem().getProperty('AspectRatio')
"""
def isSelected(*args):
"""isSelected() -- Returns the listitem's selected status.
example:
- is = self.list.getSelectedItem().isSelected()
"""
def select(*args):
"""select(selected) -- Sets the listitem's selected status.
selected : bool - True=selected/False=not selected
example:
- self.list.getSelectedItem().select(True)
"""
def setIconImage(*args):
"""setIconImage(icon) -- Sets the listitem's icon image.
icon : string or unicode - image filename.
example:
- self.list.getSelectedItem().setIconImage('emailread.png')
"""
def setInfo(*args):
"""setInfo(type, infoLabels) -- Sets the listitem's infoLabels.
type : string - type of media(video/music/pictures).
infoLabels : dictionary - pairs of { label: value }.
*Note, To set pictures exif info, prepend 'exif:' to the label. Exif values must be passed
as strings, separate value pairs with a comma. (eg. {'exif:resolution': '720,480'}
See CPictureInfoTag::TranslateString in PictureInfoTag.cpp for valid strings.
You can use the above as keywords for arguments and skip certain optional arguments.
Once you use a keyword, all following arguments require the keyword.
General Values that apply to all types:
count : integer (12) - can be used to store an id for later, or for sorting purposes
size : long (1024) - size in bytes
date : string (%d.%m.%Y / 01.01.2009) - file date
Video Values:
genre : string (Comedy)
year : integer (2009)
episode : integer (4)
season : integer (1)
top250 : integer (192)
tracknumber : integer (3)
rating : float (6.4) - range is 0..10
watched : depreciated - use playcount instead
playcount : integer (2) - number of times this item has been played
overlay : integer (2) - range is 0..8. See GUIListItem.h for values
cast : list (Michal C. Hall)
castandrole : list (Michael C. Hall|Dexter)
director : string (Dagur Kari)
mpaa : string (PG-13)
plot : string (Long Description)
plotoutline : string (Short Description)
title : string (Big Fan)
originaltitle : string (Big Fan)
duration : string (3:18)
studio : string (Warner Bros.)
tagline : string (An awesome movie) - short description of movie
writer : string (Robert D. Siegel)
tvshowtitle : string (Heroes)
premiered : string (2005-03-04)
status : string (Continuing) - status of a TVshow
code : string (tt0110293) - IMDb code
aired : string (2008-12-07)
credits : string (Andy Kaufman) - writing credits
lastplayed : string (%Y-%m-%d %h:%m:%s = 2009-04-05 23:16:04)
album : string (The Joshua Tree)
votes : string (12345 votes)
trailer : string (/home/user/trailer.avi)
Music Values:
tracknumber : integer (8)
duration : integer (245) - duration in seconds
year : integer (1998)
genre : string (Rock)
album : string (Pulse)
artist : string (Muse)
title : string (American Pie)
rating : string (3) - single character between 0 and 5
lyrics : string (On a dark desert highway...)
playcount : integer (2) - number of times this item has been played
lastplayed : string (%Y-%m-%d %h:%m:%s = 2009-04-05 23:16:04)
Picture Values:
title : string (In the last summer-1)
picturepath : string (/home/username/pictures/img001.jpg)
exif* : string (See CPictureInfoTag::TranslateString in PictureInfoTag.cpp for valid strings)
example:
- self.list.getSelectedItem().setInfo('video', { 'Genre': 'Comedy' })
"""
def setLabel(*args):
"""setLabel(label) -- Sets the listitem's label.
label : string or unicode - text string.
example:
- self.list.getSelectedItem().setLabel('Casino Royale')
"""
def setLabel2(*args):
"""setLabel2(label2) -- Sets the listitem's second label.
label2 : string or unicode - text string.
example:
- self.list.getSelectedItem().setLabel2('[pg-13]')
"""
def setPath(*args):
"""setPath(path) -- Sets the listitem's path.
path : string or unicode - path, activated when item is clicked.
*Note, You can use the above as keywords for arguments.
example:
- self.list.getSelectedItem().setPath(path='ActivateWindow(Weather)')
"""
def setProperty(*args):
"""setProperty(key, value) -- Sets a listitem property, similar to an infolabel.
key : string - property name.
value : string or unicode - value of property.
*Note, Key is NOT case sensitive.
You can use the above as keywords for arguments and skip certain optional arguments.
Once you use a keyword, all following arguments require the keyword.
Some of these are treated internally by XBMC, such as the 'StartOffset' property, which is
the offset in seconds at which to start playback of an item. Others may be used in the skin
to add extra information, such as 'WatchedCount' for tvshow items
example:
- self.list.getSelectedItem().setProperty('AspectRatio', '1.85 : 1')
- self.list.getSelectedItem().setProperty('StartOffset', '256.4')
"""
def setThumbnailImage(*args):
"""setThumbnailImage(thumb) -- Sets the listitem's thumbnail image.
thumb : string or unicode - image filename.
example:
- self.list.getSelectedItem().setThumbnailImage('emailread.png')
"""
class Window:
"""Window class.
Window(self[, int windowId) -- Create a new Window to draw on.
Specify an id to use an existing window.
Throws: ValueError, if supplied window Id does not exist.
Exception, if more then 200 windows are created.
Deleting this window will activate the old window that was active
and resets (not delete) all controls that are associated with this window.
"""
def __delattr__(*args):
"""x.__delattr__('name') <==> del x.name
"""
def __format__(*args):
"""default object formatter
"""
def __getattribute__(*args):
"""x.__getattribute__('name') <==> x.name
"""
def __hash__(*args):
"""x.__hash__() <==> hash(x)
"""
def __init__(*args):
"""x.__init__(...) initializes x; see x.__class__.__doc__ for signature
"""
def __new__(*args):
"""T.__new__(S, ...) -> a new object with type S, a subtype of T
"""
def __reduce__(*args):
"""helper for pickle
"""
def __reduce_ex__(*args):
"""helper for pickle
"""
def __repr__(*args):
"""x.__repr__() <==> repr(x)
"""
def __setattr__(*args):
"""x.__setattr__('name', value) <==> x.name = value
"""
def __sizeof__(*args):
"""__sizeof__() -> size of object in memory, in bytes
"""
def __str__(*args):
"""x.__str__() <==> str(x)
"""
def __subclasshook__(*args):
"""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).
"""
def addControl(*args):
"""addControl(self, Control) -- Add a Control to this window.
Throws: TypeError, if supplied argument is not a Control type
ReferenceError, if control is already used in another window
RuntimeError, should not happen :-)
The next controls can be added to a window atm
-ControlLabel
-ControlFadeLabel
-ControlTextBox
-ControlButton
-ControlCheckMark
-ControlList
-ControlGroup
-ControlImage
-ControlRadioButton
-ControlProgress
"""
def clearProperties(*args):
"""clearProperties() -- Clears all window properties.
example:
- win = xbmcgui.Window(xbmcgui.getCurrentWindowId())
- win.clearProperties()
"""
def clearProperty(*args):
"""clearProperty(key) -- Clears the specific window property.
key : string - property name.
*Note, key is NOT case sensitive. Equivalent to setProperty(key,'')
You can use the above as keywords for arguments and skip certain optional arguments.
Once you use a keyword, all following arguments require the keyword.
example:
- win = xbmcgui.Window(xbmcgui.getCurrentWindowId())
- win.clearProperty('Category')
"""
def close(*args):
"""close(self) -- Closes this window.
Closes this window by activating the old window.
The window is not deleted with this method.
"""
def doModal(*args):
"""doModal(self) -- Display this window until close() is called.
"""
def getControl(*args):
"""getControl(self, int controlId) -- Get's the control from this window.
Throws: Exception, if Control doesn't exist
controlId doesn't have to be a python control, it can be a control id
from a xbmc window too (you can find id's in the xml files
Note, not python controls are not completely usable yet
You can only use the Control functions
"""
def getFocus(*args):
"""getFocus(self, Control) -- returns the control which is focused.
Throws: SystemError, on Internal error
RuntimeError, if no control has focus
"""
def getFocusId(*args):
"""getFocusId(self, int) -- returns the id of the control which is focused.
Throws: SystemError, on Internal error
RuntimeError, if no control has focus
"""
def getHeight(*args):
"""getHeight(self) -- Returns the height of this screen.
"""
def getProperty(*args):
"""getProperty(key) -- Returns a window property as a string, similar to an infolabel.
key : string - property name.
*Note, key is NOT case sensitive.
You can use the above as keywords for arguments and skip certain optional arguments.
Once you use a keyword, all following arguments require the keyword.
example:
- win = xbmcgui.Window(xbmcgui.getCurrentWindowId())
- category = win.getProperty('Category')
"""
def getResolution(*args):
"""getResolution(self) -- Returns the resolution of the screen. The returned value is one of the following:
0 - 1080i (1920x1080)
1 - 720p (1280x720)
2 - 480p 4:3 (720x480)
3 - 480p 16:9 (720x480)
4 - NTSC 4:3 (720x480)
5 - NTSC 16:9 (720x480)
6 - PAL 4:3 (720x576)
7 - PAL 16:9 (720x576)
8 - PAL60 4:3 (720x480)
9 - PAL60 16:9 (720x480)
"""
def getWidth(*args):
"""getWidth(self) -- Returns the width of this screen.
"""
def onAction(*args):
"""onAction(self, Action action) -- onAction method.
This method will recieve all actions that the main program will send
to this window.
By default, only the PREVIOUS_MENU action is handled.
Overwrite this method to let your script handle all actions.
Don't forget to capture ACTION_PREVIOUS_MENU, else the user can't close this window.
"""
def onClick(*args):
"""onClick(self, Control control) -- onClick method.
This method will recieve all click events that the main program will send
to this window.
"""
def onFocus(*args):
"""onFocus(self, Control control) -- onFocus method.
This method will recieve all focus events that the main program will send
to this window.
"""
def onInit(*args):
"""onInit(self) -- onInit method.
This method will be called to initialize the window
"""
def removeControl(*args):
"""removeControl(self, Control) -- Removes the control from this window.
Throws: TypeError, if supplied argument is not a Control type
RuntimeError, if control is not added to this window
This will not delete the control. It is only removed from the window.
"""
def setCoordinateResolution(*args):
"""setCoordinateResolution(self, int resolution) -- Sets the resolution
that the coordinates of all controls are defined in. Allows XBMC
to scale control positions and width/heights to whatever resolution
XBMC is currently using.
resolution is one of the following:
0 - 1080i (1920x1080)
1 - 720p (1280x720)
2 - 480p 4:3 (720x480)
3 - 480p 16:9 (720x480)
4 - NTSC 4:3 (720x480)
5 - NTSC 16:9 (720x480)
6 - PAL 4:3 (720x576)
7 - PAL 16:9 (720x576)
8 - PAL60 4:3 (720x480)
9 - PAL60 16:9 (720x480)
"""
def setFocus(*args):
"""setFocus(self, Control) -- Give the supplied control focus.
Throws: TypeError, if supplied argument is not a Control type
SystemError, on Internal error
RuntimeError, if control is not added to a window
"""
def setFocusId(*args):
"""setFocusId(self, int) -- Gives the control with the supplied focus.
Throws:
SystemError, on Internal error
RuntimeError, if control is not added to a window
"""
def setProperty(*args):
"""setProperty(key, value) -- Sets a window property, similar to an infolabel.
key : string - property name.
value : string or unicode - value of property.
*Note, key is NOT case sensitive. Setting value to an empty string is equivalent to clearProperty(key)
You can use the above as keywords for arguments and skip certain optional arguments.
Once you use a keyword, all following arguments require the keyword.
example:
- win = xbmcgui.Window(xbmcgui.getCurrentWindowId())
- win.setProperty('Category', 'Newest')
"""
def show(*args):
"""show(self) -- Show this window.
Shows this window by activating it, calling close() after it wil activate the
current window again.
Note, if your script ends this window will be closed to. To show it forever,
make a loop at the end of your script ar use doModal() instead
"""
class WindowDialog:
"""WindowDialog class.
"""
def __delattr__(*args):
"""x.__delattr__('name') <==> del x.name
"""
def __format__(*args):
"""default object formatter
"""
def __getattribute__(*args):
"""x.__getattribute__('name') <==> x.name
"""
def __hash__(*args):
"""x.__hash__() <==> hash(x)
"""
def __init__(*args):
"""x.__init__(...) initializes x; see x.__class__.__doc__ for signature
"""
def __new__(*args):
"""T.__new__(S, ...) -> a new object with type S, a subtype of T
"""
def __reduce__(*args):
"""helper for pickle
"""
def __reduce_ex__(*args):
"""helper for pickle
"""
def __repr__(*args):
"""x.__repr__() <==> repr(x)
"""
def __setattr__(*args):
"""x.__setattr__('name', value) <==> x.name = value
"""
def __sizeof__(*args):
"""__sizeof__() -> size of object in memory, in bytes
"""
def __str__(*args):
"""x.__str__() <==> str(x)
"""
def __subclasshook__(*args):
"""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).
"""
def addControl(*args):
"""addControl(self, Control) -- Add a Control to this window.
Throws: TypeError, if supplied argument is not a Control type
ReferenceError, if control is already used in another window
RuntimeError, should not happen :-)
The next controls can be added to a window atm
-ControlLabel
-ControlFadeLabel
-ControlTextBox
-ControlButton
-ControlCheckMark
-ControlList
-ControlGroup
-ControlImage
-ControlRadioButton
-ControlProgress
"""
def clearProperties(*args):
"""clearProperties() -- Clears all window properties.
example:
- win = xbmcgui.Window(xbmcgui.getCurrentWindowId())
- win.clearProperties()
"""
def clearProperty(*args):
"""clearProperty(key) -- Clears the specific window property.
key : string - property name.
*Note, key is NOT case sensitive. Equivalent to setProperty(key,'')
You can use the above as keywords for arguments and skip certain optional arguments.
Once you use a keyword, all following arguments require the keyword.
example:
- win = xbmcgui.Window(xbmcgui.getCurrentWindowId())
- win.clearProperty('Category')
"""
def close(*args):
"""close(self) -- Closes this window.
Closes this window by activating the old window.
The window is not deleted with this method.
"""
def doModal(*args):
"""doModal(self) -- Display this window until close() is called.
"""
def getControl(*args):
"""getControl(self, int controlId) -- Get's the control from this window.
Throws: Exception, if Control doesn't exist
controlId doesn't have to be a python control, it can be a control id
from a xbmc window too (you can find id's in the xml files
Note, not python controls are not completely usable yet
You can only use the Control functions
"""
def getFocus(*args):
"""getFocus(self, Control) -- returns the control which is focused.
Throws: SystemError, on Internal error
RuntimeError, if no control has focus
"""
def getFocusId(*args):
"""getFocusId(self, int) -- returns the id of the control which is focused.
Throws: SystemError, on Internal error
RuntimeError, if no control has focus
"""
def getHeight(*args):
"""getHeight(self) -- Returns the height of this screen.
"""
def getProperty(*args):
"""getProperty(key) -- Returns a window property as a string, similar to an infolabel.
key : string - property name.
*Note, key is NOT case sensitive.
You can use the above as keywords for arguments and skip certain optional arguments.
Once you use a keyword, all following arguments require the keyword.
example:
- win = xbmcgui.Window(xbmcgui.getCurrentWindowId())
- category = win.getProperty('Category')
"""
def getResolution(*args):
"""getResolution(self) -- Returns the resolution of the screen. The returned value is one of the following:
0 - 1080i (1920x1080)
1 - 720p (1280x720)
2 - 480p 4:3 (720x480)
3 - 480p 16:9 (720x480)
4 - NTSC 4:3 (720x480)
5 - NTSC 16:9 (720x480)
6 - PAL 4:3 (720x576)
7 - PAL 16:9 (720x576)
8 - PAL60 4:3 (720x480)
9 - PAL60 16:9 (720x480)
"""
def getWidth(*args):
"""getWidth(self) -- Returns the width of this screen.
"""
def onAction(*args):
"""onAction(self, Action action) -- onAction method.
This method will recieve all actions that the main program will send
to this window.
By default, only the PREVIOUS_MENU action is handled.
Overwrite this method to let your script handle all actions.
Don't forget to capture ACTION_PREVIOUS_MENU, else the user can't close this window.
"""
def onClick(*args):
"""onClick(self, Control control) -- onClick method.
This method will recieve all click events that the main program will send
to this window.
"""
def onFocus(*args):
"""onFocus(self, Control control) -- onFocus method.
This method will recieve all focus events that the main program will send
to this window.
"""
def onInit(*args):
"""onInit(self) -- onInit method.
This method will be called to initialize the window
"""
def removeControl(*args):
"""removeControl(self, Control) -- Removes the control from this window.
Throws: TypeError, if supplied argument is not a Control type
RuntimeError, if control is not added to this window
This will not delete the control. It is only removed from the window.
"""
def setCoordinateResolution(*args):
"""setCoordinateResolution(self, int resolution) -- Sets the resolution
that the coordinates of all controls are defined in. Allows XBMC
to scale control positions and width/heights to whatever resolution
XBMC is currently using.
resolution is one of the following:
0 - 1080i (1920x1080)
1 - 720p (1280x720)
2 - 480p 4:3 (720x480)
3 - 480p 16:9 (720x480)
4 - NTSC 4:3 (720x480)
5 - NTSC 16:9 (720x480)
6 - PAL 4:3 (720x576)
7 - PAL 16:9 (720x576)
8 - PAL60 4:3 (720x480)
9 - PAL60 16:9 (720x480)
"""
def setFocus(*args):
"""setFocus(self, Control) -- Give the supplied control focus.
Throws: TypeError, if supplied argument is not a Control type
SystemError, on Internal error
RuntimeError, if control is not added to a window
"""
def setFocusId(*args):
"""setFocusId(self, int) -- Gives the control with the supplied focus.
Throws:
SystemError, on Internal error
RuntimeError, if control is not added to a window
"""
def setProperty(*args):
"""setProperty(key, value) -- Sets a window property, similar to an infolabel.
key : string - property name.
value : string or unicode - value of property.
*Note, key is NOT case sensitive. Setting value to an empty string is equivalent to clearProperty(key)
You can use the above as keywords for arguments and skip certain optional arguments.
Once you use a keyword, all following arguments require the keyword.
example:
- win = xbmcgui.Window(xbmcgui.getCurrentWindowId())
- win.setProperty('Category', 'Newest')
"""
def show(*args):
"""show(self) -- Show this window.
Shows this window by activating it, calling close() after it wil activate the
current window again.
Note, if your script ends this window will be closed to. To show it forever,
make a loop at the end of your script ar use doModal() instead
"""
class WindowXML:
"""WindowXML class.
WindowXML(self, xmlFilename, scriptPath[, defaultSkin, defaultRes]) -- Create a new WindowXML script.
xmlFilename : string - the name of the xml file to look for.
scriptPath : string - path to script. used to fallback to if the xml doesn't exist in the current skin. (eg os.getcwd())
defaultSkin : [opt] string - name of the folder in the skins path to look in for the xml. (default='Default')
defaultRes : [opt] string - default skins resolution. (default='720p')
*Note, skin folder structure is eg(resources/skins/Default/720p)
example:
- ui = GUI('script-Lyrics-main.xml', os.getcwd(), 'LCARS', 'PAL')
ui.doModal()
del ui
"""
def __delattr__(*args):
"""x.__delattr__('name') <==> del x.name
"""
def __format__(*args):
"""default object formatter
"""
def __getattribute__(*args):
"""x.__getattribute__('name') <==> x.name
"""
def __hash__(*args):
"""x.__hash__() <==> hash(x)
"""
def __init__(*args):
"""x.__init__(...) initializes x; see x.__class__.__doc__ for signature
"""
def __new__(*args):
"""T.__new__(S, ...) -> a new object with type S, a subtype of T
"""
def __reduce__(*args):
"""helper for pickle
"""
def __reduce_ex__(*args):
"""helper for pickle
"""
def __repr__(*args):
"""x.__repr__() <==> repr(x)
"""
def __setattr__(*args):
"""x.__setattr__('name', value) <==> x.name = value
"""
def __sizeof__(*args):
"""__sizeof__() -> size of object in memory, in bytes
"""
def __str__(*args):
"""x.__str__() <==> str(x)
"""
def __subclasshook__(*args):
"""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).
"""
def addControl(*args):
"""addControl(self, Control) -- Add a Control to this window.
Throws: TypeError, if supplied argument is not a Control type
ReferenceError, if control is already used in another window
RuntimeError, should not happen :-)
The next controls can be added to a window atm
-ControlLabel
-ControlFadeLabel
-ControlTextBox
-ControlButton
-ControlCheckMark
-ControlList
-ControlGroup
-ControlImage
-ControlRadioButton
-ControlProgress
"""
def addItem(*args):
"""addItem(item[, position]) -- Add a new item to this Window List.
item : string, unicode or ListItem - item to add.
position : [opt] integer - position of item to add. (NO Int = Adds to bottom,0 adds to top, 1 adds to one below from top,-1 adds to one above from bottom etc etc )
- If integer positions are greater than list size, negative positions will add to top of list, positive positions will add to bottom of list
example:
- self.addItem('Reboot XBMC', 0)
"""
def clearList(*args):
"""clearList() -- Clear the Window List.
example:
- self.clearList()
"""
def clearProperties(*args):
"""clearProperties() -- Clears all window properties.
example:
- win = xbmcgui.Window(xbmcgui.getCurrentWindowId())
- win.clearProperties()
"""
def clearProperty(*args):
"""clearProperty(key) -- Clears the specific window property.
key : string - property name.
*Note, key is NOT case sensitive. Equivalent to setProperty(key,'')
You can use the above as keywords for arguments and skip certain optional arguments.
Once you use a keyword, all following arguments require the keyword.
example:
- win = xbmcgui.Window(xbmcgui.getCurrentWindowId())
- win.clearProperty('Category')
"""
def close(*args):
"""close(self) -- Closes this window.
Closes this window by activating the old window.
The window is not deleted with this method.
"""
def doModal(*args):
"""doModal(self) -- Display this window until close() is called.
"""
def getControl(*args):
"""getControl(self, int controlId) -- Get's the control from this window.
Throws: Exception, if Control doesn't exist
controlId doesn't have to be a python control, it can be a control id
from a xbmc window too (you can find id's in the xml files
Note, not python controls are not completely usable yet
You can only use the Control functions
"""
def getCurrentListPosition(*args):
"""getCurrentListPosition() -- Gets the current position in the Window List.
example:
- pos = self.getCurrentListPosition()
"""
def getFocus(*args):
"""getFocus(self, Control) -- returns the control which is focused.
Throws: SystemError, on Internal error
RuntimeError, if no control has focus
"""
def getFocusId(*args):
"""getFocusId(self, int) -- returns the id of the control which is focused.
Throws: SystemError, on Internal error
RuntimeError, if no control has focus
"""
def getHeight(*args):
"""getHeight(self) -- Returns the height of this screen.
"""
def getListItem(*args):
"""getListItem(position) -- Returns a given ListItem in this Window List.
position : integer - position of item to return.
example:
- listitem = self.getListItem(6)
"""
def getListSize(*args):
"""getListSize() -- Returns the number of items in this Window List.
example:
- listSize = self.getListSize()
"""
def getProperty(*args):
"""getProperty(key) -- Returns a window property as a string, similar to an infolabel.
key : string - property name.
*Note, key is NOT case sensitive.
You can use the above as keywords for arguments and skip certain optional arguments.
Once you use a keyword, all following arguments require the keyword.
example:
- win = xbmcgui.Window(xbmcgui.getCurrentWindowId())
- category = win.getProperty('Category')
"""
def getResolution(*args):
"""getResolution(self) -- Returns the resolution of the screen. The returned value is one of the following:
0 - 1080i (1920x1080)
1 - 720p (1280x720)
2 - 480p 4:3 (720x480)
3 - 480p 16:9 (720x480)
4 - NTSC 4:3 (720x480)
5 - NTSC 16:9 (720x480)
6 - PAL 4:3 (720x576)
7 - PAL 16:9 (720x576)
8 - PAL60 4:3 (720x480)
9 - PAL60 16:9 (720x480)
"""
def getWidth(*args):
"""getWidth(self) -- Returns the width of this screen.
"""
def onAction(*args):
"""onAction(self, Action action) -- onAction method.
This method will recieve all actions that the main program will send
to this window.
By default, only the PREVIOUS_MENU action is handled.
Overwrite this method to let your script handle all actions.
Don't forget to capture ACTION_PREVIOUS_MENU, else the user can't close this window.
"""
def onClick(*args):
"""onClick(self, Control control) -- onClick method.
This method will recieve all click events that the main program will send
to this window.
"""
def onFocus(*args):
"""onFocus(self, Control control) -- onFocus method.
This method will recieve all focus events that the main program will send
to this window.
"""
def onInit(*args):
"""onInit(self) -- onInit method.
This method will be called to initialize the window
"""
def removeControl(*args):
"""removeControl(self, Control) -- Removes the control from this window.
Throws: TypeError, if supplied argument is not a Control type
RuntimeError, if control is not added to this window
This will not delete the control. It is only removed from the window.
"""
def removeItem(*args):
"""removeItem(position) -- Removes a specified item based on position, from the Window List.
position : integer - position of item to remove.
example:
- self.removeItem(5)
"""
def setCoordinateResolution(*args):
"""setCoordinateResolution(self, int resolution) -- Sets the resolution
that the coordinates of all controls are defined in. Allows XBMC
to scale control positions and width/heights to whatever resolution
XBMC is currently using.
resolution is one of the following:
0 - 1080i (1920x1080)
1 - 720p (1280x720)
2 - 480p 4:3 (720x480)
3 - 480p 16:9 (720x480)
4 - NTSC 4:3 (720x480)
5 - NTSC 16:9 (720x480)
6 - PAL 4:3 (720x576)
7 - PAL 16:9 (720x576)
8 - PAL60 4:3 (720x480)
9 - PAL60 16:9 (720x480)
"""
def setCurrentListPosition(*args):
"""setCurrentListPosition(position) -- Set the current position in the Window List.
position : integer - position of item to set.
example:
- self.setCurrentListPosition(5)
"""
def setFocus(*args):
"""setFocus(self, Control) -- Give the supplied control focus.
Throws: TypeError, if supplied argument is not a Control type
SystemError, on Internal error
RuntimeError, if control is not added to a window
"""
def setFocusId(*args):
"""setFocusId(self, int) -- Gives the control with the supplied focus.
Throws:
SystemError, on Internal error
RuntimeError, if control is not added to a window
"""
def setProperty(*args):
"""setProperty(key, value) -- Sets a container property, similar to an infolabel.
key : string - property name.
value : string or unicode - value of property.
*Note, Key is NOT case sensitive.
You can use the above as keywords for arguments and skip certain optional arguments.
Once you use a keyword, all following arguments require the keyword.
example:
- self.setProperty('Category', 'Newest')
"""
def show(*args):
"""show(self) -- Show this window.
Shows this window by activating it, calling close() after it wil activate the
current window again.
Note, if your script ends this window will be closed to. To show it forever,
make a loop at the end of your script ar use doModal() instead
"""
class WindowXMLDialog:
"""WindowXMLDialog class.
WindowXMLDialog(self, xmlFilename, scriptPath[, defaultSkin, defaultRes]) -- Create a new WindowXMLDialog script.
xmlFilename : string - the name of the xml file to look for.
scriptPath : string - path to script. used to fallback to if the xml doesn't exist in the current skin. (eg os.getcwd())
defaultSkin : [opt] string - name of the folder in the skins path to look in for the xml. (default='Default')
defaultRes : [opt] string - default skins resolution. (default='720p')
*Note, skin folder structure is eg(resources/skins/Default/720p)
example:
- ui = GUI('script-Lyrics-main.xml', os.getcwd(), 'LCARS', 'PAL')
ui.doModal()
del ui
"""
def __delattr__(*args):
"""x.__delattr__('name') <==> del x.name
"""
def __format__(*args):
"""default object formatter
"""
def __getattribute__(*args):
"""x.__getattribute__('name') <==> x.name
"""
def __hash__(*args):
"""x.__hash__() <==> hash(x)
"""
def __init__(*args):
"""x.__init__(...) initializes x; see x.__class__.__doc__ for signature
"""
def __new__(*args):
"""T.__new__(S, ...) -> a new object with type S, a subtype of T
"""
def __reduce__(*args):
"""helper for pickle
"""
def __reduce_ex__(*args):
"""helper for pickle
"""
def __repr__(*args):
"""x.__repr__() <==> repr(x)
"""
def __setattr__(*args):
"""x.__setattr__('name', value) <==> x.name = value
"""
def __sizeof__(*args):
"""__sizeof__() -> size of object in memory, in bytes
"""
def __str__(*args):
"""x.__str__() <==> str(x)
"""
def __subclasshook__(*args):
"""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).
"""
def addControl(*args):
"""addControl(self, Control) -- Add a Control to this window.
Throws: TypeError, if supplied argument is not a Control type
ReferenceError, if control is already used in another window
RuntimeError, should not happen :-)
The next controls can be added to a window atm
-ControlLabel
-ControlFadeLabel
-ControlTextBox
-ControlButton
-ControlCheckMark
-ControlList
-ControlGroup
-ControlImage
-ControlRadioButton
-ControlProgress
"""
def addItem(*args):
"""addItem(item[, position]) -- Add a new item to this Window List.
item : string, unicode or ListItem - item to add.
position : [opt] integer - position of item to add. (NO Int = Adds to bottom,0 adds to top, 1 adds to one below from top,-1 adds to one above from bottom etc etc )
- If integer positions are greater than list size, negative positions will add to top of list, positive positions will add to bottom of list
example:
- self.addItem('Reboot XBMC', 0)
"""
def clearList(*args):
"""clearList() -- Clear the Window List.
example:
- self.clearList()
"""
def clearProperties(*args):
"""clearProperties() -- Clears all window properties.
example:
- win = xbmcgui.Window(xbmcgui.getCurrentWindowId())
- win.clearProperties()
"""
def clearProperty(*args):
"""clearProperty(key) -- Clears the specific window property.
key : string - property name.
*Note, key is NOT case sensitive. Equivalent to setProperty(key,'')
You can use the above as keywords for arguments and skip certain optional arguments.
Once you use a keyword, all following arguments require the keyword.
example:
- win = xbmcgui.Window(xbmcgui.getCurrentWindowId())
- win.clearProperty('Category')
"""
def close(*args):
"""close(self) -- Closes this window.
Closes this window by activating the old window.
The window is not deleted with this method.
"""
def doModal(*args):
"""doModal(self) -- Display this window until close() is called.
"""
def getControl(*args):
"""getControl(self, int controlId) -- Get's the control from this window.
Throws: Exception, if Control doesn't exist
controlId doesn't have to be a python control, it can be a control id
from a xbmc window too (you can find id's in the xml files
Note, not python controls are not completely usable yet
You can only use the Control functions
"""
def getCurrentListPosition(*args):
"""getCurrentListPosition() -- Gets the current position in the Window List.
example:
- pos = self.getCurrentListPosition()
"""
def getFocus(*args):
"""getFocus(self, Control) -- returns the control which is focused.
Throws: SystemError, on Internal error
RuntimeError, if no control has focus
"""
def getFocusId(*args):
"""getFocusId(self, int) -- returns the id of the control which is focused.
Throws: SystemError, on Internal error
RuntimeError, if no control has focus
"""
def getHeight(*args):
"""getHeight(self) -- Returns the height of this screen.
"""
def getListItem(*args):
"""getListItem(position) -- Returns a given ListItem in this Window List.
position : integer - position of item to return.
example:
- listitem = self.getListItem(6)
"""
def getListSize(*args):
"""getListSize() -- Returns the number of items in this Window List.
example:
- listSize = self.getListSize()
"""
def getProperty(*args):
"""getProperty(key) -- Returns a window property as a string, similar to an infolabel.
key : string - property name.
*Note, key is NOT case sensitive.
You can use the above as keywords for arguments and skip certain optional arguments.
Once you use a keyword, all following arguments require the keyword.
example:
- win = xbmcgui.Window(xbmcgui.getCurrentWindowId())
- category = win.getProperty('Category')
"""
def getResolution(*args):
"""getResolution(self) -- Returns the resolution of the screen. The returned value is one of the following:
0 - 1080i (1920x1080)
1 - 720p (1280x720)
2 - 480p 4:3 (720x480)
3 - 480p 16:9 (720x480)
4 - NTSC 4:3 (720x480)
5 - NTSC 16:9 (720x480)
6 - PAL 4:3 (720x576)
7 - PAL 16:9 (720x576)
8 - PAL60 4:3 (720x480)
9 - PAL60 16:9 (720x480)
"""
def getWidth(*args):
"""getWidth(self) -- Returns the width of this screen.
"""
def onAction(*args):
"""onAction(self, Action action) -- onAction method.
This method will recieve all actions that the main program will send
to this window.
By default, only the PREVIOUS_MENU action is handled.
Overwrite this method to let your script handle all actions.
Don't forget to capture ACTION_PREVIOUS_MENU, else the user can't close this window.
"""
def onClick(*args):
"""onClick(self, Control control) -- onClick method.
This method will recieve all click events that the main program will send
to this window.
"""
def onFocus(*args):
"""onFocus(self, Control control) -- onFocus method.
This method will recieve all focus events that the main program will send
to this window.
"""
def onInit(*args):
"""onInit(self) -- onInit method.
This method will be called to initialize the window
"""
def removeControl(*args):
"""removeControl(self, Control) -- Removes the control from this window.
Throws: TypeError, if supplied argument is not a Control type
RuntimeError, if control is not added to this window
This will not delete the control. It is only removed from the window.
"""
def removeItem(*args):
"""removeItem(position) -- Removes a specified item based on position, from the Window List.
position : integer - position of item to remove.
example:
- self.removeItem(5)
"""
def setCoordinateResolution(*args):
"""setCoordinateResolution(self, int resolution) -- Sets the resolution
that the coordinates of all controls are defined in. Allows XBMC
to scale control positions and width/heights to whatever resolution
XBMC is currently using.
resolution is one of the following:
0 - 1080i (1920x1080)
1 - 720p (1280x720)
2 - 480p 4:3 (720x480)
3 - 480p 16:9 (720x480)
4 - NTSC 4:3 (720x480)
5 - NTSC 16:9 (720x480)
6 - PAL 4:3 (720x576)
7 - PAL 16:9 (720x576)
8 - PAL60 4:3 (720x480)
9 - PAL60 16:9 (720x480)
"""
def setCurrentListPosition(*args):
"""setCurrentListPosition(position) -- Set the current position in the Window List.
position : integer - position of item to set.
example:
- self.setCurrentListPosition(5)
"""
def setFocus(*args):
"""setFocus(self, Control) -- Give the supplied control focus.
Throws: TypeError, if supplied argument is not a Control type
SystemError, on Internal error
RuntimeError, if control is not added to a window
"""
def setFocusId(*args):
"""setFocusId(self, int) -- Gives the control with the supplied focus.
Throws:
SystemError, on Internal error
RuntimeError, if control is not added to a window
"""
def setProperty(*args):
"""setProperty(key, value) -- Sets a container property, similar to an infolabel.
key : string - property name.
value : string or unicode - value of property.
*Note, Key is NOT case sensitive.
You can use the above as keywords for arguments and skip certain optional arguments.
Once you use a keyword, all following arguments require the keyword.
example:
- self.setProperty('Category', 'Newest')
"""
def show(*args):
"""show(self) -- Show this window.
Shows this window by activating it, calling close() after it wil activate the
current window again.
Note, if your script ends this window will be closed to. To show it forever,
make a loop at the end of your script ar use doModal() instead
"""
__author__ = str
__credits__ = str
__date__ = str
__platform__ = str
__version__ = str
def getCurrentWindowDialogId(*args):
"""getCurrentWindowDialogId() -- Returns the id for the current 'active' dialog as an integer.
example:
- wid = xbmcgui.getCurrentWindowDialogId()
"""
def getCurrentWindowId(*args):
"""getCurrentWindowId() -- Returns the id for the current 'active' window as an integer.
example:
- wid = xbmcgui.getCurrentWindowId()
"""
def lock(*args):
"""lock() -- Lock the gui until xbmcgui.unlock() is called.
*Note, This will improve performance when doing a lot of gui manipulation at once.
The main program (xbmc itself) will freeze until xbmcgui.unlock() is called.
example:
- xbmcgui.lock()
"""
def unlock(*args):
"""unlock() -- Unlock the gui from a lock() call.
example:
- xbmcgui.unlock()
"""
| [
"[email protected]"
] | |
efff35648033dc2420b00bdc78193848dab512cb | fb5a99b06d2525c46ff24b97cff37ea0a14cc0ca | /opencv/convert_to_grayscale.py | ec6e28a4a805bdda7a25e24d23ae9c7066a73d97 | [] | no_license | khx0/image-processing | efac3d1e39a2ce67701a534633ce8f9af2ba35fe | 9d173b6b298d511583237011b0ffbcd01f3a1fda | refs/heads/master | 2020-03-23T09:48:34.657459 | 2018-08-29T11:15:08 | 2018-08-29T11:15:08 | 141,408,649 | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 1,456 | py | ##########################################################################################
# author: Nikolas Schnellbaecher
# contact: [email protected]
# date: 2018-08-28
# file: convert_to_grayscale.py
# requires: OpenCV
# https://opencv.org
# Tested with Python 3.7.0 and OpenCV version 3.4.2
##########################################################################################
import sys
import time
import datetime
import os
import math
import numpy as np
import matplotlib.pyplot as plt
# import OpenCV python bindings
import cv2
def ensure_dir(dir):
if not os.path.exists(dir):
os.makedirs(dir)
now = datetime.datetime.now()
now = "%s-%s-%s" %(now.year, str(now.month).zfill(2), str(now.day).zfill(2))
BASEDIR = os.path.dirname(os.path.abspath(__file__))
RAWDIR = os.path.join(BASEDIR, 'raw')
OUTDIR = os.path.join(BASEDIR, 'out')
ensure_dir(RAWDIR)
if __name__ == '__main__':
filename = 'test_image.png'
img = cv2.imread(os.path.join(RAWDIR, filename))
print("RGB image shape =", img.shape)
# convert RGB 3 channel image to grayscale
img_gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
print("Grayscale image shape =", img_gray.shape)
# plot grayscale image using matplotlib's imshow command
fig, ax = plt.subplots()
ax.imshow(img_gray,
interpolation = 'nearest',
cmap = plt.cm.gray)
plt.show()
| [
"[email protected]"
] | |
c886e1c66c831d014b2619c235b6c78fbff842fb | 0874ecce812388593a34014cad26d3b4959d07ac | /awards/views.py | bc491a3653604b8ff42c8c15273d84fadf3688b1 | [
"MIT"
] | permissive | melissa-koi/awwardsclone | d990f82eb9d1354a54af68d7fa61fe5856bfd2c1 | b82447cea82672038ea9fa9d9ca9867bff3c35f0 | refs/heads/main | 2023-06-01T12:20:05.315928 | 2021-06-03T15:31:21 | 2021-06-03T15:31:21 | 372,236,218 | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 4,212 | py | from django.db.models import Avg, F, Sum
from django.shortcuts import render, redirect
from .forms import RegisterForm, RateForm, UploadWeb, CreateProfileForm, UserUpdateForm, ProfileUpdateForm
from django.contrib.auth import authenticate, login, logout
from django.contrib.auth.decorators import login_required
from django.contrib import messages
from .models import Website, Rate,Profile
from django.contrib.auth.models import User
# Create your views here.
@login_required(login_url='/login/')
def home(request):
title = "Home Page"
cards = Website.get_all()
return render(request, 'index.html' ,{"title": title, "cards": cards})
@login_required(login_url='/login/')
def site(request, pk):
title= "site"
photo = Website.objects.get(id=pk)
site = Website.objects.get(id=pk)
rates = Rate.objects.filter(website=site)
user = request.user
if request.method == 'POST':
form = RateForm(request.POST)
if form.is_valid():
rate = form.save(commit=False)
rate.user = user
rate.website = site
rate.save()
else:
form = RateForm()
return render(request, 'site.html', {"title": title, "photo": photo, "form":form, "rates":rates})
@login_required(login_url='/login/')
def post_website(request):
current_user = request.user
print(current_user)
if request.method == "POST":
form = UploadWeb(request.POST, request.FILES)
if form.is_valid():
img = form.save(commit=False)
img.author =current_user
img.save()
return redirect('home')
else:
form = UploadWeb()
return render(request, 'post_website.html', {"form":form})
@login_required(login_url='/login/')
def profile(request,username):
title="profile"
site = Website.get_user(username)
profile = Profile.get_user(username)
print(request.user)
return render(request, 'profile.html', {"title": title, "cards":site, "profiles":profile})
@login_required(login_url='/login/')
def update_profile(request,profile_id):
user=User.objects.get(pk=profile_id)
if request.method == "POST":
u_form = UserUpdateForm(request.POST,instance=request.user)
p_form = ProfileUpdateForm(request.POST,request.FILES,instance=request.user.profile)
if u_form.is_valid() and p_form.is_valid():
u_form.save()
p_form.save()
messages.success(request,f"You Have Successfully Updated Your Profile!")
else:
u_form = UserUpdateForm(instance=request.user)
p_form = ProfileUpdateForm(instance=request.user.profile)
return render(request,'update_profile.html',{"u_form":u_form, "p_form":p_form})
@login_required(login_url='/login/')
def search_results(request):
if 'projects' in request.GET and request.GET["projects"]:
search_term = request.GET.get("projects")
searched_project = Website.get_projects(search_term)
message = f'{search_term}'
return render(request, 'search.html',{"message":message,"cards": searched_project})
else:
message = "You haven't searched for any term"
return render(request, 'search.html',{"message":message})
def registerUser(request):
form = RegisterForm()
if request.method == 'POST':
form = RegisterForm(request.POST)
if form.is_valid():
form.save()
return redirect('login')
else:
form = RegisterForm()
return render(request, 'accounts/register.html', {'form':form})
def loginUser(request):
if request.method == 'POST':
username = request.POST.get('username')
password = request.POST.get('password')
if username and password:
user = authenticate(username=username, password=password)
if user is not None:
login(request, user)
return redirect('home')
else:
messages.error(request, 'Username or Password is Incorrect')
else:
messages.error(request, 'Fill out all the fields')
return render(request, 'accounts/login.html', {})
def logoutUser(request):
logout(request)
return redirect('home')
| [
"[email protected]"
] | |
8824696e2db2d6a34fb6fc5a99c2eac887d2018b | 20e9106fd6398691dcfe95c18d75bf1e09d28369 | /runtime/Python2/src/antlr4/ParserRuleContext.py | f0eb4995f6079786342c04a78b4764390c69a617 | [
"LicenseRef-scancode-warranty-disclaimer",
"BSD-3-Clause",
"BSD-2-Clause"
] | permissive | alvarogarcia7/antlr4 | 4eb30d1e79adc31fe1901129acc2b4f91a1c0657 | 82372aae2ce73abe5e087a159a517a0890224fb7 | refs/heads/master | 2021-01-04T02:41:55.596897 | 2016-12-10T00:05:11 | 2016-12-10T00:05:11 | 76,113,547 | 0 | 0 | null | 2016-12-10T13:15:45 | 2016-12-10T13:15:45 | null | UTF-8 | Python | false | false | 5,715 | py | # Copyright (c) 2012-2016 The ANTLR Project. All rights reserved.
# Use of this file is governed by the BSD 3-clause license that
# can be found in the LICENSE.txt file in the project root.
#* A rule invocation record for parsing.
#
# Contains all of the information about the current rule not stored in the
# RuleContext. It handles parse tree children list, Any ATN state
# tracing, and the default values available for rule indications:
# start, stop, rule index, current alt number, current
# ATN state.
#
# Subclasses made for each rule and grammar track the parameters,
# return values, locals, and labels specific to that rule. These
# are the objects that are returned from rules.
#
# Note text is not an actual field of a rule return value; it is computed
# from start and stop using the input stream's toString() method. I
# could add a ctor to this so that we can pass in and store the input
# stream, but I'm not sure we want to do that. It would seem to be undefined
# to get the .text property anyway if the rule matches tokens from multiple
# input streams.
#
# I do not use getters for fields of objects that are used simply to
# group values such as this aggregate. The getters/setters are there to
# satisfy the superclass interface.
from antlr4.RuleContext import RuleContext
from antlr4.tree.Tree import TerminalNodeImpl, ErrorNodeImpl, TerminalNode, INVALID_INTERVAL
class ParserRuleContext(RuleContext):
def __init__(self, parent = None, invokingStateNumber = None ):
super(ParserRuleContext, self).__init__(parent, invokingStateNumber)
#* If we are debugging or building a parse tree for a visitor,
# we need to track all of the tokens and rule invocations associated
# with this rule's context. This is empty for parsing w/o tree constr.
# operation because we don't the need to track the details about
# how we parse this rule.
#/
self.children = None
self.start = None
self.stop = None
# The exception that forced this rule to return. If the rule successfully
# completed, this is {@code null}.
self.exception = None
#* COPY a ctx (I'm deliberately not using copy constructor)#/
def copyFrom(self, ctx):
# from RuleContext
self.parentCtx = ctx.parentCtx
self.invokingState = ctx.invokingState
self.children = None
self.start = ctx.start
self.stop = ctx.stop
# Double dispatch methods for listeners
def enterRule(self, listener):
pass
def exitRule(self, listener):
pass
#* Does not set parent link; other add methods do that#/
def addChild(self, child):
if self.children is None:
self.children = []
self.children.append(child)
return child
#* Used by enterOuterAlt to toss out a RuleContext previously added as
# we entered a rule. If we have # label, we will need to remove
# generic ruleContext object.
#/
def removeLastChild(self):
if self.children is not None:
del self.children[len(self.children)-1]
def addTokenNode(self, token):
node = TerminalNodeImpl(token)
self.addChild(node)
node.parentCtx = self
return node
def addErrorNode(self, badToken):
node = ErrorNodeImpl(badToken)
self.addChild(node)
node.parentCtx = self
return node
def getChild(self, i, ttype = None):
if ttype is None:
return self.children[i] if len(self.children)>i else None
else:
for child in self.getChildren():
if not isinstance(child, ttype):
continue
if i==0:
return child
i -= 1
return None
def getChildren(self, predicate = None):
if self.children is not None:
for child in self.children:
if predicate is not None and not predicate(child):
continue
yield child
def getToken(self, ttype, i):
for child in self.getChildren():
if not isinstance(child, TerminalNode):
continue
if child.symbol.type != ttype:
continue
if i==0:
return child
i -= 1
return None
def getTokens(self, ttype ):
if self.getChildren() is None:
return []
tokens = []
for child in self.getChildren():
if not isinstance(child, TerminalNode):
continue
if child.symbol.type != ttype:
continue
tokens.append(child)
return tokens
def getTypedRuleContext(self, ctxType, i):
return self.getChild(i, ctxType)
def getTypedRuleContexts(self, ctxType):
children = self.getChildren()
if children is None:
return []
contexts = []
for child in children:
if not isinstance(child, ctxType):
continue
contexts.append(child)
return contexts
def getChildCount(self):
return len(self.children) if self.children else 0
def getSourceInterval(self):
if self.start is None or self.stop is None:
return INVALID_INTERVAL
else:
return (self.start.tokenIndex, self.stop.tokenIndex)
RuleContext.EMPTY = ParserRuleContext()
class InterpreterRuleContext(ParserRuleContext):
def __init__(self, parent, invokingStateNumber, ruleIndex):
super(InterpreterRuleContext, self).__init__(parent, invokingStateNumber)
self.ruleIndex = ruleIndex
| [
"[email protected]"
] | |
2115b468d4bc223050b6dcdf147277fe1a3ae7cf | 7252d86a55e5e388d9e7c81c3390679116a41958 | /pages/mipagina/urls.py | b79f832ad575b90c9fbfbd83f5b10ee435653d0b | [] | no_license | IvanPuentes/Proyecto_U4_Regula | f979f2a15fbd6dd722a707dd5bf412e5cbfaee70 | 811edd72ceea450f6392d5d228e67406bf1c0371 | refs/heads/master | 2023-06-04T04:42:18.334554 | 2021-06-22T00:51:43 | 2021-06-22T00:51:43 | 379,051,861 | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 3,147 | py | from django.urls import path,include
from .views import HomePageView,TecView,RegistrarView,CreateViajesView,CreateVuelosView,VueloPageView,CreateHospedajeView,HospedajePageView,UpdatePageView,UpdateVueloPageView,UpdateHospedajePageView,DescripViajesPageView,DescripVuelosPageView,DescripHospPageView,ViajeDeleteView,AboutPageView,ComentarioCreateView,SearchResultListview,VueloDeleteView,HospDeleteView,ComentarioViajeCreateView,ComentarioHospCreateView
from django.contrib.auth.views import PasswordResetView, PasswordResetDoneView, PasswordResetConfirmView, PasswordResetCompleteView
#importar las librerias y los archivos
#rutas para los templates
urlpatterns=[
path('',HomePageView.as_view(),name='home'),
path('Vuelos',VueloPageView.as_view(),name='vuelo'),
path('Hospedaje',HospedajePageView.as_view(),name='hospedaje'),
path('orders/', include('orders.urls')),
path('Acerca_de',AboutPageView.as_view(), name='About'),
path('registrar/', RegistrarView.as_view(),name='registrar'),
path('Nuevo/Viaje',CreateViajesView.as_view(),name='CreateViaje'),
path('Nuevo/Vuelo',CreateVuelosView.as_view(),name='CreateVuelo'),
path('Nuevo/Hospedaje',CreateHospedajeView.as_view(),name='CreateHospedaje'),
path('Viajes/<int:pk>/Update',UpdatePageView.as_view(),name='EditarViaje'),
path('Vuelo/<int:pk>/Update',UpdateVueloPageView.as_view(),name='EditarVuelo'),
path('Hospedaje/<int:pk>/Update',UpdateHospedajePageView.as_view(),name='EditarHospedaje'),
path('Descripcion/Viajes/<int:pk>',DescripViajesPageView.as_view(),name='DescViajes'),
path('Descripcion/Vuelos/<int:pk>',DescripVuelosPageView.as_view(),name='DescVuelos'),
path('Descripcion/Hospedaje/<int:pk>',DescripHospPageView.as_view(),name='DescHosp'),
path('Viaje/<int:pk>/delete',ViajeDeleteView.as_view(),name='deleteViaje'),
path('Vuelo/<int:pk>/delete',VueloDeleteView.as_view(),name='deleteVuelo'),
path('Hospedaje/<int:pk>/delete',HospDeleteView.as_view(),name='deleteHosp'),
path('Tec',TecView .as_view(),name='tec'),
path('Comentarios/<int:VueloComent>',ComentarioCreateView.as_view(),name='comentarioNuevo'),
path('ComentariosViaje/<int:ViajeComent>',ComentarioViajeCreateView.as_view(),name='comentarioNuevoV'),
path('ComentariosHosp/<int:HospComent>',ComentarioHospCreateView.as_view(),name='comentarioH'),
path('search', SearchResultListview.as_view(), name='search_result'),
#rutas para los cambios y reset de contraseñas
path('password_reset/', PasswordResetView.as_view(
template_name='registration/password_reset.html'
),name='password_reset'),
path('password_reset_done/', PasswordResetDoneView.as_view(
template_name='password_reset_done.html'
),name='password_reset_done'),
path('usuarios/password_reset_confirm/<u1db64>/<token>', PasswordResetConfirmView.as_view(
template_name='password_reset_confirm.html'
),name='password_reset_confirm'),
path('usuarios/password_reset_complete', PasswordResetCompleteView.as_view(
template_name='password_reset_complete.html'
),name='password_reset_complete'),
]
| [
"[email protected]"
] | |
845d79dde7ac418ae4ca8388a71edea4e4bcbc80 | 6fcfb638fa725b6d21083ec54e3609fc1b287d9e | /python/zhaw_neural_style/neural_style-master/texturenet/make_image.py | 1b842a5854b20a9d13e4427dda47c367a03a74e6 | [] | no_license | LiuFang816/SALSTM_py_data | 6db258e51858aeff14af38898fef715b46980ac1 | d494b3041069d377d6a7a9c296a14334f2fa5acc | refs/heads/master | 2022-12-25T06:39:52.222097 | 2019-12-12T08:49:07 | 2019-12-12T08:49:07 | 227,546,525 | 10 | 7 | null | 2022-12-19T02:53:01 | 2019-12-12T07:29:39 | Python | UTF-8 | Python | false | false | 3,007 | py | import os
import time
import mxnet as mx
import numpy as np
import symbol
import cPickle as pickle
from skimage import io, transform
def crop_img(im, size):
im = io.imread(im)
if im.shape[0]*size[1] > im.shape[1]*size[0]:
c = (im.shape[0]-1.*im.shape[1]/size[1]*size[0]) / 2
c = int(c)
im = im[c:-(1+c),:,:]
else:
c = (im.shape[1]-1.*im.shape[0]/size[0]*size[1]) / 2
c = int(c)
im = im[:,c:-(1+c),:]
im = transform.resize(im, size)
im *= 255
return im
def preprocess_img(im, size):
if type(size) == int:
size = (size, size)
im = crop_img(im, size)
im = im.astype(np.float32)
im = np.swapaxes(im, 0, 2)
im = np.swapaxes(im, 1, 2)
im[0,:] -= 123.68
im[1,:] -= 116.779
im[2,:] -= 103.939
im = np.expand_dims(im, 0)
return im
def postprocess_img(im):
im = im[0]
im[0,:] += 123.68
im[1,:] += 116.779
im[2,:] += 103.939
im = np.swapaxes(im, 0, 2)
im = np.swapaxes(im, 0, 1)
im[im<0] = 0
im[im>255] = 255
return im.astype(np.uint8)
class Maker():
def __init__(self, model_prefix, output_shape, task):
self.task = task
s1, s0 = output_shape
s0 = s0//32*32
s1 = s1//32*32
self.s0 = s0
self.s1 = s1
if task == 'texture':
self.m = 5
generator = symbol.generator_symbol(self.m, task)
args = mx.nd.load('%s_args.nd'%model_prefix)
for i in range(self.m):
args['z_%d'%i] = mx.nd.zeros([1,3,s0/16*2**i,s1/16*2**i], mx.gpu())
else:
self.m = 5
generator = symbol.generator_symbol(self.m, task)
args = mx.nd.load('%s_args.nd'%model_prefix)
for i in range(self.m):
args['znoise_%d'%i] = mx.nd.zeros([1,3,s0/16*2**i,s1/16*2**i], mx.gpu())
args['zim_%d'%i] = mx.nd.zeros([1,3,s0/16*2**i,s1/16*2**i], mx.gpu())
self.gene_executor = generator.bind(ctx=mx.gpu(), args=args, aux_states=mx.nd.load('%s_auxs.nd'%model_prefix))
def generate(self, save_path, content_path=''):
if self.task == 'texture':
for i in range(self.m):
self.gene_executor.arg_dict['z_%d'%i][:] = mx.random.uniform(-128,128,[1,3,self.s0/16*2**i,self.s1/16*2**i])
self.gene_executor.forward(is_train=True)
out = self.gene_executor.outputs[0].asnumpy()
im = postprocess_img(out)
io.imsave(save_path, im)
else:
for i in range(self.m):
self.gene_executor.arg_dict['znoise_%d'%i][:] = mx.random.uniform(-10,10,[1,3,self.s0/16*2**i,self.s1/16*2**i])
self.gene_executor.arg_dict['zim_%d'%i][:] = preprocess_img(content_path, (self.s0/16*2**i,self.s1/16*2**i))
self.gene_executor.forward(is_train=True)
out = self.gene_executor.outputs[0].asnumpy()
im = postprocess_img(out)
io.imsave(save_path, im)
| [
"[email protected]"
] | |
ce4f7f8a6237434ae7a29315408556d8fbc515a1 | 4db61d3e2b36d11aff43be060f8bab6fef3a6c63 | /flask/index.py | 2b6e8fb05982a31b2f54f967d6233860b58f71f7 | [] | no_license | ramalho/microfinder | 1d59daa3cbb741d80f759ab3a4dd8c189aeed80b | 0be75d9ff0003e570668db5bcd51e6e5e72821c4 | refs/heads/master | 2020-03-24T18:17:37.355736 | 2018-10-10T15:02:22 | 2018-10-10T15:02:22 | 142,888,420 | 0 | 0 | null | 2018-07-30T14:39:53 | 2018-07-30T14:39:52 | null | UTF-8 | Python | false | false | 781 | py |
import sys, unicodedata
import flask
def add_entry(index, char, name):
for word in name.split():
index.setdefault(word, []).append(char)
def index():
entries = {}
for code in range(sys.maxunicode):
char = chr(code)
try:
name = unicodedata.name(char)
except ValueError:
continue
add_entry(entries, char, name)
return entries
word_index = index()
app = flask.Flask(__name__)
@app.route("/")
def root():
return "This is the microfinder index API server"
@app.route("/<query_str>")
def query(query_str):
try:
res = word_index[query_str.upper()]
except KeyError:
flask.abort(404)
else:
return flask.jsonify(res)
if __name__ == "__main__":
app.run()
| [
"[email protected]"
] | |
b118cd2999cf826b059834c59cf36cb1395e6d13 | a560269290749e10466b1a29584f06a2b8385a47 | /Notebooks/py/element/titanic-simple-xgboost-model/titanic-simple-xgboost-model.py | c62cce354181f28a6563da15d0f966cfde7f6e46 | [] | no_license | nischalshrestha/automatic_wat_discovery | c71befad1aa358ae876d5494a67b0f4aa1266f23 | 982e700d8e4698a501afffd6c3a2f35346c34f95 | refs/heads/master | 2022-04-07T12:40:24.376871 | 2020-03-15T22:27:39 | 2020-03-15T22:27:39 | 208,379,586 | 2 | 1 | null | null | null | null | UTF-8 | Python | false | false | 3,757 | py | #!/usr/bin/env python
# coding: utf-8
# # Basic modeling
# This notebook presents simple and quick way to implement a XGBoost classifier on the Titanic dataset. It doesn't come to data visualization and feature engineering. This is kind of a first approach.
# In[ ]:
import numpy as np # linear algebra
import pandas as pd # data processing, CSV file I/O (e.g. pd.read_csv)
from sklearn.metrics import accuracy_score
from sklearn import model_selection
from sklearn import preprocessing
from xgboost import XGBClassifier
import matplotlib.pylab as pylab
import matplotlib.pyplot as plt
from sklearn.model_selection import KFold
from sklearn.model_selection import cross_val_score
from sklearn.model_selection import GridSearchCV
from sklearn.ensemble import BaggingClassifier
def extractDeck(x):
if str(x) != "nan":
return str(x)[0]
else :
return
#Import data
train = pd.read_csv('../input/train.csv')
test = pd.read_csv('../input/test.csv')
combine = train.drop(["Survived"], axis=1).append(test).drop(["PassengerId", "Ticket"], axis=1)
target = train['Survived']
#Feature preprocessing
combine["hasParents"] = combine["Parch"].apply(lambda x : (x>0)*1)
combine["hasSibs"] = combine["SibSp"].apply(lambda x : (x>0)*1)
combine["title"] = combine['Name'].str.extract(' ([A-Za-z]+)\.', expand=False)
combine["Deck"] = combine['Cabin'].apply(extractDeck)
combine.drop(["Parch", "SibSp", "Cabin", "Name"], axis=1)
#Turning categorical to integer
combine['Sex'] = combine['Sex'].map( {'female': 1, 'male': 0} ).astype(int)
#One hot encoding on Embarked
combine['Embarked'].fillna('S', inplace = True)
#combine = pd.get_dummies(combine)#, columns = ['Embarked'])
#Fill the blank
combine['Age'].fillna(combine['Age'].dropna().median(), inplace = True)
#Turning age to ranges
combine.loc[(combine['Age'] <= 16), 'Age'] = 0
combine.loc[(combine['Age'] > 16) & (combine['Age'] <= 32), 'Age'] = 1
combine.loc[(combine['Age'] > 32) & (combine['Age'] <= 48), 'Age'] = 2
combine.loc[(combine['Age'] > 48) & (combine['Age'] <= 64), 'Age'] = 3
combine.loc[(combine['Age'] > 64), 'Age']
#Filling the blank
combine['Fare'].fillna(combine['Fare'].dropna().median(), inplace=True)
#Turning fare to ranges
combine.loc[ combine['Fare'] <= 7.91, 'Fare'] = 0
combine.loc[(combine['Fare'] > 7.91) & (combine['Fare'] <= 14.454), 'Fare'] = 1
combine.loc[(combine['Fare'] > 14.454) & (combine['Fare'] <= 31), 'Fare'] = 2
combine.loc[ combine['Fare'] > 31, 'Fare'] = 3
combine['Fare'] = combine['Fare'].astype(int)
combine["Pclass"]=combine["Pclass"].astype("str")
combine = pd.get_dummies(combine)
#Defining learning vectors
nb = train.shape[0]
X = combine[:nb]
y = target
X_train, X_test, y_train, y_test = model_selection.train_test_split(X, y, test_size=0.1, train_size=0.9)
#XGBoost model tuning
model = XGBClassifier(booster='gbtree', silent=1, seed=0, base_score=0.5, subsample=0.75)
parameters = {'n_estimators':[75], #50,100
'max_depth':[4],#1,10
'gamma':[4],#0,6
'max_delta_step':[1],#0,2
'min_child_weight':[1], #3,5
'colsample_bytree':[0.55,0.6,0.65], #0.5,
'learning_rate': [0.001,0.01,0.1]
}
tune_model = GridSearchCV(model, parameters, cv=3, scoring='accuracy')
tune_model.fit(X_train,y_train)
print('Best parameters :', tune_model.best_params_)
print('Results :', format(tune_model.cv_results_['mean_test_score'][tune_model.best_index_]*100))
#Learn on the whole data
tune_model.fit(X, y)
Y_pred = tune_model.predict(combine[nb:])
#Submit the prediction
submission = pd.DataFrame({
"PassengerId": test["PassengerId"],
"Survived": Y_pred
})
submission.to_csv('submission.csv', index=False)
# In[ ]:
| [
"[email protected]"
] | |
4c13ff083a3f83d44271bb1ae4ac3a09c020ae8e | 7298d1692c6948f0880e550d6100c63a64ce3ea1 | /deriva-annotations/catalog99/catalog-configs/PDB/ihm_cross_link_restraint.py | 7a89f39fecd5ef4fab2ac334413236a515ba6b5b | [] | no_license | informatics-isi-edu/protein-database | b7684b3d08dbf22c1e7c4a4b8460248c6f0d2c6d | ce4be1bf13e6b1c22f3fccbb513824782609991f | refs/heads/master | 2023-08-16T10:24:10.206574 | 2023-07-25T23:10:42 | 2023-07-25T23:10:42 | 174,095,941 | 2 | 0 | null | 2023-06-16T19:44:43 | 2019-03-06T07:39:14 | Python | UTF-8 | Python | false | false | 26,097 | py | import argparse
from deriva.core import ErmrestCatalog, AttrDict, get_credential
import deriva.core.ermrest_model as em
from deriva.core.ermrest_config import tag as chaise_tags
from deriva.utils.catalog.manage.update_catalog import CatalogUpdater, parse_args
groups = {
'pdb-reader': 'https://auth.globus.org/8875a770-3c40-11e9-a8c8-0ee7d80087ee',
'pdb-writer': 'https://auth.globus.org/c94a1e5c-3c40-11e9-a5d1-0aacc65bfe9a',
'pdb-admin': 'https://auth.globus.org/0b98092c-3c41-11e9-a8c8-0ee7d80087ee',
'pdb-curator': 'https://auth.globus.org/eef3e02a-3c40-11e9-9276-0edc9bdd56a6',
'isrd-staff': 'https://auth.globus.org/176baec4-ed26-11e5-8e88-22000ab4b42b',
'pdb-submitter': 'https://auth.globus.org/99da042e-64a6-11ea-ad5f-0ef992ed7ca1'
}
table_name = 'ihm_cross_link_restraint'
schema_name = 'PDB'
column_annotations = {
'structure_id': {},
'asym_id_1': {},
'asym_id_2': {},
'atom_id_1': {},
'atom_id_2': {},
'comp_id_1': {},
'comp_id_2': {},
'conditional_crosslink_flag': {},
'distance_threshold': {},
'entity_id_1': {},
'entity_id_2': {},
'group_id': {},
'id': {},
'model_granularity': {},
'psi': {},
'restraint_type': {},
'seq_id_1': {},
'seq_id_2': {},
'sigma_1': {},
'sigma_2': {},
'Owner': {}
}
column_comment = {
'structure_id': 'A reference to table entry.id.',
'asym_id_1': 'A reference to table struct_asym.id.',
'asym_id_2': 'A reference to table struct_asym.id.',
'atom_id_1': 'type:text\nThe atom identifier for the first monomer partner in the cross link.\n This data item is a pointer to _chem_comp_atom.atom_id in the \n CHEM_COMP_ATOM category.',
'atom_id_2': 'type:text\nThe atom identifier for the second monomer partner in the cross link.\n This data item is a pointer to _chem_comp_atom.atom_id in the \n CHEM_COMP_ATOM category.',
'comp_id_1': 'A reference to table chem_comp.id.',
'comp_id_2': 'A reference to table chem_comp.id.',
'conditional_crosslink_flag': 'type:text\nThe cross link conditionality.',
'distance_threshold': 'type:float4\nThe distance threshold applied to this crosslink in the integrative modeling task.',
'entity_id_1': 'A reference to table entity.id.',
'entity_id_2': 'A reference to table entity.id.',
'group_id': 'A reference to table ihm_cross_link_list.id.',
'id': 'type:int4\nA unique identifier for the cross link record.',
'model_granularity': 'type:text\nThe coarse-graining information for the crosslink implementation.',
'psi': 'type:float4\nThe uncertainty in the crosslinking experimental data;\n may be approximated to the false positive rate.',
'restraint_type': 'type:text\nThe type of the cross link restraint applied.',
'seq_id_1': 'A reference to table entity_poly_seq.num.',
'seq_id_2': 'A reference to table entity_poly_seq.num.',
'sigma_1': 'type:float4\nThe uncertainty in the position of residue 1 in the crosslink\n arising due to the multi-scale nature of the model represention.',
'sigma_2': 'type:float4\nThe uncertainty in the position of residue 2 in the crosslink\n arising due to the multi-scale nature of the model represention.',
'Owner': 'Group that can update the record.'
}
column_acls = {}
column_acl_bindings = {}
column_defs = [
em.Column.define(
'structure_id',
em.builtin_types['text'],
nullok=False,
comment=column_comment['structure_id'],
),
em.Column.define(
'asym_id_1', em.builtin_types['text'], nullok=False, comment=column_comment['asym_id_1'],
),
em.Column.define(
'asym_id_2', em.builtin_types['text'], nullok=False, comment=column_comment['asym_id_2'],
),
em.Column.define('atom_id_1', em.builtin_types['text'], comment=column_comment['atom_id_1'],
),
em.Column.define('atom_id_2', em.builtin_types['text'], comment=column_comment['atom_id_2'],
),
em.Column.define(
'comp_id_1', em.builtin_types['text'], nullok=False, comment=column_comment['comp_id_1'],
),
em.Column.define(
'comp_id_2', em.builtin_types['text'], nullok=False, comment=column_comment['comp_id_2'],
),
em.Column.define(
'conditional_crosslink_flag',
em.builtin_types['text'],
comment=column_comment['conditional_crosslink_flag'],
),
em.Column.define(
'distance_threshold',
em.builtin_types['float4'],
nullok=False,
comment=column_comment['distance_threshold'],
),
em.Column.define(
'entity_id_1',
em.builtin_types['text'],
nullok=False,
comment=column_comment['entity_id_1'],
),
em.Column.define(
'entity_id_2',
em.builtin_types['text'],
nullok=False,
comment=column_comment['entity_id_2'],
),
em.Column.define(
'group_id', em.builtin_types['int4'], nullok=False, comment=column_comment['group_id'],
),
em.Column.define('id', em.builtin_types['int4'], nullok=False, comment=column_comment['id'],
),
em.Column.define(
'model_granularity',
em.builtin_types['text'],
nullok=False,
comment=column_comment['model_granularity'],
),
em.Column.define('psi', em.builtin_types['float4'], comment=column_comment['psi'],
),
em.Column.define(
'restraint_type', em.builtin_types['text'], comment=column_comment['restraint_type'],
),
em.Column.define(
'seq_id_1', em.builtin_types['int4'], nullok=False, comment=column_comment['seq_id_1'],
),
em.Column.define(
'seq_id_2', em.builtin_types['int4'], nullok=False, comment=column_comment['seq_id_2'],
),
em.Column.define('sigma_1', em.builtin_types['float4'], comment=column_comment['sigma_1'],
),
em.Column.define('sigma_2', em.builtin_types['float4'], comment=column_comment['sigma_2'],
),
em.Column.define('Owner', em.builtin_types['text'], comment=column_comment['Owner'],
),
em.Column.define('Entry_Related_File', em.builtin_types['text'],
),
]
display = {'name': 'Chemical Crosslinking Restraints Applied in the Modeling'}
visible_columns = {
'*': [
{
'source': 'RID'
}, {
'source': [{
'outbound': ['PDB', 'ihm_cross_link_restraint_structure_id_fkey']
}, 'RID']
}, 'id', {
'source': [{
'outbound': ['PDB', 'ihm_cross_link_restraint_group_id_fkey']
}, 'RID'],
'markdown_name': 'group id'
}, {
'source': [
{
'outbound': ['PDB', 'ihm_cross_link_restraint_mm_poly_res_label_1_fkey']
}, 'entity_id'
],
'markdown_name': 'entity id 1'
}, {
'source': [
{
'outbound': ['PDB', 'ihm_cross_link_restraint_mm_poly_res_label_2_fkey']
}, 'entity_id'
],
'markdown_name': 'entity id 2'
}, {
'source': [{
'outbound': ['PDB', 'ihm_cross_link_restraint_asym_id_1_fkey']
}, 'RID'],
'markdown_name': 'asym id 1'
}, {
'source': [{
'outbound': ['PDB', 'ihm_cross_link_restraint_asym_id_2_fkey']
}, 'RID'],
'markdown_name': 'asym id 2'
}, {
'source': [
{
'outbound': ['PDB', 'ihm_cross_link_restraint_mm_poly_res_label_1_fkey']
}, 'mon_id'
],
'markdown_name': 'comp id 1'
}, {
'source': [
{
'outbound': ['PDB', 'ihm_cross_link_restraint_mm_poly_res_label_2_fkey']
}, 'mon_id'
],
'markdown_name': 'comp id 2'
}, {
'source': [
{
'outbound': ['PDB', 'ihm_cross_link_restraint_mm_poly_res_label_1_fkey']
}, 'num'
],
'markdown_name': 'seq id 1'
}, {
'source': [
{
'outbound': ['PDB', 'ihm_cross_link_restraint_mm_poly_res_label_2_fkey']
}, 'num'
],
'markdown_name': 'seq id 2'
}, {
'source': 'atom_id_1'
}, {
'source': 'atom_id_2'
}, {
'source': [
{
'outbound': ['PDB', 'ihm_cross_link_restraint_restraint_type_fkey']
}, 'RID'
]
}, ['PDB', 'ihm_cross_link_restraint_conditional_crosslink_flag_fkey'], {
'source': [
{
'outbound': ['PDB', 'ihm_cross_link_restraint_model_granularity_fkey']
}, 'RID'
]
}, {
'source': 'distance_threshold'
}, {
'source': 'psi'
}, {
'source': 'sigma_1'
}, {
'source': 'sigma_2'
}, {
'source': [
{
'outbound': ['PDB', 'ihm_cross_link_restraint_mm_poly_res_label_1_fkey']
}, 'RID'
],
'markdown_name': 'polymeric residue 1'
}, {
'source': [
{
'outbound': ['PDB', 'ihm_cross_link_restraint_mm_poly_res_label_2_fkey']
}, 'RID'
],
'markdown_name': 'polymeric residue 2'
}, ['PDB', 'ihm_cross_link_restraint_Entry_Related_File_fkey']
],
'entry': [
{
'source': [{
'outbound': ['PDB', 'ihm_cross_link_restraint_structure_id_fkey']
}, 'RID']
}, 'id', {
'source': [{
'outbound': ['PDB', 'ihm_cross_link_restraint_group_id_fkey']
}, 'RID'],
'markdown_name': 'group id'
}, {
'source': [
{
'outbound': ['PDB', 'ihm_cross_link_restraint_mm_poly_res_label_1_fkey']
}, 'entity_id'
],
'markdown_name': 'entity id 1'
}, {
'source': [
{
'outbound': ['PDB', 'ihm_cross_link_restraint_mm_poly_res_label_2_fkey']
}, 'entity_id'
],
'markdown_name': 'entity id 2'
}, {
'source': [{
'outbound': ['PDB', 'ihm_cross_link_restraint_asym_id_1_fkey']
}, 'RID'],
'markdown_name': 'asym id 1'
}, {
'source': [{
'outbound': ['PDB', 'ihm_cross_link_restraint_asym_id_2_fkey']
}, 'RID'],
'markdown_name': 'asym id 2'
}, {
'source': [
{
'outbound': ['PDB', 'ihm_cross_link_restraint_mm_poly_res_label_1_fkey']
}, 'mon_id'
],
'markdown_name': 'comp id 1'
}, {
'source': [
{
'outbound': ['PDB', 'ihm_cross_link_restraint_mm_poly_res_label_2_fkey']
}, 'mon_id'
],
'markdown_name': 'comp id 2'
}, {
'source': [
{
'outbound': ['PDB', 'ihm_cross_link_restraint_mm_poly_res_label_1_fkey']
}, 'num'
],
'markdown_name': 'seq id 1'
}, {
'source': [
{
'outbound': ['PDB', 'ihm_cross_link_restraint_mm_poly_res_label_2_fkey']
}, 'num'
],
'markdown_name': 'seq id 2'
}, {
'source': 'atom_id_1'
}, {
'source': 'atom_id_2'
}, {
'source': [
{
'outbound': ['PDB', 'ihm_cross_link_restraint_restraint_type_fkey']
}, 'RID'
]
}, ['PDB', 'ihm_cross_link_restraint_conditional_crosslink_flag_fkey'], {
'source': [
{
'outbound': ['PDB', 'ihm_cross_link_restraint_model_granularity_fkey']
}, 'RID'
]
}, {
'source': 'distance_threshold'
}, {
'source': 'psi'
}, {
'source': 'sigma_1'
}, {
'source': 'sigma_2'
}, {
'source': [
{
'outbound': ['PDB', 'ihm_cross_link_restraint_mm_poly_res_label_1_fkey']
}, 'RID'
],
'markdown_name': 'polymeric residue 1'
}, {
'source': [
{
'outbound': ['PDB', 'ihm_cross_link_restraint_mm_poly_res_label_2_fkey']
}, 'RID'
],
'markdown_name': 'polymeric residue 2'
}
],
'detailed': [
{
'source': 'RID'
}, {
'source': [{
'outbound': ['PDB', 'ihm_cross_link_restraint_structure_id_fkey']
}, 'RID']
}, 'id', {
'source': [{
'outbound': ['PDB', 'ihm_cross_link_restraint_group_id_fkey']
}, 'RID'],
'markdown_name': 'group id'
}, {
'source': [
{
'outbound': ['PDB', 'ihm_cross_link_restraint_mm_poly_res_label_1_fkey']
}, 'entity_id'
],
'markdown_name': 'entity id 1'
}, {
'source': [
{
'outbound': ['PDB', 'ihm_cross_link_restraint_mm_poly_res_label_2_fkey']
}, 'entity_id'
],
'markdown_name': 'entity id 2'
}, {
'source': [{
'outbound': ['PDB', 'ihm_cross_link_restraint_asym_id_1_fkey']
}, 'RID'],
'markdown_name': 'asym id 1'
}, {
'source': [{
'outbound': ['PDB', 'ihm_cross_link_restraint_asym_id_2_fkey']
}, 'RID'],
'markdown_name': 'asym id 2'
}, {
'source': [
{
'outbound': ['PDB', 'ihm_cross_link_restraint_mm_poly_res_label_1_fkey']
}, 'mon_id'
],
'markdown_name': 'comp id 1'
}, {
'source': [
{
'outbound': ['PDB', 'ihm_cross_link_restraint_mm_poly_res_label_2_fkey']
}, 'mon_id'
],
'markdown_name': 'comp id 2'
}, {
'source': [
{
'outbound': ['PDB', 'ihm_cross_link_restraint_mm_poly_res_label_1_fkey']
}, 'num'
],
'markdown_name': 'seq id 1'
}, {
'source': [
{
'outbound': ['PDB', 'ihm_cross_link_restraint_mm_poly_res_label_2_fkey']
}, 'num'
],
'markdown_name': 'seq id 2'
}, {
'source': 'atom_id_1'
}, {
'source': 'atom_id_2'
}, {
'source': [
{
'outbound': ['PDB', 'ihm_cross_link_restraint_restraint_type_fkey']
}, 'RID'
]
}, ['PDB', 'ihm_cross_link_restraint_conditional_crosslink_flag_fkey'], {
'source': [
{
'outbound': ['PDB', 'ihm_cross_link_restraint_model_granularity_fkey']
}, 'RID'
]
}, {
'source': 'distance_threshold'
}, {
'source': 'psi'
}, {
'source': 'sigma_1'
}, {
'source': 'sigma_2'
}, {
'source': [
{
'outbound': ['PDB', 'ihm_cross_link_restraint_mm_poly_res_label_1_fkey']
}, 'RID'
],
'markdown_name': 'polymeric residue 1'
}, {
'source': [
{
'outbound': ['PDB', 'ihm_cross_link_restraint_mm_poly_res_label_2_fkey']
}, 'RID'
],
'markdown_name': 'polymeric residue 2'
}, ['PDB', 'ihm_cross_link_restraint_Entry_Related_File_fkey'], {
'source': 'RCT'
}, {
'source': 'RMT'
}, {
'source': [{
'outbound': ['PDB', 'ihm_cross_link_restraint_RCB_fkey']
}, 'RID']
}, {
'source': [{
'outbound': ['PDB', 'ihm_cross_link_restraint_RMB_fkey']
}, 'RID']
}, {
'source': [{
'outbound': ['PDB', 'ihm_cross_link_restraint_Owner_fkey']
}, 'RID']
}
]
}
visible_foreign_keys = {
'filter': 'detailed',
'detailed': [
['PDB', 'ihm_cross_link_result_restraint_id_fkey'],
['PDB', 'ihm_cross_link_result_parameters_restraint_id_fkey']
]
}
table_display = {'row_name': {'row_markdown_pattern': '{{{id}}}'}}
table_annotations = {
chaise_tags.display: display,
chaise_tags.table_display: table_display,
chaise_tags.visible_columns: visible_columns,
chaise_tags.visible_foreign_keys: visible_foreign_keys,
}
table_comment = 'Chemical crosslinking restraints used in the modeling'
table_acls = {
'owner': [groups['pdb-admin'], groups['isrd-staff']],
'write': [],
'delete': [groups['pdb-curator']],
'insert': [groups['pdb-curator'], groups['pdb-writer'], groups['pdb-submitter']],
'select': [groups['pdb-writer'], groups['pdb-reader']],
'update': [groups['pdb-curator']],
'enumerate': ['*']
}
table_acl_bindings = {
'released_reader': {
'types': ['select'],
'scope_acl': [groups['pdb-submitter']],
'projection': [{
'outbound': ['PDB', 'ihm_cross_link_restraint_structure_id_fkey']
}, 'RCB'],
'projection_type': 'acl'
},
'self_service_group': {
'types': ['update', 'delete'],
'scope_acl': ['*'],
'projection': ['Owner'],
'projection_type': 'acl'
},
'self_service_creator': {
'types': ['update', 'delete'],
'scope_acl': [groups['pdb-submitter']],
'projection': [
{
'outbound': ['PDB', 'ihm_cross_link_restraint_structure_id_fkey']
}, {
'or': [
{
'filter': 'Workflow_Status',
'operand': 'DRAFT',
'operator': '='
}, {
'filter': 'Workflow_Status',
'operand': 'DEPO',
'operator': '='
}, {
'filter': 'Workflow_Status',
'operand': 'RECORD READY',
'operator': '='
}, {
'filter': 'Workflow_Status',
'operand': 'ERROR',
'operator': '='
}
]
}, 'RCB'
],
'projection_type': 'acl'
}
}
key_defs = [
em.Key.define(
['structure_id', 'id'],
constraint_names=[['PDB', 'ihm_cross_link_restraint_primary_key']],
),
em.Key.define(['RID'], constraint_names=[['PDB', 'ihm_cross_link_restraint_RIDkey1']],
),
]
fkey_defs = [
em.ForeignKey.define(
['RMB'],
'public',
'ERMrest_Client', ['ID'],
constraint_names=[['PDB', 'ihm_cross_link_restraint_RMB_fkey']],
),
em.ForeignKey.define(
['Entry_Related_File'],
'PDB',
'Entry_Related_File', ['RID'],
constraint_names=[['PDB', 'ihm_cross_link_restraint_Entry_Related_File_fkey']],
on_delete='CASCADE',
),
em.ForeignKey.define(
['RCB'],
'public',
'ERMrest_Client', ['ID'],
constraint_names=[['PDB', 'ihm_cross_link_restraint_RCB_fkey']],
),
em.ForeignKey.define(
['structure_id'],
'PDB',
'entry', ['id'],
constraint_names=[['PDB', 'ihm_cross_link_restraint_structure_id_fkey']],
acls={
'insert': ['*'],
'update': ['*']
},
on_update='CASCADE',
on_delete='CASCADE',
),
em.ForeignKey.define(
['restraint_type'],
'Vocab',
'ihm_cross_link_restraint_restraint_type', ['Name'],
constraint_names=[['PDB', 'ihm_cross_link_restraint_restraint_type_fkey']],
acls={
'insert': ['*'],
'update': ['*']
},
),
em.ForeignKey.define(
['model_granularity'],
'Vocab',
'ihm_cross_link_restraint_model_granularity', ['Name'],
constraint_names=[['PDB', 'ihm_cross_link_restraint_model_granularity_fkey']],
acls={
'insert': ['*'],
'update': ['*']
},
),
em.ForeignKey.define(
['conditional_crosslink_flag'],
'Vocab',
'ihm_cross_link_restraint_conditional_crosslink_flag', ['Name'],
constraint_names=[['PDB', 'ihm_cross_link_restraint_conditional_crosslink_flag_fkey']],
acls={
'insert': ['*'],
'update': ['*']
},
),
em.ForeignKey.define(
['asym_id_1', 'structure_id'],
'PDB',
'struct_asym', ['id', 'structure_id'],
constraint_names=[['PDB', 'ihm_cross_link_restraint_asym_id_1_fkey']],
annotations={
chaise_tags.foreign_key: {
'template_engine': 'handlebars',
'domain_filter_pattern': '{{#if _structure_id}}structure_id={{{_structure_id}}}{{/if}}'
}
},
acls={
'insert': ['*'],
'update': ['*']
},
on_update='CASCADE',
on_delete='SET NULL',
),
em.ForeignKey.define(
['structure_id', 'group_id'],
'PDB',
'ihm_cross_link_list', ['structure_id', 'id'],
constraint_names=[['PDB', 'ihm_cross_link_restraint_group_id_fkey']],
annotations={
chaise_tags.foreign_key: {
'template_engine': 'handlebars',
'domain_filter_pattern': '{{#if _structure_id}}structure_id={{{_structure_id}}}{{/if}}'
}
},
acls={
'insert': ['*'],
'update': ['*']
},
on_update='CASCADE',
on_delete='SET NULL',
),
em.ForeignKey.define(
['Owner'],
'public',
'Catalog_Group', ['ID'],
constraint_names=[['PDB', 'ihm_cross_link_restraint_Owner_fkey']],
acls={
'insert': [groups['pdb-curator']],
'update': [groups['pdb-curator']]
},
acl_bindings={
'set_owner': {
'types': ['update', 'insert'],
'scope_acl': ['*'],
'projection': ['ID'],
'projection_type': 'acl'
}
},
),
em.ForeignKey.define(
['structure_id', 'seq_id_2', 'entity_id_2', 'comp_id_2'],
'PDB',
'entity_poly_seq', ['structure_id', 'num', 'entity_id', 'mon_id'],
constraint_names=[['PDB', 'ihm_cross_link_restraint_mm_poly_res_label_2_fkey']],
annotations={
chaise_tags.foreign_key: {
'from_name': 'Ihm Cross Link Restraint Label 2',
'template_engine': 'handlebars',
'domain_filter_pattern': '{{#if _structure_id}}structure_id={{{_structure_id}}}{{/if}}'
}
},
acls={
'insert': ['*'],
'update': ['*']
},
on_update='CASCADE',
on_delete='SET NULL',
),
em.ForeignKey.define(
['structure_id', 'seq_id_1', 'comp_id_1', 'entity_id_1'],
'PDB',
'entity_poly_seq', ['structure_id', 'num', 'mon_id', 'entity_id'],
constraint_names=[['PDB', 'ihm_cross_link_restraint_mm_poly_res_label_1_fkey']],
annotations={
chaise_tags.foreign_key: {
'from_name': 'Ihm Cross Link Restraint Label 1',
'template_engine': 'handlebars',
'domain_filter_pattern': '{{#if _structure_id}}structure_id={{{_structure_id}}}{{/if}}'
}
},
acls={
'insert': ['*'],
'update': ['*']
},
on_update='CASCADE',
on_delete='SET NULL',
),
em.ForeignKey.define(
['asym_id_2', 'structure_id'],
'PDB',
'struct_asym', ['id', 'structure_id'],
constraint_names=[['PDB', 'ihm_cross_link_restraint_asym_id_2_fkey']],
annotations={
chaise_tags.foreign_key: {
'template_engine': 'handlebars',
'domain_filter_pattern': '{{#if _structure_id}}structure_id={{{_structure_id}}}{{/if}}'
}
},
acls={
'insert': ['*'],
'update': ['*']
},
on_update='CASCADE',
on_delete='SET NULL',
),
]
table_def = em.Table.define(
table_name,
column_defs=column_defs,
key_defs=key_defs,
fkey_defs=fkey_defs,
annotations=table_annotations,
acls=table_acls,
acl_bindings=table_acl_bindings,
comment=table_comment,
provide_system=True
)
def main(catalog, mode, replace=False, really=False):
updater = CatalogUpdater(catalog)
table_def['column_annotations'] = column_annotations
table_def['column_comment'] = column_comment
updater.update_table(mode, schema_name, table_def, replace=replace, really=really)
if __name__ == "__main__":
host = 'pdb.isrd.isi.edu'
catalog_id = 99
mode, replace, host, catalog_id = parse_args(host, catalog_id, is_table=True)
catalog = ErmrestCatalog('https', host, catalog_id=catalog_id, credentials=get_credential(host))
main(catalog, mode, replace)
| [
"[email protected]"
] | |
901f1bc9d292c42147ff6373749f92023a60771d | f77028577e88d228e9ce8252cc8e294505f7a61b | /web_backend/nvlserver/module/user/specification/create_user_specification.py | 01c30c0f0202bb9a1c221340e3632c081cd325eb | [] | no_license | Sud-26/Arkally | e82cebb7f907a3869443b714de43a1948d42519e | edf519067d0ac4c204c12450b6f19a446afc327e | refs/heads/master | 2023-07-07T02:14:28.012545 | 2021-08-06T10:29:42 | 2021-08-06T10:29:42 | 392,945,826 | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 691 | py | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
__version__ = '1.0.1'
create_user_element_query = """
INSERT INTO public."user" AS usr
(email, password, fullname, locked, language_id, meta_information,
account_type_id, active, deleted)
VALUES
($1, $2, $3, $4, $5, $6, $7, $8, FALSE) RETURNING *;
"""
create_user_element_query_front = """
INSERT INTO public."user" AS usr
(email, password, fullname, locked, language_id, meta_information,
account_type_id, active, gendar, companyName, address, city, postalcode, country, mobilenumber, webpage, updatebymails, vatid, deleted)
VALUES
($1, $2, $3, $4, $5, $6, $7, $8, $9, $10, $11, $12, $13, $14, $15, $16, $17, $18, FALSE) RETURNING *;
""" | [
"[email protected]"
] | |
9da0eadc5fc439cbbbfa4f8b4d71be538501e928 | ca7aa979e7059467e158830b76673f5b77a0f5a3 | /Python_codes/p03423/s386141222.py | 32ef67cadf9e12133fae837a4a87668df41844e1 | [] | 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 | 133 | py | def main():
import sys
input = sys.stdin.readline
N = int(input())
print(N//3)
if __name__ == '__main__':
main() | [
"[email protected]"
] | |
6a02c8fb4d49934aaaa161755b66b6468067b274 | ed0dd577f03a804cdc274f6c7558fafaac574dff | /python/pyre/services/__init__.py | 163504bbf5b01997c49c4e80a164a9d41b3fcac5 | [
"Apache-2.0"
] | permissive | leandromoreira/vmaf | fd26e2859136126ecc8e9feeebe38a51d14db3de | a4cf599444701ea168f966162194f608b4e68697 | refs/heads/master | 2021-01-19T03:43:15.677322 | 2016-10-08T18:02:22 | 2016-10-08T18:02:22 | 70,248,500 | 3 | 0 | null | 2016-10-07T13:21:28 | 2016-10-07T13:21:27 | null | UTF-8 | Python | false | false | 772 | py | #!/usr/bin/env python
#
# ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
#
# Michael A.G. Aivazis
# California Institute of Technology
# (C) 1998-2005 All Rights Reserved
#
# {LicenseText}
#
# ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
#
def evaluator(name=None):
from Evaluator import Evaluator
return Evaluator(name)
def pickler(name=None):
from Pickler import Pickler
return Pickler(name)
def request(command, args=None):
from ServiceRequest import ServiceRequest
return ServiceRequest(command, args)
# version
__id__ = "$Id: __init__.py,v 1.1.1.1 2006-11-27 00:10:06 aivazis Exp $"
# End of file
| [
"[email protected]"
] | |
14b930fa7df1323bac9ca44cd766b5d632fd3e40 | 2fd087fbc5faf43940153693823969df6c8ec665 | /pyc_decrypted/latest/ui/wxpython/static_link_text.py | 6dcea3d68f9b013de0e41f572d2e61f9da42bccc | [] | no_license | mickeystone/DropBoxLibrarySRC | ed132bbffda7f47df172056845e5f8f6c07fb5de | 2e4a151caa88b48653f31a22cb207fff851b75f8 | refs/heads/master | 2021-05-27T05:02:30.255399 | 2013-08-27T13:16:55 | 2013-08-27T13:16:55 | null | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 10,769 | py | #Embedded file name: ui/wxpython/static_link_text.py
from __future__ import absolute_import
import wx
from dropbox.gui import event_handler
from dropbox.trace import TRACE, unhandled_exc_handler
from dropbox.url_info import dropbox_url_info
from .constants import platform, Colors, GNOME
from .dropbox_controls import TransparentPanel, UnfocusableMixin
from .util import dirty_rects, ExtendedLinkedText, SPACE_TOKENS, tokenize
def CopyFont(font):
return wx.Font(pointSize=font.GetPointSize(), family=font.GetFamily(), style=font.GetStyle(), weight=font.GetWeight(), underline=font.GetUnderlined(), encoding=font.GetEncoding(), **({'face': font.GetFaceName()} if font.GetFaceName() else {}))
class StaticLinkText(TransparentPanel, UnfocusableMixin):
old_cursor = None
def __init__(self, parent, label, on_click = None, *n, **kw):
if 'line_height' in kw:
self.line_height = kw['line_height']
del kw['line_height']
else:
self.line_height = None
super(StaticLinkText, self).__init__(parent, *n, **kw)
self.label = label
self.on_click = on_click
self.mouseDown = False
self.lastMouseRect = None
self.background_color, self.foreground_color = (None, None)
self.last_munch = None
self.wrap = None
self.fixed_width = False
self.hovering_rect = None
self.center = False
self.tip = wx.ToolTip(tip='')
self.SetToolTip(self.tip)
self.tip.Enable(False)
self.text_font = None
self._buffer = None
try:
self.SetFont(platform.get_themed_font(parent))
except Exception:
TRACE("Couldn't set themed font!")
unhandled_exc_handler()
if self.old_cursor is None:
self.old_cursor = self.GetCursor()
self.click_rects = {}
self.OnSize(None)
self.Bind(wx.EVT_PAINT, self.OnPaint)
self.Bind(wx.EVT_MOVE, self.OnSize)
self.Bind(wx.EVT_SIZE, self.OnSize)
self.Bind(wx.EVT_LEFT_DOWN, self.OnMouseDown)
self.Bind(wx.EVT_LEFT_UP, self.OnMouseUp)
self.Bind(wx.EVT_MOTION, self.OnMotion)
self.Bind(wx.EVT_ENTER_WINDOW, self.OnMotion)
self.Bind(wx.EVT_LEAVE_WINDOW, self.OnMotion)
if platform is GNOME:
self.Bind(wx.EVT_ERASE_BACKGROUND, None)
def get_width(self, dc, token_list):
return dc.GetTextExtent(''.join(token_list))[0]
def munch(self, dc):
if self.last_munch:
if self.last_munch[0] == (self.label, self.wrap, self.text_font):
return self.last_munch[1]
tokens = tokenize(self.label)
lines = []
current_line = []
current_spacers = []
for token in tokens:
if token == '\n':
lines.append(current_line)
current_line = []
current_spacers = []
continue
elif token in SPACE_TOKENS:
if not current_line:
continue
else:
current_spacers += token
continue
potential_line = current_line + current_spacers + [token]
if self.wrap:
if current_line:
if self.get_width(dc, potential_line) > self.wrap:
lines.append(current_line)
current_spacers = []
current_line = [token]
continue
current_line = potential_line
current_spacers = []
lines.append(current_line)
munches = []
h = 0
for line in lines:
text = ''.join(line)
link_runs = []
offset = 0
for token in line:
if isinstance(token, ExtendedLinkedText):
link_runs.append((offset + token.start, offset + token.end, token.url))
offset += len(token)
munches.append((text, link_runs))
line_height = dc.GetTextExtent(text)[1] if text else dc.GetTextExtent('A')[1]
if self.line_height is not None and h != 0:
line_height = max(self.line_height, line_height)
h += line_height
retval = (munches, h)
self.last_munch = ((self.label, self.wrap, self.text_font), retval)
return retval
@event_handler
def Draw(self, dc):
if not dc:
return
dc.SetFont(self.text_font)
if self.GetBackground(self):
bmp, (x, y) = self.GetBackground(self)
dc.SetBackground(wx.WHITE_BRUSH)
dc.Clear()
dc.DrawBitmap(bmp, x, y)
else:
bg_col = self.background_color if self.background_color else Colors.white
dc.SetPen(wx.Pen(bg_col))
dc.SetBrush(wx.Brush(bg_col, wx.SOLID))
dc.DrawRectangle(0, 0, self.width, self.height)
lines, height = self.munch(dc)
y = 0
self.click_rects = {}
for line, link_runs in lines:
if link_runs:
pieces = [(line[:link_runs[0][0]], '')] if link_runs[0][0] else []
for i in range(len(link_runs)):
pieces.append((line[link_runs[i][0]:link_runs[i][1]], link_runs[i][2]))
pieces.append((line[link_runs[i][1]:link_runs[i + 1][0]] if i < len(link_runs) - 1 else line[link_runs[i][1]:], ''))
else:
pieces = [(line, '')]
x = 0
h = 0
if self.center:
total_width = sum((dc.GetTextExtent(piece[0])[0] for piece in pieces))
if total_width < dc.GetSize().GetWidth():
x = (dc.GetSize().GetWidth() - total_width) // 2
for piece in pieces:
if piece != ('', ''):
w, this_h = dc.GetTextExtent(piece[0])
r = wx.Rect(x, y, w, this_h)
if self.hovering_rect is not None and self.hovering_rect == r:
dc.SetFont(self.link_font)
else:
dc.SetFont(self.text_font)
if piece[1]:
self.click_rects[r] = piece[1]
dc.SetTextForeground(Colors.link)
else:
dc.SetTextForeground(self.foreground_color if self.foreground_color else Colors.black)
dc.DrawLabel(piece[0], r)
x += w
h = max(h, this_h)
else:
h = max(h, dc.GetTextExtent('A')[1])
if self.line_height is not None:
h = max(h, self.line_height)
y += h
@event_handler
def OnMotion(self, event):
for r in self.click_rects:
if r.Contains(event.GetPosition()):
self.tip.SetTip(self.click_rects[r])
self.tip.Enable(True)
self.SetCursor(wx.StockCursor(wx.CURSOR_HAND))
if self.hovering_rect != r:
old_rect = self.hovering_rect
self.hovering_rect = r
self.OnSize(None)
self.RefreshRect(old_rect)
self.RefreshRect(r)
return
self.tip.Enable(False)
self.SetCursor(self.old_cursor)
if self.hovering_rect is not None:
old_rect = self.hovering_rect
self.hovering_rect = None
self.OnSize(None)
self.RefreshRect(old_rect)
@event_handler
def OnPaint(self, event):
dc = wx.PaintDC(self)
for x, y, w, h in dirty_rects(self):
dc.Blit(x, y, w, h, self._mem_dc, x, y)
@event_handler
def init_buffer(self):
if self._buffer and self._buffer.GetWidth() == self.width:
if self._buffer.GetHeight() == self.height:
return True
dc = wx.ClientDC(self)
dc.SetFont(self.text_font)
lines, self.height = self.munch(dc)
raw_text = '\n'.join([ line[0] for line in lines ])
text_width = dc.GetMultiLineTextExtent(raw_text)[0]
if self.wrap:
if self.fixed_width:
self.width = self.wrap
else:
self.width = min(text_width, self.wrap)
else:
self.width = text_width
self.SetMinSize(wx.Size(self.width, self.height))
self._buffer = wx.EmptyBitmap(self.width, self.height)
return True
@event_handler
def OnSize(self, event):
if self.init_buffer():
self._mem_dc = wx.MemoryDC()
self._mem_dc.SelectObject(self._buffer)
self.Draw(self._mem_dc)
@event_handler
def OnMouseDown(self, event):
self.mouseDown = True
self.lastMouseRect = None
for r in self.click_rects:
if r.Contains(event.GetPosition()):
self.lastMouseRect = r
@event_handler
def OnMouseUp(self, event):
processed = False
for r in self.click_rects:
if r.Contains(event.GetPosition()):
processed = True
if self.lastMouseRect == r:
self.link_handler(self.click_rects[r])
if not processed and self.on_click is not None and self.mouseDown and self.lastMouseRect == None:
self.on_click(self.click_rects[r])
self.mouseDown = False
self.lastMouseRect = None
@event_handler
def link_handler(self, link):
dropbox_url_info.launch_full_url(link)
@event_handler
def SetLabel(self, label):
self.label = label
self.OnSize(None)
self.Refresh()
@event_handler
def Wrap(self, width, fixed_width = False, center = False):
self.wrap = width
self.fixed_width = fixed_width
self.center = center
self._buffer = None
self.OnSize(None)
def GetFont(self):
return CopyFont(self.text_font)
@event_handler
def SetFont(self, font):
if font != self.text_font:
self.text_font = CopyFont(font)
self.link_font = CopyFont(font)
self.link_font.SetUnderlined(True)
self.last_munch = None
self.OnSize(None)
Font = property(GetFont, SetFont)
@event_handler
def SetForegroundColour(self, color):
if color != self.foreground_color:
self.foreground_color = color
self.OnSize(None)
@event_handler
def SetBackgroundColour(self, color):
if color != self.background_color:
self.background_color = color
self.OnSize(None)
| [
"[email protected]"
] | |
39a8dc422113338f86c9a52b0309b38e0cc34c95 | 3b88c7805cf6b8fb9a1e00470c7c6faebd7efa80 | /src/outpost/django/geo/migrations/0022_auto_20221219_1728.py | 92841f8165ec5c82eb8781f15ea220c83c9d0db0 | [
"BSD-3-Clause",
"BSD-2-Clause"
] | permissive | medunigraz/outpost.django.geo | e84abc7a550b2d0e82f6bb58611039762543be67 | 04424d97c992b3d6f3ca16e9109df9c530a4ba2a | refs/heads/master | 2023-07-24T03:37:50.531723 | 2022-12-19T19:29:14 | 2022-12-19T19:29:14 | 183,224,271 | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 1,373 | py | # Generated by Django 2.2.28 on 2022-12-19 16:28
import django.contrib.gis.db.models.fields
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('geo', '0021_auto_20200805_1403'),
]
operations = [
migrations.AlterModelOptions(
name='node',
options={'get_latest_by': 'modified'},
),
migrations.AlterModelOptions(
name='pointofinterestinstance',
options={'get_latest_by': 'modified'},
),
migrations.AlterField(
model_name='level',
name='order',
field=models.PositiveIntegerField(db_index=True, editable=False, verbose_name='order'),
),
migrations.AlterField(
model_name='pointofinterest',
name='order',
field=models.PositiveIntegerField(db_index=True, editable=False, verbose_name='order'),
),
migrations.RunSQL(
"ALTER TABLE geo_room ALTER COLUMN layout type geometry(MultiPolygon, 3857) using ST_Multi(layout);",
state_operations=[
migrations.AlterField(
model_name='room',
name='layout',
field=django.contrib.gis.db.models.fields.MultiPolygonField(srid=3857),
),
],
)
]
| [
"[email protected]"
] | |
6ff07d0ed47b6d34994d78317a0abf2e183bcc46 | 99fca8eaa3fb5e93ed4ed857b439293bc0952c79 | /Data Visualization Pandas/plot_1.py | e37cba6e99ff3c2c68fea4f574dddd99d7c01ca1 | [] | no_license | Ebyy/python_projects | 7adb377f4e8eec94613e4e348f02c2ded306efac | 0cacfab443d3eeeb274836b7be4b7205585f7758 | refs/heads/master | 2020-05-19T22:28:17.672051 | 2019-05-19T19:32:19 | 2019-05-19T19:32:19 | 185,240,041 | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 852 | py | import pandas as pd
import matplotlib.pyplot as plt
from matplotlib import style
import numpy as np
style.use('ggplot')
web_stats = {'Day': [1,2,3,4,5,6],
'Visitors': [43,53,34,45,64,34],
'Bounce_Rate': [65,72,62,64,54,66]}
df = pd.DataFrame(web_stats)
#print(df)
#print(df.head())
#print(df.tail())
print(df.tail(2)) # prints 2 rolls from the bottom
print(df.set_index('Day'))
#df.set_index('Day', inplace=True) or equate the function to
# a variable(df2) then print to set the index permanently
print(df.head())
# t reference a specific column
print(df['Bounce_Rate'])
#or
print(df.Visitors)
print(df[['Bounce_Rate', 'Visitors']]) # to refernce two columns
print(df.Visitors.tolist())
print(np.array(df[['Bounce_Rate', 'Visitors']]))
df2 = pd.DataFrame(np.array(df[['Bounce_Rate', 'Visitors']]))
print(df2) | [
"[email protected]"
] | |
d6f6f38657b6972b2a4266a44848d7eeb98c00b3 | ba977400c6f7e23dd2934476d70db38f8d83c2e5 | /visualization/92_plot_training.py | e155069e7bd9d7bd6c01606041bffd35fa3e54a9 | [] | no_license | jasonwei20/adaptable-image-classification | 9b53396e7db84e4e025f7686bc6936b7b64fa5e1 | 4762d1a8a6a8151bfec0306d07525dc43048aba6 | refs/heads/master | 2021-02-11T08:36:21.327647 | 2020-04-05T16:53:20 | 2020-04-05T16:53:20 | 244,473,217 | 1 | 0 | null | null | null | null | UTF-8 | Python | false | false | 2,509 | py | import matplotlib
matplotlib.use('agg')
import matplotlib.pyplot as plt
import numpy as np
from pathlib import Path
from typing import (Dict, List)
checkpoint_folder_dict = { Path("/home/brenta/scratch/jason/checkpoints/voc/vanilla/exp_92a"): "Random (Baseline)",
Path("/home/brenta/scratch/jason/checkpoints/voc/vanilla/exp_92b"): "Highest 20 Percent by Gradient",
Path("/home/brenta/scratch/jason/checkpoints/voc/vanilla/exp_92c"): "Highest 10 Percent + Random Sample 10 Percent",
Path("/home/brenta/scratch/jason/checkpoints/voc/vanilla/exp_92d"): "Lowest 20 Percent by Graident", }
def get_image_names(folder: Path) -> List[Path]:
"""
Find the names and paths of all of the images in a folder.
Args:
folder: Folder containing images (assume folder only contains images).
Returns:
A list of the names with paths of the images in a folder.
"""
return sorted([
Path(f.name) for f in folder.iterdir() if ((
folder.joinpath(f.name).is_file()) and (".DS_Store" not in f.name))
],
key=str)
def checkpoint_folder_to_val_accs(checkpoint_folder):
tup_list = []
checkpoint_names = get_image_names(checkpoint_folder)
for checkpoint_name in checkpoint_names:
checkpoint_str = str(checkpoint_name)[:-3]
parts = checkpoint_str.split('_')
epoch_num = int(parts[1][1:])
mb_num = int(parts[2][2:])
val_acc = float(parts[3][2:])
tup = (mb_num, val_acc)
tup_list.append(tup)
tup_list = sorted(tup_list, key=lambda x:x[0])
mb_num_list = [x[0] for x in tup_list]
val_acc_list = [x[1] for x in tup_list]
return mb_num_list, val_acc_list
def plot_val_accs(output_path, checkpoint_folder_dict):
fig, ax = plt.subplots()
plt.ylim([-0.02, 1.02])
for checkpoint_folder in checkpoint_folder_dict:
mb_num_list, val_acc_list = checkpoint_folder_to_val_accs(checkpoint_folder)
plt.plot( mb_num_list, val_acc_list, label=checkpoint_folder_dict[checkpoint_folder] )
print(mb_num_list)
print(val_acc_list)
plt.legend(loc="lower right")
plt.title("CL performance on predicting image rotations (ResNet18, VOC RotNet)")
plt.xlabel("Minibatch Updates")
plt.ylabel("Validation Accuracy")
plt.savefig(output_path, dpi=400)
if __name__ == "__main__":
plot_val_accs("outputs/test_voc.png", checkpoint_folder_dict) | [
"[email protected]"
] | |
1586757ea05dd640f49a318120147186039c7d5d | 60aa3bcf5ace0282210685e74ee8ed31debe1769 | /simulation/objects/script_object.py | 915e604853fac23e267e443f28f990fdb162a519 | [] | no_license | TheBreadGuy/sims4-ai-engine | 42afc79b8c02527353cc084117a4b8da900ebdb4 | 865212e841c716dc4364e0dba286f02af8d716e8 | refs/heads/master | 2023-03-16T00:57:45.672706 | 2016-05-01T17:26:01 | 2016-05-01T17:26:01 | null | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 39,261 | py | import itertools
from carry.carry_postures import CarryingObject
from crafting.crafting_tunable import CraftingTuning
from distributor.rollback import ProtocolBufferRollback
from interactions.utils.animation import TunableAnimationObjectOverrides, AnimationOverrides, TunableAnimationOverrides
from interactions.utils.routing import RouteTargetType
from interactions.utils.sim_focus import FocusInterestLevel
from objects import slots
from objects.base_object import BaseObject, ResetReason
from objects.collection_manager import CollectableComponent
from objects.components import forward_to_components_gen, forward_to_components, get_component_priority_and_name_using_persist_id
from objects.components.affordance_tuning import AffordanceTuningComponent
from objects.components.autonomy import TunableAutonomyComponent
from objects.components.canvas_component import CanvasComponent
from objects.components.carryable_component import TunableCarryableComponent
from objects.components.censor_grid_component import TunableCensorGridComponent
from objects.components.consumable_component import ConsumableComponent
from objects.components.crafting_station_component import CraftingStationComponent
from objects.components.fishing_location_component import FishingLocationComponent
from objects.components.flowing_puddle_component import FlowingPuddleComponent
from objects.components.footprint_component import HasFootprintComponent
from objects.components.game_component import TunableGameComponent
from objects.components.gardening_components import TunableGardeningComponent
from objects.components.idle_component import IdleComponent
from objects.components.inventory import ObjectInventoryComponent
from objects.components.inventory_item import InventoryItemComponent, ItemLocation
from objects.components.lighting_component import LightingComponent
from objects.components.line_of_sight_component import TunableLineOfSightComponent
from objects.components.live_drag_target_component import LiveDragTargetComponent
from objects.components.name_component import NameComponent
from objects.components.object_age import TunableObjectAgeComponent
from objects.components.object_relationship_component import ObjectRelationshipComponent
from objects.components.object_teleportation_component import ObjectTeleportationComponent
from objects.components.ownable_component import OwnableComponent
from objects.components.proximity_component import ProximityComponent
from objects.components.slot_component import SlotComponent
from objects.components.spawner_component import SpawnerComponent
from objects.components.state import TunableStateComponent
from objects.components.statistic_component import HasStatisticComponent
from objects.components.time_of_day_component import TimeOfDayComponent
from objects.components.tooltip_component import TooltipComponent
from objects.components.video import TunableVideoComponent
from objects.components.welcome_component import WelcomeComponent
from objects.persistence_groups import PersistenceGroups
from objects.slots import SlotType
from protocolbuffers import SimObjectAttributes_pb2 as protocols
from protocolbuffers.FileSerialization_pb2 import ObjectData
from sims4.callback_utils import CallableList
from sims4.math import MAX_FLOAT
from sims4.tuning.geometric import TunableVector2
from sims4.tuning.instances import HashedTunedInstanceMetaclass
from sims4.tuning.tunable import TunableList, TunableReference, TunableTuple, OptionalTunable, Tunable, TunableEnumEntry, TunableMapping
from sims4.tuning.tunable_base import GroupNames, FilterTag
from sims4.utils import flexmethod, flexproperty, classproperty
from singletons import EMPTY_SET
from statistics.mood import TunableEnvironmentScoreModifiers
import caches
import distributor.fields
import objects.components.types
import objects.persistence_groups
import paths
import postures
import protocolbuffers.FileSerialization_pb2 as file_serialization
import routing
import services
import sims4.log
logger = sims4.log.Logger('Objects')
class ScriptObject(BaseObject, HasStatisticComponent, HasFootprintComponent, metaclass=HashedTunedInstanceMetaclass, manager=services.definition_manager()):
__qualname__ = 'ScriptObject'
INSTANCE_TUNABLES = {'_super_affordances': TunableList(description='\n Super affordances on this object.\n ', tunable=TunableReference(description='\n A super affordance on this object.\n ', manager=services.affordance_manager(), class_restrictions=('SuperInteraction',), pack_safe=True)), '_part_data': TunableList(description='\n Use this to define parts for an object. Parts allow multiple Sims to\n use an object in different or same ways, at the same time. The model\n and the animations for this object will have to support parts.\n Ensure this is the case with animation and modeling.\n \n There will be one entry in this list for every part the object has.\n \n e.g. The bed has six parts (two sleep parts, and four sit parts).\n add two entries for the sleep parts add four entries for the sit\n parts\n ', tunable=TunableTuple(description='\n Data that is specific to this part.\n ', part_definition=TunableReference(description='\n The part definition data.\n ', manager=services.object_part_manager()), subroot_index=OptionalTunable(description='\n If enabled, this part will have a subroot index associated\n with it. This will affect the way Sims animate, i.e. they\n will animate relative to the position of the part, not\n relative to the object.\n ', tunable=Tunable(description='\n The subroot index/suffix associated to this part.\n ', tunable_type=int, default=0, needs_tuning=False), enabled_by_default=True), overlapping_parts=TunableList(description="\n The indices of parts that are unusable when this part is in\n use. The index is the zero-based position of the part within\n the object's Part Data list.\n ", tunable=int), adjacent_parts=OptionalTunable(description='\n Define adjacent parts. If disabled, adjacent parts will be\n generated automatically based on indexing. If enabled,\n adjacent parts must be specified here.\n ', tunable=TunableList(description="\n The indices of parts that are adjacent to this part. The\n index is the zero-based position of the part within the\n object's Part Data list.\n \n An empty list indicates that no part is ajdacent to this\n part.\n ", tunable=int)), is_mirrored=OptionalTunable(description='\n Specify whether or not solo animations played on this part\n should be mirrored or not.\n ', tunable=Tunable(description='\n If checked, mirroring is enabled. If unchecked,\n mirroring is disabled.\n ', tunable_type=bool, default=False)), forward_direction_for_picking=TunableVector2(description="\n When you click on the object this part belongs to, this\n offset will be applied to this part when determining which\n part is closest to where you clicked. By default, the\n object's forward vector will be used. It should only be\n necessary to tune this value if multiple parts overlap at\n the same location (e.g. the single bed).\n ", default=sims4.math.Vector2(0, 1), x_axis_name='x', y_axis_name='z'), disable_sim_aop_forwarding=Tunable(description='\n If checked, Sims using this specific part will never forward\n AOPs.\n ', tunable_type=bool, default=False), disable_child_aop_forwarding=Tunable(description='\n If checked, objects parented to this specific part will\n never forward AOPs.\n ', tunable_type=bool, default=False), anim_overrides=TunableAnimationOverrides(description='Animation overrides for this part.'))), 'custom_posture_target_name': Tunable(description='\n An additional non-virtual actor to set for this object when used as\n a posture target.\n \n This tunable is used when the object has parts. In most cases, the\n state machines will only have one actor for the part that is\n involved in animation. In that case, this field should not be set.\n \n e.g. The Sit posture requires the sitTemplate actor to be set, but\n does not make a distinction between, for instance, Chairs and Sofas,\n because no animation ever involves the whole object.\n \n However, there may be cases when, although we are dealing with\n parts, the animation will need to also reference the entire object.\n In that case, the ASM will have an extra actor to account for the\n whole object, in addition to the part. Set this field to be that\n actor name.\n \n e.g. The Sleep posture on the bed animates the Sim on one part.\n However, the sheets and pillows need to animate on the entire bed.\n In that case, we need to set this field on Bed so that the state\n machine can have this actor set.\n ', tunable_type=str, default=None), 'posture_transition_target_tag': TunableEnumEntry(description='\n A tag to apply to this script object so that it is taken into\n account for posture transition preference scoring. For example, you\n could tune this object (and others) to be a DINING_SURFACE. Any SI\n that is set up to have posture preference scoring can override the\n score for any objects that are tagged with DINING_SURFACE.\n \n For a more detailed description of how posture preference scoring\n works, see the posture_target_preference tunable field description\n in SuperInteraction.\n ', tunable_type=postures.PostureTransitionTargetPreferenceTag, default=postures.PostureTransitionTargetPreferenceTag.INVALID), '_anim_overrides': OptionalTunable(description='\n If enabled, specify animation overrides for this object.\n ', tunable=TunableAnimationObjectOverrides()), '_focus_score': TunableEnumEntry(description='\n Determines how likely a Sim is to look at this object when focusing\n ambiently. A higher value means this object is more likely to draw\n Sim focus.\n ', tunable_type=FocusInterestLevel, default=FocusInterestLevel.LOW, needs_tuning=True), 'social_clustering': OptionalTunable(description='\n If enabled, specify how this objects affects clustering for\n preferred locations for socialization.\n ', tunable=TunableTuple(is_datapoint=Tunable(description='\n Whether or not this object is a data point for social\n clusters.\n ', tunable_type=bool, default=True))), '_should_search_forwarded_sim_aop': Tunable(description="\n If enabled, interactions on Sims using this object will appear in\n this object's pie menu as long as they are also tuned to allow\n forwarding.\n ", tunable_type=bool, default=False), '_should_search_forwarded_child_aop': Tunable(description="\n If enabled, interactions on children of this object will appear in\n this object's pie menu as long as they are also tuned to allow\n forwarding.\n ", tunable_type=bool, default=False), '_disable_child_footprint_and_shadow': Tunable(description="\n If checked, all objects parented to this object will have their\n footprints and dropshadows disabled.\n \n Example Use: object_sim has this checked so when a Sim picks up a\n plate of food, the plate's footprint and dropshadow turn off\n temporarily.\n ", tunable_type=bool, default=False), 'disable_los_reference_point': Tunable(description='\n If checked, goal points for this interaction will not be discarded\n if a ray-test from the object fails to connect without intersecting\n walls or other objects. The reason for allowing this, is for\n objects like the door where we want to allow the sim to interact\n with the object, but since the object doesnt have a footprint we\n want to allow him to use the central point as a reference point and\n not fail the LOS test.\n ', tunable_type=bool, default=False), '_components': TunableTuple(description='\n The components that instances of this object should have.\n ', tuning_group=GroupNames.COMPONENTS, affordance_tuning=OptionalTunable(AffordanceTuningComponent.TunableFactory()), autonomy=OptionalTunable(TunableAutonomyComponent()), canvas=OptionalTunable(CanvasComponent.TunableFactory()), carryable=OptionalTunable(TunableCarryableComponent()), censor_grid=OptionalTunable(TunableCensorGridComponent()), collectable=OptionalTunable(CollectableComponent.TunableFactory()), consumable=OptionalTunable(ConsumableComponent.TunableFactory()), crafting_station=OptionalTunable(CraftingStationComponent.TunableFactory()), fishing_location=OptionalTunable(FishingLocationComponent.TunableFactory()), flowing_puddle=OptionalTunable(FlowingPuddleComponent.TunableFactory()), game=OptionalTunable(TunableGameComponent()), gardening_component=TunableGardeningComponent(), idle_component=OptionalTunable(IdleComponent.TunableFactory()), inventory=OptionalTunable(ObjectInventoryComponent.TunableFactory()), inventory_item=OptionalTunable(InventoryItemComponent.TunableFactory()), lighting=OptionalTunable(LightingComponent.TunableFactory()), line_of_sight=OptionalTunable(TunableLineOfSightComponent()), live_drag_target=OptionalTunable(LiveDragTargetComponent.TunableFactory()), name=OptionalTunable(NameComponent.TunableFactory()), object_age=OptionalTunable(TunableObjectAgeComponent()), object_relationships=OptionalTunable(ObjectRelationshipComponent.TunableFactory()), object_teleportation=OptionalTunable(ObjectTeleportationComponent.TunableFactory()), ownable_component=OptionalTunable(OwnableComponent.TunableFactory()), proximity_component=OptionalTunable(ProximityComponent.TunableFactory()), spawner_component=OptionalTunable(SpawnerComponent.TunableFactory()), state=OptionalTunable(TunableStateComponent()), time_of_day_component=OptionalTunable(TimeOfDayComponent.TunableFactory()), tooltip_component=OptionalTunable(TooltipComponent.TunableFactory()), video=OptionalTunable(TunableVideoComponent()), welcome_component=OptionalTunable(WelcomeComponent.TunableFactory())), '_components_native': TunableTuple(description='\n Tuning for native components, those that an object will have even\n if not tuned.\n ', tuning_group=GroupNames.COMPONENTS, Slot=OptionalTunable(SlotComponent.TunableFactory())), '_persists': Tunable(description='\n Whether object should persist or not.\n ', tunable_type=bool, default=True, tuning_filter=FilterTag.EXPERT_MODE), '_world_file_object_persists': Tunable(description="\n If object is from world file, check this if object state should\n persist. \n Example:\n If grill is dirty, but this is unchecked and it won't stay\n dirty when reloading the street. \n If Magic tree has this checked, all object relationship data\n will be saved.\n ", tunable_type=bool, default=False, tuning_filter=FilterTag.EXPERT_MODE), '_object_state_remaps': TunableList(description='\n If this object is part of a Medator object suite, this list\n specifies which object tuning file to use for each catalog object\n state.\n ', tunable=TunableReference(description='\n Current object state.\n ', manager=services.definition_manager(), tuning_filter=FilterTag.EXPERT_MODE)), 'environment_score_trait_modifiers': TunableMapping(description='\n Each trait can put modifiers on any number of moods as well as the\n negative environment scoring.\n \n If tuning becomes a burden, consider making prototypes for many\n objects and tuning the prototype.\n \n Example: A Sim with the Geeky trait could have a modifier for the\n excited mood on objects like computers and tablets.\n \n Example: A Sim with the Loves Children trait would have a modifier\n for the happy mood on toy objects.\n \n Example: A Sim that has the Hates Art trait could get an Angry\n modifier, and should set modifiers like Happy to multiply by 0.\n ', key_type=TunableReference(description='\n The Trait that the Sim must have to enable this modifier.\n ', manager=services.get_instance_manager(sims4.resources.Types.TRAIT)), value_type=TunableEnvironmentScoreModifiers.TunableFactory(description='\n The Environmental Score modifiers for a particular trait.\n '), key_name='trait', value_name='modifiers'), 'slot_cost_modifiers': TunableMapping(description="\n A mapping of slot types to modifier values. When determining slot\n scores in the transition sequence, if the owning object of a slot\n has a modifier for its type specified here, that slot will have the\n modifier value added to its cost. A positive modifier adds to the\n cost of a path using this slot and means that a slot will be less\n likely to be chosen. A negative modifier subtracts from the cost\n of a path using this slot and means that a slot will be more likely\n to be chosen.\n \n ex: Both bookcases and toilets have deco slots on them, but you'd\n rather a Sim prefer to put down an object in a bookcase than on the\n back of a toilet.\n ", key_type=SlotType.TunableReference(description='\n A reference to the type of slot to be given a score modifier\n when considered for this object.\n '), value_type=Tunable(description='\n A tunable float specifying the score modifier for the\n corresponding slot type on this object.\n ', tunable_type=float, default=0)), 'fire_retardant': Tunable(description='\n If an object is fire retardant then not only will it not burn, but\n it also cannot overlap with fire, so fire will not spread into an\n area occupied by a fire retardant object.\n ', tunable_type=bool, default=False)}
_commodity_flags = None
additional_interaction_constraints = None
def __init__(self, definition, **kwargs):
super().__init__(definition, tuned_native_components=self._components_native, **kwargs)
self._dynamic_commodity_flags_map = dict()
for component_factory in self._components.values():
while component_factory is not None:
self.add_component(component_factory(self))
self.item_location = ItemLocation.INVALID_LOCATION
if self._persists:
self._persistence_group = PersistenceGroups.OBJECT
else:
self._persistence_group = PersistenceGroups.NONE
self._registered_transition_controllers = set()
if self.definition.negative_environment_score != 0 or (self.definition.positive_environment_score != 0 or self.definition.environment_score_mood_tags) or self.environment_score_trait_modifiers:
self.add_dynamic_component(objects.components.types.ENVIRONMENT_SCORE_COMPONENT.instance_attr)
def on_reset_early_detachment(self, reset_reason):
super().on_reset_early_detachment(reset_reason)
for transition_controller in self._registered_transition_controllers:
transition_controller.on_reset_early_detachment(self, reset_reason)
def on_reset_get_interdependent_reset_records(self, reset_reason, reset_records):
super().on_reset_get_interdependent_reset_records(reset_reason, reset_records)
for transition_controller in self._registered_transition_controllers:
transition_controller.on_reset_add_interdependent_reset_records(self, reset_reason, reset_records)
def on_reset_internal_state(self, reset_reason):
if reset_reason == ResetReason.BEING_DESTROYED:
self._registered_transition_controllers.clear()
else:
if not (self.parent is not None and self.parent.is_sim and self.parent.posture_state.is_carrying(self)):
if not CarryingObject.snap_to_good_location_on_floor(self, self.parent.transform, self.parent.routing_surface):
self.clear_parent(self.parent.transform, self.parent.routing_surface)
self.location = self.location
super().on_reset_internal_state(reset_reason)
def register_transition_controller(self, controller):
self._registered_transition_controllers.add(controller)
def unregister_transition_controller(self, controller):
self._registered_transition_controllers.discard(controller)
@classmethod
def _verify_tuning_callback(cls):
for (i, part_data) in enumerate(cls._part_data):
while part_data.forward_direction_for_picking.magnitude() != 1.0:
logger.warn('On {}, forward_direction_for_picking is {} on part {}, which is not a normalized vector.', cls, part_data.forward_direction_for_picking, i, owner='bhill')
for sa in cls._super_affordances:
if sa.allow_user_directed and not sa.display_name:
logger.error('Interaction {} on {} does not have a valid display name.', sa.__name__, cls.__name__)
while sa.consumes_object() or sa.contains_stat(CraftingTuning.CONSUME_STATISTIC):
logger.error('ScriptObject: Interaction {} on {} is consume affordance, should tune on ConsumableComponent of the object.', sa.__name__, cls.__name__, owner='tastle/cjiang')
@flexmethod
def update_commodity_flags(cls, inst):
commodity_flags = set()
inst_or_cls = inst if inst is not None else cls
for sa in inst_or_cls.super_affordances():
commodity_flags |= sa.commodity_flags
if commodity_flags:
cls._commodity_flags = frozenset(commodity_flags)
else:
cls._commodity_flags = EMPTY_SET
@flexproperty
def commodity_flags(cls, inst):
if cls._commodity_flags is None:
if inst is not None:
inst.update_commodity_flags()
else:
cls.update_commodity_flags()
if inst is not None:
dynamic_commodity_flags = set()
for dynamic_commodity_flags_entry in inst._dynamic_commodity_flags_map.values():
dynamic_commodity_flags.update(dynamic_commodity_flags_entry)
return frozenset(cls._commodity_flags | dynamic_commodity_flags)
return cls._commodity_flags
def add_dynamic_commodity_flags(self, key, commodity_flags):
self._dynamic_commodity_flags_map[key] = commodity_flags
def remove_dynamic_commodity_flags(self, key):
if key in self._dynamic_commodity_flags_map:
del self._dynamic_commodity_flags_map[key]
@classproperty
def tuned_components(cls):
return cls._components
@flexproperty
def allowed_hands(cls, inst):
if inst is not None:
carryable = inst.carryable_component
if carryable is not None:
return carryable.allowed_hands
return ()
carryable_tuning = cls._components.carryable
if carryable_tuning is not None:
return carryable_tuning.allowed_hands
return ()
@flexproperty
def holster_while_routing(cls, inst):
if inst is not None:
carryable = inst.carryable_component
if carryable is not None:
return carryable.holster_while_routing
return False
carryable_tuning = cls._components.carryable
if carryable_tuning is not None:
return carryable_tuning.holster_while_routing
return False
def is_surface(self, *args, **kwargs):
return False
@classproperty
def _anim_overrides_cls(cls):
if cls._anim_overrides is not None:
return cls._anim_overrides(None)
@property
def object_routing_surface(self):
pass
@property
def _anim_overrides_internal(self):
params = {'isParented': self.parent is not None, 'heightAboveFloor': slots.get_surface_height_parameter_for_object(self)}
if self.is_part:
params['subroot'] = self.part_suffix
params['isMirroredPart'] = True if self.is_mirrored() else False
overrides = AnimationOverrides(params=params)
for component_overrides in self.component_anim_overrides_gen():
overrides = overrides(component_overrides())
if self._anim_overrides is not None:
return overrides(self._anim_overrides())
return overrides
@forward_to_components_gen
def component_anim_overrides_gen(self):
pass
@property
def parent(self):
pass
def ancestry_gen(self):
obj = self
while obj is not None:
yield obj
if obj.is_part:
obj = obj.part_owner
else:
obj = obj.parent
@property
def parent_slot(self):
pass
def get_closest_parts_to_position(self, position, posture=None, posture_spec=None):
best_parts = set()
best_distance = MAX_FLOAT
if position is not None and self.parts is not None:
while True:
for part in self.parts:
while (posture is None or part.supports_posture_type(posture)) and (posture_spec is None or part.supports_posture_spec(posture_spec)):
dist = (part.position_with_forward_offset - position).magnitude_2d_squared()
if dist < best_distance:
best_parts.clear()
best_parts.add(part)
best_distance = dist
elif dist == best_distance:
best_parts.add(part)
return best_parts
def num_valid_parts(self, posture):
raise RuntimeError('[bhill] This function is believed to be dead code and is scheduled for pruning. If this exception has been raised, the code is not dead and this exception should be removed.')
if self.parts is not None:
return sum(part.supports_posture_type(posture.posture_type) for part in self.parts)
return 0
def is_same_object_or_part(self, obj):
if not isinstance(obj, ScriptObject):
return False
if obj is self:
return True
if obj.is_part and obj.part_owner is self or self.is_part and self.part_owner is obj:
return True
return False
def is_same_object_or_part_of_same_object(self, obj):
if not isinstance(obj, ScriptObject):
return False
if self.is_same_object_or_part(obj):
return True
if self.is_part and obj.is_part and self.part_owner is obj.part_owner:
return True
return False
def get_compatible_parts(self, posture, interaction=None):
if posture is not None and posture.target is not None and posture.target.is_part:
return (posture.target,)
return self.get_parts_for_posture(posture, interaction)
def get_parts_for_posture(self, posture, interaction=None):
if self.parts is not None:
return (part for part in self.parts if part.supports_posture_type(posture.posture_type, interaction))
return ()
def get_parts_for_affordance(self, affordance):
raise RuntimeError('[bhill] This function is believed to be dead code and is scheduled for pruning. If this exception has been raised, the code is not dead and this exception should be removed.')
if self.parts is not None and affordance is not None:
return (part for part in self.parts if part.supports_affordance(affordance))
return ()
def may_reserve(self, *args, **kwargs):
return True
def reserve(self, *args, **kwargs):
pass
def release(self, *args, **kwargs):
pass
@property
def build_buy_lockout(self):
return False
@property
def route_target(self):
return (RouteTargetType.NONE, None)
@flexmethod
def super_affordances(cls, inst, context=None):
from objects.base_interactions import BaseInteractionTuning
inst_or_cls = inst if inst is not None else cls
component_affordances_gen = inst.component_super_affordances_gen() if inst is not None else EMPTY_SET
super_affordances = itertools.chain(inst_or_cls._super_affordances, BaseInteractionTuning.GLOBAL_AFFORDANCES, component_affordances_gen)
super_affordances = list(super_affordances)
shift_held = False
if context is not None:
shift_held = context.shift_held
for sa in super_affordances:
if shift_held:
if sa.cheat:
yield sa
elif sa.debug and __debug__:
yield sa
elif sa.automation and paths.AUTOMATION_MODE:
yield sa
while not sa.debug and not sa.cheat:
yield sa
else:
while not sa.debug and not sa.cheat:
yield sa
@forward_to_components_gen
def component_super_affordances_gen(self):
pass
@caches.cached_generator
def posture_interaction_gen(self):
for affordance in self._super_affordances:
while not affordance.debug:
if affordance._provided_posture_type is not None:
while True:
for aop in affordance.potential_interactions(self, None):
yield aop
def supports_affordance(self, affordance):
return True
def potential_interactions(self, context, get_interaction_parameters=None, allow_forwarding=True, **kwargs):
try:
for affordance in self.super_affordances(context):
if not self.supports_affordance(affordance):
pass
if get_interaction_parameters is not None:
interaction_parameters = get_interaction_parameters(affordance, kwargs)
else:
interaction_parameters = kwargs
for aop in affordance.potential_interactions(self, context, **interaction_parameters):
yield aop
for aop in self.potential_component_interactions(context):
yield aop
while allow_forwarding and (self._should_search_forwarded_sim_aop or self._should_search_forwarded_child_aop):
for aop in self._search_forwarded_interactions(context, self._should_search_forwarded_sim_aop, self._should_search_forwarded_child_aop, get_interaction_parameters=get_interaction_parameters, **kwargs):
yield aop
except Exception:
logger.exception('Exception while generating potential interactions for {}:', self)
def supports_posture_type(self, posture_type):
for super_affordance in self._super_affordances:
while super_affordance.provided_posture_type == posture_type:
return True
return False
def _search_forwarded_interactions(self, context, search_sim_aops, search_child_aops, **kwargs):
if search_sim_aops:
for part_or_object in (self,) if not self.parts else self.parts:
user_list = part_or_object.get_users(sims_only=True)
for user in user_list:
if part_or_object.is_part and part_or_object.disable_child_aop_forwarding:
pass
for aop in user.potential_interactions(context, **kwargs):
while aop.affordance.allow_forward:
yield aop
if not search_child_aops:
return
for child in self.children:
if child.parent.is_part and child.parent.disable_child_aop_forwarding:
pass
for aop in child.potential_interactions(context, **kwargs):
while aop.affordance.allow_forward:
yield aop
def add_dynamic_component(self, *args, **kwargs):
result = super().add_dynamic_component(*args, **kwargs)
if result:
self.resend_interactable()
return result
@distributor.fields.Field(op=distributor.ops.SetInteractable, default=False)
def interactable(self):
if self.build_buy_lockout:
return False
if self._super_affordances:
return True
for _ in self.component_interactable_gen():
pass
return False
resend_interactable = interactable.get_resend()
@forward_to_components_gen
def component_interactable_gen(self):
pass
@caches.cached(maxsize=20)
def check_line_of_sight(self, transform, verbose=False):
top_level_parent = self
while top_level_parent.parent is not None:
top_level_parent = top_level_parent.parent
if top_level_parent.wall_or_fence_placement:
if verbose:
return (routing.RAYCAST_HIT_TYPE_NONE, None)
return (True, None)
if self.is_in_inventory():
if verbose:
return (routing.RAYCAST_HIT_TYPE_NONE, None)
return (True, None)
slot_routing_location = self.get_routing_location_for_transform(transform)
if verbose:
ray_test = routing.ray_test_verbose
else:
ray_test = routing.ray_test
return ray_test(slot_routing_location, self.routing_location, self.raycast_context(), return_object_id=True)
clear_check_line_of_sight_cache = check_line_of_sight.cache.clear
def _create_raycast_context(self, *args, **kwargs):
super()._create_raycast_context(*args, **kwargs)
if not self.is_sim:
self.clear_check_line_of_sight_cache()
@property
def connectivity_handles(self):
routing_context = self.get_or_create_routing_context()
return routing_context.connectivity_handles
def _clear_connectivity_handles(self):
if self._routing_context is not None:
self._routing_context.connectivity_handles.clear()
@property
def focus_bone(self):
return 0
@forward_to_components
def on_state_changed(self, state, old_value, new_value):
pass
@forward_to_components
def on_post_load(self):
pass
@forward_to_components
def on_finalize_load(self):
pass
@property
def attributes(self):
pass
@property
def flammable(self):
return False
@attributes.setter
def attributes(self, value):
logger.debug('PERSISTENCE: Attributes property on {0} were set', self)
try:
object_data = ObjectData()
object_data.ParseFromString(value)
self.load_object(object_data)
except:
logger.exception('Exception applying attributes to object {0}', self)
def load_object(self, object_data):
save_data = protocols.PersistenceMaster()
save_data.ParseFromString(object_data.attributes)
self.load(save_data)
self.on_post_load()
def is_persistable(self):
if self.persistence_group == objects.persistence_groups.PersistenceGroups.OBJECT:
return True
if self.item_location == ItemLocation.FROM_WORLD_FILE:
return self._world_file_object_persists
if self.item_location == ItemLocation.ON_LOT or self.item_location == ItemLocation.FROM_OPEN_STREET:
return self._persists
if self.persistence_group == objects.persistence_groups.PersistenceGroups.IN_OPEN_STREET and self.item_location == ItemLocation.INVALID_LOCATION:
return self._persist
return False
def save_object(self, object_list, item_location=ItemLocation.ON_LOT, container_id=0):
if not self.is_persistable():
return
with ProtocolBufferRollback(object_list) as save_data:
attribute_data = self.get_attribute_save_data()
save_data.object_id = self.id
if attribute_data is not None:
save_data.attributes = attribute_data.SerializeToString()
save_data.guid = self.definition.id
save_data.loc_type = item_location
save_data.container_id = container_id
return save_data
def get_attribute_save_data(self):
attribute_data = protocols.PersistenceMaster()
self.save(attribute_data)
return attribute_data
@forward_to_components
def save(self, persistence_master_message):
pass
def load(self, persistence_master_message):
component_priority_list = []
for persistable_data in persistence_master_message.data:
component_priority_list.append((get_component_priority_and_name_using_persist_id(persistable_data.type), persistable_data))
component_priority_list.sort(key=lambda priority: priority[0][0], reverse=True)
for ((_, (_, inst_comp)), persistable_data) in component_priority_list:
while inst_comp:
self.add_dynamic_component(inst_comp)
if self.has_component(inst_comp):
getattr(self, inst_comp).load(persistable_data)
def finalize(self, **kwargs):
self.on_finalize_load()
def clone(self, **kwargs):
clone = objects.system.create_object(self.definition, **kwargs)
object_list = file_serialization.ObjectList()
save_data = self.save_object(object_list.objects)
clone.load_object(save_data)
return clone
| [
"[email protected]"
] | |
7fd36cfa7f03dce19df244b78377d20894673f87 | 523f8f5febbbfeb6d42183f2bbeebc36f98eadb5 | /41_2.py | f343d466c7476a09c8c0fa86b2be1400e2016843 | [] | no_license | saleed/LeetCode | 655f82fdfcc3000400f49388e97fc0560f356af0 | 48b43999fb7e2ed82d922e1f64ac76f8fabe4baa | refs/heads/master | 2022-06-15T21:54:56.223204 | 2022-05-09T14:05:50 | 2022-05-09T14:05:50 | 209,430,056 | 2 | 0 | null | null | null | null | UTF-8 | Python | false | false | 954 | py | class Solution(object):
def firstMissingPositive(self, nums):
"""
:type nums: List[int]
:rtype: int
"""
#哈希表的思路,但是哈希表又不能新开辟内存,所以直接使用nums的内存,
for i in range(len(nums)):
j=i
# print(j)
# while nums[j]>0 and nums[j]<=len(nums) and nums[j]!= j+1:
while nums[j] > 0 and nums[j] <= len(nums) and nums[nums[j]-1] != nums[j]:
# print(j,nums[j])
# nums[j],nums[nums[j]-1]=nums[nums[j]-1],nums[j]
tmp=nums[nums[j]-1]
nums[nums[j]-1]=nums[j]
nums[j]=tmp
print(nums)
for i in range(len(nums)):
if nums[i]!=i+1:
return i+1
return len(nums)+1
a=Solution()
# test1=[1,2,0]
# print(a.firstMissingPositive(test1))
test2=[-1,4,2,1,9,10]
print(a.firstMissingPositive(test2))
| [
"[email protected]"
] | |
8fd706f7e60376636515b21a0251659fca0ba11a | f16c091a4a5eacbf4baa4d9a5bd747de7e43c9fd | /webfeet.py | a1584157608c132d8d3b6f92699212dffebab86d | [
"BSD-3-Clause"
] | permissive | tdsmithCapU/pymarc-ebooks-scripts | 28c2e2040510cce2b28a12f098bf702f3b3fcc15 | 61cba8e4d83ea6621d2a004294c9cf29d6cdfff8 | refs/heads/master | 2021-05-28T16:53:23.540185 | 2014-11-07T20:25:09 | 2014-11-07T20:25:09 | null | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 505 | py | #!/usr/bin/env python
"""
outputs number of these terrible "Web Feet" records we had in our catalog
because we wanted to delete them all
"""
from pymarc import MARCReader
reader = MARCReader(open('ebooks.MRC'))
numWF = 0
op = ''
for record in reader:
op = ''
if record['245'] is not None:
if record['245']['c'] is not None:
if record['245']['c'] == '[selected by Web Feet].':
numWF += 1
print record.title()
print "Web Feet records: ", numWF
| [
"[email protected]"
] | |
1efba9bbb51a11c2017e78de5abfebea16dc6fd2 | 0afdfbe3f5b16ef9662d69968a3675a0b51766a7 | /bin/svn-release | 537c25a62d21dd59bb75a98bb9517ac4fd36cc7a | [] | no_license | tumb1er/bamboo-build-tools | 3fd5b54f28d037ef67d86e2d8c5f74b2400a28a6 | c10f31850bfcd8fd3e5ba075740c4138482e541c | refs/heads/master | 2021-01-02T08:39:32.697471 | 2019-01-22T06:35:32 | 2019-01-22T06:35:32 | 10,936,292 | 14 | 13 | null | 2015-12-24T15:47:00 | 2013-06-25T11:18:40 | Python | UTF-8 | Python | false | false | 1,200 | #!/usr/bin/env python
from optparse import OptionParser
import re
import sys
from bamboo.helpers import cerr
from bamboo.svn import SVNHelper
parser = OptionParser(
usage='%prog [options] <integration-task-key> <stable>',
epilog='if not task_key supplied, will take them from STDIN')
parser.add_option("-c", "--config-file", dest="configfile",
default='bamboo.cfg', help="read config from FILE",
metavar="FILE")
parser.add_option("-t", "--root", dest="root", default="^",
help="project root location")
parser.add_option("-i", "--interactive", dest="interactive", default=False,
action="store_true", help="confirm actions")
options, args = parser.parse_args()
if len(args) < 2:
parser.print_usage()
sys.exit(-1)
m = re.match(r'([A-Z]+)-[\d]+', args[0])
if not m:
cerr('invalid JIRA task key: ' + args[0])
sys.exit(-2)
if not re.match(r'^[\d]+\.(x|[\d]+\.(x|[\d]+))$', args[1]):
cerr('invalid stable: ' + args[1])
sys.exit(-2)
project_key = m.group(1)
svn = SVNHelper(project_key, root=options.root, configfile=options.configfile)
svn.release(args[0], args[1], interactive=options.interactive)
| [
"[email protected]"
] | ||
4da67f7240f871ec3438e461842e4d016a41d031 | 9da6036e7448a30d1b30fa054f0c8019215343f7 | /epaper7in5b.py | 60eec18a29920c0228b2d6d5ea7e89fa4cd224a6 | [
"MIT"
] | permissive | Markus-Be/micropython-waveshare-epaper | 4e24a3535bade98d030b4259a089d9521b83f372 | 54e44f5eb1f58185f6ee4c3bf698a5b270584c8a | refs/heads/master | 2020-03-17T23:25:02.684134 | 2018-02-25T22:02:23 | 2018-02-25T22:02:23 | null | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 4,906 | py | # MicroPython library for Waveshare 7.5" B/W/R e-paper display GDEW075Z09
from micropython import const
from time import sleep_ms
import ustruct
# Display resolution
EPD_WIDTH = const(640)
EPD_HEIGHT = const(384)
# Display commands
PANEL_SETTING = const(0x00)
POWER_SETTING = const(0x01)
POWER_OFF = const(0x02)
#POWER_OFF_SEQUENCE_SETTING = const(0x03)
POWER_ON = const(0x04)
#POWER_ON_MEASURE = const(0x05)
BOOSTER_SOFT_START = const(0x06)
DEEP_SLEEP = const(0x07)
DATA_START_TRANSMISSION_1 = const(0x10)
#DATA_STOP = const(0x11)
DISPLAY_REFRESH = const(0x12)
#IMAGE_PROCESS = const(0x13)
#LUT_FOR_VCOM = const(0x20)
#LUT_BLUE = const(0x21)
#LUT_WHITE = const(0x22)
#LUT_GRAY_1 = const(0x23)
#LUT_GRAY_2 = const(0x24)
#LUT_RED_0 = const(0x25)
#LUT_RED_1 = const(0x26)
#LUT_RED_2 = const(0x27)
#LUT_RED_3 = const(0x28)
#LUT_XON = const(0x29)
PLL_CONTROL = const(0x30)
#TEMPERATURE_SENSOR_COMMAND = const(0x40)
TEMPERATURE_CALIBRATION = const(0x41)
#TEMPERATURE_SENSOR_WRITE = const(0x42)
#TEMPERATURE_SENSOR_READ = const(0x43)
VCOM_AND_DATA_INTERVAL_SETTING = const(0x50)
#LOW_POWER_DETECTION = const(0x51)
TCON_SETTING = const(0x60)
TCON_RESOLUTION = const(0x61)
#SPI_FLASH_CONTROL = const(0x65)
#REVISION = const(0x70)
#GET_STATUS = const(0x71)
#AUTO_MEASUREMENT_VCOM = const(0x80)
#READ_VCOM_VALUE = const(0x81)
VCM_DC_SETTING = const(0x82)
FLASH_MODE = const(0xE5)
class EPD:
def __init__(self, spi, cs, dc, rst, busy):
self.spi = spi
self.cs = cs
self.dc = dc
self.rst = rst
self.busy = busy
self.cs.init(self.cs.OUT, value=1)
self.dc.init(self.dc.OUT, value=0)
self.rst.init(self.rst.OUT, value=0)
self.busy.init(self.busy.IN)
self.width = EPD_WIDTH
self.height = EPD_HEIGHT
def _command(self, command, data=None):
self.dc.low()
self.cs.low()
self.spi.write(bytearray([command]))
self.cs.high()
if data is not None:
self._data(data)
def _data(self, data):
self.dc.high()
self.cs.low()
self.spi.write(data)
self.cs.high()
def init(self):
self.reset()
self._command(POWER_SETTING, b'\x37\x00')
self._command(PANEL_SETTING, b'\xCF\x08')
self._command(BOOSTER_SOFT_START, b'\xC7\xCC\x28')
self._command(POWER_ON)
self.wait_until_idle()
self._command(PLL_CONTROL, b'\x3C')
self._command(TEMPERATURE_CALIBRATION, b'\x00')
self._command(VCOM_AND_DATA_INTERVAL_SETTING, b'\x77')
self._command(TCON_SETTING, b'\x22')
self._command(TCON_RESOLUTION, ustruct.pack(">HH", EPD_WIDTH, EPD_HEIGHT))
self._command(VCM_DC_SETTING, b'\x1E') # decide by LUT file
self._command(FLASH_MODE, b'\x03')
def wait_until_idle(self):
while self.busy.value() == 1:
sleep_ms(100)
def reset(self):
self.rst.low()
sleep_ms(200)
self.rst.high()
sleep_ms(200)
# draw the current frame memory
def display_frame(self, frame_buffer):
self._command(DATA_START_TRANSMISSION_1)
for i in range(0, self.width // 4 * self.height):
temp1 = frame_buffer[i]
j = 0
while (j < 4):
if ((temp1 & 0xC0) == 0xC0):
temp2 = 0x03
elif ((temp1 & 0xC0) == 0x00):
temp2 = 0x00
else:
temp2 = 0x04
temp2 = (temp2 << 4) & 0xFF
temp1 = (temp1 << 2) & 0xFF
j += 1
if ((temp1 & 0xC0) == 0xC0):
temp2 |= 0x03
elif ((temp1 & 0xC0) == 0x00):
temp2 |= 0x00
else:
temp2 |= 0x04
temp1 = (temp1 << 2) & 0xFF
self._data(bytearray([temp2]))
j += 1
self._command(DISPLAY_REFRESH)
sleep_ms(100)
self.wait_until_idle()
# to wake call reset() or init()
def sleep(self):
self._command(POWER_OFF)
self.wait_until_idle()
self._command(DEEP_SLEEP, b'\xA5')
| [
"[email protected]"
] | |
d00852eda6279d4ffe2238dc7824a7afd39520d7 | 3151fabc3eb907d6cd1bb17739c215a8e95a6370 | /storagetest/pkgs/pts/aio/__init__.py | d65ddb2e7f4c7fe45271498226071e84ce8e9a13 | [
"MIT"
] | permissive | txu2k8/storage-test | a3afe96dc206392603f4aa000a7df428d885454b | 62a16ec57d619f724c46939bf85c4c0df82ef47c | refs/heads/master | 2023-03-25T11:00:54.346476 | 2021-03-15T01:40:53 | 2021-03-15T01:40:53 | 307,604,046 | 1 | 0 | null | null | null | null | UTF-8 | Python | false | false | 2,366 | py | #!/usr/bin/python
# -*- coding: UTF-8 -*-
"""
@file : __init__.py.py
@Time : 2020/11/12 17:17
@Author: Tao.Xu
@Email : [email protected]
"""
from .aio_stress import *
__all__ = ['AioStress']
"""
DBENCH
==============
https://dbench.samba.org/web/index.html
https://openbenchmarking.org/test/pts/dbench-1.0.0
DBENCH is a tool to generate I/O workloads to either a filesystem or to
a networked CIFS or NFS server. It can even talk to an iSCSI target.
DBENCH can be used to stress a filesystem or a server to see which workload
it becomes saturated and can also be used for preditcion analysis to determine
"How many concurrent clients/applications performing this workload can my server
handle before response starts to lag?"
DBENCH provides a similar benchmarking and client emulation that is implemented
in SMBTORTURE using the BENCH-NBENCH test for CIFS, but DBENCH can play these
loadfiles onto a local filesystem instead of to a CIFS server.
Using a different type of loadfiles DBENCH can also generate and measure latency for NFS.
Features include:
1. Reading SMBTORTURE BENCH-NBENCH loadfiles and emulating this workload as posix
calls to a local filesystem
2. NFS style loadfiles which allows DBENCH to mimic the i/o pattern of a real
application doing real i/o to a real server.
3. iSCSI support and iSCSI style loadfiles.
Loadfiles
At the heart of DBENCH is the concept of a "loadfile". A loadfile is a sequence of operations
to be performed once statement at a time. This could be operations such as "Open file XYZ",
"Read 5 bytes from offset ABC", "Close the file", etc etc.
By carefully crafting a loadfile it is possible to describe an I/O pattern that almost exactly
matches what a particular application performs. While cumbersome to produce, such a loadfile
it does allow you to describe exactly how/what an application performs and "replay" this
sequence of operations any time you want.
Each line in the DBENCH loadfile contain a timestamp for the operation.
This is used by DBENCH to try to keep the same rate of operations as the original application.
This is very useful since this allows to perform accurate scalability predictions based on the
exact application we are interested in. and not an artificial benchmark which may or may not
be relevant to our particular applications workload pattern.
"""
| [
"[email protected]"
] | |
39dc4db957a259186b8dda8fdafdf81bdf7c08aa | a2d36e471988e0fae32e9a9d559204ebb065ab7f | /huaweicloud-sdk-waf/huaweicloudsdkwaf/v1/model/list_statistics_response.py | 37f0f31bc7acb2df13f6c9f35c68b04e2742fea8 | [
"Apache-2.0"
] | permissive | zhouxy666/huaweicloud-sdk-python-v3 | 4d878a90b8e003875fc803a61414788e5e4c2c34 | cc6f10a53205be4cb111d3ecfef8135ea804fa15 | refs/heads/master | 2023-09-02T07:41:12.605394 | 2021-11-12T03:20:11 | 2021-11-12T03:20:11 | null | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 3,097 | py | # coding: utf-8
import re
import six
from huaweicloudsdkcore.sdk_response import SdkResponse
from huaweicloudsdkcore.utils.http_utils import sanitize_for_serialization
class ListStatisticsResponse(SdkResponse):
"""
Attributes:
openapi_types (dict): The key is attribute name
and the value is attribute type.
attribute_map (dict): The key is attribute name
and the value is json key in definition.
"""
sensitive_list = []
openapi_types = {
'body': 'list[CountItem]'
}
attribute_map = {
'body': 'body'
}
def __init__(self, body=None):
"""ListStatisticsResponse - a model defined in huaweicloud sdk"""
super(ListStatisticsResponse, self).__init__()
self._body = None
self.discriminator = None
if body is not None:
self.body = body
@property
def body(self):
"""Gets the body of this ListStatisticsResponse.
安全统计数据
:return: The body of this ListStatisticsResponse.
:rtype: list[CountItem]
"""
return self._body
@body.setter
def body(self, body):
"""Sets the body of this ListStatisticsResponse.
安全统计数据
:param body: The body of this ListStatisticsResponse.
:type: list[CountItem]
"""
self._body = body
def to_dict(self):
"""Returns the model properties as a dict"""
result = {}
for attr, _ in six.iteritems(self.openapi_types):
value = getattr(self, attr)
if isinstance(value, list):
result[attr] = list(map(
lambda x: x.to_dict() if hasattr(x, "to_dict") else x,
value
))
elif hasattr(value, "to_dict"):
result[attr] = value.to_dict()
elif isinstance(value, dict):
result[attr] = dict(map(
lambda item: (item[0], item[1].to_dict())
if hasattr(item[1], "to_dict") else item,
value.items()
))
else:
if attr in self.sensitive_list:
result[attr] = "****"
else:
result[attr] = value
return result
def to_str(self):
"""Returns the string representation of the model"""
import simplejson as json
if six.PY2:
import sys
reload(sys)
sys.setdefaultencoding("utf-8")
return json.dumps(sanitize_for_serialization(self), ensure_ascii=False)
def __repr__(self):
"""For `print`"""
return self.to_str()
def __eq__(self, other):
"""Returns true if both objects are equal"""
if not isinstance(other, ListStatisticsResponse):
return False
return self.__dict__ == other.__dict__
def __ne__(self, other):
"""Returns true if both objects are not equal"""
return not self == other
| [
"[email protected]"
] | |
98add982addaab600ecf76da05cada48297224f9 | 53181572c4b22df4b569a9901bcd5347a3459499 | /tuit_190315_songyuda/demo0322/integer.py | 199c22c41f1d87f7184e01b623c85f7d1d6bf3de | [] | no_license | edu-athensoft/ceit4101python_student | 80ef067b77421fce76d04f778d5c6de8b12f676c | 33cfa438c062d45e8d246b853e93d3c14b92ff2d | refs/heads/master | 2020-07-30T01:04:21.084384 | 2020-07-27T02:21:57 | 2020-07-27T02:21:57 | 210,027,310 | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 146 | py | # data types
# number (integer, float)
# string
# decimal, hex, oct, bin
d1 = 11
h1 = 0xF
o1 = 0o10
b1 = 0b1100
# hex(), oct(), bin()
print(h1) | [
"[email protected]"
] | |
d5dc3e2fbf8dccb285ca1d21ad9ffb8564f280a0 | b92b9f089ace00f8b301abca3d2871faf33f11af | /rrdpic/update.py | faf2f1214e0ed9382ff0f39eb1f193e972cfac4b | [] | no_license | zhouyu37/study | c3453613d8b446478af61bf4df7910ec4649b536 | a8b2702fc94e6abd6a15f21b833bb885ee011fa9 | refs/heads/master | 2021-03-17T22:15:25.924902 | 2020-03-13T08:32:55 | 2020-03-13T08:32:55 | 247,022,027 | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 312 | py | # -*- coding: utf-8 -*-
import rrdtool
import time,psutil
total_input_traffic=psutil.net_io_counters()[1]
total_ouput_traffic=psutil.net_io_counters()[0]
starttime=int(time.time())
update=rrdtool.updatev('Flow.rrd','%s:%s:%s'%(str(total_input_traffic),str(total_ouput_traffic),str(starttime)))
print(update)
| [
"[email protected]"
] | |
7b44072c08d20cbfaf773b21a7025382966bb70b | 0f7496520832831a6ae89481fa994fb540882efd | /feedback/views.py | 315627663293e3ce54660bf14f1b12cac40a1678 | [
"ISC"
] | permissive | pmaigutyak/mp-feedback | f88287f6aa7e5812e24f51f3ea14c1a8b2d98cb3 | a5bcf5e67aeced62f048466b9e1354f5183f8eeb | refs/heads/master | 2022-04-19T12:02:18.729823 | 2020-04-20T17:55:07 | 2020-04-20T17:55:07 | 257,354,018 | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 2,545 | py |
from django.conf import settings
from django.apps import apps
from django.shortcuts import render
from django.http.response import HttpResponse
from django.views.generic import FormView
from django.core.mail import send_mail
from django.template.loader import render_to_string
from feedback.forms import FeedbackForm
class CreateFeedbackView(FormView):
form_class = FeedbackForm
def dispatch(self, request, *args, **kwargs):
self.is_modal = request.GET.get('modal', False)
return super().dispatch(request, *args, **kwargs)
def get_initial(self):
user = self.request.user
if user.is_authenticated:
return {
'name': user.get_full_name(),
'email': user.email
}
return self.initial
@property
def template_name(self):
return 'feedback/modal.html' if self.is_modal else 'feedback/view.html'
def form_valid(self, form):
obj = form.save(commit=False)
if self.request.user.is_authenticated:
obj.user = self.request.user
obj.save()
self.send_email_notification(obj)
self.send_sms_notification(obj)
message = render_to_string(
'feedback/success-message.html', {'object': obj})
return HttpResponse(message)
def form_invalid(self, form):
return render(
self.request,
'feedback/form.html' if self.is_modal else 'feedback/view.html',
{'form': form},
status=403)
def send_email_notification(self, obj):
context = self.get_notifications_context(obj)
subject = render_to_string('feedback/email/subject.txt', context)
html = render_to_string('feedback/email/message.html', context)
send_mail(
subject=subject.strip(),
message='',
from_email=settings.DEFAULT_FROM_EMAIL,
html_message=html,
recipient_list=self.get_email_recipients())
def get_email_recipients(self):
return [a[1] for a in settings.MANAGERS]
def send_sms_notification(self, obj):
if not apps.is_installed('turbosms'):
return
from turbosms.lib import send_sms_from_template
context = self.get_notifications_context(obj)
send_sms_from_template('feedback/sms.txt', context)
def get_notifications_context(self, obj):
return {
'object': obj,
'site': apps.get_model('sites', 'Site').objects.get_current()
}
| [
"[email protected]"
] | |
00a316aa39850a1dc405504c4831723c20a04bf6 | fea6b4ab5da18c35c3c876a970419e213690f5a9 | /backend/test_app_26036/urls.py | c6de92e7a661fddd934f36e409bd37a689172d87 | [] | no_license | crowdbotics-apps/test-app-26036 | bd4fc88769219c7be9d41b11352a0a7012aaa622 | f327b949d474cdeedb541c41aa6d5035fccb3106 | refs/heads/master | 2023-06-23T09:43:49.218044 | 2021-04-30T03:05:06 | 2021-04-30T03:05:06 | 363,010,187 | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 2,211 | py | """test_app_26036 URL Configuration
The `urlpatterns` list routes URLs to views. For more information please see:
https://docs.djangoproject.com/en/2.2/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, re_path
from django.views.generic.base import TemplateView
from allauth.account.views import confirm_email
from rest_framework import permissions
from drf_yasg.views import get_schema_view
from drf_yasg import openapi
urlpatterns = [
path("", include("home.urls")),
path("accounts/", include("allauth.urls")),
path("modules/", include("modules.urls")),
path("api/v1/", include("home.api.v1.urls")),
path("admin/", admin.site.urls),
path("users/", include("users.urls", namespace="users")),
path("rest-auth/", include("rest_auth.urls")),
# Override email confirm to use allauth's HTML view instead of rest_auth's API view
path("rest-auth/registration/account-confirm-email/<str:key>/", confirm_email),
path("rest-auth/registration/", include("rest_auth.registration.urls")),
]
admin.site.site_header = "Test App"
admin.site.site_title = "Test App Admin Portal"
admin.site.index_title = "Test App Admin"
# swagger
api_info = openapi.Info(
title="Test App API",
default_version="v1",
description="API documentation for Test App App",
)
schema_view = get_schema_view(
api_info,
public=True,
permission_classes=(permissions.IsAuthenticated,),
)
urlpatterns += [
path("api-docs/", schema_view.with_ui("swagger", cache_timeout=0), name="api_docs")
]
urlpatterns += [path("", TemplateView.as_view(template_name='index.html'))]
urlpatterns += [re_path(r"^(?:.*)/?$",
TemplateView.as_view(template_name='index.html'))]
| [
"[email protected]"
] | |
238e9f37d5e366d3845c2409f3db92ee35db09c2 | 1e90f2e153c9040c4e0ff417e009bf929ddfa1a4 | /preprocess.py | 13ebed8963e1c6314cfb23827dd8f2b107d65d85 | [] | no_license | hkxIron/SlotGated-SLU | d83b786b3f9243fd04bffe6c13d451c435b15679 | dc17780cc37f79ed9c4c3854af1c076020742a2f | refs/heads/master | 2020-04-11T12:19:19.724026 | 2019-03-10T16:35:51 | 2019-03-10T16:35:51 | 161,776,548 | 0 | 0 | null | 2018-12-14T11:37:22 | 2018-12-14T11:37:21 | null | UTF-8 | Python | false | false | 2,007 | py | #!/usr/bin/env python
# -*- coding: utf-8 -*-
# @Time : 2018/10/28 下午 08:55
# @Author : Aaron Chou
# @Site : https://github.com/InsaneLife
import gensim
import numpy as np
data_root = 'E:\project_data\word_vector/'
model_path = data_root + 'GoogleNews-vectors-negative300.bin.gz'
# 导入模型
model = gensim.models.KeyedVectors.load_word2vec_format(model_path, binary=True)
# model.save_word2vec_format(data_root + 'GoogleNews-vectors-negative300.txt', binary=False)
google_embedding_path = data_root + 'GoogleNews-vectors-negative300.txt'
# print(model['to'])
def get_embedding_map(path):
map = {}
with open(path, 'r',encoding="utf-8") as f:
for each in f.readlines():
each = each.strip().split()
map[each[0]] = [float(x) for x in each[1:]]
return map
def write_vector2file(embedding_map, vocab_path, out_path, dim):
with open(vocab_path) as vocabs:
vocabs = vocabs.readlines()
embedding = np.zeros([len(vocabs), dim])
for i, v in enumerate(vocabs):
v = v.strip()
try:
embedding[i] = np.array(embedding_map[v])
except:
continue
np.save(out_path, embedding)
def write_model_vector2file(model, vocab_path, out_path, dim):
with open(vocab_path) as vocabs:
vocabs = vocabs.readlines()
embedding = np.zeros([len(vocabs), dim])
for i, v in enumerate(vocabs):
v = v.strip()
try:
embedding[i] = np.array(model[v])
except:
print("do not have: {}".format(v))
continue
np.save(out_path, embedding)
vocab_path = "./vocab/in_vocab"
out_path = "./vocab/google_in_vocab_embedding.npy"
dim = 300
# embedding_map = get_embedding_map(google_embedding_path)
# write_vector2file(embedding_map, vocab_path, out_path, dim)
write_model_vector2file(model, vocab_path, out_path, dim)
| [
"[email protected]"
] | |
b06d8c40c0056f651b15c192c20b92aa0e21e03f | 84e661d5d293ec0c544fedab7727767f01e7ddcf | /gallery/migrations-old/0009_photograph_featured.py | 6408790716972e18b35daf2e444fa702b7aff740 | [
"BSD-3-Clause"
] | permissive | groundupnews/gu | ea6734fcb9509efc407061e35724dfe8ba056044 | 4c036e79fd735dcb1e5a4f15322cdf87dc015a42 | refs/heads/master | 2023-08-31T13:13:47.178119 | 2023-08-18T11:42:58 | 2023-08-18T11:42:58 | 48,944,009 | 21 | 23 | BSD-3-Clause | 2023-09-14T13:06:42 | 2016-01-03T11:56:48 | JavaScript | UTF-8 | Python | false | false | 457 | py | # -*- coding: utf-8 -*-
# Generated by Django 1.9.6 on 2016-11-17 11:34
from __future__ import unicode_literals
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('gallery', '0008_auto_20161104_1658'),
]
operations = [
migrations.AddField(
model_name='photograph',
name='featured',
field=models.BooleanField(default=False),
),
]
| [
"[email protected]"
] | |
29fcf5c22c1c7225a673988eb942de70924f71d7 | 0db19410e9751790af8ce4a0a9332293e379c02f | /tests/test_datasets/test_datasets/test_animal_datasets/test_animalkingdom_dataset.py | cc5e42ffbbdc7b17adaeaedc41fc52bc0cc6667a | [
"Apache-2.0"
] | permissive | open-mmlab/mmpose | 2c9986521d35eee35d822fb255e8e68486026d94 | 537bd8e543ab463fb55120d5caaa1ae22d6aaf06 | refs/heads/main | 2023-08-30T19:44:21.349410 | 2023-07-04T13:18:22 | 2023-07-04T13:18:22 | 278,003,645 | 4,037 | 1,171 | Apache-2.0 | 2023-09-14T09:44:55 | 2020-07-08T06:02:55 | Python | UTF-8 | Python | false | false | 5,276 | py | # Copyright (c) OpenMMLab. All rights reserved.
from unittest import TestCase
import numpy as np
from mmpose.datasets.datasets.animal import AnimalKingdomDataset
class TestAnimalKingdomDataset(TestCase):
def build_ak_dataset(self, **kwargs):
cfg = dict(
ann_file='test_animalkingdom.json',
bbox_file=None,
data_mode='topdown',
data_root='tests/data/ak',
pipeline=[],
test_mode=False)
cfg.update(kwargs)
return AnimalKingdomDataset(**cfg)
def check_data_info_keys(self,
data_info: dict,
data_mode: str = 'topdown'):
if data_mode == 'topdown':
expected_keys = dict(
img_id=int,
img_path=str,
bbox=np.ndarray,
bbox_score=np.ndarray,
keypoints=np.ndarray,
keypoints_visible=np.ndarray,
id=int)
elif data_mode == 'bottomup':
expected_keys = dict(
img_id=int,
img_path=str,
bbox=np.ndarray,
bbox_score=np.ndarray,
keypoints=np.ndarray,
keypoints_visible=np.ndarray,
invalid_segs=list,
id=list)
else:
raise ValueError(f'Invalid data_mode {data_mode}')
for key, type_ in expected_keys.items():
self.assertIn(key, data_info)
self.assertIsInstance(data_info[key], type_, key)
def check_metainfo_keys(self, metainfo: dict):
expected_keys = dict(
dataset_name=str,
num_keypoints=int,
keypoint_id2name=dict,
keypoint_name2id=dict,
upper_body_ids=list,
lower_body_ids=list,
flip_indices=list,
flip_pairs=list,
keypoint_colors=np.ndarray,
num_skeleton_links=int,
skeleton_links=list,
skeleton_link_colors=np.ndarray,
dataset_keypoint_weights=np.ndarray)
for key, type_ in expected_keys.items():
self.assertIn(key, metainfo)
self.assertIsInstance(metainfo[key], type_, key)
def test_metainfo(self):
dataset = self.build_ak_dataset()
self.check_metainfo_keys(dataset.metainfo)
# test dataset_name
self.assertEqual(dataset.metainfo['dataset_name'], 'Animal Kingdom')
# test number of keypoints
num_keypoints = 23
self.assertEqual(dataset.metainfo['num_keypoints'], num_keypoints)
self.assertEqual(
len(dataset.metainfo['keypoint_colors']), num_keypoints)
self.assertEqual(
len(dataset.metainfo['dataset_keypoint_weights']), num_keypoints)
# note that len(sigmas) may be zero if dataset.metainfo['sigmas'] = []
self.assertEqual(len(dataset.metainfo['sigmas']), num_keypoints)
# test some extra metainfo
self.assertEqual(
len(dataset.metainfo['skeleton_links']),
len(dataset.metainfo['skeleton_link_colors']))
def test_topdown(self):
# test topdown training
dataset = self.build_ak_dataset(data_mode='topdown')
self.assertEqual(dataset.data_mode, 'topdown')
self.assertEqual(dataset.bbox_file, None)
self.assertEqual(len(dataset), 2)
self.check_data_info_keys(dataset[0])
# test topdown testing
dataset = self.build_ak_dataset(data_mode='topdown', test_mode=True)
self.assertEqual(dataset.data_mode, 'topdown')
self.assertEqual(dataset.bbox_file, None)
self.assertEqual(len(dataset), 2)
self.check_data_info_keys(dataset[0])
def test_bottomup(self):
# test bottomup training
dataset = self.build_ak_dataset(data_mode='bottomup')
self.assertEqual(len(dataset), 2)
self.check_data_info_keys(dataset[0], data_mode='bottomup')
# test bottomup testing
dataset = self.build_ak_dataset(data_mode='bottomup', test_mode=True)
self.assertEqual(len(dataset), 2)
self.check_data_info_keys(dataset[0], data_mode='bottomup')
def test_exceptions_and_warnings(self):
with self.assertRaisesRegex(ValueError, 'got invalid data_mode'):
_ = self.build_ak_dataset(data_mode='invalid')
with self.assertRaisesRegex(
ValueError,
'"bbox_file" is only supported when `test_mode==True`'):
_ = self.build_ak_dataset(
data_mode='topdown',
test_mode=False,
bbox_file='temp_bbox_file.json')
with self.assertRaisesRegex(
ValueError, '"bbox_file" is only supported in topdown mode'):
_ = self.build_ak_dataset(
data_mode='bottomup',
test_mode=True,
bbox_file='temp_bbox_file.json')
with self.assertRaisesRegex(
ValueError,
'"bbox_score_thr" is only supported in topdown mode'):
_ = self.build_ak_dataset(
data_mode='bottomup',
test_mode=True,
filter_cfg=dict(bbox_score_thr=0.3))
| [
"[email protected]"
] | |
85af35808f800c062b40cacb1937c95adddd9cb7 | ca7aa979e7059467e158830b76673f5b77a0f5a3 | /Python_codes/p02681/s149964589.py | f36d8a296b72710b130581d9203271aaa9469b6e | [] | 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 | 48 | py | s=input()
print("Yes"if s==input()[:-1]else"No") | [
"[email protected]"
] | |
e29851cd23e6c39680be789b1ca1f46aa0da0450 | 96f8d1f282f5d9a526af3a4c50c97b758f7e1357 | /pv_wfun_v2.5.py | c9815bd949093cff2975fd57d4a04add436fe0b5 | [] | no_license | ccme-tmc/tmckit | 4b80bcc4991d1448b02cfdef5dbd077c653624d0 | 54054434a6da59160860478ee50f3118e20e2d16 | refs/heads/master | 2021-07-02T01:11:44.162474 | 2019-10-29T01:04:33 | 2019-10-29T01:04:33 | 182,224,486 | 12 | 3 | null | null | null | null | UTF-8 | Python | false | false | 14,223 | py | #!/usr/bin/env python
# v1 is written by HJ, v2 is modified by ZHC
import sys,os,shutil,scipy,numpy,math
import matplotlib.pyplot as plt
from scipy import interpolate
from struct_utils import *
from constants import *
#from vasp_utils_jh import vasp_read_pot
from io_utils import *
#from wfun_utils import *
#import matplotlib.pyplot as plt
def vasp_read_pot(potfile="LOCPOT",zshift=0.0,bulk_flag=0,direct_flag='0'):
"""
Read the electron density or potential from the file
"""
ifile = open(potfile,'r')
ifile.readline()
latt_scale = float(ifile.readline()) # scale for the lattice vectors
# read the lattice vectors
latt_vec=[]
for i in range(3):
line_s = ifile.readline().split()
x = float(line_s[0])
y = float(line_s[1])
z = float(line_s[2])
latt_vec.append([x,y,z])
#print latt_vec
mat=numpy.array(latt_vec)
if direct_flag=='0':
if mat[2][2]>mat[0][0]:
if mat[2][2]>mat[1][1]:
zdirect=2
else:
zdirect=1
else:
if mat[0][0]>mat[1][1]:
zdirect=0
else:
zdirect=1
else:
if direct_flag=='x':
zdirect=0
elif direct_flag=='y':
zdirect=1
else:
zdirect=2
# print mat
trans_mat=numpy.transpose(mat)
# print trans_mat
inv_mat=numpy.linalg.inv(trans_mat)
# print inv_mat
# read species
specs = ifile.readline().split()
nat_sp =[]
line_s = ifile.readline().split()
nat = 0
for i in range(len(specs)):
nat_sp.append(int(line_s[i]))
nat += nat_sp[i]
cord_type=ifile.readline()
#add by ZHC
cord_type=cord_type.lstrip()
zlist=[]
zmin=1000000.0
zmax=0.0
for i in range(nat):
line = ifile.readline().split()
atvec=[]
for j in range(3):
atvec.append(float(line[j]))
atvec=numpy.array(atvec)
# print atvec
# zpos=float(line[2])
if cord_type[0]=='D' or cord_type[0]=='d': ### all convert to Cartizian to find the center of the slab
#print "NOTE: The coordination is DIRECT!!!"
for j in range(3):
if j==zdirect:
atvec[j]=atvec[j]+zshift
atvec[j]=atvec[j]-math.floor(atvec[j])
cart_vec=numpy.dot(trans_mat,atvec)
if cart_vec[zdirect]<zmin:
zmin=cart_vec[zdirect]
if cart_vec[zdirect]>zmax:
zmax=cart_vec[zdirect]
else:
#print "NOTE: The coordination is CARTISIAN!!!"
dir_vec=numpy.dot(inv_mat,atvec)
#print dir_vec
for j in range(3):
if j==zdirect:
dir_vec[j]=dir_vec[j]+zshift
dir_vec[j]=dir_vec[j]-math.floor(dir_vec[j])
#print dir_vec
cart_vec=numpy.dot(trans_mat,dir_vec)
#print cart_vec
if cart_vec[zdirect]<zmin:
zmin=cart_vec[zdirect]
if cart_vec[zdirect]>zmax:
zmax=cart_vec[zdirect]
center_pos=(zmax+zmin)/2.0
# print "zmax,zmin"
# print zmax,zmin
# print "CENTER:"
# print center_pos
dis_vac_up=mat[zdirect][zdirect]-zmax
dis_vac_down=zmin-0.0
thick_vac=abs(dis_vac_up+dis_vac_down)
if zmax-zmin>0.8*mat[zdirect][zdirect] and mat[zdirect][zdirect]>12.0 and bulk_flag==0:
frac=(mat[zdirect][zdirect]-zmax)/float((mat[zdirect][zdirect]))
print "PLEASE SET -z tag to ensure the slab does not cross the boundary!!!"
sys.exit(0)
vac_center=thick_vac/2.0+zmax
if vac_center>mat[zdirect][zdirect]+zshift*mat[zdirect][zdirect]:
vac_center=vac_center-mat[zdirect][zdirect]
# print "vac_center"
# print vac_center
ifile.readline()
line_s = ifile.readline().split()
nx = int(line_s[0])
ny = int(line_s[1])
nz = int(line_s[2])
ndata = nx*ny*nz
nlines = ndata/5
if ndata%5 != 0: nlines += 1
data = []
for il in range(nlines):
line_s = ifile.readline().split()
for i in range(len(line_s)):
data.append(float(line_s[i]))
ifile.close()
return data,(nx,ny,nz),latt_vec,center_pos,vac_center,zmax,zmin,zdirect,thick_vac
#vasp_read_pot()
def f_Help_Info():
myname = sys.argv[0]
print "\n"+myname + ": a Python script to get work function using VAPS output. Mainly for bulk correction calculations. \n"
print " Usage: " + os.path.basename(myname) + " [options]"\
+ """
Options:
-h # display this help information
-f <file > # prefix for input and output
-d <x/y/z> # the normal direction of the surface. Default is determined automatically.
-n <int> # set the # of point for average WITHOUT automatic procedure. Use for the case that the average range is not correctly found.
-i <int> # set the factor of cubic spline interpolation. The default value is 10, so that the total number of point will be 10*number of original data. If i=0, the interpolation will be switched off.
-b <1/0> # set the type slab(0), bulk(1). Default: bulk or slab will be determined automatically. Or you can use this tag to force it as bulk.
-t <data_type>: # VH/RHO
-tol <float>: # the tolerance for automatic determination of periodic range for averaging. The default value is 0.2.
-z <float>: # shift of the fractional coordination in z direction to ensure the slab will NOT span the boundary. The default value is 0.0.
-s <int> # 1 for save the electric potential curve figure as png. 0 for show the figure to the screen. The default is 0.
--debug # set debug mode
Examples1:
./pv_wfun_v2.py -f LOCPOT
"""
sys.exit(0)
def findpeak(ax,ay): #find the peaks of electric potential
if len(ax)!=len(ay):
print "FIND PEAK ERROR: length of vector not equal"
peakx=[]
peaky=[]
peakindex=[]
for i in range(len(ay)-1):
if (ay[i]-ay[i-1])*(ay[i+1]-ay[i])<=0.0:
peakindex.append(i)
peakx.append(ax[i])
peaky.append(ay[i])
last=len(ay)-1
if (ay[last]-ay[last-1])*(ay[0]-ay[last])<=0.0:
peakx.append(ax[last])
peaky.append(ay[last])
peakindex.append(last)
if len(peakx)<=3:
print "\n WARNING!!!!!!!!!!!!\n The # of peaks is rather small!!!!!The averaging range may be NOT correct!!!!\n"
return peakx,peaky,peakindex
# default input and output format
def_dnorm = '0'
#def_intflag = 1
def_file = ''
def_debug = False
def_np = 10
def_bulk=1
def_zshift=0.0
def_tolerance=0.2
def_save=0
if f_Getopt('-h',0,False): f_Help_Info()
dnorm = f_Getopt('-d',1,'0' )
np = f_Getopt('-i',1,10)
bulk = f_Getopt('-b',1,0)
num_set=f_Getopt('-n',1,0)
file = f_Getopt('-f',1,'LOCPOT' )
#np = f_Getopt('-n',1,10 )
type = f_Getopt('-t',1,'VH')
zshift = f_Getopt('-z',1,0.0)
tolerance = f_Getopt('-tol',1,0.2)
save = f_Getopt('-s',1,0)
vh,nxyz,latt_vec,center_pos,vac_center,zmax,zmin,zdirect,thick_vac = vasp_read_pot(file,zshift,bulk,dnorm)
if bulk==0 and thick_vac<5.0:
bulk=1
directs=['x','y','z']
if dnorm=='0':
dnorm=directs[zdirect]
#print center_pos
(nx,ny,nz) = nxyz
#print " nx,ny,nz=",nx,ny,nz
if dnorm == 'x':
nd = nx
vd = latt_vec[0]
elif dnorm == 'y':
nd = ny
# vd = latt_vec[1+shift]
vd = latt_vec[1]
elif dnorm == 'z':
nd = nz
vd = latt_vec[2]
elif dnorm == '0':
nd = 1
vd = [0.0,0.0,0.0]
else:
print "ERROR: unsupported option for dnorm= ",dnorm
nsum = nx*ny*nz/nd
vd0 = []
for i in range(nd): vd0.append(0.0)
ip=0
vsum=0.0
for iz in range(nz):
for iy in range(ny):
for ix in range(nx):
if dnorm == 'x': vd0[ix] += vh[ip]
elif dnorm == 'y': vd0[iy] += vh[ip]
elif dnorm == 'z': vd0[iz] += vh[ip]
else: vd0[0] += vh[ip]
ip += 1
for i in range(nd): vd0[i] = (vd0[i]/nsum)
print 'Number of original data:',nd
if nd == 1:
print "Averaged electrostatic potetial= %12.4f"%(vd0[0])
sys.exit(0)
ld = sqrt(vd[0]**2+vd[1]**2+vd[2]**2)
vd0.append(vd0[0])
nd += 1
hd = ld/(nd-1)
xd0 = []
for i in range(nd): xd0.append(i*hd)
fname = file+'-'+type+'-wfun'
print "Original data after xy averaging is written to ",fname+"0.dat"
ofile = open( fname+"0.dat",'w')
xd_moved=[]
for i in range(len(xd0)):
# xd_moved.append(xd0[i]-ld/2.0)
xd_moved.append(xd0[i]+zshift*vd[zdirect])
ofile.write('%12.6f %12.6f \n' %(xd0[i]-ld/2.0,vd0[i]))
ofile.close()
if bulk==1:
sum_bulk=0.0 ### bulk==1 case
for i in range(len(xd0)):
sum_bulk=sum_bulk+vd0[i]
sum_bulk=sum_bulk/float(len(xd0))
print "TREAT AS BULK!!!"
print "The averaged electric potential is:"
print sum_bulk
sys.exit(0)
#print xd_moved
#print "V0(z=0 )= %12.4f "%vd0[0]
if np > 0: ### interpolation in cubic spline
print 'Factor of interpolated data:',np
np = (nd-1)*np+1
f_intp=interpolate.interp1d(xd_moved,vd0,kind='cubic')
xd_intp=numpy.linspace(xd_moved[0],xd_moved[-1],num=np)
y_intp=f_intp(xd_intp)
peakx,peaky,peakindex=findpeak(xd_intp,y_intp) ### find the peak
cent_center=100000.0
cent_index=-999999
for i in range(len(xd_intp)):
dis=abs(xd_intp[i]-center_pos)
if dis<cent_center:
cent_center=dis
cent_index=i
dis_center=100000.0
dis_index=-999999
for i in range(len(peakx)): ### find the peak nearest to the center of slab
dis=abs(peakx[i]-center_pos)
if dis<dis_center:
dis_center=dis
dis_index=i
# print "DIS"
# print dis_center,dis_index,peakx[dis_index]
min_dis=9999999.0
min_index=-9999999
#tolerance=0.2
for i in range(len(peakx)): ### find another peak which has the same value of the peak nearest to the center
if abs(peaky[i]-peaky[dis_index])<tolerance:
if abs(peakx[i]-peakx[dis_index])<min_dis and i!=dis_index and abs(y_intp[peakindex[i]-int(np/50)]-y_intp[peakindex[dis_index]-int(np/50)])<tolerance:
min_dis=abs(peakx[i]-peakx[dis_index])
min_index=i
# print min_dis,min_index
# print "!!!!!Q"
# print min_index,dis_index
find_peak_flag=1
if min_index==-9999999:
min_dis=9999999.0
min_index=-9999999
print "\nWARNING!!!!!!!!!!!!!!!!!!!!!!!!!\nCan not find the range for averaging automatically!!!\n TRY TO INCREASE THE TOLERANCE AND FIND IT AGAIN!!!\nWARNING!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!\n"
tolerance=2*tolerance
for i in range(len(peakx)): ### find another peak which has the same value of the peak nearest to the center
if abs(peaky[i]-peaky[dis_index])<tolerance:
if abs(peakx[i]-peakx[dis_index])<min_dis and i!=dis_index and abs(y_intp[peakindex[i]-int(np/50)]-y_intp[peakindex[dis_index]-int(np/50)])<tolerance:
min_dis=abs(peakx[i]-peakx[dis_index])
min_index=i
if min_index==-9999999:
print "\nWARNING!!!!!!!!!!!!!!!!!!!!!!!!!\nCan not find the range for averaging automatically AGAIN!!!\n PLEASE set the range manually!!!\nWARNING!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!\n"
min_index=dis_index-1
min_dis=1.0
find_peak_flag=0
else:
print "\nWARNING!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!\nSEEMS FIND THE PERIOD AFTER INCREASE THE TOLERANCE, CHECK THE PERIOD BY YOUR SELF!!!!\nWARNING!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!\n"
num_ave=int(abs(peakindex[min_index]-peakindex[dis_index])) ### determine the # of points for averaging
if num_set!=0:
num_ave=num_set
# print peakx
# print peakindex
print "num_ave",num_ave
if num_ave%2==0:
spanl=num_ave/2-1
spanr=num_ave/2
else:
spanl=num_ave/2
spanr=num_ave/2
x_ave=[]
y_ave=[]
for i in range(0,len(xd_intp)-spanr): ### plot the averaged curve
sumy=0.0
for j in range(i-spanl,i+spanr):
sumy=sumy+y_intp[j]
x_ave.append(xd_intp[i])
y_ave.append(sumy/float(num_ave))
dis_center_vac=100000.0
dis_vac_index=-999999
for i in range(len(xd_intp)-spanr): ### find the vacuum center
dis_vac=abs(xd_intp[i]-vac_center)
if dis_vac<dis_center_vac:
dis_center_vac=dis_vac
dis_vac_index=i
# print "DIS_VAC"
# print dis_center_vac,dis_vac_index,peakx[dis_vac_index]
# print y_ave
# plt.plot(xd_moved, vd0, 'o', xd_intp, y_intp, '-')
# plt.plot(peakx, peaky, 'o', xd_intp, y_intp, '-')
# xd,vd,vd0_intp = f_Smooth_Spline(xd0,vd0,width,ld,np)
# print "V(z=0 )= %12.4f "%y_intp[0]
# print "V(z=1/2)= %12.4f "%y_intp[np/2]
print "\n ========================== RESULTS =========================== \n"
print "All the peaks and their index (check the average range is correct!!!)"
peakx_novac=[]
peakindex_novac=[]
# for i in range(len(peakx)):
# if peakx[i]<=zmax+0.5 and peakx[i]>=zmin-0.5:
# peakx_novac.append(peakx)
for i in range(len(peakindex)):
if xd_intp[peakindex[i]]<=zmax+0.5 and xd_intp[peakindex[i]]>=zmin-0.5:
peakindex_novac.append(peakindex[i])
peakx_novac.append(xd_intp[peakindex[i]])
# print peakx
# print peakindex
# print peakx_novac
print '%16s %16s %16s' %('# of peak','correspond index','x coordinate')
for i in range(len(peakx_novac)):
print '%16d %16d %16.4f' %(i,peakindex_novac[i],peakx_novac[i])
print "\n"
print "current average peak and index:"
print peakindex[min_index]," ",xd_intp[peakindex[min_index]]
print peakindex[dis_index]," ",xd_intp[peakindex[dis_index]]
# print peakindex_novac
print "\n"
print "1. Averaged Electric Potential at the Center of the Slab:"
print y_ave[cent_index]
print "\n"
print "2. The Coordinate of the Center of the Slab:"
print x_ave[cent_index]
print "\n"
print "3. The Level of the Vacuum:"
print y_ave[dis_vac_index]
print "\n"
print "4. E_vac-E_ave:"
print y_ave[dis_vac_index]-y_ave[cent_index]
print "\n"
#print peakindex[dis_index],peakindex[min_index]
print "Smoothed data and Averaged data is written to ",fname+".dat"
ofile = open( fname+".dat",'w')
for i in range(len(xd_intp)):
ofile.write('%12.6f %12.6f \n' %(xd_intp[i],y_intp[i]))
ofile.write("\n")
for i in range(len(x_ave)):
ofile.write('%12.6f %12.6f \n' %(x_ave[i],y_ave[i]))
ofile.close()
savepath=os.getcwd()
if find_peak_flag==1 or num_set!=0:
plt.plot(peakx[dis_index], peaky[dis_index], 'o',peakx[min_index], peaky[min_index], 'o', xd_intp, y_intp, '-',x_ave,y_ave,'-',x_ave[cent_index],y_ave[cent_index],'o',x_ave[dis_vac_index],y_ave[dis_vac_index],'o')
if save==1:
plt.savefig(fname+'average.png')
else:
plt.show()
else:
plt.plot(peakx, peaky, 'o',xd_intp, y_intp, '-',x_ave,y_ave,'-')
if save==1:
plt.savefig(fname+'average.png')
else:
plt.show()
| [
"[email protected]"
] | |
3a2e785791e7462bb3a02e89809ac03e184ec239 | 188d5160cbc54d36d76110ad75478db951b525ac | /consumer/models.py | 1fb2eb82e6b5ee5d1a14be3358cf9295f3ccb39e | [] | no_license | adnankattekaden/hackathon | 660d71e11d00e6f8cce8c1b994ed2c8ab0a76bd1 | 329447d1a461a96a919d90be37dce1fb386f75db | refs/heads/master | 2023-02-27T08:58:32.903279 | 2021-01-25T07:00:29 | 2021-01-25T07:00:29 | 332,652,477 | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 268 | py | from django.db import models
from django.contrib.auth.models import User,auth
# Create your models here.
class UserDetails(models.Model):
user = models.OneToOneField(User, on_delete=models.CASCADE)
mobile_number = models.BigIntegerField(null=True,blank=True)
| [
"[email protected]"
] | |
e5c3a7732b89ca410005224d0909b9aae4783c99 | 385ce240ae264a1449079c21bd0c4cbe7c0fe3b8 | /GUI/rovan.py | a86c206a7737e0fefdd6181a8e91f57041743956 | [] | no_license | Maxcousin123/Python-workspace | 3ed60ae80d790b5c055bf47872ff0fdd39f4ec58 | 326b023190a12e082dcb35ae5ab8ef644c32159b | refs/heads/master | 2022-11-24T11:05:08.707003 | 2020-07-29T06:32:08 | 2020-07-29T06:32:08 | 283,415,557 | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 2,396 | py | import mysql.connector
x,y,z,v='color: ','size: ','price: ','Enter the code: '
mydb = mysql.connector.connect(
host='localhost',
user='maxcousin',
password='secret :)',
database='testdb' #to request a specific database
)
mycursor = mydb.cursor()
def newdata(b,c,d,e):
"""to insert the code and data"""
mycursor = mydb.cursor()
mycursor.execute('SELECT * FROM rovan WHERE code=(%s) ',(b,));
myresult = mycursor.fetchall()
if len(myresult) > 1:
print('code already exists')
else:
mycursor = mydb.cursor()
sqlFormula = "INSERT INTO rovan (code, size, price, color) VALUES (%s, %s, %s ,%s)"
rovan1 = (b, d, e, c)
mycursor.execute(sqlFormula, rovan1)
mydb.commit()
print('Done !')
def olddata(g):
'''to get the data related to code'''
try:
mycursor = mydb.cursor()
mycursor.execute("SELECT * FROM rovan WHERE code=(%s)",(g,));
myresult = mycursor.fetchall()
for result in myresult:
print(result)
except:
print('Error')
def editcode(f):
i = input('what will you edit ?: ')
if i == ('price'):
j = input("Enter the new price: ")
mycursor = mydb.cursor()
mycursor.execute("UPDATE rovan SET price=(%s) WHERE code=(%s)",(j,f));
mydb.commit()
print('Done')
elif i == ('size'):
k = input('Enter the sizes: ')
mycursor = mydb.cursor()
mycursor.execute("UPDATE rovan SET size=(%s) WHERE code=(%s)",(k,f));
mydb.commit()
print('Done')
elif i == ('color'):
l = ('Enter the colors: ')
mycursor = mydb.cursor()
mycursor.execute("UPDATE rovan SET color=(%s) WHERE code=(%s)",(l,f));
mydb.commit()
print('Done')
else:
print('Wrong command')
def delcode(h):
try:
mycursor.execute("DELETE FROM rovan WHERE code=(%s)",(h,));
mydb.commit()
print('Done !')
except:
print("Error")
a = input('What will you do ?: ')
if a == 'new code':
b = int(input(v))
c = input(x)
d = input(y)
e = input(z)
newdata(b,c,d,e)
elif a == 'edit code':
f = input(v)
editcode(f)
elif a == 'old code':
g = input(v)
olddata(g)
elif a == 'delete code':
h = input(v)
delcode(h)
else:
print('Wrong command')
| [
"[email protected]"
] | |
527b0be34e8054db78151a98fa3d6f2997ac2bb7 | 1f067fe2e85ccf2c11b6cbece41028273fa6dcd6 | /tests/test_user.py | c454a18cb82b75f46a56653019a313078cd507e1 | [
"MIT"
] | permissive | mireille1999/Pitches | f02d76396c69ed36dd4b019dda9e588c7a52b291 | 425d996404569b23f63fe5217867adc0ac2f3afc | refs/heads/main | 2023-03-31T08:56:52.953314 | 2021-03-31T10:45:13 | 2021-03-31T10:45:13 | 353,043,808 | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 839 | py | import unittest
from app.models import User
from os import urandom
class UserModelTest(unittest.TestCase):
"""
Test class to test the behaviour of the user class
"""
def setUp(self):
"""
Set up method that will run before every Test
"""
self.new_user = User(username='mireille', password = 'potatopeel420')
def test_password_setter(self):
self.assertTrue(self.new_user.password_hash is not None)
def test_no_access_password(self):
with self.assertRaises(AttributeError):
self.new_user.password
def test_password_verification(self):
self.assertTrue(self.new_user.verify_password('potatopeel420'))
def tearDown(self):
user = User.query.filter_by(username="cjjhvghxdf").first()
if user:
print("found")
| [
"[email protected]"
] | |
d2d1d9574f9531a0aa9afcb6fcad627939cbaf98 | b685c82024360588ccff3db9004c01ba8292fd62 | /tools/zoom/templates/apps/basic/index.py | b174f07c7cfe7786142add35e6ffd4f627d2621a | [
"MIT"
] | permissive | sean-hayes/zoom | 2a9662d568e9ca04f0bed99c63275af5680b7e9f | eda69c64ceb69dd87d2f7a5dfdaeea52ef65c581 | refs/heads/master | 2021-01-19T10:39:10.274324 | 2017-12-20T22:44:26 | 2017-12-20T22:44:26 | 87,887,573 | 1 | 1 | null | 2017-04-11T04:16:47 | 2017-04-11T04:16:47 | null | UTF-8 | Python | false | false | 467 | py | """
basic index
"""
import zoom
class MyView(zoom.View):
"""Index View"""
def index(self):
"""Index page"""
return zoom.page('Content goes here', title='Overview')
def about(self):
"""About page"""
content = '{app.description}'
return zoom.page(
content.format(app=zoom.system.request.app),
title='About {app.title}'.format(app=zoom.system.request.app)
)
view = MyView()
| [
"[email protected]"
] | |
f162dd80f73af34527b03764bb675bc9b75df772 | fab14fae2b494068aa793901d76464afb965df7e | /benchmarks/ltl_maxplus/f3/maxplus_20_41.py | 61563953b47ff60f51260ced94d97f2da6690995 | [
"MIT"
] | permissive | teodorov/F3 | 673f6f9ccc25acdfdecbfc180f439253474ba250 | c863215c318d7d5f258eb9be38c6962cf6863b52 | refs/heads/master | 2023-08-04T17:37:38.771863 | 2021-09-16T07:38:28 | 2021-09-16T07:38:28 | null | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 43,916 | py |
from collections import Iterable
from mathsat import msat_term, msat_env
from mathsat import msat_make_true, msat_make_false
from mathsat import msat_make_constant, msat_declare_function
from mathsat import msat_get_rational_type
from mathsat import msat_make_and as _msat_make_and
from mathsat import msat_make_or as _msat_make_or
from mathsat import msat_make_not
from mathsat import msat_make_leq, msat_make_equal
from mathsat import msat_make_number, msat_make_plus, msat_make_times
from ltl.ltl import TermMap, LTLEncoder
from utils import name_next
def msat_make_and(menv: msat_env, *args):
if len(args) == 0:
return msat_make_true(menv)
if len(args) == 1:
return args[0]
res = _msat_make_and(menv, args[0], args[1])
for arg in args[2:]:
res = _msat_make_and(menv, res, arg)
return res
def msat_make_or(menv: msat_env, *args):
if len(args) == 0:
return msat_make_false(menv)
if len(args) == 1:
return args[0]
res = _msat_make_or(menv, args[0], args[1])
for arg in args[2:]:
res = _msat_make_or(menv, res, arg)
return res
def msat_make_minus(menv: msat_env, arg0: msat_term, arg1: msat_term):
n_m1 = msat_make_number(menv, "-1")
arg1 = msat_make_times(menv, arg1, n_m1)
return msat_make_plus(menv, arg0, arg1)
def msat_make_lt(menv: msat_env, arg0: msat_term, arg1: msat_term):
geq = msat_make_geq(menv, arg0, arg1)
return msat_make_not(menv, geq)
def msat_make_geq(menv: msat_env, arg0: msat_term, arg1: msat_term):
return msat_make_leq(menv, arg1, arg0)
def msat_make_gt(menv: msat_env, arg0: msat_term, arg1: msat_term):
leq = msat_make_leq(menv, arg0, arg1)
return msat_make_not(menv, leq)
def msat_make_impl(menv: msat_env, arg0: msat_term, arg1: msat_term):
n_arg0 = msat_make_not(menv, arg0)
return msat_make_or(menv, n_arg0, arg1)
def check_ltl(menv: msat_env, enc: LTLEncoder) -> (Iterable, msat_term,
msat_term, msat_term):
assert menv
assert isinstance(menv, msat_env)
assert enc
assert isinstance(enc, LTLEncoder)
real_type = msat_get_rational_type(menv)
names = ["x_0", "x_1", "x_2", "x_3", "x_4", "x_5", "x_6", "x_7", "x_8", "x_9", "x_10", "x_11", "x_12", "x_13", "x_14", "x_15", "x_16", "x_17", "x_18", "x_19"]
xs = [msat_declare_function(menv, name, real_type)
for name in names]
xs = [msat_make_constant(menv, x) for x in xs]
x_xs = [msat_declare_function(menv, name_next(name), real_type)
for name in names]
x_xs = [msat_make_constant(menv, x_x) for x_x in x_xs]
curr2next = {x: x_x for x, x_x in zip(xs, x_xs)}
n_10_0 = msat_make_number(menv, "10.0")
n_11_0 = msat_make_number(menv, "11.0")
n_12_0 = msat_make_number(menv, "12.0")
n_13_0 = msat_make_number(menv, "13.0")
n_14_0 = msat_make_number(menv, "14.0")
n_15_0 = msat_make_number(menv, "15.0")
n_16_0 = msat_make_number(menv, "16.0")
n_17_0 = msat_make_number(menv, "17.0")
n_18_0 = msat_make_number(menv, "18.0")
n_19_0 = msat_make_number(menv, "19.0")
n_1_0 = msat_make_number(menv, "1.0")
n_20_0 = msat_make_number(menv, "20.0")
n_2_0 = msat_make_number(menv, "2.0")
n_3_0 = msat_make_number(menv, "3.0")
n_4_0 = msat_make_number(menv, "4.0")
n_5_0 = msat_make_number(menv, "5.0")
n_6_0 = msat_make_number(menv, "6.0")
n_7_0 = msat_make_number(menv, "7.0")
n_8_0 = msat_make_number(menv, "8.0")
n_9_0 = msat_make_number(menv, "9.0")
init = msat_make_true(menv)
trans = msat_make_true(menv)
# transitions
expr0 = msat_make_plus(menv, xs[0], n_16_0)
expr1 = msat_make_plus(menv, xs[1], n_2_0)
expr2 = msat_make_plus(menv, xs[3], n_12_0)
expr3 = msat_make_plus(menv, xs[4], n_11_0)
expr4 = msat_make_plus(menv, xs[6], n_15_0)
expr5 = msat_make_plus(menv, xs[7], n_8_0)
expr6 = msat_make_plus(menv, xs[9], n_13_0)
expr7 = msat_make_plus(menv, xs[10], n_8_0)
expr8 = msat_make_plus(menv, xs[12], n_1_0)
expr9 = msat_make_plus(menv, xs[18], n_17_0)
_t = msat_make_and(menv,
msat_make_geq(menv, x_xs[0], expr0),
msat_make_geq(menv, x_xs[0], expr1),
msat_make_geq(menv, x_xs[0], expr2),
msat_make_geq(menv, x_xs[0], expr3),
msat_make_geq(menv, x_xs[0], expr4),
msat_make_geq(menv, x_xs[0], expr5),
msat_make_geq(menv, x_xs[0], expr6),
msat_make_geq(menv, x_xs[0], expr7),
msat_make_geq(menv, x_xs[0], expr8),
msat_make_geq(menv, x_xs[0], expr9),)
_t = msat_make_and(menv, _t,
msat_make_or(menv,
msat_make_equal(menv, x_xs[0], expr0),
msat_make_equal(menv, x_xs[0], expr1),
msat_make_equal(menv, x_xs[0], expr2),
msat_make_equal(menv, x_xs[0], expr3),
msat_make_equal(menv, x_xs[0], expr4),
msat_make_equal(menv, x_xs[0], expr5),
msat_make_equal(menv, x_xs[0], expr6),
msat_make_equal(menv, x_xs[0], expr7),
msat_make_equal(menv, x_xs[0], expr8),
msat_make_equal(menv, x_xs[0], expr9),))
trans = msat_make_and(menv, trans, _t)
expr0 = msat_make_plus(menv, xs[1], n_4_0)
expr1 = msat_make_plus(menv, xs[2], n_8_0)
expr2 = msat_make_plus(menv, xs[5], n_16_0)
expr3 = msat_make_plus(menv, xs[7], n_8_0)
expr4 = msat_make_plus(menv, xs[10], n_15_0)
expr5 = msat_make_plus(menv, xs[14], n_5_0)
expr6 = msat_make_plus(menv, xs[15], n_6_0)
expr7 = msat_make_plus(menv, xs[16], n_14_0)
expr8 = msat_make_plus(menv, xs[17], n_6_0)
expr9 = msat_make_plus(menv, xs[19], n_1_0)
_t = msat_make_and(menv,
msat_make_geq(menv, x_xs[1], expr0),
msat_make_geq(menv, x_xs[1], expr1),
msat_make_geq(menv, x_xs[1], expr2),
msat_make_geq(menv, x_xs[1], expr3),
msat_make_geq(menv, x_xs[1], expr4),
msat_make_geq(menv, x_xs[1], expr5),
msat_make_geq(menv, x_xs[1], expr6),
msat_make_geq(menv, x_xs[1], expr7),
msat_make_geq(menv, x_xs[1], expr8),
msat_make_geq(menv, x_xs[1], expr9),)
_t = msat_make_and(menv, _t,
msat_make_or(menv,
msat_make_equal(menv, x_xs[1], expr0),
msat_make_equal(menv, x_xs[1], expr1),
msat_make_equal(menv, x_xs[1], expr2),
msat_make_equal(menv, x_xs[1], expr3),
msat_make_equal(menv, x_xs[1], expr4),
msat_make_equal(menv, x_xs[1], expr5),
msat_make_equal(menv, x_xs[1], expr6),
msat_make_equal(menv, x_xs[1], expr7),
msat_make_equal(menv, x_xs[1], expr8),
msat_make_equal(menv, x_xs[1], expr9),))
trans = msat_make_and(menv, trans, _t)
expr0 = msat_make_plus(menv, xs[0], n_13_0)
expr1 = msat_make_plus(menv, xs[1], n_4_0)
expr2 = msat_make_plus(menv, xs[3], n_4_0)
expr3 = msat_make_plus(menv, xs[4], n_11_0)
expr4 = msat_make_plus(menv, xs[5], n_1_0)
expr5 = msat_make_plus(menv, xs[14], n_10_0)
expr6 = msat_make_plus(menv, xs[15], n_2_0)
expr7 = msat_make_plus(menv, xs[16], n_1_0)
expr8 = msat_make_plus(menv, xs[17], n_6_0)
expr9 = msat_make_plus(menv, xs[18], n_10_0)
_t = msat_make_and(menv,
msat_make_geq(menv, x_xs[2], expr0),
msat_make_geq(menv, x_xs[2], expr1),
msat_make_geq(menv, x_xs[2], expr2),
msat_make_geq(menv, x_xs[2], expr3),
msat_make_geq(menv, x_xs[2], expr4),
msat_make_geq(menv, x_xs[2], expr5),
msat_make_geq(menv, x_xs[2], expr6),
msat_make_geq(menv, x_xs[2], expr7),
msat_make_geq(menv, x_xs[2], expr8),
msat_make_geq(menv, x_xs[2], expr9),)
_t = msat_make_and(menv, _t,
msat_make_or(menv,
msat_make_equal(menv, x_xs[2], expr0),
msat_make_equal(menv, x_xs[2], expr1),
msat_make_equal(menv, x_xs[2], expr2),
msat_make_equal(menv, x_xs[2], expr3),
msat_make_equal(menv, x_xs[2], expr4),
msat_make_equal(menv, x_xs[2], expr5),
msat_make_equal(menv, x_xs[2], expr6),
msat_make_equal(menv, x_xs[2], expr7),
msat_make_equal(menv, x_xs[2], expr8),
msat_make_equal(menv, x_xs[2], expr9),))
trans = msat_make_and(menv, trans, _t)
expr0 = msat_make_plus(menv, xs[0], n_12_0)
expr1 = msat_make_plus(menv, xs[3], n_9_0)
expr2 = msat_make_plus(menv, xs[4], n_4_0)
expr3 = msat_make_plus(menv, xs[6], n_14_0)
expr4 = msat_make_plus(menv, xs[8], n_10_0)
expr5 = msat_make_plus(menv, xs[10], n_6_0)
expr6 = msat_make_plus(menv, xs[14], n_6_0)
expr7 = msat_make_plus(menv, xs[15], n_11_0)
expr8 = msat_make_plus(menv, xs[17], n_15_0)
expr9 = msat_make_plus(menv, xs[19], n_17_0)
_t = msat_make_and(menv,
msat_make_geq(menv, x_xs[3], expr0),
msat_make_geq(menv, x_xs[3], expr1),
msat_make_geq(menv, x_xs[3], expr2),
msat_make_geq(menv, x_xs[3], expr3),
msat_make_geq(menv, x_xs[3], expr4),
msat_make_geq(menv, x_xs[3], expr5),
msat_make_geq(menv, x_xs[3], expr6),
msat_make_geq(menv, x_xs[3], expr7),
msat_make_geq(menv, x_xs[3], expr8),
msat_make_geq(menv, x_xs[3], expr9),)
_t = msat_make_and(menv, _t,
msat_make_or(menv,
msat_make_equal(menv, x_xs[3], expr0),
msat_make_equal(menv, x_xs[3], expr1),
msat_make_equal(menv, x_xs[3], expr2),
msat_make_equal(menv, x_xs[3], expr3),
msat_make_equal(menv, x_xs[3], expr4),
msat_make_equal(menv, x_xs[3], expr5),
msat_make_equal(menv, x_xs[3], expr6),
msat_make_equal(menv, x_xs[3], expr7),
msat_make_equal(menv, x_xs[3], expr8),
msat_make_equal(menv, x_xs[3], expr9),))
trans = msat_make_and(menv, trans, _t)
expr0 = msat_make_plus(menv, xs[3], n_5_0)
expr1 = msat_make_plus(menv, xs[5], n_11_0)
expr2 = msat_make_plus(menv, xs[6], n_18_0)
expr3 = msat_make_plus(menv, xs[8], n_4_0)
expr4 = msat_make_plus(menv, xs[10], n_14_0)
expr5 = msat_make_plus(menv, xs[11], n_20_0)
expr6 = msat_make_plus(menv, xs[12], n_7_0)
expr7 = msat_make_plus(menv, xs[14], n_19_0)
expr8 = msat_make_plus(menv, xs[15], n_12_0)
expr9 = msat_make_plus(menv, xs[19], n_1_0)
_t = msat_make_and(menv,
msat_make_geq(menv, x_xs[4], expr0),
msat_make_geq(menv, x_xs[4], expr1),
msat_make_geq(menv, x_xs[4], expr2),
msat_make_geq(menv, x_xs[4], expr3),
msat_make_geq(menv, x_xs[4], expr4),
msat_make_geq(menv, x_xs[4], expr5),
msat_make_geq(menv, x_xs[4], expr6),
msat_make_geq(menv, x_xs[4], expr7),
msat_make_geq(menv, x_xs[4], expr8),
msat_make_geq(menv, x_xs[4], expr9),)
_t = msat_make_and(menv, _t,
msat_make_or(menv,
msat_make_equal(menv, x_xs[4], expr0),
msat_make_equal(menv, x_xs[4], expr1),
msat_make_equal(menv, x_xs[4], expr2),
msat_make_equal(menv, x_xs[4], expr3),
msat_make_equal(menv, x_xs[4], expr4),
msat_make_equal(menv, x_xs[4], expr5),
msat_make_equal(menv, x_xs[4], expr6),
msat_make_equal(menv, x_xs[4], expr7),
msat_make_equal(menv, x_xs[4], expr8),
msat_make_equal(menv, x_xs[4], expr9),))
trans = msat_make_and(menv, trans, _t)
expr0 = msat_make_plus(menv, xs[0], n_20_0)
expr1 = msat_make_plus(menv, xs[1], n_11_0)
expr2 = msat_make_plus(menv, xs[2], n_17_0)
expr3 = msat_make_plus(menv, xs[3], n_5_0)
expr4 = msat_make_plus(menv, xs[9], n_1_0)
expr5 = msat_make_plus(menv, xs[11], n_13_0)
expr6 = msat_make_plus(menv, xs[12], n_15_0)
expr7 = msat_make_plus(menv, xs[13], n_20_0)
expr8 = msat_make_plus(menv, xs[18], n_19_0)
expr9 = msat_make_plus(menv, xs[19], n_12_0)
_t = msat_make_and(menv,
msat_make_geq(menv, x_xs[5], expr0),
msat_make_geq(menv, x_xs[5], expr1),
msat_make_geq(menv, x_xs[5], expr2),
msat_make_geq(menv, x_xs[5], expr3),
msat_make_geq(menv, x_xs[5], expr4),
msat_make_geq(menv, x_xs[5], expr5),
msat_make_geq(menv, x_xs[5], expr6),
msat_make_geq(menv, x_xs[5], expr7),
msat_make_geq(menv, x_xs[5], expr8),
msat_make_geq(menv, x_xs[5], expr9),)
_t = msat_make_and(menv, _t,
msat_make_or(menv,
msat_make_equal(menv, x_xs[5], expr0),
msat_make_equal(menv, x_xs[5], expr1),
msat_make_equal(menv, x_xs[5], expr2),
msat_make_equal(menv, x_xs[5], expr3),
msat_make_equal(menv, x_xs[5], expr4),
msat_make_equal(menv, x_xs[5], expr5),
msat_make_equal(menv, x_xs[5], expr6),
msat_make_equal(menv, x_xs[5], expr7),
msat_make_equal(menv, x_xs[5], expr8),
msat_make_equal(menv, x_xs[5], expr9),))
trans = msat_make_and(menv, trans, _t)
expr0 = msat_make_plus(menv, xs[0], n_2_0)
expr1 = msat_make_plus(menv, xs[1], n_13_0)
expr2 = msat_make_plus(menv, xs[4], n_12_0)
expr3 = msat_make_plus(menv, xs[6], n_3_0)
expr4 = msat_make_plus(menv, xs[11], n_18_0)
expr5 = msat_make_plus(menv, xs[12], n_16_0)
expr6 = msat_make_plus(menv, xs[13], n_11_0)
expr7 = msat_make_plus(menv, xs[14], n_3_0)
expr8 = msat_make_plus(menv, xs[16], n_16_0)
expr9 = msat_make_plus(menv, xs[19], n_17_0)
_t = msat_make_and(menv,
msat_make_geq(menv, x_xs[6], expr0),
msat_make_geq(menv, x_xs[6], expr1),
msat_make_geq(menv, x_xs[6], expr2),
msat_make_geq(menv, x_xs[6], expr3),
msat_make_geq(menv, x_xs[6], expr4),
msat_make_geq(menv, x_xs[6], expr5),
msat_make_geq(menv, x_xs[6], expr6),
msat_make_geq(menv, x_xs[6], expr7),
msat_make_geq(menv, x_xs[6], expr8),
msat_make_geq(menv, x_xs[6], expr9),)
_t = msat_make_and(menv, _t,
msat_make_or(menv,
msat_make_equal(menv, x_xs[6], expr0),
msat_make_equal(menv, x_xs[6], expr1),
msat_make_equal(menv, x_xs[6], expr2),
msat_make_equal(menv, x_xs[6], expr3),
msat_make_equal(menv, x_xs[6], expr4),
msat_make_equal(menv, x_xs[6], expr5),
msat_make_equal(menv, x_xs[6], expr6),
msat_make_equal(menv, x_xs[6], expr7),
msat_make_equal(menv, x_xs[6], expr8),
msat_make_equal(menv, x_xs[6], expr9),))
trans = msat_make_and(menv, trans, _t)
expr0 = msat_make_plus(menv, xs[1], n_11_0)
expr1 = msat_make_plus(menv, xs[2], n_14_0)
expr2 = msat_make_plus(menv, xs[4], n_20_0)
expr3 = msat_make_plus(menv, xs[5], n_13_0)
expr4 = msat_make_plus(menv, xs[6], n_10_0)
expr5 = msat_make_plus(menv, xs[9], n_7_0)
expr6 = msat_make_plus(menv, xs[10], n_12_0)
expr7 = msat_make_plus(menv, xs[12], n_8_0)
expr8 = msat_make_plus(menv, xs[13], n_17_0)
expr9 = msat_make_plus(menv, xs[17], n_10_0)
_t = msat_make_and(menv,
msat_make_geq(menv, x_xs[7], expr0),
msat_make_geq(menv, x_xs[7], expr1),
msat_make_geq(menv, x_xs[7], expr2),
msat_make_geq(menv, x_xs[7], expr3),
msat_make_geq(menv, x_xs[7], expr4),
msat_make_geq(menv, x_xs[7], expr5),
msat_make_geq(menv, x_xs[7], expr6),
msat_make_geq(menv, x_xs[7], expr7),
msat_make_geq(menv, x_xs[7], expr8),
msat_make_geq(menv, x_xs[7], expr9),)
_t = msat_make_and(menv, _t,
msat_make_or(menv,
msat_make_equal(menv, x_xs[7], expr0),
msat_make_equal(menv, x_xs[7], expr1),
msat_make_equal(menv, x_xs[7], expr2),
msat_make_equal(menv, x_xs[7], expr3),
msat_make_equal(menv, x_xs[7], expr4),
msat_make_equal(menv, x_xs[7], expr5),
msat_make_equal(menv, x_xs[7], expr6),
msat_make_equal(menv, x_xs[7], expr7),
msat_make_equal(menv, x_xs[7], expr8),
msat_make_equal(menv, x_xs[7], expr9),))
trans = msat_make_and(menv, trans, _t)
expr0 = msat_make_plus(menv, xs[0], n_4_0)
expr1 = msat_make_plus(menv, xs[1], n_15_0)
expr2 = msat_make_plus(menv, xs[5], n_9_0)
expr3 = msat_make_plus(menv, xs[8], n_4_0)
expr4 = msat_make_plus(menv, xs[10], n_13_0)
expr5 = msat_make_plus(menv, xs[12], n_8_0)
expr6 = msat_make_plus(menv, xs[13], n_5_0)
expr7 = msat_make_plus(menv, xs[17], n_1_0)
expr8 = msat_make_plus(menv, xs[18], n_12_0)
expr9 = msat_make_plus(menv, xs[19], n_6_0)
_t = msat_make_and(menv,
msat_make_geq(menv, x_xs[8], expr0),
msat_make_geq(menv, x_xs[8], expr1),
msat_make_geq(menv, x_xs[8], expr2),
msat_make_geq(menv, x_xs[8], expr3),
msat_make_geq(menv, x_xs[8], expr4),
msat_make_geq(menv, x_xs[8], expr5),
msat_make_geq(menv, x_xs[8], expr6),
msat_make_geq(menv, x_xs[8], expr7),
msat_make_geq(menv, x_xs[8], expr8),
msat_make_geq(menv, x_xs[8], expr9),)
_t = msat_make_and(menv, _t,
msat_make_or(menv,
msat_make_equal(menv, x_xs[8], expr0),
msat_make_equal(menv, x_xs[8], expr1),
msat_make_equal(menv, x_xs[8], expr2),
msat_make_equal(menv, x_xs[8], expr3),
msat_make_equal(menv, x_xs[8], expr4),
msat_make_equal(menv, x_xs[8], expr5),
msat_make_equal(menv, x_xs[8], expr6),
msat_make_equal(menv, x_xs[8], expr7),
msat_make_equal(menv, x_xs[8], expr8),
msat_make_equal(menv, x_xs[8], expr9),))
trans = msat_make_and(menv, trans, _t)
expr0 = msat_make_plus(menv, xs[2], n_8_0)
expr1 = msat_make_plus(menv, xs[3], n_9_0)
expr2 = msat_make_plus(menv, xs[4], n_11_0)
expr3 = msat_make_plus(menv, xs[5], n_20_0)
expr4 = msat_make_plus(menv, xs[7], n_3_0)
expr5 = msat_make_plus(menv, xs[12], n_1_0)
expr6 = msat_make_plus(menv, xs[13], n_14_0)
expr7 = msat_make_plus(menv, xs[14], n_16_0)
expr8 = msat_make_plus(menv, xs[16], n_1_0)
expr9 = msat_make_plus(menv, xs[18], n_9_0)
_t = msat_make_and(menv,
msat_make_geq(menv, x_xs[9], expr0),
msat_make_geq(menv, x_xs[9], expr1),
msat_make_geq(menv, x_xs[9], expr2),
msat_make_geq(menv, x_xs[9], expr3),
msat_make_geq(menv, x_xs[9], expr4),
msat_make_geq(menv, x_xs[9], expr5),
msat_make_geq(menv, x_xs[9], expr6),
msat_make_geq(menv, x_xs[9], expr7),
msat_make_geq(menv, x_xs[9], expr8),
msat_make_geq(menv, x_xs[9], expr9),)
_t = msat_make_and(menv, _t,
msat_make_or(menv,
msat_make_equal(menv, x_xs[9], expr0),
msat_make_equal(menv, x_xs[9], expr1),
msat_make_equal(menv, x_xs[9], expr2),
msat_make_equal(menv, x_xs[9], expr3),
msat_make_equal(menv, x_xs[9], expr4),
msat_make_equal(menv, x_xs[9], expr5),
msat_make_equal(menv, x_xs[9], expr6),
msat_make_equal(menv, x_xs[9], expr7),
msat_make_equal(menv, x_xs[9], expr8),
msat_make_equal(menv, x_xs[9], expr9),))
trans = msat_make_and(menv, trans, _t)
expr0 = msat_make_plus(menv, xs[0], n_17_0)
expr1 = msat_make_plus(menv, xs[4], n_8_0)
expr2 = msat_make_plus(menv, xs[6], n_6_0)
expr3 = msat_make_plus(menv, xs[8], n_13_0)
expr4 = msat_make_plus(menv, xs[10], n_19_0)
expr5 = msat_make_plus(menv, xs[13], n_18_0)
expr6 = msat_make_plus(menv, xs[14], n_20_0)
expr7 = msat_make_plus(menv, xs[17], n_15_0)
expr8 = msat_make_plus(menv, xs[18], n_15_0)
expr9 = msat_make_plus(menv, xs[19], n_2_0)
_t = msat_make_and(menv,
msat_make_geq(menv, x_xs[10], expr0),
msat_make_geq(menv, x_xs[10], expr1),
msat_make_geq(menv, x_xs[10], expr2),
msat_make_geq(menv, x_xs[10], expr3),
msat_make_geq(menv, x_xs[10], expr4),
msat_make_geq(menv, x_xs[10], expr5),
msat_make_geq(menv, x_xs[10], expr6),
msat_make_geq(menv, x_xs[10], expr7),
msat_make_geq(menv, x_xs[10], expr8),
msat_make_geq(menv, x_xs[10], expr9),)
_t = msat_make_and(menv, _t,
msat_make_or(menv,
msat_make_equal(menv, x_xs[10], expr0),
msat_make_equal(menv, x_xs[10], expr1),
msat_make_equal(menv, x_xs[10], expr2),
msat_make_equal(menv, x_xs[10], expr3),
msat_make_equal(menv, x_xs[10], expr4),
msat_make_equal(menv, x_xs[10], expr5),
msat_make_equal(menv, x_xs[10], expr6),
msat_make_equal(menv, x_xs[10], expr7),
msat_make_equal(menv, x_xs[10], expr8),
msat_make_equal(menv, x_xs[10], expr9),))
trans = msat_make_and(menv, trans, _t)
expr0 = msat_make_plus(menv, xs[1], n_5_0)
expr1 = msat_make_plus(menv, xs[5], n_10_0)
expr2 = msat_make_plus(menv, xs[6], n_17_0)
expr3 = msat_make_plus(menv, xs[8], n_12_0)
expr4 = msat_make_plus(menv, xs[9], n_20_0)
expr5 = msat_make_plus(menv, xs[10], n_2_0)
expr6 = msat_make_plus(menv, xs[13], n_2_0)
expr7 = msat_make_plus(menv, xs[15], n_11_0)
expr8 = msat_make_plus(menv, xs[17], n_9_0)
expr9 = msat_make_plus(menv, xs[18], n_5_0)
_t = msat_make_and(menv,
msat_make_geq(menv, x_xs[11], expr0),
msat_make_geq(menv, x_xs[11], expr1),
msat_make_geq(menv, x_xs[11], expr2),
msat_make_geq(menv, x_xs[11], expr3),
msat_make_geq(menv, x_xs[11], expr4),
msat_make_geq(menv, x_xs[11], expr5),
msat_make_geq(menv, x_xs[11], expr6),
msat_make_geq(menv, x_xs[11], expr7),
msat_make_geq(menv, x_xs[11], expr8),
msat_make_geq(menv, x_xs[11], expr9),)
_t = msat_make_and(menv, _t,
msat_make_or(menv,
msat_make_equal(menv, x_xs[11], expr0),
msat_make_equal(menv, x_xs[11], expr1),
msat_make_equal(menv, x_xs[11], expr2),
msat_make_equal(menv, x_xs[11], expr3),
msat_make_equal(menv, x_xs[11], expr4),
msat_make_equal(menv, x_xs[11], expr5),
msat_make_equal(menv, x_xs[11], expr6),
msat_make_equal(menv, x_xs[11], expr7),
msat_make_equal(menv, x_xs[11], expr8),
msat_make_equal(menv, x_xs[11], expr9),))
trans = msat_make_and(menv, trans, _t)
expr0 = msat_make_plus(menv, xs[3], n_17_0)
expr1 = msat_make_plus(menv, xs[4], n_11_0)
expr2 = msat_make_plus(menv, xs[6], n_7_0)
expr3 = msat_make_plus(menv, xs[7], n_8_0)
expr4 = msat_make_plus(menv, xs[8], n_4_0)
expr5 = msat_make_plus(menv, xs[9], n_4_0)
expr6 = msat_make_plus(menv, xs[11], n_13_0)
expr7 = msat_make_plus(menv, xs[15], n_12_0)
expr8 = msat_make_plus(menv, xs[17], n_1_0)
expr9 = msat_make_plus(menv, xs[19], n_20_0)
_t = msat_make_and(menv,
msat_make_geq(menv, x_xs[12], expr0),
msat_make_geq(menv, x_xs[12], expr1),
msat_make_geq(menv, x_xs[12], expr2),
msat_make_geq(menv, x_xs[12], expr3),
msat_make_geq(menv, x_xs[12], expr4),
msat_make_geq(menv, x_xs[12], expr5),
msat_make_geq(menv, x_xs[12], expr6),
msat_make_geq(menv, x_xs[12], expr7),
msat_make_geq(menv, x_xs[12], expr8),
msat_make_geq(menv, x_xs[12], expr9),)
_t = msat_make_and(menv, _t,
msat_make_or(menv,
msat_make_equal(menv, x_xs[12], expr0),
msat_make_equal(menv, x_xs[12], expr1),
msat_make_equal(menv, x_xs[12], expr2),
msat_make_equal(menv, x_xs[12], expr3),
msat_make_equal(menv, x_xs[12], expr4),
msat_make_equal(menv, x_xs[12], expr5),
msat_make_equal(menv, x_xs[12], expr6),
msat_make_equal(menv, x_xs[12], expr7),
msat_make_equal(menv, x_xs[12], expr8),
msat_make_equal(menv, x_xs[12], expr9),))
trans = msat_make_and(menv, trans, _t)
expr0 = msat_make_plus(menv, xs[3], n_19_0)
expr1 = msat_make_plus(menv, xs[4], n_12_0)
expr2 = msat_make_plus(menv, xs[6], n_18_0)
expr3 = msat_make_plus(menv, xs[7], n_1_0)
expr4 = msat_make_plus(menv, xs[11], n_3_0)
expr5 = msat_make_plus(menv, xs[12], n_9_0)
expr6 = msat_make_plus(menv, xs[14], n_2_0)
expr7 = msat_make_plus(menv, xs[15], n_20_0)
expr8 = msat_make_plus(menv, xs[16], n_17_0)
expr9 = msat_make_plus(menv, xs[19], n_1_0)
_t = msat_make_and(menv,
msat_make_geq(menv, x_xs[13], expr0),
msat_make_geq(menv, x_xs[13], expr1),
msat_make_geq(menv, x_xs[13], expr2),
msat_make_geq(menv, x_xs[13], expr3),
msat_make_geq(menv, x_xs[13], expr4),
msat_make_geq(menv, x_xs[13], expr5),
msat_make_geq(menv, x_xs[13], expr6),
msat_make_geq(menv, x_xs[13], expr7),
msat_make_geq(menv, x_xs[13], expr8),
msat_make_geq(menv, x_xs[13], expr9),)
_t = msat_make_and(menv, _t,
msat_make_or(menv,
msat_make_equal(menv, x_xs[13], expr0),
msat_make_equal(menv, x_xs[13], expr1),
msat_make_equal(menv, x_xs[13], expr2),
msat_make_equal(menv, x_xs[13], expr3),
msat_make_equal(menv, x_xs[13], expr4),
msat_make_equal(menv, x_xs[13], expr5),
msat_make_equal(menv, x_xs[13], expr6),
msat_make_equal(menv, x_xs[13], expr7),
msat_make_equal(menv, x_xs[13], expr8),
msat_make_equal(menv, x_xs[13], expr9),))
trans = msat_make_and(menv, trans, _t)
expr0 = msat_make_plus(menv, xs[0], n_11_0)
expr1 = msat_make_plus(menv, xs[2], n_9_0)
expr2 = msat_make_plus(menv, xs[3], n_4_0)
expr3 = msat_make_plus(menv, xs[6], n_10_0)
expr4 = msat_make_plus(menv, xs[7], n_17_0)
expr5 = msat_make_plus(menv, xs[9], n_1_0)
expr6 = msat_make_plus(menv, xs[11], n_6_0)
expr7 = msat_make_plus(menv, xs[13], n_10_0)
expr8 = msat_make_plus(menv, xs[15], n_6_0)
expr9 = msat_make_plus(menv, xs[18], n_7_0)
_t = msat_make_and(menv,
msat_make_geq(menv, x_xs[14], expr0),
msat_make_geq(menv, x_xs[14], expr1),
msat_make_geq(menv, x_xs[14], expr2),
msat_make_geq(menv, x_xs[14], expr3),
msat_make_geq(menv, x_xs[14], expr4),
msat_make_geq(menv, x_xs[14], expr5),
msat_make_geq(menv, x_xs[14], expr6),
msat_make_geq(menv, x_xs[14], expr7),
msat_make_geq(menv, x_xs[14], expr8),
msat_make_geq(menv, x_xs[14], expr9),)
_t = msat_make_and(menv, _t,
msat_make_or(menv,
msat_make_equal(menv, x_xs[14], expr0),
msat_make_equal(menv, x_xs[14], expr1),
msat_make_equal(menv, x_xs[14], expr2),
msat_make_equal(menv, x_xs[14], expr3),
msat_make_equal(menv, x_xs[14], expr4),
msat_make_equal(menv, x_xs[14], expr5),
msat_make_equal(menv, x_xs[14], expr6),
msat_make_equal(menv, x_xs[14], expr7),
msat_make_equal(menv, x_xs[14], expr8),
msat_make_equal(menv, x_xs[14], expr9),))
trans = msat_make_and(menv, trans, _t)
expr0 = msat_make_plus(menv, xs[1], n_6_0)
expr1 = msat_make_plus(menv, xs[3], n_13_0)
expr2 = msat_make_plus(menv, xs[5], n_12_0)
expr3 = msat_make_plus(menv, xs[6], n_19_0)
expr4 = msat_make_plus(menv, xs[10], n_18_0)
expr5 = msat_make_plus(menv, xs[15], n_4_0)
expr6 = msat_make_plus(menv, xs[16], n_18_0)
expr7 = msat_make_plus(menv, xs[17], n_2_0)
expr8 = msat_make_plus(menv, xs[18], n_10_0)
expr9 = msat_make_plus(menv, xs[19], n_8_0)
_t = msat_make_and(menv,
msat_make_geq(menv, x_xs[15], expr0),
msat_make_geq(menv, x_xs[15], expr1),
msat_make_geq(menv, x_xs[15], expr2),
msat_make_geq(menv, x_xs[15], expr3),
msat_make_geq(menv, x_xs[15], expr4),
msat_make_geq(menv, x_xs[15], expr5),
msat_make_geq(menv, x_xs[15], expr6),
msat_make_geq(menv, x_xs[15], expr7),
msat_make_geq(menv, x_xs[15], expr8),
msat_make_geq(menv, x_xs[15], expr9),)
_t = msat_make_and(menv, _t,
msat_make_or(menv,
msat_make_equal(menv, x_xs[15], expr0),
msat_make_equal(menv, x_xs[15], expr1),
msat_make_equal(menv, x_xs[15], expr2),
msat_make_equal(menv, x_xs[15], expr3),
msat_make_equal(menv, x_xs[15], expr4),
msat_make_equal(menv, x_xs[15], expr5),
msat_make_equal(menv, x_xs[15], expr6),
msat_make_equal(menv, x_xs[15], expr7),
msat_make_equal(menv, x_xs[15], expr8),
msat_make_equal(menv, x_xs[15], expr9),))
trans = msat_make_and(menv, trans, _t)
expr0 = msat_make_plus(menv, xs[1], n_11_0)
expr1 = msat_make_plus(menv, xs[2], n_13_0)
expr2 = msat_make_plus(menv, xs[3], n_16_0)
expr3 = msat_make_plus(menv, xs[5], n_9_0)
expr4 = msat_make_plus(menv, xs[6], n_4_0)
expr5 = msat_make_plus(menv, xs[9], n_3_0)
expr6 = msat_make_plus(menv, xs[14], n_3_0)
expr7 = msat_make_plus(menv, xs[17], n_3_0)
expr8 = msat_make_plus(menv, xs[18], n_13_0)
expr9 = msat_make_plus(menv, xs[19], n_2_0)
_t = msat_make_and(menv,
msat_make_geq(menv, x_xs[16], expr0),
msat_make_geq(menv, x_xs[16], expr1),
msat_make_geq(menv, x_xs[16], expr2),
msat_make_geq(menv, x_xs[16], expr3),
msat_make_geq(menv, x_xs[16], expr4),
msat_make_geq(menv, x_xs[16], expr5),
msat_make_geq(menv, x_xs[16], expr6),
msat_make_geq(menv, x_xs[16], expr7),
msat_make_geq(menv, x_xs[16], expr8),
msat_make_geq(menv, x_xs[16], expr9),)
_t = msat_make_and(menv, _t,
msat_make_or(menv,
msat_make_equal(menv, x_xs[16], expr0),
msat_make_equal(menv, x_xs[16], expr1),
msat_make_equal(menv, x_xs[16], expr2),
msat_make_equal(menv, x_xs[16], expr3),
msat_make_equal(menv, x_xs[16], expr4),
msat_make_equal(menv, x_xs[16], expr5),
msat_make_equal(menv, x_xs[16], expr6),
msat_make_equal(menv, x_xs[16], expr7),
msat_make_equal(menv, x_xs[16], expr8),
msat_make_equal(menv, x_xs[16], expr9),))
trans = msat_make_and(menv, trans, _t)
expr0 = msat_make_plus(menv, xs[0], n_7_0)
expr1 = msat_make_plus(menv, xs[3], n_19_0)
expr2 = msat_make_plus(menv, xs[5], n_12_0)
expr3 = msat_make_plus(menv, xs[6], n_16_0)
expr4 = msat_make_plus(menv, xs[9], n_17_0)
expr5 = msat_make_plus(menv, xs[11], n_4_0)
expr6 = msat_make_plus(menv, xs[13], n_19_0)
expr7 = msat_make_plus(menv, xs[14], n_8_0)
expr8 = msat_make_plus(menv, xs[17], n_10_0)
expr9 = msat_make_plus(menv, xs[19], n_5_0)
_t = msat_make_and(menv,
msat_make_geq(menv, x_xs[17], expr0),
msat_make_geq(menv, x_xs[17], expr1),
msat_make_geq(menv, x_xs[17], expr2),
msat_make_geq(menv, x_xs[17], expr3),
msat_make_geq(menv, x_xs[17], expr4),
msat_make_geq(menv, x_xs[17], expr5),
msat_make_geq(menv, x_xs[17], expr6),
msat_make_geq(menv, x_xs[17], expr7),
msat_make_geq(menv, x_xs[17], expr8),
msat_make_geq(menv, x_xs[17], expr9),)
_t = msat_make_and(menv, _t,
msat_make_or(menv,
msat_make_equal(menv, x_xs[17], expr0),
msat_make_equal(menv, x_xs[17], expr1),
msat_make_equal(menv, x_xs[17], expr2),
msat_make_equal(menv, x_xs[17], expr3),
msat_make_equal(menv, x_xs[17], expr4),
msat_make_equal(menv, x_xs[17], expr5),
msat_make_equal(menv, x_xs[17], expr6),
msat_make_equal(menv, x_xs[17], expr7),
msat_make_equal(menv, x_xs[17], expr8),
msat_make_equal(menv, x_xs[17], expr9),))
trans = msat_make_and(menv, trans, _t)
expr0 = msat_make_plus(menv, xs[2], n_3_0)
expr1 = msat_make_plus(menv, xs[4], n_2_0)
expr2 = msat_make_plus(menv, xs[7], n_1_0)
expr3 = msat_make_plus(menv, xs[9], n_18_0)
expr4 = msat_make_plus(menv, xs[11], n_13_0)
expr5 = msat_make_plus(menv, xs[12], n_20_0)
expr6 = msat_make_plus(menv, xs[13], n_8_0)
expr7 = msat_make_plus(menv, xs[14], n_15_0)
expr8 = msat_make_plus(menv, xs[16], n_9_0)
expr9 = msat_make_plus(menv, xs[18], n_20_0)
_t = msat_make_and(menv,
msat_make_geq(menv, x_xs[18], expr0),
msat_make_geq(menv, x_xs[18], expr1),
msat_make_geq(menv, x_xs[18], expr2),
msat_make_geq(menv, x_xs[18], expr3),
msat_make_geq(menv, x_xs[18], expr4),
msat_make_geq(menv, x_xs[18], expr5),
msat_make_geq(menv, x_xs[18], expr6),
msat_make_geq(menv, x_xs[18], expr7),
msat_make_geq(menv, x_xs[18], expr8),
msat_make_geq(menv, x_xs[18], expr9),)
_t = msat_make_and(menv, _t,
msat_make_or(menv,
msat_make_equal(menv, x_xs[18], expr0),
msat_make_equal(menv, x_xs[18], expr1),
msat_make_equal(menv, x_xs[18], expr2),
msat_make_equal(menv, x_xs[18], expr3),
msat_make_equal(menv, x_xs[18], expr4),
msat_make_equal(menv, x_xs[18], expr5),
msat_make_equal(menv, x_xs[18], expr6),
msat_make_equal(menv, x_xs[18], expr7),
msat_make_equal(menv, x_xs[18], expr8),
msat_make_equal(menv, x_xs[18], expr9),))
trans = msat_make_and(menv, trans, _t)
expr0 = msat_make_plus(menv, xs[0], n_10_0)
expr1 = msat_make_plus(menv, xs[2], n_9_0)
expr2 = msat_make_plus(menv, xs[3], n_5_0)
expr3 = msat_make_plus(menv, xs[5], n_16_0)
expr4 = msat_make_plus(menv, xs[6], n_4_0)
expr5 = msat_make_plus(menv, xs[12], n_17_0)
expr6 = msat_make_plus(menv, xs[13], n_16_0)
expr7 = msat_make_plus(menv, xs[14], n_11_0)
expr8 = msat_make_plus(menv, xs[15], n_5_0)
expr9 = msat_make_plus(menv, xs[17], n_17_0)
_t = msat_make_and(menv,
msat_make_geq(menv, x_xs[19], expr0),
msat_make_geq(menv, x_xs[19], expr1),
msat_make_geq(menv, x_xs[19], expr2),
msat_make_geq(menv, x_xs[19], expr3),
msat_make_geq(menv, x_xs[19], expr4),
msat_make_geq(menv, x_xs[19], expr5),
msat_make_geq(menv, x_xs[19], expr6),
msat_make_geq(menv, x_xs[19], expr7),
msat_make_geq(menv, x_xs[19], expr8),
msat_make_geq(menv, x_xs[19], expr9),)
_t = msat_make_and(menv, _t,
msat_make_or(menv,
msat_make_equal(menv, x_xs[19], expr0),
msat_make_equal(menv, x_xs[19], expr1),
msat_make_equal(menv, x_xs[19], expr2),
msat_make_equal(menv, x_xs[19], expr3),
msat_make_equal(menv, x_xs[19], expr4),
msat_make_equal(menv, x_xs[19], expr5),
msat_make_equal(menv, x_xs[19], expr6),
msat_make_equal(menv, x_xs[19], expr7),
msat_make_equal(menv, x_xs[19], expr8),
msat_make_equal(menv, x_xs[19], expr9),))
trans = msat_make_and(menv, trans, _t)
# ltl property: ((x_9 - x_11 > 15) U ((x_3 - x_19 > -17) U (x_15 - x_12 >= -20)))
ltl = enc.make_U(msat_make_gt(menv, msat_make_minus(menv, xs[9], xs[11]), msat_make_number(menv, "15")), enc.make_U(msat_make_gt(menv, msat_make_minus(menv, xs[3], xs[19]), msat_make_number(menv, "-17")), msat_make_geq(menv, msat_make_minus(menv, xs[15], xs[12]), msat_make_number(menv, "-20"))))
return TermMap(curr2next), init, trans, ltl
| [
"[email protected]"
] | |
ff47bf42bf696623df4bb9b6b23f46bb1c872804 | f50fca4275b43ed0fc7411e5d4a79c75ef1c1ed7 | /maximalsum.py | 8d4c8efc5e2963e16a5b14766fcbb4da2fa59600 | [] | no_license | swang2000/DP | 2169a85eec05d9be13cbcee1dcaf417ee4c4d70f | 6d9523398a9f4e802213b1184166a90530bfc26b | refs/heads/master | 2020-04-05T09:55:02.004433 | 2018-11-08T23:10:01 | 2018-11-08T23:10:01 | 156,780,628 | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 1,408 | py | '''
Dynamic Programming | Set 31 (Optimal Strategy for a Game)
4.1
Problem statement: Consider a row of n coins of values v1 . . . vn, where n is even. We play a game against an opponent
by alternating turns. In each turn, a player selects either the first or last coin from the row, removes it from the
row permanently, and receives the value of the coin. Determine the maximum possible amount of money we can definitely
win if we move first.
Note: The opponent is as clever as the user.
Let us understand the problem with few examples:
1. 5, 3, 7, 10 : The user collects maximum value as 15(10 + 5)
2. 8, 15, 3, 7 : The user collects maximum value as 22(7 + 15)
Does choosing the best at each move give an optimal solution?
No. In the second example, this is how the game can finish:
1.
…….User chooses 8.
…….Opponent chooses 15.
…….User chooses 7.
…….Opponent chooses 3.
Total value collected by user is 15(8 + 7)
2.
…….User chooses 7.
…….Opponent chooses 8.
…….User chooses 15.
…….Opponent chooses 3.
Total value collected by user is 22(7 + 15)
'''
def maximalsum(a):
if len(a) ==0:
return 0
if len(a) == 2:
return max(a)
return max(a[0]+ min(maximalsum(a[2:]), maximalsum(a[1:-1])),
a[-1]+min(maximalsum(a[1:-1]), maximalsum(a[:-2])))
a = [5, 3, 7, 10]
b = [8, 15, 3, 7]
maximalsum(a)
maximalsum(b)
| [
"[email protected]"
] | |
881e52cb5bec9d59a3252f6959ed3dc909a7de28 | d31d744f62c09cb298022f42bcaf9de03ad9791c | /tfx-bsl/tfx_bsl/tfxio/record_to_tensor_tfxio_test.py | 0e86b35939ada7adf0e5b762d4e63f90cf0b2a71 | [] | no_license | yuhuofei/TensorFlow-1 | b2085cb5c061aefe97e2e8f324b01d7d8e3f04a0 | 36eb6994d36674604973a06159e73187087f51c6 | refs/heads/master | 2023-02-22T13:57:28.886086 | 2021-01-26T14:18:18 | 2021-01-26T14:18:18 | null | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 12,293 | py | # 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.
"""Tests for tfx_bsl.tfxio.record_to_tensor_tfxio."""
import os
import tempfile
from absl import flags
import apache_beam as beam
from apache_beam.testing import util as beam_testing_util
import pyarrow as pa
import tensorflow as tf
from tfx_bsl.coders import tf_graph_record_decoder
from tfx_bsl.tfxio import dataset_options
from tfx_bsl.tfxio import record_to_tensor_tfxio
from tfx_bsl.tfxio import telemetry_test_util
from google.protobuf import text_format
from absl.testing import parameterized
from tensorflow_metadata.proto.v0 import schema_pb2
FLAGS = flags.FLAGS
class _DecoderForTesting(tf_graph_record_decoder.TFGraphRecordDecoder):
def __init__(self):
super().__init__("DecoderForTesting")
def _decode_record_internal(self, record):
indices = tf.transpose(
tf.stack([
tf.range(tf.size(record), dtype=tf.int64),
tf.zeros(tf.size(record), dtype=tf.int64)
]))
sparse_tensor = tf.SparseTensor(
values=record, indices=indices, dense_shape=[tf.size(record), 1])
return {
"st1": sparse_tensor,
"st2": sparse_tensor
}
class _DecoderForTestingWithRecordIndex(_DecoderForTesting):
def _decode_record_internal(self, record):
result = super(
_DecoderForTestingWithRecordIndex, self)._decode_record_internal(record)
result["ragged_record_index"] = tf.RaggedTensor.from_row_splits(
values=tf.range(tf.size(record), dtype=tf.int64),
row_splits=tf.range(tf.size(record) + 1, dtype=tf.int64))
result["sparse_record_index"] = result["ragged_record_index"].to_sparse()
return result
class _DecoderForTestingWithRaggedRecordIndex(
_DecoderForTestingWithRecordIndex):
@property
def record_index_tensor_name(self):
return "ragged_record_index"
class _DecoderForTestingWithSparseRecordIndex(
_DecoderForTestingWithRecordIndex):
@property
def record_index_tensor_name(self):
return "sparse_record_index"
_RECORDS = [b"aaa", b"bbb"]
_RECORDS_AS_TENSORS = [{
"st1":
tf.SparseTensor(values=[b"aaa"], indices=[[0, 0]], dense_shape=[1, 1]),
"st2":
tf.SparseTensor(values=[b"aaa"], indices=[[0, 0]], dense_shape=[1, 1])
}, {
"st1":
tf.SparseTensor(values=[b"bbb"], indices=[[0, 0]], dense_shape=[1, 1]),
"st2":
tf.SparseTensor(values=[b"bbb"], indices=[[0, 0]], dense_shape=[1, 1])
}]
_TELEMETRY_DESCRIPTORS = ["Some", "Component"]
def _write_input():
result = os.path.join(tempfile.mkdtemp(dir=FLAGS.test_tmpdir), "input")
with tf.io.TFRecordWriter(result) as w:
for r in _RECORDS:
w.write(r)
return result
def _write_decoder(decoder=_DecoderForTesting()):
result = tempfile.mkdtemp(dir=FLAGS.test_tmpdir)
tf_graph_record_decoder.save_decoder(decoder, result)
return result
class RecordToTensorTfxioTest(tf.test.TestCase, parameterized.TestCase):
def setUp(self):
super().setUp()
self._input_path = _write_input()
def _assert_sparse_tensor_equal(self, lhs, rhs):
self.assertAllEqual(lhs.values, rhs.values)
self.assertAllEqual(lhs.indices, rhs.indices)
self.assertAllEqual(lhs.dense_shape, rhs.dense_shape)
# pylint: disable=unnecessary-lambda
# the create_decoder lambdas may seem unnecessary, but they are picklable, and
# the classes (not the instances of those classes) are not.
@parameterized.named_parameters(*[
dict(testcase_name="attach_raw_records",
attach_raw_records=True,
create_decoder=lambda: _DecoderForTesting()),
dict(testcase_name="attach_raw_records_with_ragged_record_index",
attach_raw_records=True,
create_decoder=lambda: _DecoderForTestingWithRaggedRecordIndex()),
dict(testcase_name="attach_raw_records_with_sparse_record_index",
attach_raw_records=True,
create_decoder=lambda: _DecoderForTestingWithSparseRecordIndex()),
dict(testcase_name="noattach_raw_records",
attach_raw_records=False,
create_decoder=lambda: _DecoderForTesting()),
dict(testcase_name="noattach_raw_records_but_with_record_index",
attach_raw_records=False,
create_decoder=lambda: _DecoderForTestingWithSparseRecordIndex()),
dict(testcase_name="beam_record_tfxio",
attach_raw_records=False,
create_decoder=lambda: _DecoderForTesting(),
beam_record_tfxio=True),
])
# pylint: enable=unnecessary-lambda
def test_beam_source_and_tensor_adapter(
self, attach_raw_records, create_decoder, beam_record_tfxio=False):
decoder = create_decoder()
raw_record_column_name = "_raw_records" if attach_raw_records else None
decoder_path = _write_decoder(decoder)
if beam_record_tfxio:
tfxio = record_to_tensor_tfxio.BeamRecordToTensorTFXIO(
saved_decoder_path=decoder_path,
telemetry_descriptors=_TELEMETRY_DESCRIPTORS,
physical_format="tfrecords_gzip",
raw_record_column_name=raw_record_column_name)
else:
tfxio = record_to_tensor_tfxio.TFRecordToTensorTFXIO(
self._input_path,
decoder_path,
_TELEMETRY_DESCRIPTORS,
raw_record_column_name=raw_record_column_name)
expected_tensor_representations = {
"st1":
text_format.Parse("""varlen_sparse_tensor { column_name: "st1" }""",
schema_pb2.TensorRepresentation()),
"st2":
text_format.Parse("""varlen_sparse_tensor { column_name: "st2" }""",
schema_pb2.TensorRepresentation())
}
if isinstance(decoder, _DecoderForTestingWithRecordIndex):
expected_fields = [
pa.field("ragged_record_index", pa.large_list(pa.int64())),
pa.field("sparse_record_index", pa.large_list(pa.int64())),
pa.field("st1", pa.large_list(pa.large_binary())),
pa.field("st2", pa.large_list(pa.large_binary())),
]
expected_tensor_representations["ragged_record_index"] = (
text_format.Parse(
"""ragged_tensor {
feature_path: { step: "ragged_record_index" }
row_partition_dtype: INT64
}""", schema_pb2.TensorRepresentation()))
expected_tensor_representations["sparse_record_index"] = (
text_format.Parse(
"""varlen_sparse_tensor { column_name: "sparse_record_index" }""",
schema_pb2.TensorRepresentation()))
else:
expected_fields = [
pa.field("st1", pa.large_list(pa.large_binary())),
pa.field("st2", pa.large_list(pa.large_binary())),
]
if attach_raw_records:
expected_fields.append(
pa.field(raw_record_column_name, pa.large_list(pa.large_binary())))
self.assertTrue(tfxio.ArrowSchema().equals(
pa.schema(expected_fields)), tfxio.ArrowSchema())
self.assertEqual(
tfxio.TensorRepresentations(), expected_tensor_representations)
tensor_adapter = tfxio.TensorAdapter()
self.assertEqual(tensor_adapter.TypeSpecs(),
decoder.output_type_specs())
def _assert_fn(list_of_rb):
self.assertLen(list_of_rb, 1)
rb = list_of_rb[0]
self.assertTrue(rb.schema.equals(tfxio.ArrowSchema()))
if attach_raw_records:
self.assertEqual(rb.column(rb.num_columns - 1).flatten().to_pylist(),
_RECORDS)
tensors = tensor_adapter.ToBatchTensors(rb)
for tensor_name in ("st1", "st2"):
self.assertIn(tensor_name, tensors)
st = tensors[tensor_name]
self.assertAllEqual(st.values, _RECORDS)
self.assertAllEqual(st.indices, [[0, 0], [1, 0]])
self.assertAllEqual(st.dense_shape, [2, 1])
p = beam.Pipeline()
pipeline_input = (p | beam.Create(_RECORDS)) if beam_record_tfxio else p
rb_pcoll = pipeline_input | tfxio.BeamSource(batch_size=len(_RECORDS))
beam_testing_util.assert_that(rb_pcoll, _assert_fn)
pipeline_result = p.run()
pipeline_result.wait_until_finish()
telemetry_test_util.ValidateMetrics(
self, pipeline_result, _TELEMETRY_DESCRIPTORS,
"tensor", "tfrecords_gzip")
def test_project(self):
decoder_path = _write_decoder()
tfxio = record_to_tensor_tfxio.TFRecordToTensorTFXIO(
self._input_path, decoder_path, ["some", "component"])
projected = tfxio.Project(["st1"])
self.assertIn("st1", projected.TensorRepresentations())
self.assertNotIn("st2", projected.TensorRepresentations())
tensor_adapter = projected.TensorAdapter()
def _assert_fn(list_of_rb):
self.assertLen(list_of_rb, 1)
rb = list_of_rb[0]
tensors = tensor_adapter.ToBatchTensors(rb)
self.assertLen(tensors, 1)
self.assertIn("st1", tensors)
st = tensors["st1"]
self.assertAllEqual(st.values, _RECORDS)
self.assertAllEqual(st.indices, [[0, 0], [1, 0]])
self.assertAllEqual(st.dense_shape, [2, 1])
with beam.Pipeline() as p:
rb_pcoll = p | tfxio.BeamSource(batch_size=len(_RECORDS))
beam_testing_util.assert_that(rb_pcoll, _assert_fn)
def test_tensorflow_dataset(self):
decoder_path = _write_decoder()
tfxio = record_to_tensor_tfxio.TFRecordToTensorTFXIO(
self._input_path, decoder_path, ["some", "component"])
options = dataset_options.TensorFlowDatasetOptions(
batch_size=1, shuffle=False, num_epochs=1)
for i, decoded_tensors_dict in enumerate(
tfxio.TensorFlowDataset(options=options)):
for key, tensor in decoded_tensors_dict.items():
self._assert_sparse_tensor_equal(tensor, _RECORDS_AS_TENSORS[i][key])
def test_projected_tensorflow_dataset(self):
decoder_path = _write_decoder()
tfxio = record_to_tensor_tfxio.TFRecordToTensorTFXIO(
self._input_path, decoder_path, ["some", "component"])
feature_name = "st1"
projected_tfxio = tfxio.Project([feature_name])
options = dataset_options.TensorFlowDatasetOptions(
batch_size=1, shuffle=False, num_epochs=1)
for i, decoded_tensors_dict in enumerate(
projected_tfxio.TensorFlowDataset(options=options)):
self.assertIn(feature_name, decoded_tensors_dict)
self.assertLen(decoded_tensors_dict, 1)
tensor = decoded_tensors_dict[feature_name]
self._assert_sparse_tensor_equal(
tensor, _RECORDS_AS_TENSORS[i][feature_name])
def test_tensorflow_dataset_with_label_key(self):
decoder_path = _write_decoder()
tfxio = record_to_tensor_tfxio.TFRecordToTensorTFXIO(
self._input_path, decoder_path, ["some", "component"])
label_key = "st1"
options = dataset_options.TensorFlowDatasetOptions(
batch_size=1, shuffle=False, num_epochs=1, label_key=label_key)
for i, (decoded_tensors_dict, label_feature) in enumerate(
tfxio.TensorFlowDataset(options=options)):
self._assert_sparse_tensor_equal(
label_feature, _RECORDS_AS_TENSORS[i][label_key])
for key, tensor in decoded_tensors_dict.items():
self._assert_sparse_tensor_equal(tensor, _RECORDS_AS_TENSORS[i][key])
def test_tensorflow_dataset_with_invalid_label_key(self):
decoder_path = _write_decoder()
tfxio = record_to_tensor_tfxio.TFRecordToTensorTFXIO(
self._input_path, decoder_path, ["some", "component"])
label_key = "invalid"
options = dataset_options.TensorFlowDatasetOptions(
batch_size=1, shuffle=False, num_epochs=1, label_key=label_key)
with self.assertRaisesRegex(ValueError, "The `label_key` provided.*"):
tfxio.TensorFlowDataset(options=options)
if __name__ == "__main__":
# Do not run these tests under TF1.x -- not supported.
if tf.__version__ >= "2":
tf.test.main()
| [
"[email protected]"
] | |
c6ce4a8d43a2a3b900beb1f0c64bc4d7f9912bf0 | 5fd96aaeebcf137b46c611ad992de307861639a1 | /recollection/apps/support/forms.py | 74fbfd9abc5d92361edb2d02a1b7053380ee87f9 | [
"Apache-2.0",
"LicenseRef-scancode-unknown-license-reference",
"MIT",
"LicenseRef-scancode-secret-labs-2011",
"CC-BY-2.5",
"BSD-3-Clause",
"BSD-2-Clause"
] | permissive | tfmorris/recollection | f91800c569ee9d05334e085c8dd050bc65ae23ca | 9e818f91b30b43b392ad9ca608e0068f868a51c1 | refs/heads/master | 2021-01-18T03:58:20.393406 | 2012-04-15T22:08:39 | 2012-04-15T22:08:39 | null | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 6,770 | py | from django import forms
from django.forms import widgets
from django.utils.translation import ugettext_lazy as _
from django.utils import simplejson as json
from . import models
class SupportIssueForm(forms.Form):
"""
Base form for recollection support
>>> f = SupportIssueForm({'contact_type':'email', 'contact_email':'[email protected]'})
>>> f.is_valid()
True
>>>f.cleaned_data.get("contact_type_pretty")== _("E-mail")
True
"""
contact_type = forms.ChoiceField(required=True,
choices=[('email',_('E-mail')), ('phone',_('Phone'))],
label=_("Preferred Contact Method"))
contact_email = forms.EmailField(required=False, max_length=200, label=_("E-mail address"))
contact_phone = forms.CharField(required=False, max_length=25, label=_("Phone number"))
browser = forms.ChoiceField(label=_("Browser"),
help_text=_("Please select your browser from the list, or 'Other' to enter an alternative"),
required=False)
browser_text=forms.CharField(required=False, label=_("Browser Description"), help_text=_("Please describe your browser"))
def __init__(self, *args, **kwargs):
super(SupportIssueForm, self).__init__(*args, **kwargs)
self.fields["browser"].choices = [('',''),] + [(b.key, b.value,) for b in models.BrowserPickListItem.objects.all()] + [('other', 'Other',),]
def clean(self):
cleaned_data = self.cleaned_data
for val in self.fields['contact_type'].choices:
if val[0] == cleaned_data.get('contact_type'):
cleaned_data["contact_type_pretty"] = val[1]
for val in self.fields['browser'].choices:
if val[0] == cleaned_data.get('browser') and cleaned_data.get('browser') != 'other':
cleaned_data["browser_text"] = val[1]
return cleaned_data
def clean_contact_email(self):
contact_type = self.cleaned_data.get("contact_type")
email = self.cleaned_data.get("contact_email")
if contact_type == "email":
if not email:
raise forms.ValidationError(_("Please supply an e-mail address"))
else:
self.cleaned_data["contact_point"] = email
return email
def clean_contact_phone(self):
contact_type = self.cleaned_data.get("contact_type")
phone = self.cleaned_data.get("contact_phone")
if contact_type == "phone":
if not phone:
raise forms.ValidationError(_("Please supply a phone number"))
else:
self.cleaned_data["contact_point"] = phone
return phone
def clean_browser_text(self):
browser_text = self.cleaned_data.get("browser_text")
browser = self.cleaned_data.get("browser")
if browser:
if not browser == "other":
browser_text = models.BrowserPickListItem.objects.get(key=browser).value
elif not browser_text:
raise forms.ValidationError(_("Please describe your browser"))
return browser_text
class DataLoadUploadIssueForm(SupportIssueForm):
issue_reason = forms.ChoiceField(required=True, label=_("Reason"),
help_text="Please select the issue you are experiencing, or 'Other' if it isn't listed")
issue_reason_text = forms.CharField(required=False, label=_("Description"))
file_format=forms.ChoiceField(required=True, label=_("Format"),
help_text="Please select the format of the file you are attempting to load, or 'Other' to enter another format")
file_format_text=forms.CharField(required=False, label=_("File Format Description"), help_text=_("Please describe your file format"))
def __init__(self, *args, **kwargs):
super(DataLoadUploadIssueForm, self).__init__(*args, **kwargs)
self.fields["file_format"].choices = [(b.key, b.value,) for b in models.FileFormatPickListItem.objects.all()] + [('other', 'Other',),]
self.fields["issue_reason"].choices = [(b.key, b.value,) for b in models.DataLoadReasonPickListItem.objects.all()] + [('other', 'Other',),]
def clean_file_format_text(self):
file_format_text = self.cleaned_data.get("file_format_text")
file_format = self.cleaned_data.get("file_format")
if file_format:
if not file_format == "other":
file_format_text = models.FileFormatPickListItem.objects.get(key=file_format).value
elif not file_format_text:
raise forms.ValidationError(_("Please describe your file format"))
return file_format_text
def clean_issue_reason_text(self):
issue_reason_text = self.cleaned_data.get("issue_reason_text")
issue_reason=self.cleaned_data.get("issue_reason")
if not issue_reason == "other":
issue_reason_text = models.DataLoadReasonPickListItem.objects.get(key=issue_reason).value
elif not issue_reason_text:
raise forms.ValidationError(_("Please describe your data loading issue"))
return issue_reason_text
class DataLoadIgnoredFieldsIssueForm(SupportIssueForm):
"""
Form for reporting ignored data in transformation
"""
elements = forms.CharField(required=True, widget=widgets.Textarea, help_text=_("Please edit this list to highlight the elements or attributes for which you would like support"))
comments = forms.CharField(required=False, widget=widgets.Textarea,
label=_("Additional Comments"),
help_text=_("Any additional information about your data or the issue you are experiencing that could be helpful"))
class AugmentationIssueForm(SupportIssueForm):
"""
Form for data augmentation support.
Requires that the `profile_json` field be populated with a JSON snapshot of the dataset
"""
profile_json = forms.CharField(required=True, widget=widgets.HiddenInput)
field_name = forms.CharField(required=False,
label="Augmented Field",
help_text=_("Enter a label to highlight a particular field"))
comments = forms.CharField(required=False, widget=widgets.Textarea,
label=_("Additional Comments"),
help_text=_("Any additional information about your data or the issue you are experiencing that could be helpful"))
def clean_profile_json(self):
try:
return json.loads(self.cleaned_data.get("profile_json"))
except:
raise forms.ValidationError(_("Invalid profile description"))
| [
"[email protected]"
] | |
bc6753a7cd0f2642d7b4b8c2e587b1fdbd850bd8 | 33ce95a46bad431fb9acde07f10f472c43533824 | /functions_advanced_lab/absolute_values.py | 0e7d743dc7d8b0c0dd460d48eb7f661c1730c4b7 | [] | no_license | ivan-yosifov88/python_advanced | 91dead1a44771a46e85cecdfc6b02e11c0cb4d91 | 21830aabc87eb28eb32bf3c070bf202b4740f628 | refs/heads/main | 2023-06-29T21:31:30.285019 | 2021-06-23T20:31:36 | 2021-06-23T20:31:36 | 342,571,734 | 1 | 0 | null | null | null | null | UTF-8 | Python | false | false | 234 | py | def read_input():
list_of_numbers = [float(num) for num in input().split()]
return list_of_numbers
def print_result(numbers_list):
print([abs(num) for num in numbers_list])
numbers = read_input()
print_result(numbers) | [
"ivan.yosifov88gmail.com"
] | ivan.yosifov88gmail.com |
93a13f5c7aae90aafc40f7680b9fdc982234540b | 53fab060fa262e5d5026e0807d93c75fb81e67b9 | /backup/user_172/ch73_2020_04_22_12_07_59_451590.py | 7d390abc9a0f7b282992c69a56b50822905358f1 | [] | no_license | gabriellaec/desoft-analise-exercicios | b77c6999424c5ce7e44086a12589a0ad43d6adca | 01940ab0897aa6005764fc220b900e4d6161d36b | refs/heads/main | 2023-01-31T17:19:42.050628 | 2020-12-16T05:21:31 | 2020-12-16T05:21:31 | 306,735,108 | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 273 | py | def remove_vogais(palavra):
i = 0
while i < len(palavra):
if palavra[i] == 'a' or palavra[i] == 'e' or palavra[i] == 'i' or palavra[i] == 'o' or palavra[i] == 'u':
del palavra[i]
i+=1
else:
i+=1
return palavra | [
"[email protected]"
] | |
7cf703c9e6a3e84f639e61fbb79d305d183c1026 | 73758dde83d1a1823c103e1a4ba71e7c95168f71 | /nsd2006/devops/day02/dingtalk.py | f09a620f5c3c08dd4c56aa692938ff3c8368b2ce | [] | no_license | tonggh220/md_5_nsd_notes | 07ffdee7c23963a7a461f2a2340143b0e97bd9e1 | a58a021ad4c7fbdf7df327424dc518f4044c5116 | refs/heads/master | 2023-07-02T01:34:38.798929 | 2021-05-12T08:48:40 | 2021-05-12T08:48:40 | 393,885,415 | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 960 | py | import requests
import json
url = ''
headers = {'Content-Type': 'application/json; charset=UTF-8'}
# data = {
# "msgtype": "text",
# "text": {
# "content": "我就是我, 是不一样的烟火 好好学习天天向上"
# },
# "at": { # @哪些电话号码
# "atMobiles": [
# # "156xxxx8827",
# # "189xxxx8325"
# ],
# "isAtAll": False # 是否@所有人
# }
# }
data = {
"msgtype": "markdown",
"markdown": {
"title": "Offer",
"text": """## 入职邀请
您已被我公司录取,请于2020-12-10来报到,公司详情参见:[TEDU](http://www.tedu.cn)

好好学习天天向上"""
},
"at": {
"atMobiles": [
# "150XXXXXXXX"
],
"isAtAll": False
}
}
r = requests.post(url, headers=headers, data=json.dumps(data))
print(r.json())
| [
"[email protected]"
] | |
4f1d9ab5863aa6c57561c239f1fac7c3dcaad503 | 4b7b46a6d0f8ebeb544ff4b213a9c710e4db59c1 | /src/make_select_occultation_times_table.py | 37167b9a48f724cf579391caca8ae2f839332f1f | [] | no_license | lgbouma/WASP-4b_anomaly | 7eb44a54af553298075c69a3e4f7d9ea607bb762 | 124b0bb9912e43d47d98f6dfc390be7ef9823095 | refs/heads/master | 2021-08-19T20:28:18.577334 | 2020-04-11T17:49:09 | 2020-04-11T17:49:09 | 160,554,122 | 0 | 0 | null | 2020-02-09T14:13:21 | 2018-12-05T17:27:01 | TeX | UTF-8 | Python | false | false | 2,054 | py | # -*- coding: utf-8 -*-
'''
make table of selected transit times
'''
from __future__ import division, print_function
import matplotlib as mpl
mpl.use('Agg')
import matplotlib.pyplot as plt, pandas as pd, numpy as np
from glob import glob
import os, pickle
def get_data(
datacsv='../data/WASP-18b_literature_and_TESS_times_O-C_vs_epoch_selected.csv'
):
# need to run make_parameter_vs_epoch_plots.py first; this generates the
# SELECTED epochs (x values), mid-times (y values), and mid-time errors
# (sigma_y).
df = pd.read_csv(datacsv, sep=';')
return df
def main():
plname = 'WASP-4b'
allseldatapath = (
'/home/luke/Dropbox/proj/tessorbitaldecay/data/'+
'{:s}_occultation_times_selected.csv'.
format(plname)
)
df = get_data(datacsv=allseldatapath)
midpoints = np.array(df['sel_occ_times_BJD_TDB'])
uncertainty = np.array(df['err_sel_occ_times_BJD_TDB'])
epochs = np.array(df['sel_epoch']).astype(int)
original_references = np.array(df['original_reference'])
references = []
for ref in original_references:
if ref == '2011A&A...530A...5C':
references.append('\citet{caceres_ground-based_2011}')
elif ref == '2011ApJ...727...23B':
references.append('\citet{beerer_secondary_2011}')
elif ref == '2015MNRAS.454.3002Z':
references.append('\citet{zhou_secondary_2015}')
references = np.array(references)
outdf = pd.DataFrame(
{'midpoints': np.round(midpoints,5),
'uncertainty': np.round(uncertainty,5),
'epochs': epochs,
'original_reference': references
}
)
outdf['midpoints'] = outdf['midpoints'].map('{:.5f}'.format)
outdf = outdf[
['midpoints', 'uncertainty', 'epochs', 'original_reference']
]
outpath = 'selected_occultation_times.tex'
with open(outpath,'w') as tf:
print('wrote {:s}'.format(outpath))
tf.write(outdf.to_latex(index=False, escape=False))
if __name__=="__main__":
main()
| [
"[email protected]"
] | |
335248f2dc979c968e6eebcf946bc83489b010b2 | afbae26b958b5ef20548402a65002dcc8e55b66a | /release/stubs.min/Autodesk/Revit/DB/__init___parts/FilterDoubleRule.py | 27c4478ffdcdb2e5d8a367b3b2f1c85017c412ed | [
"MIT"
] | permissive | gtalarico/ironpython-stubs | d875cb8932c7644f807dc6fde9dd513d159e4f5c | c7f6a6cb197e3949e40a4880a0b2a44e72d0a940 | refs/heads/master | 2023-07-12T01:43:47.295560 | 2022-05-23T18:12:06 | 2022-05-23T18:12:06 | 95,340,553 | 235 | 88 | NOASSERTION | 2023-07-05T06:36:28 | 2017-06-25T05:30:46 | Python | UTF-8 | Python | false | false | 1,749 | py | class FilterDoubleRule(FilterNumericValueRule,IDisposable):
"""
A filter rule that operates on double-precision numeric values in a Revit project.
FilterDoubleRule(valueProvider: FilterableValueProvider,evaluator: FilterNumericRuleEvaluator,ruleValue: float,epsilon: float)
"""
def Dispose(self):
""" Dispose(self: FilterRule,A_0: bool) """
pass
def ReleaseUnmanagedResources(self,*args):
""" ReleaseUnmanagedResources(self: FilterRule,disposing: bool) """
pass
def __enter__(self,*args):
""" __enter__(self: IDisposable) -> object """
pass
def __exit__(self,*args):
""" __exit__(self: IDisposable,exc_type: object,exc_value: object,exc_back: object) """
pass
def __init__(self,*args):
""" x.__init__(...) initializes x; see x.__class__.__doc__ for signaturex.__init__(...) initializes x; see x.__class__.__doc__ for signaturex.__init__(...) initializes x; see x.__class__.__doc__ for signature """
pass
@staticmethod
def __new__(self,valueProvider,evaluator,ruleValue,epsilon):
""" __new__(cls: type,valueProvider: FilterableValueProvider,evaluator: FilterNumericRuleEvaluator,ruleValue: float,epsilon: float) """
pass
Epsilon=property(lambda self: object(),lambda self,v: None,lambda self: None)
"""The tolerance within which two floating-point values may be considered equal.
Get: Epsilon(self: FilterDoubleRule) -> float
Set: Epsilon(self: FilterDoubleRule)=value
"""
RuleValue=property(lambda self: object(),lambda self,v: None,lambda self: None)
"""The user-supplied value against which values from a Revit document will be tested.
Get: RuleValue(self: FilterDoubleRule) -> float
Set: RuleValue(self: FilterDoubleRule)=value
"""
| [
"[email protected]"
] | |
5be03d61a8e343b861e064451418f9530ddfa6e1 | 28a3860f80ff80ae3ce0650f99a7b8e00fbfdb4f | /compredospequenos/viviremediavenv/bin/futurize | e5e7466a0a3f40107a8ec3ef9ac5ee6fc7c3dd59 | [] | no_license | ladislauadri/compredospequenos | 3a47f9433c2a6c389c2b02c04b587e70c5fb1168 | 639d44c0488700b0bb359e83c16ee9c6302aad17 | refs/heads/main | 2023-03-08T07:27:12.970315 | 2021-02-18T10:56:49 | 2021-02-18T10:56:49 | 339,982,844 | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 425 | #!/var/django/compredospequenos/viviremediavenv/bin/python3
# EASY-INSTALL-ENTRY-SCRIPT: 'future==0.18.2','console_scripts','futurize'
__requires__ = 'future==0.18.2'
import re
import sys
from pkg_resources import load_entry_point
if __name__ == '__main__':
sys.argv[0] = re.sub(r'(-script\.pyw?|\.exe)?$', '', sys.argv[0])
sys.exit(
load_entry_point('future==0.18.2', 'console_scripts', 'futurize')()
)
| [
"[email protected]"
] | ||
48bffe0c9f300459f379cdb715aa7d5b13343fa1 | 9e401071eb220b299df1fec0be5a6da0976d6a9b | /wordlioud.py | 1c478e796e64b6dca0635812380a1582a769f39b | [] | no_license | skyshu/WordCloudExample | 543ccc4eeacf5a4962cefee3f9cf9912f5b5dc2b | f44311bcdc4e05af7eab2700833436698ff27964 | refs/heads/master | 2021-01-21T17:57:30.420006 | 2017-05-22T04:08:41 | 2017-05-22T04:08:41 | 92,003,767 | 2 | 1 | null | null | null | null | UTF-8 | Python | false | false | 1,474 | py | #coding:utf-8
from os import path
from scipy.misc import imread
import matplotlib.pyplot as plt
import jieba
import codecs
from wordcloud import WordCloud, ImageColorGenerator
# 获取当前文件路径
# __file__ 为当前文件, 在ide中运行此行会报错,可改为
# d = path.dirname('.')
d = path.dirname(__file__)
# 读取文本 alice.txt 在包文件的example目录下
text = open(path.join(d, 'alice.txt')).read()
#中文分割
cut_text = " ".join(jieba.cut(text))
# read the mask / color image
# 设置背景图片
alice_coloring = imread(path.join(d, "love.png"))
wc = WordCloud(
#设置中文字体
font_path="HYQiHei-25J.ttf",
#背景颜色
background_color="white",
#词云显示的最大词数
max_words=200,
#设置背景图片
mask=alice_coloring,
#字体最大值
max_font_size=80,
)
# 生成词云,也可以我们计算好词频后使用generate_from_frequencies函数
wc.generate(cut_text)
#fre = {u'吃饭':100,u'睡觉':20,u'打豆豆':80}
# 不加u会乱码
#wc.generate_from_frequencies(fre)
#从背景图片生成颜色值
image_colors = ImageColorGenerator(alice_coloring)
# 显示默认词云
plt.imshow(wc)
plt.axis("off")
# 绘制以图片色彩为背景的词云
plt.figure()
plt.imshow(wc.recolor(color_func=image_colors))
plt.axis("off")
# 绘制原图像
#plt.figure()
#plt.imshow(alice_coloring, cmap=plt.cm.gray)
#plt.axis("off")
plt.show()
# 保存图片
wc.to_file(path.join(d, "LOVE.png")) | [
"="
] | = |
cbe4a683f083cefc8d159895afa7eb75d352e5c8 | 5b93930ce8280b3cbc7d6b955df0bfc5504ee99c | /nodes/Ramsundar18TensorFlow/D_Chapter3/D_Review/index.py | ee8d6792fe9cd217a56ecbb6f3b415dcf80f3fc2 | [] | no_license | nimra/module_gen | 8749c8d29beb700cac57132232861eba4eb82331 | 2e0a4452548af4fefd4cb30ab9d08d7662122cf4 | refs/heads/master | 2022-03-04T09:35:12.443651 | 2019-10-26T04:40:49 | 2019-10-26T04:40:49 | 213,980,247 | 0 | 1 | null | null | null | null | UTF-8 | Python | false | false | 4,004 | py | # Lawrence McAfee
# ~~~~~~~~ import ~~~~~~~~
from modules.node.HierNode import HierNode
from modules.node.LeafNode import LeafNode
from modules.node.Stage import Stage
from modules.node.block.CodeBlock import CodeBlock as cbk
from modules.node.block.ImageBlock import ImageBlock as ibk
from modules.node.block.MarkdownBlock import MarkdownBlock as mbk
# ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
# Review
# In this chapter, we’ve shown you how to build and train some simple learning systems
# in TensorFlow. We started by reviewing some foundational mathematical concepts
# including loss functions and gradient descent. We then introduced you to some new
# TensorFlow concepts such as placeholders, scopes, and TensorBoard. We ended the
# chapter with case studies that trained linear and logistic regression systems on toy
# datasets. We covered a lot of material in this chapter, and it’s OK if you haven’t yet
# internalized everything. The foundational material introduced here will be used
# throughout the remainder of this book.
# In Chapter 4, we will introduce you to your first deep learning model and to fully
# connected networks, and will show you how to define and train fully connected net‐
# works in TensorFlow. In following chapters, we will explore more complicated deep
# networks, but all of these architectures will use the same fundamental learning princi‐
# ples introduced in this chapter.
#
#
#
#
# Review | 79
#
#
# CHAPTER 4
# Fully Connected Deep Networks
#
#
#
#
# This chapter will introduce you to fully connected deep networks. Fully connected
# networks are the workhorses of deep learning, used for thousands of applications.
# The major advantage of fully connected networks is that they are “structure agnostic.”
# That is, no special assumptions need to be made about the input (for example, that
# the input consists of images or videos). We will make use of this generality to use fully
# connected deep networks to address a problem in chemical modeling later in this
# chapter.
# We delve briefly into the mathematical theory underpinning fully connected net‐
# works. In particular, we explore the concept that fully connected architectures are
# “universal approximators” capable of learning any function. This concept provides an
# explanation of the generality of fully connected architectures, but comes with many
# caveats that we discuss at some depth.
# While being structure agnostic makes fully connected networks very broadly applica‐
# ble, such networks do tend to have weaker performance than special-purpose net‐
# works tuned to the structure of a problem space. We will discuss some of the
# limitations of fully connected architectures later in this chapter.
#
# What Is a Fully Connected Deep Network?
# A fully connected neural network consists of a series of fully connected layers. A fully
# connected layer is a function from ℝm to ℝn. Each output dimension depends on
# each input dimension. Pictorially, a fully connected layer is represented as follows in
# Figure 4-1.
#
#
#
#
# 81
#
# ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
class Content(LeafNode):
def __init__(self):
super().__init__(
"Review",
# Stage.CROP_TEXT,
# Stage.CODE_BLOCKS,
# Stage.MARKDOWN_BLOCKS,
# Stage.FIGURES,
# Stage.EXERCISES,
# Stage.CUSTOMIZED,
)
self.add(mbk("# Review"))
# ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
class Review(HierNode):
def __init__(self):
super().__init__("Review")
self.add(Content())
# eof
| [
"[email protected]"
] | |
ad8a8be88f337d0531bf7228029cf49b62dfd7ff | 59a688e68421794af64bfe69a74f64b2c80cd79d | /math_numbers/number_relations.py | 54380ae099fc73542c01e7baa6c84156986a75ef | [] | no_license | hearues-zueke-github/python_programs | f23469b306e057512aadecad0ca0a02705667a15 | d24f04ca143aa93f172210a4b9dfdd9bf1b79a15 | refs/heads/master | 2023-07-26T00:36:56.512635 | 2023-07-17T12:35:16 | 2023-07-17T12:35:16 | 117,093,746 | 6 | 0 | null | null | null | null | UTF-8 | Python | false | false | 1,649 | py | #! /usr/bin/python3.5
import decimal
import math
import numpy as np
import matplotlib.pyplot as plt
from decimal import Decimal as D
from functools import reduce
decimal.getcontext().prec = 2000
def to_digit_list(n):
return list(map(int, list(str(n))))
''' Number manipulation functions '''
def digit_sum(n):
return np.sum(to_digit_list(n))
def digit_diff(n):
l = list(map(int, list(str(n))))
return int("".join(list(map(lambda a, b: str((a-b)%10), l[1:], l[:-1]))))
def digit_prod(n):
l = np.array(to_digit_list(n))
l[l==0] = 1
return np.prod(l)
a = 1234568
print("a: {}".format(a))
print("digit_sum(a): {}".format(digit_sum(a)))
print("digit_diff(a): {}".format(digit_diff(a)))
print("digit_prod(a): {}".format(digit_prod(a)))
n_max = 100000
l_dig_sums = [digit_sum(i) for i in range(0, n_max+1)]
l_dig_diffs = [0 for _ in range(0, 10)]+[digit_diff(i) for i in range(10, n_max+1)]
l_dig_prods = [digit_prod(i) for i in range(0, n_max+1)]
print("np.min(l_dig_sums): {}".format(np.min(l_dig_sums)))
print("np.min(l_dig_diffs): {}".format(np.min(l_dig_diffs)))
print("np.min(l_dig_prods): {}".format(np.min(l_dig_prods)))
print("np.max(l_dig_sums): {}".format(np.max(l_dig_sums)))
print("np.max(l_dig_diffs): {}".format(np.max(l_dig_diffs)))
print("np.max(l_dig_prods): {}".format(np.max(l_dig_prods)))
ls = []
for n in range(1, 1000):
l = [n]
j = n
for i in range(0, 10):
j = l_dig_sums[j]
l.append(j)
# j = l_dig_diffs[j]
# l.append(j)
j = l_dig_prods[j]
l.append(j)
ls.append((n, l))
for n, l in ls:
print("n: {}, l:\n{}".format(n, l))
| [
"[email protected]"
] | |
68d0876c783e333bac7aede80bfc8173d2d38b21 | ee2181511a6e4165c348d3c20d01f81673650e33 | /dask_xgboost/core.py | ca3b8309a75d1b557d7f0d7882ded76248b83891 | [] | no_license | sunyoubo/dask-xgboost | bf7f7ef20b39203145591911f44739748ae8debf | 7cedc4fad9b82ce07bb90a9dd91f8a9cda84659e | refs/heads/master | 2021-05-08T05:56:52.429563 | 2017-10-04T18:17:08 | 2017-10-04T18:17:08 | null | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 6,518 | py | from collections import defaultdict
import logging
from threading import Thread
import dask.dataframe as dd
import dask.array as da
import numpy as np
import pandas as pd
from toolz import first, assoc
from tornado import gen
from dask import delayed
from distributed.client import _wait
from distributed.utils import sync
import xgboost as xgb
from .tracker import RabitTracker
logger = logging.getLogger(__name__)
def parse_host_port(address):
if '://' in address:
address = address.rsplit('://', 1)[1]
host, port = address.split(':')
port = int(port)
return host, port
def start_tracker(host, n_workers):
""" Start Rabit tracker """
env = {'DMLC_NUM_WORKER': n_workers}
rabit = RabitTracker(hostIP=host, nslave=n_workers)
env.update(rabit.slave_envs())
rabit.start(n_workers)
logger.info("Starting Rabit Tracker")
thread = Thread(target=rabit.join)
thread.daemon = True
thread.start()
return env
def concat(L):
if isinstance(L[0], np.ndarray):
return np.concatenate(L, axis=0)
elif isinstance(L[0], (pd.DataFrame, pd.Series)):
return pd.concat(L, axis=0)
else:
raise TypeError("Data must be either numpy arrays or pandas dataframes"
". Got %s" % type(L[0]))
def train_part(env, param, list_of_parts, **kwargs):
"""
Run part of XGBoost distributed workload
This starts an xgboost.rabit slave, trains on provided data, and then shuts
down the xgboost.rabit slave
Returns
-------
model if rank zero, None otherwise
"""
data, labels = zip(*list_of_parts) # Prepare data
data = concat(data) # Concatenate many parts into one
labels = concat(labels)
dtrain = xgb.DMatrix(data, labels) # Convert to xgboost data structure
args = [('%s=%s' % item).encode() for item in env.items()]
xgb.rabit.init(args)
try:
logger.info("Starting Rabit, Rank %d", xgb.rabit.get_rank())
bst = xgb.train(param, dtrain, **kwargs)
if xgb.rabit.get_rank() == 0: # Only return from one worker
result = bst
else:
result = None
finally:
xgb.rabit.finalize()
return result
@gen.coroutine
def _train(client, params, data, labels, **kwargs):
"""
Asynchronous version of train
See Also
--------
train
"""
# Break apart Dask.array/dataframe into chunks/parts
data_parts = data.to_delayed()
label_parts = labels.to_delayed()
if isinstance(data_parts, np.ndarray):
assert data_parts.shape[1] == 1
data_parts = data_parts.flatten().tolist()
if isinstance(label_parts, np.ndarray):
assert label_parts.ndim == 1 or label_parts.shape[1] == 1
label_parts = label_parts.flatten().tolist()
# Arrange parts into pairs. This enforces co-locality
parts = list(map(delayed, zip(data_parts, label_parts)))
parts = client.compute(parts) # Start computation in the background
yield _wait(parts)
# Because XGBoost-python doesn't yet allow iterative training, we need to
# find the locations of all chunks and map them to particular Dask workers
key_to_part_dict = dict([(part.key, part) for part in parts])
who_has = yield client.scheduler.who_has(keys=[part.key for part in parts])
worker_map = defaultdict(list)
for key, workers in who_has.items():
worker_map[first(workers)].append(key_to_part_dict[key])
ncores = yield client.scheduler.ncores() # Number of cores per worker
# Start the XGBoost tracker on the Dask scheduler
host, port = parse_host_port(client.scheduler.address)
env = yield client._run_on_scheduler(start_tracker,
host.strip('/:'),
len(worker_map))
# Tell each worker to train on the chunks/parts that it has locally
futures = [client.submit(train_part, env,
assoc(params, 'nthreads', ncores[worker]),
list_of_parts, workers=worker, **kwargs)
for worker, list_of_parts in worker_map.items()]
# Get the results, only one will be non-None
results = yield client._gather(futures)
result = [v for v in results if v][0]
raise gen.Return(result)
def train(client, params, data, labels, **kwargs):
""" Train an XGBoost model on a Dask Cluster
This starts XGBoost on all Dask workers, moves input data to those workers,
and then calls ``xgboost.train`` on the inputs.
Parameters
----------
client: dask.distributed.Client
params: dict
Parameters to give to XGBoost (see xgb.Booster.train)
data: dask array or dask.dataframe
labels: dask.array or dask.dataframe
**kwargs:
Keywords to give to XGBoost
Examples
--------
>>> client = Client('scheduler-address:8786') # doctest: +SKIP
>>> data = dd.read_csv('s3://...') # doctest: +SKIP
>>> labels = data['outcome'] # doctest: +SKIP
>>> del data['outcome'] # doctest: +SKIP
>>> train(client, params, data, labels, **normal_kwargs) # doctest: +SKIP
<xgboost.core.Booster object at ...>
See Also
--------
predict
"""
return sync(client.loop, _train, client, params, data, labels, **kwargs)
def _predict_part(part, model=None):
xgb.rabit.init()
dm = xgb.DMatrix(part)
result = model.predict(dm)
xgb.rabit.finalize()
if isinstance(part, pd.DataFrame):
result = pd.Series(result, index=part.index, name='predictions')
return result
def predict(client, model, data):
""" Distributed prediction with XGBoost
Parameters
----------
client: dask.distributed.Client
model: xgboost.Booster
data: dask array or dataframe
Examples
--------
>>> client = Client('scheduler-address:8786') # doctest: +SKIP
>>> test_data = dd.read_csv('s3://...') # doctest: +SKIP
>>> model
<xgboost.core.Booster object at ...>
>>> predictions = predict(client, model, test_data) # doctest: +SKIP
Returns
-------
Dask.dataframe or dask.array, depending on the input data type
See Also
--------
train
"""
if isinstance(data, dd._Frame):
result = data.map_partitions(_predict_part, model=model)
elif isinstance(data, da.Array):
result = data.map_blocks(_predict_part, model=model, dtype=float,
drop_axis=1)
return result
| [
"[email protected]"
] | |
8a98a0654fc13703c66153234d7ba4d3b9c49692 | 4a7b5b3c2819dbf9b2bdfafcdf31745f88cf98b6 | /jaraco/financial/paychex.py | 40affd8d58d470882c7deae625312c3975f07cd9 | [
"MIT"
] | permissive | jaraco/jaraco.financial | 7eb37fddc37e029ac38e162aaaf1a3bd1767a921 | a5d0f996b2ee6bf9051d94d2a5656a1ca3f8b607 | refs/heads/main | 2023-09-01T15:12:26.069574 | 2023-08-06T23:45:05 | 2023-08-06T23:45:05 | 53,203,095 | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 4,841 | py | """
Paychex, when they generate OFX downloads of their 401k account
data, their routine crashes and terminates output when it
encounters a Gain/Loss entry.
This routine takes instead the CSV output and generates a
proper OFX file suitable for importing into your favorite
accounting system.
"""
import itertools
import os
import copy
import decimal
import datetime
import logging
from textwrap import dedent
import autocommand
import ofxparse
import csv
log = logging.getLogger(__name__)
def header(ofx):
for field, value in ofx.headers.items():
yield f'{field}:{value}'
yield dedent(
f"""
<OFX>
<SIGNONMSGSRSV1>
<SONRS>
<STATUS>
<CODE>{ofx.signon.code}</CODE>
<SEVERITY>{ofx.signon.severity}</SEVERITY>
</STATUS>
<DTSERVER>{ofx.signon.dtserver}</DTSERVER>
<LANGUAGE>{ofx.signon.language}</LANGUAGE>
</SONRS>
</SIGNONMSGSRSV1>
"""
).strip()
yield dedent(
f"""
<INVSTMTMSGSRSV1>
<INVSTMTTRNRS>
<TRNUID>1</TRNUID>
<STATUS>
<CODE>0</CODE>
<SEVERITY>INFO</SEVERITY>
</STATUS>
<INVSTMTRS>
<DTASOF>{datetime.date.today().strftime("%Y%m%d")}</DTASOF>
<CURDEF>{ofx.account.statement.currency}</CURDEF>
<INVACCTFROM>
<BROKERID>{ofx.account.brokerid}</BROKERID>
<ACCTID>{ofx.account.account_id}</ACCTID>
</INVACCTFROM>
<INVTRANLIST>
<DTSTART>{ofx.account.statement.start_date.strftime("%Y%m%d")}</DTSTART>
<DTEND>{ofx.account.statement.end_date.strftime("%Y%m%d")}</DTEND>
"""
).strip()
tmpl = dedent(
"""
<{type}MF>
<INV{type}>
<INVTRAN>
<FITID>{abs_amount}{abs_shares}{price:0.6f}{row[Date]}</FITID>
<DTTRADE>{ofx_date}</DTTRADE>
<MEMO>{row[Transaction]}</MEMO>
</INVTRAN>
<SECID>
<UNIQUEID>{security.uniqueid}</UNIQUEID>
<UNIQUEIDTYPE>CUSIP</UNIQUEIDTYPE>
</SECID>
<UNITS>{abs_shares}</UNITS>
<UNITPRICE>{row[Price]}</UNITPRICE>
<TOTAL>{row[Amount]}</TOTAL>
<CURRENCY>
<CURRATE>1.0000</CURRATE>
<CURSYM>USD</CURSYM>
</CURRENCY>
<SUBACCTSEC>OTHER</SUBACCTSEC>
<SUBACCTFUND>OTHER</SUBACCTFUND>
</INV{type}>
<{type}TYPE>{type}</{type}TYPE>
</{type}MF>"""
).strip()
def to_ofx(row, securities):
if row['Shares'] == 'N/A':
return
amount = decimal.Decimal(row['Amount'])
price = decimal.Decimal(row['Price'])
shares = decimal.Decimal(row['Shares'])
type = 'SELL' if shares < 0 else 'BUY'
abs_amount = abs(amount)
abs_shares = abs(shares)
date = datetime.datetime.strptime(row['Date'], '%m/%d/%Y').date()
ofx_date = date.strftime('%Y%m%d')
security = securities[row['Ticker']]
yield tmpl.format_map(locals())
def footer(ofx):
"""
Given the original OFX template, extract the securities list.
"""
yield dedent(
"""
</INVTRANLIST>
</INVSTMTRS>
</INVSTMTTRNRS>
</INVSTMTMSGSRSV1>
<SECLISTMSGSRSV1>
<SECLIST>"""
).strip()
for sec in ofx.security_list:
yield dedent(
f"""
<MFINFO>
<SECINFO>
<SECID>
<UNIQUEID>{sec.uniqueid}</UNIQUEID>
<UNIQUEIDTYPE>CUSIP</UNIQUEIDTYPE>
</SECID>
<SECNAME>{sec.name}</SECNAME>
<TICKER>{sec.ticker}</TICKER>
</SECINFO>
</MFINFO>
"""
).strip()
yield dedent(
"""
</SECLIST>
</SECLISTMSGSRSV1>
</OFX>
"""
).strip()
def remove_bad(data):
"""
PayChex seems to have other behaviors that yield bad data
in the CSV. Log the presence of these rows and exclude
them.
"""
for n, row in enumerate(data, start=1):
if row['Ticker'] == 'null':
log.warning(f"Encountered bad row {n}: {row}")
continue
yield row
@autocommand.autocommand(__name__)
def main(csv_filename, ofx_filename, limit: int = None):
"""
Create a new OFX file based on the CSV and OFX downloads from
PayChex.
"""
logging.basicConfig(level=logging.INFO)
csv_filename = os.path.expanduser(csv_filename)
ofx_filename = os.path.expanduser(ofx_filename)
ofx = ofxparse.OfxParser.parse(open(ofx_filename))
for line in header(ofx):
print(line)
dialect = copy.copy(csv.excel)
dialect.skipinitialspace = True
data = csv.DictReader(open(csv_filename), dialect=dialect)
securities = {security.ticker: security for security in ofx.security_list}
for row in itertools.islice(remove_bad(data), limit):
for line in to_ofx(row, securities):
print(line)
for line in footer(ofx):
print(line)
| [
"[email protected]"
] | |
2cd2c384fdbc60c15b88b6e758d6ca61953489d4 | 70ab3ee89cafa7f4882a6944e6ec335210875d30 | /test_case/Lemi/ArrangeThere/test_arrang_there_group_there_case.py | ca3bea426bd51a0e05a030dc7fe3ad347bd1911c | [] | no_license | SXL5519/caipiao1.0_1 | 3fa1fecd00576c36f37e6af21f0fe9b326289a6a | 2db4387c5bad536cce99417041fbd34a699aa2cc | refs/heads/master | 2021-10-10T07:39:45.127902 | 2019-01-08T09:32:47 | 2019-01-08T09:32:59 | 164,613,453 | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 32,918 | py | from element_operate.Arrange_five.Arrange_five_choosenumber import ArrangeFiveChooseNumber
from element_operate.Arrange_five.Arrange_five_confirm import ArrangeFiveConfirmLottery
from element_operate.Arrange_there.Arrang_there_choosenumber import Arrang_there_choosenumber
from element_operate.UnionLotto.UnionLotto_choosenumber import UnionLottoChooseNumber
from element_operate.UnionLotto.confirm_lottery import ConfirmLottery
from element_operate.homepage import HomePage
from element_operate.login import Login
from test_case.Base.mytest import MyTest
from element_operate.Seven_color.Seven_color_choosenumber import Seven_color_choosenumber
from element_operate.There_D.three_D_choosenumber import There_D_choosenumber
from element_operate.less_pay_sucess import LessPaySucess
from element_operate.PaintBall.paintball_choosenumber import PaintBallChooseNumber
from time import sleep
class Arrang_there_group_there(MyTest):
"""排列三,组三"""
def test_group_there_all_choosenumber_case(self):
"""验证选号页面数字球功能"""
ha = HomePage(self.driver)
hb = Arrang_there_choosenumber(self.driver)
hb1 = ArrangeFiveChooseNumber(self.driver)
hc = ConfirmLottery(self.driver)
hd = ArrangeFiveConfirmLottery(self.driver)
hl = Login(self.driver)
ha.open()
######判断是否出现浮层弹框,如果出现浮层点击X,然后执行下一步操作
ha.Moveable_float_close()
ha.rank_three_link() ####点击排列3
hb.Play() ###点击玩法
hb.Play_Group_there() ####点击组三
hb.group_there()
hb.group_there()
hb.group_theres(4)
hb1.Confirm_nu() # 点击确认选号
mur = hd.Test_note_nu()
self.assertEqual('12', mur) ####断言注数
hc.submit_order_to_station_owner_button() ##点击提交给站主
#hl.new_user_login_tab() # 点击新登录
hl.login() # 输入账号,密码
hc.submit_order_to_station_owner_button() # 点击提交给站主
hc.confirm_and_pay_button() # 点击确认支付
def test_group_there_Screening_ji_case(self):
"""验证选号页面筛选 奇按钮功能"""
ha = HomePage(self.driver)
hb = Arrang_there_choosenumber(self.driver)
hb1 = ArrangeFiveChooseNumber(self.driver)
hc = ConfirmLottery(self.driver)
hd = ArrangeFiveConfirmLottery(self.driver)
hl = Login(self.driver)
ha.open()
######判断是否出现浮层弹框,如果出现浮层点击X,然后执行下一步操作
ha.Moveable_float_close()
ha.rank_three_link() ####点击排列3
hb.Play() ###点击玩法
hb.Play_Group_there() ####点击组三
hb.Screening(0) ###点击筛选中 奇 按钮
hb1.Confirm_nu() # 点击确认选号
mur = hd.Test_note_nu()
self.assertEqual('20', mur) ####断言注数
hc.submit_order_to_station_owner_button() ##点击提交给站主
#hl.new_user_login_tab() # 点击新登录
hl.login() # 输入账号,密码
hc.submit_order_to_station_owner_button() # 点击提交给站主
hc.confirm_and_pay_button() # 点击确认支付
def test_group_there_Screening_ou_case(self):
"""验证选号页面筛选 偶 按钮功能"""
ha = HomePage(self.driver)
hb = Arrang_there_choosenumber(self.driver)
hb1 = ArrangeFiveChooseNumber(self.driver)
hc = ConfirmLottery(self.driver)
hd = ArrangeFiveConfirmLottery(self.driver)
hl = Login(self.driver)
ha.open()
######判断是否出现浮层弹框,如果出现浮层点击X,然后执行下一步操作
ha.Moveable_float_close()
ha.rank_three_link() ####点击排列3
hb.Play() ###点击玩法
hb.Play_Group_there() ####点击组三
hb.Screening(1) ###点击筛选中 偶 按钮
hb1.Confirm_nu() # 点击确认选号
mur = hd.Test_note_nu()
self.assertEqual('20', mur) ####断言注数
hc.submit_order_to_station_owner_button() ##点击提交给站主
#hl.new_user_login_tab() # 点击新登录
hl.login() # 输入账号,密码
hc.submit_order_to_station_owner_button() # 点击提交给站主
hc.confirm_and_pay_button() # 点击确认支付
def test_group_there_Screening_da_case(self):
"""验证选号页面筛选 大 按钮功能"""
ha = HomePage(self.driver)
hb = Arrang_there_choosenumber(self.driver)
hb1 = ArrangeFiveChooseNumber(self.driver)
hc = ConfirmLottery(self.driver)
hd = ArrangeFiveConfirmLottery(self.driver)
hl = Login(self.driver)
ha.open()
######判断是否出现浮层弹框,如果出现浮层点击X,然后执行下一步操作
ha.Moveable_float_close()
ha.rank_three_link() ####点击排列3
hb.Play() ###点击玩法
hb.Play_Group_there() ####点击组三
hb.Screening(2) ###点击筛选中 大 按钮
hb1.Confirm_nu() # 点击确认选号
mur = hd.Test_note_nu()
self.assertEqual('20', mur) ####断言注数
hc.submit_order_to_station_owner_button() ##点击提交给站主
#hl.new_user_login_tab() # 点击新登录
hl.login() # 输入账号,密码
hc.submit_order_to_station_owner_button() # 点击提交给站主
hc.confirm_and_pay_button() # 点击确认支付
def test_group_there_Screening_xi_case(self):
"""验证选号页面筛选 小 按钮功能"""
ha = HomePage(self.driver)
hb = Arrang_there_choosenumber(self.driver)
hb1 = ArrangeFiveChooseNumber(self.driver)
hc = ConfirmLottery(self.driver)
hd = ArrangeFiveConfirmLottery(self.driver)
hl = Login(self.driver)
ha.open()
######判断是否出现浮层弹框,如果出现浮层点击X,然后执行下一步操作
ha.Moveable_float_close()
ha.rank_three_link() ####点击排列3
hb.Play() ###点击玩法
hb.Play_Group_there() ####点击组三
hb.Screening(2) ###点击筛选中 小 按钮
hb1.Confirm_nu() # 点击确认选号
mur = hd.Test_note_nu()
self.assertEqual('20', mur) ####断言注数
hc.submit_order_to_station_owner_button() ##点击提交给站主
#hl.new_user_login_tab() # 点击新登录
hl.login() # 输入账号,密码
hc.submit_order_to_station_owner_button() # 点击提交给站主
hc.confirm_and_pay_button() # 点击确认支付
def test_group_there_Screening_qu_case(self):
"""验证选号页面筛选 全 按钮功能"""
ha = HomePage(self.driver)
hb = Arrang_there_choosenumber(self.driver)
hb1 = ArrangeFiveChooseNumber(self.driver)
hc = ConfirmLottery(self.driver)
hd = ArrangeFiveConfirmLottery(self.driver)
hl = Login(self.driver)
ha.open()
######判断是否出现浮层弹框,如果出现浮层点击X,然后执行下一步操作
ha.Moveable_float_close()
ha.rank_three_link() ####点击排列3
hb.Play() ###点击玩法
hb.Play_Group_there() ####点击组三
hb.Screening(4) ###点击筛选中 全 按钮
hb1.Confirm_nu() # 点击确认选号
mur = hd.Test_note_nu()
self.assertEqual('90', mur) ####断言注数
hc.submit_order_to_station_owner_button() ##点击提交给站主
#hl.new_user_login_tab() # 点击新登录
hl.login() # 输入账号,密码
hc.submit_order_to_station_owner_button() # 点击提交给站主
hc.confirm_and_pay_button() # 点击确认支付
def test_group_there_Screening_qing_case(self):
"""验证选号页面筛选 清 按钮功能"""
ha = HomePage(self.driver)
hb = Arrang_there_choosenumber(self.driver)
hb1 = ArrangeFiveChooseNumber(self.driver)
hc = ConfirmLottery(self.driver)
hd = ArrangeFiveConfirmLottery(self.driver)
hl = Login(self.driver)
ha.open()
######判断是否出现浮层弹框,如果出现浮层点击X,然后执行下一步操作
ha.Moveable_float_close()
ha.rank_three_link() ####点击排列3
hb.Play() ###点击玩法
hb.Play_Group_there() ####点击组三
hb.Screening(5) ###点击筛选中 清 按钮
hb.group_theres(2)
hb1.Confirm_nu() # 点击确认选号
mur = hd.Test_note_nu()
self.assertEqual('2', mur) ####断言注数
hc.submit_order_to_station_owner_button() ##点击提交给站主
#hl.new_user_login_tab() # 点击新登录
hl.login() # 输入账号,密码
hc.submit_order_to_station_owner_button() # 点击提交给站主
hc.confirm_and_pay_button() # 点击确认支付
def test_group_there_Group_delet_case(self):
"""验证选号页面组合显示X 按钮功能"""
ha = HomePage(self.driver)
hb = Arrang_there_choosenumber(self.driver)
hb1 = ArrangeFiveChooseNumber(self.driver)
hc = ConfirmLottery(self.driver)
hd = ArrangeFiveConfirmLottery(self.driver)
hl = Login(self.driver)
ha.open()
######判断是否出现浮层弹框,如果出现浮层点击X,然后执行下一步操作
ha.Moveable_float_close()
ha.rank_three_link() ####点击排列3
hb.Play() ###点击玩法
hb.Play_Group_there() ####点击组三
hb.Screening(4) ###点击筛选中 全 按钮
hb.Group_delet()
hb1.Confirm_nu() # 点击确认选号
mur = hd.Test_note_nu()
self.assertEqual('89', mur) ####断言注数
hc.submit_order_to_station_owner_button() ##点击提交给站主
#hl.new_user_login_tab() # 点击新登录
hl.login() # 输入账号,密码
hc.submit_order_to_station_owner_button() # 点击提交给站主
hc.confirm_and_pay_button() # 点击确认支付
def test_group_there_pause_one_case(self):
"""验证选号页面,点击机选一注功能"""
ha = HomePage(self.driver)
hb = Arrang_there_choosenumber(self.driver)
hb1 = ArrangeFiveChooseNumber(self.driver)
hb2 = UnionLottoChooseNumber(self.driver)
hc = ConfirmLottery(self.driver)
hd = ArrangeFiveConfirmLottery(self.driver)
hl = Login(self.driver)
ha.open()
######判断是否出现浮层弹框,如果出现浮层点击X,然后执行下一步操作
ha.Moveable_float_close()
ha.rank_three_link() ####点击排列3
hb.Play() ###点击玩法
hb.Play_Group_there() ####点击组三
hb2.machine_choose_button() ###点击机选
hb2.machine_choose_one_button() ##点击机选一注
hb1.Confirm_nu() # 点击确认选号
mur = hd.Test_note_nu()
self.assertEqual('2', mur) ####断言注数
hc.submit_order_to_station_owner_button() ##点击提交给站主
#hl.new_user_login_tab() # 点击新登录
hl.login() # 输入账号,密码
hc.submit_order_to_station_owner_button() # 点击提交给站主
hc.confirm_and_pay_button() # 点击确认支付
def test_group_there_pause_five_case(self):
"""验证选号页面,点击机选五注功能"""
ha = HomePage(self.driver)
hb = Arrang_there_choosenumber(self.driver)
hb1 = ArrangeFiveChooseNumber(self.driver)
hb2 = UnionLottoChooseNumber(self.driver)
hc = ConfirmLottery(self.driver)
hd = ArrangeFiveConfirmLottery(self.driver)
hl = Login(self.driver)
ha.open()
######判断是否出现浮层弹框,如果出现浮层点击X,然后执行下一步操作
ha.Moveable_float_close()
ha.rank_three_link() ####点击排列3
hb.Play() ###点击玩法
hb.Play_Group_there() ####点击组三
hb2.machine_choose_button() ###点击机选
hb2.machine_choose_five_button() ##点击机选五注
mur = hd.Test_note_nu()
self.assertEqual('5', mur) ####断言注数
hc.submit_order_to_station_owner_button() ##点击提交给站主
#hl.new_user_login_tab() # 点击新登录
hl.login() # 输入账号,密码
hc.submit_order_to_station_owner_button() # 点击提交给站主
hc.confirm_and_pay_button() # 点击确认支付
def test_group_there_pause_ten_case(self):
"""验证选号页面,点击机选10注功能"""
ha = HomePage(self.driver)
hb = Arrang_there_choosenumber(self.driver)
hb1 = ArrangeFiveChooseNumber(self.driver)
hb2 = UnionLottoChooseNumber(self.driver)
hc = ConfirmLottery(self.driver)
hd = ArrangeFiveConfirmLottery(self.driver)
hl = Login(self.driver)
ha.open()
######判断是否出现浮层弹框,如果出现浮层点击X,然后执行下一步操作
ha.Moveable_float_close()
ha.rank_three_link() ####点击排列3
hb.Play() ###点击玩法
hb.Play_Group_there() ####点击组三
hb2.machine_choose_button() ###点击机选
hb2.machine_choose_ten_button() ##点击机选10注
mur = hd.Test_note_nu()
self.assertEqual('10', mur) ####断言注数
hc.submit_order_to_station_owner_button() ##点击提交给站主
#hl.new_user_login_tab() # 点击新登录
hl.login() # 输入账号,密码
hc.submit_order_to_station_owner_button() # 点击提交给站主
hc.confirm_and_pay_button() # 点击确认支付
def test_group_there_click_too_confirm_case(self):
"""验证选号页面,点击2次确认选号按钮功能"""
ha = HomePage(self.driver)
hb = Arrang_there_choosenumber(self.driver)
hb1 = ArrangeFiveChooseNumber(self.driver)
hb2 = UnionLottoChooseNumber(self.driver)
hc = ConfirmLottery(self.driver)
hd = ArrangeFiveConfirmLottery(self.driver)
hl = Login(self.driver)
ha.open()
######判断是否出现浮层弹框,如果出现浮层点击X,然后执行下一步操作
ha.Moveable_float_close()
ha.rank_three_link() ####点击排列3
hb.Play() ###点击玩法
hb.Play_Group_there() ####点击组三
hb1.Confirm_nu() # 点击确认选号
hb1.Confirm_nu() # 点击确认选号
mur = hd.Test_note_nu()
self.assertEqual('2', mur) ####断言注数
hc.submit_order_to_station_owner_button() ##点击提交给站主
#hl.new_user_login_tab() # 点击新登录
hl.login() # 输入账号,密码
hc.submit_order_to_station_owner_button() # 点击提交给站主
hc.confirm_and_pay_button() # 点击确认支付
def test_group_there_clear_number_case(self):
"""验证选号页面,点击清除选号按钮功能"""
ha = HomePage(self.driver)
hb = Arrang_there_choosenumber(self.driver)
hb1 = ArrangeFiveChooseNumber(self.driver)
hb2 = UnionLottoChooseNumber(self.driver)
hc = ConfirmLottery(self.driver)
hd = ArrangeFiveConfirmLottery(self.driver)
hl = Login(self.driver)
ha.open()
######判断是否出现浮层弹框,如果出现浮层点击X,然后执行下一步操作
ha.Moveable_float_close()
ha.rank_three_link() ####点击排列3
hb.Play() ###点击玩法
hb.Play_Group_there() ####点击组三
hb.group_theres(4)
hb2.clear_number() # 点击清除选号页面
hb1.Confirm_nu() # 点击确认选号
hb1.Confirm_nu() # 点击确认选号
mur = hd.Test_note_nu()
self.assertEqual('2', mur) ####断言注数
hc.submit_order_to_station_owner_button() ##点击提交给站主
#hl.new_user_login_tab() # 点击新登录
hl.login() # 输入账号,密码
hc.submit_order_to_station_owner_button() # 点击提交给站主
hc.confirm_and_pay_button() # 点击确认支付
def test_many_note_many_double_case(self):
"""多注多倍"""
ha = HomePage(self.driver)
hb = Arrang_there_choosenumber(self.driver)
hb1 = UnionLottoChooseNumber(self.driver)
hb2 = ArrangeFiveChooseNumber(self.driver)
hc = ConfirmLottery(self.driver)
hc1 = ArrangeFiveConfirmLottery(self.driver)
hl = Login(self.driver)
hd = LessPaySucess(self.driver)
ha.open()
######判断是否出现浮层弹框,如果出现浮层点击X,然后执行下一步操作
ha.Moveable_float_close()
ha.rank_three_link() ####点击排列3
hb.Play() ###点击玩法
hb.Play_Group_there() ####点击组三
hb.group_theres(2)
hb2.Confirm_nu() # 点击确认选号
hc1.Multiple_input(5) ###点击倍数输入功能
mur = hc1.Test_multiple_show() ##读取倍数
self.assertEqual('5',mur)
mur1 = hc1.Test_note_nu() ##读取注数
self.assertEqual('2', mur1)
hc.submit_order_to_station_owner_button() # 点击提交给站主
#hl.new_user_login_tab() # 点击新登录
hl.login() # 输入账号,密码
hc.submit_order_to_station_owner_button() # 点击提交给站主
hc.confirm_and_pay_button() # 点击确认支付
mur2 = hd.assect_pay() ##读取支付状态文本
self.assertEqual('订单提交成功', mur2)
def test_many_note_many_double_Continue_case(self):
"""多注多倍,继续选号"""
ha = HomePage(self.driver)
hb = Arrang_there_choosenumber(self.driver)
hb1 = UnionLottoChooseNumber(self.driver)
hb2 = ArrangeFiveChooseNumber(self.driver)
hc = ConfirmLottery(self.driver)
hc1 = ArrangeFiveConfirmLottery(self.driver)
hl = Login(self.driver)
hd = LessPaySucess(self.driver)
ha.open()
######判断是否出现浮层弹框,如果出现浮层点击X,然后执行下一步操作
ha.Moveable_float_close()
ha.rank_three_link() ####点击排列3
hb.Play() ###点击玩法
hb.Play_Group_there() ####点击组三
hb.group_theres(2)
hb2.Confirm_nu() # 点击确认选号
mur1 = hc1.Test_note_nu() ##读取注数
self.assertEqual('2', mur1)
hc1.Multiple_input(5) ###点击倍数输入功能
mur = hc1.Test_multiple_show() ##读取倍数
self.assertEqual('5', mur)
hc1.Coun_nu()###点击继续选号
hb.group_theres(2)
hb2.Confirm_nu() # 点击确认选号
mur2 = hc1.Test_multiple_show() ##读取倍数
self.assertEqual('5',mur2)
mur3 = hc1.Test_note_nu() ##读取注数
self.assertEqual('4', mur3)
hc.submit_order_to_station_owner_button() # 点击提交给站主
#hl.new_user_login_tab() # 点击新登录
hl.login() # 输入账号,密码
hc.submit_order_to_station_owner_button() # 点击提交给站主
hc.confirm_and_pay_button() # 点击确认支付
mur4 = hd.assect_pay() ##读取支付状态文本
self.assertEqual('订单提交成功', mur4)
def test_many_note_many_double_Continue_after_case(self):
"""多注多倍,继续选号,复式"""
ha = HomePage(self.driver)
hb = Arrang_there_choosenumber(self.driver)
hb1 = UnionLottoChooseNumber(self.driver)
hb2 = ArrangeFiveChooseNumber(self.driver)
hc = ConfirmLottery(self.driver)
hc1 = ArrangeFiveConfirmLottery(self.driver)
hl = Login(self.driver)
hd = LessPaySucess(self.driver)
ha.open()
######判断是否出现浮层弹框,如果出现浮层点击X,然后执行下一步操作
ha.Moveable_float_close()
ha.rank_three_link() ####点击排列3
hb.Play() ###点击玩法
hb.Play_Group_there() ####点击组三
hb.group_theres(2)
hb2.Confirm_nu() # 点击确认选号
mur1 = hc1.Test_note_nu() ##读取注数
self.assertEqual('2', mur1)
hc1.Multiple_input(5) ###点击倍数输入功能
mur = hc1.Test_multiple_show() ##读取倍数
self.assertEqual('5', mur)
hc1.Coun_nu()###点击继续选号
hb.group_theres(2)
hb2.Confirm_nu() # 点击确认选号
mur2 = hc1.Test_multiple_show() ##读取倍数
self.assertEqual('5',mur2)
mur3= hc1.Test_note_nu() ##读取注数
self.assertEqual('4', mur3)
hc.submit_order_to_station_owner_button() # 点击提交给站主
#hl.new_user_login_tab() # 点击新登录
hl.login() # 输入账号,密码
hc.submit_order_to_station_owner_button() # 点击提交给站主
hc.confirm_and_pay_button() # 点击确认支付
mur4= hd.assect_pay() ##读取支付状态文本
self.assertEqual('订单提交成功', mur4)
'''def test_many_note_many_double_pause_one_case(self):
"""多注多倍,机选一注"""
ha = HomePage(self.driver)
hb = Arrang_there_choosenumber(self.driver)
hb1 = UnionLottoChooseNumber(self.driver)
hb2 = ArrangeFiveChooseNumber(self.driver)
hc = ConfirmLottery(self.driver)
hc1 = ArrangeFiveConfirmLottery(self.driver)
hl = Login(self.driver)
hd = LessPaySucess(self.driver)
ha.open()
######判断是否出现浮层弹框,如果出现浮层点击X,然后执行下一步操作
ha.Moveable_float_close()
ha.rank_three_link() ####点击排列3
hb.Play() ###点击玩法
hb.Play_Group_there() ####点击组三
hb.group_theres(2)
hb2.Confirm_nu() # 点击确认选号
mur1 = hc1.Test_note_nu() ##读取注数
self.assertEqual('2', mur1)
hc1.Multiple_input(5) ###点击倍数输入功能
mur = hc1.Test_multiple_show() ##读取倍数
self.assertEqual('5', mur)
hc1.Pause_one() ###点击机选一注
mur2 = hc1.Test_multiple_show() ##读取倍数
self.assertEqual('5',mur2)
mur3 = hc1.Test_note_nu() ##读取注数
self.assertEqual('3', mur3)
hc.submit_order_to_station_owner_button() # 点击提交给站主
#hl.new_user_login_tab() # 点击新登录
hl.login() # 输入账号,密码
hc.submit_order_to_station_owner_button() # 点击提交给站主
hc.confirm_and_pay_button() # 点击确认支付
mur4= hd.assect_pay() ##读取支付状态文本
self.assertEqual('订单提交成功', mur4)'''
def test_many_note_many_double_pause_five_case(self):
"""多注多倍,机选五注"""
ha = HomePage(self.driver)
hb = Arrang_there_choosenumber(self.driver)
hb1 = UnionLottoChooseNumber(self.driver)
hb2 = ArrangeFiveChooseNumber(self.driver)
hc = ConfirmLottery(self.driver)
hc1 = ArrangeFiveConfirmLottery(self.driver)
hl = Login(self.driver)
hd = LessPaySucess(self.driver)
ha.open()
######判断是否出现浮层弹框,如果出现浮层点击X,然后执行下一步操作
ha.Moveable_float_close()
ha.rank_three_link() ####点击排列3
hb.Play() ###点击玩法
hb.Play_Group_there() ####点击组三
hb.group_theres(2)
hb2.Confirm_nu() # 点击确认选号
mur1 = hc1.Test_note_nu() ##读取注数
self.assertEqual('2', mur1)
hc1.Multiple_input(5) ###点击倍数输入功能
mur = hc1.Test_multiple_show() ##读取倍数
self.assertEqual('5', mur)
hc1.Pause_five() ###点击机选五注
mur2 = hc1.Test_multiple_show() ##读取倍数
self.assertEqual('5',mur2)
mur3 = hc1.Test_note_nu() ##读取注数
self.assertEqual('7', mur3)
hc.submit_order_to_station_owner_button() # 点击提交给站主
#hl.new_user_login_tab() # 点击新登录
hl.login() # 输入账号,密码
hc.submit_order_to_station_owner_button() # 点击提交给站主
hc.confirm_and_pay_button() # 点击确认支付
mur4 = hd.assect_pay() ##读取支付状态文本
self.assertEqual('订单提交成功', mur4)
'''def test_many_note_many_double_pause_period_one_case(self):
"""多注多倍,机选一注,追期"""
ha = HomePage(self.driver)
hb = Arrang_there_choosenumber(self.driver)
hb1 = UnionLottoChooseNumber(self.driver)
hb2 = ArrangeFiveChooseNumber(self.driver)
hc = ConfirmLottery(self.driver)
hc1 = ArrangeFiveConfirmLottery(self.driver)
hl = Login(self.driver)
hd = LessPaySucess(self.driver)
ha.open()
######判断是否出现浮层弹框,如果出现浮层点击X,然后执行下一步操作
ha.Moveable_float_close()
ha.rank_three_link() ####点击排列3
hb.Play() ###点击玩法
hb.Play_Group_there() ####点击组三
hb.group_theres(2)
hb2.Confirm_nu() # 点击确认选号
mur1 = hc1.Test_note_nu() ##读取注数
self.assertEqual('2', mur1)
hc1.Multiple_input(5) ###点击倍数输入功能
mur = hc1.Test_multiple_show() ##读取倍数
self.assertEqual('5', mur)
hc1.Pause_one() ###点击机选一注
hc.chase_ticket_input(3) ##输入追期
nu = hc1.Test_period_show()
self.assertEqual('3', nu)
mur2 = hc1.Test_multiple_show() ##读取倍数
self.assertEqual('5',mur2)
mur3 = hc1.Test_note_nu() ##读取注数
self.assertEqual('3', mur3)
hc.submit_order_to_station_owner_button() # 点击提交给站主
#hl.new_user_login_tab() # 点击新登录
hl.login() # 输入账号,密码
hc.submit_order_to_station_owner_button() # 点击提交给站主
hc.confirm_and_pay_button() # 点击确认支付
mur4 = hd.assect_pay() ##读取支付状态文本
self.assertEqual('订单提交成功', mur4)'''
def test_many_note_many_double_pause_five_period_case(self):
"""多注多倍,机选五注,追期"""
ha = HomePage(self.driver)
hb = Arrang_there_choosenumber(self.driver)
hb1 = UnionLottoChooseNumber(self.driver)
hb2 = ArrangeFiveChooseNumber(self.driver)
hc = ConfirmLottery(self.driver)
hc1 = ArrangeFiveConfirmLottery(self.driver)
hl = Login(self.driver)
hd = LessPaySucess(self.driver)
ha.open()
######判断是否出现浮层弹框,如果出现浮层点击X,然后执行下一步操作
ha.Moveable_float_close()
ha.rank_three_link() ####点击排列3
hb.Play() ###点击玩法
hb.Play_Group_there() ####点击组三
hb.group_theres(2)
hb2.Confirm_nu() # 点击确认选号
mur1 = hc1.Test_note_nu() ##读取注数
self.assertEqual('2', mur1)
hc1.Multiple_input(5) ###点击倍数输入功能
mur = hc1.Test_multiple_show() ##读取倍数
self.assertEqual('5', mur)
hc1.Pause_five() ###点击机选五注
hc.chase_ticket_input(3) ##输入追期
nu = hc1.Test_period_show()
self.assertEqual('3', nu)
mur2 = hc1.Test_multiple_show() ##读取倍数
self.assertEqual('5',mur2)
mur3 = hc1.Test_note_nu() ##读取注数
self.assertEqual('7', mur3)
hc.submit_order_to_station_owner_button() # 点击提交给站主
#hl.new_user_login_tab() # 点击新登录
hl.login() # 输入账号,密码
hc.submit_order_to_station_owner_button() # 点击提交给站主
hc.confirm_and_pay_button() # 点击确认支付
mur4 = hd.assect_pay() ##读取支付状态文本
self.assertEqual('订单提交成功', mur4)
def test_seven_color_Del_all_nu_cancel_case(self):
"""验证确认投注页面,点击删除选号图标功能"""
ha = HomePage(self.driver)
hb = Arrang_there_choosenumber(self.driver)
hb1 = UnionLottoChooseNumber(self.driver)
hb2 = ArrangeFiveChooseNumber(self.driver)
hc = ConfirmLottery(self.driver)
hc1 = ArrangeFiveConfirmLottery(self.driver)
hl = Login(self.driver)
hd = LessPaySucess(self.driver)
ha.open()
######判断是否出现浮层弹框,如果出现浮层点击X,然后执行下一步操作
ha.Moveable_float_close()
ha.rank_three_link() ####点击排列3
hb.Play() ###点击玩法
hb.Play_Group_six() ####点击组六
hb.group_sixs(3)
hb2.Confirm_nu() # 点击确认选号
hc.delete_all_num_button() ###点击清除所有选号
hc.cancel_delete_button() # 点击取消
mur=hc.confirm_num_page_text()
self.assertEqual('提交订单给站主',mur)
def test_seven_color_Del_all_nu_case(self):
"""验证确认投注页面,点击删除选号图标功能"""
ha = HomePage(self.driver)
hb = Arrang_there_choosenumber(self.driver)
hb1 = There_D_choosenumber(self.driver)
hb2 = ArrangeFiveChooseNumber(self.driver)
hc = ConfirmLottery(self.driver)
hc1 = ArrangeFiveConfirmLottery(self.driver)
hl = Login(self.driver)
hd = LessPaySucess(self.driver)
ha.open()
######判断是否出现浮层弹框,如果出现浮层点击X,然后执行下一步操作
ha.Moveable_float_close()
ha.rank_three_link() ####点击排列3
hb.Play() ###点击玩法
hb.Play_Group_six() ####点击组六
hb.group_sixs(3)
hb2.Confirm_nu() # 点击确认选号
hc.delete_all_num_button() ###点击清除所有选号
mur=hb1.Clear()
self.assertEqual('清空',mur)
def test_seven_color_Del_all_nu_ok_case(self):
"""验证确认投注页面,点击删除选号,点击确定"""
ha = HomePage(self.driver)
hb = Arrang_there_choosenumber(self.driver)
hb1 = Seven_color_choosenumber(self.driver)
hb2 = ArrangeFiveChooseNumber(self.driver)
hc = ConfirmLottery(self.driver)
hc1 = PaintBallChooseNumber(self.driver)
hl = Login(self.driver)
hd = LessPaySucess(self.driver)
ha.open()
######判断是否出现浮层弹框,如果出现浮层点击X,然后执行下一步操作
ha.Moveable_float_close()
ha.rank_three_link() ####点击排列3
hb.Play() ###点击玩法
hb.Play_Group_six() ####点击组六
hb.group_sixs(3)
hb2.Confirm_nu() # 点击确认选号
hc.delete_all_num_button() ###点击清除所有选号
hc.confirm_delete_button() # 点击确定
mur = hc1.Play_fb()
self.assertEqual('玩\n法', mur)
def test_arrany_there_Continue_switch_play_case(self):
""",组三,继续选号,切换玩法为直选"""
ha = HomePage(self.driver)
hb = Arrang_there_choosenumber(self.driver)
hb1 = Seven_color_choosenumber(self.driver)
hb2 = ArrangeFiveChooseNumber(self.driver)
hc = ConfirmLottery(self.driver)
hc1 = ArrangeFiveConfirmLottery(self.driver)
hl = Login(self.driver)
hd = LessPaySucess(self.driver)
ha.open()
######判断是否出现浮层弹框,如果出现浮层点击X,然后执行下一步操作
ha.Moveable_float_close()
ha.rank_three_link() ####点击排列3
hb.Play() ###点击玩法
hb.Play_Group_six() ####点击组六
hb.group_sixs(3)
hb2.Confirm_nu() # 点击确认选号
hc1.Coun_nu()###点击继续选号
hb.Play() ###点击玩法
hb.Play_Group_there() ####点击组三
hb.Switch_play_ok()##点击确定
hb.group_theres(4) ###组三,选择4个号码
hb2.Confirm_nu() # 点击确认选号
hc.submit_order_to_station_owner_button() # 点击提交给站主
#hl.new_user_login_tab() # 点击新登录
hl.login() # 输入账号,密码
hc.submit_order_to_station_owner_button() # 点击提交给站主
hc.confirm_and_pay_button() # 点击确认支付
mur1 = hd.assect_pay() ##读取支付状态文本
self.assertEqual('订单提交成功', mur1) | [
"[email protected]"
] | |
efbf8677c2ce4ad6ed0ecb013edc7f601f9907bf | 978248bf0f275ae688f194593aa32c267832b2b6 | /xlsxwriter/test/styles/test_write_cell_style.py | e348931f5c8422daa52141da17985d77bc95e182 | [
"BSD-2-Clause-Views"
] | permissive | satish1337/XlsxWriter | b0c216b91be1b74d6cac017a152023aa1d581de2 | 0ab9bdded4f750246c41a439f6a6cecaf9179030 | refs/heads/master | 2021-01-22T02:35:13.158752 | 2015-03-31T20:32:28 | 2015-03-31T20:32:28 | 33,300,989 | 1 | 0 | null | null | null | null | UTF-8 | Python | false | false | 764 | py | ###############################################################################
#
# Tests for XlsxWriter.
#
# Copyright (c), 2013-2015, John McNamara, [email protected]
#
import unittest
from ...compatibility import StringIO
from ...styles import Styles
class TestWriteCellStyle(unittest.TestCase):
"""
Test the Styles _write_cell_style() method.
"""
def setUp(self):
self.fh = StringIO()
self.styles = Styles()
self.styles._set_filehandle(self.fh)
def test_write_cell_style(self):
"""Test the _write_cell_style() method"""
self.styles._write_cell_style()
exp = """<cellStyle name="Normal" xfId="0" builtinId="0"/>"""
got = self.fh.getvalue()
self.assertEqual(got, exp)
| [
"[email protected]"
] | |
7878d5a7c827bbac0814c83d3388cc54cc73f6f1 | c21faf85627b1cfd96494aac73cc40e5f11ebb46 | /results/test_174.py | d0d0deb96fda2b6c3e938e71b6ebdf633b711c0b | [] | no_license | ekkya/Cyclomatic-Complexity | d02c61e009087e7d51738e60605875741532b878 | 172db2efdd974f5abad964e335552aec974b47cb | refs/heads/master | 2021-08-28T17:13:14.718314 | 2017-12-12T22:04:13 | 2017-12-12T22:04:13 | 112,042,202 | 0 | 1 | null | null | null | null | UTF-8 | Python | false | false | 101,260 | py | """
Author: Ankit Agarwal (ankit167)
Usage: python google.py <keyword>
Description: Script googles the keyword and opens
top 5 (max) search results in separate
tabs in the browser
Version: 1.0
"""
import webbrowser, sys, pyperclip, requests, bs4
def main():
if len(sys.argv) > 1:
keyword = ' '.join(sys.argv[1:])
else:
# if no keyword is entered, the script would search for the keyword
# copied in the clipboard
keyword = pyperclip.paste()
res=requests.get('http://google.com/search?q='+ keyword)
res.raise_for_status()
soup = bs4.BeautifulSoup(res.text)
linkElems = soup.select('.r a')
numOpen = min(5, len(linkElems))
for i in range(numOpen):
webbrowser.open('http://google.com' + linkElems[i].get('href'))
if __name__ == '__main__':
main()"""Get the number of each character in any given text.
Inputs:
A txt file -- You will be asked for an input file. Simply input the name
of the txt file in which you have the desired text.
"""
import pprint
import collections
def main():
file_input = input('File Name: ')
with open(file_input, 'r') as info:
count = collections.Counter(info.read().upper())
value = pprint.pformat(count)
print(value)
if __name__ == "__main__":
main()# Script Name : pscheck.py
# Author : Craig Richards
# Created : 19th December 2011
# Last Modified : 17th June 2013
# Version : 1.1
# Modifications : 1.1 - 17/06/13 - CR - Changed to functions, and check os before running the program
# Description : Process check on Nix boxes, diplsay formatted output from ps command
import commands, os, string
def ps():
program = raw_input("Enter the name of the program to check: ")
try:
#perform a ps command and assign results to a list
output = commands.getoutput("ps -f|grep " + program)
proginfo = string.split(output)
#display results
print "\n\
Full path:\t\t", proginfo[5], "\n\
Owner:\t\t\t", proginfo[0], "\n\
Process ID:\t\t", proginfo[1], "\n\
Parent process ID:\t", proginfo[2], "\n\
Time started:\t\t", proginfo[4]
except:
print "There was a problem with the program."
def main():
if os.name == "posix": # Unix/Linux/MacOS/BSD/etc
ps() # Call the function
elif os.name in ("nt", "dos", "ce"): # if the OS is windows
print "You need to be on Linux or Unix to run this"
if __name__ == '__main__':
main()from bs4 import BeautifulSoup
import datetime
import mechanize
import urllib2
# Create a Browser
b = mechanize.Browser()
# Disable loading robots.txt
b.set_handle_robots(False)
b.addheaders = [('User-agent',
'Mozilla/4.0 (compatible; MSIE 5.0; Windows 98;)')]
# Navigate
b.open('http://cbseresults.nic.in/jee/jee_2015.htm')
# Choose a form
b.select_form(nr=0)
# Fill it out
b['regno'] = '37000304'
currentdate = datetime.date(1997,3,10)
enddate = datetime.date(1998,4,1)
while currentdate <= enddate:
ct=0
#print currentdate
yyyymmdd = currentdate.strftime("%Y/%m/%d")
ddmmyyyy = yyyymmdd[8:] + "/" + yyyymmdd[5:7] + "/" +yyyymmdd[:4]
print(ddmmyyyy)
b.open('http://cbseresults.nic.in/jee/jee_2015.htm')
b.select_form(nr=0)
b['regno'] = '37000304'
b['dob'] = ddmmyyyy
fd = b.submit()
#print(fd.read())
soup = BeautifulSoup(fd.read(),'html.parser')
for writ in soup.find_all('table'):
ct = ct + 1;
#print (ct)
if ct == 6:
print("---fail---")
else:
print("--true--")
break;
currentdate += datetime.timedelta(days=1)
#print fd.read()# Script Name : new_script.py
# Author : Craig Richards
# Created : 20th November 2012
# Last Modified :
# Version : 1.0
# Modifications :
# Description : This will create a new basic template for a new script
import os # Load the library module
import sys # Load the library module
import datetime # Load the library module
text = '''You need to pass an argument for the new script you want to create, followed by the script name. You can use
-python : Python Script
-bash : Bash Script
-ksh : Korn Shell Script
-sql : SQL Script'''
if len(sys.argv) < 3:
print text
sys.exit()
if '-h' in sys.argv or '--h' in sys.argv or '-help' in sys.argv or '--help' in sys.argv:
print text
sys.exit()
else:
if '-python' in sys.argv[1]:
config_file = "python.cfg"
extension = ".py"
elif '-bash' in sys.argv[1]:
config_file = "bash.cfg"
extension = ".bash"
elif '-ksh' in sys.argv[1]:
config_file = "ksh.cfg"
extension = ".ksh"
elif '-sql' in sys.argv[1]:
config_file = "sql.cfg"
extension = ".sql"
else:
print 'Unknown option - ' + text
sys.exit()
confdir = os.getenv("my_config")
scripts = os.getenv("scripts")
dev_dir = "Development"
newfile = sys.argv[2]
output_file = (newfile + extension)
outputdir = os.path.join(scripts,dev_dir)
script = os.path.join(outputdir, output_file)
input_file = os.path.join(confdir,config_file)
old_text = " Script Name : "
new_text = (" Script Name : " + output_file)
if not(os.path.exists(outputdir)):
os.mkdir(outputdir)
newscript = open(script, 'w')
input = open(input_file, 'r')
today = datetime.date.today()
old_date = " Created :"
new_date = (" Created : " + today.strftime("%d %B %Y"))
for line in input:
line = line.replace(old_text, new_text)
line = line.replace(old_date, new_date)
newscript.write(line)
# Script Name : osinfo.py
# Authors : {'geekcomputers': 'Craig Richards', 'dmahugh': 'Doug Mahugh','rutvik1010':'Rutvik Narayana Nadimpally','y12uc231': 'Satyapriya Krishna', 'minto4644':'Mohit Kumar'}
# Created : 5th April 2012
# Last Modified : July 19 2016
# Version : 1.0
# Modification 1 : Changed the profile to list again. Order is important. Everytime we run script we don't want to see different ordering.
# Modification 2 : Fixed the AttributeError checking for all properties. Using hasttr().
# Modification 3 : Removed ': ' from properties inside profile.
# Description : Displays some information about the OS you are running this script on
import platform as pl
profile = [
'architecture',
'linux_distribution',
'mac_ver',
'machine',
'node',
'platform',
'processor',
'python_build',
'python_compiler',
'python_version',
'release',
'system',
'uname',
'version',
]
class bcolors:
HEADER = '\033[95m'
OKBLUE = '\033[94m'
OKGREEN = '\033[92m'
WARNING = '\033[93m'
FAIL = '\033[91m'
ENDC = '\033[0m'
BOLD = '\033[1m'
UNDERLINE = '\033[4m'
for key in profile:
if hasattr(pl, key):
print(key + bcolors.BOLD + ": " + str(getattr(pl, key)()) + bcolors.ENDC)
# author:[email protected]
#!/usr/bin/env python
# -*- coding=utf-8 -*-
import os
# define the result filename
resultfile = 'result.csv'
# the merge func
def merge():
"""merge csv files to one file"""
# use list save the csv files
csvfiles = [f for f in os.listdir('.') if f != resultfile and f.split('.')[1]=='csv']
# open file to write
with open(resultfile,'w') as writefile:
for csvfile in csvfiles:
with open(csvfile) as readfile:
print('File {} readed.'.format(csvfile))
# do the read and write
writefile.write(readfile.read()+'\n')
print('\nFile {} wrote.'.format(resultfile))
# the main program
if __name__ == '__main__':
merge()import mechanize
import re
import urllib2
from random import *
br=mechanize.Browser()
br.addheaders = [('User-Agent','Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/37.0.2062.120 Safari/537.36')]
br.set_handle_robots(False)
#For page exploration
page=raw_input('Enter Page No:')
#print type(page)
p=urllib2.Request('https://www.google.co.in/search?q=gate+psu+2017+ext:pdf&start='+page)
ht=br.open(p)
text='<cite\sclass="_Rm">(.+?)</cite>'
patt=re.compile(text)
h=ht.read()
urls=re.findall(patt,h)
int=0
while int<len(urls):
urls[int]=urls[int].replace("<b>","")
urls[int]=urls[int].replace("</b>","")
int=int+1
print urls
for url in urls:
try:
temp=url.split("/")
q=temp[len(temp)-1]
if "http" in url:
r=urllib2.urlopen(url)
else:
r=urllib2.urlopen("http://"+url)
file=open('psu2'+q+'.pdf','wb')
file.write(r.read())
file.close()
print "Done"
except urllib2.URLError as e:
print "Sorry there exists a problem with this URL Please Download this Manually "+str(url)
# Script Name : logs.py
# Author : Craig Richards
# Created : 13th October 2011
# Last Modified : 14 February 2016
# Version : 1.2
#
# Modifications : 1.1 - Added the variable zip_program so you can set it for the zip program on whichever OS, so to run on a different OS just change the locations of these two variables.
# : 1.2 - Tidy up comments and syntax
#
# Description : This script will search for all *.log files in the given directory, zip them using the program you specify and then date stamp them
import os # Load the Library Module
from time import strftime # Load just the strftime Module from Time
logsdir = "c:\puttylogs" # Set the Variable logsdir
zip_program = "zip.exe" # Set the Variable zip_program - 1.1
for files in os.listdir(logsdir): # Find all the files in the directory
if files.endswith(".log"): # Check to ensure the files in the directory end in .log
files1 = files + "." + strftime("%Y-%m-%d") + ".zip" # Create the Variable files1, this is the files in the directory, then we add a suffix with the date and the zip extension
os.chdir(logsdir) # Change directory to the logsdir
os.system(zip_program + " " + files1 +" "+ files) # Zip the logs into dated zip files for each server. - 1.1
os.remove(files) # Remove the original log files"""
Author: Shreyas Daniel (shreydan)
Install: tweepy - "pip install tweepy"
API: Create a twitter app "apps.twitter.com" to get your OAuth requirements.
Version: 1.0
Tweet text and pics directly from the terminal.
"""
import tweepy, os
def getStatus():
lines = []
while True:
line = raw_input()
if line:
lines.append(line)
else:
break
status = '\n'.join(lines)
return status
def tweetthis(type):
if type == "text":
print "Enter your tweet "+user.name
tweet = getStatus()
try:
api.update_status(tweet)
except Exception as e:
print e
return
elif type == "pic":
print "Enter pic path "+user.name
pic = os.path.abspath(raw_input())
print "Enter status "+user.name
title = getStatus()
try:
api.update_with_media(pic, status=title)
except Exception as e:
print e
return
print "\n\nDONE!!"
def initialize():
global api, auth, user
ck = "here" # consumer key
cks = "here" # consumer key SECRET
at = "here" # access token
ats = "here" # access token SECRET
auth = tweepy.OAuthHandler(ck,cks)
auth.set_access_token(at,ats)
api = tweepy.API(auth)
user = api.me()
def main():
doit = int(raw_input("\n1. text\n2. picture\n"))
initialize()
if doit == 1:
tweetthis("text")
elif doit == 2:
tweetthis("pic")
else:
print "OK, Let's try again!"
main()
main()# Script Name : dice.py
# Author : Craig Richards
# Created : 05th February 2017
# Last Modified :
# Version : 1.0
# Modifications :
# Description : This will randomly select two numbers, like throwing dice, you can change the sides of the dice if you wish
import random
class Die(object):
#A dice has a feature of number about how many sides it has when it's established,like 6.
def __init__(self):
self.sides=6
"""because a dice contains at least 4 planes.
So use this method to give it a judgement when you need to change the instance attributes."""
def set_sides(self,sides_change):
if self.sides_change>=4:
self.sides=self.sides_change
print("change sides!")
else:
print("wrong sides!")
def roll(self):
return random.randint(1, self.sides)
d = Die()
d1 = Die()
d.set_sides(4)
d1.set_sides(4)
print (d.roll(), d1.roll())from sys import argv # import argment variable
script, rows, columns = argv #define rows and columns for the table and assign them to the argument variable
def table(rows, columns):
for i in range(1, int(rows) + 1 ): #it's safe to assume that the user would mean 12 rows when they provide 12 as an argument, b'coz 12 will produce 11 rows
print "\t", i,
print "\n\n"
for i in range(1, int(columns) + 1 ):
print i,
for j in range(1, int(rows) + 1 ):
print "\t",i*j,
print "\n\n"
table(rows, columns)import os
import sys
import shutil
Music = ['MP3', 'WAV', 'WMA', 'MKA', 'AAC', 'MID', 'RA', 'RAM', 'RM', 'OGG']
Codes = ['CPP', 'RB', 'PY', 'HTML', 'CSS', 'JS']
Compressed = ['RAR', 'JAR', 'ZIP', 'TAR', 'MAR', 'ISO', 'LZ', '7ZIP', 'TGZ', 'GZ', 'BZ2']
Documents = ['DOC', 'DOCX', 'PPT', 'PPTX', 'PAGES', 'PDF', 'ODT', 'ODP', 'XLSX', 'XLS', 'ODS', 'TXT', 'IN', 'OUT', 'MD']
Images = ['JPG', 'JPEG', 'GIF', 'PNG', 'SVG']
Executables = ['LNK','DEB', 'EXE', 'SH', 'BUNDLE']
Video = ['FLV', 'WMV', 'MOV', 'MP4', 'MPEG', '3GP', 'MKV','AVI']
def getVideo():
return Video
def getMusic():
return Music
def getCodes():
return Codes
def getCompressed():
return Compressed
def getImages():
return Images
def getExe():
return Executables
def getDoc():
return Documents
# taking the location of the Folder to Arrange
try:
arrange_dir = str(sys.argv[1])
except IndexError:
arrange_dir = str(raw_input("Enter the Path of directory: "))
# when we make a folder that already exist then WindowsError happen
# changing directory may give WindowsError
def change(direc):
try:
os.chdir(direc)
#print "path changed"
except WindowsError:
print "Error! Cannot change the Directory"
print "Enter a valid directory!"
direc = str(raw_input("Enter the Path of directory: "))
change(direc)
change(arrange_dir)
# now we will get the list of all the directories in the folder
list_dir = os.listdir(os.getcwd())
#print list_dir
#check_Folder = False # for organising Folders
check_Music = False
check_Video = False
check_Exe = False
check_Code = False
check_Compressed = False
check_Img = False
check_Docs = False
main_names = ['Video','Folders','Images','Documents','Music','Codes','Executables','Compressed']
for name in list_dir:
#print name.split('.')
if len(name.split('.')) == 2:
if name.split('.')[1].upper() in getVideo():
try:
os.mkdir("Video")
print "Video Folder Created"
except WindowsError:
print "Images Folder Exists"
old_dir = arrange_dir + "\\" + name
new_dir = arrange_dir + "\Video"
os.chdir(new_dir)
shutil.move(old_dir, new_dir + "\\" + name)
print os.getcwd()
os.chdir(arrange_dir)
#print "It is a folder"
elif name.split('.')[1].upper() in getImages():
try:
os.mkdir("Images")
print "Images Folder Created"
except WindowsError:
print "Images Folder Exists"
old_dir = arrange_dir + "\\" + name
new_dir = arrange_dir + "\Images"
os.chdir(new_dir)
shutil.move(old_dir, new_dir + "\\" + name)
print os.getcwd()
os.chdir(arrange_dir)
#print "It is a folder"
elif name.split('.')[1].upper() in getMusic():
try:
os.mkdir("Music")
print "Music Folder Created"
except WindowsError:
print "Music Folder Exists"
old_dir = arrange_dir + "\\" + name
new_dir = arrange_dir + "\Music"
os.chdir(new_dir)
shutil.move(old_dir, new_dir + "\\" + name)
print os.getcwd()
os.chdir(arrange_dir)
#print "It is a folder"
elif name.split('.')[1].upper() in getDoc():
try:
os.mkdir("Documents")
print "Documents Folder Created"
except WindowsError:
print "Documents Folder Exists"
old_dir = arrange_dir + "\\" + name
new_dir = arrange_dir + "\Documents"
os.chdir(new_dir)
shutil.move(old_dir, new_dir + "\\" + name)
print os.getcwd()
os.chdir(arrange_dir)
#print "It is a folder"
elif name.split('.')[1].upper() in getCodes():
try:
os.mkdir("Codes")
print "Codes Folder Created"
except WindowsError:
print "Codes Folder Exists"
old_dir = arrange_dir + "\\" + name
new_dir = arrange_dir + "\Codes"
os.chdir(new_dir)
shutil.move(old_dir, new_dir + "\\" + name)
print os.getcwd()
os.chdir(arrange_dir)
#print "It is a folder"
elif name.split('.')[1].upper() in getCompressed():
try:
os.mkdir("Compressed")
print "Compressed Folder Created"
except WindowsError:
print "Compressed Folder Exists"
old_dir = arrange_dir + "\\" + name
new_dir = arrange_dir + "\Compressed"
os.chdir(new_dir)
shutil.move(old_dir, new_dir + "\\" + name)
print os.getcwd()
os.chdir(arrange_dir)
#print "It is a folder"
elif name.split('.')[1].upper() in getExe():
try:
os.mkdir("Executables")
print "Executables Folder Created"
except WindowsError:
print "Executables Folder Exists"
old_dir = arrange_dir + "\\" + name
new_dir = arrange_dir + "\Executables"
os.chdir(new_dir)
shutil.move(old_dir, new_dir + "\\" + name)
print os.getcwd()
os.chdir(arrange_dir)
#print "It is a folder"
else:
if name not in main_names:
try:
os.mkdir("Folders")
print "Folders Folder Created"
except WindowsError:
print "Folders Folder Exists"
old_dir = arrange_dir + "\\" + name
new_dir = arrange_dir + "\Folders"
os.chdir(new_dir)
shutil.move(old_dir, new_dir + "\\" + name)
print os.getcwd()
os.chdir(arrange_dir)
print "Done Arranging Files and Folder in your specified directory""""
Written by: Shreyas Daniel - github.com/shreydan
Written on: 26 April 2017
Description: Download latest XKCD Comic with this program.
NOTE:
if this script is launched from the cloned repo, a new folder is created.
Please move the file to another directory to avoid messing with the folder structure.
"""
import requests
from lxml import html
import urllib.request
import os
def main():
# opens xkcd.com
try:
page = requests.get("https://www.xkcd.com")
except requests.exceptions.RequestException as e:
print (e)
exit()
# parses xkcd.com page
tree = html.fromstring(page.content)
# finds image src url
image_src = tree.xpath(".//*[@id='comic']/img/@src")[0]
image_src = "https:" + str(image_src)
# gets comic name from the image src url
comic_name = image_src.split('/')[-1]
comic_name = comic_name[:-4]
# save location of comic
comic_location = os.getcwd() + '/comics/'
# checks if save location exists else creates
if not os.path.exists(comic_location):
os.makedirs(comic_location)
# creates final comic location including name of the comic
comic_location = comic_location + comic_name
# downloads the comic
urllib.request.urlretrieve(image_src, comic_location)
if __name__ == "__main__":
main()# Script Name : check_for_sqlite_files.py
# Author : Craig Richards
# Created : 07 June 2013
# Last Modified : 14 February 2016
# Version : 1.0.1
# Modifications : 1.0.1 - Remove unecessary line and variable on Line 21
# Description : Scans directories to check if there are any sqlite files in there
from __future__ import print_function
import os
def isSQLite3(filename):
from os.path import isfile, getsize
if not isfile(filename):
return False
if getsize(filename) < 100: # SQLite database file header is 100 bytes
return False
else:
fd = open(filename, 'rb')
Header = fd.read(100)
fd.close()
if Header[0:16] == 'SQLite format 3\000':
return True
else:
return False
log=open('sqlite_audit.txt','w')
for r,d,f in os.walk(r'.'):
for files in f:
if isSQLite3(files):
print(files)
print("[+] '%s' **** is a SQLITE database file **** " % os.path.join(r,files))
log.write("[+] '%s' **** is a SQLITE database file **** " % files+'\n')
else:
log.write("[-] '%s' is NOT a sqlite database file" % os.path.join(r,files)+'\n')
log.write("[-] '%s' is NOT a sqlite database file" % files+'\n')# Script Name : create_dir_if_not_there.py
# Author : Craig Richards
# Created : 09th January 2012
# Last Modified : 22nd October 2015
# Version : 1.0.1
# Modifications : Added exceptions
# : 1.0.1 Tidy up comments and syntax
#
# Description : Checks to see if a directory exists in the users home directory, if not then create it
import os # Import the OS module
MESSAGE = 'The directory already exists.'
TESTDIR = 'testdir'
try:
home = os.path.expanduser("~") # Set the variable home by expanding the user's set home directory
print(home) # Print the location
if not os.path.exists(os.path.join(home, TESTDIR)): # os.path.join() for making a full path safely
os.makedirs(os.path.join(home, TESTDIR)) # If not create the directory, inside their home directory
else:
print(MESSAGE)
except Exception as e:
print(e)
# Script Name : move_files_over_x_days.py
# Author : Craig Richards
# Created : 8th December 2011
# Last Modified :
# Version : 1.0
# Modifications :
# Description : This will move all the files from the src directory that are over 240 days old to the destination directory.
import shutil
import sys
import time
import os
src = 'u:\\test' # Set the source directory
dst = 'c:\\test' # Set the destination directory
now = time.time() # Get the current time
for f in os.listdir(src): # Loop through all the files in the source directory
if os.stat(f).st_mtime < now - 240 * 86400: # Work out how old they are, if they are older than 240 days old
if os.path.isfile(f): # Check it's a file
shutil.move(f, dst) # Move the files
# Script Name : sqlite_table_check.py
# Author : Craig Richards
# Created : 07 June 2013
# Last Modified :
# Version : 1.0
# Modifications :
# Description : Checks the main SQLITE database to ensure all the tables should exist
import sqlite3
import sys
import os
dropbox = os.getenv("dropbox")
config = os.getenv("my_config")
dbfile = ("Databases\jarvis.db")
listfile = ("sqlite_master_table.lst")
master_db = os.path.join(dropbox, dbfile)
config_file = os.path.join(config, listfile)
tablelist = open(config_file,'r');
conn = sqlite3.connect(master_db)
cursor = conn.cursor()
cursor.execute('SELECT SQLITE_VERSION()')
data = cursor.fetchone()
if str(data) == "(u'3.6.21',)":
print ("\nCurrently " + master_db + " is on SQLite version: %s" % data + " - OK -\n")
else:
print ("\nDB On different version than master version - !!!!! \n")
conn.close()
print ("\nCheckling " + master_db + " against " + config_file + "\n")
for table in tablelist.readlines():
conn = sqlite3.connect(master_db)
cursor = conn.cursor()
cursor.execute("select count(*) from sqlite_master where name = ?",(table.strip(), ))
res = cursor.fetchone()
if (res[0]):
print ('[+] Table : ' + table.strip() + ' exists [+]')
else:
print ('[-] Table : ' + table.strip() + ' does not exist [-]')
# Script Name : puttylogs.py
# Author : Craig Richards
# Created : 13th October 2011
# Last Modified : 29th February 2012
# Version : 1.2
# Modifications : 1.1 - Added the variable zip_program so you can set it for the zip program on whichever OS, so to run on a different OS just change the locations of these two variables.
# : 1.2 - 29-02-12 - CR - Added shutil module and added one line to move the zipped up logs to the zipped_logs directory
# Description : Zip up all the logs in the given directory
import os # Load the Library Module
import shutil # Load the Library Module - 1.2
from time import strftime # Load just the strftime Module from Time
logsdir="c:\logs\puttylogs" # Set the Variable logsdir
zipdir="c:\logs\puttylogs\zipped_logs" # Set the Variable zipdir - 1.2
zip_program="zip.exe" # Set the Variable zip_program - 1.1
for files in os.listdir(logsdir): # Find all the files in the directory
if files.endswith(".log"): # Check to ensure the files in the directory end in .log
files1=files+"."+strftime("%Y-%m-%d")+".zip" # Create the Variable files1, this is the files in the directory, then we add a suffix with the date and the zip extension
os.chdir(logsdir) # Change directory to the logsdir
os.system(zip_program + " " + files1 +" "+ files) # Zip the logs into dated zip files for each server. - 1.1
shutil.move(files1, zipdir) # Move the zipped log files to the zipped_logs directory - 1.2
os.remove(files) # Remove the original log files
# Script Name : daily_checks.py
# Author : Craig Richards
# Created : 07th December 2011
# Last Modified : 01st May 2013
# Version : 1.5
#
# Modifications : 1.1 Removed the static lines for the putty sessions, it now reads a file, loops through and makes the connections.
# : 1.2 Added a variable filename=sys.argv[0] , as when you use __file__ it errors when creating an exe with py2exe.
# : 1.3 Changed the server_list.txt file name and moved the file to the config directory.
# : 1.4 Changed some settings due to getting a new pc
# : 1.5 Tidy comments and syntax
#
# Description : This simple script loads everything I need to carry out the daily checks for our systems.
import platform # Load Modules
import os
import subprocess
import sys
from time import strftime # Load just the strftime Module from Time
def clear_screen(): # Function to clear the screen
if os.name == "posix": # Unix/Linux/MacOS/BSD/etc
os.system('clear') # Clear the Screen
elif os.name in ("nt", "dos", "ce"): # DOS/Windows
os.system('CLS') # Clear the Screen
def print_docs(): # Function to print the daily checks automatically
print ("Printing Daily Check Sheets:")
# The command below passes the command line string to open word, open the document, print it then close word down
subprocess.Popen(["C:\\Program Files (x86)\Microsoft Office\Office14\winword.exe", "P:\\\\Documentation\\Daily Docs\\Back office Daily Checks.doc", "/mFilePrintDefault", "/mFileExit"]).communicate()
def putty_sessions(): # Function to load the putty sessions I need
for server in open(conffilename): # Open the file server_list.txt, loop through reading each line - 1.1 -Changed - 1.3 Changed name to use variable conffilename
subprocess.Popen(('putty -load '+server)) # Open the PuTTY sessions - 1.1
def rdp_sessions():
print ("Loading RDP Sessions:")
subprocess.Popen("mstsc eclr.rdp") # Open up a terminal session connection and load the euroclear session
def euroclear_docs():
# The command below opens IE and loads the Euroclear password document
subprocess.Popen('"C:\\Program Files\\Internet Explorer\\iexplore.exe"' '"file://fs1\pub_b\Pub_Admin\Documentation\Settlements_Files\PWD\Eclr.doc"')
# End of the functions
# Start of the Main Program
def main():
filename = sys.argv[0] # Create the variable filename
confdir = os.getenv("my_config") # Set the variable confdir from the OS environment variable - 1.3
conffile = ('daily_checks_servers.conf') # Set the variable conffile - 1.3
conffilename = os.path.join(confdir, conffile) # Set the variable conffilename by joining confdir and conffile together - 1.3
clear_screen() # Call the clear screen function
# The command below prints a little welcome message, as well as the script name, the date and time and where it was run from.
print ("Good Morning " + os.getenv('USERNAME') + ", "+
filename, "ran at", strftime("%Y-%m-%d %H:%M:%S"), "on",platform.node(), "run from",os.getcwd())
print_docs() # Call the print_docs function
putty_sessions() # Call the putty_session function
rdp_sessions() # Call the rdp_sessions function
euroclear_docs() # Call the euroclear_docs function
if __name__ == "__main__":
main()
import serial
import sys
#A serial port-scanner for linux and windows platforms
#Author: Julio César Echeverri Marulanda
#e-mail: [email protected]
#blog: blogdelingeniero1.wordpress.com
#You should have installed the PySerial module to use this method.
#You can install pyserial with the following line: pip install pyserial
def ListAvailablePorts():
#This function return a list containing the string names for Virtual Serial Ports
#availables in the computer (this function works only for Windows & Linux Platforms but you can extend it)
#if there isn't available ports, returns an empty List
AvailablePorts = []
platform = sys.platform
if platform == 'win32':
for i in range(255):
try:
ser = serial.Serial(i,9600)
except serial.serialutil.SerialException:
pass
else:
AvailablePorts.append(ser.portstr)
ser.close()
elif platform == 'linux':
for i in range(0,255):
try:
ser = serial.Serial('/dev/ttyUSB'+str(i))
except serial.serialutil.SerialException:
pass
else:
AvailablePorts.append('/dev/ttyUSB'+str(i))
ser.close()
else:
print '''This method was developed only for linux and windows
the current platform isn't recognised'''
return AvailablePorts
# EXAMPLE OF HOW IT WORKS
# if an Arduino is connected to the computer, the port will be show in the terminal
# print ListAvailablePorts()# Script Name : nslookup_check.py
# Author : Craig Richards
# Created : 5th January 2012
# Last Modified :
# Version : 1.0
# Modifications :
# Description : This very simple script opens the file server_list.txt and the does an nslookup for each one to check the DNS entry
import subprocess # Import the subprocess module
for server in open('server_list.txt'): # Open the file and read each line
subprocess.Popen(('nslookup ' + server)) # Run the nslookup command for each server in the listimport urllib
import json
import sys
import os
accessToken = 'TOKENVALUE' # YOUR ACCESS TOKEN GETS INSERTED HERE
userId = sys.argv[1] #USERID
limit=100
url='https://graph.facebook.com/'+userId+'/posts?access_token='+accessToken +'&limit='+str(limit) #FB Link
data = json.load(urllib.urlopen(url))
id=0
print str(id)
for item in data['data']:
time=item['created_time'][11:19]
date=item['created_time'][5:10]
year=item['created_time'][0:4]
if 'shares' in item:
num_share=item['shares']['count']
else:
num_share=0
if 'likes' in item:
num_like=item['likes']['count']
else:
num_like=0
id+=1
print str(id)+'\t'+ time.encode('utf-8')+'\t'+date.encode('utf-8')+'\t'+year.encode('utf-8')+'\t'+ str(num_share)+'\t'+str(num_like)"""
Written by: Shreyas Daniel - github.com/shreydan
Description: an overview of 'timy' module - pip install timy
A great alternative to Pythons 'timeit' module and easier to use.
"""
import timy # begin by importing timy
@timy.timer(ident = 'listcomp', loops = 1) # timy decorator
def listcomprehension(): # the function whose execution time is calculated.
li = [x for x in range(0,100000,2)]
listcomprehension()
"""
this is how the above works:
timy decorator is created.
any function underneath the timy decorator is the function whose execution time
need to be calculated.
after the function is called. The execution time is printed.
in the timy decorator:
ident: an identity for each timy decorator, handy when using a lot of them
loops: no. of times this function has to be executed
"""
# this can also be accomplished by 'with' statement:
# tracking points in between code can be added
# to track specific instances in the program
def listcreator():
with timy.Timer() as timer:
li = []
for i in range(0,100000,2):
li.append(i)
if i == 50000:
timer.track('reached 50000')
listcreator()
"""
there are many more aspects to 'timy' module.
check it out here: https://github.com/ramonsaraiva/timy
"""'''Simple million word count program.
main idea is Python pairs words
with the number of times
that number appears in the triple quoted string.
Credit to William J. Turkel and Adam Crymble for the word
frequency code used below. I just merged the two ideas.
'''
wordstring = '''SCENE I. Yorkshire. Gaultree Forest.
Enter the ARCHBISHOP OF YORK, MOWBRAY, LORD HASTINGS, and others
ARCHBISHOP OF YORK
What is this forest call'd?
HASTINGS
'Tis Gaultree Forest, an't shall please your grace.
ARCHBISHOP OF YORK
Here stand, my lords; and send discoverers forth
To know the numbers of our enemies.
HASTINGS
We have sent forth already.
ARCHBISHOP OF YORK
'Tis well done.
My friends and brethren in these great affairs,
I must acquaint you that I have received
New-dated letters from Northumberland;
Their cold intent, tenor and substance, thus:
Here doth he wish his person, with such powers
As might hold sortance with his quality,
The which he could not levy; whereupon
He is retired, to ripe his growing fortunes,
To Scotland: and concludes in hearty prayers
That your attempts may overlive the hazard
And fearful melting of their opposite.
MOWBRAY
Thus do the hopes we have in him touch ground
And dash themselves to pieces.
Enter a Messenger
HASTINGS
Now, what news?
Messenger
West of this forest, scarcely off a mile,
In goodly form comes on the enemy;
And, by the ground they hide, I judge their number
Upon or near the rate of thirty thousand.
MOWBRAY
The just proportion that we gave them out
Let us sway on and face them in the field.
ARCHBISHOP OF YORK
What well-appointed leader fronts us here?
Enter WESTMORELAND
MOWBRAY
I think it is my Lord of Westmoreland.
WESTMORELAND
Health and fair greeting from our general,
The prince, Lord John and Duke of Lancaster.
ARCHBISHOP OF YORK
Say on, my Lord of Westmoreland, in peace:
What doth concern your coming?
WESTMORELAND
Then, my lord,
Unto your grace do I in chief address
The substance of my speech. If that rebellion
Came like itself, in base and abject routs,
Led on by bloody youth, guarded with rags,
And countenanced by boys and beggary,
I say, if damn'd commotion so appear'd,
In his true, native and most proper shape,
You, reverend father, and these noble lords
Had not been here, to dress the ugly form
Of base and bloody insurrection
With your fair honours. You, lord archbishop,
Whose see is by a civil peace maintained,
Whose beard the silver hand of peace hath touch'd,
Whose learning and good letters peace hath tutor'd,
Whose white investments figure innocence,
The dove and very blessed spirit of peace,
Wherefore do you so ill translate ourself
Out of the speech of peace that bears such grace,
Into the harsh and boisterous tongue of war;
Turning your books to graves, your ink to blood,
Your pens to lances and your tongue divine
To a trumpet and a point of war?
ARCHBISHOP OF YORK
Wherefore do I this? so the question stands.
Briefly to this end: we are all diseased,
And with our surfeiting and wanton hours
Have brought ourselves into a burning fever,
And we must bleed for it; of which disease
Our late king, Richard, being infected, died.
But, my most noble Lord of Westmoreland,
I take not on me here as a physician,
Nor do I as an enemy to peace
Troop in the throngs of military men;
But rather show awhile like fearful war,
To diet rank minds sick of happiness
And purge the obstructions which begin to stop
Our very veins of life. Hear me more plainly.
I have in equal balance justly weigh'd
What wrongs our arms may do, what wrongs we suffer,
And find our griefs heavier than our offences.
We see which way the stream of time doth run,
And are enforced from our most quiet there
By the rough torrent of occasion;
And have the summary of all our griefs,
When time shall serve, to show in articles;
Which long ere this we offer'd to the king,
And might by no suit gain our audience:
When we are wrong'd and would unfold our griefs,
We are denied access unto his person
Even by those men that most have done us wrong.
The dangers of the days but newly gone,
Whose memory is written on the earth
With yet appearing blood, and the examples
Of every minute's instance, present now,
Hath put us in these ill-beseeming arms,
Not to break peace or any branch of it,
But to establish here a peace indeed,
Concurring both in name and quality.
WESTMORELAND
When ever yet was your appeal denied?
Wherein have you been galled by the king?
What peer hath been suborn'd to grate on you,
That you should seal this lawless bloody book
Of forged rebellion with a seal divine
And consecrate commotion's bitter edge?
ARCHBISHOP OF YORK
My brother general, the commonwealth,
To brother born an household cruelty,
I make my quarrel in particular.
WESTMORELAND
There is no need of any such redress;
Or if there were, it not belongs to you.
MOWBRAY
Why not to him in part, and to us all
That feel the bruises of the days before,
And suffer the condition of these times
To lay a heavy and unequal hand
Upon our honours?
WESTMORELAND
O, my good Lord Mowbray,
Construe the times to their necessities,
And you shall say indeed, it is the time,
And not the king, that doth you injuries.
Yet for your part, it not appears to me
Either from the king or in the present time
That you should have an inch of any ground
To build a grief on: were you not restored
To all the Duke of Norfolk's signories,
Your noble and right well remember'd father's?
MOWBRAY
What thing, in honour, had my father lost,
That need to be revived and breathed in me?
The king that loved him, as the state stood then,
Was force perforce compell'd to banish him:
And then that Harry Bolingbroke and he,
Being mounted and both roused in their seats,
Their neighing coursers daring of the spur,
Their armed staves in charge, their beavers down,
Their eyes of fire sparking through sights of steel
And the loud trumpet blowing them together,
Then, then, when there was nothing could have stay'd
My father from the breast of Bolingbroke,
O when the king did throw his warder down,
His own life hung upon the staff he threw;
Then threw he down himself and all their lives
That by indictment and by dint of sword
Have since miscarried under Bolingbroke.
WESTMORELAND
You speak, Lord Mowbray, now you know not what.
The Earl of Hereford was reputed then
In England the most valiant gentlemen:
Who knows on whom fortune would then have smiled?
But if your father had been victor there,
He ne'er had borne it out of Coventry:
For all the country in a general voice
Cried hate upon him; and all their prayers and love
Were set on Hereford, whom they doted on
And bless'd and graced indeed, more than the king.
But this is mere digression from my purpose.
Here come I from our princely general
To know your griefs; to tell you from his grace
That he will give you audience; and wherein
It shall appear that your demands are just,
You shall enjoy them, every thing set off
That might so much as think you enemies.
MOWBRAY
But he hath forced us to compel this offer;
And it proceeds from policy, not love.
WESTMORELAND
Mowbray, you overween to take it so;
This offer comes from mercy, not from fear:
For, lo! within a ken our army lies,
Upon mine honour, all too confident
To give admittance to a thought of fear.
Our battle is more full of names than yours,
Our men more perfect in the use of arms,
Our armour all as strong, our cause the best;
Then reason will our heart should be as good
Say you not then our offer is compell'd.
MOWBRAY
Well, by my will we shall admit no parley.
WESTMORELAND
That argues but the shame of your offence:
A rotten case abides no handling.
HASTINGS
Hath the Prince John a full commission,
In very ample virtue of his father,
To hear and absolutely to determine
Of what conditions we shall stand upon?
WESTMORELAND
That is intended in the general's name:
I muse you make so slight a question.
ARCHBISHOP OF YORK
Then take, my Lord of Westmoreland, this schedule,
For this contains our general grievances:
Each several article herein redress'd,
All members of our cause, both here and hence,
That are insinew'd to this action,
Acquitted by a true substantial form
And present execution of our wills
To us and to our purposes confined,
We come within our awful banks again
And knit our powers to the arm of peace.
WESTMORELAND
This will I show the general. Please you, lords,
In sight of both our battles we may meet;
And either end in peace, which God so frame!
Or to the place of difference call the swords
Which must decide it.
ARCHBISHOP OF YORK
My lord, we will do so.
Exit WESTMORELAND
MOWBRAY
There is a thing within my bosom tells me
That no conditions of our peace can stand.
HASTINGS
Fear you not that: if we can make our peace
Upon such large terms and so absolute
As our conditions shall consist upon,
Our peace shall stand as firm as rocky mountains.
MOWBRAY
Yea, but our valuation shall be such
That every slight and false-derived cause,
Yea, every idle, nice and wanton reason
Shall to the king taste of this action;
That, were our royal faiths martyrs in love,
We shall be winnow'd with so rough a wind
That even our corn shall seem as light as chaff
And good from bad find no partition.
ARCHBISHOP OF YORK
No, no, my lord. Note this; the king is weary
Of dainty and such picking grievances:
For he hath found to end one doubt by death
Revives two greater in the heirs of life,
And therefore will he wipe his tables clean
And keep no tell-tale to his memory
That may repeat and history his loss
To new remembrance; for full well he knows
He cannot so precisely weed this land
As his misdoubts present occasion:
His foes are so enrooted with his friends
That, plucking to unfix an enemy,
He doth unfasten so and shake a friend:
So that this land, like an offensive wife
That hath enraged him on to offer strokes,
As he is striking, holds his infant up
And hangs resolved correction in the arm
That was uprear'd to execution.
HASTINGS
Besides, the king hath wasted all his rods
On late offenders, that he now doth lack
The very instruments of chastisement:
So that his power, like to a fangless lion,
May offer, but not hold.
ARCHBISHOP OF YORK
'Tis very true:
And therefore be assured, my good lord marshal,
If we do now make our atonement well,
Our peace will, like a broken limb united,
Grow stronger for the breaking.
MOWBRAY
Be it so.
Here is return'd my Lord of Westmoreland.
Re-enter WESTMORELAND
WESTMORELAND
The prince is here at hand: pleaseth your lordship
To meet his grace just distance 'tween our armies.
MOWBRAY
Your grace of York, in God's name then, set forward.
ARCHBISHOP OF YORK
Before, and greet his grace: my lord, we come.
Exeunt'''
wordlist = wordstring.split()
wordfreq = [wordlist.count(w) for w in wordlist]
print("String\n {} \n".format(wordstring))
print("List\n {} \n".format(str(wordlist)))
print("Frequencies\n {} \n".format(str(wordfreq)))
print("Pairs\n {}".format(str(list(zip(wordlist, wordfreq)))))#!/usr/bin/python
import urllib2
import cookielib
from getpass import getpass
import sys
username = raw_input('Enter mobile number:')
passwd = getpass()
message = raw_input('Enter Message:')
#Fill the list with Recipients
x=raw_input('Enter Mobile numbers seperated with comma:')
num=x.split(',')
message = "+".join(message.split(' '))
#Logging into the SMS Site
url = 'http://site24.way2sms.com/Login1.action?'
data = 'username='+username+'&password='+passwd+'&Submit=Sign+in'
#For Cookies:
cj = cookielib.CookieJar()
opener = urllib2.build_opener(urllib2.HTTPCookieProcessor(cj))
# Adding Header detail:
opener.addheaders = [('User-Agent','Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/37.0.2062.120 Safari/537.36')]
try:
usock = opener.open(url, data)
except IOError:
print "Error while logging in."
sys.exit(1)
jession_id = str(cj).split('~')[1].split(' ')[0]
send_sms_url = 'http://site24.way2sms.com/smstoss.action?'
opener.addheaders = [('Referer', 'http://site25.way2sms.com/sendSMS?Token='+jession_id)]
try:
for number in num:
send_sms_data = 'ssaction=ss&Token='+jession_id+'&mobile='+number+'&message='+message+'&msgLen=136'
sms_sent_page = opener.open(send_sms_url,send_sms_data)
except IOError:
print "Error while sending message"
sys.exit(1)
print "SMS has been sent."# Script Name : get_info_remoute_srv.py
# Author : Pavel Sirotkin
# Created : 3th April 2016
# Last Modified : -
# Version : 1.0.0
# Modifications :
# Description : this will get info about remoute server on linux through ssh connection. Connect these servers must be through keys
import subprocess
HOSTS = ('proxy1', 'proxy')
COMMANDS = ('uname -a', 'uptime')
for host in HOSTS:
result = []
for command in COMMANDS:
ssh = subprocess.Popen(["ssh", "%s" % host, command],
shell=False,
stdout=subprocess.PIPE,
stderr=subprocess.PIPE)
result.append(ssh.stdout.readlines())
print('--------------- ' + host + ' --------------- ')
for res in result:
if not res:
print(ssh.stderr.readlines())
break
else:
print(res)# Script Name : portscanner.py
# Author : Craig Richards
# Created : 20 May 2013
# Last Modified :
# Version : 1.0
# Modifications :
# Description : Port Scanner, you just pass the host and the ports
import optparse # Import the module
from socket import * # Import the module
from threading import * # Import the module
screenLock = Semaphore(value=1) # Prevent other threads from preceeding
def connScan(tgtHost, tgtPort): # Start of the function
try:
connSkt = socket(AF_INET, SOCK_STREAM) # Open a socket
connSkt.connect((tgtHost, tgtPort))
connSkt.send('')
results=connSkt.recv(100)
screenLock.acquire() # Acquire the lock
print '[+] %d/tcp open'% tgtPort
print '[+] ' + str(results)
except:
screenLock.acquire()
print '[-] %d/tcp closed '% tgtPort
finally:
screenLock.release()
connSkt.close()
def portScan(tgtHost, tgtPorts): # Start of the function
try:
tgtIP = gethostbyname(tgtHost) # Get the IP from the hostname
except:
print "[-] Cannot resolve '%s': Unknown host"%tgtHost
return
try:
tgtName = gethostbyaddr(tgtIP) # Get hostname from IP
print '\n[+] Scan Results for: ' +tgtName[0]
except:
print '\n[+] Scan Results for: ' + tgtIP
setdefaulttimeout(1)
for tgtPort in tgtPorts: # Scan host and ports
t = Thread(target=connScan, args=(tgtHost, int(tgtPort)))
t.start()
def main():
parser = optparse.OptionParser('usage %prog -H'+' <target host> -p <target port>')
parser.add_option('-H', dest='tgtHost', type='string', help='specify target host')
parser.add_option('-p', dest='tgtPort',type='string', help='specify target port[s] seperated by a comma')
(options, args) = parser.parse_args()
tgtHost = options.tgtHost
tgtPorts = str(options.tgtPort).split(',')
if (tgtHost == None) | (tgtPorts[0] == None):
print parser.usage
exit(0)
portScan(tgtHost, tgtPorts)
if __name__ == '__main__':
main()# Script Name : work_connect.py
# Author : Craig Richards
# Created : 11th May 2012
# Last Modified : 31st October 2012
# Version : 1.1
# Modifications : 1.1 - CR - Added some extra code, to check an argument is passed to the script first of all, then check it's a valid input
# Description : This simple script loads everything I need to connect to work etc
import subprocess # Load the Library Module
import sys # Load the Library Module
import os # Load the Library Module
import time # Load the Library Module
dropbox = os.getenv("dropbox") # Set the variable dropbox, by getting the values of the environment setting for dropbox
rdpfile = ("remote\\workpc.rdp") # Set the variable logfile, using the arguments passed to create the logfile
conffilename=os.path.join(dropbox, rdpfile) # Set the variable conffilename by joining confdir and conffile together
remote = (r"c:\windows\system32\mstsc.exe ") # Set the variable remote with the path to mstsc
text = '''You need to pass an argument
-c Followed by login password to connect
-d to disconnect''' # Text to display if there is no argument passed or it's an invalid option - 1.2
if len(sys.argv) < 2: # Check there is at least one option passed to the script - 1.2
print text # If not print the text above - 1.2
sys.exit() # Exit the program - 1.2
if '-h' in sys.argv or '--h' in sys.argv or '-help' in sys.argv or '--help' in sys.argv: # Help Menu if called
print text # Print the text, stored in the text variable - 1.2
sys.exit(0) # Exit the program
else:
if sys.argv[1].lower().startswith('-c'): # If the first argument is -c then
passwd = sys.argv[2] # Set the variable passwd as the second argument passed, in this case my login password
subprocess.Popen((r"c:\Program Files\Checkpoint\Endpoint Connect\trac.exe connect -u username -p "+passwd))
subprocess.Popen((r"c:\geektools\puttycm.exe"))
time.sleep(15) # Sleep for 15 seconds, so the checkpoint software can connect before opening mstsc
subprocess.Popen([remote, conffilename])
elif sys.argv[1].lower().startswith('-d'): # If the first argument is -d then disconnect my checkpoint session.
subprocess.Popen((r"c:\Program Files\Checkpoint\Endpoint Connect\trac.exe disconnect "))
else:
print 'Unknown option - ' + text # If any other option is passed, then print Unknown option and the text from above - 1.2# Script Name : testlines.py
# Author : Craig Richards
# Created : 08th December 2011
# Last Modified :
# Version : 1.0
# Modifications : beven nyamande
# Description : This is a very simple script that opens up a file and writes whatever is set "
def write_to_file(filename, txt):
with open(filename, 'w') as file_object:
s = file_object.write(txt)
if __name__ == '__main__':
write_to_file('test.txt', 'I am beven')
# Script Name : ping_subnet.py
# Author : Craig Richards
# Created : 12th January 2012
# Last Modified :
# Version : 1.0
# Modifications :
# Description : After supplying the first 3 octets it will scan the final range for available addresses
import os # Load the Library Module
import subprocess # Load the Library Module
import sys # Load the Library Module
filename = sys.argv[0] # Sets a variable for the script name
if '-h' in sys.argv or '--h' in sys.argv or '-help' in sys.argv or '--help' in sys.argv: # Help Menu if called
print '''
You need to supply the first octets of the address Usage : ''' + filename + ''' 111.111.111 '''
sys.exit(0)
else:
if (len(sys.argv) < 2): # If no arguments are passed then display the help and instructions on how to run the script
sys.exit (' You need to supply the first octets of the address Usage : ' + filename + ' 111.111.111')
subnet = sys.argv[1] # Set the variable subnet as the three octets you pass it
if os.name == "posix": # Check the os, if it's linux then
myping = "ping -c 2 " # This is the ping command
elif os.name in ("nt", "dos", "ce"): # Check the os, if it's windows then
myping = "ping -n 2 " # This is the ping command
f = open('ping_' + subnet + '.log', 'w') # Open a logfile
for ip in range(2,255): # Set the ip variable for the range of numbers
ret = subprocess.call(myping + str(subnet) + "." + str(ip) ,
shell=True, stdout=f, stderr=subprocess.STDOUT) # Run the command pinging the servers
if ret == 0: # Depending on the response
f.write (subnet + "." + str(ip) + " is alive" + "\n") # Write out that you can receive a reponse
else:
f.write (subnet + "." + str(ip) + " did not respond" + "\n") # Write out you can't reach the box# Script Name : ping_servers.py
# Author : Craig Richards
# Created : 9th May 2012
# Last Modified : 14th May 2012
# Version : 1.1
# Modifications : 1.1 - 14th May 2012 - CR Changed it to use the config directory to store the server files
# Description : This script will, depending on the arguments supplied will ping the servers associated with that application group.
import os # Load the Library Module
import subprocess # Load the Library Module
import sys # Load the Library Module
if '-h' in sys.argv or '--h' in sys.argv or '-help' in sys.argv or '--help' in sys.argv: # Help Menu if called
print '''
You need to supply the application group for the servers you want to ping, i.e.
dms
swaps
Followed by the site i.e.
155
bromley'''
sys.exit(0)
else:
if (len(sys.argv) < 3): # If no arguments are passed,display the help/instructions on how to run the script
sys.exit ('\nYou need to supply the app group. Usage : ' + filename + ' followed by the application group i.e. \n \t dms or \n \t swaps \n then the site i.e. \n \t 155 or \n \t bromley')
appgroup = sys.argv[1] # Set the variable appgroup as the first argument you supply
site = sys.argv[2] # Set the variable site as the second argument you supply
if os.name == "posix": # Check the os, if it's linux then
myping = "ping -c 2 " # This is the ping command
elif os.name in ("nt", "dos", "ce"): # Check the os, if it's windows then
myping = "ping -n 2 " # This is the ping command
if 'dms' in sys.argv: # If the argument passed is dms then
appgroup = 'dms' # Set the variable appgroup to dms
elif 'swaps' in sys.argv: # Else if the argment passed is swaps then
appgroup = 'swaps' # Set the variable appgroup to swaps
if '155' in sys.argv: # If the argument passed is 155 then
site = '155' # Set the variable site to 155
elif 'bromley' in sys.argv: # Else if the argument passed is bromley
site = 'bromley' # Set the variable site to bromley
filename = sys.argv[0] # Sets a variable for the script name
logdir = os.getenv("logs") # Set the variable logdir by getting the OS environment logs
logfile = 'ping_' + appgroup + '_' + site + '.log' # Set the variable logfile, using the arguments passed to create the logfile
logfilename = os.path.join(logdir, logfile) # Set the variable logfilename by joining logdir and logfile together
confdir = os.getenv("my_config") # Set the variable confdir from the OS environment variable - 1.2
conffile = (appgroup + '_servers_' + site + '.txt') # Set the variable conffile - 1.2
conffilename = os.path.join(confdir, conffile) # Set the variable conffilename by joining confdir and conffile together - 1.2
f = open(logfilename, "w") # Open a logfile to write out the output
for server in open(conffilename): # Open the config file and read each line - 1.2
ret = subprocess.call(myping + server, shell=True, stdout=f, stderr=subprocess.STDOUT) # Run the ping command for each server in the list.
if ret == 0: # Depending on the response
f.write (server.strip() + " is alive" + "\n") # Write out that you can receive a reponse
else:
f.write (server.strip() + " did not respond" + "\n") # Write out you can't reach the box
print ("\n\tYou can see the results in the logfile : " + logfilename); # Show the location of the logfile# Script Name : backup_automater_services.py
# Author : Craig Richards
# Created : 24th October 2012
# Last Modified : 13th February 2016
# Version : 1.0.1
# Modifications : 1.0.1 - Tidy up the comments and syntax
# Description : This will go through and backup all my automator services workflows
import datetime # Load the library module
import os # Load the library module
import shutil # Load the library module
today = datetime.date.today() # Get Today's date
todaystr = today.isoformat() # Format it so we can use the format to create the directory
confdir = os.getenv("my_config") # Set the variable by getting the value from the OS setting
dropbox = os.getenv("dropbox") # Set the variable by getting the value from the OS setting
conffile = ('services.conf') # Set the variable as the name of the configuration file
conffilename = os.path.join(confdir, conffile) # Set the variable by combining the path and the file name
sourcedir = os.path.expanduser('~/Library/Services/') # Source directory of where the scripts are located
destdir = os.path.join(dropbox, "My_backups" + "/" +
"Automater_services" + todaystr + "/") # Combine several settings to create
# the destination backup directory
for file_name in open(conffilename): # Walk through the configuration file
fname = file_name.strip() # Strip out the blank lines from the configuration file
if fname: # For the lines that are not blank
sourcefile = os.path.join(sourcedir, fname) # Get the name of the source files to backup
destfile = os.path.join(destdir, fname) # Get the name of the destination file names
shutil.copytree(sourcefile, destfile) # Copy the directories# Script Name : powerup_checks.py
# Author : Craig Richards
# Created : 25th June 2013
# Last Modified :
# Version : 1.0
# Modifications :
# Description : Creates an output file by pulling all the servers for the given site from SQLITE database, then goes through the list pinging the servers to see if they are up on the network
import sys # Load the Library Module
import sqlite3 # Load the Library Module
import os # Load the Library Module
import subprocess # Load the Library Module
from time import strftime # Load just the strftime Module from Time
dropbox=os.getenv("dropbox") # Set the variable, by getting the value of the variable from the OS
config=os.getenv("my_config") # Set the variable, by getting the value of the variable from the OS
dbfile=("Databases/jarvis.db") # Set the variable to the database
master_db=os.path.join(dropbox, dbfile) # Create the variable by linking the path and the file
listfile=("startup_list.txt") # File that will hold the servers
serverfile=os.path.join(config,listfile) # Create the variable by linking the path and the file
outputfile=('server_startup_'+strftime("%Y-%m-%d-%H-%M")+'.log')
# Below is the help text
text = '''
You need to pass an argument, the options the script expects is
-site1 For the Servers relating to site1
-site2 For the Servers located in site2'''
def windows(): # This is the function to run if it detects the OS is windows.
f = open(outputfile, 'a') # Open the logfile
for server in open(serverfile,'r'): # Read the list of servers from the list
#ret = subprocess.call("ping -n 3 %s" % server.strip(), shell=True,stdout=open('NUL', 'w'),stderr=subprocess.STDOUT) # Ping the servers in turn
ret = subprocess.call("ping -n 3 %s" % server.strip(),stdout=open('NUL', 'w'),stderr=subprocess.STDOUT) # Ping the servers in turn
if ret == 0: # Depending on the response
f.write ("%s: is alive" % server.strip().ljust(15) + "\n") # Write out to the logfile is the server is up
else:
f.write ("%s: did not respond" % server.strip().ljust(15) + "\n") # Write to the logfile if the server is down
def linux(): # This is the function to run if it detects the OS is nix.
f = open('server_startup_'+strftime("%Y-%m-%d")+'.log', 'a') # Open the logfile
for server in open(serverfile,'r'): # Read the list of servers from the list
ret = subprocess.call("ping -c 3 %s" % server, shell=True,stdout=open('/dev/null', 'w'),stderr=subprocess.STDOUT) # Ping the servers in turn
if ret == 0: # Depending on the response
f.write ("%s: is alive" % server.strip().ljust(15) + "\n") # Write out to the logfile is the server is up
else:
f.write ("%s: did not respond" % server.strip().ljust(15) + "\n") # Write to the logfile if the server is down
def get_servers(query): # Function to get the servers from the database
conn = sqlite3.connect(master_db) # Connect to the database
cursor = conn.cursor() # Create the cursor
cursor.execute('select hostname from tp_servers where location =?',(query,)) # SQL Statement
print ('\nDisplaying Servers for : ' + query + '\n')
while True: # While there are results
row = cursor.fetchone() # Return the results
if row == None:
break
f = open(serverfile, 'a') # Open the serverfile
f.write("%s\n" % str(row[0])) # Write the server out to the file
print row[0] # Display the server to the screen
f.close() # Close the file
def main(): # Main Function
if os.path.exists(serverfile): # Checks to see if there is an existing server file
os.remove(serverfile) # If so remove it
if len(sys.argv) < 2: # Check there is an argument being passed
print text # Display the help text if there isn't one passed
sys.exit() # Exit the script
if '-h' in sys.argv or '--h' in sys.argv or '-help' in sys.argv or '--help' in sys.argv: # If the ask for help
print text # Display the help text if there isn't one passed
sys.exit(0) # Exit the script after displaying help
else:
if sys.argv[1].lower().startswith('-site1'): # If the argument is site1
query = 'site1' # Set the variable to have the value site
elif sys.argv[1].lower().startswith('-site2'): # Else if the variable is bromley
query = 'site2' # Set the variable to have the value bromley
else:
print '\n[-] Unknown option [-] ' + text # If an unknown option is passed, let the user know
sys.exit(0)
get_servers(query) # Call the get servers funtion, with the value from the argument
if os.name == "posix": # If the OS is linux.
linux() # Call the linux function
elif os.name in ("nt", "dos", "ce"): # If the OS is Windows...
windows() # Call the windows function
print ('\n[+] Check the log file ' + outputfile + ' [+]\n') # Display the name of the log
if __name__ == '__main__':
main() # Call the main function# Script Name : password_cracker.py
# Author : Craig Richards
# Created : 20 May 2013
# Last Modified :
# Version : 1.0
# Modifications :
# Description : Old school password cracker using python
from sys import platform as _platform
# Check the current operating system to import the correct version of crypt
if _platform in ["linux", "linux2", "darwin"]: # darwin is _platform name for Mac OS X
import crypt # Import the module
elif _platform == "win32":
# Windows
try:
import fcrypt # Try importing the fcrypt module
except ImportError:
print 'Please install fcrypt if you are on Windows'
def testPass(cryptPass): # Start the function
salt = cryptPass[0:2]
dictFile = open('dictionary.txt','r') # Open the dictionary file
for word in dictFile.readlines(): # Scan through the file
word = word.strip('\n')
cryptWord = crypt.crypt(word, salt) # Check for password in the file
if (cryptWord == cryptPass):
print "[+] Found Password: "+word+"\n"
return
print "[-] Password Not Found.\n"
return
def main():
passFile = open('passwords.txt') # Open the password file
for line in passFile.readlines(): # Read through the file
if ":" in line:
user = line.split(':')[0]
cryptPass = line.split(':')[1].strip(' ') # Prepare the user name etc
print "[*] Cracking Password For: " + user
testPass(cryptPass) # Call it to crack the users password
if __name__ == "__main__":
main()# Script Name : check_file.py
# Author : Craig Richards
# Created : 20 May 2013
# Last Modified :
# Version : 1.0
# Modifications : with statement added to ensure correct file closure
# Description : Check a file exists and that we can read the file
from __future__ import print_function
import sys # Import the Modules
import os # Import the Modules
# Prints usage if not appropriate length of arguments are provided
def usage():
print('[-] Usage: python check_file.py [filename1] [filename2] ... [filenameN]')
# Readfile Functions which open the file that is passed to the script
def readfile(filename):
with open(filename, 'r') as f: # Ensure file is correctly closed under
file = f.read() # all circumstances
print(file)
print()
print('#'*80)
print()
def main():
# Check the arguments passed to the script
if len(sys.argv) >= 2:
filenames = sys.argv[1:]
# Iterate for each filename passed in command line argument
for filename in filenames:
if not os.path.isfile(filename): # Check the File exists
print('[-] ' + filename + ' does not exist.')
filenames.remove(filename) #remove non existing files from fileNames list
continue
# Check you can read the file
if not os.access(filename, os.R_OK):
print('[-] ' + filename + ' access denied')
# remove non readable fileNames
filenames.remove(filename)
continue
# Read the content of each file
for filename in filenames:
# Display Message and read the file contents
print('[+] Reading from : ' + filename)
readfile(filename)
else:
usage() # Print usage if not all parameters passed/Checked
if __name__ == '__main__':
main()# Script Name : factorial_perm_comp.py
# Author : Ebiwari Williams
# Created : 20th May 2017
# Last Modified :
# Version : 1.0
# Modifications :
# Description : Find Factorial, Permutation and Combination of a Number
def factorial(n):
fact = 1
while(n >= 1 ):
fact = fact * n
n = n - 1
return fact
def permutation(n,r):
return factorial(n)/factorial(n-r)
def combination(n,r):
return permutation(n,r)/factorial(r)
def main():
print('choose between operator 1,2,3')
print('1) Factorial')
print('2) Permutation')
print('3) Combination')
operation = input('\n')
if(operation == '1'):
print('Factorial Computation\n')
while(True):
try:
n = int(input('\n Enter Value for n '))
print('Factorial of {} = {}'.format(n,factorial(n)))
break
except(ValueError):
print('Invalid Value')
continue
elif(operation == '2'):
print('Permutation Computation\n')
while(True):
try:
n = int(input('\n Enter Value for n '))
r = int(input('\n Enter Value for r '))
print('Permutation of {}P{} = {}'.format(n,r,permutation(n,r)))
break
except(ValueError):
print('Invalid Value')
continue
elif(operation == '3'):
print('Combination Computation\n')
while(True):
try:
n = int(input('\n Enter Value for n '))
r = int(input('\n Enter Value for r '))
print('Combination of {}C{} = {}'.format(n,r,combination(n,r)))
break
except(ValueError):
print('Invalid Value')
continue
if __name__ == '__main__':
main()# Script Name : nmap_scan.py
# Author : Craig Richards
# Created : 24th May 2013
# Last Modified :
# Version : 1.0
# Modifications :
# Description : This scans my scripts directory and gives a count of the different types of scripts, you need nmap installed to run this
import nmap # Import the module
import optparse # Import the module
def nmapScan(tgtHost, tgtPort): # Create the function, this fucntion does the scanning
nmScan = nmap.PortScanner()
nmScan.scan(tgtHost, tgtPort)
state = nmScan[tgtHost]['tcp'][int(tgtPort)]['state']
print "[*] " + tgtHost + " tcp/" + tgtPort + " " + state
def main(): # Main Program
parser = optparse.OptionParser('usage%prog ' + '-H <host> -p <port>') # Display options/help if required
parser.add_option('-H', dest='tgtHost', type='string', help='specify host')
parser.add_option('-p', dest='tgtPort', type='string', help='port')
(options, args) = parser.parse_args()
tgtHost = options.tgtHost
tgtPorts = str(options.tgtPort).split(',')
if (tgtHost == None) | (tgtPorts[0] == None):
print parser.usage
exit(0)
for tgtPort in tgtPorts: # Scan the hosts with the ports etc
nmapScan(tgtHost, tgtPort)
if __name__ == '__main__':
main()
# Script Created by Yash Ladha
# Requirements:
# youtube-dl
# aria2c
# 10 Feb 2017
import subprocess
import sys
video_link, threads = sys.argv[1], sys.argv[2]
subprocess.call([
"youtube-dl",
video_link,
"--external-downloader",
"aria2c",
"--external-downloader-args",
"-x"+threads
])import urllib2
try:
urllib2.urlopen("http://google.com", timeout=2)
print ("working connection")
except urllib2.URLError:
print ("No internet connection")# Script Name : sqlite_check.py
# Author : Craig Richards
# Created : 20 May 2013
# Last Modified :
# Version : 1.0
# Modifications :
# Description : Runs checks to check my SQLITE database
import sqlite3 as lite
import sys
import os
dropbox= os.getenv("dropbox")
dbfile=("Databases\jarvis.db")
master_db=os.path.join(dropbox, dbfile)
con = None
try:
con = lite.connect(master_db)
cur = con.cursor()
cur.execute('SELECT SQLITE_VERSION()')
data = cur.fetchone()
print "SQLite version: %s" % data
except lite.Error, e:
print "Error %s:" % e.args[0]
sys.exit(1)
finally:
if con:
con.close()
con = lite.connect(master_db)
cur=con.cursor()
cur.execute("SELECT name FROM sqlite_master WHERE type='table'")
rows = cur.fetchall()
for row in rows:
print row
con = lite.connect(master_db)
cur=con.cursor()
cur.execute("SELECT name FROM sqlite_master WHERE type='table'")
while True:
row = cur.fetchone()
if row == None:
break
print row[0]print [x for x in range(2, 100) if not x % 2]
print range(2, 100, 2)import pygame, sys, time
from pygame.locals import *
pygame.init()
window = pygame.display.set_mode((400, 300), 0, 32)
pygame.display.set_caption("Shape")
WHITE = (255, 255, 255)
GREEN = ( 0, 255, 0)
window.fill(WHITE)
pygame.draw.polygon(window, GREEN, ((146, 0), (236, 277), (56, 277)))
# Game logic
while True:
for event in pygame.event.get():
if event.type == QUIT:
pygame.quit()
sys.exit()
pygame.display.update()# Script Name : fileinfo.py
# Author : Not sure where I got this from
# Created : 28th November 2011
# Last Modified :
# Version : 1.0
# Modifications :
# Description : Show file information for a given file
# get file information using os.stat()
# tested with Python24 vegsaeat 25sep2006
from __future__ import print_function
import os
import sys
import stat # index constants for os.stat()
import time
try_count = 16
while try_count:
file_name = raw_input("Enter a file name: ") # pick a file you have
try_count >>= 1
try:
file_stats = os.stat(file_name)
break
except OSError:
print ("\nNameError : [%s] No such file or directory\n", file_name)
if try_count == 0:
print ("Trial limit exceded \nExiting program")
sys.exit()
# create a dictionary to hold file info
file_info = {
'fname': file_name,
'fsize': file_stats[stat.ST_SIZE],
'f_lm' : time.strftime("%d/%m/%Y %I:%M:%S %p",
time.localtime(file_stats[stat.ST_MTIME])),
'f_la' : time.strftime("%d/%m/%Y %I:%M:%S %p",
time.localtime(file_stats[stat.ST_ATIME])),
'f_ct' : time.strftime("%d/%m/%Y %I:%M:%S %p",
time.localtime(file_stats[stat.ST_CTIME]))
}
print ("\nfile name = %(fname)s", file_info)
print ("file size = %(fsize)s bytes", file_info)
print ("last modified = %(f_lm)s", file_info)
print ("last accessed = %(f_la)s", file_info)
print ("creation time = %(f_ct)s\n", file_info)
if stat.S_ISDIR(file_stats[stat.ST_MODE]):
print ("This a directory")
else:
print ("This is not a directory\n")
print ("A closer look at the os.stat(%s) tuple:" % file_name)
print (file_stats)
print ("\nThe above tuple has the following sequence:")
print ("""st_mode (protection bits), st_ino (inode number),
st_dev (device), st_nlink (number of hard links),
st_uid (user ID of owner), st_gid (group ID of owner),
st_size (file size, bytes), st_atime (last access time, seconds since epoch),
st_mtime (last modification time), st_ctime (time of creation, Windows)"""
)# Script Name : dir_test.py
# Author : Craig Richards
# Created : 29th November 2011
# Last Modified :
# Version : 1.0
# Modifications :
# Description : Tests to see if the directory testdir exists, if not it will create the directory for you
from __future__ import print_function
import os # Import the OS Module
import sys
def main():
if sys.version_info.major >= 3: # if the interpreter version is 3.X, use 'input',
input_func = input # otherwise use 'raw_input'
else:
input_func = raw_input
CheckDir = input_func("Enter the name of the directory to check : ")
print()
if os.path.exists(CheckDir): # Checks if the dir exists
print("The directory exists")
else:
print("No directory found for " + CheckDir) # Output if no directory
print()
os.makedirs(CheckDir) # Creates a new dir for the given name
print("Directory created for " + CheckDir)
if __name__ == '__main__':
main()import sys
from PIL import ImageDraw, ImageFont, Image
def input_par():
print('Enter the text to insert in image: ')
text = str(input())
print('Enter the desired size: ')
size = int(input())
print('Enter the color for the text(r, g, b): ')
color_value = [int(i) for i in input().split(' ')]
return text, size, color_value
pass
def main():
path_to_image = sys.argv[1]
image_file = Image.open(path_to_image + '.jpg')
image_file = image_file.convert("RGBA")
pixdata = image_file.load()
print(image_file.size)
text, size, color_value = input_par()
font = ImageFont.truetype("C:\\Windows\\Fonts\\Arial.ttf", size=size)
# Clean the background noise, if color != white, then set to black.
# change with your color
for y in range(100):
for x in range(100):
pixdata[x, y] = (255, 255, 255, 255)
image_file.show()
# Drawing text on the picture
draw = ImageDraw.Draw(image_file)
draw.text((0, 2300), text, (color_value[0], color_value[1], color_value[2]), font=font)
draw = ImageDraw.Draw(image_file)
print('Enter the file name: ')
file_name = str(input())
image_file.save(file_name + ".jpg")
pass
if __name__ == '__main__':
main()def get_user_input(start,end):
testcase = False
while testcase == False:
try:
userInput = int(input("Enter Your choice: "))
if userInput > 6 or userInput < 1:
print("Please try again.")
testcase = False
else:
return userInput
except ValueError:
print("Please try again.")
x = get_user_input(1,6)
print(x)
###Asks user to enter something, ie. a number option from a menu.
###While type != interger, and not in the given range,
###Program gives error message and asks for new input."""
Created on Thu Apr 27 16:28:36 2017
@author: barnabysandeford
"""
# Currently works for Safari, but just change to whichever
# browser you're using.
import time
#Changed the method of opening the browser.
#Selenium allows for the page to be refreshed.
from selenium import webdriver
#adding ability to change number of repeats
count = int(raw_input("Number of times to be repeated: "))
#Same as before
x = raw_input("Enter the URL (no https): ")
print( "Length of video:")
minutes = int(raw_input("Minutes "))
seconds = int(raw_input("Seconds "))
#Calculating the refreshrate from the user input
refreshrate = minutes * 60 + seconds
#Selecting Safari as the browser
driver = webdriver.Safari()
driver.get("http://"+x)
for i in range(count):
#Sets the page to refresh at the refreshrate.
time.sleep(refreshrate)
driver.refresh()# batch_file_rename.py
# Created: 6th August 2012
'''
This will batch rename a group of files in a given directory,
once you pass the current and new extensions
'''
__author__ = 'Craig Richards'
__version__ = '1.0'
import os
import sys
import argparse
def batch_rename(work_dir, old_ext, new_ext):
'''
This will batch rename a group of files in a given directory,
once you pass the current and new extensions
'''
# files = os.listdir(work_dir)
for filename in os.listdir(work_dir):
# Get the file extension
file_ext = os.path.splitext(filename)[1]
# Start of the logic to check the file extensions, if old_ext = file_ext
if old_ext == file_ext:
# Returns changed name of the file with new extention
name_list=list(filename)
name_list[len(name_list)-len(old_ext):]=list(new_ext)
newfile=''.join(name_list)
# Write the files
os.rename(
os.path.join(work_dir, filename),
os.path.join(work_dir, newfile)
)
def get_parser():
parser = argparse.ArgumentParser(description='change extension of files in a working directory')
parser.add_argument('work_dir', metavar='WORK_DIR', type=str, nargs=1, help='the directory where to change extension')
parser.add_argument('old_ext', metavar='OLD_EXT', type=str, nargs=1, help='old extension')
parser.add_argument('new_ext', metavar='NEW_EXT', type=str, nargs=1, help='new extension')
return parser
def main():
'''
This will be called if the script is directly invoked.
'''
# adding command line argument
parser = get_parser()
args = vars(parser.parse_args())
# Set the variable work_dir with the first argument passed
work_dir = args['work_dir'][0]
# Set the variable old_ext with the second argument passed
old_ext = args['old_ext'][0]
# Set the variable new_ext with the third argument passed
new_ext = args['new_ext'][0]
batch_rename(work_dir, old_ext, new_ext)
if __name__ == '__main__':
main()
# Script Name : python_sms.py
# Author : Craig Richards
# Created : 16th February 2017
# Last Modified :
# Version : 1.0
# Modifications :
# Description : This will text all the students Karate Club
import urllib # URL functions
import urllib2 # URL functions
import os
from time import strftime
import sqlite3
import sys
dropbox= os.getenv("dropbox")
scripts=os.getenv("scripts")
dbfile=("database/maindatabase.db")
master_db=os.path.join(dropbox, dbfile)
f=open(scripts+'/output/student.txt','a')
tdate=strftime("%d-%m")
conn = sqlite3.connect(master_db)
cursor = conn.cursor()
loc_stmt='SELECT name, number from table'
cursor.execute(loc_stmt)
while True:
row = cursor.fetchone()
if row == None:
break
sname=row[0]
snumber=row[1]
message = (sname + ' There will be NO training tonight on the ' + tdate + ' Sorry for the late notice, I have sent a mail as well, just trying to reach everyone, please do not reply to this message as this is automated')
username = 'YOUR_USERNAME'
sender = 'WHO_IS_SENDING_THE_MAIL'
hash = 'YOUR HASH YOU GET FROM YOUR ACCOUNT'
numbers = (snumber)
# Set flag to 1 to simulate sending, this saves your credits while you are testing your code. # To send real message set this flag to 0
test_flag = 0
#-----------------------------------
# No need to edit anything below this line
#-----------------------------------
values = {'test' : test_flag,
'uname' : username,
'hash' : hash,
'message' : message,
'from' : sender,
'selectednums' : numbers }
url = 'http://www.txtlocal.com/sendsmspost.php'
postdata = urllib.urlencode(values)
req = urllib2.Request(url, postdata)
print ('Attempting to send SMS to '+ sname + ' at ' + snumber + ' on ' + tdate)
f.write ('Attempting to send SMS to '+ sname + ' at ' + snumber + ' on ' + tdate + '\n')
try:
response = urllib2.urlopen(req)
response_url = response.geturl()
if response_url==url:
print 'SMS sent!'
except urllib2.URLError, e:
print 'Send failed!'
print e.reasonfrom sys import argv
script, input_file = argv
def print_all(f):
print f.read()
# seek(n) to read a file's content from byte-n
def rewind(f):
f.seek(0)
def print_a_line(line_count, f):
print line_count, f.readline()
current_file = open(input_file)
print "First let's print the whole file:\n"
print_all(current_file)
print "Now let's rewind, kind of like a tape."
rewind(current_file)
print "Let's print three lines:"
current_line = 1
print_a_line(current_line, current_file)
current_line = current_line + 1
print_a_line(current_line, current_file)
current_line = current_line + 1
print_a_line(current_line, current_file)
current_file.close()# Script Name : recyclebin.py
# Author : Craig Richards
# Created : 07th June 2013
# Last Modified :
# Version : 1.0
# Modifications :
# Description : Scans the recyclebin and displays the files in there, originally got this script from the Violent Python book
import os # Load the Module
import optparse # Load the Module
from _winreg import * # Load the Module
def sid2user(sid): # Start of the function to gather the user
try:
key = OpenKey(HKEY_LOCAL_MACHINE, "SOFTWARE\Microsoft\Windows NT\CurrentVersion\ProfileList" + '\\' + sid)
(value, type) = QueryValueEx(key, 'ProfileImagePath')
user = value.split('\\')[-1]
return user
except:
return sid
def returnDir(): # Start of the function to search through the recyclebin
dirs=['c:\\Recycler\\','C:\\Recycled\\','C:\\$RECYCLE.BIN\\']
#dirs=['c:\\$RECYCLE.BIN\\']
for recycleDir in dirs:
if os.path.isdir(recycleDir):
return recycleDir
return None
def findRecycled(recycleDir): # Start of the function, list the contents of the recyclebin
dirList = os.listdir(recycleDir)
for sid in dirList:
files = os.listdir(recycleDir + sid)
user = sid2user(sid)
print '\n[*] Listing Files for User: ' + str(user)
for file in files:
print '[+] Found File: ' + str(file)
def main():
recycleDir = returnDir()
findRecycled(recycleDir)
if __name__ == '__main__':
main()# Script Name : powerdown_startup.py
# Author : Craig Richards
# Created : 05th January 2012
# Last Modified :
# Version : 1.0
# Modifications :
# Description : This goes through the server list and pings the machine, if it's up it will load the putty session, if its not it will notify you.
import os # Load the Library Module
import subprocess # Load the Library Module
from time import strftime # Load just the strftime Module from Time
def windows(): # This is the function to run if it detects the OS is windows.
f = open('server_startup_'+strftime("%Y-%m-%d")+'.log', 'a') # Open the logfile
for server in open('startup_list.txt','r'): # Read the list of servers from the list
ret = subprocess.call("ping -n 3 %s" % server, shell=True,stdout=open('NUL', 'w'),stderr=subprocess.STDOUT) # Ping the servers in turn
if ret == 0: # If you get a response.
f.write ("%s: is alive, loading PuTTY session" % server.strip() + "\n") # Write out to the logfile
subprocess.Popen(('putty -load '+server)) # Load the putty session
else:
f.write ("%s : did not respond" % server.strip() + "\n") # Write to the logfile if the server is down
def linux():
f = open('server_startup_'+strftime("%Y-%m-%d")+'.log', 'a') # Open the logfile
for server in open('startup_list.txt'): # Read the list of servers from the list
ret = subprocess.call("ping -c 3 %s" % server, shell=True,stdout=open('/dev/null', 'w'),stderr=subprocess.STDOUT) # Ping the servers in turn
if ret == 0: # If you get a response.
f.write ("%s: is alive" % server.strip() + "\n") # Print a message
subprocess.Popen(['ssh', server.strip()])
else:
f.write ("%s: did not respond" % server.strip() + "\n")
# End of the functions
# Start of the Main Program
if os.name == "posix": # If the OS is linux...
linux() # Call the linux function
elif os.name in ("nt", "dos", "ce"): # If the OS is Windows...
windows() # Call the windows functionfrom __future__ import print_function
import SimpleHTTPServer
import SocketServer
PORT = 8000 #This will serve at port 8080
Handler = SimpleHTTPServer.SimpleHTTPRequestHandler
httpd = SocketServer.TCPServer(("", PORT), Handler)
print("serving at port", PORT)
httpd.serve_forever()#Author: OMKAR PATHAK
#This script helps to build a simple stopwatch application using Python's time module.
import time
print('Press ENTER to begin, Press Ctrl + C to stop')
while True:
try:
input() #For ENTER
starttime = time.time()
print('Started')
except KeyboardInterrupt:
print('Stopped')
endtime = time.time()
print('Total Time:', round(endtime - starttime, 2),'secs')
break# Script Name : folder_size.py
# Author : Craig Richards
# Created : 19th July 2012
# Last Modified : 22 February 2016
# Version : 1.0.1
# Modifications : Modified the Printing method and added a few comments
# Description : This will scan the current directory and all subdirectories and display the size.
import os
import sys # Load the library module and the sys module for the argument vector'''
try:
directory = sys.argv[1] # Set the variable directory to be the argument supplied by user.
except IndexError:
sys.exit("Must provide an argument.")
dir_size = 0 # Set the size to 0
fsizedicr = {'Bytes': 1,
'Kilobytes': float(1) / 1024,
'Megabytes': float(1) / (1024 * 1024),
'Gigabytes': float(1) / (1024 * 1024 * 1024)}
for (path, dirs, files) in os.walk(directory): # Walk through all the directories. For each iteration, os.walk returns the folders, subfolders and files in the dir.
for file in files: # Get all the files
filename = os.path.join(path, file)
dir_size += os.path.getsize(filename) # Add the size of each file in the root dir to get the total size.
fsizeList = [str(round(fsizedicr[key] * dir_size, 2)) + " " + key for key in fsizedicr] # List of units
if dir_size == 0: print ("File Empty") # Sanity check to eliminate corner-case of empty file.
else:
for units in sorted(fsizeList)[::-1]: # Reverse sort list of units so smallest magnitude units print first.
print ("Folder Size: " + units)"""
Written by: Shreyas Daniel - github.com/shreydan
Description: Uses Pythons eval() function
as a way to implement calculator
Functions available:
+ : addition
- : subtraction
* : multiplication
/ : division
% : percentage
sine: sin(rad)
cosine: cos(rad)
tangent: tan(rad)
square root: sqrt(n)
pi: 3.141......
"""
import math
def main():
def calc(k):
functions = ['sin', 'cos', 'tan', 'sqrt', 'pi']
for i in functions:
if i in k.lower():
withmath = 'math.' + i
k = k.replace(i, withmath)
try:
k = eval(k)
except ZeroDivisionError:
print ("Can't divide by 0")
exit()
except NameError:
print ("Invalid input")
exit()
return k
print ("\nScientific Calculator\nEg: pi * sin(90) - sqrt(81)")
k = raw_input("\nWhat is ") # Using input() function is causing NameError. Changing it to raw_input() fixes this.
k = k.replace(' ', '')
k = k.replace('^', '**')
k = k.replace('=', '')
k = k.replace('?', '')
k = k.replace('%', '/100')
print ("\n" + str(calc(k)))
if __name__ == "__main__":
main()# Script Name : env_check.py
# Author : Craig Richards
# Created : 14th May 2012
# Last Modified : 14 February 2016
# Version : 1.0.1
# Modifications : 1.0.1 - Tidy up comments and syntax
# Description : This script will check to see if all of the environment variables I require are set
import os
confdir = os.getenv("my_config") # Set the variable confdir from the OS environment variable
conffile = 'env_check.conf' # Set the variable conffile
conffilename = os.path.join(confdir, conffile) # Set the variable conffilename by joining confdir and conffile together
for env_check in open(conffilename): # Open the config file and read all the settings
env_check = env_check.strip() # Set the variable as itsself, but strip the extra text out
print '[{}]'.format(env_check) # Format the Output to be in Square Brackets
newenv = os.getenv(env_check) # Set the variable newenv to get the settings from the OS what is currently set for the settings out the configfile
if newenv is None: # If it doesn't exist
print env_check, 'is not set' # Print it is not set
else: # Else if it does exist
print 'Current Setting for {}={}\n'.format(env_check, newenv) # Print out the details# Script Name : script_count.py
# Author : Craig Richards
# Created : 27th February 2012
# Last Modified : 20th July 2012
# Version : 1.3
# Modifications : 1.1 - 28-02-2012 - CR - Changed inside github and development functions, so instead of if os.name = "posix" do this else do this etc
# : I used os.path.join, so it condensed 4 lines down to 1
# : 1.2 - 10-05-2012 - CR - Added a line to include PHP scripts.
# : 1.3 - 20-07-2012 - CR - Added the line to include Batch scripts
# Description : This scans my scripts directory and gives a count of the different types of scripts
import os # Load the library module
path = os.getenv("scripts") # Set the variable path by getting the value from the OS environment variable scripts
dropbox = os.getenv("dropbox") # Set the variable dropbox by getting the value from the OS environment variable dropbox
def clear_screen(): # Function to clear the screen
if os.name == "posix": # Unix/Linux/MacOS/BSD/etc
os.system('clear') # Clear the Screen
elif os.name in ("nt", "dos", "ce"): # DOS/Windows
os.system('CLS') # Clear the Screen
def count_files(path, extensions): # Start of the function to count the files in the scripts directory, it counts the extension when passed below
counter = 0 # Set the counter to 0
for root, dirs, files in os.walk(path): # Loop through all the directories in the given path
for file in files: # For all the files
counter += file.endswith(extensions) # Count the files
return counter # Return the count
def github(): # Start of the function just to count the files in the github directory
github_dir = os.path.join(dropbox, 'github') # Joins the paths to get the github directory - 1.1
github_count = sum((len(f) for _, _, f in os.walk(github_dir))) # Get a count for all the files in the directory
if github_count > 5: # If the number of files is greater then 5, then print the following messages
print '\nYou have too many in here, start uploading !!!!!'
print 'You have: ' + str(github_count) + ' waiting to be uploaded to github!!'
elif github_count == 0: # Unless the count is 0, then print the following messages
print '\nGithub directory is all Clear'
else: # If it is any other number then print the following message, showing the number outstanding.
print '\nYou have: ' + str(github_count) + ' waiting to be uploaded to github!!'
def development(): # Start of the function just to count the files in the development directory
dev_dir = os.path.join(path, 'development') # Joins the paths to get the development directory - 1.1
dev_count = sum((len(f) for _, _, f in os.walk(dev_dir))) # Get a count for all the files in the directory
if dev_count > 10: # If the number of files is greater then 10, then print the following messages
print '\nYou have too many in here, finish them or delete them !!!!!'
print 'You have: ' + str(dev_count) + ' waiting to be finished!!'
elif dev_count ==0: # Unless the count is 0, then print the following messages
print '\nDevelopment directory is all clear'
else:
print '\nYou have: ' + str(dev_count) + ' waiting to be finished!!' # If it is any other number then print the following message, showing the number outstanding.
clear_screen() # Call the function to clear the screen
print '\nYou have the following :\n'
print 'AutoIT:\t' + str(count_files(path, '.au3')) # Run the count_files function to count the files with the extension we pass
print 'Batch:\t' + str(count_files(path, ('.bat', ',cmd'))) # 1.3
print 'Perl:\t' + str(count_files(path, '.pl'))
print 'PHP:\t' + str(count_files(path, '.php')) # 1.2
print 'Python:\t' + str(count_files(path, '.py'))
print 'Shell:\t' + str(count_files(path, ('.ksh', '.sh', '.bash')))
print 'SQL:\t' + str(count_files(path, '.sql'))
github() # Call the github function
development() # Call the development function#Made on May 27th, 2017
#Made by SlimxShadyx
#Editted by CaptMcTavish, June 17th, 2017
#Dice Rolling Simulator
import random
global user_exit_checker
user_exit_checker="exit"
def start():
print "Welcome to dice rolling simulator: \nPress Enter to proceed"
raw_input(">")
result()
def bye():
print "Thanks for using the Dice Rolling Simulator! Have a great day! =)"
def result():
user_dice_chooser
print "\r\nGreat! Begin by choosing a die! [6] [8] [12]?\r\n"
user_dice_chooser = raw_input(">")
user_dice_chooser = int(user_dice_chooser)
if user_dice_chooser == 6:
dice6()
elif user_dice_chooser == 8:
dice8()
elif user_dice_chooser == 12:
dice12()
else:
print "\r\nPlease choose one of the applicable options!\r\n"
result()
def dice6():
dice_6 = random.randint(1,6)
print "\r\nYou rolled a " + str(dice_6) + "!\r\n"
user_exit_checker_raw = raw_input("\r\nIf you want to roll another die, type [roll]. To exit, type [exit].\r\n?>")
user_exit_checker = (user_exit_checker_raw.lower())
if user_exit_checker=="roll":
start()
else:
bye()
def dice8():
dice_8 = random.randint(1,8)
print "\r\nYou rolled a " + str(dice_8) + "!"
user_exit_checker_raw = raw_input("\r\nIf you want to roll another die, type [roll]. To exit, type [exit].\r\n?>")
user_exit_checker = (user_exit_checker_raw.lower())
if user_exit_checker=="roll":
start()
else:
bye()
def dice12():
dice_12 = random.randint(1,12)
print "\r\nYou rolled a " + str(dice_12) + "!"
user_exit_checker_raw = raw_input("\r\nIf you want to roll another die, type [roll]. To exit, type [exit].\r\n?>")
user_exit_checker = (user_exit_checker_raw.lower())
if user_exit_checker=="roll":
start()
else:
bye()
start()# Script Name : script_listing.py
# Author : Craig Richards
# Created : 15th February 2012
# Last Modified : 29th May 2012
# Version : 1.2
# Modifications : 1.1 - 28-02-2012 - CR - Added the variable to get the logs directory, I then joined the output so the file goes to the logs directory
# : 1.2 - 29-05/2012 - CR - Changed the line so it doesn't ask for a directory, it now uses the environment varaible scripts
# Description : This will list all the files in the given directory, it will also go through all the subdirectories as well
import os # Load the library module
logdir = os.getenv("logs") # Set the variable logdir by getting the value from the OS environment variable logs
logfile = 'script_list.log' # Set the variable logfile
path = os.getenv("scripts") # Set the varable path by getting the value from the OS environment variable scripts - 1.2
#path = (raw_input("Enter dir: ")) # Ask the user for the directory to scan
logfilename = os.path.join(logdir, logfile) # Set the variable logfilename by joining logdir and logfile together
log = open(logfilename, 'w') # Set the variable log and open the logfile for writing
for dirpath, dirname, filenames in os.walk(path): # Go through the directories and the subdirectories
for filename in filenames: # Get all the filenames
log.write(os.path.join(dirpath, filename)+'\n') # Write the full path out to the logfile
print ("\nYour logfile " , logfilename, "has been created") # Small message informing the user the file has been created# Requirements:
# pip install numpy
# sudo apt-get install python-openCV
import numpy as np
import cv2
cap = cv2.VideoCapture(0)
while(True):
# Capture frame-by-frame
ret, frame = cap.read()
# Our operations on the frame come here
gray = cv2.cvtColor(frame, cv2.COLOR_BGR2GRAY)
# Display the resulting frame
cv2.imshow('frame',gray)
if cv2.waitKey(1) & 0xFF == ord('q'):
break
# When everything done, release the capture
cap.release()
cv2.destroyAllWindows() | [
"[email protected]"
] | |
f02305cf4e2591a356cae884abd638de7a8fa9fc | cbf9f600374d7510988632d7dba145c8ff0cd1f0 | /abc/190/c.py | 07fa190a978955b4555478224dd795a4394b14cf | [] | no_license | sakakazu2468/AtCoder_py | d0945d03ad562474e40e413abcec39ded61e6855 | 34bdf39ee9647e7aee17e48c928ce5288a1bfaa5 | refs/heads/master | 2022-04-27T18:32:28.825004 | 2022-04-21T07:27:00 | 2022-04-21T07:27:00 | 225,844,364 | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 719 | py | n, m = map(int, input().split())
condition = []
for i in range(m):
a, b = map(int, input().split())
condition.append([a, b])
k = int(input())
ball = []
for i in range(k):
c, d = map(int, input().split())
ball.append([c, d])
decision = []
for intnum in range(2**k):
binnum = bin(intnum)[2:]
binnum = binnum.zfill(k)
state = []
for j in range(len(binnum)):
state.append(ball[j][int(binnum[j])])
decision.append(state)
max_satis = -1
for i in range(len(decision)):
satis = 0
for j in range(len(condition)):
if (condition[j][0] in decision[i]) and (condition[j][1] in decision[i]):
satis += 1
max_satis = max(max_satis, satis)
print(max_satis)
| [
"[email protected]"
] | |
69c3575e4bc800259603a29d1a2a5811c432892c | bd3b4a3403ad0476d287eb555bbe4211134b093e | /nuitka/codegen/templates/CodeTemplatesIterators.py | 720c515a35f61ab167035473f612312da61f9a33 | [
"LicenseRef-scancode-warranty-disclaimer",
"Apache-2.0"
] | permissive | suryansh2020/Nuitka | 7ecff5bd0199a6510e446be13569c829ba165be5 | 3dd382e91884a77c28aeee6b0bd44a0fc58beee8 | refs/heads/master | 2021-01-19T14:28:47.154859 | 2014-12-21T07:34:12 | 2014-12-21T07:34:12 | null | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 1,885 | py | # Copyright 2014, Kay Hayen, mailto:[email protected]
#
# Part of "Nuitka", an optimizing Python compiler that is compatible and
# integrates with CPython, but also works on its own.
#
# 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.
#
""" Templates for the iterator handling.
"""
template_iterator_check = """\
// Check if iterator has left-over elements.
assertObject( %(iterator_name)s ); assert( PyIter_Check( %(iterator_name)s ) );
%(attempt_name)s = (*Py_TYPE( %(iterator_name)s )->tp_iternext)( %(iterator_name)s );
if (likely( %(attempt_name)s == NULL ))
{
// TODO: Could first fetch, then check, should be faster.
if ( !ERROR_OCCURED() )
{
}
else if ( PyErr_ExceptionMatches( PyExc_StopIteration ))
{
PyErr_Clear();
}
else
{
PyErr_Fetch( &exception_type, &exception_value, (PyObject **)&exception_tb );
%(release_temps_1)s
goto %(exception_exit)s;
}
}
else
{
Py_DECREF( %(attempt_name)s );
// TODO: Could avoid PyErr_Format.
#if PYTHON_VERSION < 300
PyErr_Format( PyExc_ValueError, "too many values to unpack" );
#else
PyErr_Format( PyExc_ValueError, "too many values to unpack (expected %(count)d)" );
#endif
PyErr_Fetch( &exception_type, &exception_value, (PyObject **)&exception_tb );
%(release_temps_2)s
goto %(exception_exit)s;
}"""
| [
"[email protected]"
] | |
e2274ab12d26245e6dd74947dcd285ea874883ae | 23f6dbacd9b98fdfd08a6f358b876d3d371fc8f6 | /rootfs/usr/lib/pymodules/python2.6/papyon/service/AddressBook/scenario/base.py | 2546f4c9cfa6b7f4dd6eebd60276440b637da3dc | [] | no_license | xinligg/trainmonitor | 07ed0fa99e54e2857b49ad3435546d13cc0eb17a | 938a8d8f56dc267fceeb65ef7b867f1cac343923 | refs/heads/master | 2021-09-24T15:52:43.195053 | 2018-10-11T07:12:25 | 2018-10-11T07:12:25 | 116,164,395 | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 63 | py | /usr/share/pyshared/papyon/service/AddressBook/scenario/base.py | [
"[email protected]"
] | |
0bdf3e816ff9ec54f042fc647c0bff60a6dfa776 | 9e988c0dfbea15cd23a3de860cb0c88c3dcdbd97 | /sdBs/AllRun/kuv_16078+1916/sdB_kuv_16078+1916_lc.py | e2e7da47b7b2cee664f35675ccc1dfa277b97a7f | [] | 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 | 351 | py | from gPhoton.gAperture import gAperture
def main():
gAperture(band="NUV", skypos=[242.511208,19.132844], stepsz=30., csvfile="/data2/fleming/GPHOTON_OUTPU/LIGHTCURVES/sdBs/sdB_kuv_16078+1916/sdB_kuv_16078+1916_lc.csv", maxgap=1000., overwrite=True, radius=0.00555556, annulus=[0.005972227,0.0103888972], verbose=3)
if __name__ == "__main__":
main()
| [
"[email protected]"
] | |
5f3d93adb6e1b349c18fda1d3b4c003973388250 | 077a17b286bdd6c427c325f196eb6e16b30c257e | /00-BofVar/cuctf19_bof1/verified-exploit-BofVar-1.py | c2f027d3b604c21593fd4310b04ec142c6764730 | [] | no_license | KurSh/remenissions_test | 626daf6e923459b44b82521aa4cb944aad0dbced | 9dec8085b62a446f7562adfeccf70f8bfcdbb738 | refs/heads/master | 2023-07-08T20:25:04.823318 | 2020-10-05T06:45:16 | 2020-10-05T06:45:16 | null | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 1,103 | py | # +------------------------------------------------+
# | Atack: Overwrite Variables |
# +------------------------------------------------+
#
# For more info checkout: https://github.com/guyinatuxedo/nightmare/tree/master/modules/04-bof_variable
from pwn import *
import time
import sf
target = process("./chall-test_cuctf19-bof1")
gdb.attach(target)
bof_payload = sf.BufferOverflow(arch=64)
bof_payload.set_input_start(0x58)
bof_payload.add_int32(0x18, 0x1)
payload = bof_payload.generate_payload()
target.sendline(payload)
target.interactive()
# +------------------------------------------------+
# | Artist: Avenged Sevenfold |
# +------------------------------------------------+
# | Song: Hail to the King |
# +------------------------------------------------+
# | There's a taste of fear |
# | when the henchmen call |
# | iron fist to tame the lands |
# | iron fist to claim it all |
# +------------------------------------------------+
| [
"[email protected]"
] | |
8ee8d74b338bd6127549827428f21ac60c32734c | 68f78e45e7cdeeaf2f9f3e8551c5bc922971a3be | /script_12m/selfcal_scriptForImaging_continuum_flag_spw3.py | 262d1e4837e1dab96a777e9d9d956960b6f0b71d | [] | no_license | keflavich/W51_ALMA_2013.1.00308.S | cdbb2b2aa569836c15fd424356d4a0778fccd2ec | 5389047e3e8adf7bcb4f91b1f4783bcc825961f6 | refs/heads/master | 2023-02-02T08:47:30.104031 | 2023-01-30T16:21:18 | 2023-01-30T16:21:18 | 44,909,889 | 3 | 12 | null | 2016-11-09T11:58:26 | 2015-10-25T12:51:54 | TeX | UTF-8 | Python | false | false | 19,220 | py | """
run this then iterative_clean to get the "best" image
"""
import time
t0 = time.time()
phasecenter = "J2000 19:23:41.629000 +14.30.42.38000"
fields_to_selfcal = (31,32,33,39,40,24,25,20,13,21,27)
fields_after_split = [f-4 for f in fields_to_selfcal]
field = ",".join([str(x) for x in fields_after_split])
contvis='w51_spw3_continuum_flagged.split'
vis0 = 'w51_contvis_selfcal_0.ms'
os.system('rm -rf {0}'.format(vis0))
os.system('rm -rf {0}.flagversions'.format(vis0))
assert split(vis=contvis,
outputvis=vis0,
#field=','.join([str(x-4) for x in (31,32,33,39,40,24,25)]),
field='w51', # 32-4
spw='',
datacolumn='data',
)
print("Done splitting")
summary_init = flagdata(vis=vis0, mode='summary')
print("{flagged}/{total} of flagged points in vis0".format(**summary_init))
imsize = [3072,3072]
cell = '0.05arcsec'
solint = 'int'
threshold = '50.0mJy'
multiscale = [0,5,15,45]
# multiscale clean... does not work.
multiscale = []
clearcal(vis=vis0)
#flagmanager(vis=vis0, versionname='flagdata_1', mode='restore')
myimagebase = "selfcal_spw3_dirty"
os.system('rm -rf {0}.*'.format(myimagebase))
clean(vis=vis0, imagename=myimagebase, field="", spw='',
mode='mfs', outframe='LSRK', interpolation='linear', imagermode='mosaic',
interactive=False, niter=0, threshold=threshold, imsize=imsize,
cell=cell, phasecenter=phasecenter,
minpb=0.4,
weighting='briggs', usescratch=True, pbcor=True, robust=-2.0)
exportfits(myimagebase+'.image', myimagebase+'.image.fits', dropdeg=True, overwrite=True)
impbcor(imagename=myimagebase+'.image',pbimage=myimagebase+'.flux',
outfile=myimagebase+'.image.pbcor', overwrite=True)
exportfits(myimagebase+'.image.pbcor', myimagebase+'.image.pbcor.fits', dropdeg=True, overwrite=True)
exportfits(myimagebase+'.model', myimagebase+'.model.fits', dropdeg=True, overwrite=True)
exportfits(myimagebase+'.residual', myimagebase+'.residual.fits', dropdeg=True, overwrite=True)
myimagebase = "selfcal_spw3_mfs"
os.system('rm -rf {0}.*'.format(myimagebase))
clean(vis=vis0, imagename=myimagebase, field="", spw='',
mode='mfs', outframe='LSRK', interpolation='linear', imagermode='mosaic',
multiscale=multiscale,
interactive=False, niter=10000, threshold=threshold, imsize=imsize,
minpb=0.4,
cell=cell, phasecenter=phasecenter,
weighting='briggs', usescratch=True, pbcor=True, robust=-2.0)
exportfits(myimagebase+'.image', myimagebase+'.image.fits', dropdeg=True, overwrite=True)
impbcor(imagename=myimagebase+'.image',pbimage=myimagebase+'.flux',
outfile=myimagebase+'.image.pbcor', overwrite=True)
exportfits(myimagebase+'.image.pbcor', myimagebase+'.image.pbcor.fits', dropdeg=True, overwrite=True)
exportfits(myimagebase+'.model', myimagebase+'.model.fits', dropdeg=True, overwrite=True)
exportfits(myimagebase+'.residual', myimagebase+'.residual.fits', dropdeg=True, overwrite=True)
rmtables('selfcal_spw3_phase.cal')
gaincal(vis=vis0, caltable="selfcal_spw3_phase.cal", field=field, solint='inf',
calmode="p", refant="", gaintype="G", minsnr=5)
#plotcal(caltable="phase.cal", xaxis="time", yaxis="phase", subplot=331,
# iteration="antenna", plotrange=[0,0,-30,30], markersize=5,
# fontsize=10.0,)
flagmanager(vis=vis0, mode='save', versionname='backup')
applycal(vis=vis0, field="", gaintable=["selfcal_spw3_phase.cal"],
interp="linear", applymode='calonly', calwt=False)
flagmanager(vis=vis0, mode='restore', versionname='backup')
summary0 = flagdata(vis=vis0, mode='summary')
print("{flagged}/{total} flagged points in vis0".format(**summary0))
vis1 = 'w51_contvis_selfcal_1.ms'
os.system('rm -rf {0}'.format(vis1))
os.system('rm -rf {0}.flagversions'.format(vis1))
split(vis=vis0, outputvis=vis1,
datacolumn="corrected")
myimagebase="selfcal_spw3_selfcal_mfs"
os.system('rm -rf {0}.*'.format(myimagebase))
clean(vis=vis1, imagename=myimagebase,
field="", spw='', mode='mfs', outframe='LSRK',
multiscale=multiscale,
interpolation='linear', imagermode='mosaic', interactive=False,
niter=10000, threshold=threshold, imsize=imsize, cell=cell,
phasecenter=phasecenter, weighting='briggs',
minpb=0.4,
usescratch=True, pbcor=True, robust=-2.0)
exportfits(myimagebase+'.image', myimagebase+'.image.fits', dropdeg=True, overwrite=True)
impbcor(imagename=myimagebase+'.image',pbimage=myimagebase+'.flux',
outfile=myimagebase+'.image.pbcor', overwrite=True)
exportfits(myimagebase+'.image.pbcor', myimagebase+'.image.pbcor.fits', dropdeg=True, overwrite=True)
exportfits(myimagebase+'.model', myimagebase+'.model.fits', dropdeg=True, overwrite=True)
exportfits(myimagebase+'.residual', myimagebase+'.residual.fits', dropdeg=True, overwrite=True)
rmtables('selfcal_spw3_phase_2.cal')
gaincal(vis=vis1, caltable="selfcal_spw3_phase_2.cal", field=field,
solint=solint, calmode="p", refant="", gaintype="G", minsnr=5)
#plotcal(caltable="phase_2.cal", xaxis="time", yaxis="phase", subplot=331,
# iteration="antenna", plotrange=[0,0,-30,30], markersize=5,
# fontsize=10.0,)
flagmanager(vis=vis1, mode='save', versionname='backup')
applycal(vis=vis1, field="", gaintable=["selfcal_spw3_phase_2.cal"],
interp="linear", applymode='calonly', calwt=False)
flagmanager(vis=vis1, mode='restore', versionname='backup')
summary1 = flagdata(vis=vis1, mode='summary')
print("{flagged}/{total} flagged points in vis1".format(**summary1))
vis2 = 'w51_contvis_selfcal_2.ms'
os.system('rm -rf {0}'.format(vis2))
os.system('rm -rf {0}.flagversions'.format(vis2))
split(vis=vis1, outputvis=vis2,
datacolumn="corrected")
myimagebase = "selfcal_spw3_selfcal_2_mfs"
os.system('rm -rf {0}.*'.format(myimagebase))
clean(vis=vis2, imagename=myimagebase,
field="", spw='', mode='mfs', outframe='LSRK',
multiscale=multiscale,
interpolation='linear', imagermode='mosaic', interactive=False,
niter=10000, threshold=threshold, imsize=imsize, cell=cell,
minpb=0.4,
phasecenter=phasecenter, weighting='briggs',
usescratch=True, pbcor=True, robust=-2.0)
exportfits(myimagebase+'.image', myimagebase+'.image.fits', dropdeg=True, overwrite=True)
impbcor(imagename=myimagebase+'.image',pbimage=myimagebase+'.flux',
outfile=myimagebase+'.image.pbcor', overwrite=True)
exportfits(myimagebase+'.image.pbcor', myimagebase+'.image.pbcor.fits', dropdeg=True, overwrite=True)
exportfits(myimagebase+'.model', myimagebase+'.model.fits', dropdeg=True, overwrite=True)
exportfits(myimagebase+'.residual', myimagebase+'.residual.fits', dropdeg=True, overwrite=True)
rmtables("selfcal_spw3_phase_3.cal")
gaincal(vis=vis2, caltable="selfcal_spw3_phase_3.cal", field=field,
solint=solint, calmode="p", refant="", gaintype="G", minsnr=5)
#plotcal(caltable="phase_3.cal", xaxis="time", yaxis="phase", subplot=331,
# iteration="antenna", plotrange=[0,0,-30,30], markersize=5,
# fontsize=10.0,)
flagmanager(vis=vis2, mode='save', versionname='backup')
applycal(vis=vis2, field="", gaintable=["selfcal_spw3_phase_3.cal"],
interp="linear", applymode='calonly', calwt=False)
flagmanager(vis=vis2, mode='restore', versionname='backup')
summary2 = flagdata(vis=vis2, mode='summary')
print("{flagged}/{total} flagged points in vis2".format(**summary2))
vis3 = 'w51_contvis_selfcal_3.ms'
os.system('rm -rf {0}'.format(vis3))
os.system('rm -rf {0}.flagversions'.format(vis3))
split(vis=vis2, outputvis=vis3,
datacolumn="corrected")
myimagebase = "selfcal_spw3_selfcal_3_mfs"
os.system('rm -rf {0}.*'.format(myimagebase))
clean(vis=vis3, imagename=myimagebase,
field="", spw='', mode='mfs', outframe='LSRK',
multiscale=multiscale,
interpolation='linear', imagermode='mosaic', interactive=False,
minpb=0.4,
niter=10000, threshold=threshold, imsize=imsize, cell=cell,
phasecenter=phasecenter, weighting='briggs',
usescratch=True, pbcor=True, robust=-2.0)
exportfits(myimagebase+'.image', myimagebase+'.image.fits', dropdeg=True, overwrite=True)
impbcor(imagename=myimagebase+'.image',pbimage=myimagebase+'.flux',
outfile=myimagebase+'.image.pbcor', overwrite=True)
exportfits(myimagebase+'.image.pbcor', myimagebase+'.image.pbcor.fits', dropdeg=True, overwrite=True)
exportfits(myimagebase+'.model', myimagebase+'.model.fits', dropdeg=True, overwrite=True)
exportfits(myimagebase+'.residual', myimagebase+'.residual.fits', dropdeg=True, overwrite=True)
rmtables("selfcal_spw3_phase_4.cal")
gaincal(vis=vis3, caltable="selfcal_spw3_phase_4.cal", field=field, solint=solint, calmode="p",
refant="", gaintype="G", minsnr=5)
rmtables("selfcal_spw3_ampphase.cal")
gaincal(vis=vis3, caltable="selfcal_spw3_ampphase.cal", field=field, solint=solint,
solnorm=True, calmode="ap", refant="", gaintype="G", minsnr=5)
flagmanager(vis=vis3, mode='save', versionname='backup')
applycal(vis=vis3, field="", gaintable=["selfcal_spw3_phase_4.cal", 'selfcal_spw3_ampphase.cal'],
interp="linear", applymode='calonly', calwt=False)
summary3 = flagdata(vis=vis3, mode='summary')
print("{flagged}/{total} flagged points in vis3 afer applycal".format(**summary3))
flagmanager(vis=vis3, mode='restore', versionname='backup')
summary3 = flagdata(vis=vis3, mode='summary')
print("{flagged}/{total} flagged points in vis3 after restoration".format(**summary3))
vis4 = 'w51_contvis_selfcal_4.ms'
os.system('rm -rf {0}'.format(vis4))
os.system('rm -rf {0}.flagversions'.format(vis4))
split(vis=vis3, outputvis=vis4,
datacolumn="corrected")
summary4 = flagdata(vis=vis4, mode='summary')
print("{flagged}/{total} flagged points in vis4 after restoration".format(**summary4))
# WHY IS THIS EMPTY?!
myimagebase = "selfcal_spw3_selfcal_4ampphase_mfs"
os.system('rm -rf {0}.*'.format(myimagebase))
clean(vis=vis4, imagename=myimagebase,
field="", spw='', mode='mfs', outframe='LSRK',
multiscale=multiscale,
minpb=0.4,
interpolation='linear', imagermode='mosaic', interactive=False,
niter=10000, threshold=threshold, imsize=imsize, cell=cell,
phasecenter=phasecenter, weighting='briggs',
usescratch=True, pbcor=True, robust=-2.0)
exportfits(myimagebase+'.image', myimagebase+'.image.fits', dropdeg=True, overwrite=True)
impbcor(imagename=myimagebase+'.image',pbimage=myimagebase+'.flux',
outfile=myimagebase+'.image.pbcor', overwrite=True)
exportfits(myimagebase+'.image.pbcor', myimagebase+'.image.pbcor.fits', dropdeg=True, overwrite=True)
exportfits(myimagebase+'.model', myimagebase+'.model.fits', dropdeg=True, overwrite=True)
exportfits(myimagebase+'.residual', myimagebase+'.residual.fits', dropdeg=True, overwrite=True)
myimagebase = "selfcal_spw3_selfcal_4ampphase_mfs_tclean"
os.system('rm -rf {0}.*'.format(myimagebase))
tclean(vis=vis4, imagename=myimagebase, field="", spw="", specmode='mfs',
deconvolver='multiscale', gridder='mosaic', outframe='LSRK',
scales=multiscale, pblimit=0.4, interpolation='linear',
interactive=False, niter=10000,
threshold=threshold, imsize=imsize, cell=cell, phasecenter=phasecenter,
weighting='briggs', savemodel='modelcolumn', robust=-2.0)
exportfits(myimagebase+'.image', myimagebase+'.image.fits', dropdeg=True, overwrite=True)
impbcor(imagename=myimagebase+'.image', pbimage=myimagebase+'.pb',
outfile=myimagebase+'.image.pbcor', overwrite=True)
exportfits(myimagebase+'.image.pbcor', myimagebase+'.image.pbcor.fits', dropdeg=True, overwrite=True)
exportfits(myimagebase+'.model', myimagebase+'.model.fits', dropdeg=True, overwrite=True)
exportfits(myimagebase+'.residual', myimagebase+'.residual.fits', dropdeg=True, overwrite=True)
myimagebase = "selfcal_spw3_selfcal_4ampphase_mfs_tclean_deeper"
os.system('rm -rf {0}.*'.format(myimagebase))
tclean(vis=vis4, imagename=myimagebase, field="", spw="", specmode='mfs',
deconvolver='clark', gridder='mosaic', outframe='LSRK',
pblimit=0.4, interpolation='linear',
interactive=False, niter=100000,
threshold='15mJy', imsize=imsize, cell=cell, phasecenter=phasecenter,
weighting='briggs', savemodel='modelcolumn', robust=-2.0)
exportfits(myimagebase+'.image', myimagebase+'.image.fits', dropdeg=True, overwrite=True)
impbcor(imagename=myimagebase+'.image', pbimage=myimagebase+'.pb',
outfile=myimagebase+'.image.pbcor', overwrite=True)
exportfits(myimagebase+'.image.pbcor', myimagebase+'.image.pbcor.fits', dropdeg=True, overwrite=True)
exportfits(myimagebase+'.model', myimagebase+'.model.fits', dropdeg=True, overwrite=True)
exportfits(myimagebase+'.residual', myimagebase+'.residual.fits', dropdeg=True, overwrite=True)
# since ampphase fails by flagging out good data, try deeper here...
# No, something else has caused problems. Screw it, try ampphase.
# oooooh, vis3.corrected = vis4.data, and clean automatically selected corrected... sigh
myimagebase = "selfcal_spw3_selfcal_4ampphase_mfs_deeper"
os.system('rm -rf {0}.*'.format(myimagebase))
clean(vis=vis4, imagename=myimagebase,
field="", spw='', mode='mfs', outframe='LSRK',
multiscale=multiscale,
interpolation='linear', imagermode='mosaic', interactive=False,
minpb=0.4,
niter=50000, threshold='5mJy', imsize=imsize, cell=cell,
phasecenter=phasecenter, weighting='briggs',
usescratch=True, pbcor=True, robust=-2.0)
exportfits(myimagebase+'.image', myimagebase+'.image.fits', dropdeg=True, overwrite=True)
impbcor(imagename=myimagebase+'.image',pbimage=myimagebase+'.flux',
outfile=myimagebase+'.image.pbcor', overwrite=True)
exportfits(myimagebase+'.image.pbcor', myimagebase+'.image.pbcor.fits', dropdeg=True, overwrite=True)
exportfits(myimagebase+'.model', myimagebase+'.model.fits', dropdeg=True, overwrite=True)
exportfits(myimagebase+'.residual', myimagebase+'.residual.fits', dropdeg=True, overwrite=True)
# using vis2.corrected = vis3.data
myimagebase = "selfcal_spw3_selfcal_3_mfs_deeper"
os.system('rm -rf {0}.*'.format(myimagebase))
clean(vis=vis2, imagename=myimagebase,
field="", spw='', mode='mfs', outframe='LSRK',
multiscale=multiscale,
interpolation='linear', imagermode='mosaic', interactive=False,
minpb=0.4,
niter=50000, threshold='5mJy', imsize=imsize, cell=cell,
phasecenter=phasecenter, weighting='briggs',
usescratch=True, pbcor=True, robust=-2.0)
exportfits(myimagebase+'.image', myimagebase+'.image.fits', dropdeg=True, overwrite=True)
impbcor(imagename=myimagebase+'.image',pbimage=myimagebase+'.flux',
outfile=myimagebase+'.image.pbcor', overwrite=True)
exportfits(myimagebase+'.image.pbcor', myimagebase+'.image.pbcor.fits', dropdeg=True, overwrite=True)
exportfits(myimagebase+'.model', myimagebase+'.model.fits', dropdeg=True, overwrite=True)
exportfits(myimagebase+'.residual', myimagebase+'.residual.fits', dropdeg=True, overwrite=True)
import numpy as np
from astropy.io import fits
print("Stats (mfs):")
slc = slice(1007,1434), slice(1644,1900)
sigma, peak = (fits.getdata('selfcal_spw3_dirty.image.fits')[slc].std(), np.nanmax(fits.getdata('selfcal_spw3_dirty.image.fits')))
print("dirty: peak={1:0.5f} sigma={0:0.5f} s/n={2:0.5f}".format(sigma, peak, peak/sigma))
sigma, peak = (fits.getdata('selfcal_spw3_mfs.image.pbcor.fits')[slc].std(), np.nanmax(fits.getdata('selfcal_spw3_mfs.image.pbcor.fits')))
print("clean: peak={1:0.5f} sigma={0:0.5f} s/n={2:0.5f}".format(sigma, peak, peak/sigma))
sigma, peak = (fits.getdata('selfcal_spw3_selfcal_mfs.image.pbcor.fits')[slc].std(), np.nanmax(fits.getdata('selfcal_spw3_selfcal_mfs.image.pbcor.fits')))
print("selfcal: peak={1:0.5f} sigma={0:0.5f} s/n={2:0.5f}".format(sigma, peak, peak/sigma))
sigma, peak = (fits.getdata('selfcal_spw3_selfcal_2_mfs.image.pbcor.fits')[slc].std(), np.nanmax(fits.getdata('selfcal_spw3_selfcal_2_mfs.image.pbcor.fits')))
print("selfcal2: peak={1:0.5f} sigma={0:0.5f} s/n={2:0.5f}".format(sigma, peak, peak/sigma))
sigma, peak = (fits.getdata('selfcal_spw3_selfcal_3_mfs.image.pbcor.fits')[slc].std(), np.nanmax(fits.getdata('selfcal_spw3_selfcal_3_mfs.image.pbcor.fits')))
print("selfcal3: peak={1:0.5f} sigma={0:0.5f} s/n={2:0.5f}".format(sigma, peak, peak/sigma))
sigma, peak = (fits.getdata('selfcal_spw3_selfcal_4ampphase_mfs.image.pbcor.fits')[slc].std(), np.nanmax(fits.getdata('selfcal_spw3_selfcal_4ampphase_mfs.image.pbcor.fits')))
print("selfcal4 ampphase: peak={1:0.5f} sigma={0:0.5f} s/n={2:0.5f}".format(sigma, peak, peak/sigma))
print("Completed in {0}s".format(time.time()-t0))
"""
Stats (mfs):
dirty: peak=0.57990 sigma=0.00056 s/n=1031.64363
clean: peak=0.62937 sigma=0.00059 s/n=1060.74211
selfcal: peak=0.64963 sigma=0.00059 s/n=1104.06681
selfcal2: peak=0.65766 sigma=0.00059 s/n=1115.24844
selfcal3: peak=0.66613 sigma=0.00059 s/n=1129.29259
selfcal4 ampphase: peak=0.70497 sigma=0.00063 s/n=1126.32878
Completed in 2088.65619898s
"""
# Extras to try to reproduce bug:
phasecenter = "J2000 19:23:41.629000 +14.30.42.38000"
imsize = [3072,3072]
cell = '0.05arcsec'
solint = 'int'
threshold = '50.0mJy'
multiscale = [0,5,15,45]
vis4 = 'w51_contvis_selfcal_4.ms'
myimagebase = "selfcal_spw3_selfcal_4ampphase_mfs_dirty"
os.system('rm -rf {0}.*'.format(myimagebase))
clean(vis=vis4, imagename=myimagebase,
field="", spw='', mode='mfs', outframe='LSRK',
multiscale=multiscale,
interpolation='linear', imagermode='mosaic', interactive=False,
minpb=0.4,
niter=0, threshold='5mJy', imsize=imsize, cell=cell,
phasecenter=phasecenter, weighting='briggs',
usescratch=True, pbcor=True, robust=-2.0)
exportfits(myimagebase+'.image', myimagebase+'.image.fits', dropdeg=True, overwrite=True)
impbcor(imagename=myimagebase+'.image',pbimage=myimagebase+'.flux',
outfile=myimagebase+'.image.pbcor', overwrite=True)
exportfits(myimagebase+'.image.pbcor', myimagebase+'.image.pbcor.fits', dropdeg=True, overwrite=True)
exportfits(myimagebase+'.model', myimagebase+'.model.fits', dropdeg=True, overwrite=True)
exportfits(myimagebase+'.residual', myimagebase+'.residual.fits', dropdeg=True, overwrite=True)
myimagebase = "selfcal_spw3_selfcal_4ampphase_mfs_dirty_field32"
os.system('rm -rf {0}.*'.format(myimagebase))
clean(vis=vis4, imagename=myimagebase,
field="28", spw='', mode='mfs', outframe='LSRK',
multiscale=multiscale,
interpolation='linear', imagermode='mosaic', interactive=False,
minpb=0.4,
niter=0, threshold='5mJy', imsize=imsize, cell=cell,
phasecenter="", weighting='briggs',
usescratch=True, pbcor=True, robust=-2.0)
exportfits(myimagebase+'.image', myimagebase+'.image.fits', dropdeg=True, overwrite=True)
impbcor(imagename=myimagebase+'.image',pbimage=myimagebase+'.flux',
outfile=myimagebase+'.image.pbcor', overwrite=True)
exportfits(myimagebase+'.image.pbcor', myimagebase+'.image.pbcor.fits', dropdeg=True, overwrite=True)
exportfits(myimagebase+'.model', myimagebase+'.model.fits', dropdeg=True, overwrite=True)
exportfits(myimagebase+'.residual', myimagebase+'.residual.fits', dropdeg=True, overwrite=True)
| [
"[email protected]"
] | |
f430a0ac37b1b88571218138a666585365a31784 | f576f0ea3725d54bd2551883901b25b863fe6688 | /sdk/iothub/azure-mgmt-iothub/azure/mgmt/iothub/v2022_04_30_preview/_iot_hub_client.py | 47230c84ab3900aa522476f57ff1fb01a0045485 | [
"MIT",
"LicenseRef-scancode-generic-cla",
"LGPL-2.1-or-later"
] | permissive | Azure/azure-sdk-for-python | 02e3838e53a33d8ba27e9bcc22bd84e790e4ca7c | c2ca191e736bb06bfbbbc9493e8325763ba990bb | refs/heads/main | 2023-09-06T09:30:13.135012 | 2023-09-06T01:08:06 | 2023-09-06T01:08:06 | 4,127,088 | 4,046 | 2,755 | MIT | 2023-09-14T21:48:49 | 2012-04-24T16:46:12 | Python | UTF-8 | Python | false | false | 6,158 | py | # coding=utf-8
# --------------------------------------------------------------------------
# Copyright (c) Microsoft Corporation. All rights reserved.
# Licensed under the MIT License. See License.txt in the project root for license information.
# Code generated by Microsoft (R) AutoRest Code Generator.
# Changes may cause incorrect behavior and will be lost if the code is regenerated.
# --------------------------------------------------------------------------
from copy import deepcopy
from typing import Any, TYPE_CHECKING
from azure.core.rest import HttpRequest, HttpResponse
from azure.mgmt.core import ARMPipelineClient
from . import models as _models
from .._serialization import Deserializer, Serializer
from ._configuration import IotHubClientConfiguration
from .operations import (
CertificatesOperations,
IotHubOperations,
IotHubResourceOperations,
Operations,
PrivateEndpointConnectionsOperations,
PrivateLinkResourcesOperations,
ResourceProviderCommonOperations,
)
if TYPE_CHECKING:
# pylint: disable=unused-import,ungrouped-imports
from azure.core.credentials import TokenCredential
class IotHubClient: # pylint: disable=client-accepts-api-version-keyword,too-many-instance-attributes
"""Use this API to manage the IoT hubs in your Azure subscription.
:ivar operations: Operations operations
:vartype operations: azure.mgmt.iothub.v2022_04_30_preview.operations.Operations
:ivar iot_hub_resource: IotHubResourceOperations operations
:vartype iot_hub_resource:
azure.mgmt.iothub.v2022_04_30_preview.operations.IotHubResourceOperations
:ivar resource_provider_common: ResourceProviderCommonOperations operations
:vartype resource_provider_common:
azure.mgmt.iothub.v2022_04_30_preview.operations.ResourceProviderCommonOperations
:ivar certificates: CertificatesOperations operations
:vartype certificates: azure.mgmt.iothub.v2022_04_30_preview.operations.CertificatesOperations
:ivar iot_hub: IotHubOperations operations
:vartype iot_hub: azure.mgmt.iothub.v2022_04_30_preview.operations.IotHubOperations
:ivar private_link_resources: PrivateLinkResourcesOperations operations
:vartype private_link_resources:
azure.mgmt.iothub.v2022_04_30_preview.operations.PrivateLinkResourcesOperations
:ivar private_endpoint_connections: PrivateEndpointConnectionsOperations operations
:vartype private_endpoint_connections:
azure.mgmt.iothub.v2022_04_30_preview.operations.PrivateEndpointConnectionsOperations
:param credential: Credential needed for the client to connect to Azure. Required.
:type credential: ~azure.core.credentials.TokenCredential
:param subscription_id: The subscription identifier. Required.
:type subscription_id: str
:param base_url: Service URL. Default value is "https://management.azure.com".
:type base_url: str
:keyword api_version: Api Version. Default value is "2022-04-30-preview". Note that overriding
this default value may result in unsupported behavior.
:paramtype api_version: str
:keyword int polling_interval: Default waiting time between two polls for LRO operations if no
Retry-After header is present.
"""
def __init__(
self,
credential: "TokenCredential",
subscription_id: str,
base_url: str = "https://management.azure.com",
**kwargs: Any
) -> None:
self._config = IotHubClientConfiguration(credential=credential, subscription_id=subscription_id, **kwargs)
self._client: ARMPipelineClient = ARMPipelineClient(base_url=base_url, config=self._config, **kwargs)
client_models = {k: v for k, v in _models.__dict__.items() if isinstance(v, type)}
self._serialize = Serializer(client_models)
self._deserialize = Deserializer(client_models)
self._serialize.client_side_validation = False
self.operations = Operations(self._client, self._config, self._serialize, self._deserialize)
self.iot_hub_resource = IotHubResourceOperations(self._client, self._config, self._serialize, self._deserialize)
self.resource_provider_common = ResourceProviderCommonOperations(
self._client, self._config, self._serialize, self._deserialize
)
self.certificates = CertificatesOperations(self._client, self._config, self._serialize, self._deserialize)
self.iot_hub = IotHubOperations(self._client, self._config, self._serialize, self._deserialize)
self.private_link_resources = PrivateLinkResourcesOperations(
self._client, self._config, self._serialize, self._deserialize
)
self.private_endpoint_connections = PrivateEndpointConnectionsOperations(
self._client, self._config, self._serialize, self._deserialize
)
def _send_request(self, request: HttpRequest, **kwargs: Any) -> HttpResponse:
"""Runs the network request through the client's chained policies.
>>> from azure.core.rest import HttpRequest
>>> request = HttpRequest("GET", "https://www.example.org/")
<HttpRequest [GET], url: 'https://www.example.org/'>
>>> response = client._send_request(request)
<HttpResponse: 200 OK>
For more information on this code flow, see https://aka.ms/azsdk/dpcodegen/python/send_request
:param request: The network request you want to make. Required.
:type request: ~azure.core.rest.HttpRequest
:keyword bool stream: Whether the response payload will be streamed. Defaults to False.
:return: The response of your network call. Does not do error handling on your response.
:rtype: ~azure.core.rest.HttpResponse
"""
request_copy = deepcopy(request)
request_copy.url = self._client.format_url(request_copy.url)
return self._client.send_request(request_copy, **kwargs)
def close(self) -> None:
self._client.close()
def __enter__(self) -> "IotHubClient":
self._client.__enter__()
return self
def __exit__(self, *exc_details: Any) -> None:
self._client.__exit__(*exc_details)
| [
"[email protected]"
] | |
3e7c64b7612e7ce036f9a8e3bba9415c44a26cb2 | d9f6f439300d298246c37ccfb881e8e8af4fda22 | /cfp/migrations/0016_conference_programming_language.py | 9509c8683591594493f325252131db83577df5a3 | [
"MIT"
] | permissive | ajlozier/speakers | e62b8d346a58a034998860d1b42a38b00cbdbd23 | d7d87c99b1cfa5f9df5455f737385115d9d5279c | refs/heads/master | 2021-09-08T19:33:08.894305 | 2018-03-12T00:54:10 | 2018-03-12T00:54:10 | 122,101,157 | 0 | 0 | null | 2018-02-19T18:08:18 | 2018-02-19T18:08:18 | null | UTF-8 | Python | false | false | 3,218 | py | # -*- coding: utf-8 -*-
from __future__ import unicode_literals
from django.db import models, migrations
class Migration(migrations.Migration):
dependencies = [
('cfp', '0015_auto_20150214_1834'),
]
operations = [
migrations.AddField(
model_name='conference',
name='programming_language',
field=models.CharField(default='', choices=[('', ''), ('Actionscript', 'Actionscript'), ('Ada', 'Ada'), ('Agda', 'Agda'), ('Android', 'Android'), ('AppceleratorTitanium', 'AppceleratorTitanium'), ('ArchLinuxPackages', 'ArchLinuxPackages'), ('Autotools', 'Autotools'), ('Bancha', 'Bancha'), ('C', 'C'), ('C++', 'C++'), ('CFWheels', 'CFWheels'), ('CMake', 'CMake'), ('CakePHP', 'CakePHP'), ('ChefCookbook', 'ChefCookbook'), ('Clojure', 'Clojure'), ('CodeIgniter', 'CodeIgniter'), ('CommonLisp', 'CommonLisp'), ('Composer', 'Composer'), ('Concrete5', 'Concrete5'), ('Coq', 'Coq'), ('CraftCMS', 'CraftCMS'), ('DM', 'DM'), ('Dart', 'Dart'), ('Delphi', 'Delphi'), ('Drupal', 'Drupal'), ('EPiServer', 'EPiServer'), ('Eagle', 'Eagle'), ('Elisp', 'Elisp'), ('Elixir', 'Elixir'), ('Erlang', 'Erlang'), ('ExpressionEngine', 'ExpressionEngine'), ('ExtJS-MVC', 'ExtJS-MVC'), ('Fancy', 'Fancy'), ('Finale', 'Finale'), ('ForceDotCom', 'ForceDotCom'), ('Fortran', 'Fortran'), ('FuelPHP', 'FuelPHP'), ('GWT', 'GWT'), ('GitBook', 'GitBook'), ('Go', 'Go'), ('Gradle', 'Gradle'), ('Grails', 'Grails'), ('Haskell', 'Haskell'), ('Idris', 'Idris'), ('Java', 'Java'), ('Jboss', 'Jboss'), ('Jekyll', 'Jekyll'), ('Joomla', 'Joomla'), ('Jython', 'Jython'), ('Kohana', 'Kohana'), ('LabVIEW', 'LabVIEW'), ('Laravel', 'Laravel'), ('Leiningen', 'Leiningen'), ('LemonStand', 'LemonStand'), ('Lilypond', 'Lilypond'), ('Lithium', 'Lithium'), ('Magento', 'Magento'), ('Maven', 'Maven'), ('Mercury', 'Mercury'), ('MetaProgrammingSystem', 'MetaProgrammingSystem'), ('Meteor', 'Meteor'), ('Node', 'Node'), ('OCaml', 'OCaml'), ('Objective-C', 'Objective-C'), ('Opa', 'Opa'), ('OracleForms', 'OracleForms'), ('Packer', 'Packer'), ('Perl', 'Perl'), ('Phalcon', 'Phalcon'), ('PlayFramework', 'PlayFramework'), ('Plone', 'Plone'), ('Prestashop', 'Prestashop'), ('Processing', 'Processing'), ('Python', 'Python'), ('Qooxdoo', 'Qooxdoo'), ('Qt', 'Qt'), ('R', 'R'), ('ROS', 'ROS'), ('Rails', 'Rails'), ('RhodesRhomobile', 'RhodesRhomobile'), ('Ruby', 'Ruby'), ('Rust', 'Rust'), ('SCons', 'SCons'), ('Sass', 'Sass'), ('Scala', 'Scala'), ('Scrivener', 'Scrivener'), ('Sdcc', 'Sdcc'), ('SeamGen', 'SeamGen'), ('SketchUp', 'SketchUp'), ('SugarCRM', 'SugarCRM'), ('Swift', 'Swift'), ('Symfony', 'Symfony'), ('SymphonyCMS', 'SymphonyCMS'), ('Target3001', 'Target3001'), ('Tasm', 'Tasm'), ('TeX', 'TeX'), ('Textpattern', 'Textpattern'), ('TurboGears2', 'TurboGears2'), ('Typo3', 'Typo3'), ('Umbraco', 'Umbraco'), ('Unity', 'Unity'), ('VVVV', 'VVVV'), ('VisualStudio', 'VisualStudio'), ('Waf', 'Waf'), ('WordPress', 'WordPress'), ('Xojo', 'Xojo'), ('Yeoman', 'Yeoman'), ('Yii', 'Yii'), ('ZendFramework', 'ZendFramework'), ('Zephir', 'Zephir'), ('gcov', 'gcov'), ('nanoc', 'nanoc'), ('opencart', 'opencart'), ('stella', 'stella')], db_index=True, max_length=30),
preserve_default=True,
),
]
| [
"[email protected]"
] |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.