Dataset Viewer
__id__
int64 17.2B
19,722B
| blob_id
stringlengths 40
40
| directory_id
stringlengths 40
40
| path
stringlengths 4
133
| content_id
stringlengths 40
40
| detected_licenses
sequence | license_type
stringclasses 3
values | repo_name
stringlengths 7
73
| repo_url
stringlengths 26
92
| snapshot_id
stringlengths 40
40
| revision_id
stringlengths 40
40
| branch_name
stringclasses 12
values | visit_date
timestamp[ns] | revision_date
timestamp[ns] | committer_date
timestamp[ns] | github_id
int64 61.3k
283M
⌀ | star_events_count
int64 0
47
| fork_events_count
int64 0
15
| gha_license_id
stringclasses 5
values | gha_fork
bool 2
classes | gha_event_created_at
timestamp[ns] | gha_created_at
timestamp[ns] | gha_updated_at
timestamp[ns] | gha_pushed_at
timestamp[ns] | gha_size
int64 0
5.76M
⌀ | gha_stargazers_count
int32 0
82
⌀ | gha_forks_count
int32 0
25
⌀ | gha_open_issues_count
int32 0
80
⌀ | gha_language
stringclasses 5
values | gha_archived
bool 1
class | gha_disabled
bool 1
class | content
stringlengths 19
187k
| src_encoding
stringclasses 4
values | language
stringclasses 1
value | is_vendor
bool 1
class | is_generated
bool 1
class | year
int64 2k
2.01k
|
---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
4,191,888,086,158 |
18a5246b0b6779b2316407c203e6699f38779a28
|
83380cb5dd9388d8ed684560a2a9674f2ed4440a
|
/src/petl/interactive.py
|
0d2859b13465d4f30369771390c7ab2f2a11df80
|
[
"MIT"
] |
permissive
|
obsoleter/petl
|
https://github.com/obsoleter/petl
|
f60590db7c57dd9046e4f42f2dd7b38e56cfb3b0
|
e3e8ff5423482f7c61974e66acea631027762ea3
|
refs/heads/master
| 2020-06-02T01:15:45.048000 | 2013-03-07T17:35:29 | 2013-03-07T17:35:29 | 8,632,864 | 1 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null |
"""
As the root :mod:`petl` module but with optimisations for use in an interactive
session.
"""
from itertools import islice
import sys
from .util import valueset, RowContainer
import petl.fluent
import collections
petl = sys.modules['petl']
thismodule = sys.modules[__name__]
cachesize = 1000
debug = False
representation = petl.look
class InteractiveWrapper(petl.fluent.FluentWrapper):
def __init__(self, inner):
super(InteractiveWrapper, self).__init__(inner)
object.__setattr__(self, '_cache', [])
object.__setattr__(self, '_tag', None)
object.__setattr__(self, '_cachecomplete', False)
def __iter__(self):
try:
tag = self._inner.cachetag()
except:
# cannot cache for some reason, just pass through
if debug: print(repr(self._inner) + ' :: uncacheable')
return iter(self._inner)
else:
if self._tag is None or self._tag != tag:
# _tag is not fresh
if debug: print(repr(self._inner) + ' :: stale, clearing cache')
object.__setattr__(self, '_cache', []) # reset cache
object.__setattr__(self, '_tag', tag)
object.__setattr__(self, '_cachecomplete', False)
return self._iterwithcache()
def _iterwithcache(self):
if debug: print(repr(self._inner) + ' :: serving from cache, cache size ' + str(len(self._cache)))
# serve whatever is in the cache first
for row in self._cache:
yield row
if not self._cachecomplete:
# serve the remainder from the inner iterator
if debug: print(repr(self._inner) + ' :: cache exhausted, serving from inner iterator')
it = iter(self._inner)
for row in islice(it, len(self._cache), None):
# maybe there's more room in the cache?
if len(self._cache) < cachesize:
self._cache.append(row)
yield row
if len(self._cache) < cachesize:
object.__setattr__(self, '_cachecomplete', True)
def __repr__(self):
if representation is not None:
return repr(representation(self))
else:
return object.__repr__(self)
def wrap(f):
def wrapper(*args, **kwargs):
_innerresult = f(*args, **kwargs)
if isinstance(_innerresult, RowContainer):
return InteractiveWrapper(_innerresult)
else:
return _innerresult
wrapper.__name__ = f.__name__
wrapper.__doc__ = f.__doc__
return wrapper
# import and wrap all functions from root petl module
for n, c in list(petl.__dict__.items()):
if isinstance(c, collections.Callable):
setattr(thismodule, n, wrap(c))
else:
setattr(thismodule, n, c)
# add module functions as methods on the wrapper class
# TODO add only those methods that expect to have row container as first argument
for n, c in list(thismodule.__dict__.items()):
if isinstance(c, collections.Callable):
setattr(InteractiveWrapper, n, c)
# need to manually override for facet, because it returns a dict
def facet(table, field):
fct = dict()
for v in valueset(table, field):
fct[v] = getattr(thismodule, 'selecteq')(table, field, v)
return fct
# need to manually override for diff(), because it returns a tuple
def diff(*args, **kwargs):
a, b = petl.diff(*args, **kwargs)
return InteractiveWrapper(a), InteractiveWrapper(b)
|
UTF-8
|
Python
| false | false | 2,013 |
8,598,524,527,749 |
476ba0c1cd32e3473638c0ce13b6c6fc33af963e
|
1db4f25f6cd4003615a2d97a37c2110f8f27555a
|
/mysql/einfach/TestUserRepository.py
|
6ce4528aafe67ffc8cd99bef973215931027477e
|
[] |
no_license
|
ww-lessons/datenhistorisierung
|
https://github.com/ww-lessons/datenhistorisierung
|
5baed6108c8f181a9004e29339bb0a270119fffa
|
e3d4798b096cfe57ece2352a08ec15806634ec9a
|
refs/heads/master
| 2020-04-05T23:44:24.056000 | 2014-12-04T16:35:42 | 2014-12-04T16:35:42 | null | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null |
# coding=utf-8
from UserRepository import UserRepository
from datetime import datetime
import time
import unittest
USERNAME = 'Mustermann.Max'
class SimpleHistoryMySQLTestCase(unittest.TestCase):
def test_create_user(self):
repo = UserRepository()
user = repo.create_user(USERNAME)
self.assertEqual(user.username, USERNAME)
def test_list_users(self):
repo = UserRepository()
list = repo.list_users()
for item in list:
print item
self.assertLessEqual(1, len(list))
def test_update_user_empty(self):
time.sleep(1)
repo = UserRepository()
user = repo.get_user_by_name(USERNAME)
user.birth_date = None
user.description = None
user.assigned_rolename = None
repo.update_user(user)
user2 = repo.get_user_by_name(USERNAME)
self.assertEqual(None, user2.birth_date)
self.assertEqual(user.assigned_rolename, user2.assigned_rolename)
self.assertEqual(user.description, user2.description)
def test_update_user(self):
repo = UserRepository()
user = repo.get_user_by_name(USERNAME)
user.birth_date = datetime.now()
user.description = "Description"
user.assigned_rolename = "Beispielrolle"
repo.update_user(user)
user2 = repo.get_user_by_name(USERNAME)
self.assertNotEqual(None, user2.birth_date)
self.assertEqual(user.assigned_rolename, user2.assigned_rolename)
self.assertEqual(user.description, user2.description)
def test_get_history(self):
repo = UserRepository()
user = repo.get_user_by_name(USERNAME)
history = repo.get_history(USERNAME)
print "History for User {0}:{1}:".format(user.username, user.valid_until)
for version in history:
print " Version {0}:{1}:{2}:{3}".format(version.username, version.valid_until,
version.description, version.assigned_rolename)
def test_xdelete_user(self):
repo = UserRepository()
repo.delete_user(USERNAME)
if __name__ == '__main__':
unittest.main()
|
UTF-8
|
Python
| false | false | 2,014 |
1,185,411,018,453 |
77fdb229f95f0647ef25dc36a176447e7986f496
|
949df3d182cf893acebf300057a99643cd4d792d
|
/tags/SKUNKWEB_RELEASE_3_4_2/SkunkWeb/Services/oracle/__init__.py
|
7b87ca22501e77dab431eac887991f941786543b
|
[
"GPL-1.0-or-later",
"LicenseRef-scancode-other-copyleft",
"LicenseRef-scancode-philippe-de-muyter",
"GPL-2.0-only"
] |
non_permissive
|
BackupTheBerlios/skunkweb-svn
|
https://github.com/BackupTheBerlios/skunkweb-svn
|
112aa0d3a28efdfbf87e3120c980589a98d2fee4
|
19a497ee9316760bf8c8504ebd185acc91c753f0
|
refs/heads/master
| 2016-09-05T15:23:31.069000 | 2008-02-29T17:26:02 | 2008-02-29T17:26:02 | 40,803,350 | 1 | 1 | null | null | null | null | null | null | null | null | null | null | null | null | null |
#
# Copyright (C) 2001 Andrew T. Csillag <[email protected]>
#
# You may distribute under the terms of either the GNU General
# Public License or the SkunkWeb License, as specified in the
# README file.
#
from SkunkWeb import Configuration, LogObj, ServiceRegistry
from requestHandler.requestHandler import CleanupRequest
import Oracle
ServiceRegistry.registerService('oracle')
Configuration.mergeDefaults(
OracleConnectStrings = {},
OracleProcedurePackageLists = {}
)
for u, str in Configuration.OracleConnectStrings.items():
LogObj.DEBUG(ServiceRegistry.ORACLE, 'initializing user %s' % u)
Oracle.initUser(u, str)
for u, pkglist in Configuration.OracleProcedurePackageLists:
Oracle.loadSignatures(u, pkglist, LogObj.LOG,
lambda x: LogObj.DEBUG(ServiceRegistry.ORACLE, x))
def rollbackConnection(*args):
for v in Oracle._connections.values():
v.rollback()
CleanupRequest.addFunction(rollbackConnection)
|
UTF-8
|
Python
| false | false | 2,008 |
11,716,670,807,757 |
6785034ca4ff3b8616c9b86c827a5481ef116897
|
8b36013b62e5c39772c7d84444916fa0daec2783
|
/flypy/tests/test_cffi.py
|
ee7bfa9d5271659db364373055d8574b58380313
|
[
"BSD-2-Clause"
] |
permissive
|
filmackay/flypy
|
https://github.com/filmackay/flypy
|
cc7cfad447905ecd2211ab462ccc9ca6e0b469a5
|
1fd06e2d4189d3355fa0e8c1a66657c5423591b4
|
refs/heads/master
| 2021-01-17T17:10:44.892000 | 2014-03-18T15:44:39 | 2014-03-18T15:44:39 | 17,741,144 | 0 | 1 | null | null | null | null | null | null | null | null | null | null | null | null | null |
# -*- coding: utf-8 -*-
from __future__ import print_function, division, absolute_import
import math
import unittest
from flypy import jit
try:
import cffi
ffi = cffi.FFI()
except ImportError:
ffi = None
# ______________________________________________________________________
ffi.cdef("int printf(char *, ...);")
ffi.cdef("double cos(double);")
lib = ffi.dlopen(None)
libm = ffi.dlopen('m')
printf = lib.printf
cos = libm.cos
# ______________________________________________________________________
class TestCFFI(unittest.TestCase):
def test_call_c_strings(self):
raise unittest.SkipTest("TODO: unwrap() arguments to FFI calls")
@jit
def f(value):
return printf(value)
f("Hello world!\n")
def test_call(self):
@jit
def f(value):
return cos(value)
self.assertEqual(f(math.pi), -1.0)
# ______________________________________________________________________
if __name__ == "__main__":
unittest.main()
|
UTF-8
|
Python
| false | false | 2,014 |
6,880,537,637,918 |
a108703fce94d8ddf10084ae51dfc6fb18daf4fc
|
81a7871d6afdfd6fc4b9087d7c1774b0eb042925
|
/bom_stock/__openerp__.py
|
ef33f5b2c984296adff35a5036863fc8cdb23f61
|
[] |
no_license
|
credativUK/product-kitting-bom-stock-fixes
|
https://github.com/credativUK/product-kitting-bom-stock-fixes
|
b3a2c7b03aa2e710a20819f88602e193ddd7ad66
|
c3fa9465cde4da7167c8112894fdb7d0990069c8
|
refs/heads/master
| 2021-01-19T03:11:30.617000 | 2014-07-30T13:47:29 | 2014-07-30T13:47:29 | 22,427,728 | 1 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null |
# -*- encoding: utf-8 -*-
##############################################################################
#
# Copyright Camptocamp SA
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program. If not, see <http://www.gnu.org/licenses/>.
#
##############################################################################
{
'name': 'Compute Stock from BoM',
'version': '5.0.2',
'category': 'Generic Modules/Others',
'description':
"""Compute the BOM stock Value. BoM Stock Value are computed by:
(`Reference stock` of `Product` + How much could I produce of that `Product` according to the component's `Reference Stock`)
This reference stock can be chosen by company through a selection field
and can be one of the available stock quantity computed in the system :
Available stock, Virtual stock, immediately_usable stock (from
stock_available_immediately)."""
,
'author': 'Camptocamp',
'website': 'http://www.camptocamp.com',
'depends': ['stock',
'mrp',
'stock_available_immediately',
],
'data': ['bom_stock_view.xml'],
'demo': [],
'test': ['tests/test_bom_stock.yml',
],
'installable': True,
'active': False,
}
# vim:expandtab:smartindent:tabstop=4:softtabstop=4:shiftwidth=4:
|
UTF-8
|
Python
| false | false | 2,014 |
5,377,299,080,165 |
20dcb0e8d8e60fdb4ce22c25f3b9e008de232d5e
|
d6bbd6cb0d70f8fb085b44d1f28d7c3b748c0799
|
/closures.py
|
c70961bda0f9c5227731b4c5021fb3456d0b28cb
|
[] |
no_license
|
viniciusfeitosa/estudosPython
|
https://github.com/viniciusfeitosa/estudosPython
|
92c9915cab53623c7811b7340f19b0c19cf77bec
|
c629ff17adb9de81f1be0a71be7259910c1acd49
|
refs/heads/master
| 2016-08-07T12:09:58.625000 | 2014-03-10T03:49:18 | 2014-03-10T03:49:18 | null | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null |
#!/usr/bin/env python
# -*- conding: utf-8 -*-
# closures.py - Exemplo de closures
import time
def fib(n): #Calcula fibonacci de forma recursiva
if n < 2: return 1
return fib(n-1) + fib(n-2)
def memoize(fn):
memo = {}
def memoizer(*param1):
key = repr(param1)
if not key in memo:
memo[key] = fn(*param1)
return memo[key]
return memoizer
t1 = time.time()
for i in range(20):
fib(i)
t2 = time.time()
# Adiciona o suporte a cache em fib
fib = memoize(fib)
t3 = time.time()
for i in range(20):
fib(i)
t4 = time.time()
print "Tempo da funcao fib() normal (20 chamadas): %2.5fs" % (t2-t1)
print "Tempo da funcao fib() memoize (20 chamadas): %2.5fs" % (t4-t3)
|
UTF-8
|
Python
| false | false | 2,014 |
18,356,690,238,131 |
01c7c68081faf3018f326bf011d8f580026a5b4a
|
7f0a01fd9e37ddff02b371aefca357da5cc3ee74
|
/loho/apps/blog/admin.py
|
3a55112d61ccc26de481a921fe4b342afbb59593
|
[] |
no_license
|
lorenmh/lorenhoward.com
|
https://github.com/lorenmh/lorenhoward.com
|
ade10f962a8c5e8a3e811b8f1aa3eccb0db36fdb
|
7b61f63a16f718f4603814daa5fad57c58ed01b2
|
refs/heads/master
| 2021-01-23T01:41:15.740000 | 2014-10-06T04:55:26 | 2014-10-06T04:55:26 | 15,729,115 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null |
from apps.blog.models import Blog, BlogImage
from apps.comment.models import Comment
from django.contrib.contenttypes import generic
from django import forms
from django.contrib import admin
class CommentInline(generic.GenericStackedInline):
model = Comment
extra = 0
readonly_fields = ('name','email','subject','text',)
class BlogImageInline(admin.StackedInline):
extra = 3
model = BlogImage
class BlogAdmin(admin.ModelAdmin):
inlines = [CommentInline, BlogImageInline];
filter_horizontal = ['tags',]
prepopulated_fields = {"url": ("title",)}
admin.site.register(Blog, BlogAdmin)
|
UTF-8
|
Python
| false | false | 2,014 |
5,437,428,604,910 |
d74e2100e46a8c85154acc172165912d5310e5e7
|
cf1f609ac79783e58a710b0367dc90e7147d2c84
|
/cgi-bin/tompressor.py
|
a221f2d582b3079100416120c0cefdd8329d6f13
|
[
"Apache-2.0"
] |
permissive
|
whereistom/Tompressor
|
https://github.com/whereistom/Tompressor
|
77379f9ba35df3f8a5e4bfb85a60bcd04fdc5807
|
3733bad6e5a7c4fc2b5eac6243969848756e59b1
|
refs/heads/master
| 2021-01-10T19:50:04.102000 | 2012-09-28T06:30:55 | 2012-09-28T06:30:55 | null | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null |
#!/usr/bin/python
#
# Imports
#
import functions
import result
import httplib
import urlparse
import time
import sys
import hashlib
import cgi
import cgitb
cgitb.enable()
#######################
# Initialization area #
#######################
#database /path/name.sqlite
dbname = "tompressor.sqlite"
#read user input
form = cgi.FieldStorage()
longurl = form.getvalue("longurl")
##################################
# section 1: verify users' input #
##################################
#verify that the input is not null
if longurl is None:
#handle the error
result.redirect_to_error("BLANK")
sys.exit(1)
#verify that the URL is not longer then 2083 chars. Following recommandations here http://www.boutell.com/newfaq/misc/urllength.html
if len(longurl) > 2083:
#handle the error
#print only first 50 chars...
result.redirect_to_error(longurl[0:50]+"...")
sys.exit(1)
#verify lazy user input without http:// substring
if longurl.startswith('http://', 0, 7) is False:
longurl = "http://"+ longurl
#check after adding http:// if there is a valid port in the url
if functions.http_port_in_url(longurl) is False:
result.redirect_to_error(longurl)
#check for active URL to avoid a database full of junk
if functions.check_url(longurl) is False:
#handle the error
result.redirect_to_error(longurl)
sys.exit(1)
##################################
# section 2: database operations #
##################################
# Calculation of url's SHA1
urlhash = hashlib.sha1()
urlhash.update(longurl)
# We check for duplicate entry (users might input url already in our DB)
id = functions.sqlite3_check_for_duplicate(dbname, urlhash.hexdigest())
if id:
#if we already have an entry we give the result to the user
shorturl=functions.base62encoding(id,)
result.redirect_to_result(shorturl, longurl)
else:
# We insert in DBNAME, the longurl and the sha1(longurl)
id = functions.sqlite3_insert_url(dbname, longurl, urlhash.hexdigest())
#compute the shorturl
shorturl = functions.base62encoding(id,)
#send the result to the user
result.redirect_to_result(shorturl, longurl)
|
UTF-8
|
Python
| false | false | 2,012 |
17,222,818,875,269 |
c4199aceac67f2269f0c73cabf3abb37c47dc48b
|
8512ff37fca380558b883c11c3c1a20f731219a4
|
/minimo/fattura/management/commands/from_cliente_to_fattura.py
|
0366aa3493253c179486d405c08a269e0e9b1036
|
[
"LGPL-2.1-or-later",
"GPL-1.0-or-later",
"GPL-2.0-or-later",
"GPL-2.0-only",
"LicenseRef-scancode-warranty-disclaimer"
] |
non_permissive
|
algebreico/minimo
|
https://github.com/algebreico/minimo
|
6adf2212b1474d2c9338784d556cc54201cf20fa
|
c01da75f9473718783b24125d0f93c762ff38f6c
|
refs/heads/master
| 2020-12-25T10:24:48.662000 | 2013-08-19T17:42:57 | 2013-08-19T17:42:57 | null | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null |
import logging
import sys, os, socket, re
from django.core.management.base import NoArgsCommand
from django.db.models import Avg, Sum
from minimo.fattura.models import *
from datetime import datetime, timedelta
class Command(NoArgsCommand):
help = "genera le medie."
def handle_noargs(fattura, **options):
fatture = Fattura.objects.all()
print len(fatture)
conv = 0
for fattura in fatture:
#codice per recuperare dati da vecchia versione del db
fattura.ragione_sociale = fattura.cliente.ragione_sociale
fattura.via = fattura.cliente.via
fattura.cap = fattura.cliente.cap
fattura.citta = fattura.cliente.citta
fattura.provincia = fattura.cliente.provincia
fattura.p_iva = fattura.cliente.p_iva
fattura.cod_fiscale = fattura.cliente.cod_fiscale
fattura.save()
print fattura.ragione_sociale
conv += 1
print "convertite %s fatture" %conv
|
UTF-8
|
Python
| false | false | 2,013 |
1,065,151,897,224 |
8c1e272a0564c0b48fb7c1b759c3f3fe64d3dadc
|
414144d0c94f8e0ff5d325c83a17bf277f9e30b2
|
/datatypes/datapoint.py
|
2a6833d2a9b027a2e9a312bda83836dbc41ae127
|
[] |
no_license
|
stenri/PyBacktest
|
https://github.com/stenri/PyBacktest
|
2f6a82cdff4581a46dd9ec0450e139599926abe8
|
98e90bc4ad520921dfa858b4931b07c9249b4e77
|
refs/heads/master
| 2021-01-18T13:46:43.220000 | 2012-10-26T15:14:04 | 2012-10-26T15:14:04 | 6,405,707 | 1 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null |
# coding: utf8
import datetime
from decimal import Decimal
base_fields = ('O', 'H', 'L', 'C', 'V')
readonly_fields = ('Date', 'Time', 'date', 'time', 'TS', 'ts')
fields = ('O', 'H', 'L', 'C', 'V', 'timestamp', 'contract')
repr_fields = base_fields
class Datapoint(dict):
''' Market datapoint (e.g. tick or bar) '''
def __init__(self, **kwargs):
[setattr(self, k, v) for k, v in kwargs.iteritems() if k in fields]
def __reprstring(self):
s = ''
for f in repr_fields:
if hasattr(self, f):
if len(s) != 0:
s += ' / '
s += '%s %s' % (f, str(getattr(self, f)))
return s
def __repr__(self):
return '<(%s) %s>' % (self.timestamp, self.__reprstring())
def __getattr__(self, name):
try:
return self[name]
except KeyError as e:
raise AttributeError(e)
def __setattr__(self, name, value):
if not name in readonly_fields:
self[name] = value
else:
raise Exception("Attribute '%s' is read-only." % name)
@property
def fields(self):
return [f for f in fields if hasattr(self, f)]
@property
def Date(self):
''' Legacy compatibility conversion. '''
return int(self.timestamp.strftime("%Y%m%d"))
@property
def Time(self):
''' Legacy compatibility conversion. '''
if self.timestamp.microsecond == 0:
return int(self.timestamp.strftime("%H%M%S"))
else:
return float(self.timestamp.strftime("%H%M%S.%f"))
@property
def TS(self):
return self.timestamp
def decimalize(self):
"""Convert all float attributes to decimals with 5-point precision."""
for k, v in self.__dict__.iteritems():
if isinstance(float, v):
setattr(self, k, Decimal(v).quantize('1.00000'))
## -------------------------------------------------------
# Compatibility classes
class bar(Datapoint):
pass
class Bar(bar):
def __init__(self, Date, Time, O, H, L, C, V):
self.timestamp = datetime.datetime.strptime(str(int(Date))+" "+str(int(Time)), "%Y%m%d %H%M%S")
self.O = float(O)
self.H = float(H)
self.L = float(L)
self.C = float(C)
self.V = float(V)
class tick(Datapoint):
pass
class Tick(tick):
def __init__(self, Date, Time, C, V, OI=None):
self.timestamp = datetime.datetime.strptime(str(int(Date))+" "+str(int(Time)), "%Y%m%d %H%M%S")
self.C = float(C)
self.V = float(V)
if OI != None:
self.OI = OI
## --------------------------------------------------------
class BarFrame(object):
def __init__(self, datapoints):
self.frame = data.BarsToDataframe(datapoints)
def __repr__(self):
return '<BarFrame %s .. %s>' % (self.frame['timestamp'][0].date(),
self.frame['timestamp'][-1].date())
@property
def datapoints(self):
return data.BarsFromDataframe(self.frame)
DatapointContainer = BarFrame
|
UTF-8
|
Python
| false | false | 2,012 |
15,169,824,495,279 |
ac801e5a58889920b01465abe07afafa46d9fc5a
|
d5214b1331c9dae59d95ba5b3aa3e9f449ad6695
|
/quintagroup.plonecaptchas/branches/compatible-plone4/quintagroup/plonecaptchas/browser/view.py
|
2c3ef7f6d3ec092ec9548b98f93868abe309d372
|
[] |
no_license
|
kroman0/products
|
https://github.com/kroman0/products
|
1661ee25a224c4b5f172f98110944f56136c77cf
|
f359bb64db22f468db5d1e411638790e94d535a2
|
refs/heads/master
| 2021-01-10T07:58:04.579000 | 2014-06-11T12:05:56 | 2014-06-11T12:05:56 | 52,677,831 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null |
from DateTime import DateTime
from zope.interface import implements
from Acquisition import aq_parent
from Products.Five import BrowserView
from Products.CMFCore.utils import getToolByName
from quintagroup.plonecaptchas.browser.interfaces import ICaptchaView
from quintagroup.plonecaptchas.utils import decrypt, parseKey, encrypt1, getWord
COOKIE_ID = 'captchahashkey'
class Captcha(BrowserView):
implements(ICaptchaView)
def getSafeContext(self):
""" Return context for this view that is acquisition aware (it's needed
because when this view is called from captcha widget self.context
may be some adapted object and it isn't aqcuisiton wrapped).
"""
if aq_parent(self.context) is not None:
return self.context
else:
return self.context.context
def image_tag(self):
""" Generate an image tag linking to a captcha """
context = self.getSafeContext()
hk = context.getCaptcha()
resp = self.request.response
if COOKIE_ID in resp.cookies:
# clear the cookie first, clearing out any expiration cookie
# that may have been set during verification
del resp.cookies[COOKIE_ID]
resp.setCookie(COOKIE_ID, hk, path='/')
portal_url = getToolByName(context, 'portal_url')()
img_url = '%s/getCaptchaImage/%s' % (portal_url, hk)
return '<img src="%s" />' % img_url
def verify(self, input):
context = self.getSafeContext()
result = False
try:
hashkey = self.request[COOKIE_ID]
self.request.response.expireCookie(COOKIE_ID, path='/')
decrypted_key = decrypt(context.captcha_key, hashkey)
parsed_key = parseKey(decrypted_key)
index = parsed_key['key']
date = parsed_key['date']
captcha_type = context.getCaptchaType()
if captcha_type == 'static':
img = getattr(context, '%s.jpg' % index)
solution = img.title
enc = encrypt1(input)
else:
enc = input
solution = getWord(int(index))
captcha_tool = getToolByName(context, 'portal_captchas')
if (enc != solution) or (captcha_tool.has_key(decrypted_key)) or (DateTime().timeTime() - float(date) > 3600):
pass
else:
captcha_tool.addExpiredKey(decrypted_key)
result = True
except KeyError:
pass # No cookie
return result
|
UTF-8
|
Python
| false | false | 2,014 |
15,762,529,997,351 |
1770de8c8d0579bac38fc7994759f6da0f226ac1
|
e2f04785b6c91637cb1ddeca9682869fc5d3c899
|
/cmake/EnvConfig/TestEnvOps.py
|
b501534207c0c11c6406d9b6d818debd32c31fa6
|
[] |
no_license
|
atlas-org/gaudi
|
https://github.com/atlas-org/gaudi
|
26dab8f3da294c2de5263946c5a25a5008c3254e
|
3d132a898a505fe4064181567f2d4118531989bb
|
refs/heads/master
| 2020-04-29T17:19:56.511000 | 2013-12-03T16:48:49 | 2013-12-03T16:48:49 | 12,948,370 | 1 | 1 | null | null | null | null | null | null | null | null | null | null | null | null | null |
'''
Created on Jul 12, 2011
@author: mplajner
'''
import unittest
import os
import sys
import shutil
from tempfile import mkdtemp
from EnvConfig import Variable
from EnvConfig import Control
# Keep only some Variable processors.
saved_processors = Variable.processors
Variable.processors = [Variable.EnvExpander,
Variable.PathNormalizer,
Variable.DuplicatesRemover]
def buildDir(files, rootdir=os.curdir):
'''
Create a directory structure from the content of files.
@param files: a dictionary or list of pairs mapping a filename to the content
if the content is a dictionary, recurse
@param rootdir: base directory
'''
if type(files) is dict:
files = files.items()
# ensure that the root exists (to allow empty directories)
if not os.path.exists(rootdir):
os.makedirs(rootdir)
# create all the entries
for filename, data in files:
filename = os.path.join(rootdir, filename)
if type(data) is dict:
buildDir(data, filename)
else:
d = os.path.dirname(filename)
if not os.path.exists(d):
os.makedirs(d)
f = open(filename, "w")
if data:
f.write(data)
f.close()
class TempDir(object):
'''
Class for easy creation, use and removal of temporary directory structures.
'''
def __init__(self, files=None):
self.tmpdir = mkdtemp()
if files is None:
files = {}
buildDir(files, self.tmpdir)
def __del__(self):
shutil.rmtree(self.tmpdir, ignore_errors=False)
def __call__(self, *args):
'''
Return the absolute path to a file in the temporary directory.
'''
return os.path.join(self.tmpdir, *args)
class Test(unittest.TestCase):
def setUp(self):
pass
def tearDown(self):
pass
def testValues(self):
'''Test of value appending, prepending, setting, unsetting, removing'''
control = Control.Environment()
self.assertFalse('MY_PATH' in control.vars())
control.append('MY_PATH', 'newValue')
self.assertTrue('MY_PATH' in control.vars())
var = control.var('MY_PATH')
control.append('MY_PATH', 'newValue:secondVal:valval')
self.assertTrue(var[len(var)-1] == 'valval')
self.assertTrue('newValue' in var)
control.remove('MY_PATH', 'newValue')
self.assertFalse('newValue' in var)
control.prepend('MY_PATH', 'newValue')
self.assertTrue('newValue' == var[0])
control.set('MY_PATH', 'hi:hello')
self.assertTrue(len(var) == 2)
self.assertTrue('hi' == var[0])
control.unset('MY_PATH')
self.assertTrue('MY_PATH' not in control)
def testWrite(self):
"""XML file write and load test"""
control = Control.Environment(useAsWriter = True)
control.unset('MY_PATH')
control.set('MY_PATH', 'set:toDelete')
control.append('MY_PATH', 'appended:toDelete')
control.prepend('MY_PATH', 'prepended:toDelete')
control.remove('MY_PATH', 'toDelete')
control.finishXMLinput('testOutputFile.xml')
control = Control.Environment()
self.assertFalse('MY_PATH' in control.vars())
control.loadXML('testOutputFile.xml')
self.assertTrue('MY_PATH' in control.vars())
var = control.var('MY_PATH')
self.assertTrue(var[0] == 'prepended')
self.assertTrue(var[1] == 'set')
self.assertTrue(var[2] == 'appended')
self.assertFalse('toDelete' in var)
os.remove('testOutputFile.xml')
def testWriteWithList(self):
"""XML file write and load test"""
control = Control.Environment(useAsWriter = True)
control.unset('MY_PATH')
control.set('MY_PATH', ['set','toDelete'])
control.append('MY_PATH', ['appended','toDelete'])
control.prepend('MY_PATH', ['prepended','toDelete'])
control.remove('MY_PATH', ['toDelete'])
control.finishXMLinput('testOutputFile.xml')
control = Control.Environment()
self.assertFalse('MY_PATH' in control.vars())
control.loadXML('testOutputFile.xml')
self.assertTrue('MY_PATH' in control.vars())
var = control.var('MY_PATH')
self.assertTrue(var[0] == 'prepended')
self.assertTrue(var[1] == 'set')
self.assertTrue(var[2] == 'appended')
self.assertFalse('toDelete' in var)
os.remove('testOutputFile.xml')
def testSaveToXML(self):
"""XML file write and load test"""
control = Control.Environment()
control.unset('MY_PATH')
control.set('MY_PATH', 'set:toDelete')
control.append('MY_PATH', 'appended:toDelete')
control.prepend('MY_PATH', 'prepended:toDelete')
control.remove('MY_PATH', 'toDelete')
control.writeToXMLFile('testOutputFile.xml')
control = Control.Environment()
self.assertFalse('MY_PATH' in control.vars())
control.loadXML('testOutputFile.xml')
self.assertTrue('MY_PATH' in control.vars())
var = control.var('MY_PATH')
self.assertTrue(var[0] == 'prepended')
self.assertTrue(var[1] == 'set')
self.assertTrue(var[2] == 'appended')
self.assertFalse('toDelete' in var)
os.remove('testOutputFile.xml')
def testSaveToFile(self):
'''Test addition of variable to system'''
control = Control.Environment()
control.append('sysVar', 'newValue:lala')
control.writeToFile('setupFile.txt')
with open('setupFile.txt', "r") as f:
f.readline()
stri = f.readline()
f.close()
self.assertEqual(stri, 'export sysVar=newValue:lala\n')
os.remove('setupFile.txt')
def testSearch(self):
'''Testing searching in variables'''
control = Control.Environment()
control.append('MY_PATH', 'newValue:mess:something new:aaaabbcc')
def count(val, regExp = False):
return len(control.search('MY_PATH', val, regExp))
self.assertEqual(count('new'), 0)
self.assertEqual(count('newValue'), 1)
self.assertEqual(count('me', False), 0)
self.assertEqual(count('me', True), 2)
self.assertEqual(count('cc', False), 0)
self.assertEqual(count('cc', True), 1)
self.assertEqual(count('a{2}b{2}c{2}', True), 1)
self.assertEqual(count('a{2}b{2}', True), 1)
self.assertEqual(count('a{1}b{2}c{2}', True), 1)
self.assertEqual(count('a{1}b{1}c{2}', True), 0)
self.assertEqual(count('a{1,2}b{1,2}c{2}', True), 1)
self.assertEqual(count('a{2,3}', True), 1)
self.assertEqual(count('a{2,3}?', True), 1)
def testVariables(self):
'''Tests variables creation and redeclaration.'''
control = Control.Environment()
control.append('MY_PATH', 'newValue')
self.assertFalse(control.var('MY_PATH').local)
self.assertTrue(isinstance(control.var('MY_PATH'),Variable.List))
control.declare('loc', 'list', True)
self.assertTrue(control.var('loc').local)
self.assertTrue(isinstance(control.var('loc'),Variable.List))
control.declare('myVar2', 'scalar', False)
self.assertFalse(control.var('myVar2').local)
self.assertTrue(isinstance(control.var('myVar2'),Variable.Scalar))
control.declare('loc2', 'scalar', True)
self.assertTrue(control.var('loc2').local)
self.assertTrue(isinstance(control.var('loc2'),Variable.Scalar))
control.declare('MY_PATH', 'list', False)
self.failUnlessRaises(Variable.EnvError, control.declare, 'MY_PATH', 'list', True)
self.failUnlessRaises(Variable.EnvError, control.declare, 'MY_PATH', 'scalar', True)
self.failUnlessRaises(Variable.EnvError, control.declare, 'MY_PATH', 'scalar', True)
control.declare('loc', 'list', True)
self.failUnlessRaises(Variable.EnvError, control.declare,'loc', 'list', False)
self.failUnlessRaises(Variable.EnvError, control.declare,'loc', 'scalar', True)
self.failUnlessRaises(Variable.EnvError, control.declare,'loc', 'scalar', True)
control.declare('myVar2', 'scalar', False)
self.failUnlessRaises(Variable.EnvError, control.declare,'myVar2', 'list', False)
self.failUnlessRaises(Variable.EnvError, control.declare,'myVar2', 'list', True)
self.failUnlessRaises(Variable.EnvError, control.declare,'myVar2', 'scalar', True)
control.declare('loc2', 'scalar', True)
self.failUnlessRaises(Variable.EnvError, control.declare,'loc2', 'list', False)
self.failUnlessRaises(Variable.EnvError, control.declare,'loc2', 'list', True)
self.failUnlessRaises(Variable.EnvError, control.declare,'loc2', 'scalar', False)
def testDelete(self):
control = Control.Environment()
control.append('MY_PATH','myVal:anotherVal:lastVal')
control.remove('MY_PATH','anotherVal')
self.assertFalse('anotherVal' in control['MY_PATH'])
self.assertTrue('myVal' in control['MY_PATH'])
self.assertTrue('lastVal' in control['MY_PATH'])
control.set('MY_PATH','myVal:anotherVal:lastVal:else')
control.remove('MY_PATH', '^anotherVal$', False)
self.assertTrue('anotherVal' in control['MY_PATH'])
control.remove('MY_PATH', '^anotherVal$', True)
self.assertFalse('anotherVal' in control['MY_PATH'])
self.assertTrue('myVal' in control['MY_PATH'])
self.assertTrue('lastVal' in control['MY_PATH'])
self.assertTrue('lastVal' in control['MY_PATH'])
control.remove('MY_PATH', 'Val', True)
self.assertTrue('else' in control['MY_PATH'])
self.assertTrue(len(control['MY_PATH']) == 1)
control.declare('myLoc', 'scalar', False)
control.append('myLoc','myVal:anotherVal:lastVal')
control.remove('myLoc', 'Val:', True)
self.assertTrue(str(control['myLoc']) == 'myanotherlastVal')
def testSystemEnvironment(self):
control = Control.Environment()
os.environ['MY_PATH'] = '$myVal'
os.environ['myScal'] = '$myVal'
control.set('ABC','anyValue')
control.declare('MY_PATH', 'list', False)
control.append('MY_PATH','$ABC')
self.assertTrue(control['MY_PATH'].value(True) == '$myVal:anyValue')
control.declare('myScal', 'scalar', False)
control.append('myScal', '$ABC')
self.assertTrue(control['myScal'].value(True) == '$myValanyValue')
def testDependencies(self):
control = Control.Environment()
control.declare('myVar', 'list', False)
control.declare('loc', 'list', True)
control.append('loc','locVal')
control.append('loc','locVal2')
control.declare('scal', 'scalar', False)
control.append('scal','scalVal')
control.append('scal','scalVal2')
control.declare('scal2', 'scalar', True)
control.append('scal2','locScal')
control.append('scal2','locScal2')
control.set('myVar', 'newValue:$loc:endValue')
self.assertEqual(str(control['myVar']),'newValue:locVal:locVal2:endValue')
control.set('myVar', 'newValue:$scal:endValue')
self.assertEqual(str(control['myVar']),'newValue:scalValscalVal2:endValue')
control.set('myVar', 'new${scal}Value:endValue')
self.assertEqual(str(control['myVar']),'newscalValscalVal2Value:endValue')
control.set('myVar', 'bla:$myVar:Value')
self.assertEqual(str(control['myVar']),'bla:newscalValscalVal2Value:endValue:Value')
control.set('scal', 'new${scal2}Value')
self.assertEqual(str(control['scal']),'newlocScallocScal2Value')
control.set('scal', 'new${loc}Value')
self.assertEqual(str(control['scal']),'newlocVal:locVal2Value')
control.set('scal2', 'new${scal2}Value')
self.assertEqual(str(control['scal2']),'newlocScallocScal2Value')
def testInclude(self):
tmp = TempDir({'first.xml':
'''<?xml version="1.0" ?>
<env:config xmlns:env="EnvSchema" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="EnvSchema ./EnvSchema.xsd ">
<env:set variable="main">first</env:set>
<env:append variable="test_path">data1</env:append>
<env:include>first_inc.xml</env:include>
</env:config>''',
'second.xml':
'''<?xml version="1.0" ?>
<env:config xmlns:env="EnvSchema" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="EnvSchema ./EnvSchema.xsd ">
<env:set variable="main">second</env:set>
<env:include>second_inc.xml</env:include>
<env:append variable="test_path">data1</env:append>
</env:config>''',
'third.xml':
'''<?xml version="1.0" ?>
<env:config xmlns:env="EnvSchema" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="EnvSchema ./EnvSchema.xsd ">
<env:set variable="main">third</env:set>
<env:append variable="test_path">data1</env:append>
<env:include>subdir/first_inc.xml</env:include>
</env:config>''',
'fourth.xml':
'''<?xml version="1.0" ?>
<env:config xmlns:env="EnvSchema" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="EnvSchema ./EnvSchema.xsd ">
<env:set variable="main">fourth</env:set>
<env:include hints="subdir2">fourth_inc.xml</env:include>
</env:config>''',
'recursion.xml':
'''<?xml version="1.0" ?>
<env:config xmlns:env="EnvSchema" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="EnvSchema ./EnvSchema.xsd ">
<env:set variable="main">recursion</env:set>
<env:include>recursion.xml</env:include>
</env:config>''',
'first_inc.xml':
'''<?xml version="1.0" ?>
<env:config xmlns:env="EnvSchema" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="EnvSchema ./EnvSchema.xsd ">
<env:append variable="test_path">data2</env:append>
<env:append variable="derived">another_${main}</env:append>
</env:config>''',
'subdir': {'second_inc.xml':
'''<?xml version="1.0" ?>
<env:config xmlns:env="EnvSchema" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="EnvSchema ./EnvSchema.xsd ">
<env:append variable="test_path">data0</env:append>
<env:set variable="map">this_is_second_inc</env:set>
</env:config>''',
'first_inc.xml':
'''<?xml version="1.0" ?>
<env:config xmlns:env="EnvSchema" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="EnvSchema ./EnvSchema.xsd ">
<env:append variable="derived">second_${main}</env:append>
</env:config>''',
'fourth_inc.xml':
'''<?xml version="1.0" ?>
<env:config xmlns:env="EnvSchema" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="EnvSchema ./EnvSchema.xsd ">
<env:append variable="included">from subdir</env:append>
</env:config>''',},
'subdir2': {'fourth_inc.xml':
'''<?xml version="1.0" ?>
<env:config xmlns:env="EnvSchema" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="EnvSchema ./EnvSchema.xsd ">
<env:append variable="included">from subdir2</env:append>
</env:config>''',}})
# set the basic search path to the minimal default
if 'ENVXMLPATH' in os.environ:
del os.environ['ENVXMLPATH']
import EnvConfig
saved_path = list(EnvConfig.path)
EnvConfig.path[:] = ['.']
control = Control.Environment(searchPath=[])
#self.assertRaises(OSError, control.loadXML, tmp('first.xml'))
control.loadXML(tmp('first.xml'))
self.assertEqual(str(control['main']), 'first')
self.assertEqual(str(control['test_path']), 'data1:data2')
self.assertEqual(str(control['derived']), 'another_first')
control = Control.Environment(searchPath=[tmp()])
control.loadXML(tmp('first.xml'))
self.assertEqual(str(control['main']), 'first')
self.assertEqual(str(control['test_path']), 'data1:data2')
self.assertEqual(str(control['derived']), 'another_first')
control = Control.Environment(searchPath=[tmp()])
control.loadXML('first.xml')
self.assertEqual(str(control['main']), 'first')
self.assertEqual(str(control['test_path']), 'data1:data2')
self.assertEqual(str(control['derived']), 'another_first')
control = Control.Environment(searchPath=[tmp()])
self.assertRaises(OSError, control.loadXML, tmp('second.xml'))
control = Control.Environment(searchPath=[tmp(), tmp('subdir')])
control.loadXML(tmp('second.xml'))
self.assertEqual(str(control['main']), 'second')
self.assertEqual(str(control['test_path']), 'data0:data1')
self.assertEqual(str(control['map']), 'this_is_second_inc')
control = Control.Environment(searchPath=[tmp(), tmp('subdir')])
control.loadXML(tmp('first.xml'))
self.assertEqual(str(control['main']), 'first')
self.assertEqual(str(control['test_path']), 'data1:data2')
self.assertEqual(str(control['derived']), 'another_first')
control = Control.Environment(searchPath=[tmp('subdir'), tmp()])
control.loadXML(tmp('first.xml'))
self.assertEqual(str(control['main']), 'first')
self.assertEqual(str(control['test_path']), 'data1:data2')
self.assertEqual(str(control['derived']), 'another_first')
control = Control.Environment(searchPath=[tmp('subdir'), tmp()])
control.loadXML('first.xml')
self.assertEqual(str(control['main']), 'first')
self.assertEqual(str(control['test_path']), 'data1:data2')
self.assertEqual(str(control['derived']), 'another_first')
#os.environ['ENVXMLPATH'] = os.pathsep.join([tmp(), tmp('subdir')])
EnvConfig.path[:] = ['.', tmp(), tmp('subdir')]
control = Control.Environment(searchPath=[])
control.loadXML(tmp('second.xml'))
self.assertEqual(str(control['main']), 'second')
self.assertEqual(str(control['test_path']), 'data0:data1')
self.assertEqual(str(control['map']), 'this_is_second_inc')
#del os.environ['ENVXMLPATH']
EnvConfig.path[:] = ['.']
control = Control.Environment(searchPath=[])
control.loadXML(tmp('third.xml'))
self.assertEqual(str(control['main']), 'third')
self.assertEqual(str(control['test_path']), 'data1')
self.assertEqual(str(control['derived']), 'second_third')
control = Control.Environment(searchPath=[tmp('subdir')])
control.loadXML(tmp('fourth.xml'))
self.assertEqual(str(control['main']), 'fourth')
self.assertEqual(str(control['included']), 'from subdir')
control = Control.Environment(searchPath=[])
control.loadXML(tmp('fourth.xml'))
self.assertEqual(str(control['main']), 'fourth')
self.assertEqual(str(control['included']), 'from subdir2')
control = Control.Environment(searchPath=[])
#self.assertRaises(OSError, control.loadXML, tmp('first.xml'))
control.loadXML(tmp('recursion.xml'))
# restore search path
EnvConfig.path = saved_path
def testFileDir(self):
tmp = TempDir({'env.xml':
'''<?xml version="1.0" ?>
<env:config xmlns:env="EnvSchema" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="EnvSchema ./EnvSchema.xsd ">
<env:set variable="mydirs">${.}</env:set>
<env:set variable="myparent">${.}/..</env:set>
</env:config>'''})
control = Control.Environment()
control.loadXML(tmp('env.xml'))
self.assertEqual(str(control['mydirs']), tmp())
self.assertEqual(str(control['myparent']), os.path.dirname(tmp()))
olddir = os.getcwd()
os.chdir(tmp())
try:
control = Control.Environment()
control.loadXML('env.xml')
self.assertEqual(str(control['mydirs']), tmp())
self.assertEqual(str(control['myparent']), os.path.dirname(tmp()))
finally:
os.chdir(olddir)
def testDefaults(self):
tmp = TempDir({'env.xml':
'''<?xml version="1.0" ?>
<env:config xmlns:env="EnvSchema" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="EnvSchema ./EnvSchema.xsd ">
<env:default variable="var1">value1</env:default>
<env:declare variable="var2" local="true" />
<env:default variable="var2">test2</env:default>
</env:config>'''})
if 'var1' in os.environ:
del os.environ['var1']
control = Control.Environment()
control.loadXML(tmp('env.xml'))
self.assertEqual(str(control['var1']), "value1")
self.assertEqual(str(control['var2']), "test2")
os.environ['var1'] = "some_value"
control = Control.Environment()
control.loadXML(tmp('env.xml'))
self.assertEqual(str(control['var1']), "some_value")
self.assertEqual(str(control['var2']), "test2")
def testVariableManipulations(self):
l = Variable.List('PATH')
l.set("/usr/bin:/some//strange/../nice/./location")
assert l.value(asString=True) == "/usr/bin:/some/nice/location"
l.append("/another/path")
assert l.value(asString=True) == "/usr/bin:/some/nice/location:/another/path"
# duplicates removal
l.append("/usr/bin")
assert l.value(asString=True) == "/usr/bin:/some/nice/location:/another/path"
l.prepend("/another/path")
assert l.value(asString=True) == "/another/path:/usr/bin:/some/nice/location"
s = Variable.Scalar('VAR')
s.set("/usr/bin")
assert s.value(asString=True) == "/usr/bin"
s.set("/some//strange/../nice/./location")
assert s.value(asString=True) == "/some/nice/location"
# This is undefined
# l.set("http://cern.ch")
s.set("http://cern.ch")
assert s.value(asString=True) == "http://cern.ch"
if __name__ == "__main__":
#import sys;sys.argv = ['', 'Test.testName']
unittest.main()
|
UTF-8
|
Python
| false | false | 2,013 |
10,711,648,455,121 |
239b5c25a1904785db4af300aec2b8d8500ee1c0
|
2ad9b0245ae49ee62bf9058cff3e4bd5cd8f5a8c
|
/predicate.py
|
e62fb8f57b1ec03422d72275c4c0b7eafa70baaa
|
[] |
no_license
|
hbradlow/pygeom
|
https://github.com/hbradlow/pygeom
|
7918904b837da45baac2b5289b976eca9424c7b6
|
8bc5a7e871b4acb23aa6c1eaf8bfefe85e6c7d3d
|
refs/heads/master
| 2021-01-22T09:47:56.097000 | 2013-02-02T11:53:02 | 2013-02-02T11:53:02 | null | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null |
import numpy as np
def orient_2d(p,q,r):
"""
> 0 if CCW
< 0 if CW
= 0 if colinear
"""
return (q[0]-p[0])*(r[1]-p[1]) - (r[0]-p[0])*(q[1]-p[1])
def intersects(seg1,seg2):
return \
orient_2d(seg2.start,seg2.end,seg1.start)* \
orient_2d(seg2.start,seg2.end,seg1.end)<=0 \
and \
orient_2d(seg1.start,seg1.end,seg2.start)* \
orient_2d(seg1.start,seg1.end,seg2.end)<=0
|
UTF-8
|
Python
| false | false | 2,013 |
13,099,650,274,113 |
141a55d6cd86a2afad74562325557d8fdffb9c3f
|
430bc3cb9ab5c6d9772450a1d922059883310188
|
/src/caffe/test/test_data/generate_sample_data.py
|
1f16fad91606bd800a23d4334c348b7ad7e5ad17
|
[
"BSD-2-Clause",
"LicenseRef-scancode-proprietary-license"
] |
non_permissive
|
RyanLiuNtust/DSN
|
https://github.com/RyanLiuNtust/DSN
|
8b1ae30424bbf0e20fc62ba803863ee56a91bf11
|
93937e5e581d44bd16e75665b464dc74cdad7392
|
refs/heads/master
| 2020-12-11T09:22:25.101000 | 2014-10-23T05:27:26 | 2014-10-23T05:27:26 | 33,246,698 | 0 | 1 | null | true | 2015-04-01T12:39:54 | 2015-04-01T12:39:54 | 2015-03-23T15:27:37 | 2014-10-23T05:27:32 | 4,108 | 0 | 0 | 0 | null | null | null |
"""
Generate data used in the HDF5DataLayer test.
"""
import numpy as np
import h5py
num_cols = 8
num_rows = 10
data = np.arange(num_cols * num_rows).reshape(num_rows, num_cols)
label = np.arange(num_rows)[:, np.newaxis]
print data
print label
with h5py.File('./sample_data.h5', 'w') as f:
f['data'] = data.astype('float32')
f['label'] = label.astype('float32')
|
UTF-8
|
Python
| false | false | 2,014 |
15,350,213,138,552 |
4de86f7d9d64cacc4904ff9970d9644b8217450e
|
fad0306f76819c5b877590dbbd4a8d968335a395
|
/main.py
|
405ac0959594f33feca5eb7cff31e29d3789742c
|
[] |
no_license
|
anandtakawale/online2dconduction
|
https://github.com/anandtakawale/online2dconduction
|
f6f1e564ba409ddb8bb39b7878db668126e81de0
|
603249bf21fbb375407ea5e7cd6b6a443b302f4c
|
refs/heads/master
| 2020-05-02T12:15:36.348000 | 2014-04-15T18:02:31 | 2014-04-15T18:02:31 | null | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null |
import webapp2
from parameter import parameter
from conduct2d import conduct2d
from conduct2d import cacheFlush
app = webapp2.WSGIApplication([('/',parameter),
('/result', conduct2d),
('/flush', cacheFlush)],
debug = True)
|
UTF-8
|
Python
| false | false | 2,014 |
18,202,071,404,169 |
121eb333d7cb530cd745fceac3ca145d68f5f5ce
|
b332d4d9aaf385e749046f28d52f8e445eeac8d9
|
/libwbook/inputing.py
|
be52c402b7258ea4de03dcc124385ac42f997ac8
|
[] |
no_license
|
fidlej/wbook-py
|
https://github.com/fidlej/wbook-py
|
cbd36633f9beee17ef21af1ec4a36a9b2787e3b7
|
d1105b8b9882768445fc7f4195af90623795d505
|
refs/heads/master
| 2016-09-06T06:27:58.099000 | 2010-11-21T11:41:49 | 2010-11-21T11:41:49 | 32,650,798 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null |
import sys
import readline
import logging
from libwbook.encoding import incode, out
from libwbook import searching
class Reader(object):
def __init__(self, search, arg_bytes=""):
self.line = incode(arg_bytes)
_set_completer(search)
def read_line(self):
if self.line:
line = self.line
self.line = ""
readline.add_history(line)
return line
return incode(raw_input("wbook> "))
def _set_completer(search):
readline.set_completer_delims("")
readline.set_completer(LineCompleter(search).complete)
readline.parse_and_bind("tab: complete")
class LineCompleter(object):
MAX_RESULTS = 100
def __init__(self, search):
self.search = search
self.results = []
def complete(self, inbytes, state):
try:
return self._complete(inbytes, state)
except Exception:
logging.exception("complete problem: %s, %s", inbytes, state)
return None
def _complete(self, inbytes, state):
text = incode(inbytes)
if state == 0:
self.results = self.search.find_forth(text, self.MAX_RESULTS)
if state >= len(self.results):
return self._stop(state)
orig, translated = self.results[state]
result = _rstrip_extra(orig, len(text))
if searching.startswith(result, text):
return out(result)
logging.debug("complete stop: %s, %s, %r", inbytes, state, result)
return self._stop(state)
def _stop(self, state):
self.results = []
return None
def _rstrip_extra(result, input_len):
"""It strips the trailing spaces from the result,
if they are after the input length.
"""
return result[:input_len] + result[input_len:].rstrip()
|
UTF-8
|
Python
| false | false | 2,010 |
4,690,104,329,408 |
03346fe2897d7109e132417e18e813bf28b3d23d
|
0ee3a0b594ca30f2710f421529aa0eb61e03a4e6
|
/mibs/pycopia/mibs/CISCO_ATM_SWITCH_ADDR_MIB.py
|
39376410574548ee3d8c4bff3660ef39d6846640
|
[
"LGPL-2.0-or-later",
"MIT",
"BSD-3-Clause",
"LGPL-2.1-only"
] |
non_permissive
|
xiangke/pycopia
|
https://github.com/xiangke/pycopia
|
d9f89678d837bd0b3f6cc105ecd670a4c2a4338a
|
0f655f0c80ff601a0ac28531eca9b4d7c604eceb
|
refs/heads/master
| 2020-05-18T12:04:09.833000 | 2008-11-11T07:45:45 | 2008-11-11T07:45:45 | 75,153 | 5 | 1 | null | null | null | null | null | null | null | null | null | null | null | null | null |
# python
# This file is generated by a program (mib2py). Any edits will be lost.
from pycopia.aid import Enum
import pycopia.SMI.Basetypes
Range = pycopia.SMI.Basetypes.Range
Ranges = pycopia.SMI.Basetypes.Ranges
from pycopia.SMI.Objects import ColumnObject, MacroObject, NotificationObject, RowObject, ScalarObject, NodeObject, ModuleObject, GroupObject
# imports
from SNMPv2_SMI import MODULE_IDENTITY, OBJECT_TYPE, Integer32
from SNMPv2_CONF import MODULE_COMPLIANCE, OBJECT_GROUP
from CISCO_SMI import ciscoMgmt
from SNMPv2_TC import TEXTUAL_CONVENTION, RowStatus
class CISCO_ATM_SWITCH_ADDR_MIB(ModuleObject):
path = '/usr/share/snmp/mibs/site/CISCO-ATM-SWITCH-ADDR-MIB'
conformance = 5
name = 'CISCO-ATM-SWITCH-ADDR-MIB'
language = 2
description = 'ATM Switch address MIB'
# nodes
class ciscoAtmSwAddrMIB(NodeObject):
status = 1
OID = pycopia.SMI.Basetypes.ObjectIdentifier([1, 3, 6, 1, 4, 1, 9, 9, 51])
name = 'ciscoAtmSwAddrMIB'
class ciscoAtmSwAddrMIBObjects(NodeObject):
OID = pycopia.SMI.Basetypes.ObjectIdentifier([1, 3, 6, 1, 4, 1, 9, 9, 51, 1])
name = 'ciscoAtmSwAddrMIBObjects'
class ciscoAtmSwAddrMIBConformance(NodeObject):
OID = pycopia.SMI.Basetypes.ObjectIdentifier([1, 3, 6, 1, 4, 1, 9, 9, 51, 3])
name = 'ciscoAtmSwAddrMIBConformance'
class ciscoAtmSwAddrMIBCompliances(NodeObject):
OID = pycopia.SMI.Basetypes.ObjectIdentifier([1, 3, 6, 1, 4, 1, 9, 9, 51, 3, 1])
name = 'ciscoAtmSwAddrMIBCompliances'
class ciscoAtmSwAddrMIBGroups(NodeObject):
OID = pycopia.SMI.Basetypes.ObjectIdentifier([1, 3, 6, 1, 4, 1, 9, 9, 51, 3, 2])
name = 'ciscoAtmSwAddrMIBGroups'
# macros
# types
class AtmAddr(pycopia.SMI.Basetypes.OctetString):
status = 1
ranges = Ranges(Range(13, 13), Range(20, 20))
# scalars
# columns
class ciscoAtmSwAddrIndex(ColumnObject):
access = 2
status = 1
OID = pycopia.SMI.Basetypes.ObjectIdentifier([1, 3, 6, 1, 4, 1, 9, 9, 51, 1, 1, 1, 1])
syntaxobject = pycopia.SMI.Basetypes.Integer32
class ciscoAtmSwAddrAddress(ColumnObject):
access = 5
status = 1
OID = pycopia.SMI.Basetypes.ObjectIdentifier([1, 3, 6, 1, 4, 1, 9, 9, 51, 1, 1, 1, 2])
syntaxobject = AtmAddr
class ciscoAtmSwAddrRowStatus(ColumnObject):
access = 5
status = 1
OID = pycopia.SMI.Basetypes.ObjectIdentifier([1, 3, 6, 1, 4, 1, 9, 9, 51, 1, 1, 1, 3])
syntaxobject = pycopia.SMI.Basetypes.RowStatus
# rows
class ciscoAtmSwAddrEntry(RowObject):
status = 1
index = pycopia.SMI.Objects.IndexObjects([ciscoAtmSwAddrIndex], False)
create = 1
OID = pycopia.SMI.Basetypes.ObjectIdentifier([1, 3, 6, 1, 4, 1, 9, 9, 51, 1, 1, 1])
access = 2
rowstatus = ciscoAtmSwAddrRowStatus
columns = {'ciscoAtmSwAddrIndex': ciscoAtmSwAddrIndex, 'ciscoAtmSwAddrAddress': ciscoAtmSwAddrAddress, 'ciscoAtmSwAddrRowStatus': ciscoAtmSwAddrRowStatus}
# notifications (traps)
# groups
class ciscoAtmSwAddrMIBGroup(GroupObject):
access = 2
status = 1
OID = pycopia.SMI.Basetypes.ObjectIdentifier([1, 3, 6, 1, 4, 1, 9, 9, 51, 3, 2, 1])
group = [ciscoAtmSwAddrAddress, ciscoAtmSwAddrRowStatus]
# capabilities
# special additions
# Add to master OIDMAP.
from pycopia import SMI
SMI.update_oidmap(__name__)
|
UTF-8
|
Python
| false | false | 2,008 |
5,574,867,577,874 |
65811a379ff97b2dfdce01f7168296c7f5a7c8e6
|
781b72991d65599a35b2df06d1f8d072979dfe7f
|
/tests/test_test_action.py
|
04157ae215ee02f6bcb7ecb0629e7ddb5cc269d2
|
[] |
no_license
|
sh0ked/lode_runner
|
https://github.com/sh0ked/lode_runner
|
eecb9352c19710feb60c4b5e130b2ccd95c90517
|
a88816dd1225a52ddd1b0b3c899fb3e9f678c201
|
refs/heads/master
| 2020-12-25T23:57:19.781000 | 2014-10-14T05:34:33 | 2014-10-14T05:34:33 | null | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null |
# -*- coding: utf-8 -*-
import unittest
import cStringIO
from lode_runner import TestAction
def temp(test_action):
with test_action:
pass
class TestActionTest(unittest.TestCase):
"""
Common use is:
from lode_runner import TestAction
class Test(unittest.TestCase):
def test(self):
with TestAction(u"doing stuff"):
do_stuff()
with TestAction(u"doing another stuff"):
do_another_stuff()
with TestAction(u"making assertions"):
self.assertTrue(True)
self.assertFalse(False)
"""
def setUp(self):
self._resultForDoCleanups.config.verbosity = 2
def test_ok_test_action(self):
msg = u"test_action_message"
output = cStringIO.StringIO()
test_action = TestAction(msg, output)
with test_action:
pass
parts = output.getvalue().split()
time = test_action.current_time
self.assertEquals("[%s]" % time, parts.pop(0))
self.assertEquals(msg, parts.pop(0))
self.assertEquals("...ok", parts.pop(0))
def test_error_test_action(self):
msg = u"test_action_message"
output = cStringIO.StringIO()
test_action = TestAction(msg, output)
try:
with test_action:
raise Exception("some exception")
except Exception:
pass
parts = output.getvalue().split()
time = test_action.current_time
self.assertEquals("[%s]" % time, parts.pop(0))
self.assertEquals(msg, parts.pop(0))
self.assertEquals("...error", parts.pop(0))
def test_fail_test_action(self):
msg = u"test_action_message"
output = cStringIO.StringIO()
test_action = TestAction(msg, output)
try:
with test_action:
self.assertTrue(False)
except AssertionError:
pass
parts = output.getvalue().split()
time = test_action.current_time
self.assertEquals("[%s]" % time, parts.pop(0))
self.assertEquals(msg, parts.pop(0))
self.assertEquals("...fail", parts.pop(0))
def test_test_action_in_function(self):
msg = u"test_action_message"
output = cStringIO.StringIO()
test_action = TestAction(msg, output)
temp(test_action)
parts = output.getvalue().split()
time = test_action.current_time
self.assertEquals("[%s]" % time, parts.pop(0))
self.assertEquals(msg, parts.pop(0))
self.assertEquals("...ok", parts.pop(0))
|
UTF-8
|
Python
| false | false | 2,014 |
14,181,982,055,779 |
d06da63f91fb1097940534940dc1490fd9c437ee
|
37dd16e4e48511e5dab789c57d97ab47ccffd561
|
/src/libs/python_utils/errors/exceptions.py
|
a16f9fd66ed4d8c61b771247615a6f79fdda978c
|
[] |
no_license
|
willow/scone-api
|
https://github.com/willow/scone-api
|
c9473a043996639024ae028bb3d7bf420eb3d75b
|
c786915bc0535cb0ed78726afa4ee3c0772a8c0e
|
refs/heads/production
| 2016-09-05T18:43:22.953000 | 2014-08-18T23:16:47 | 2014-08-18T23:18:23 | 18,448,114 | 1 | 0 | null | false | 2014-08-08T16:40:35 | 2014-04-04T18:21:18 | 2014-08-03T00:43:52 | 2014-08-08T16:40:33 | 6,164 | 1 | 0 | 0 |
Python
| null | null |
import os
import sys
from django.utils import encoding
def re_throw_ex(ex_type, message, inner_ex):
return (
ex_type,
log_ex_with_message(message, inner_ex),
sys.exc_info()[2] #this is the traceback
)
def log_ex_with_message(message, inner_ex):
return "{0}{sep}Inner Exception: {1}{sep}\t{2}".format(
message, type(inner_ex), encoding.smart_unicode(inner_ex, errors='ignore'), sep=os.linesep
)
|
UTF-8
|
Python
| false | false | 2,014 |
6,992,206,797,207 |
22567767751138d7853a922114a2b82e2e915fc6
|
35c3462107ca0a0b9a062565adb02eda0dd12bfe
|
/com.yoursway.sadr.python.core.tests/tests/gen_oper_tests.py
|
16ac9d5d62cde1cc9b4949c7a09d3b93c9c125b7
|
[] |
no_license
|
cha63506/yoursway-sadr
|
https://github.com/cha63506/yoursway-sadr
|
f64603cf175e2d6ec9339220e540586578eab834
|
d4d5728c9935ef995e3f08031f2cb4f5dd65dabb
|
refs/heads/master
| 2017-05-30T05:42:01.553000 | 2009-05-09T04:49:56 | 2009-05-09T04:50:30 | null | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null |
from test_gen import TestBuilder
value_klass = """
class Q(object):
pass
"""
binklass = """
class Foo(object):
def %s (self, rhs):
return Q()
"""
unklass = """
class Foo(object):
def %s (self):
return Q()
"""
assklass = """
class Foo(object):
def %s (self, rhs):
print rhs
"""
BINARY_OPERATORS = {
"__add__": "+",
"__sub__": "-",
"__mul__": "*",
"__floordiv__": "//",
"__mod__": "%",
#TODO __divmod__": "divmod",
"__pow__": "**", #( self, other[, modulo])
"__lshift__": "<<",
"__rshift__": ">>",
"__and__": "&",
"__xor__": "^",
"__or__": "|",
"__div__": "/",
# "__truediv__": "/",
"__radd__": "+",
"__rsub__": "-",
"__rmul__": "*",
"__rdiv__": "/",
# "__rtruediv__": "/",
"__rfloordiv__": "//",
"__rmod__": "%",
#TODO __rdivmod__": "",
"__rpow__": "**",
"__rlshift__": "<<",
"__rrshift__": ">>",
"__rand__": "&",
"__rxor__": "^",
"__ror__": "|",
"__lt__": "<",
"__le__": "<=",
"__eq__": "==",
"__ne__": "!=",
"__gt__": ">",
"__ge__": ">="
}
UNARY_OPERATORS = {
"__neg__": "-",
"__pos__": "+",
"__invert__": "~"
}
ASS_OPERATORS = {
"__iadd__": "+=",
"__isub__": "-=",
"__imul__": "*=",
"__idiv__": "/=",
"__itruediv__": "/=",
"__ifloordiv__": "//=",
"__imod__": "%=",
"__ipow__": "**=", #( self, other[, modulo])
"__ilshift__": "<<=",
"__irshift__": ">>=",
"__iand__": "&=",
"__ixor__": "^=",
"__ior__": "|="
}
TEST_BINOP = "x = Foo() %s Foo() ## expr x => Q"
TEST_ASS = "x = Foo()\nx %s Foo() ## expr x => Foo"
TEST_UNOP = "x = %sFoo() ## expr x => Q"
def gen_tests(suite_name, operators, test_str, klass):
builder = TestBuilder(suite_name)
for oper, symname in operators.items():
script_content = value_klass + klass % oper + test_str % symname
builder.addTest(oper, script_content)
if __name__ == "__main__":
gen_tests("BinaryOperators", BINARY_OPERATORS, TEST_BINOP, binklass)
gen_tests("UnaryOperators", UNARY_OPERATORS, TEST_UNOP, unklass)
gen_tests("AssignmentOperators", ASS_OPERATORS, TEST_ASS, assklass)
|
UTF-8
|
Python
| false | false | 2,009 |
11,433,202,957,584 |
3e33fb4fe8ec22211c3362e02b7254932d7c28cb
|
9eaaa7b042f9ee4dd73da38b1f0f20dadcbd034b
|
/staffmethods.py
|
d9ef7d245b19447b878519992a2bf47052d628e2
|
[
"GPL-2.0-only",
"GPL-1.0-or-later"
] |
non_permissive
|
cyncyncyn/evette
|
https://github.com/cyncyncyn/evette
|
15f126baad662ac95e5a75aac987f14fba258a06
|
00a56790cdcacd955854ff37ff12b92ce12efd3d
|
refs/heads/master
| 2021-01-15T13:11:20.979000 | 2014-09-08T11:56:37 | 2014-09-08T11:56:37 | 23,789,177 | 1 | 4 | null | null | null | null | null | null | null | null | null | null | null | null | null |
#!?usr/bin/python
# -*- coding: UTF-8 -*-
#Copyright (C) 2007 Adam Spencer - Free Veterinary Management Suite
#This program is free software; you can redistribute it and/or
#modify it under the terms of the GNU General Public License
#as published by the Free Software Foundation; either version 2
#of the License, or (at your option) any later version.
#This program is distributed in the hope that it will be useful,
#but WITHOUT ANY WARRANTY; without even the implied warranty of
#MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
#GNU General Public License for more details.
#You should have received a copy of the GNU General Public License
#along with this program; if not, write to the Free Software
#Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
##Contact: [email protected]
import wx
import wx.html
import miscmethods
import db
import dbmethods
import customwidgets
ADD_USER = 1301
EDIT_USER = 1302
DELETE_USER = 1304
REFRESH_USERS = 1305
class GenericSettingsPanel(wx.Panel):
def GetLabel(self, field):
return self.localsettings.dictionary[field][self.localsettings.language]
def __init__(self, parent, title):
self.localsettings = parent.GetParent().localsettings
wx.Panel.__init__(self, parent)
topsizer = wx.BoxSizer(wx.VERTICAL)
edit = wx.CheckBox(self, -1, self.GetLabel("editlabel"))
edit.Bind(wx.EVT_CHECKBOX, self.EditChecked)
topsizer.Add(edit, 0, wx.ALIGN_LEFT)
delete = wx.CheckBox(self, -1, self.GetLabel("deletelabel"))
delete.Bind(wx.EVT_CHECKBOX, self.DeleteChecked)
topsizer.Add(delete, 0, wx.ALIGN_LEFT)
self.SetSizer(topsizer)
self.edit = edit
self.delete = delete
def DeleteChecked(self, ID):
if self.delete.GetValue() == True:
self.edit.SetValue(True)
def EditChecked(self, ID):
if self.edit.GetValue() == False:
self.delete.SetValue(False)
class AppointmentSettingsPanel(wx.Panel):
def GetLabel(self, field):
return self.localsettings.dictionary[field][self.localsettings.language]
def __init__(self, parent, title):
self.localsettings = parent.GetParent().localsettings
wx.Panel.__init__(self, parent)
topsizer = wx.BoxSizer(wx.VERTICAL)
edit = wx.CheckBox(self, -1, self.GetLabel("editlabel"))
edit.Bind(wx.EVT_CHECKBOX, self.EditChecked)
topsizer.Add(edit, 0, wx.ALIGN_LEFT)
delete = wx.CheckBox(self, -1, self.GetLabel("deletelabel"))
delete.Bind(wx.EVT_CHECKBOX, self.DeleteChecked)
topsizer.Add(delete, 0, wx.ALIGN_LEFT)
vetform = wx.CheckBox(self, -1, self.GetLabel("editvetformlabel"))
vetform.Bind(wx.EVT_CHECKBOX, self.EditVetFormChecked)
topsizer.Add(vetform, 0, wx.ALIGN_LEFT)
self.SetSizer(topsizer)
self.edit = edit
self.delete = delete
self.vetform = vetform
def DeleteChecked(self, ID):
if self.delete.GetValue() == True:
self.edit.SetValue(True)
def EditChecked(self, ID):
if self.edit.GetValue() == False:
self.delete.SetValue(False)
self.vetform.SetValue(False)
def EditVetFormChecked(self, ID):
if self.vetform.GetValue() == True:
self.edit.SetValue(True)
class ClientSettingsPanel(wx.Panel):
def GetLabel(self, field):
return self.localsettings.dictionary[field][self.localsettings.language]
def __init__(self, parent, title):
self.localsettings = parent.GetParent().localsettings
wx.Panel.__init__(self, parent)
topsizer = wx.BoxSizer(wx.VERTICAL)
edit = wx.CheckBox(self, -1, self.GetLabel("editlabel"))
edit.Bind(wx.EVT_CHECKBOX, self.EditChecked)
topsizer.Add(edit, 0, wx.ALIGN_LEFT)
delete = wx.CheckBox(self, -1, self.GetLabel("deletelabel"))
delete.Bind(wx.EVT_CHECKBOX, self.DeleteChecked)
topsizer.Add(delete, 0, wx.ALIGN_LEFT)
editfinances = wx.CheckBox(self, -1, self.GetLabel("editfinanceslabel"))
topsizer.Add(editfinances, 0, wx.ALIGN_LEFT)
self.SetSizer(topsizer)
self.edit = edit
self.delete = delete
self.editfinances = editfinances
def DeleteChecked(self, ID):
if self.delete.GetValue() == True:
self.edit.SetValue(True)
def EditChecked(self, ID):
if self.edit.GetValue() == False:
self.delete.SetValue(False)
class MiscSettingsPanel(wx.Panel):
def GetLabel(self, field):
return self.localsettings.dictionary[field][self.localsettings.language]
def __init__(self, parent, title):
self.localsettings = parent.GetParent().localsettings
wx.Panel.__init__(self, parent)
topsizer = wx.BoxSizer(wx.VERTICAL)
toolbar = wx.CheckBox(self, -1, self.GetLabel("showtoolbarlabel"))
topsizer.Add(toolbar, 0, wx.ALIGN_LEFT)
changelog = wx.CheckBox(self, -1, self.GetLabel("viewchangeloglabel"))
topsizer.Add(changelog, 0, wx.ALIGN_LEFT)
editsettings = wx.CheckBox(self, -1, self.GetLabel("editsettingslabel"))
topsizer.Add(editsettings, 0, wx.ALIGN_LEFT)
multiplepanels = wx.CheckBox(self, -1, self.GetLabel("multiplepanellabel"))
topsizer.Add(multiplepanels, 0, wx.ALIGN_LEFT)
asmsync = wx.CheckBox(self, -1, self.GetLabel("synctoasmlabel"))
topsizer.Add(asmsync, 0, wx.ALIGN_LEFT)
self.SetSizer(topsizer)
self.toolbar = toolbar
self.changelog = changelog
self.editsettings = editsettings
self.multiplepanels = multiplepanels
self.asmsync = asmsync
class DiarySettingsPanel(wx.Panel):
def GetLabel(self, field):
return self.localsettings.dictionary[field][self.localsettings.language]
def __init__(self, parent, title):
self.localsettings = parent.GetParent().localsettings
wx.Panel.__init__(self, parent)
topsizer = wx.BoxSizer(wx.VERTICAL)
adddiarynotes = wx.CheckBox(self, -1, self.GetLabel("adddiarynotes"))
topsizer.Add(adddiarynotes, 0, wx.ALIGN_LEFT)
editdiarynotes = wx.CheckBox(self, -1, self.GetLabel("editdiarynotes"))
topsizer.Add(editdiarynotes, 0, wx.ALIGN_LEFT)
deletediarynotes = wx.CheckBox(self, -1, self.GetLabel("deletediarynotes"))
topsizer.Add(deletediarynotes, 0, wx.ALIGN_LEFT)
self.SetSizer(topsizer)
self.adddiarynotes = adddiarynotes
self.editdiarynotes = editdiarynotes
self.deletediarynotes = deletediarynotes
class UserSettingsPanel(wx.Panel):
def GetLabel(self, field):
return self.localsettings.dictionary[field][self.localsettings.language]
def __init__(self, parent, title):
self.localsettings = parent.GetParent().localsettings
wx.Panel.__init__(self, parent)
topsizer = wx.BoxSizer(wx.VERTICAL)
edit = wx.CheckBox(self, -1, self.GetLabel("editlabel"))
edit.Bind(wx.EVT_CHECKBOX, self.EditChecked)
topsizer.Add(edit, 0, wx.ALIGN_LEFT)
delete = wx.CheckBox(self, -1, self.GetLabel("deletelabel"))
delete.Bind(wx.EVT_CHECKBOX, self.DeleteChecked)
topsizer.Add(delete, 0, wx.ALIGN_LEFT)
editrota = wx.CheckBox(self, -1, self.GetLabel("editrotalabel"))
topsizer.Add(editrota, 0, wx.ALIGN_LEFT)
self.SetSizer(topsizer)
self.edit = edit
self.delete = delete
self.editrota = editrota
def DeleteChecked(self, ID):
if self.delete.GetValue() == True:
self.edit.SetValue(True)
def EditChecked(self, ID):
if self.edit.GetValue() == False:
self.delete.SetValue(False)
class EditStaffPanel(wx.Panel):
def GetLabel(self, field):
return self.localsettings.dictionary[field][self.localsettings.language]
def __init__(self, notebook, localsettings):
self.localsettings = localsettings
self.pagetitle = miscmethods.GetPageTitle(notebook, self.GetLabel("editstaffpagetitle"))
wx.Panel.__init__(self, notebook)
topsizer = wx.BoxSizer(wx.VERTICAL)
userlist = wx.ListBox(self, -1)
userlist.Bind(wx.EVT_RIGHT_DOWN, self.Popup)
userlist.Bind(wx.EVT_LISTBOX_DCLICK, self.EditUser)
topsizer.Add(userlist, 1, wx.EXPAND)
self.SetSizer(topsizer)
self.localsettings = self.localsettings
self.userlist = userlist
self.RefreshUsers()
def Popup(self, ID):
popupmenu = wx.Menu()
add = wx.MenuItem(popupmenu, ADD_USER, self.GetLabel("addlabel"))
add.SetBitmap(wx.Bitmap("icons/new.png"))
popupmenu.AppendItem(add)
wx.EVT_MENU(popupmenu, ADD_USER, self.AddUser)
if self.userlist.GetSelection() > -1:
edit = wx.MenuItem(popupmenu, EDIT_USER, self.GetLabel("editlabel"))
edit.SetBitmap(wx.Bitmap("icons/edit.png"))
popupmenu.AppendItem(edit)
wx.EVT_MENU(popupmenu, EDIT_USER, self.EditUser)
delete = wx.MenuItem(popupmenu, DELETE_USER, self.GetLabel("deletelabel"))
delete.SetBitmap(wx.Bitmap("icons/delete.png"))
popupmenu.AppendItem(delete)
wx.EVT_MENU(popupmenu, DELETE_USER, self.DeleteUser)
popupmenu.AppendSeparator()
refresh = wx.MenuItem(popupmenu, REFRESH_USERS, self.GetLabel("refreshlabel"))
refresh.SetBitmap(wx.Bitmap("icons/refresh.png"))
popupmenu.AppendItem(refresh)
wx.EVT_MENU(popupmenu, REFRESH_USERS, self.RefreshUsers)
self.PopupMenu(popupmenu)
def AddUser(self, ID):
self.EditUserDialog()
def EditUser(self, ID):
listboxid = self.userlist.GetSelection()
userid = self.users[listboxid]
action = "SELECT * FROM user WHERE ID = " + str(userid)
results = db.SendSQL(action, self.localsettings.dbconnection)
self.EditUserDialog(results[0])
def EditUserDialog(self, userdata=False):
busy = wx.BusyCursor()
action = "SELECT Position FROM user ORDER BY Position"
results = db.SendSQL(action, self.localsettings.dbconnection)
positions = []
for a in results:
if positions.__contains__(a[0]) == False:
positions.append(a[0])
dialog = wx.Dialog(self, -1, self.GetLabel("edituserlabel"))
dialogsizer = wx.BoxSizer(wx.VERTICAL)
panel = wx.Panel(dialog)
panel.userdata = userdata
panel.localsettings = self.localsettings
permissionssizer = wx.BoxSizer(wx.VERTICAL)
permissionssizer.Add(wx.StaticText(panel, -1, "", size=(-1,10)), 0, wx.EXPAND)
inputsizer = wx.BoxSizer(wx.HORIZONTAL)
namesizer = wx.BoxSizer(wx.VERTICAL)
namelabel = wx.StaticText(panel, -1, self.GetLabel("namelabel") + ":")
font = namelabel.GetFont()
font.SetPointSize(font.GetPointSize() - 2)
namelabel.SetFont(font)
namesizer.Add(namelabel, 0, wx.ALIGN_LEFT)
nameentry = wx.TextCtrl(panel, -1, "", size=(150,-1))
namesizer.Add(nameentry, 1, wx.EXPAND)
inputsizer.Add(namesizer, 0, wx.EXPAND)
passwordsizer = wx.BoxSizer(wx.VERTICAL)
passwordlabel = wx.StaticText(panel, -1, miscmethods.NoWrap(" " + self.GetLabel("passwordlabel") + ":"))
passwordlabel.SetFont(font)
passwordsizer.Add(passwordlabel, 0, wx.ALIGN_LEFT)
passwordentry = wx.TextCtrl(panel, -1, "", size=(150,-1))
passwordsizer.Add(passwordentry, 1, wx.EXPAND)
inputsizer.Add(passwordsizer, 0, wx.EXPAND)
positionsizer = wx.BoxSizer(wx.VERTICAL)
positionlabel = wx.StaticText(panel, -1, miscmethods.NoWrap(" " + self.GetLabel("positionlabel") + ":"))
positionlabel.SetFont(font)
positionsizer.Add(positionlabel, 0, wx.ALIGN_LEFT)
positionentry = wx.ComboBox(panel, -1, "", choices=positions)
positionsizer.Add(positionentry, 1, wx.EXPAND)
inputsizer.Add(positionsizer, 0, wx.EXPAND)
permissionssizer.Add(inputsizer, 0, wx.EXPAND)
permissionssizer.Add(wx.StaticText(panel, -1, "", size=(-1,10)), 0, wx.EXPAND)
permissionsnotebook = wx.Notebook(panel)
clientpermissions = ClientSettingsPanel(permissionsnotebook, self.GetLabel("clientslabel"))
permissionsnotebook.AddPage(clientpermissions, self.GetLabel("clientslabel"), select=True)
animalpermissions = GenericSettingsPanel(permissionsnotebook, self.GetLabel("animalslabel"))
permissionsnotebook.AddPage(animalpermissions, self.GetLabel("animalslabel"), select=False)
appointmentpermissions = AppointmentSettingsPanel(permissionsnotebook, self.GetLabel("appointmentslabel"))
permissionsnotebook.AddPage(appointmentpermissions, self.GetLabel("appointmentslabel"), select=False)
medicationpermissions = GenericSettingsPanel(permissionsnotebook, self.GetLabel("medicationlabel"))
permissionsnotebook.AddPage(medicationpermissions, self.GetLabel("medicationlabel"), select=False)
procedurepermissions = GenericSettingsPanel(permissionsnotebook, self.GetLabel("procedureslabel"))
permissionsnotebook.AddPage(procedurepermissions, self.GetLabel("procedureslabel"), select=False)
lookuppermissions = GenericSettingsPanel(permissionsnotebook, self.GetLabel("lookupslabel"))
permissionsnotebook.AddPage(lookuppermissions, self.GetLabel("lookupslabel"), select=False)
formpermissions = GenericSettingsPanel(permissionsnotebook, self.GetLabel("formslabel"))
permissionsnotebook.AddPage(formpermissions, self.GetLabel("formslabel"), select=False)
userpermissions = UserSettingsPanel(permissionsnotebook, self.GetLabel("userslabel"))
permissionsnotebook.AddPage(userpermissions, self.GetLabel("userslabel"), select=False)
diarypermissions = DiarySettingsPanel(permissionsnotebook, self.GetLabel("diarylabel"))
permissionsnotebook.AddPage(diarypermissions, self.GetLabel("diarylabel"), select=False)
miscpermissions = MiscSettingsPanel(permissionsnotebook, self.GetLabel("misclabel"))
permissionsnotebook.AddPage(miscpermissions, self.GetLabel("misclabel"), select=False)
permissionssizer.Add(permissionsnotebook, 1, wx.EXPAND)
tickallsizer = wx.BoxSizer(wx.HORIZONTAL)
untickallbitmap = wx.Bitmap("icons/reset.png")
untickallbutton = wx.BitmapButton(panel, -1, untickallbitmap)
untickallbutton.SetToolTipString(self.GetLabel("resetlabel"))
untickallbutton.Bind(wx.EVT_BUTTON, self.UnTickAll)
tickallsizer.Add(untickallbutton, 0, wx.EXPAND)
tickallbitmap = wx.Bitmap("icons/tickall.png")
tickallbutton = wx.BitmapButton(panel, -1, tickallbitmap)
tickallbutton.SetToolTipString(self.GetLabel("tickalltooltip"))
tickallbutton.Bind(wx.EVT_BUTTON, self.TickAll)
tickallsizer.Add(tickallbutton, 0, wx.EXPAND)
tickallsizer.Add(wx.StaticText(panel, -1, ""), 1, wx.EXPAND)
submitbitmap = wx.Bitmap("icons/submit.png")
submitbutton = wx.BitmapButton(panel, -1, submitbitmap)
submitbutton.SetToolTipString(self.GetLabel("submitlabel"))
submitbutton.Bind(wx.EVT_BUTTON, self.SubmitUser)
tickallsizer.Add(submitbutton, 0, wx.EXPAND)
permissionssizer.Add(tickallsizer, 0, wx.EXPAND)
panel.SetSizer(permissionssizer)
panel.clientpermissions = clientpermissions
panel.animalpermissions = animalpermissions
panel.appointmentpermissions = appointmentpermissions
panel.medicationpermissions = medicationpermissions
panel.procedurepermissions = procedurepermissions
panel.lookuppermissions = lookuppermissions
panel.formpermissions = formpermissions
panel.userpermissions = userpermissions
panel.diarypermissions = diarypermissions
panel.miscpermissions = miscpermissions
panel.nameentry = nameentry
panel.passwordentry = passwordentry
panel.positionentry = positionentry
dialogsizer.Add(panel, 1, wx.EXPAND)
dialog.SetSizer(dialogsizer)
if userdata != False:
panel.nameentry.SetValue(userdata[1])
panel.passwordentry.SetValue(userdata[2])
panel.positionentry.SetValue(userdata[3])
changelog = userdata[4].split("$")
if changelog[0][0] == "1":
panel.clientpermissions.edit.SetValue(True)
else:
panel.clientpermissions.edit.SetValue(False)
if changelog[0][1] == "1":
panel.clientpermissions.delete.SetValue(True)
else:
panel.clientpermissions.delete.SetValue(False)
if changelog[0][2] == "1":
panel.clientpermissions.editfinances.SetValue(True)
else:
panel.clientpermissions.editfinances.SetValue(False)
if changelog[1][0] == "1":
panel.animalpermissions.edit.SetValue(True)
else:
panel.animalpermissions.edit.SetValue(False)
if changelog[1][1] == "1":
panel.animalpermissions.delete.SetValue(True)
else:
panel.animalpermissions.delete.SetValue(False)
if changelog[2][0] == "1":
panel.appointmentpermissions.edit.SetValue(True)
else:
panel.appointmentpermissions.edit.SetValue(False)
if changelog[2][1] == "1":
panel.appointmentpermissions.delete.SetValue(True)
else:
panel.appointmentpermissions.delete.SetValue(False)
if changelog[2][2] == "1":
panel.appointmentpermissions.vetform.SetValue(True)
else:
panel.appointmentpermissions.vetform.SetValue(False)
if changelog[3][0] == "1":
panel.medicationpermissions.edit.SetValue(True)
else:
panel.medicationpermissions.edit.SetValue(False)
if changelog[3][1] == "1":
panel.medicationpermissions.delete.SetValue(True)
else:
panel.medicationpermissions.delete.SetValue(False)
if changelog[4][0] == "1":
panel.procedurepermissions.edit.SetValue(True)
else:
panel.procedurepermissions.edit.SetValue(False)
if changelog[4][1] == "1":
panel.procedurepermissions.delete.SetValue(True)
else:
panel.procedurepermissions.delete.SetValue(False)
if changelog[5][0] == "1":
panel.lookuppermissions.edit.SetValue(True)
else:
panel.lookuppermissions.edit.SetValue(False)
if changelog[5][1] == "1":
panel.lookuppermissions.delete.SetValue(True)
else:
panel.lookuppermissions.delete.SetValue(False)
if changelog[6][0] == "1":
panel.formpermissions.edit.SetValue(True)
else:
panel.formpermissions.edit.SetValue(False)
if changelog[6][1] == "1":
panel.formpermissions.delete.SetValue(True)
else:
panel.formpermissions.delete.SetValue(False)
if changelog[7][0] == "1":
panel.userpermissions.edit.SetValue(True)
else:
panel.userpermissions.edit.SetValue(False)
if changelog[7][1] == "1":
panel.userpermissions.delete.SetValue(True)
else:
panel.userpermissions.delete.SetValue(False)
if changelog[7][2] == "1":
panel.userpermissions.editrota.SetValue(True)
else:
panel.userpermissions.editrota.SetValue(False)
if changelog[8][0] == "1":
panel.miscpermissions.toolbar.SetValue(True)
else:
panel.miscpermissions.toolbar.SetValue(False)
if changelog[8][1] == "1":
panel.miscpermissions.changelog.SetValue(True)
else:
panel.miscpermissions.changelog.SetValue(False)
if changelog[8][2] == "1":
panel.miscpermissions.editsettings.SetValue(True)
else:
panel.miscpermissions.editsettings.SetValue(False)
if changelog[8][3] == "1":
panel.miscpermissions.multiplepanels.SetValue(True)
else:
panel.miscpermissions.multiplepanels.SetValue(False)
if changelog[8][4] == "1":
panel.miscpermissions.asmsync.SetValue(True)
else:
panel.miscpermissions.asmsync.SetValue(False)
if changelog[9][0] == "1":
panel.diarypermissions.adddiarynotes.SetValue(True)
else:
panel.diarypermissions.adddiarynotes.SetValue(False)
if changelog[9][1] == "1":
panel.diarypermissions.editdiarynotes.SetValue(True)
else:
panel.diarypermissions.editdiarynotes.SetValue(False)
if changelog[9][2] == "1":
panel.diarypermissions.deletediarynotes.SetValue(True)
else:
panel.diarypermissions.deletediarynotes.SetValue(False)
dialog.SetSize((800,400))
del busy
dialog.ShowModal()
def TickAll(self, ID):
panel = ID.GetEventObject().GetParent()
panel.clientpermissions.edit.SetValue(True)
panel.clientpermissions.delete.SetValue(True)
panel.clientpermissions.editfinances.SetValue(True)
panel.animalpermissions.edit.SetValue(True)
panel.animalpermissions.delete.SetValue(True)
panel.appointmentpermissions.edit.SetValue(True)
panel.appointmentpermissions.delete.SetValue(True)
panel.appointmentpermissions.vetform.SetValue(True)
panel.medicationpermissions.edit.SetValue(True)
panel.medicationpermissions.delete.SetValue(True)
panel.procedurepermissions.edit.SetValue(True)
panel.procedurepermissions.delete.SetValue(True)
panel.lookuppermissions.edit.SetValue(True)
panel.lookuppermissions.delete.SetValue(True)
panel.formpermissions.edit.SetValue(True)
panel.formpermissions.delete.SetValue(True)
panel.userpermissions.edit.SetValue(True)
panel.userpermissions.delete.SetValue(True)
panel.userpermissions.editrota.SetValue(True)
panel.miscpermissions.toolbar.SetValue(True)
panel.miscpermissions.changelog.SetValue(True)
panel.miscpermissions.editsettings.SetValue(True)
panel.miscpermissions.multiplepanels.SetValue(True)
panel.miscpermissions.asmsync.SetValue(True)
panel.diarypermissions.adddiarynotes.SetValue(True)
panel.diarypermissions.editdiarynotes.SetValue(True)
panel.diarypermissions.deletediarynotes.SetValue(True)
def UnTickAll(self, ID):
panel = ID.GetEventObject().GetParent()
panel.clientpermissions.edit.SetValue(False)
panel.clientpermissions.delete.SetValue(False)
panel.clientpermissions.editfinances.SetValue(False)
panel.animalpermissions.edit.SetValue(False)
panel.animalpermissions.delete.SetValue(False)
panel.appointmentpermissions.edit.SetValue(False)
panel.appointmentpermissions.delete.SetValue(False)
panel.appointmentpermissions.vetform.SetValue(False)
panel.medicationpermissions.edit.SetValue(False)
panel.medicationpermissions.delete.SetValue(False)
panel.procedurepermissions.edit.SetValue(False)
panel.procedurepermissions.delete.SetValue(False)
panel.lookuppermissions.edit.SetValue(False)
panel.lookuppermissions.delete.SetValue(False)
panel.formpermissions.edit.SetValue(False)
panel.formpermissions.delete.SetValue(False)
panel.userpermissions.edit.SetValue(False)
panel.userpermissions.delete.SetValue(False)
panel.userpermissions.editrota.SetValue(False)
panel.miscpermissions.toolbar.SetValue(False)
panel.miscpermissions.changelog.SetValue(False)
panel.miscpermissions.editsettings.SetValue(False)
panel.miscpermissions.multiplepanels.SetValue(False)
panel.miscpermissions.asmsync.SetValue(False)
panel.diarypermissions.adddiarynotes.SetValue(False)
panel.diarypermissions.editdiarynotes.SetValue(False)
panel.diarypermissions.deletediarynotes.SetValue(False)
def RefreshUsers(self, ID=False):
self.userlist.Clear()
self.users = []
action = "SELECT * FROM user ORDER BY Name;"
results = db.SendSQL(action, self.localsettings.dbconnection)
for a in results:
self.users.append(a[0])
self.userlist.Append(a[1] + " - " + a[3])
self.userlist.SetSelection(-1)
def SubmitUser(self, ID):
panel = ID.GetEventObject().GetParent()
username = panel.nameentry.GetValue()
userpassword = panel.passwordentry.GetValue()
position = panel.positionentry.GetValue()
if panel.clientpermissions.edit.GetValue() == True:
permissions = "1"
else:
permissions = "0"
if panel.clientpermissions.delete.GetValue() == True:
permissions = permissions + "1"
else:
permissions = permissions + "0"
if panel.clientpermissions.editfinances.GetValue() == True:
permissions = permissions + "1$"
else:
permissions = permissions + "0$"
if panel.animalpermissions.edit.GetValue() == True:
permissions = permissions + "1"
else:
permissions = permissions + "0"
if panel.animalpermissions.delete.GetValue() == True:
permissions = permissions + "1$"
else:
permissions = permissions + "0$"
if panel.appointmentpermissions.edit.GetValue() == True:
permissions = permissions + "1"
else:
permissions = permissions + "0"
if panel.appointmentpermissions.delete.GetValue() == True:
permissions = permissions + "1"
else:
permissions = permissions + "0"
if panel.appointmentpermissions.vetform.GetValue() == True:
permissions = permissions + "1$"
else:
permissions = permissions + "0$"
if panel.medicationpermissions.edit.GetValue() == True:
permissions = permissions + "1"
else:
permissions = permissions + "0"
if panel.medicationpermissions.delete.GetValue() == True:
permissions = permissions + "1$"
else:
permissions = permissions + "0$"
if panel.procedurepermissions.edit.GetValue() == True:
permissions = permissions + "1"
else:
permissions = permissions + "0"
if panel.procedurepermissions.delete.GetValue() == True:
permissions = permissions + "1$"
else:
permissions = permissions + "0$"
if panel.lookuppermissions.edit.GetValue() == True:
permissions = permissions + "1"
else:
permissions = permissions + "0"
if panel.lookuppermissions.delete.GetValue() == True:
permissions = permissions + "1$"
else:
permissions = permissions + "0$"
if panel.formpermissions.edit.GetValue() == True:
permissions = permissions + "1"
else:
permissions = permissions + "0"
if panel.formpermissions.delete.GetValue() == True:
permissions = permissions + "1$"
else:
permissions = permissions + "0$"
if panel.userpermissions.edit.GetValue() == True:
permissions = permissions + "1"
else:
permissions = permissions + "0"
if panel.userpermissions.delete.GetValue() == True:
permissions = permissions + "1"
else:
permissions = permissions + "0"
if panel.userpermissions.editrota.GetValue() == True:
permissions = permissions + "1$"
else:
permissions = permissions + "0$"
if panel.miscpermissions.toolbar.GetValue() == True:
permissions = permissions + "1"
else:
permissions = permissions + "0"
if panel.miscpermissions.changelog.GetValue() == True:
permissions = permissions + "1"
else:
permissions = permissions + "0"
if panel.miscpermissions.editsettings.GetValue() == True:
permissions = permissions + "1"
else:
permissions = permissions + "0"
if panel.miscpermissions.multiplepanels.GetValue() == True:
permissions = permissions + "1"
else:
permissions = permissions + "0"
if panel.miscpermissions.asmsync.GetValue() == True:
permissions = permissions + "1$"
else:
permissions = permissions + "0$"
if panel.diarypermissions.adddiarynotes.GetValue() == True:
permissions = permissions + "1"
else:
permissions = permissions + "0"
if panel.diarypermissions.editdiarynotes.GetValue() == True:
permissions = permissions + "1"
else:
permissions = permissions + "0"
if panel.diarypermissions.deletediarynotes.GetValue() == True:
permissions = permissions + "1"
else:
permissions = permissions + "0"
if panel.userdata == False:
userid = False
else:
userid = panel.userdata[0]
dbmethods.WriteToUserTable(self.localsettings.dbconnection, userid, username, userpassword, position, permissions)
self.RefreshUsers()
panel.GetParent().Close()
def DeleteUser(self, ID):
listboxid = self.userlist.GetSelection()
userid = self.users[listboxid]
action = "SELECT * FROM user WHERE ID = " + str(userid) + ";"
results = db.SendSQL(action, self.localsettings.dbconnection)
self.selecteduserid = userid
if miscmethods.ConfirmMessage(self.GetLabel("userdeletemessage")) == True:
action = "DELETE FROM user WHERE ID = " + str(self.selecteduserid) + ";"
results = db.SendSQL(action, self.localsettings.dbconnection)
self.RefreshUsers()
class EditStaffRota(wx.Panel):
def GetLabel(self, field):
return self.localsettings.dictionary[field][self.localsettings.language]
def __init__(self, notebook, localsettings):
self.localsettings = localsettings
self.pagetitle = miscmethods.GetPageTitle(notebook, self.GetLabel("editrotapagetitle"))
wx.Panel.__init__(self, notebook)
topsizer = wx.BoxSizer(wx.VERTICAL)
action = "SELECT Name FROM user WHERE Position LIKE \"%Vet%\" ORDER BY Name"
results = db.SendSQL(action, localsettings.dbconnection)
vets = []
for a in results:
vets.append(a[0])
toolssizer = wx.FlexGridSizer(rows=1)
vetlabel = wx.StaticText(self, -1, self.GetLabel("vetlabel") + ": ")
toolssizer.Add(vetlabel, 0, wx.ALIGN_CENTER)
vetentry = wx.ComboBox(self, -1, "", choices=vets)
toolssizer.Add(vetentry, 1, wx.EXPAND)
timeonlabel = wx.StaticText(self, -1, " " + self.GetLabel("timeonlabel") + ": ")
toolssizer.Add(timeonlabel, 0, wx.ALIGN_CENTER)
timeonentry = wx.TextCtrl(self, -1, "")
toolssizer.Add(timeonentry, 1, wx.EXPAND)
timeofflabel = wx.StaticText(self, -1, " " + self.GetLabel("timeofflabel") + ": ")
toolssizer.Add(timeofflabel, 0, wx.ALIGN_CENTER)
timeoffentry = wx.TextCtrl(self, -1, "")
toolssizer.Add(timeoffentry, 1, wx.EXPAND)
operatingcheckbox = wx.CheckBox(self, -1, " " + self.GetLabel("operatinglabel") + ": ")
toolssizer.Add(operatingcheckbox, 0, wx.ALIGN_CENTER)
#spacer2 = wx.StaticText(self, -1, "")
#toolssizer.Add(spacer2, 2, wx.EXPAND)
for a in (1, 3, 5):
toolssizer.AddGrowableCol(a)
submitbitmap = wx.Bitmap("icons/submit.png")
submitbutton = wx.BitmapButton(self, -1, submitbitmap)
submitbutton.Bind(wx.EVT_BUTTON, self.Submit)
toolssizer.Add(submitbutton, 0, wx.ALIGN_CENTER)
topsizer.Add(toolssizer, 0, wx.EXPAND)
spacer = wx.StaticText(self, -1, "")
topsizer.Add(spacer, 0, wx.EXPAND)
listssizer = wx.BoxSizer(wx.HORIZONTAL)
datesizer = wx.BoxSizer(wx.VERTICAL)
datelabel = wx.StaticText(self, -1, self.GetLabel("datelabel") + ":")
datesizer.Add(datelabel, 0, wx.ALIGN_LEFT)
datepickersizer = wx.BoxSizer(wx.HORIZONTAL)
#self.dateentry = wx.DatePickerCtrl(self, -1, size=(200,-1))
self.dateentry = customwidgets.DateCtrl(self, self.localsettings)
#self.dateentry.Bind(wx.EVT_DATE_CHANGED, self.RefreshRota)
datepickersizer.Add(self.dateentry, 1, wx.EXPAND)
refreshbitmap = wx.Bitmap("icons/refresh.png")
refreshbutton = wx.BitmapButton(self, -1, refreshbitmap)
refreshbutton.Bind(wx.EVT_BUTTON, self.RefreshRota)
datepickersizer.Add(refreshbutton, 0, wx.wx.EXPAND)
datesizer.Add(datepickersizer, 0, wx.EXPAND)
listssizer.Add(datesizer, 1, wx.EXPAND)
spacer1 = wx.StaticText(self, -1, "", size=(20,-1))
listssizer.Add(spacer1, 0, wx.EXPAND)
summarysizer = wx.BoxSizer(wx.VERTICAL)
staffsummarylabel = wx.StaticText(self, -1, self.GetLabel("staffsummarylabel") + ":")
summarysizer.Add(staffsummarylabel, 0, wx.ALIGN_LEFT)
staffsummarylistbox = customwidgets.StaffSummaryListbox(self, self.localsettings)
staffsummarylistbox.Bind(wx.EVT_LISTBOX, self.SlotSelected)
summarysizer.Add(staffsummarylistbox, 1, wx.EXPAND)
summarybuttonssizer = wx.BoxSizer(wx.HORIZONTAL)
editbitmap = wx.Bitmap("icons/edit.png")
editbutton = wx.BitmapButton(self, -1, editbitmap)
editbutton.Bind(wx.EVT_BUTTON, self.Edit)
summarybuttonssizer.Add(editbutton, 0, wx.ALIGN_LEFT)
deletebitmap = wx.Bitmap("icons/delete.png")
deletebutton = wx.BitmapButton(self, -1, deletebitmap)
deletebutton.Bind(wx.EVT_BUTTON, self.Delete)
summarybuttonssizer.Add(deletebutton, 0, wx.ALIGN_LEFT)
summarysizer.Add(summarybuttonssizer, 0, wx.ALIGN_LEFT)
listssizer.Add(summarysizer, 2, wx.EXPAND)
spacer3 = wx.StaticText(self, -1, "", size=(20,-1))
listssizer.Add(spacer3, 0, wx.EXPAND)
dayplansizer = wx.BoxSizer(wx.VERTICAL)
dayplanlabel = wx.StaticText(self, -1, self.GetLabel("dayplanlabel") + ":")
dayplansizer.Add(dayplanlabel, 0, wx.ALIGN_LEFT)
dayplan = wx.html.HtmlWindow(self)
dayplansizer.Add(dayplan, 1, wx.EXPAND)
listssizer.Add(dayplansizer, 3, wx.EXPAND)
topsizer.Add(listssizer, 1, wx.EXPAND)
self.SetSizer(topsizer)
self.vetentry = vetentry
self.timeonentry = timeonentry
self.timeoffentry = timeoffentry
self.staffsummarylistbox = staffsummarylistbox
self.dayplan = dayplan
self.operatingcheckbox = operatingcheckbox
self.staffsummarylistbox.RefreshList()
self.GenerateDayPlan()
def Submit(self, ID):
success = False
date = self.dateentry.GetValue()
date = miscmethods.GetSQLDateFromWXDate(date)
vet = self.vetentry.GetValue()
timeon = self.timeonentry.GetValue()
timeoff = self.timeoffentry.GetValue()
if self.operatingcheckbox.GetValue() == True:
operating = 1
else:
operating = 0
if vet == "":
miscmethods.ShowMessage(self.GetLabel("novetnamemessage"))
else:
if miscmethods.ValidateTime(timeon) == True and miscmethods.ValidateTime(timeoff) == True:
timeonint = int(timeon[:2] + timeon[3:5])
timeoffint = int(timeoff[:2] + timeoff[3:5])
if timeonint < timeoffint:
success = True
else:
miscmethods.ShowMessage(self.GetLabel("vetfinishedbeforestartingmessage"))
if success == True:
starttimesql = timeon[:2] + ":" + timeon[3:5] + ":00"
offtimesql = timeoff[:2] + ":" + timeoff[3:5] + ":00"
action = "SELECT ID FROM staff WHERE DATE = \"" + date + "\" AND Vet = \"" + vet + "\" AND ( \"" + starttimesql + "\" BETWEEN TimeOn AND TimeOff OR \"" + offtimesql + "\" BETWEEN TimeOn AND TimeOff OR TimeOn BETWEEN \"" + starttimesql + "\" AND \"" + offtimesql + "\" OR TimeOff BETWEEN \"" + starttimesql + "\" AND \"" + offtimesql + "\" )"
results = db.SendSQL(action, self.localsettings.dbconnection)
if len(results) > 0:
miscmethods.ShowMessage(self.GetLabel("vettwoplacesatoncemessage"))
else:
dbmethods.WriteToStaffTable(self.localsettings.dbconnection, date, vet, timeon, timeoff, operating)
self.RefreshRota()
else:
miscmethods.ShowMessage(self.GetLabel("invalidtimemessage"))
def Delete(self, ID):
listboxid = self.staffsummarylistbox.GetSelection()
staffid = self.staffsummarylistbox.htmllist[listboxid][0]
action = "DELETE FROM staff WHERE ID = " + str(staffid)
db.SendSQL(action, self.localsettings.dbconnection)
self.RefreshRota()
def GenerateDayPlan(self, ID=False):
date = self.dateentry.GetValue()
sqldate = miscmethods.GetSQLDateFromWXDate(date)
output = miscmethods.GenerateDayPlan(self.localsettings, sqldate, 30)
self.dayplan.SetPage(output)
def RefreshRota(self, ID=False):
self.staffsummarylistbox.RefreshList()
self.GenerateDayPlan()
def Edit(self, ID):
listboxid = self.staffsummarylistbox.GetSelection()
staffid = self.staffsummarylistbox.htmllist[listboxid][0]
success = False
date = self.dateentry.GetValue()
date = miscmethods.GetSQLDateFromWXDate(date)
vet = self.vetentry.GetValue()
timeon = self.timeonentry.GetValue()
timeoff = self.timeoffentry.GetValue()
if self.operatingcheckbox.GetValue() == True:
operating = 1
else:
operating = 0
if miscmethods.ValidateTime(timeon) == True and miscmethods.ValidateTime(timeoff) == True:
timeonint = int(timeon[:2] + timeon[3:5])
timeoffint = int(timeoff[:2] + timeoff[3:5])
if timeonint < timeoffint:
success = True
else:
miscmethods.ShowMessage(self.GetLabel("vetfinishedbeforestartingmessage"))
if success == True:
dbmethods.WriteToStaffTable(self.localsettings.dbconnection, date, vet, timeon, timeoff, operating, staffid)
self.RefreshRota()
else:
miscmethods.ShowMessage(self.GetLabel("invalidtimemessage"))
def SlotSelected(self, ID):
listboxid = self.staffsummarylistbox.GetSelection()
staffdata = self.staffsummarylistbox.htmllist[listboxid]
self.vetentry.SetValue(staffdata[1])
self.timeonentry.SetValue(staffdata[3])
self.timeoffentry.SetValue(staffdata[4])
if staffdata[5] == 0:
self.operatingcheckbox.SetValue(False)
else:
self.operatingcheckbox.SetValue(True)
|
UTF-8
|
Python
| false | false | 2,014 |
3,607,772,569,782 |
790492450f4b6acd6107e43aab439df03e15d6f0
|
9bd0004220edc6cde7927d06f4d06d05a57d6d7d
|
/snake/protocol.py
|
064e328fc1b1200cc3dd979e7772138aa0023fe2
|
[] |
no_license
|
lwm3751/folium
|
https://github.com/lwm3751/folium
|
32b8c1450d8a1dc1c899ac959493fd4ae5166264
|
e32237b6bb5dabbce64ea08e2cf8f4fe60b514d5
|
refs/heads/master
| 2021-01-22T03:12:58.594000 | 2011-01-09T15:36:02 | 2011-01-09T15:36:02 | 26,789,096 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null |
import time
import _xq
import snake.book.dictbook
class Engine(_xq.UCCI):
def __init__(self):
_xq.UCCI.__init__(self)
self.book = snake.book.dictbook.dictbook()
def run(self):
_xq.writeline('id name folium')
_xq.writeline('id author Wangmao Lin')
_xq.writeline('id user folium users')
_xq.writeline('option usemillisec type check default true')
self.usemillisec = True
_xq.writeline('ucciok')
self.bans = []
self.loop()
def loop(self):
while True:
while not _xq.readable():
time.sleep(0.001)
line = _xq.readline()
if line == 'isready':
_xq.writeline('readyok')
elif line == 'quit' or line == 'exit':
_xq.writeline('bye')
return
elif line.startswith('setoption '):
self.setoption(line[10:])
elif line.startswith('position '):
self.position(line[9:])
elif line.startswith('banmoves '):
self.banmoves(line[9:])
elif line.startswith('go'):
self.go(line)
elif line.startswith('probe'):
self.probe(line)
def position(self, position):
if " moves " in position:
position, moves = position.split(" moves ")
moves = moves.split()
else:
moves = []
if position.startswith("fen "):
fen = position[4:]
elif position == "startpos":
fen = "rnbakabnr/9/1c5c1/p1p1p1p1p/9/9/P1P1P1P1P/1C5C1/9/RNBAKABNR r"
self.load(fen)
for move in moves:
move = _xq.ucci2move(move)
self.makemove(move)
self.bans = []
def setoption(self, option):
return
if option.startswith('usemillisec '):
self.usemillisec = (option[12:] == 'true')
elif option.startswith('debug'):
pass
def banmoves(self, moves):
self.bans = moves.split()
def go(self, line):
self.stop = False
self.ponder = False
self.draw = False
self.depth = 255
self.starttime = _xq.currenttime()
self.mintime = self.maxtime = self.starttime + 24*60*60
move = self.book.search(str(self), self.bans) if self.book else None
if move:
_xq.writeline("info book move: %s" % move)
_xq.writeline("info book search time: %f" % (_xq.currenttime() - self.starttime))
_xq.writeline("bestmove %s" % move)
return
if line.startswith("go ponder "):
self.ponder = True
line = line[10:]
elif line.startswith("go draw "):
self.draw = True
line = line[8:]
else:
line = line[2:]
if self.usemillisec:
propertime = limittime = float(24*3600*1000)
else:
propertime = limittime = float(24*3600)
parameters = line.split()
if parameters:
parameter = parameters[0]
if parameter == "depth":
self.ponder = False
parameter = parameters[1]
if parameter != "infinite":
self.depth = int(parameter)
elif parameter == "time":
propertime = limittime = totaltime = float(parameters[1])
parameters = parameters[2:]
while parameters:
parameter = parameters[0]
if parameter == "movestogo":
count = int(parameters[1])
propertime = totaltime/count
limittime = totaltime
elif parameter == "increment":
increment = int(parameters[1])
propertime = totaltime*0.05+increment
limittime = totaltime*0.5
parameters = parameters[2:]
limittime = min(propertime*1.618, limittime)
propertime = propertime*0.618
if self.usemillisec:
propertime = propertime * 0.001
limittime = limittime * 0.001
self.mintime = self.starttime + propertime
self.maxtime = self.starttime + limittime
move = self.search([_xq.ucci2move(move) for move in self.bans])
if move:
_xq.writeline("bestmove %s" % _xq.move2ucci(move))
else:
_xq.writeline("nobestmove")
|
UTF-8
|
Python
| false | false | 2,011 |
2,972,117,399,431 |
274d4b578b05fb3ba9b918df81da722331b899ac
|
d9a68ddcc29bd23e2db2d513de14e95d8fbb1b64
|
/HexagonExample.py
|
b4507ea25b9080463b6f65a75e00b27e71da53f5
|
[] |
no_license
|
PamelaM/AntWars
|
https://github.com/PamelaM/AntWars
|
984401f33407910eba6d170452eb95489a33e02f
|
9de0ebcf877eff44a619db90fcf03eeffe744f09
|
refs/heads/master
| 2020-12-24T18:03:39.312000 | 2012-09-05T00:15:55 | 2012-09-05T00:15:55 | 2,583,380 | 1 | 2 | null | false | 2020-09-30T18:53:17 | 2011-10-15T20:21:50 | 2014-02-11T01:01:51 | 2012-09-05T00:16:01 | 186 | 6 | 4 | 1 |
Python
| false | false |
#/usr/bin/env python
import os, pygame,math
from pygame.locals import *
# This is the rectangular size of the hexagon tiles.
TILE_WIDTH = 38
TILE_HEIGHT = 41
# This is the distance in height between two rows.
ROW_HEIGHT = 31
# This value will be applied to all odd rows x value.
ODD_ROW_X_MOD = 19
# This is the size of the square grid that will help us convert pixel locations to hexagon map locations.
GRID_WIDTH = 38
GRID_HEIGHT = 31
# This is the modification tables for the square grid.
a1=(-1,-1)
b1=(0,0)
c1=(0,-1)
gridEvenRows = [
[a1,a1,a1,a1,a1,a1,a1,a1,a1,a1,a1,a1,a1,a1,a1,a1,a1,a1,b1,b1,c1,c1,c1,c1,c1,c1,c1,c1,c1,c1,c1,c1,c1,c1,c1,c1,c1,c1],
[a1,a1,a1,a1,a1,a1,a1,a1,a1,a1,a1,a1,a1,a1,a1,a1,b1,b1,b1,b1,b1,b1,c1,c1,c1,c1,c1,c1,c1,c1,c1,c1,c1,c1,c1,c1,c1,c1],
[a1,a1,a1,a1,a1,a1,a1,a1,a1,a1,a1,a1,a1,a1,b1,b1,b1,b1,b1,b1,b1,b1,b1,b1,c1,c1,c1,c1,c1,c1,c1,c1,c1,c1,c1,c1,c1,c1],
[a1,a1,a1,a1,a1,a1,a1,a1,a1,a1,a1,a1,b1,b1,b1,b1,b1,b1,b1,b1,b1,b1,b1,b1,b1,b1,c1,c1,c1,c1,c1,c1,c1,c1,c1,c1,c1,c1],
[a1,a1,a1,a1,a1,a1,a1,a1,a1,a1,b1,b1,b1,b1,b1,b1,b1,b1,b1,b1,b1,b1,b1,b1,b1,b1,b1,b1,c1,c1,c1,c1,c1,c1,c1,c1,c1,c1],
[a1,a1,a1,a1,a1,a1,a1,a1,a1,b1,b1,b1,b1,b1,b1,b1,b1,b1,b1,b1,b1,b1,b1,b1,b1,b1,b1,b1,b1,c1,c1,c1,c1,c1,c1,c1,c1,c1],
[a1,a1,a1,a1,a1,a1,a1,b1,b1,b1,b1,b1,b1,b1,b1,b1,b1,b1,b1,b1,b1,b1,b1,b1,b1,b1,b1,b1,b1,b1,b1,c1,c1,c1,c1,c1,c1,c1],
[a1,a1,a1,a1,a1,b1,b1,b1,b1,b1,b1,b1,b1,b1,b1,b1,b1,b1,b1,b1,b1,b1,b1,b1,b1,b1,b1,b1,b1,b1,b1,b1,b1,c1,c1,c1,c1,c1],
[a1,a1,a1,b1,b1,b1,b1,b1,b1,b1,b1,b1,b1,b1,b1,b1,b1,b1,b1,b1,b1,b1,b1,b1,b1,b1,b1,b1,b1,b1,b1,b1,b1,b1,b1,c1,c1,c1],
[a1,b1,b1,b1,b1,b1,b1,b1,b1,b1,b1,b1,b1,b1,b1,b1,b1,b1,b1,b1,b1,b1,b1,b1,b1,b1,b1,b1,b1,b1,b1,b1,b1,b1,b1,b1,b1,c1],
[b1,b1,b1,b1,b1,b1,b1,b1,b1,b1,b1,b1,b1,b1,b1,b1,b1,b1,b1,b1,b1,b1,b1,b1,b1,b1,b1,b1,b1,b1,b1,b1,b1,b1,b1,b1,b1,b1],
[b1,b1,b1,b1,b1,b1,b1,b1,b1,b1,b1,b1,b1,b1,b1,b1,b1,b1,b1,b1,b1,b1,b1,b1,b1,b1,b1,b1,b1,b1,b1,b1,b1,b1,b1,b1,b1,b1],
[b1,b1,b1,b1,b1,b1,b1,b1,b1,b1,b1,b1,b1,b1,b1,b1,b1,b1,b1,b1,b1,b1,b1,b1,b1,b1,b1,b1,b1,b1,b1,b1,b1,b1,b1,b1,b1,b1],
[b1,b1,b1,b1,b1,b1,b1,b1,b1,b1,b1,b1,b1,b1,b1,b1,b1,b1,b1,b1,b1,b1,b1,b1,b1,b1,b1,b1,b1,b1,b1,b1,b1,b1,b1,b1,b1,b1],
[b1,b1,b1,b1,b1,b1,b1,b1,b1,b1,b1,b1,b1,b1,b1,b1,b1,b1,b1,b1,b1,b1,b1,b1,b1,b1,b1,b1,b1,b1,b1,b1,b1,b1,b1,b1,b1,b1],
[b1,b1,b1,b1,b1,b1,b1,b1,b1,b1,b1,b1,b1,b1,b1,b1,b1,b1,b1,b1,b1,b1,b1,b1,b1,b1,b1,b1,b1,b1,b1,b1,b1,b1,b1,b1,b1,b1],
[b1,b1,b1,b1,b1,b1,b1,b1,b1,b1,b1,b1,b1,b1,b1,b1,b1,b1,b1,b1,b1,b1,b1,b1,b1,b1,b1,b1,b1,b1,b1,b1,b1,b1,b1,b1,b1,b1],
[b1,b1,b1,b1,b1,b1,b1,b1,b1,b1,b1,b1,b1,b1,b1,b1,b1,b1,b1,b1,b1,b1,b1,b1,b1,b1,b1,b1,b1,b1,b1,b1,b1,b1,b1,b1,b1,b1],
[b1,b1,b1,b1,b1,b1,b1,b1,b1,b1,b1,b1,b1,b1,b1,b1,b1,b1,b1,b1,b1,b1,b1,b1,b1,b1,b1,b1,b1,b1,b1,b1,b1,b1,b1,b1,b1,b1],
[b1,b1,b1,b1,b1,b1,b1,b1,b1,b1,b1,b1,b1,b1,b1,b1,b1,b1,b1,b1,b1,b1,b1,b1,b1,b1,b1,b1,b1,b1,b1,b1,b1,b1,b1,b1,b1,b1],
[b1,b1,b1,b1,b1,b1,b1,b1,b1,b1,b1,b1,b1,b1,b1,b1,b1,b1,b1,b1,b1,b1,b1,b1,b1,b1,b1,b1,b1,b1,b1,b1,b1,b1,b1,b1,b1,b1],
[b1,b1,b1,b1,b1,b1,b1,b1,b1,b1,b1,b1,b1,b1,b1,b1,b1,b1,b1,b1,b1,b1,b1,b1,b1,b1,b1,b1,b1,b1,b1,b1,b1,b1,b1,b1,b1,b1],
[b1,b1,b1,b1,b1,b1,b1,b1,b1,b1,b1,b1,b1,b1,b1,b1,b1,b1,b1,b1,b1,b1,b1,b1,b1,b1,b1,b1,b1,b1,b1,b1,b1,b1,b1,b1,b1,b1],
[b1,b1,b1,b1,b1,b1,b1,b1,b1,b1,b1,b1,b1,b1,b1,b1,b1,b1,b1,b1,b1,b1,b1,b1,b1,b1,b1,b1,b1,b1,b1,b1,b1,b1,b1,b1,b1,b1],
[b1,b1,b1,b1,b1,b1,b1,b1,b1,b1,b1,b1,b1,b1,b1,b1,b1,b1,b1,b1,b1,b1,b1,b1,b1,b1,b1,b1,b1,b1,b1,b1,b1,b1,b1,b1,b1,b1],
[b1,b1,b1,b1,b1,b1,b1,b1,b1,b1,b1,b1,b1,b1,b1,b1,b1,b1,b1,b1,b1,b1,b1,b1,b1,b1,b1,b1,b1,b1,b1,b1,b1,b1,b1,b1,b1,b1],
[b1,b1,b1,b1,b1,b1,b1,b1,b1,b1,b1,b1,b1,b1,b1,b1,b1,b1,b1,b1,b1,b1,b1,b1,b1,b1,b1,b1,b1,b1,b1,b1,b1,b1,b1,b1,b1,b1],
[b1,b1,b1,b1,b1,b1,b1,b1,b1,b1,b1,b1,b1,b1,b1,b1,b1,b1,b1,b1,b1,b1,b1,b1,b1,b1,b1,b1,b1,b1,b1,b1,b1,b1,b1,b1,b1,b1],
[b1,b1,b1,b1,b1,b1,b1,b1,b1,b1,b1,b1,b1,b1,b1,b1,b1,b1,b1,b1,b1,b1,b1,b1,b1,b1,b1,b1,b1,b1,b1,b1,b1,b1,b1,b1,b1,b1],
[b1,b1,b1,b1,b1,b1,b1,b1,b1,b1,b1,b1,b1,b1,b1,b1,b1,b1,b1,b1,b1,b1,b1,b1,b1,b1,b1,b1,b1,b1,b1,b1,b1,b1,b1,b1,b1,b1],
[b1,b1,b1,b1,b1,b1,b1,b1,b1,b1,b1,b1,b1,b1,b1,b1,b1,b1,b1,b1,b1,b1,b1,b1,b1,b1,b1,b1,b1,b1,b1,b1,b1,b1,b1,b1,b1,b1]
]
a2=(-1,0)
b2=(0,-1)
c2=(0,0)
gridOddRows = [
[a2,b2,b2,b2,b2,b2,b2,b2,b2,b2,b2,b2,b2,b2,b2,b2,b2,b2,b2,b2,b2,b2,b2,b2,b2,b2,b2,b2,b2,b2,b2,b2,b2,b2,b2,b2,b2,c2],
[a2,a2,a2,b2,b2,b2,b2,b2,b2,b2,b2,b2,b2,b2,b2,b2,b2,b2,b2,b2,b2,b2,b2,b2,b2,b2,b2,b2,b2,b2,b2,b2,b2,b2,b2,c2,c2,c2],
[a2,a2,a2,a2,a2,b2,b2,b2,b2,b2,b2,b2,b2,b2,b2,b2,b2,b2,b2,b2,b2,b2,b2,b2,b2,b2,b2,b2,b2,b2,b2,b2,b2,c2,c2,c2,c2,c2],
[a2,a2,a2,a2,a2,a2,a2,b2,b2,b2,b2,b2,b2,b2,b2,b2,b2,b2,b2,b2,b2,b2,b2,b2,b2,b2,b2,b2,b2,b2,b2,c2,c2,c2,c2,c2,c2,c2],
[a2,a2,a2,a2,a2,a2,a2,a2,a2,b2,b2,b2,b2,b2,b2,b2,b2,b2,b2,b2,b2,b2,b2,b2,b2,b2,b2,b2,b2,c2,c2,c2,c2,c2,c2,c2,c2,c2],
[a2,a2,a2,a2,a2,a2,a2,a2,a2,a2,b2,b2,b2,b2,b2,b2,b2,b2,b2,b2,b2,b2,b2,b2,b2,b2,b2,b2,c2,c2,c2,c2,c2,c2,c2,c2,c2,c2],
[a2,a2,a2,a2,a2,a2,a2,a2,a2,a2,a2,a2,b2,b2,b2,b2,b2,b2,b2,b2,b2,b2,b2,b2,b2,b2,c2,c2,c2,c2,c2,c2,c2,c2,c2,c2,c2,c2],
[a2,a2,a2,a2,a2,a2,a2,a2,a2,a2,a2,a2,a2,a2,b2,b2,b2,b2,b2,b2,b2,b2,b2,b2,c2,c2,c2,c2,c2,c2,c2,c2,c2,c2,c2,c2,c2,c2],
[a2,a2,a2,a2,a2,a2,a2,a2,a2,a2,a2,a2,a2,a2,a2,a2,b2,b2,b2,b2,b2,b2,c2,c2,c2,c2,c2,c2,c2,c2,c2,c2,c2,c2,c2,c2,c2,c2],
[a2,a2,a2,a2,a2,a2,a2,a2,a2,a2,a2,a2,a2,a2,a2,a2,a2,a2,b2,b2,c2,c2,c2,c2,c2,c2,c2,c2,c2,c2,c2,c2,c2,c2,c2,c2,c2,c2],
[a2,a2,a2,a2,a2,a2,a2,a2,a2,a2,a2,a2,a2,a2,a2,a2,a2,a2,a2,c2,c2,c2,c2,c2,c2,c2,c2,c2,c2,c2,c2,c2,c2,c2,c2,c2,c2,c2],
[a2,a2,a2,a2,a2,a2,a2,a2,a2,a2,a2,a2,a2,a2,a2,a2,a2,a2,a2,c2,c2,c2,c2,c2,c2,c2,c2,c2,c2,c2,c2,c2,c2,c2,c2,c2,c2,c2],
[a2,a2,a2,a2,a2,a2,a2,a2,a2,a2,a2,a2,a2,a2,a2,a2,a2,a2,a2,c2,c2,c2,c2,c2,c2,c2,c2,c2,c2,c2,c2,c2,c2,c2,c2,c2,c2,c2],
[a2,a2,a2,a2,a2,a2,a2,a2,a2,a2,a2,a2,a2,a2,a2,a2,a2,a2,a2,c2,c2,c2,c2,c2,c2,c2,c2,c2,c2,c2,c2,c2,c2,c2,c2,c2,c2,c2],
[a2,a2,a2,a2,a2,a2,a2,a2,a2,a2,a2,a2,a2,a2,a2,a2,a2,a2,a2,c2,c2,c2,c2,c2,c2,c2,c2,c2,c2,c2,c2,c2,c2,c2,c2,c2,c2,c2],
[a2,a2,a2,a2,a2,a2,a2,a2,a2,a2,a2,a2,a2,a2,a2,a2,a2,a2,a2,c2,c2,c2,c2,c2,c2,c2,c2,c2,c2,c2,c2,c2,c2,c2,c2,c2,c2,c2],
[a2,a2,a2,a2,a2,a2,a2,a2,a2,a2,a2,a2,a2,a2,a2,a2,a2,a2,a2,c2,c2,c2,c2,c2,c2,c2,c2,c2,c2,c2,c2,c2,c2,c2,c2,c2,c2,c2],
[a2,a2,a2,a2,a2,a2,a2,a2,a2,a2,a2,a2,a2,a2,a2,a2,a2,a2,a2,c2,c2,c2,c2,c2,c2,c2,c2,c2,c2,c2,c2,c2,c2,c2,c2,c2,c2,c2],
[a2,a2,a2,a2,a2,a2,a2,a2,a2,a2,a2,a2,a2,a2,a2,a2,a2,a2,a2,c2,c2,c2,c2,c2,c2,c2,c2,c2,c2,c2,c2,c2,c2,c2,c2,c2,c2,c2],
[a2,a2,a2,a2,a2,a2,a2,a2,a2,a2,a2,a2,a2,a2,a2,a2,a2,a2,a2,c2,c2,c2,c2,c2,c2,c2,c2,c2,c2,c2,c2,c2,c2,c2,c2,c2,c2,c2],
[a2,a2,a2,a2,a2,a2,a2,a2,a2,a2,a2,a2,a2,a2,a2,a2,a2,a2,a2,c2,c2,c2,c2,c2,c2,c2,c2,c2,c2,c2,c2,c2,c2,c2,c2,c2,c2,c2],
[a2,a2,a2,a2,a2,a2,a2,a2,a2,a2,a2,a2,a2,a2,a2,a2,a2,a2,a2,c2,c2,c2,c2,c2,c2,c2,c2,c2,c2,c2,c2,c2,c2,c2,c2,c2,c2,c2],
[a2,a2,a2,a2,a2,a2,a2,a2,a2,a2,a2,a2,a2,a2,a2,a2,a2,a2,a2,c2,c2,c2,c2,c2,c2,c2,c2,c2,c2,c2,c2,c2,c2,c2,c2,c2,c2,c2],
[a2,a2,a2,a2,a2,a2,a2,a2,a2,a2,a2,a2,a2,a2,a2,a2,a2,a2,a2,c2,c2,c2,c2,c2,c2,c2,c2,c2,c2,c2,c2,c2,c2,c2,c2,c2,c2,c2],
[a2,a2,a2,a2,a2,a2,a2,a2,a2,a2,a2,a2,a2,a2,a2,a2,a2,a2,a2,c2,c2,c2,c2,c2,c2,c2,c2,c2,c2,c2,c2,c2,c2,c2,c2,c2,c2,c2],
[a2,a2,a2,a2,a2,a2,a2,a2,a2,a2,a2,a2,a2,a2,a2,a2,a2,a2,a2,c2,c2,c2,c2,c2,c2,c2,c2,c2,c2,c2,c2,c2,c2,c2,c2,c2,c2,c2],
[a2,a2,a2,a2,a2,a2,a2,a2,a2,a2,a2,a2,a2,a2,a2,a2,a2,a2,a2,c2,c2,c2,c2,c2,c2,c2,c2,c2,c2,c2,c2,c2,c2,c2,c2,c2,c2,c2],
[a2,a2,a2,a2,a2,a2,a2,a2,a2,a2,a2,a2,a2,a2,a2,a2,a2,a2,a2,c2,c2,c2,c2,c2,c2,c2,c2,c2,c2,c2,c2,c2,c2,c2,c2,c2,c2,c2],
[a2,a2,a2,a2,a2,a2,a2,a2,a2,a2,a2,a2,a2,a2,a2,a2,a2,a2,a2,c2,c2,c2,c2,c2,c2,c2,c2,c2,c2,c2,c2,c2,c2,c2,c2,c2,c2,c2],
[a2,a2,a2,a2,a2,a2,a2,a2,a2,a2,a2,a2,a2,a2,a2,a2,a2,a2,a2,c2,c2,c2,c2,c2,c2,c2,c2,c2,c2,c2,c2,c2,c2,c2,c2,c2,c2,c2],
[a2,a2,a2,a2,a2,a2,a2,a2,a2,a2,a2,a2,a2,a2,a2,a2,a2,a2,a2,c2,c2,c2,c2,c2,c2,c2,c2,c2,c2,c2,c2,c2,c2,c2,c2,c2,c2,c2]
]
class HexagonExample:
def pixelToHexMap(self,x,y):
"""
Converts a pixel location to a location on the hexagon map.
"""
# Get the square location in our help grid.
gridX = x/GRID_WIDTH
gridY = y/GRID_HEIGHT
# Calculate the pixel location within that square
gridPixelX = x%GRID_WIDTH
gridPixelY = y%GRID_HEIGHT
# Update the gridRect to show the correct location in the grid
self.gridRect.topleft = (gridX*GRID_WIDTH,gridY*GRID_HEIGHT)
# Apply the modifiers to get the correct hexagon map location.
if gridY&1:
# Odd rows
hexMapX=gridX+gridOddRows[gridPixelY][gridPixelX][0]
hexMapY=gridY+gridOddRows[gridPixelY][gridPixelX][1]
else:
# Even rows
hexMapX=gridX+gridEvenRows[gridPixelY][gridPixelX][0]
hexMapY=gridY+gridEvenRows[gridPixelY][gridPixelX][1]
return (hexMapX,hexMapY)
def hexMapToPixel(self,mapX,mapY):
"""
Returns the top left pixel location of a hexagon map location.
"""
if mapY & 1:
# Odd rows will be moved to the right.
return (mapX*TILE_WIDTH+ODD_ROW_X_MOD,mapY*ROW_HEIGHT)
else:
return (mapX*TILE_WIDTH,mapY*ROW_HEIGHT)
def drawMap(self):
"""
Draw the tiles.
"""
fnt = pygame.font.Font(pygame.font.get_default_font(),12)
self.mapimg = pygame.Surface((640,480),1)
self.mapimg= self.mapimg.convert()
self.mapimg.fill((104,104,104))
for x in range(16):
for y in range(15):
# Get the top left location of the tile.
pixelX,pixelY = self.hexMapToPixel(x,y)
# Blit the tile to the map image.
self.mapimg.blit(self.tile,(pixelX,pixelY))
# Show the hexagon map location in the center of the tile.
location = fnt.render("%d,%d" % (x,y), 0, (0xff,0xff,0xff))
lrect=location.get_rect()
lrect.center = (pixelX+(TILE_WIDTH/2),pixelY+(TILE_HEIGHT/2))
self.mapimg.blit(location,lrect.topleft)
def loadTiles(self):
"""
Load the tile and the cursor.
"""
self.tile = pygame.image.load("./hextile.png").convert()
self.tile.set_colorkey((0x80, 0x00, 0x80), RLEACCEL)
self.up_cursor = pygame.image.load("./hexcursor.png").convert()
self.up_cursor.set_colorkey((0x80, 0x00, 0x80), RLEACCEL)
self.cursorPos = self.up_cursor.get_rect()
self.cursor = self.up_cursor
self.down_cursor = pygame.image.load("./hexcursor_down.png").convert()
self.down_cursor.set_colorkey((0x80, 0x00, 0x80), RLEACCEL)
assert(self.down_cursor.get_rect()==self.up_cursor.get_rect())
def init(self):
"""
Setup the screen etc.
"""
self.screen = pygame.display.set_mode((640, 480),1)
pygame.display.set_caption('Press SPACE to toggle the gridRect display')
self.loadTiles()
self.drawMap()
self.gridRect = pygame.Rect(0,0,GRID_WIDTH,GRID_HEIGHT)
def setCursor(self,x,y):
"""
Set the hexagon map cursor.
"""
mapX,mapY = self.pixelToHexMap(x,y)
pixelX,pixelY = self.hexMapToPixel(mapX,mapY)
self.cursorPos.topleft = (pixelX,pixelY)
def mainLoop(self):
pygame.init()
self.init()
clock = pygame.time.Clock()
showGridRect = True
while 1:
clock.tick(30)
for event in pygame.event.get():
if event.type == QUIT:
return
elif event.type == KEYDOWN:
if event.key == K_ESCAPE:
return
elif event.key == K_SPACE:
showGridRect = not showGridRect
elif event.type == MOUSEMOTION:
self.setCursor(event.pos[0],event.pos[1])
elif event.type == MOUSEBUTTONDOWN:
self.cursor = self.down_cursor
elif event.type == MOUSEBUTTONUP:
self.cursor = self.up_cursor
# DRAWING
self.screen.blit(self.mapimg, (0, 0))
self.screen.blit(self.cursor,self.cursorPos)
if showGridRect:
pygame.draw.rect(self.screen, (0xff,0xff,0xff), self.gridRect, 1)
pygame.display.flip()
def main():
g = HexagonExample()
g.mainLoop()
#this calls the 'main' function when this script is executed
if __name__ == '__main__': main()
|
UTF-8
|
Python
| false | false | 2,012 |
3,848,290,728,309 |
6d357e65549c08e626ae2ec086f9eadded3be9bf
|
bacfc3f6b633b6b73cbb9e40d10674d809358c75
|
/tools/__init__.py
|
5b977fa46d5dc9f50474a11961af5c818fa60bc2
|
[
"Apache-2.0"
] |
permissive
|
satra/BrainImagingPipelines
|
https://github.com/satra/BrainImagingPipelines
|
fc1c4e63fc790a1931aa421bef6b7d3814ed4e65
|
2b0da2b50814cc685f15fefbae8144624308ebfc
|
refs/heads/master
| 2021-01-18T08:26:03.118000 | 2012-08-18T15:29:57 | 2012-08-18T15:29:57 | 3,511,786 | 1 | 2 | null | true | 2012-07-11T20:43:17 | 2012-02-22T05:50:20 | 2012-06-19T05:16:11 | 2012-06-19T05:16:11 | 280 | null | null | null |
Python
| null | null |
__author__ = 'keshavan'
|
UTF-8
|
Python
| false | false | 2,012 |
5,411,658,798,094 |
f092e0763d745946bedf026c0cfe6bdb6d6c704e
|
84bda016e90a040318ed3d0728ae6b17b2c1fcb1
|
/scripts/arm_scripts/check_pc_match.py
|
eaa2a24fc66784f65e014aa3c0618a8903a299a7
|
[] |
no_license
|
silkyar/kremlin_cc_space
|
https://github.com/silkyar/kremlin_cc_space
|
b7747d76463015a74071181fc9fb62eadbc2e302
|
47d9a67f4ce648e4aa16d4a6d42add7bbbaa3178
|
refs/heads/master
| 2019-07-28T18:30:29.601000 | 2014-05-20T04:00:16 | 2014-05-20T04:00:16 | null | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null |
from pprint import pprint
from collections import defaultdict
from sys import argv
script, trace_dec, bb_offset_arm_out = argv
f1 = open(trace_dec)
f2 = open(bb_offset_arm_out)
pc = []
f = []
nf = []
for line in f2:
if line:
text = line.split()
if text:
pc.append(text[2])
f2.close()
found = not_found = 0
for line in f1:
if line:
text = line.split()
if text:
if text[0] in pc:
f.append(text[0])
found = found + 1
else:
nf.append(text[0])
not_found = not_found + 1
f1.close()
for x in nf:
print x
print found, not_found
|
UTF-8
|
Python
| false | false | 2,014 |
4,647,154,634,952 |
a944492059f711876741fb9e23a251c830b0d778
|
1e0dbcb5f277b5b2f074288d41b4fcaa30dce2f0
|
/make_html_str_set.py
|
12a6497557a0813dd36e81f99c5f8dd71ecb2ef9
|
[
"CC0-1.0",
"LicenseRef-scancode-public-domain"
] |
non_permissive
|
tsee/hash-table-shootout
|
https://github.com/tsee/hash-table-shootout
|
522a72ddbe71ef69537ff325be110f67add3b806
|
82e6634311de83ddde5f750da13fe3dffd4b9d2f
|
refs/heads/master
| 2021-01-21T00:22:31.117000 | 2013-01-11T06:51:29 | 2013-01-11T07:33:03 | null | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null |
import sys
html_template = file('charts-template-str_set.html', 'r').read()
file('charts_str_set.html', 'w').write(html_template.replace('__CHART_DATA_GOES_HERE__', sys.stdin.read()))
|
UTF-8
|
Python
| false | false | 2,013 |
12,421,045,467,195 |
dea71b5a015f3113fc8eda58f758a1994130696c
|
0fdfac03eeedbd12e1fe6f45ffa46c33c7a2c6ef
|
/module.py
|
386ba03a4db256c706b2eaf8c48a3e00c028e588
|
[] |
no_license
|
grockcharger/LXFpython
|
https://github.com/grockcharger/LXFpython
|
3c151bf9169f866034d21c70b3a71727ae9c32f4
|
5266ebee1ce14f5492d56fc5ef19ed3657f36d32
|
refs/heads/master
| 2020-03-26T05:56:26.813000 | 2014-07-24T14:21:46 | 2014-07-24T14:21:46 | null | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null |
#!/usr/bin/env python in Linux/OS X
# -*- coding: utf-8 -*-
# 模块的文档注释,任何模块代码的第一个字符串都被视为模块的文档注释;
'a test module'
# 作者是谁。。。
__auther__ = 'Michael Liao'
import sys
# argv至少有一个元素,因为第一个参数永远是该.py文件的名称
# 用list存储了命令行的所有参数
def test():
args = sys.argv
if len(args)==1:
print 'Hello World!'
elif len(args)==2:
print 'Hello, %s !' % args[1]
else:
print 'too many arguments!'
# 当我们在命令行运行hello模块文件时,
# Python解释器把一个特殊变量__name__置为__main__,
# 而如果在其他地方导入该hello模块时,if判断将失败,
# 因此,这种if测试可以让一个模块通过命令行运行时执行一些额外的代码
# 最常见的就是运行测试。
if __name__=='__main__':
test()
# 别名 ...as
try:
import cStringIO as cStringIO
except ImportError:
import StringIO
# 作用域
#内部函数的命名,不是无法被调用,但是习惯上这么写
def _private_1(name):
return 'Hello, %s' % name
def _private_2(name):
return 'Hi, %s' % name
#外部函数的命名,调用的时候用到的
def greeting(name):
if len(name) > 3:
return _private_1(name)
else:
return _private_2(name)
|
UTF-8
|
Python
| false | false | 2,014 |
12,592,844,162,318 |
0d7505ac320f91ee544c6e1f8773ba299f412eb4
|
52a7b47662d1cebbdbe82b1bc3128b0017bbfea2
|
/plugins/9_export_collada/mh2collada.py
|
a40e6a4c7ecb9f03cd8057534a8ed210803d1a5d
|
[
"CC0-1.0",
"GPL-1.0-or-later",
"LicenseRef-scancode-generic-exception",
"LicenseRef-scancode-unknown-license-reference",
"AGPL-3.0-or-later",
"AGPL-3.0-only"
] |
non_permissive
|
BlenderCN-Org/MakeHuman
|
https://github.com/BlenderCN-Org/MakeHuman
|
33380a7fbdfe9e2d45d111b3801f9b19a88da58e
|
108191b28abb493f3c7256747cf7b575e467d36a
|
refs/heads/master
| 2020-05-23T21:02:57.147000 | 2013-07-31T18:37:50 | 2013-07-31T18:37:50 | null | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null |
#!/usr/bin/python
# -*- coding: utf-8 -*-
"""
**Project Name:** MakeHuman
**Product Home Page:** http://www.makehuman.org/
**Code Home Page:** http://code.google.com/p/makehuman/
**Authors:** Thomas Larsson, Jonas Hauquier
**Copyright(c):** MakeHuman Team 2001-2013
**Licensing:** AGPL3 (see also http://www.makehuman.org/node/318)
**Coding Standards:** See http://www.makehuman.org/node/165
Abstract
--------
MakeHuman to Collada (MakeHuman eXchange format) exporter. Collada files can be loaded into
Blender by collada_import.py.
TODO
"""
import os.path
import time
import codecs
import math
import numpy as np
import transformations as tm
import log
import gui3d
import exportutils
import posemode
#
# Size of end bones = 1 mm
#
Delta = [0,0.01,0]
#
# exportCollada(human, filepath, config):
#
def exportCollada(human, filepath, config):
#posemode.exitPoseMode()
#posemode.enterPoseMode()
gui3d.app.progress(0, text="Preparing")
time1 = time.clock()
config.setHuman(human)
config.setupTexFolder(filepath)
filename = os.path.basename(filepath)
name = config.goodName(os.path.splitext(filename)[0])
rawTargets = exportutils.collect.readTargets(human, config)
rmeshes,amt = exportutils.collect.setupObjects(
name,
human,
config=config,
rawTargets = rawTargets,
helpers=config.helpers,
eyebrows=config.eyebrows,
lashes=config.lashes)
amt.calcBindMatrices()
gui3d.app.progress(0.5, text="Exporting %s" % filepath)
try:
fp = codecs.open(filepath, 'w', encoding="utf-8")
log.message("Writing Collada file %s" % filepath)
except:
log.error("Unable to open file for writing %s" % filepath)
date = time.strftime("%a, %d %b %Y %H:%M:%S +0000", time.localtime())
fp.write('<?xml version="1.0" encoding="utf-8"?>\n' +
'<COLLADA version="1.4.0" xmlns="http://www.collada.org/2005/11/COLLADASchema">\n' +
' <asset>\n' +
' <contributor>\n' +
' <author>www.makehuman.org</author>\n' +
' </contributor>\n' +
' <created>%s</created>\n' % date +
' <modified>%s</modified>\n' % date +
' <unit meter="1.0" name="meter"/>\n' +
' <up_axis>Y_UP</up_axis>\n' +
' </asset>\n' +
' <library_images>\n')
for rmesh in rmeshes:
writeImages(fp, rmesh, config)
fp.write(
' </library_images>\n' +
' <library_effects>\n')
gui3d.app.progress(0.1, text="Exporting effects")
for rmesh in rmeshes:
writeEffects(fp, rmesh)
fp.write(
' </library_effects>\n' +
' <library_materials>\n')
gui3d.app.progress(0.2, text="Exporting materials")
for rmesh in rmeshes:
writeMaterials(fp, rmesh)
fp.write(
' </library_materials>\n'+
' <library_controllers>\n')
gui3d.app.progress(0.3, text="Exporting controllers")
for rmesh in rmeshes:
writeController(fp, rmesh, amt, config)
fp.write(
' </library_controllers>\n'+
' <library_geometries>\n')
dt = 0.4/len(rmeshes)
t = 0.4
for rmesh in rmeshes:
gui3d.app.progress(t, text="Exporting %s" % rmesh.name)
t += dt
writeGeometry(fp, rmesh, config)
gui3d.app.progress(0.8, text="Exporting bones")
fp.write(
' </library_geometries>\n\n' +
' <library_visual_scenes>\n' +
' <visual_scene id="Scene" name="Scene">\n' +
' <node id="%s">\n' % name +
' <matrix sid="transform">\n')
if config.rotate90X:
mat = tm.rotation_matrix(-math.pi/2, (1,0,0))
else:
mat = np.identity(4, float)
if config.rotate90Z:
rotZ = tm.rotation_matrix(math.pi/2, (0,0,1))
mat = np.dot(mat, rotZ)
for i in range(4):
fp.write(' %.4f %.4f %.4f %.4f\n' % (mat[i][0], mat[i][1], mat[i][2], mat[i][3]))
fp.write(' </matrix>\n')
for root in amt.hierarchy:
writeBone(fp, root, [0,0,0], 'layer="L1"', ' ', amt, config)
gui3d.app.progress(0.9, text="Exporting nodes")
for rmesh in rmeshes:
writeNode(fp, " ", rmesh, amt, config)
fp.write(
' </node>\n' +
' </visual_scene>\n' +
' </library_visual_scenes>\n' +
' <scene>\n' +
' <instance_visual_scene url="#Scene"/>\n' +
' </scene>\n' +
'</COLLADA>\n')
fp.close()
time2 = time.clock()
log.message("Wrote Collada file in %g s: %s" % (time2-time1, filepath))
gui3d.app.progress(1)
#posemode.exitPoseMode()
return
#
# Write images
#
def writeImages(fp, rmesh, config):
mat = rmesh.material
if mat.diffuseTexture:
writeImage(fp, mat.diffuseTexture, config)
if mat.specularMapTexture:
writeImage(fp, mat.specularMapTexture, config)
if mat.bumpMapTexture:
writeImage(fp, mat.bumpMapTexture, config)
if mat.normalMapTexture:
writeImage(fp, mat.normalMapTexture, config)
if mat.displacementMapTexture:
writeImage(fp, mat.displacementMapTexture, config)
def getTextureName(filepath):
texfile = os.path.basename(filepath)
return texfile.replace(".","_")
def writeImage(fp, filepath, config):
if not filepath:
return
newpath = config.copyTextureToNewLocation(filepath)
print(("Collada Image", filepath, newpath))
texname = getTextureName(filepath)
fp.write(
' <image id="%s" name="%s">\n' % (texname, texname) +
' <init_from>%s</init_from>\n' % newpath +
' </image>\n'
)
#
# writeEffects(fp, rmesh):
#
def writeIntensity(fp, tech, intensity):
fp.write(' <%s><float>%s</float></%s>\n' % (tech, intensity, tech))
def writeTexture(fp, tech, filepath, color, intensity, s=1.0):
if not filepath:
return
fp.write(' <%s>\n' % tech)
if color:
fp.write(' <color>%.4f %.4f %.4f 1</color> \n' % (s*color.r, s*color.g, s*color.b))
if intensity:
fp.write(' <float>%s</float>\n' % intensity)
texname = getTextureName(filepath)
fp.write(
' <texture texture="%s-sampler" texcoord="UVTex"/>\n' % texname +
' </%s>\n' % tech)
def writeEffects(fp, rmesh):
mat = rmesh.material
fp.write(
' <effect id="%s-effect">\n' % mat.name.replace(" ", "_") +
' <profile_COMMON>\n')
writeSurfaceSampler(fp, mat.diffuseTexture)
writeSurfaceSampler(fp, mat.specularMapTexture)
writeSurfaceSampler(fp, mat.normalMapTexture)
writeSurfaceSampler(fp, mat.bumpMapTexture)
writeSurfaceSampler(fp, mat.displacementMapTexture)
fp.write(
' <technique sid="common">\n' +
' <phong>\n')
writeTexture(fp, 'diffuse', mat.diffuseTexture, mat.diffuseColor, mat.diffuseIntensity)
writeTexture(fp, 'transparency', mat.diffuseTexture, None, mat.transparencyIntensity)
writeTexture(fp, 'specular', mat.specularMapTexture, mat.specularColor, 0.1*mat.specularIntensity)
writeIntensity(fp, 'shininess', mat.specularHardness)
writeTexture(fp, 'normal', mat.normalMapTexture, None, mat.normalMapIntensity)
writeTexture(fp, 'bump', mat.bumpMapTexture, None, mat.bumpMapIntensity)
writeTexture(fp, 'displacement', mat.displacementMapTexture, None, mat.displacementMapIntensity)
fp.write(
' </phong>\n' +
' <extra/>\n' +
' </technique>\n' +
' <extra>\n' +
' <technique profile="GOOGLEEARTH">\n' +
' <show_double_sided>1</show_double_sided>\n' +
' </technique>\n' +
' </extra>\n' +
' </profile_COMMON>\n' +
' <extra><technique profile="MAX3D"><double_sided>1</double_sided></technique></extra>\n' +
' </effect>\n')
def writeSurfaceSampler(fp, filepath):
if not filepath:
return
texname = getTextureName(filepath)
fp.write(
' <newparam sid="%s-surface">\n' % texname +
' <surface type="2D">\n' +
' <init_from>%s</init_from>\n' % texname +
' </surface>\n' +
' </newparam>\n' +
' <newparam sid="%s-sampler">\n' % texname +
' <sampler2D>\n' +
' <source>%s-surface</source>\n' % texname +
' </sampler2D>\n' +
' </newparam>\n')
#
# writeMaterials(fp, rmesh):
#
def writeMaterials(fp, rmesh):
mat = rmesh.material
matname = mat.name.replace(" ", "_")
fp.write(
' <material id="%s" name="%s">\n' % (matname, matname) +
' <instance_effect url="#%s-effect"/>\n' % matname +
' </material>\n')
def writeController(fp, rmesh, amt, config):
obj = rmesh.object
rmesh.calculateSkinWeights(amt)
nVerts = len(obj.coord)
nUvVerts = len(obj.texco)
nFaces = len(obj.fvert)
nWeights = len(rmesh.skinWeights)
nBones = len(amt.bones)
nShapes = len(rmesh.shapes)
fp.write('\n' +
' <controller id="%s-skin">\n' % rmesh.name +
' <skin source="#%sMesh">\n' % rmesh.name +
' <bind_shape_matrix>\n' +
' 1 0 0 0 \n' +
' 0 0 -1 0 \n' +
' 0 1 0 0 \n' +
' 0 0 0 1 \n' +
' </bind_shape_matrix>\n' +
' <source id="%s-skin-joints">\n' % rmesh.name +
' <IDREF_array count="%d" id="%s-skin-joints-array">\n' % (nBones,rmesh.name) +
' ')
for bone in list(amt.bones.values()):
fp.write(' %s' % bone.name)
fp.write('\n' +
' </IDREF_array>\n' +
' <technique_common>\n' +
' <accessor count="%d" source="#%s-skin-joints-array" stride="1">\n' % (nBones,rmesh.name) +
' <param type="IDREF" name="JOINT"></param>\n' +
' </accessor>\n' +
' </technique_common>\n' +
' </source>\n' +
' <source id="%s-skin-weights">\n' % rmesh.name +
' <float_array count="%d" id="%s-skin-weights-array">\n' % (nWeights,rmesh.name) +
' ')
for w in rmesh.skinWeights:
fp.write(' %s' % w[1])
fp.write('\n' +
' </float_array>\n' +
' <technique_common>\n' +
' <accessor count="%d" source="#%s-skin-weights-array" stride="1">\n' % (nWeights,rmesh.name) +
' <param type="float" name="WEIGHT"></param>\n' +
' </accessor>\n' +
' </technique_common>\n' +
' </source>\n' +
' <source id="%s-skin-poses">\n' % rmesh.name +
' <float_array count="%d" id="%s-skin-poses-array">' % (16*nBones,rmesh.name))
"""
mat = [[1,0,0,0],[0,1,0,0],[0,0,1,0],[0,0,0,1]]
for bone in amt.bones.values():
(x,y,z) = rotateLoc(bone.head, config)
mat[0][3] = -x
mat[1][3] = -y
mat[2][3] = -z
fp.write('\n ')
for i in range(4):
for j in range(4):
fp.write('%.4f ' % mat[i][j])
"""
for bone in list(amt.bones.values()):
#bone.calcBindMatrix()
mat = bone.bindMatrix
mat = bone.getBindMatrixCollada()
for i in range(4):
fp.write('\n ')
for j in range(4):
fp.write(' %.4f' % mat[i,j])
fp.write('\n')
fp.write('\n' +
' </float_array>\n' +
' <technique_common>\n' +
' <accessor count="%d" source="#%s-skin-poses-array" stride="16">\n' % (nBones,rmesh.name) +
' <param type="float4x4"></param>\n' +
' </accessor>\n' +
' </technique_common>\n' +
' </source>\n' +
' <joints>\n' +
' <input semantic="JOINT" source="#%s-skin-joints"/>\n' % rmesh.name +
' <input semantic="INV_BIND_MATRIX" source="#%s-skin-poses"/>\n' % rmesh.name +
' </joints>\n' +
' <vertex_weights count="%d">\n' % nVerts +
' <input offset="0" semantic="JOINT" source="#%s-skin-joints"/>\n' % rmesh.name +
' <input offset="1" semantic="WEIGHT" source="#%s-skin-weights"/>\n' % rmesh.name +
' <vcount>\n' +
' ')
for wts in rmesh.vertexWeights:
fp.write('%d ' % len(wts))
fp.write('\n' +
' </vcount>\n'
' <v>\n' +
' ')
for wts in rmesh.vertexWeights:
for pair in wts:
fp.write(' %d %d' % pair)
fp.write('\n' +
' </v>\n' +
' </vertex_weights>\n' +
' </skin>\n' +
' </controller>\n')
# Morph controller
if rmesh.shapes:
nShapes = len(rmesh.shapes)
fp.write(
' <controller id="%sMorph" name="%sMorph">\n' % (rmesh.name, rmesh.name)+
' <morph source="#%sMesh" method="NORMALIZED">\n' % (rmesh.name) +
' <source id="%sTargets">\n' % (rmesh.name) +
' <IDREF_array id="%sTargets-array" count="%d">' % (rmesh.name, nShapes))
for key,_ in rmesh.shapes:
fp.write(" %sMeshMorph_%s" % (rmesh.name, key))
fp.write(
' </IDREF_array>\n' +
' <technique_common>\n' +
' <accessor source="#%sTargets-array" count="%d" stride="1">\n' % (rmesh.name, nShapes) +
' <param name="IDREF" type="IDREF"/>\n' +
' </accessor>\n' +
' </technique_common>\n' +
' </source>\n' +
' <source id="%sWeights">\n' % (rmesh.name) +
' <float_array id="%sWeights-array" count="%d">' % (rmesh.name, nShapes))
fp.write(nShapes*" 0")
fp.write('\n' +
' </float_array>\n' +
' <technique_common>\n' +
' <accessor source="#%sWeights-array" count="%d" stride="1">\n' % (rmesh.name, nShapes) +
' <param name="MORPH_WEIGHT" type="float"/>\n' +
' </accessor>\n' +
' </technique_common>\n' +
' </source>\n' +
' <targets>\n' +
' <input semantic="MORPH_TARGET" source="#%sTargets"/>\n' % (rmesh.name) +
' <input semantic="MORPH_WEIGHT" source="#%sWeights"/>\n' % (rmesh.name) +
' </targets>\n' +
' </morph>\n' +
' </controller>\n')
#
# writeGeometry(fp, rmesh, config):
#
def writeGeometry(fp, rmesh, config):
obj = rmesh.object
nVerts = len(obj.coord)
nUvVerts = len(obj.texco)
nWeights = len(rmesh.skinWeights)
nShapes = len(rmesh.shapes)
fp.write('\n' +
' <geometry id="%sMesh" name="%s">\n' % (rmesh.name,rmesh.name) +
' <mesh>\n' +
' <source id="%s-Position">\n' % rmesh.name +
' <float_array count="%d" id="%s-Position-array">\n' % (3*nVerts,rmesh.name) +
' ')
for co in obj.coord:
(x,y,z) = rotateLoc(co, config)
fp.write("%.4f %.4f %.4f " % (x,y,z))
fp.write('\n' +
' </float_array>\n' +
' <technique_common>\n' +
' <accessor count="%d" source="#%s-Position-array" stride="3">\n' % (nVerts,rmesh.name) +
' <param type="float" name="X"></param>\n' +
' <param type="float" name="Y"></param>\n' +
' <param type="float" name="Z"></param>\n' +
' </accessor>\n' +
' </technique_common>\n' +
' </source>\n')
# Normals
if config.useNormals:
obj.calcFaceNormals()
nNormals = len(obj.fnorm)
fp.write(
' <source id="%s-Normals">\n' % rmesh.name +
' <float_array count="%d" id="%s-Normals-array">\n' % (3*nNormals,rmesh.name) +
' ')
for no in obj.fnorm:
(x,y,z) = rotateLoc(no, config)
fp.write("%.4f %.4f %.4f " % (x,y,z))
fp.write('\n' +
' </float_array>\n' +
' <technique_common>\n' +
' <accessor count="%d" source="#%s-Normals-array" stride="3">\n' % (nNormals,rmesh.name) +
' <param type="float" name="X"></param>\n' +
' <param type="float" name="Y"></param>\n' +
' <param type="float" name="Z"></param>\n' +
' </accessor>\n' +
' </technique_common>\n' +
' </source>\n')
# UV coordinates
fp.write(
' <source id="%s-UV">\n' % rmesh.name +
' <float_array count="%d" id="%s-UV-array">\n' % (2*nUvVerts,rmesh.name) +
' ')
for uv in obj.texco:
fp.write(" %.4f %.4f" % tuple(uv))
fp.write('\n' +
' </float_array>\n' +
' <technique_common>\n' +
' <accessor count="%d" source="#%s-UV-array" stride="2">\n' % (nUvVerts,rmesh.name) +
' <param type="float" name="S"></param>\n' +
' <param type="float" name="T"></param>\n' +
' </accessor>\n' +
' </technique_common>\n' +
' </source>\n')
# Faces
fp.write(
' <vertices id="%s-Vertex">\n' % rmesh.name +
' <input semantic="POSITION" source="#%s-Position"/>\n' % rmesh.name +
' </vertices>\n')
checkFaces(rmesh, nVerts, nUvVerts)
#writePolygons(fp, rmesh, config)
writePolylist(fp, rmesh, config)
fp.write(
' </mesh>\n' +
' </geometry>\n')
for name,shape in rmesh.shapes:
writeShapeKey(fp, name, shape, rmesh, config)
return
def writeShapeKey(fp, name, shape, rmesh, config):
obj = rmesh.object
nVerts = len(obj.coord)
# Verts
fp.write(
' <geometry id="%sMeshMorph_%s" name="%s">\n' % (rmesh.name, name, name) +
' <mesh>\n' +
' <source id="%sMeshMorph_%s-positions">\n' % (rmesh.name, name) +
' <float_array id="%sMeshMorph_%s-positions-array" count="%d">\n' % (rmesh.name, name, 3*nVerts) +
' ')
target = np.array(obj.coord)
for n,dr in list(shape.items()):
target[n] += np.array(dr)
for co in target:
loc = rotateLoc(co, config)
fp.write(" %.4g %.4g %.4g" % tuple(loc))
fp.write('\n' +
' </float_array>\n' +
' <technique_common>\n' +
' <accessor source="#%sMeshMorph_%s-positions-array" count="%d" stride="3">\n' % (rmesh.name, name, nVerts) +
' <param name="X" type="float"/>\n' +
' <param name="Y" type="float"/>\n' +
' <param name="Z" type="float"/>\n' +
' </accessor>\n' +
' </technique_common>\n' +
' </source>\n')
# Normals
"""
fp.write(
' <source id="%sMeshMorph_%s-normals">\n' % (rmesh.name, name) +
' <float_array id="%sMeshMorph_%s-normals-array" count="18">\n' % (rmesh.name, name))
-0.9438583 0 0.3303504 0 0.9438583 0.3303504 0.9438583 0 0.3303504 0 -0.9438583 0.3303504 0 0 -1 0 0 1
fp.write(
' </float_array>\n' +
' <technique_common>\n' +
' <accessor source="#%sMeshMorph_%s-normals-array" count="6" stride="3">\n' % (rmesh.name, name) +
' <param name="X" type="float"/>\n' +
' <param name="Y" type="float"/>\n' +
' <param name="Z" type="float"/>\n' +
' </accessor>\n' +
' </technique_common>\n' +
' </source>\n')
"""
# Polylist
fp.write(
' <vertices id="%sMeshMorph_%s-vertices">\n' % (rmesh.name, name) +
' <input semantic="POSITION" source="#%sMeshMorph_%s-positions"/>\n' % (rmesh.name, name) +
' </vertices>\n' +
' <polylist count="%d">\n' % len(obj.fvert) +
' <input semantic="VERTEX" source="#%sMeshMorph_%s-vertices" offset="0"/>\n' % (rmesh.name, name) +
#' <input semantic="NORMAL" source="#%sMeshMorph_%s-normals" offset="1"/>\n' % (rmesh.name, name) +
' <vcount>')
for fv in obj.fvert:
if fv[0] == fv[3]:
fp.write("3 ")
else:
fp.write("4 ")
fp.write('\n' +
' </vcount>\n' +
' <p>')
for fv in obj.fvert:
if fv[0] == fv[3]:
fp.write("%d %d %d " % (fv[0], fv[1], fv[2]))
else:
fp.write("%d %d %d %s " % (fv[0], fv[1], fv[2], fv[3]))
fp.write('\n' +
' </p>\n' +
' </polylist>\n' +
' </mesh>\n' +
' </geometry>\n')
#
# writePolygons(fp, rmesh, config):
# writePolylist(fp, rmesh, config):
#
def writePolygons(fp, rmesh, config):
obj = rmesh.object
fp.write(
' <polygons count="%d">\n' % len(obj.fvert) +
' <input offset="0" semantic="VERTEX" source="#%s-Vertex"/>\n' % rmesh.name +
' <input offset="1" semantic="NORMAL" source="#%s-Normals"/>\n' % rmesh.name +
' <input offset="2" semantic="TEXCOORD" source="#%s-UV"/>\n' % rmesh.name)
for fn,fverts in enumerate(obj.fvert):
fuv = obj.fuvs[fn]
fp.write(' <p>')
for n,vn in enumerate(fverts):
fp.write("%d %d %d " % (vn, vn, fuv[n]))
fp.write('</p>\n')
fp.write('\n' +
' </polygons>\n')
return
def writePolylist(fp, rmesh, config):
obj = rmesh.object
fp.write(
' <polylist count="%d">\n' % len(obj.fvert) +
' <input offset="0" semantic="VERTEX" source="#%s-Vertex"/>\n' % rmesh.name)
if config.useNormals:
fp.write(
' <input offset="1" semantic="NORMAL" source="#%s-Normals"/>\n' % rmesh.name +
' <input offset="2" semantic="TEXCOORD" source="#%s-UV"/>\n' % rmesh.name +
' <vcount>')
else:
fp.write(
' <input offset="1" semantic="TEXCOORD" source="#%s-UV"/>\n' % rmesh.name +
' <vcount>')
for fv in obj.fvert:
if fv[0] == fv[3]:
fp.write('3 ')
else:
fp.write('4 ')
fp.write('\n' +
' </vcount>\n'
' <p>')
for fn,fv in enumerate(obj.fvert):
fuv = obj.fuvs[fn]
if fv[0] == fv[3]:
nverts = 3
else:
nverts = 4
if config.useNormals:
for n in range(nverts):
fp.write("%d %d %d " % (fv[n], fn, fuv[n]))
else:
for n in range(nverts):
fp.write("%d %d " % (fv[n], fuv[n]))
fp.write(
' </p>\n' +
' </polylist>\n')
return
#
# checkFaces(rmesh, nVerts, nUvVerts):
#
def checkFaces(rmesh, nVerts, nUvVerts):
obj = rmesh.object
for fn,fverts in enumerate(obj.fvert):
for n,vn in enumerate(fverts):
uv = obj.fuvs[fn][n]
if vn > nVerts:
raise NameError("v %d > %d" % (vn, nVerts))
if uv > nUvVerts:
raise NameError("uv %d > %d" % (uv, nUvVerts))
return
def writeNode(fp, pad, rmesh, amt, config):
fp.write('\n' +
'%s<node id="%sObject" name="%s">\n' % (pad, rmesh.name,rmesh.name) +
'%s <matrix sid="transform">\n' % pad +
'%s 1 0 0 0\n' % pad +
'%s 0 1 0 0\n' % pad +
'%s 0 0 1 0\n' % pad +
'%s 0 0 0 1\n' % pad +
'%s </matrix>\n' % pad +
'%s <instance_controller url="#%s-skin">\n' % (pad, rmesh.name) +
'%s <skeleton>#%sSkeleton</skeleton>\n' % (pad, amt.roots[0].name))
mat = rmesh.material
matname = mat.name.replace(" ", "_")
fp.write(
'%s <bind_material>\n' % pad +
'%s <technique_common>\n' % pad +
'%s <instance_material symbol="%s" target="#%s">\n' % (pad, matname, matname) +
'%s <bind_vertex_input semantic="UVTex" input_semantic="TEXCOORD" input_set="0"/>\n' % pad +
'%s </instance_material>\n' % pad +
'%s </technique_common>\n' % pad +
'%s </bind_material>\n' % pad)
fp.write(
'%s </instance_controller>\n' % pad +
'%s</node>\n' % pad)
return
def rotateLoc(loc, config):
return loc
(x,y,z) = loc
if config.rotate90X:
yy = -z
z = y
y = yy
if config.rotate90Z:
yy = x
x = -y
y = yy
return (x,y,z)
def writeBone(fp, hier, orig, extra, pad, amt, config):
(bone, children) = hier
if bone:
nameStr = 'sid="%s"' % bone.name
idStr = 'id="%s" name="%s"' % (bone.name, bone.name)
else:
nameStr = ''
idStr = ''
fp.write(
'%s <node %s %s type="JOINT" %s>\n' % (pad, extra, nameStr, idStr) +
'%s <matrix sid="transform">\n' % pad)
mat = bone.matrixRelative
for i in range(4):
fp.write('%s %.5f %.5f %.5f %.5f\n' % (pad, mat[i][0], mat[i][1], mat[i][2], mat[i][3]))
fp.write('%s </matrix>\n' % pad)
for child in children:
writeBone(fp, child, bone.head, '', pad+' ', amt, config)
fp.write('%s </node>\n' % pad)
return
|
UTF-8
|
Python
| false | false | 2,013 |
12,326,556,156,458 |
109bc3239e86dd587c145b6a630dfe79514148ed
|
32ef4eb01a0422c60357ec54a9dc705f273238d2
|
/knuth/Exer-1-1.py
|
2cf2fc46559dcc1a2b08b643c08ecd8082800e3c
|
[] |
no_license
|
nagrajan/recre
|
https://github.com/nagrajan/recre
|
2a054965cc01138e6f5ee354b481e75f9d9dedbb
|
70be4cc88f8e211cd73dba743aedc11db4ea1449
|
refs/heads/master
| 2021-01-10T19:46:50.106000 | 2013-05-28T16:23:36 | 2013-05-28T16:23:36 | null | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null |
# solutions to problems in
# Art of Computer Programming - Knuth
__author__ = 'nagarajan'
def solve1(abcd):
t = abcd[0]
for idx1 in range(len(abcd)-1):
abcd[idx1] = abcd[idx1 + 1]
abcd[-1] = t
return abcd
def solve4(a, b):
def gcd(a, b):
if b == 0:
return a
return gcd(b, a%b)
return gcd(a, b)
def solve6(n=5, nExp=1000):
"""
The theoretical solution is 2.6
"""
opCount = [0]
def gcd(a, b):
if b == 0:
return a
opCount[0] += 1
return gcd(b, a%b)
totalOps = 0
for m in range(1, nExp):
opCount[0] = 0
gcd(m, n)
totalOps += opCount[0]
return totalOps/float(nExp)
if __name__ == "__main__":
print "Solution 1 returns : %s"%(solve1([1,2,3,4]))
print "Solution 4 returns : %s"%(solve4(2166, 6099))
print "Solution 6 returns : %s"%(solve6(5, 10000))
|
UTF-8
|
Python
| false | false | 2,013 |
5,325,759,494,852 |
48f3de00acf66ba918a18cf1fb94b3ede570b867
|
bbd37dd2fdad2db524576254b075c43d11fd932f
|
/src/geometry.py
|
4e2517b70dec1bc635f09de7dcdb47242df6eeb7
|
[] |
no_license
|
ariaBennett/python_geometry
|
https://github.com/ariaBennett/python_geometry
|
65febb220d96bb4d1578bad1b112ec75b94b5cb1
|
88947e8309610b4ec72c2110be80c71bcfa55c9d
|
refs/heads/master
| 2021-01-23T07:34:39.173000 | 2013-02-05T22:39:33 | 2013-02-05T22:39:33 | null | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null |
'''
Created on Feb 1, 2013
@author: Aria
'''
import math
import copy
#===============================================================================
# Class Point
#
# Defines the Point class which consists of two values
# representing an x and y coordinate.
#===============================================================================
class Point():
def __init__(self, point_x, point_y):
self.x = point_x
self.y = point_y
#===============================================================================
# Class Rectangle
#
# Defines the Rectangle class which consists of one point
# value, and two additional values defining the width and height
# of the rectangle from the point origin in the lower left corner
#===============================================================================
class Rectangle():
def __init__(self, corner, width, height):
self.corner = corner
self.width = width
self.height = height
#===============================================================================
# Function move_rectangle
#
# Takes one rectangle and two numeric values representing
# new x and y coordinates for the rectangles corner Point object
#===============================================================================
def move_rectangle(rect, x, y):
rect.corner.x = x
rect.corner.y = y
#===============================================================================
# Function move_new_rectangle
#
# Takes one rectangle and two numeric values representing
# x and y coordinates for the rectangles corner Point object
# and returns a new rectangle with provided coordinates
#===============================================================================
def move_new_rectangle(rect, x, y):
rect = copy.deepcopy(rect)
rect.corner.x = x
rect.corner.y = y
return rect
#===============================================================================
# Function distance_between_points
#
# Takes two Point objects and returns a tuple containing
# the absolute value distance between each
#===============================================================================
def distance_between_points(point_a, point_b):
return (find_difference(point_a.x, point_b.x), find_difference(point_a.y, point_b.y))
#===============================================================================
# Function find_difference
#
# Takes the x or y coordinates of two points,
# compares them, and returns the absolute value
# difference between them.
#===============================================================================
def find_difference(point_x, point_y):
point_x = math.fabs(point_x)
point_y = math.fabs(point_y)
if point_x > point_y:
return point_x - point_y
elif point_y > point_x:
return point_y - point_x
else:
return 0;
#===============================================================================
# Main
#===============================================================================
some_point_a = Point(10, 15)
some_point_b = Point(15, 25)
print "some_point_a = Point(10, 15) "
print "some_point_b = Point(15, 25)"
print "distance_between_points(some_point_a, some_point_b)"
print distance_between_points(some_point_a, some_point_b)
print ""
some_rectangle_a = Rectangle(some_point_a, 10, 20)
print "some_rectangle_a = Rectangle(some_point_a, 10, 20)"
print "some_rectangle_a.corner.x"
print some_rectangle_a.corner.x
print "some_rectangle_a.corner.y"
print some_rectangle_a.corner.y
print "some_rectangle_a.width"
print some_rectangle_a.width
print "some_rectangle_a.height"
print some_rectangle_a.height
print ""
move_rectangle(some_rectangle_a, 20, 40)
print "move_rectangle(some_rectangle_a, 20, 40)"
print "some_rectangle_a.corner.x"
print some_rectangle_a.corner.x
print "some_rectangle_a.corner.y"
print some_rectangle_a.corner.y
print ""
some_rectangle_b = move_new_rectangle(some_rectangle_a, 100, 100)
print "some_rectangle_b = move_new_rectangle(some_rectangle_a, 100, 100)"
print "some_rectangle_a.corner.x"
print some_rectangle_a.corner.x
print "some_rectangle_a.corner.y"
print some_rectangle_a.corner.y
print "some_rectangle_b.corner.x"
print some_rectangle_b.corner.x
print "some_rectangle_b.corner.y"
print some_rectangle_b.corner.y
print ""
|
UTF-8
|
Python
| false | false | 2,013 |
11,055,245,864,136 |
0654850a0209d0f2d3e100fb48923ddcb5fbace2
|
beb099fd2b56fbfa598c51af06a2b7047965cc21
|
/tackaholic/pinry/core/feeds.py
|
2bdb8df588c7b3dee67cc542011d08fa0dabfe76
|
[
"BSD-2-Clause"
] |
permissive
|
farcryzry/CMPE203-Group1
|
https://github.com/farcryzry/CMPE203-Group1
|
2c7a76a49e735189e251f6874f33043288c424d1
|
3ab5c1bc1410a4eecd1634a632f22ac8addaf9cf
|
refs/heads/master
| 2020-05-20T03:41:00.659000 | 2014-09-26T06:54:45 | 2014-09-26T06:54:45 | 13,978,403 | 1 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null |
from __future__ import unicode_literals
from django.contrib.syndication.views import Feed
from django.contrib.sites.models import get_current_site
from django.shortcuts import get_object_or_404
from django.contrib.auth.models import User
from django_images.models import Thumbnail
from taggit.models import Tag
from .models import Tack
def filter_generator_for(size):
def wrapped_func(obj):
return Thumbnail.objects.get_or_create_at_size(obj.pk, size)
return wrapped_func
class LatestTacks(Feed):
title = 'Latest Tacks'
link = '/'
description = 'The latest tacks from around the internet.'
domain_name = None
item_enclosure_mime_type = 'image/jpeg'
def get_object(self, request):
"""
Doing this as a fix for Django's not including the domain name in
enclosure urls.
"""
try:
request_type = 'http'
if request.is_secure(): request_type = 'https'
self.domain_name = ''.join([request_type, '://',
get_current_site(request).domain])
except:
pass
def items(self):
return Tack.objects.order_by('-published')[:15]
def item_pubdate(self, item):
return item.published
def item_link(self, item):
return item.url
def item_title(self, item):
return item.url
def item_description(self, item):
tags = ', '.join(tag.name for tag in item.tags.all())
return ''.join(['Description: ', item.description or 'None',
' | Tags: ', tags or 'None'])
def item_enclosure_url(self, item):
slug = unicode(filter_generator_for('standard')(item.image).image.url)
return self.domain_name + slug
def item_enclosure_length(self, item):
return filter_generator_for('standard')(item.image).image.size
class LatestUserTacks(Feed):
description = 'The latest tacks from around the internet.'
domain_name = None
item_enclosure_mime_type = 'image/jpeg'
def get_object(self, request, user):
"""
Doing this as a fix for Django's not including the domain name in
enclosure urls.
"""
request_type = 'http'
if request.is_secure(): request_type = 'https'
self.domain_name = ''.join([request_type, '://',
get_current_site(request).domain])
return get_object_or_404(User, username=user)
def title(self, obj):
return 'Latest Tacks from ' + obj.username
def link(self, obj):
return '/tacks/user/' + obj.username + '/'
def items(self, obj):
return Tack.objects.filter(submitter=obj).order_by('-published')[:15]
def item_pubdate(self, item):
return item.published
def item_link(self, item):
return item.url
def item_title(self, item):
return item.url
def item_description(self, item):
tags = ', '.join(tag.name for tag in item.tags.all())
return ''.join(['Description: ', item.description or 'None',
' | Tags: ', tags or 'None'])
def item_enclosure_url(self, item):
slug = unicode(filter_generator_for('standard')(item.image).image.url)
return self.domain_name + slug
def item_enclosure_length(self, item):
return filter_generator_for('standard')(item.image).image.size
class LatestTagTacks(Feed):
link = '/'
description = 'The latest tacks from around the internet.'
domain_name = None
item_enclosure_mime_type = 'image/jpeg'
def get_object(self, request, tag):
"""
Doing this as a fix for Django's not including the domain name in
enclosure urls.
"""
request_type = 'http'
if request.is_secure(): request_type = 'https'
self.domain_name = ''.join([request_type, '://',
get_current_site(request).domain])
return get_object_or_404(Tag, name=tag)
def title(self, obj):
return 'Latest Tacks in ' + obj.name
def link(self, obj):
return '/tacks/tag/' + obj.name + '/'
def items(self, obj):
return Tack.objects.filter(tags=obj).order_by('-published')[:15]
def item_pubdate(self, item):
return item.published
def item_link(self, item):
return item.url
def item_title(self, item):
return item.url
def item_description(self, item):
tags = ', '.join(tag.name for tag in item.tags.all())
return ''.join(['Description: ', item.description or 'None',
' | Tags: ', tags or 'None'])
def item_enclosure_url(self, item):
slug = unicode(filter_generator_for('standard')(item.image).image.url)
return self.domain_name + slug
def item_enclosure_length(self, item):
return filter_generator_for('standard')(item.image).image.size
|
UTF-8
|
Python
| false | false | 2,014 |
8,117,488,202,910 |
eee4408ca078af1515a046eff3d9576d43d0be1a
|
505931fc1f7f0403e76a671bc4a37e2d79284eb2
|
/hw2_Birch-Tamarack-Linux.py
|
2d870863f3c46163f8de641e829677ab474f7842
|
[] |
no_license
|
twheeles/cs_161
|
https://github.com/twheeles/cs_161
|
5df051350c76b21b0392d17facf4ea23d3f7d454
|
cd10efa2cd4dd087fcce29b3644c024f6d7037ee
|
refs/heads/master
| 2016-09-06T05:52:56.763000 | 2013-06-16T06:47:49 | 2013-06-16T06:47:49 | null | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null |
# Copyright © 2013 Tamarack Birch
# Homework Assignment 2
bottle_count = int(input("How many bottles are there? "))
if (bottle_count > 99):
print ("ALERT: No more than 99 bottles allowed, reverting to 99 bottles")
bottle_count = 99
while (bottle_count > 0):
if (bottle_count > 1):
print (str(bottle_count) + " bottles of pop on the wall, " + str(bottle_count) + " bottles of pop")
else:
print (str(bottle_count) + " bottle of pop on the wall, " + str(bottle_count) + " bottle of pop")
bottle_count -= 1
if (bottle_count > 1):
print ("\t" + "take one down, pass it around, " + str(bottle_count) + " bottles of pop on the wall")
elif (bottle_count == 1):
print ("\t" + "take one down, pass it around, " + str(bottle_count) + " bottle of pop on the wall")
else:
print ("\t" + "take one down, pass it around, no bottles of pop on the wall")
|
UTF-8
|
Python
| false | false | 2,013 |
12,403,865,582,156 |
57d70ecd44c109a462533e880a6e3966595a5397
|
9acfe8ea905a7613b232cf9e512311289d4e5e27
|
/respublicaminerva/auth/templatetags/authtags.py
|
e4160ffbd8ff128170f8395f0a93efbd3a33e119
|
[] |
no_license
|
antofik/Python
|
https://github.com/antofik/Python
|
e790ecb61babb23fad198ba996f24b31fdff9f39
|
bb6ab6cd87d7bfb1d6efca6623b4b00c387313a8
|
refs/heads/master
| 2020-12-24T14:27:39.341000 | 2014-03-09T07:32:07 | 2014-03-09T07:32:07 | 17,551,107 | 1 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null |
from django import template
from django.template import Template, RequestContext
from django.template.loader import get_template
register = template.Library()
@register.tag
def login_control(parser, token):
return LoginControlNode()
class LoginControlNode(template.Node):
def render(self, context):
t = get_template('login_control.html')
html = t.render(context)
return html
|
UTF-8
|
Python
| false | false | 2,014 |
5,798,205,861,666 |
10ca73551a88ae6bf4baa528585ca42415124cca
|
a2844699937ce623c6df0aecd4dd81dbb779c6dc
|
/abjad/tools/pitchtools/test/test_pitchtools_PitchRangeInventory_name.py
|
9b38042fa800ceeb0f9b576a96c0e81edab579d2
|
[
"GPL-3.0-or-later",
"LGPL-2.0-or-later",
"GPL-1.0-or-later",
"LicenseRef-scancode-warranty-disclaimer",
"GPL-3.0-only",
"LGPL-2.1-or-later",
"AGPL-3.0-or-later",
"LicenseRef-scancode-other-copyleft",
"LicenseRef-scancode-unknown-license-reference"
] |
non_permissive
|
jonathanmarmor/abjad
|
https://github.com/jonathanmarmor/abjad
|
a50002b27230853306f06a37c6bfb5b0bebe4d8c
|
cb1ead2e75b65e622cec957083da3abd4959c726
|
refs/heads/master
| 2021-01-21T09:06:25.498000 | 2014-02-15T22:43:40 | 2014-02-15T22:43:40 | null | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null |
# -*- encoding: utf-8 -*-
import pytest
from abjad import *
def test_pitchtools_PitchRangeInventory_name_01():
inventory = pitchtools.PitchRangeInventory(['[A0, C8]'])
assert inventory.custom_identifier is None
inventory.custom_identifier = 'blue inventory'
assert inventory.custom_identifier == 'blue inventory'
def test_pitchtools_PitchRangeInventory_name_02():
inventory = pitchtools.PitchRangeInventory(['[A0, C8]'])
assert pytest.raises(Exception, 'inventory.custom_identifier = 99')
|
UTF-8
|
Python
| false | false | 2,014 |
End of preview. Expand
in Data Studio
- Downloads last month
- 5