__id__
int64 3.09k
19,722B
| blob_id
stringlengths 40
40
| directory_id
stringlengths 40
40
| path
stringlengths 2
256
| content_id
stringlengths 40
40
| detected_licenses
list | license_type
stringclasses 3
values | repo_name
stringlengths 5
109
| repo_url
stringlengths 24
128
| snapshot_id
stringlengths 40
40
| revision_id
stringlengths 40
40
| branch_name
stringlengths 4
42
| visit_date
timestamp[ns] | revision_date
timestamp[ns] | committer_date
timestamp[ns] | github_id
int64 6.65k
581M
⌀ | star_events_count
int64 0
1.17k
| fork_events_count
int64 0
154
| gha_license_id
stringclasses 16
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
407
⌀ | gha_forks_count
int32 0
119
⌀ | gha_open_issues_count
int32 0
640
⌀ | gha_language
stringlengths 1
16
⌀ | gha_archived
bool 2
classes | gha_disabled
bool 1
class | content
stringlengths 9
4.53M
| src_encoding
stringclasses 18
values | language
stringclasses 1
value | is_vendor
bool 2
classes | is_generated
bool 2
classes | year
int64 1.97k
2.01k
|
---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
953,482,787,211 |
2f8daf94d9390ea0e01cd982e7652795d80e2328
|
ce31900e7823b9e9da18587c6c1b353b2b5ccd7a
|
/mail.py
|
5cf4ce73396bcb0b3f5453fe7c815fc0f693dff7
|
[
"AGPL-3.0-only"
] |
non_permissive
|
mgway/skillbook
|
https://github.com/mgway/skillbook
|
eccc933509d69b0a6eeb41007abaf76b6f1204ca
|
9e1d1aafa4ef721c72e0e172465b3a76db3b7b72
|
refs/heads/master
| 2021-01-20T21:00:36.174623 | 2014-08-20T06:37:37 | 2014-08-20T06:37:37 | 16,677,979 | 0 | 1 | null | null | null | null | null | null | null | null | null | null | null | null | null |
import requests
from tornado.template import Loader
import db
import config
def send(to, subject, text=None, html=None):
url = 'https://api.mailgun.net/v2/%s/messages' % config.mail.url
data = {'from': config.mail.from_address,
'to': to,
'subject': subject}
if text:
data['text'] = text
if html:
data['html'] = html
return requests.post(url, auth=('api', config.mail.key), data=data)
def send_confirmation(user):
if user.unsubscribed:
return
loader = Loader('templates/mail')
text = loader.load('confirm.txt').generate(user=user, config=config.web)
html = loader.load('confirm.html').generate(user=user, config=config.web)
send(user.email, 'Confirmation instructions', text=text, html=html)
def send_alert(user_id, alert, alert_value):
user = db.get_email_attributes(user_id)
if user.unsubscribed:
return
alert.email_description = alert.email_description.replace('REPLACE_TRIGGER', str(alert.option_1_value))
alert.email_description = alert.email_description.replace('REPLACE_ACTUAL', str(alert_value))
if int(alert.interval) > 1440:
alert.interval = "%d day(s)" % (int(alert.interval)/1440) # minutes to days
else:
alert.interval = "%d hour(s)" % (int(alert.interval)/60) # minutes to hours
loader = Loader('templates/mail')
text = loader.load('alert.txt').generate(user=user, alert=alert, config=config.web)
html = loader.load('alert.html').generate(user=user, alert=alert, config=config.web)
send(user.email, 'Character alert: ' + alert.name , text=text, html=html)
|
UTF-8
|
Python
| false | false | 2,014 |
5,652,177,002,178 |
d98e516e40a532a2ad6e496fe955be35d8212376
|
1018213b9f309a46f342278227860ef72667df31
|
/shop_digitalproducts/__init__.py
|
c5e27fc24b73641d705bf975da4e3801cc41b9d5
|
[
"MIT"
] |
permissive
|
airtonix/django-shop-digitalproducts
|
https://github.com/airtonix/django-shop-digitalproducts
|
526ccc235b8ced5868ec02147b242bc452237815
|
5aff9dda11fae40fc48ebab390bf8c4168a71619
|
refs/heads/master
| 2016-08-07T20:38:25.341718 | 2013-08-24T16:12:27 | 2013-08-24T16:12:27 | 12,345,599 | 0 | 3 | null | null | null | null | null | null | null | null | null | null | null | null | null |
__package__="django-shop-digitalproducts"
__version__="0.0.1"
__license__='MIT'
__author__='Zenobius Jiricek'
__author_email__='airtonix@gmail.com'
__contributors__=[]
__homepage__='https://github.com/airtonix/django-shop-digitalproducts'
|
UTF-8
|
Python
| false | false | 2,013 |
13,993,003,496,637 |
9680fdae3c7c89a282eec3c98d92f16b6fb62879
|
63dea3171ace33dabd07bc4d755161fe8532e5f8
|
/doGestures.py
|
0515b56e2a7136998f16f8471326eda24d2c9a54
|
[] |
no_license
|
julian-ramos/fingers
|
https://github.com/julian-ramos/fingers
|
481fe8ea0fe62bb6af36d7eacc0eebe0a662a4bf
|
840f53271a2173373d5af0bdd5de826e3b2075ee
|
refs/heads/master
| 2021-01-10T21:36:58.028345 | 2014-10-31T07:53:10 | 2014-10-31T07:53:10 | null | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null |
import constants as vals
import findingPoints
import checkingInRange
import gestureCheck
from pymouse import PyMouse
from pykeyboard import PyKeyboard
import pygame
from pygame import mouse
from pygame.locals import *
import pickle
import cwiid, time
from pylab import *
import funcs as fun
import math
import copy
from time import sleep
import sys
import numpy as np
import threading
import os
import miniQueue as q
def gestures(averageX,averageY,keyboard,mouse):
#Swipe Right to Left
k=keyboard
m=mouse
if gestureCheck.allAboveGestureRight(averageX,vals.gestureRightThreshHold) and not vals.gesture_flg_RL:
vals.gestureTime=time.time()
vals.gesture_flg_RL=1
if vals.gesture_flg_RL and (time.time()-vals.gestureTime)<1:
if gestureCheck.allAboveGestureLeft(averageX, vals.gestureLeftThreshHold):
k.press_key(k.control_key)
k.press_key(k.alt_key)
k.press_key(k.left_key)
k.release_key(k.control_key)
k.release_key(k.alt_key)
k.release_key(k.left_key)
vals.gesture_flg_RL=0
print 'right to left'
#Swipe Left to Right
if gestureCheck.allAboveGestureLeft(averageX,vals.gestureLeftThreshHold) and not vals.gesture_flg_LR:
vals.gestureTime=time.time()
vals.gesture_flg_LR=1
if vals.gesture_flg_LR and (time.time()-vals.gestureTime)<1:
if gestureCheck.allAboveGestureRight(averageX, vals.gestureRightThreshHold):
k.press_key(k.control_key)
k.press_key(k.alt_key)
k.press_key(k.right_key)
k.release_key(k.control_key)
k.release_key(k.alt_key)
k.release_key(k.right_key)
vals.gesture_flg_LR=0
print 'left to right'
#Swipe Down to Up
if gestureCheck.allAboveGestureDown(averageY,vals.gestureDownThreshHold) and not vals.gesture_flg_DU:
vals.gestureTime=time.time()
vals.gesture_flg_DU=1
if vals.gesture_flg_DU and (time.time()-vals.gestureTime)<1:
if gestureCheck.allAboveGestureUp(averageY, vals.gestureUpThreshHold):
k.press_key(k.control_key)
k.press_key(k.alt_key)
k.press_key(k.up_key)
k.release_key(k.control_key)
k.release_key(k.alt_key)
k.release_key(k.up_key)
vals.gesture_flg_DU=0
print 'down to up'
#Swipe Up to Down
if gestureCheck.allAboveGestureUp(averageY,vals.gestureUpThreshHold) and not vals.gesture_flg_UD:
vals.gestureTime=time.time()
vals.gesture_flg_UD=1
if vals.gesture_flg_UD and (time.time()-vals.gestureTime)<1:
if gestureCheck.allAboveGestureDown(averageY, vals.gestureDownThreshHold):
k.press_key(k.control_key)
k.press_key(k.alt_key)
k.press_key(k.down_key)
k.release_key(k.control_key)
k.release_key(k.alt_key)
k.release_key(k.down_key)
vals.gesture_flg_UD=0
print 'up to down'
if vals.gesture_flg_RL and (time.time()-vals.gestureTime)>=1:
vals.gesture_flg_RL=0
if vals.gesture_flg_LR and (time.time()-vals.gestureTime)>=1:
vals.gesture_flg_LR=0
if vals.gesture_flg_UD and (time.time()-vals.gestureTime)>=1:
vals.gesture_flg_UD=0
if vals.gesture_flg_DU and (time.time()-vals.gestureTime)>=1:
vals.gesture_flg_DU=0
|
UTF-8
|
Python
| false | false | 2,014 |
10,763,188,048,496 |
bd9d81682b43fac3cf8d23f55cc8386dba289f3b
|
40bac4587c1163f22239809af7d0660a8ed564ab
|
/settings.py
|
caf8bbd3327bfcdc7581a7d1d56628dc862da66a
|
[] |
no_license
|
coordt/pkgbin
|
https://github.com/coordt/pkgbin
|
caf7dde7c67910e8b0adb710003a273e0da0fae6
|
39212d27605c4f0962390e9f33968c6069c28b09
|
refs/heads/master
| 2022-12-20T03:19:41.613198 | 2013-12-11T02:48:22 | 2013-12-11T02:48:22 | 3,892,531 | 4 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null |
# Django settings for project project.
import calloway
import os
import sys
CALLOWAY_ROOT = os.path.abspath(os.path.dirname(calloway.__file__))
sys.path.insert(0, os.path.join(CALLOWAY_ROOT, 'apps'))
PROJECT_ROOT = os.path.abspath(os.path.dirname(__file__))
sys.path.insert(0, os.path.join(PROJECT_ROOT, 'apps'))
sys.path.insert(0, os.path.join(PROJECT_ROOT, 'lib'))
try:
from local_settings import DEBUG as LOCAL_DEBUG
DEBUG = LOCAL_DEBUG
except ImportError:
DEBUG = False
TEMPLATE_DEBUG = DEBUG
from calloway.settings import *
ADMINS = (
('webmaster', 'webmaster@pkgbin.com'),
)
MANAGERS = ADMINS
DEFAULT_FROM_EMAIL='webmaster@pkgbin.com'
SERVER_EMAIL='webmaster@pkgbin.com'
SECRET_KEY = ''
DATABASES = {
'default': {
'ENGINE': 'django.db.backends.sqlite3',
'NAME': 'dev.db',
'USER': '',
'PASSWORD': '',
'HOST': '',
'PORT': '',
}
}
USE_TZ = True
LANGUAGE_CODE = 'en-us'
USE_I18N = True
try:
from local_settings import MEDIA_URL_PREFIX
except ImportError:
MEDIA_URL_PREFIX = "/media/"
try:
from local_settings import MEDIA_ROOT_PREFIX
except ImportError:
MEDIA_ROOT_PREFIX = os.path.join(PROJECT_ROOT, 'media')
try:
from local_settings import MEDIA_ROOT
except ImportError:
MEDIA_ROOT = os.path.join(MEDIA_ROOT_PREFIX, 'uploads')
try:
from local_settings import STATIC_ROOT
except ImportError:
STATIC_ROOT = os.path.join(MEDIA_ROOT_PREFIX, 'static')
MEDIA_URL = '%suploads/' % MEDIA_URL_PREFIX
STATIC_URL = "%sstatic/" % MEDIA_URL_PREFIX
ADMIN_MEDIA_PREFIX = "%sadmin/" % STATIC_URL
STATICFILES_DIRS = (
os.path.join(PROJECT_ROOT, 'static'),
)
MMEDIA_DEFAULT_STORAGE = 'media_storage.MediaStorage'
MMEDIA_IMAGE_UPLOAD_TO = 'image/%Y/%m/%d'
AUTH_PROFILE_MODULE = 'profiles.Profile'
MIDDLEWARE_CLASSES = (
'django.middleware.common.CommonMiddleware',
'django.contrib.sessions.middleware.SessionMiddleware',
'django.middleware.locale.LocaleMiddleware',
'django.middleware.csrf.CsrfViewMiddleware',
'django.contrib.auth.middleware.AuthenticationMiddleware',
'django.contrib.messages.middleware.MessageMiddleware',
'userena.middleware.UserenaLocaleMiddleware',
# 'hunger.middleware.BetaMiddleware',
'beta_middleware.BetaMiddleware',
)
TEMPLATE_CONTEXT_PROCESSORS = (
"django.contrib.auth.context_processors.auth",
"django.core.context_processors.debug",
"django.core.context_processors.i18n",
"django.core.context_processors.media",
"django.core.context_processors.static",
"django.contrib.messages.context_processors.messages",
"django.core.context_processors.request",
)
# List of callables that know how to import templates from various sources.
TEMPLATE_LOADERS = (
'django.template.loaders.filesystem.Loader',
'django.template.loaders.app_directories.Loader',
# 'django.template.loaders.eggs.Loader',
)
AUTHENTICATION_BACKENDS = (
# 'social_auth.backends.twitter.TwitterBackend',
# 'social_auth.backends.google.GoogleOAuthBackend',
# 'social_auth.backends.google.GoogleOAuth2Backend',
# 'social_auth.backends.google.GoogleBackend',
# 'social_auth.backends.yahoo.YahooBackend',
# 'social_auth.backends.browserid.BrowserIDBackend',
# 'social_auth.backends.contrib.linkedin.LinkedinBackend',
# 'social_auth.backends.contrib.livejournal.LiveJournalBackend',
# 'social_auth.backends.contrib.github.GithubBackend',
# 'social_auth.backends.OpenIDBackend',
'userena.backends.UserenaAuthenticationBackend',
'guardian.backends.ObjectPermissionBackend',
'django.contrib.auth.backends.ModelBackend',
)
EMAIL_BACKEND = 'django.core.mail.backends.smtp.EmailBackend'
TEMPLATE_DIRS = (
# Put strings here, like "/home/html/django_templates" or "C:/www/django/templates".
# Always use forward slashes, even on Windows.
# Don't forget to use absolute paths, not relative paths.
os.path.join(PROJECT_ROOT, 'templates'),
) + CALLOWAY_TEMPLATE_DIRS
CACHE_BACKEND = 'memcached://localhost:11211/'
# Python dotted path to the WSGI application used by Django's runserver.
WSGI_APPLICATION = 'wsgi.application'
INSTALLED_APPS = (
'admin_tools',
'admin_tools.theming',
'admin_tools.menu',
'admin_tools.dashboard',
'django.contrib.auth',
'django.contrib.sites',
'django.contrib.admin',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.sites',
'django.contrib.flatpages',
'django.contrib.messages',
'django.contrib.staticfiles',
'calloway',
'userena',
'guardian',
'easy_thumbnails',
'profiles',
'userpypi',
'userrouter',
'bootstrapform',
'djcelery',
'queued_storage',
#"kombu.transport.django",
'hunger',
'selectable',
'tastypie',
'teams',
'robots',
)
ADMIN_TOOLS_THEMING_CSS = 'calloway/admin/css/theming.css'
ADMIN_TOOLS_MENU = 'menu.CustomMenu'
TINYMCE_JS_URL = '%scalloway/js/tiny_mce/tiny_mce.js' % STATIC_URL
TINYMCE_JS_ROOT = os.path.join(STATIC_ROOT, 'js/tiny_mce')
LOGIN_REDIRECT_URL = '/accounts/%(username)s/'
LOGIN_URL = '/accounts/signin/'
LOGOUT_URL = '/accounts/signout/'
DJANGOPYPI_SETTINGS = {
'PROXY_MISSING': True,
'RELEASE_FILE_STORAGE': 'media_storage.QueuedUserCloudFilesStorage',
'RELEASE_UPLOAD_TO': lambda x,y: "%s/%s" % (x.release.package.owner.username, y)
}
#######################
# Userena settings
#######################
ANONYMOUS_USER_ID = -1
USERENA_SIGNIN_REDIRECT_URL = "/%(username)s/"
USERENA_FORBIDDEN_USERNAMES = ('signup', 'signout', 'signin', 'activate', 'me',
'password', 'pypi', 'pkgbin', 'admin', 'admin_tools', 'username', 'user',)
USERENA_DISABLE_PROFILE_LIST = True
USERENA_HIDE_EMAIL = True
# A sample logging configuration. The only tangible logging
# performed by this configuration is to send an email to
# the site admins on every HTTP 500 error when DEBUG=False.
# See http://docs.djangoproject.com/en/dev/topics/logging for
# more details on how to customize your logging configuration.
LOGGING = {
'version': 1,
'disable_existing_loggers': False,
'filters': {
'require_debug_false': {
'()': 'django.utils.log.RequireDebugFalse'
}
},
'handlers': {
'mail_admins': {
'level': 'ERROR',
'filters': ['require_debug_false'],
'class': 'django.utils.log.AdminEmailHandler'
}
},
'loggers': {
'django.request': {
'handlers': ['mail_admins'],
'level': 'ERROR',
'propagate': True,
},
}
}
#######################
# Celery settings
#######################
import djcelery
djcelery.setup_loader()
BROKER_URL = "redis://localhost:6379/0"
CELERY_RESULT_BACKEND = "redis"
CELERY_REDIS_HOST = "localhost"
CELERY_REDIS_PORT = 6379
CELERY_REDIS_DB = 0
CELERYBEAT_PIDFILE = '/var/run/celerybeat.pid'
TEMPLATED_EMAIL_BACKEND = 'templated_email.backends.vanilla_django.TemplateBackend'
#######################
# Hunger settings
#######################
# BETA_INVITE_CODE_LENGTH
BETA_ENABLE_BETA = True
# BETA_NEVER_ALLOW_VIEWS
BETA_ALWAYS_ALLOW_VIEWS = (
'userena.views.signin',
'userena.views.direct_to_user_template',
'userena.views.activate',
'tastypie.api.wrapper',
'tastypie.resources.wrapper',
'userpypi.utils._wrapped',
'userpypi.views.root',
'userpypi.views.packages.PackageListView',
'userpypi.views.packages.PackageDetailView',
'robots.views.rules_list',
)
# BETA_ALWAYS_ALLOW_MODULES
# BETA_ALLOW_FLATPAGES
BETA_SIGNUP_VIEWS = ('userena.views.signup',)
BETA_SIGNUP_CONFIRMATION_VIEW = 'userena.views.profile_detail'
# BETA_REDIRECT_URL
BETA_SIGNUP_URL = '/signup/'
# BETA_EMAIL_TEMPLATES_DIR
# BETA_EMAIL_MODULE
# BETA_EMAIL_CONFIRM_FUNCTION
# BETA_EMAIL_INVITE_FUNCTION
SELECTABLEWRAPPER_SETTINGS = {
'AUTOCOMPLETESELECT_FIELDS': {
'userpypi.maintainer.user': 'lookups.UserLookup'
}
}
try:
from local_settings import *
except ImportError:
pass
|
UTF-8
|
Python
| false | false | 2,013 |
12,515,534,727,723 |
1517382023ef4f3adc342abeb42a4264172dd72a
|
24b8b50a8269fdc9704a8205bbe9126295c50e9b
|
/tests/dungeon_generators_tests.py
|
32214a7dbbae68313d85e26212c559e971a63345
|
[] |
no_license
|
sirvaulterscoff/darktower-rl
|
https://github.com/sirvaulterscoff/darktower-rl
|
45aaa79e6d3d2b912408e3bcb045b8590f670e2e
|
7d0680c99acc6fd4e33f4b08811f3d468e19f7da
|
refs/heads/master
| 2020-12-24T18:04:06.419611 | 2012-05-23T08:22:12 | 2012-05-23T08:22:12 | 1,511,396 | 6 | 2 | null | null | null | null | null | null | null | null | null | null | null | null | null |
import os
import sys
import dungeon_generators
sys.path.insert(0, os.path.join(os.path.dirname(__file__), '..'))
from dungeon_generators import CaveGenerator, StaticGenerator
from features import *
import unittest
class TestCaveGenerator(unittest.TestCase):
def testFinish(self):
gen = CaveGenerator(5, 5)
gen._map = dungeon_generators.parse_string(['NAME=TEST',
'#####',
'# #',
'# # #',
'# #',
'#####'])['TEST']
map = gen.finish()
print_map(map)
etalon_map = [[FT_ROCK_WALL() for i in range(0, 5)],
[FT_ROCK_WALL(), FT_ROCK_WALL(), FT_FLOOR(), FT_FLOOR(), FT_ROCK_WALL()],
[FT_ROCK_WALL(), FT_FLOOR(), FT_FLOOR(), FT_FLOOR(), FT_ROCK_WALL()],
[FT_ROCK_WALL(), FT_ROCK_WALL(), FT_FLOOR(), FT_FLOOR(), FT_ROCK_WALL()],
[FT_ROCK_WALL() for i in range(0, 5)]]
y,x = 0,0
for row in map:
for item in row:
assert item.char == etalon_map[y][x].char
x +=1
y += 1
x = 0
def print_map(map):
for row in map:
str = ''
for item in row:
str += item.char
print(str)
|
UTF-8
|
Python
| false | false | 2,012 |
3,753,801,425,441 |
56a6ed3f09c30af6df5a5c48d94ebcd81891c3ce
|
11215ad52ea3eef58ef3e8e803f33afbc9aa12e4
|
/foobrowser.pyw
|
6f209ae5e30eb9fed4744fc6a9986f2b079c28ac
|
[] |
no_license
|
fluffynuts/foobrowser
|
https://github.com/fluffynuts/foobrowser
|
4aeb81638bd049c4b081bf196970308bad0d35b6
|
15c1f00dd64aaf8f1d0ec0c711195a9b00720e6b
|
refs/heads/master
| 2021-01-21T16:32:17.718269 | 2012-05-04T15:45:31 | 2012-05-04T15:45:31 | 32,150,945 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null |
#!/usr/bin/python
# minimalistic browser levering off of Python, PyQt and Webkit
from PyQt4 import QtGui, QtCore, QtWebKit, QtNetwork
import sqlite3
import os
import sys
import time
import base64
import socket
import sip # put here to make py2exe work better
import subprocess
def registerShortcuts(actions, defaultOwner):
for action in actions:
shortcut = actions[action][1]
if shortcut.lower() == "none":
continue
# allow multiple shortcuts with keys delimited by |
shortcuts = shortcut.split("|")
for shortcut in shortcuts:
shortcut = shortcut.strip()
if shortcut == "":
continue
callback = actions[action][0]
if len(actions[action]) == 2:
owner = defaultOwner
else:
if type(actions[action][2]) != str:
owner = actions[action][2]
elif len(actions[action]) == 4:
owner = actions[action][3]
else:
owner = defaultOwner
QtGui.QShortcut(shortcut, owner, callback)
class Icons:
"""Container class to hold icons for Bonsai in base64-encoded format"""
def __init__(self):
if os.name == "nt":
import ctypes
try:
ctypes.windll.shell32.SetCurrentProcessExplicitAppUserModelID(os.path.basename(sys.argv[0]))
except:
# not a win7 client
pass
self.icons = dict()
self.icons["foobrowser"] = "iVBORw0KGgoAAAANSUhEUgAAAEAAAABACAYAAACqaXHeAAAAAXNSR0IArs4c6QAAAAZiS0dEAP8A\
/wD/oL2nkwAAAAlwSFlzAAALEwAACxMBAJqcGAAAAAd0SU1FB9sIFw0xIyVxhzgAAAAZdEVYdENv\
bW1lbnQAQ3JlYXRlZCB3aXRoIEdJTVBXgQ4XAAABJUlEQVR42u3WMUoDURSF4V8JKAoqQlyJ2Fll\
B+JKRF2ChcsSQU0hSlAXYJoEUihok0KbOxBkeMZ40Vf8HzyGyTtnArd4MyBJkiRJkiRJkiTN4+Ob\
NasLnAED4C3WIH7rFv5j0V5VA9gDxoXcODJfLdr78wGUbALDyF0BPWA9Vg+4ib1hZH/bq24AJ5G5\
BVZa9leB+8gcJ/SqG8BlZA4KmcPIXCT0qjkDGpO4Lx1YO5GZJPSqG8A07juF53QiM03o/chy0iCW\
WlbjNa5bhf52XF8Sev8ygJKnuO4XMs3eQ0KvukPwdI7T/C4yRwm9qr8DruMdvharB/Rj7xnYSOhV\
NwCAXWBUODBHkcnqVTeAtm/6d+AROI/XWXZPkiRJkiRJkiRJsz4BmPGrGG5RdTEAAAAASUVORK5C\
YII="
def QIcon(self, name):
if list(self.icons.keys()).count(name) == 0:
return None
pixmap = QtGui.QPixmap()
if dir(base64).count("decodebytes"):
if not pixmap.loadFromData(base64.decodebytes(bytes(self.icons[name], encoding="UTF-8"))):
return None
elif dir(base64).count("b64decode"):
if not pixmap.loadFromData(base64.b64decode(self.icons[name])):
return None
icon = QtGui.QIcon(pixmap)
return icon
class DiskCookies(QtNetwork.QNetworkCookieJar):
def __init__(self, storage_location, parent=None):
self.db = None
QtNetwork.QNetworkCookieJar.__init__(self, parent)
self.LoadFromDisk(storage_location)
def LoadFromDisk(self, path):
cookiefile = os.path.join(path, "cookies.db")
init = False
if not os.path.isfile(cookiefile):
init = True
self.db = sqlite3.connect(cookiefile)
if init:
self.initDB()
cur = self.db.execute("select domain, expires, http_only, secure, name, path, value from cookies;")
cookies = []
for row in cur.fetchall():
cookie = QtNetwork.QNetworkCookie()
cookie.setDomain(row[0])
try:
if len(row[1]):
e = time.strptime(row[1], "%Y-%m-%d %H:%M:%S")
cookie.setExpirationDate(QtCore.QDateTime(e.tm_year, e.tm_mon, e.tm_mday, e.tm_hour, e.tm_min, e.tm_sec))
except:
pass
if row[2]:
cookie.setHttpOnly(True)
else:
cookie.setHttpOnly(False)
if row[3]:
cookie.setSecure(True)
else:
cookie.setSecure(False)
cookie.setName(row[4])
cookie.setPath(row[5])
try:
cookie.setValue(bytes(row[6]))
except:
try:
cookie.setValue(bytes(row[6], encoding="UTF-8"))
except:
pass
cookies.append(cookie)
self.setAllCookies(cookies)
def clear(self):
self.setAllCookies([])
if self.db:
self.db.execute("delete from cookies;")
def quote(self, s):
s = str(s)
return "'%s'" % (s.replace("'", "''"))
def boolToInt(self, b):
if b:
return 1
else:
return 0
def Persist(self):
if self.db == None:
return
self.db.execute("delete from cookies;")
sqlstr = "insert into cookies (domain, expires, http_only, secure, name, path, value) values (%s, %s, %i, %i, %s, %s, %s);";
fmt = "yyyy-MM-dd hh:mm:ss"
for cookie in self.allCookies():
cval = cookie.value().data()
if type(cval) != str:
cval = cval.decode("UTF-8")
#print("cookie:\n\tsession: %s\n\tname: %s\n\tpath: %s\n\tvalue: %s\n\t" % (str(cookie.isSessionCookie()),cookie.name(), cookie.path(), cval))
esql = (sqlstr % (self.quote(cookie.domain()),
self.quote(cookie.expirationDate().toString(fmt)),
self.boolToInt(cookie.isHttpOnly()),
self.boolToInt(cookie.isSecure()),
self.quote(cookie.name()),
self.quote(cookie.path()),
self.quote(cookie.value().data().decode("UTF-8"))))
self.db.execute(esql)
self.db.commit()
self.db.close()
def initDB(self):
cur = self.db.execute("create table cookies(domain text, expires text, http_only int, secure int, session int, name text, path text, value text);")
cur.close()
class FooWebView(QtWebKit.QWebView):
def __init__(self, parent = None):
self.parent = parent
QtWebKit.QWebView.__init__(self, parent)
def createWindow(self, type):
return self.parent.browser.addTab().webkit
class WebTab(QtGui.QWidget):
def __init__(self, browser, actions=None, parent=None, showStatusBar=False):
QtGui.QWidget.__init__(self, parent)
self.actions = dict()
self.grid = QtGui.QGridLayout(self)
self.grid.setSpacing(1)
self.cmb = QtGui.QComboBox()
self.cmb.setEditable(True)
self.browser = browser
if browser is not None:
browser.LoadHistoryToCmb(self.cmb)
self.webkit = FooWebView(self)
self.webkit.page().setLinkDelegationPolicy(QtWebKit.QWebPage.DelegateAllLinks)
self.webkit.linkClicked.connect(self.onLinkClick)
self.webkit.settings().setAttribute(QtWebKit.QWebSettings.PluginsEnabled,True)
self.pbar = QtGui.QProgressBar()
self.pbar.setRange(0, 100)
self.pbar.setTextVisible(False)
self.grid.addWidget(self.cmb, 0, 0)
self.grid.addWidget(self.pbar, 1, 0, 1, self.grid.columnCount())
self.grid.addWidget(self.webkit, 2, 0, 1, self.grid.columnCount())
self.pbar.setVisible(False)
self.pbar.setMaximumHeight(10)
self.fraSearch = QtGui.QFrame()
self.searchGrid = QtGui.QGridLayout(self.fraSearch)
self.searchGrid.setSpacing(1)
self.lblSearch = QtGui.QLabel("Find text in page:")
self.txtSearch = QtGui.QLineEdit()
self.btnClearSearch = QtGui.QPushButton("[X]")
self.searchGrid.addWidget(self.lblSearch, 0, 0)
self.searchGrid.addWidget(self.txtSearch, 0, 1)
self.searchGrid.addWidget(self.btnClearSearch, 0, 2)
self.statusbar = QtGui.QStatusBar()
self.statusbar.setVisible(showStatusBar)
self.statusbar.setMaximumHeight(25)
self.grid.addWidget(self.statusbar, self.grid.rowCount(), 0, 1, self.grid.columnCount())
for i in range(2):
self.searchGrid.setColumnStretch(i, i % 2)
self.fraSearch.setVisible(False)
self.grid.addWidget(self.fraSearch, self.grid.rowCount() + 1, 0, 1, self.grid.columnCount())
for c in range(self.grid.columnCount() + 1):
self.grid.setColumnStretch(c, 0)
for r in range(self.grid.rowCount() + 1):
self.grid.setRowStretch(r, 0)
self.grid.setRowStretch(2, 1)
self.grid.setColumnStretch(0, 1)
self.connect(self.cmb, QtCore.SIGNAL("currentIndexChanged(int)"), self.navigate)
if browser:
self.browser.setupWebkit(self.webkit)
self.connect(self.webkit, QtCore.SIGNAL("iconChanged()"), self.setIcon)
self.connect(self.webkit, QtCore.SIGNAL("loadStarted()"), self.loadStarted)
self.connect(self.webkit, QtCore.SIGNAL("loadFinished(bool)"), self.loadFinished)
self.connect(self.webkit, QtCore.SIGNAL("titleChanged(QString)"), self.setTitle)
self.connect(self.webkit, QtCore.SIGNAL("loadProgress(int)"), self.loadProgress)
self.connect(self.webkit, QtCore.SIGNAL("urlChanged(QUrl)"), self.setURL)
self.connect(self.webkit.page(), QtCore.SIGNAL("linkHovered(QString, QString, QString)"), self.onLinkHovered)
page = self.webkit.page()
page.downloadRequested.connect(self.onDownloadRequested)
page.setForwardUnsupportedContent(True)
page.unsupportedContent.connect(self.onUnsupportedContent)
self.connect(self.btnClearSearch, QtCore.SIGNAL("clicked()"), self.stopOrHideSearch)
self.connect(self.txtSearch, QtCore.SIGNAL("textChanged(QString)"), self.doSearch)
self.registerActions(actions)
registerShortcuts(self.actions, self)
self.cmb.setFocus()
self.showHideMessage()
def onLinkClick(self, qurl):
self.navigate(qurl.toString())
def registerActions(self, template):
self.actions["addressnav"] = [self.navigate, "Enter", self.cmb, "Navigate to the url in the address bar"]
self.actions["reload"] = [self.reload, "F5|Ctrl+R", "Reload the current page"]
self.actions["back"] = [self.back, "Alt+Left", "Go back in history"]
self.actions["fwd"] = [self.fwd, "Alt+Right", "Go forward in history"]
self.actions["search"] = [self.showSearch, "/|Ctrl-F", "Search in page"]
self.actions["smartsearch"] = [self.smartSearch, "F3", "Smart search (find next or start search)"]
self.actions["stopsearch"] = [self.stopOrHideSearch, "Escape", self.fraSearch, "Stop current load or searching"]
self.actions["findnext"] = [self.doSearch, "Return", self.txtSearch, "Next match for current search"]
self.actions["togglestatus"]= [self.toggleStatus, "Ctrl+Space", "Toggle visibility of status bar"]
if template:
actionnames = list(self.actions.keys())
for action in template:
if actionnames.count(action):
self.actions[action][1] = template[action][1]
def toggleStatus(self):
if self.browser:
self.browser.toggleStatusVisiblity()
else:
self.statusbar.setVisible(not self.statusBar.isVisible())
def setStatusVisibility(self, visible):
self.statusbar.setVisible(visible)
def loadContent(self, html, baseUrl = None):
if baseUrl:
baseUrl = QtWebKit.QUrl(baseUrl)
else:
baseUrl = QtWebKit.QUrl()
self.webkit.setHTML(html, baseUrl)
def onUnsupportedContent(self, reply):
self.log("Unsupported content %s" % (reply.url().toString()))
if self.browser:
self.browser.addDownload(reply.url().toString())
def onDownloadRequested(self, request):
if self.browser:
self.browser.addDownload(request.url().toString())
def doSearch(self, s = None):
if s is None: s = self.txtSearch.text()
self.webkit.findText(s, QtWebKit.QWebPage.FindWrapsAroundDocument)
def stopOrHideSearch(self):
if self.fraSearch.isVisible():
self.fraSearch.setVisible(False)
self.webkit.setFocus()
else:
self.webkit.stop()
def showSearch(self):
self.txtSearch.setText("")
self.fraSearch.setVisible(True)
self.txtSearch.setFocus()
def zoom(self, lvl):
self.webkit.setZoomFactor(self.webkit.zoomFactor() + (lvl * 0.25))
def stop(self):
self.webkit.stop()
def URL(self):
return self.cmb.currentText()
def loadProgress(self, val):
if self.pbar.isVisible():
self.pbar.setValue(val)
def setTitle(self, title):
if self.browser:
self.browser.setTabTitle(self, title)
def setURL(self, url):
self.cmb.setEditText(url.toString())
def refresh(self):
self.navigate(self.URL())
self.webkit.reload()
def loadStarted(self):
self.showProgressBar()
def loadFinished(self, success):
self.hideProgressBar()
self.setIcon()
if self.cmb.hasFocus():
self.webkit.setFocus()
def showProgressBar(self):
self.pbar.setValue(0)
self.pbar.setVisible(True)
def hideProgressBar(self, success = False):
self.pbar.setVisible(False)
def setIcon(self):
if self.browser:
self.browser.setTabIcon(self, self.webkit.icon())
def reload(self):
self.webkit.reload()
def smartSearch(self):
if self.fraSearch.isVisible():
self.doSearch()
else:
self.showSearch()
def mkShortcuts(self):
if self.browser:
self.bro
def fwd(self):
self.webkit.history().forward()
def back(self):
self.webkit.history().back()
def navigate(self, url = None):
if url and type(url) == str:
u = url
else:
u = str(self.cmb.currentText())
parts = u.split(":")
if len(parts) == 2 and parts[0] == "about":
self.navabout(parts[1].strip().lower())
return
if u.strip() == "":
return
if self.browser is not None:
u = self.browser.fixUrl(u)
self.cmb.setEditText(u)
if self.browser is not None:
self.browser.addHistory(u)
url = QtCore.QUrl(u)
self.setTitle("Loading...")
self.webkit.load(url)
def onStatusBarMessage(self, s):
if s:
self.statusbar.showMessage(s)
else:
self.showHideMessage()
def showHideMessage(self):
self.statusbar.showMessage("(press %s to hide this)" % (self.actions["togglestatus"][1]))
def onLinkHovered(self, link, title, content):
if link or title:
if title and not link:
self.statusbar.showMessage(title)
elif link and not title:
self.statusbar.showMessage(link)
elif link and title:
self.statusbar.showMessage("%s (%s)" % (title, link))
else:
self.showHideMessage()
def navabout(self, dst):
if self.browser is None:
return
if dst == "help":
self.webkit.setHtml(self.browser.genHelp())
self.cmb.setEditText("about:help")
return
elif dst == "foo":
self.webkit.setHtml(self.browser.genAboutFoo())
self.cmb.setEditText("about:foo")
return
elif dst == "nothing":
self.webkit.setHtml("")
self.cmb.setEditText("about:nothing")
return
self.webkit.setHtml("<p>Sorry, Jim, that resource cannot be found</p>")
self.cmb.setEditText("about:lost")
class PrivacyDialog(QtGui.QDialog):
def __init__(self, parent=None, icon=None):
QtGui.QDialog.__init__(self, parent)
if icon:
self.setWindowIcon(icon)
self.setWindowTitle("Clear private data")
self.chkClearCookies = QtGui.QCheckBox("Clear cookies")
self.chkClearHistory = QtGui.QCheckBox("Clear history")
self.chkClearCache = QtGui.QCheckBox("Clear cache")
self.btnOk = QtGui.QPushButton("OK")
self.btnCancel = QtGui.QPushButton("Cancel")
self.grid = QtGui.QGridLayout(self)
row = 0
for chk in [self.chkClearCookies, self.chkClearHistory, self.chkClearCache]:
self.grid.addWidget(chk, row, 0, 1, 3)
chk.setChecked(True)
row += 1
growrow = row
row += 1
self.grid.addWidget(self.btnOk, row, 1)
self.grid.addWidget(self.btnCancel, row, 2)
for i in range(self.grid.rowCount()):
self.grid.setRowStretch(i, 0)
self.grid.setRowStretch(growrow, 1)
self.grid.setColumnStretch(0, 1)
for i in range(self.grid.columnCount()):
if i:
self.grid.setColumnStretch(i, 1)
self.connect(self.btnOk, QtCore.SIGNAL("clicked()"), self.accept)
self.connect(self.btnCancel, QtCore.SIGNAL("clicked()"), self.reject)
class AuthDialog(QtGui.QDialog):
def __init__(self, parent=None, icon=None):
QtGui.QDialog.__init__(self, parent)
if icon:
self.setWindowIcon(icon)
self.setWindowTitle("Authentication required")
self.lblAuth = QtGui.QLabel("Authentication required")
self.lblUserName = QtGui.QLabel("Username:")
self.txtUserName = QtGui.QLineEdit()
self.lblPassword = QtGui.QLabel("Password:")
self.txtPassword = QtGui.QLineEdit()
self.txtPassword.setEchoMode(QtGui.QLineEdit.Password)
self.btnCancel = QtGui.QPushButton("Cancel")
self.btnOK = QtGui.QPushButton("OK")
self.grid = QtGui.QGridLayout(self)
self.grid.addWidget(self.lblAuth, 0, 0, 1, 3)
self.grid.addWidget(self.lblUserName, 1, 0)
self.grid.addWidget(self.txtUserName, 1, 1, 1, 3)
self.grid.addWidget(self.lblPassword, 2, 0)
self.grid.addWidget(self.txtPassword, 2, 1, 1, 3)
self.grid.addWidget(self.btnOK, 3, 2)
self.grid.addWidget(self.btnCancel, 3, 3)
for i in range(self.grid.columnCount()):
self.grid.setColumnStretch(i, 0)
self.grid.setColumnStretch(1, 1)
for i in range(self.grid.rowCount()):
self.grid.setRowStretch(i, 0)
self.cancelled = False
self.connect(self.btnCancel, QtCore.SIGNAL("clicked()"), self.onCancel)
self.connect(self.btnOK, QtCore.SIGNAL("clicked()"), self.onOK)
def onOK(self):
self.cancelled = False
self.close()
def onCancel(self):
self.cancelled = True
self.close()
def prompt(self, url=None):
self.cancelled = False
if url:
self.lblAuth.setText("The page at:\n\n%s\n\nrequires authentication to continue" % (url))
self.exec_()
if self.cancelled:
return None, None
else:
return self.txtUserName.text(), self.txtPassword.text()
class MainWin(QtGui.QMainWindow):
def __init__(self, debug=False):
QtGui.QMainWindow.__init__(self, None)
self.downloader = None
self.debug = debug
self.actions = dict()
self.tabactions = dict()
self.tabactions = dict()
tmp = WebTab(None, None)
self.tabactions = tmp.actions
self.configdir = os.path.join(os.path.expanduser("~"), ".foobrowser")
self.registerActions()
self.showStatusBar = False
self.loadConfig()
self.icons = Icons()
self.setWindowIcon(self.icons.QIcon("foobrowser"))
self.appname = "Foo browser!"
self.cache_mb = 512
self.maxHistory = 4096
self.tabs = []
self.historyDateFormat = "%Y-%m-%d %H:%M:%S"
self.maxTitleLen = 40
if not os.path.isdir(self.configdir):
try:
os.mkdir(self.configdir)
except Exception as e:
self.configdir = None
if self.configdir is not None:
self.loadHistory()
self.disk_cache = None
self.cookie_jar = None
if self.configdir:
cachedir = os.path.join(self.configdir, "cache")
if not os.path.isdir(cachedir):
os.mkdir(cachedir)
self.disk_cache = QtNetwork.QNetworkDiskCache()
self.disk_cache.setCacheDirectory(cachedir)
self.disk_cache.setMaximumCacheSize(self.cache_mb * (1024 * 1024))
self.cookie_jar = DiskCookies(self.configdir)
self.auth_cache = dict()
tmp.deleteLater()
self.mkGui()
registerShortcuts(self.actions, self)
def loadConfig(self):
if self.configdir:
if not os.path.isdir(self.configdir):
try:
os.mkdir(self.configdir)
except:
return
conffile = os.path.join(self.configdir, "config.ini")
if not os.path.isfile(conffile):
return
try:
fp = open(conffile, "r")
except:
return
section = ""
for line in fp:
line = line.strip()
if len(line) == 0:
continue
if line[0] == "[" and line[-1] == "]":
section = line.strip("[]")
continue
parts = line.split("=")
if len(parts) < 2:
continue
setting = parts[0].strip()
value = "=".join(parts[1:]).strip()
self.log("config: %s/%s/%s" % (section, setting, value))
if section == "shortcuts":
setting = setting.lower()
if list(self.actions.keys()).count(setting):
self.actions[setting][1] = value
continue
if section == "tabshortcuts":
setting = setting.lower()
if list(self.tabactions.keys()).count(setting):
self.tabactions[setting][1] = value
continue
if section == "general":
setting = setting.lower()
if setting == "downloader":
if value.lower() != "none":
self.log("setting downloader to %s" % (value))
self.downloader = value
elif setting == "showstatus":
if value.lower() in ["yes", "true", "1"]:
self.showStatusBar = True
else:
self.showStatusBar = False
fp.close()
def toggleStatusVisiblity(self):
self.showStatusBar = not self.showStatusBar
for t in self.tabs:
t.setStatusVisibility(self.showStatusBar)
def persistConfig(self):
if self.configdir:
if not os.path.isdir(self.configdir):
try:
os.mkdir(self.configdir)
except:
return
conffile = os.path.join(self.configdir, "config.ini")
try:
fp = open(conffile, "w")
except:
return
# write out shortcuts
fp.write("[general]\n")
fp.write("; general settings\n")
if self.downloader:
fp.write("downloader = %s\n" % (str(self.downloader)))
else:
fp.write("downloader = None\n")
if self.showStatusBar:
fp.write("showstatus = True\n")
else:
fp.write("showstatus = False\n")
fp.write("[shortcuts]\n")
fp.write("; shortcuts applied to the application as a whole\n")
actionnames = list(self.actions.keys())
actionnames.sort()
for action in actionnames:
fp.write("%s = %s\n" % (action, self.actions[action][1]))
fp.write("[tabshortcuts]\n")
fp.write("; shortcuts applied to individual tabs\n")
actionnames = list(self.tabactions.keys())
actionnames.sort()
for action in actionnames:
fp.write("%s = %s\n" % (action, self.tabactions[action][1]))
fp.close()
def registerActions(self):
self.actions["newwin"] = [self.addWin, "Ctrl+N", "Open new window"]
self.actions["newtab"] = [self.addTab, "Ctrl+T", "Open new tab"]
self.actions["closetab"] = [self.delTab, "Ctrl+W", "Close current tab"]
self.actions["tabprev"] = [self.decTab, "Ctrl+PgUp", "Switch to previous tab"]
self.actions["tabnext"] = [self.incTab, "Ctrl+PgDown", "Switch to next tab"]
self.actions["go"] = [self.currentTabGo, "Ctrl+G", "Focus address bar"]
self.actions["close"] = [self.close, "Ctrl+Q", "Close application"]
self.actions["zoomin"] = [self.zoomIn, "Ctrl+Up", "Zoom into page"]
self.actions["zoomout"] = [self.zoomOut, "Ctrl+Down", "Zoom out of page"]
self.actions["help"] = [self.showHelp, "F1", "Show this help page"]
self.actions["cleardata"] = [self.clearData, "Ctrl+Shift+Delete", "Clear cache and private data"]
def clearData(self):
dlg = PrivacyDialog(parent=self, icon=self.icons.QIcon("foobrowser"))
if dlg.exec_() == QtGui.QDialog.Accepted:
if dlg.chkClearCookies.isChecked() and self.cookie_jar:
self.cookie_jar.clear()
if dlg.chkClearCache.isChecked() and self.disk_cache:
self.disk_cache.clear()
if dlg.chkClearHistory.isChecked():
self.history = {}
def showHelp(self):
self.addTab().navigate("about:help")
def addWin(self):
MainWin().show()
def currentTabGo(self):
self.tabs[self.tabWidget.currentIndex()].cmb.setFocus()
def zoomIn(self):
self.zoom(1)
def zoomOut(self):
self.zoom(-1)
def zoom(self, lvl):
self.tabs[self.tabWidget.currentIndex()].zoom(lvl)
def decTab(self):
self.incTab(-1)
def incTab(self, incby = 1):
if self.tabWidget.count() < 2:
return
idx = self.tabWidget.currentIndex()
idx += incby
if idx < 0:
idx = self.tabWidget.count()-1;
elif idx >= self.tabWidget.count():
idx = 0
self.tabWidget.setCurrentIndex(idx)
def setTabIcon(self, tab, icon):
idx = self.getTabIndex(tab)
if idx > -1:
self.tabWidget.setTabIcon(idx, icon)
def setTabTitle(self, tab, title):
idx = self.getTabIndex(tab)
if idx > -1:
if len(title) > self.maxTitleLen:
title = title[:self.maxTitleLen-3] + "..."
self.tabWidget.setTabText(idx, title)
def getTabIndex(self, tab):
for i in range(len(self.tabs)):
if tab == self.tabs[i]:
return i
return -1
def setupWebkit(self, webkit):
nam = webkit.page().networkAccessManager()
nam.authenticationRequired.connect(self.onAuthRequest)
nam.setCache(self.disk_cache)
nam.setCookieJar(self.cookie_jar)
self.cookie_jar.setParent(None)
self.disk_cache.setParent(None)
g = webkit.settings()
g.enablePersistentStorage(self.configdir)
def onAuthRequest(self, networkreply, authenticator):
cached = list(self.auth_cache.keys())
r = authenticator.realm()
if cached.count(r):
authenticator.setUser(self.auth_cache[r]["user"])
authenticator.setPassword(self.auth_cache[r]["password"])
else:
authdlg = AuthDialog(parent=self, icon=self.icons.QIcon("foobrowser"))
username, password = authdlg.prompt(networkreply.url().toString())
if username and password:
authenticator.setUser(username)
authenticator.setPassword(password)
self.auth_cache[r] = {"user":username, "password":password}
def closeEvent(self, e):
if len(self.tabs) > 1:
if QtGui.QMessageBox.question(self, "Confirm exit", "You have more than one tab open. Are you sure you want to exit?", QtGui.QMessageBox.Yes, QtGui.QMessageBox.No) == QtGui.QMessageBox.No:
e.ignore()
return
self.persistHistory()
self.persistConfig()
if self.disk_cache:
self.disk_cache.expire()
if self.cookie_jar:
self.cookie_jar.Persist()
e.accept()
self.close()
def log(self, s):
if self.debug:
print(s)
def persistHistory(self):
if self.configdir is None:
return
hfile = os.path.join(self.configdir, "history")
try:
fp = open(hfile, "w")
except Exception as e:
return
keys = list(self.history.keys())
keys.sort()
for k in keys[:self.maxHistory]: # only store up to the last maxHistory history points
fp.write("%s :: %s\n" % (time.strftime(self.historyDateFormat, k), self.history[k]))
fp.close()
def loadHistory(self):
self.history = {}
if self.configdir is None:
return
hfile = os.path.join(self.configdir, "history")
if os.path.isfile(hfile):
for line in open(hfile, "r"):
line = line.strip()
parts = line.split("::")
try:
k = time.strptime(parts[0].strip(), self.historyDateFormat)
hurl = "::".join(parts[1:]).strip()
self.history[k] = hurl
except Exception as e:
self.log(str(e))
pass
def LoadHistoryToCmb(self, cmb):
if self.configdir is None:
return
keys = list(self.history.keys())
keys.sort(reverse=True)
if keys:
cmb.addItem("")
items = []
for k in keys:
if self.history[k] in items:
continue
cmb.addItem(self.history[k])
items.append(self.history[k])
if keys:
cmb.setCurrentIndex(0)
def addHistory(self, url, when = None):
if when is None:
when = time.localtime()
self.history[when] = url
def mkGui(self):
self.layout().setSpacing(1)
self.setWindowTitle(self.appname)
self.tabWidget = QtGui.QTabWidget(self)
self.tabWidget.tabBar().setMovable(True)
self.tabWidget.setStyleSheet("padding: 2px; margin: 2px;")
self.setCentralWidget(self.tabWidget)
self.tabWidget.setTabsClosable(True)
self.connect(self.tabWidget, QtCore.SIGNAL("tabCloseRequested(int)"), self.delTab)
self.connect(self, QtCore.SIGNAL("refreshAll()"), self.refreshAll)
self.addTab()
def addTab(self, url = None):
tab = WebTab(browser=self, actions=self.tabactions, showStatusBar = self.showStatusBar)
self.tabWidget.addTab(tab, "New tab")
self.tabs.append(tab)
self.tabWidget.setCurrentWidget(tab)
if url:
tab.navigate(url)
else:
self.currentTabGo()
return self.tabs[self.tabWidget.currentIndex()]
def addDownload(self, url):
if type(self.downloader) == str:
# commandline
cmd = self.downloader.replace("%url%", "\"%s\"" % url)
retcode = subprocess.call(cmd)
if retcode:
if (QtGui.QMessageBox.question(self, "External downloader failure", "An attempt to invoke your external downloader with the command line:\n\n%s\n\nappears to have failed. Would you like to change the commandline to your external downloader?" % (cmd)) == QtGui.QMessageBox.Ok):
self.downloader = None
self.addDownload(url)
elif self.downloader is None:
# prompt the user
dlg = QtGui.QInputDialog()
lbltxt = "%s does not implement an internal download manager but will talk to external download managers which can be command-line driven.\n\nPlease enter a commandline for an external downloader. %%url%% in your command will be replaced with the url to download" % (self.appname)
commandline, ok = dlg.getText(self, "External downloader configuration", lbltxt)
commandline = commandline.strip()
if commandline == "" or ok == False:
if QtGui.QMessageBox.question(self, "External downloader problem", "You haven't specified an external downloader command line. This means the request to download %s can't be processed. Are you sure?" % (url), QtGui.QMessageBox.Yes, QtGui.QMessageBox.No) == QtGui.QMessageBox.Yes:
return
self.addDownload(url)
self.downloader = commandline
self.addDownload(url)
def fixUrl(self, url):
# look for "smart" google search
search = False
parts = url.split("://")
if len(parts) != 2 or (len(parts) == 2 and parts[0] not in ["http", "https", "ftp"]):
parts = url.split(" ") # multipl words == search
if len(parts) > 1:
search = True
hostname = url.split("/")[0]
parts = hostname.split(".") # hostname without periods == perhaps search
if len(parts) == 1:
try:
socket.gethostbyname(hostname) # if we can look up the host name, go for it
except:
search = True
if search:
url = "http://www.google.com/search?q=%s" % (url.replace(" ", "+"))
else:
try:
if url.index("about:") == 0:
return url
except:
if url.count("://") == 0:
url = "%s%s" % ("http://", url)
return url
def delTab(self, idx = -1):
if idx >= len(self.tabs):
return
if idx == -1:
idx = self.tabWidget.currentIndex()
t = self.tabs.pop(idx)
t.stop()
self.tabWidget.removeTab(idx)
t.deleteLater()
if len(self.tabs) == 0:
self.close()
def load(self, url):
if self.tabs[-1].URL() == "":
self.tabs[-1].navigate(url)
else:
self.addTab(url)
def refreshAll(self):
for t in self.tabs:
t.refresh()
def defaultCSS(self):
return " html {background-color: Window, color: WindowText}\ntable {border-collapse: collapse; margin: auto;}\ntd,th {border: 1px solid ThreeDDarkShadow; padding-left: 5px; padding-right: 5px}\n h1,h2,h3,h4,h5 {text-align: center;}"
def genAboutFoo(self):
return "<html><head><title>About %s</title><style>%s</style></head><body><h4>About %s</h4><p>%s is a dead-simple, lightweight tabbed web browser with support for:</p><ul><li>Disk cache</li><li>Persistent cookies</li><li>Plugin support (eg flash), where WebKit supports it</li><li>Re-orderable tabs</li><li>Browsing history (max %i items)</li><li>External download manager</li><li>Basic authentication for websites that require authentication</li></ul><p>%s would have been completely impossible without the giants upon whose shoulders it stands:</p><ul><li>Python</li><li>Qt (and PyQt4 in particular)</li><li>And, of course, Webkit</li></ul><p>%s was started as a fun project just to see what would be involved in creating a light browser out of the available powerful components. I hope that you find it useful!</p><p>Author: Davyd McColl (<a href=\"mailto:davydm@gmail.com\">davydm@gmail.com</a>)</body></html>" % (self.appname, self.appname, self.appname, self.appname, self.maxHistory, self.appname, self.appname)
def genHelp(self):
ret = ["<html><head><title>Help for: %s</title><style>%s</style></head><body><h4>Help for: <a href=\"about:foo\">%s</a></h4>" % (self.appname, self.defaultCSS(), self.appname)]
ret.extend(self.genActionTable(self.actions, "Application shortcuts"))
ret.append("<br/>")
ret.extend(self.genActionTable(self.tabactions, "Tab shortcuts"))
ret.append("</body></html>")
return "".join(ret)
def genActionTable(self, actions, title):
ret = []
ret.append("<h5>%s</h5><table>" % (title))
ret.append("<tr><th>Action</th><th>Shortcut</th></tr>")
data = {}
for action in actions:
shortcut = None
description = None
# each item is either a list of 3 elements:
# bound method, shortcut key, description
# or:
# bound method, shortcut key, bound object, description
shortcut = actions[action][1]
if len(actions[action]) == 3:
description = actions[action][2]
elif len(actions[action]) == 4:
description = actions[action][3]
if shortcut and description:
data[description] = shortcut
d = list(data.keys())
d.sort()
for desc in d:
ret.append("<tr><td>%s</td><td>%s</td></tr>" % (desc, data[desc]))
ret.append("</table>")
return ret
if __name__ == "__main__":
app = QtGui.QApplication([])
debug = False
if sys.argv[1:].count("-debug"):
debug = True
mainwin = MainWin(debug=debug)
mainwin.show()
for arg in sys.argv[1:]:
if arg not in ["-debug"]:
mainwin.load(arg)
app.exec_()
|
UTF-8
|
Python
| false | false | 2,012 |
9,491,877,735,057 |
8cbd87fec9b670555c1f9eef801d6ecf75697e17
|
c04e121306dd2c9d3081417f0f523e0b51fc4a8a
|
/trqacc/dynamicviews.py
|
c9818980ef2756fdb2ebe6eb68e5d7d26c5872f7
|
[] |
no_license
|
tomaso/goove
|
https://github.com/tomaso/goove
|
65484a8b9a4fca1a8c6f5b71d2175bd7954d693e
|
79fb05e0405d500f7af6cea6a285813af9c398d8
|
refs/heads/master
| 2016-09-06T08:25:14.829797 | 2012-04-05T15:37:28 | 2012-04-05T15:37:28 | 772,581 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null |
from django.http import HttpResponse,HttpResponseNotFound
from django.shortcuts import render_to_response
from django.utils import simplejson
from models import Node,SubCluster,BatchServer,Queue,Job
import live_updaters
testvar = 0
pbs_data_nodes = {}
def nodes_overview(request, batchserver_name=None,subcluster_name=None):
l = []
if request.GET.has_key('subcluster_name') and not subcluster_name:
subcluster_name = request.GET['subcluster_name']
if request.GET.has_key('batchserver_name') and not batchserver_name:
batchserver_name = request.GET['batchserver_name']
if not subcluster_name or not batchserver_name:
return HttpResponseNotFound()
updated_nodes = live_updaters.update_all_nodes(batchserver_name)
ns = Node.objects.filter(server__name=batchserver_name, subcluster__name=subcluster_name)
for n in ns:
th = "<table style='border: 1px'><tr>"
c = 0
for jobid in updated_nodes[batchserver_name]['nodes'][n]['jobs']:
th += "<td><a href='#'>%s</a> </td>" % jobid
if c%2 == 1:
th += "</tr><tr>"
c += 1
th += "</tr></table>"
l.append({
'name': n.name,
'shortname': n.shortname(),
'state': " ".join([un.name for un in updated_nodes[batchserver_name]['nodes'][n]['state']]),
'ttiphtml': th,
# 'jobs': [ j.job.jobid for j in n.jobslot_set.all() ]
})
return HttpResponse(simplejson.dumps(l))
def nodes_list(request, batchserver_name=None):
""" Return the list of nodes with properties """
l = []
if request.GET.has_key('batchserver_name') and not batchserver_name:
batchserver_name = request.GET['batchserver_name']
if not batchserver_name:
return HttpResponseNotFound()
updated_nodes = live_updaters.update_all_nodes(batchserver_name)
ns = Node.objects.filter(server__name=batchserver_name)
for n in ns:
if not n.isactive:
continue
l.append({
'name': n.name,
'state': ",".join([un.name for un in updated_nodes[batchserver_name]['nodes'][n]['state']]),
'properties': ",".join([un.name for un in updated_nodes[batchserver_name]['nodes'][n]['properties']]),
'subcluster': n.subcluster.name,
'cputmult': n.cputmult,
'wallmult': n.wallmult
})
return HttpResponse(simplejson.dumps(l))
def subclusters_list(request, batchserver_name=None):
""" Return just the list of subcluster names (optionally withing given batch server) """
l = []
if request.GET.has_key('batchserver_name') and not batchserver_name:
batchserver_name = request.GET['batchserver_name']
if batchserver_name:
scl = SubCluster.objects.filter(server__name=batchserver_name)
else:
scl = SubCluster.objects.all()
for i in scl.values_list('name'):
l.append({'name': i[0]})
return HttpResponse(simplejson.dumps(l))
def batchservers_list(request):
""" Return the list of batchserver hostnames """
bs = []
for i in BatchServer.objects.values_list('name'):
bs.append({'name': i[0]})
return HttpResponse(simplejson.dumps(bs))
def queues_list(request, batchserver_name=None):
global testvar
l = []
if request.GET.has_key('batchserver_name') and not batchserver_name:
batchserver_name = request.GET['batchserver_name']
if batchserver_name:
live_updaters.update_all_queues(batchserver_name)
ql = Queue.objects.filter(server__name=batchserver_name, obsolete=False)
else:
ql = Queue.objects.filter(obsolete=False)
testvar += 1
print testvar
for i in ql:
l.append({
'name': i.name,
'Q': i.state_count_queued,
'W': i.state_count_waiting,
'R': i.state_count_running,
'started': i.started,
'enabled': i.enabled,
'queue_type': i.queue_type,
'max_running': i.max_running,
'total_jobs': i.total_jobs
})
return HttpResponse(simplejson.dumps(l))
def jobs_list(request, batchserver_name=None):
if request.GET.has_key('batchserver_name') and not batchserver_name:
batchserver_name = request.GET['batchserver_name']
if not batchserver_name:
return HttpResponseNotFound()
updated_jobs = live_updaters.update_all_jobs(batchserver_name)
l = []
for jobid,data in updated_jobs[batchserver_name]['jobs'].items():
l.append({
'jobid': jobid,
'job_name': data['Job_Name'],
'queue': data['queue'].name,
'job_state': data['job_state'].name
})
return HttpResponse(simplejson.dumps(l))
# vi:ts=4:sw=4:expandtab
|
UTF-8
|
Python
| false | false | 2,012 |
19,189,913,888,602 |
950919985503f3f14e281d7d06d3ead5cbc273f5
|
da81672acff332966143b31a479e7cf3a2eee687
|
/downloaderClass.py
|
7d42068e9e0aed22a691ddcf605f4498fb84131e
|
[
"GPL-3.0-only"
] |
non_permissive
|
slawqo/logs_analyzer
|
https://github.com/slawqo/logs_analyzer
|
1b61d66e6fe094b00b4c562d206296a81cedc596
|
6fb11813394c83fc9ee0a73e8132b359d0685447
|
refs/heads/master
| 2021-01-10T20:18:43.214754 | 2013-07-04T11:33:11 | 2013-07-04T11:33:11 | null | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null |
#!/usr/bin/env python
#-*- coding: utf-8 -*-
'''
Created on 14-06-2012
@author: Sławek Kapłoński
@contact: slawek@kaplonski.pl
This file is part of Logs Analyzer.
Logs Analyzer 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.
Logs Analyzer 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 Logs Analyzer; if not, write to the Free Software
Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
Ten plik jest częścią Foobar.
Logs Analyzer jest wolnym oprogramowaniem; możesz go rozprowadzać dalej
i/lub modyfikować na warunkach Powszechnej Licencji Publicznej GNU,
wydanej przez Fundację Wolnego Oprogramowania - według wersji 2 tej
Licencji lub (według twojego wyboru) którejś z późniejszych wersji.
Niniejszy program rozpowszechniany jest z nadzieją, iż będzie on
użyteczny - jednak BEZ JAKIEJKOLWIEK GWARANCJI, nawet domyślnej
gwarancji PRZYDATNOŚCI HANDLOWEJ albo PRZYDATNOŚCI DO OKREŚLONYCH
ZASTOSOWAŃ. W celu uzyskania bliższych informacji sięgnij do
Powszechnej Licencji Publicznej GNU.
Z pewnością wraz z niniejszym programem otrzymałeś też egzemplarz
Powszechnej Licencji Publicznej GNU (GNU General Public License);
jeśli nie - napisz do Free Software Foundation, Inc., 59 Temple
Place, Fifth Floor, Boston, MA 02110-1301 USA
'''
from PyQt4 import QtCore
from urllib import error, request, parse
import os, sys, base64, datetime, calendar, gzip
from io import StringIO, BytesIO, TextIOBase
from exceptionClass import Exception
class downloader(QtCore.QThread):
homeDir = os.path.expanduser("~")
dataDir = ".logs_analyzer"
programDir = os.path.abspath(os.path.dirname(sys.argv[0]))
settings = None
main_address = "http://logs.ovh.net"
logs = ""
login = ""
password = ""
fileName = ""
download_finished = QtCore.pyqtSignal()
download_aborted = QtCore.pyqtSignal()
step_done = QtCore.pyqtSignal(object)
def __init__(self, settings):
QtCore.QThread.__init__(self)
self.today = datetime.date.today()
self.settings = settings
#definiowanie i tworzenie katalogów z danymi:
self.createAndLoadDirs()
def run(self):
self.downloadLogs()
self.download_finished.emit()
def stop(self):
if self.isRunning():
self.terminate()
self.download_aborted.emit()
def createAndLoadDirs(self):
self.logsDir = self.homeDir+"/"+self.dataDir+"/"+"logs"
if os.path.isdir(self.homeDir) == False:
os.makedirs(self.homeDir)
if os.path.isdir(self.logsDir) == False:
os.makedirs(self.logsDir)
def prepareFullFileName(self):
if self.settings.logs_type == "":
file_logs_type = "access"
else:
file_logs_type = self.settings.logs_type
if (self.settings.date_start == self.settings.date_end):
self.fileName = self.logsDir+"/"+self.settings.test_page+"_"+self.settings.date_start.strftime("%Y.%m.%d")+"-"+file_logs_type+".log"
else:
self.fileName = self.logsDir+"/"+self.settings.test_page+"_"+self.settings.date_start.strftime("%Y.%m.%d")+"-"+self.settings.date_end.strftime("%Y.%m.%d")+"-"+file_logs_type+".log"
def prepareAddress(self, day):
'''prepare logs file web address with correct date and server page name
arguments: datetime day
'''
if self.settings.logs_type == "":
logs_type = "/"
else:
logs_type = "/"+self.settings.logs_type+"/"
if day != self.today:
self.logs_address = self.main_address+"/"+self.settings.test_page+"/logs-"+day.strftime("%m")+"-"+day.strftime("%Y")+logs_type+self.settings.test_page+"-"+day.strftime("%d")+"-"+day.strftime("%m")+"-"+day.strftime("%Y")+".log.gz"
else:
self.logs_address = self.main_address+"/"+self.settings.test_page+"/osl"+logs_type+self.settings.test_page+"-"+day.strftime("%d")+"-"+day.strftime("%m")+"-"+day.strftime("%Y")+".log"
def prepareLoginData(self):
auth_handler = request.HTTPBasicAuthHandler()
auth_handler.add_password(realm='Statistiques Web. Utilisez votre identifiant pour vous connecter.',
uri="https://logs.ovh.net",
user=self.login,
passwd=self.password)
opener = request.build_opener(auth_handler)
# ...and install it globally so it can be used with urlopen.
request.install_opener(opener)
def loadPage(self):
try:
if len(self.login) != 0:
self.prepareLoginData()
opened_url = request.urlopen(self.logs_address)
self.page_handle = BytesIO(opened_url.read())
return 1
except error.HTTPError as er:
errMsg = str(er)
if "401" in errMsg:
return 401
elif "404" in errMsg:
return 404
else:
return -1
def loadLogsFromDay(self, day):
self.prepareAddress(day)
getPageResult = self.loadPage()
if getPageResult == 1:
if day == self.today:
result = self.page_handle.read()
else:
result = self.decompresFile()
else:
result = str(getPageResult)
if type(result) is str:
return result
else:
return result.decode("utf-8", "strict")
def downloadLogs(self):
if len(self.logs) == 0:
if self.settings.isLocalFile == False:
self.prepareFullFileName()
if (os.path.isfile(self.fileName) == False or self.today in self.settings.days_range) and self.settings.isLocalFile == False:
if (self.settings.date_start == self.settings.date_end):
result = self.loadLogsFromDay(self.settings.date_start)
else:
result = ""
percent_per_day = 100/len(self.settings.days_range)
counter = 0
for day in self.settings.days_range:
day_result = ""
day_result = self.loadLogsFromDay(day)
if day_result != "401" and day_result != "404" and day_result != "-1":
result = result+self.loadLogsFromDay(day)
elif day_result == "401":
self.logs = day_result
return self.logs
counter = counter + percent_per_day
print ("Downloaded: "+str(counter)+"%")
self.step_done.emit(counter)
sys.stdout.write("\n")
else:
result = open(self.fileName, "r").read()
self.logs = result
return self.logs
def getDownloadedLogs(self):
return self.logs
def saveLogs(self, fileName = ""):
if len(fileName) == 0:
self.prepareFullFileName()
else:
self.fileName = fileName
if len(self.logs) == 0:
self.downloadLogs()
if len(self.logs) > 3 :
out = open(self.fileName, "w")
out.write(self.logs)
out.close()
return self.fileName
def decompresFile(self):
params = parse.urlencode("")
if len(self.login) != 0:
self.prepareLoginData()
req = request.Request(self.logs_address)
handle = request.urlopen(req)
f = gzip.GzipFile(fileobj=self.page_handle)
return f.read()
def progressBar(self, progress):
sys.stdout.write('\r[{0}{1}] {2}%'.format('#'*(progress/1),'-'*((100-progress)/1), progress))
sys.stdout.flush()
def graphicalProgressBar(self, bar, progress):
bar.setValue(progress)
|
UTF-8
|
Python
| false | false | 2,013 |
2,078,764,201,333 |
8e0a841be804a0fd9d38a95e8380e306edf96495
|
c4a25d37ec4bc8357347202820ec416719d35331
|
/assistly/exceptions.py
|
a29353e7e7a34fd658caa2e0ab8d17a072d31c75
|
[
"BSD-2-Clause",
"BSD-3-Clause"
] |
permissive
|
marinho/python-assistly
|
https://github.com/marinho/python-assistly
|
1e7846622d3c7d727f0094141cff8f8819cfebc8
|
2506ff8c381ef580906024812e083164a879e692
|
refs/heads/master
| 2020-07-20T14:14:05.374280 | 2012-08-30T16:55:35 | 2012-08-30T16:55:35 | null | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null |
class AssistlyError(BaseException): pass
class ResourceNotFound(AssistlyError): pass
class AuthenticationError(AssistlyError): pass
class TemporarilyUnavailable(AssistlyError): pass
class InvalidReturn(AssistlyError): pass
|
UTF-8
|
Python
| false | false | 2,012 |
5,239,860,121,086 |
5d1856798e467888c8b819e9c9835f75ba807194
|
c97a8f6e447ee68a5be40f298d1a9e9564e7e91a
|
/test/test_symbol.py
|
875b1f3fdb447d166493ff23be5f44d7adc94cb0
|
[] |
no_license
|
frodwith/pysch
|
https://github.com/frodwith/pysch
|
0d78f8cbadbea7fb00ee3ef4f44a27695c87cb3e
|
87e85ebca1b09bed8c3dbd89c4fe7cf74fa99f0b
|
refs/heads/master
| 2021-01-15T13:44:58.666317 | 2009-03-05T01:33:36 | 2009-03-05T01:33:36 | 126,687 | 1 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null |
from pysch.atoms import get_symbol, Symbol
def test_class():
x = get_symbol('foo')
assert type(x) == Symbol
def test_equality():
x = get_symbol('foo')
y = get_symbol('foo')
assert x == y
def test_value():
x = get_symbol('foo')
assert x.string == 'foo'
def test_inequality():
x = get_symbol('foo')
y = get_symbol('bar')
assert x != y
|
UTF-8
|
Python
| false | false | 2,009 |
15,058,155,386,825 |
fc53c0ec23898152222313b217907dba6cb17c8a
|
75fff271731a304d0c17ef5c278b6aebade56ddb
|
/full_domain_personalisation/script/process/semu/listUnsubscribeHeader.py
|
65a62cf8d1ee83787a2e2f5924013b9df09fbb36
|
[
"MIT"
] |
permissive
|
AntonOfTheWoods/openemm-patches
|
https://github.com/AntonOfTheWoods/openemm-patches
|
36031126c541199b305ddf57fb494c1d806b1670
|
0c6325a3275be30005cdac161a9f0663830f1b55
|
refs/heads/master
| 2016-09-06T07:32:52.634546 | 2013-08-30T15:21:49 | 2013-08-30T15:21:49 | 12,160,827 | 1 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null |
__aps__ = {
'api': '1.0.0',
'version': '1.0',
'uri': None,
'urimatrix': None
}
import re
#
def handleOutgoingMail(ctx, mail):
urimatrix = __aps__['urimatrix']
uri = __aps__['uri']
if urimatrix or uri:
found = None
mid = None
for line in mail.head:
if line.lower().startswith('list-unsubscribe:'):
found = line
elif line.lower().startswith('message-id:'):
m = re.search(
'Message-ID: <(?P<mid>.*)@.*>', line)
mid = m.group(1)
if found is None:
try:
from urllib2 import quote
except ImportError:
from urllib import quote
data = {
'sender': mail.sender,
'urlsender': quote(mail.sender),
'recv': mail.receiver,
'urlrecv': quote(mail.receiver),
'mid': mid
}
isInMatrix = False
if urimatrix and not mid is None:
sDomain = mail.sender.rsplit('@', 1)[1]
for cline in urimatrix.split('\n'):
if cline.startswith(sDomain + '|'):
mail.head.append('List-Unsubscribe: <%s>, <%s>' % (
cline.split('|')[1] % data, cline.split('|')[2] % data, ))
isInMatrix = True
break
if uri and not isInMatrix:
mail.head.append(
'List-Unsubscribe: <%s>' % (uri % data, ))
if __name__ == '__main__':
def _main():
class struct:
pass
mail = struct()
mail.head = []
mail.sender = 'news@toto.com'
mail.receiver = 'someone@somewhere.com'
__aps__['uri'] = 'http://localhost/unsubscribe?%(urlrecv)s'
handleOutgoingMail(None, mail)
print mail.head[0]
mail.head = []
__aps__['urimatrix'] = 'news.example.com|mailto:DUN-%(urlrecv)s@lu.example.com|http://news.example.com?%(urlrecv)s\nletter.com|mailto:ext-%(urlrecv)s@localhost|http://localhost?%(urlrecv)s'
handleOutgoingMail(None, mail)
print mail.head[0]
_main()
|
UTF-8
|
Python
| false | false | 2,013 |
8,160,437,879,882 |
79be5f6683d03a699c348fa701e6606800b42a2f
|
f6ebc15fb39246d23bec26ce8a735dd9b473d40a
|
/fpuf/utils/my_utils.py
|
898733e6cc9c1d72154b2e1e9feb4e58a9029dbf
|
[
"LGPL-2.0-or-later",
"LGPL-2.1-or-later",
"GPL-3.0-or-later",
"GPL-1.0-or-later",
"LicenseRef-scancode-warranty-disclaimer",
"GPL-3.0-only"
] |
non_permissive
|
ctrl-alt-d/fpuf
|
https://github.com/ctrl-alt-d/fpuf
|
fc20e39a19c64150c8f27184b8bcfc8c8fdbf6eb
|
eb9ab19de2c571fa992e7c04f7d11af1b91d1dca
|
refs/heads/master
| 2018-12-31T21:14:11.798922 | 2013-11-27T10:03:40 | 2013-11-27T10:03:40 | null | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null |
# -*- encoding: utf-8 -*-
import random, string
from hashlib import sha1
def new_slug( n = 4 ):
slug = ''
for n in range(n):
slug += random.sample(string.ascii_uppercase, 1)[0]
return slug
def new_slug_h(n=5):
slug = new_slug(n-1)
slug += sha1(slug + "SUPERSECRET" ).hexdigest()[1].upper()
return slug
|
UTF-8
|
Python
| false | false | 2,013 |
5,617,817,244,025 |
750f0ae4dbcd06ab8e995c767e204be3e8855049
|
932b1e743e33aaed033953b37868b712388af642
|
/securityNode/pollForMotion.py
|
0500c1a6abcc0d23b775db53469c652ec2838c8f
|
[
"MIT"
] |
permissive
|
crowe20/ECE4564FinalProject
|
https://github.com/crowe20/ECE4564FinalProject
|
b9323e8c6029482371d200b3b61ca35a8891beb7
|
62de24ac7bde786edb555219ce50f8d489303700
|
refs/heads/master
| 2021-01-25T08:59:50.676846 | 2014-12-16T23:33:09 | 2014-12-16T23:33:09 | null | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null |
##########################################################################
#
#Constantly poll a gpio pin, waiting for it to go high.
#When it does, send a message via amqp saying motion is detected
#
#After 20 seconds of no motion, send a message via amqp saying that
#there is no longer any motion in the room
#
##########################################################################
import pika
import RPi.GPIO as GPIO
import time
sensorPin = 23 #gpio pin on pi to poll
GPIO.setmode(GPIO.BCM)
GPIO.setup(sensorPin, GPIO.IN)
#initial declarations
currState = False
prev = False
#cycle counters
motion = 0
still = 0
time.sleep(60) #let motion detector stabalize and server get running
#connect to the message broker and login
msg_broker = pika.BlockingConnection(
pika.ConnectionParameters(host="netapps.ece.vt.edu",
virtual_host="/2014/fall/observer",
credentials=pika.PlainCredentials("observer",
"N1ght|visi0N44",
True)))
#create the channel to be used
channel = msg_broker.channel()
channel.exchange_declare(exchange="msgexchange",
type="fanout")
try:
while True:
time.sleep(2)
currState = GPIO.input(sensorPin) #read pin
if currState: #motion has been detected
motion += 1 #increment motion cycle counter
still = 0 #reset still cycle counter
else:
still += 1 #increment still cycle counter
motion = 0 #reset motion cycle counter
if motion == 1 and not prev: #publish single motion message
channel.basic_publish(exchange="msgexchange",
routing_key='',
body="Node1,192.168.1.61:12894,Motion")
prev = True
if still == 10 and prev: #publish stop method
channel.basic_publish(exchange="msgexchange",
routing_key='',
body="Node1,192.168.1.61:12894,Stop")
prev = False
finally:
#close broker and exit
msg_broker.close()
|
UTF-8
|
Python
| false | false | 2,014 |
4,750,233,863,309 |
d9435dd9950716bce3e92d15cf61d90e0c2c039c
|
10a625c83ce522574d823dd50951e35b9ba38286
|
/octopus_user/utils.py
|
742306317b2f76cc7e2f51c76962e6a41427f75a
|
[] |
no_license
|
john-dwuarin/octopus_baskettt
|
https://github.com/john-dwuarin/octopus_baskettt
|
b3c9f795224a44bde6d8cca9fee891cf69b3bdee
|
d3c5ad972d89141cf68b74bbb3829b4e4e88d947
|
refs/heads/master
| 2020-04-15T11:10:34.987917 | 2014-05-30T19:34:02 | 2014-05-30T19:34:02 | null | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null |
import json
import string
import random
from haystack.query import SearchQuerySet
from octopus_groceries.models import *
from octopus_user.models import *
from django.http import HttpResponse
from django.conf import settings
# Function that finds the client http host and returns the right url
def get_client_url(request):
if not request:
return ""
else:
http_string = 'http://' if settings.DEBUG else 'https://'
return http_string + request.META["HTTP_HOST"] + '/'
def get_list_from_comma_separated_string(comma_separated_string):
# first get rid of the [ and ] from string
comma_separated_string = comma_separated_string[1:-1]
# then create the list from the string
return_list = comma_separated_string.split(", ")
return return_list
def save_user_settings(user):
user_settings = UserSettings()
user_settings.user = user
user_settings.default_supermarket = Supermarket.objects.get(name='waitrose')
user_settings.save()
return user_settings #will be none if user_settings is not found
def test_password_validation(request, data, ressource):
password = data['password']
password_confirm = data['password_confirm']
if password != password_confirm:
return ressource.create_response(request, {
#passwrd confirm doesn't match password
'reason': 'password_mismatch',
'success': False
})
elif len(password) < 8:
return ressource.create_response(request, {
#passwrd confirm doesn't match password
'reason': 'password_too_short',
'success': False
})
else:
return None
|
UTF-8
|
Python
| false | false | 2,014 |
7,146,825,597,192 |
f10007a93a496438befb55c1d8f730dc52a01381
|
8b8cfcdebd6611f20a3a7068cba56d5449deac9e
|
/dir_mapper.py
|
c01b65f03ef87e9b35456eeb88fcc4f435cf54a2
|
[] |
no_license
|
sumonsun/Hadoop
|
https://github.com/sumonsun/Hadoop
|
e2945197ba5828adc90daa7bc54f70c820c3f283
|
83970495136b0b743e86863e8531dbcd9ea0c8c0
|
refs/heads/master
| 2016-05-28T05:45:22.000103 | 2014-01-04T08:38:31 | 2014-01-04T08:38:31 | null | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null |
#!/usr/bin/env python
import sys
import re
import os
debug=False
#f=open("/tmp/sep-2013.txt","r")
arr={}
for line in sys.stdin:
m=re.search(r'GET',line)
if m:
fs=line.split('"')
tdirnm=''.join(fs[1:2])
t2dirnm=tdirnm.split()
t3dirnm=t2dirnm[1]
t4dirnm=os.path.split(t3dirnm)
dirnm=t4dirnm[0]
if(arr.has_key(dirnm)):
arr[dirnm]+=1
else:
arr.setdefault(dirnm,1)
#lines=f.readlines()
#for line in sys.stdin:
# ipaddress = re.compile(r'(((2[0-4]\d|25[0-5]|[01]?\d\d?)\.){3}(2[0-4]\d|25[0-5]|[01]?\d\d?))')
# match = ipaddress.match(line)
# if match:
# ip = match.group(1)
# if(arr.has_key(ip)):
# arr[ip]+=1
# else:
# arr.setdefault(ip,1)
#f.close()
for key in arr:
print key+"\t"+str(arr[key])
|
UTF-8
|
Python
| false | false | 2,014 |
15,470,472,211,192 |
ee776b0b146124036f291684e4abefc604dabd01
|
897d7aafdc3a7b903afea8a6aea77d1874f9ed0d
|
/tests/models/test_file_operation.py
|
331390bd3912bddc3f465d2c5a1c2124c79660d9
|
[] |
no_license
|
jafi666/pyCommander
|
https://github.com/jafi666/pyCommander
|
c402c0b6dcf93cce9170346e82e282b55d2545fd
|
5f7ab5b39c1dc7d8d2182048c5d8eaff04de3d06
|
refs/heads/master
| 2021-01-21T05:05:30.279892 | 2014-12-15T22:55:52 | 2014-12-15T22:55:52 | null | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null |
'''
Created on 12/08/2014
@author: Scarlen Quinsamolle
'''
import unittest
from models.file_operation import FileOperation
class TestFileOperation(unittest.TestCase):
def test_verify_that_it_returns_true_when_the_file_is_created_given_a_path_and_filename(self):
filemanager = FileOperation()
path = "C:/monitor/pyComander_1209/pyComander"
filename = "test.txt"
self.assertTrue(filemanager.create_file(path, filename))
def test_verify_that_it_returns_false_when_the_file_is_not_created_given_a_path_and_an_empty_filename(self):
filemanager = FileOperation()
path = "C:/monitor/pyComander_1209/pyComander"
filename = ""
self.assertFalse(filemanager.create_file(path, filename))
def test_verify_that_it_returns_false_when_the_file_is_not_created_given_an_wrong_path_and_a_filename(self):
filemanager = FileOperation()
path = "D:"
filename = "test.txt"
self.assertFalse(filemanager.create_file(path, filename))
if __name__ == "__main__":
unittest.main()
|
UTF-8
|
Python
| false | false | 2,014 |
489,626,307,051 |
f766c39cb4a5d7bff292b7e35ac7775c136b07ea
|
b4c08b9ca12d7ccc89d8c1d88db503141baf3890
|
/host/pcbwriter.py
|
6fe85da3ea119c8f5e681635486ec17ea9118253
|
[
"GPL-2.0-only"
] |
non_permissive
|
Topy44/pcbwriter
|
https://github.com/Topy44/pcbwriter
|
d663891cbc506804121edf7ec9f8283e518dc503
|
e930c1af7e44495313a2a82bd898593b3a3bf6d0
|
refs/heads/master
| 2021-01-17T20:56:50.630311 | 2014-03-24T02:20:40 | 2014-03-24T02:20:40 | null | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null |
import time
import array
import struct
import usb.core
import usb.util
class StepperStatus:
def __init__(self, s):
(self.flags, dummy, self.pos) = struct.unpack("BBh", s)
class PCBWriter:
PCBWRITER_TIMEOUT = 100 # ms
REQ_SET_SPEED = 0x80
REQ_ENABLE_DEBUG_OUT = 0x81
REQ_SET_PERSISTENT_FLASH = 0x82
REQ_GET_PERSISTENT_FLASH = 0x83
REQ_GET_STEPPER_STATUS = 0x90
REQ_HOME_STEPPER = 0x91
REQ_MOVE_STEPPER = 0x92
REQ_STEPPER_OFF = 0x93
REQ_SET_N_SCANS = 0xA0
REQ_SET_AUTOSTEP = 0xA1
REQ_CAN_SEND = 0xC0
def __init__(self, called_from_gui=False):
self.dev = usb.core.find(idVendor = 0x1337, idProduct = 0xabcd)
if self.dev is None and not called_from_gui:
raise RuntimeError("Device not found")
def __del__(self):
if self.dev is not None:
self.stepper_off()
def find_device(self):
self.dev = usb.core.find(idVendor = 0x1337, idProduct = 0xabcd)
def set_n_scans(self, n_scans): # Scans per line (exposure time)
self.dev.ctrl_transfer(bmRequestType=0xC0, bRequest=self.REQ_SET_N_SCANS, wValue=n_scans, wIndex=0, data_or_wLength=0, timeout=1000)
def set_autostep(self, autostep):
self.dev.ctrl_transfer(bmRequestType=0xC0, bRequest=self.REQ_SET_AUTOSTEP, wValue=autostep, wIndex=0, data_or_wLength=0, timeout=1000)
def put_line(self, data, wait=True, fill=False):
if wait:
# Wait for line to become ready
while not self.dev.ctrl_transfer(bmRequestType=0xC0, bRequest=self.REQ_CAN_SEND, wValue=0, wIndex=0, data_or_wLength=4, timeout=1000)[0]:
pass
if len(data) > 6000:
raise ValueError
if self.dev.write(1, data, 0, self.PCBWRITER_TIMEOUT) != len(data):
raise RuntimeError, "Failed to communicate with endpoint."
if fill:
if self.dev.write(1, array.array("B", [0]*(6000-len(data))).tostring(), 0, self.PCBWRITER_TIMEOUT) != (6000 - len(data)):
raise RuntimeError, "Failed to communicate with endpoint."
def get_stepper_status(self):
return StepperStatus(self.dev.ctrl_transfer(bmRequestType=0xC0, bRequest=self.REQ_GET_STEPPER_STATUS, wValue=0, wIndex=0, data_or_wLength=4, timeout=1000))
def get_stepper_busy(self):
return bool(self.get_stepper_status().flags & 0x01)
def get_stepper_homed(self):
return bool(self.get_stepper_status().flags & 0x02)
def home_stepper(self, wait=False):
self.dev.ctrl_transfer(bmRequestType=0xC0, bRequest=self.REQ_HOME_STEPPER, wValue=0, wIndex=0, data_or_wLength=0, timeout=1000)
if wait:
while self.get_stepper_busy():
time.sleep(0.1)
def move_stepper(self, pos, relative, wait=False): # Move stepper (1/600" in prototype), relative move if relative == True
self.dev.ctrl_transfer(bmRequestType=0xC0, bRequest=self.REQ_MOVE_STEPPER, wValue=pos, wIndex=relative, data_or_wLength=0, timeout=1000)
if wait:
while self.get_stepper_busy():
time.sleep(0.1)
def stepper_off(self):
self.dev.ctrl_transfer(bmRequestType=0xC0, bRequest=self.REQ_STEPPER_OFF, wValue=0, wIndex=0, data_or_wLength=0, timeout=1000)
|
UTF-8
|
Python
| false | false | 2,014 |
3,796,751,104,203 |
a8b738187ed11a9bbb2633e08883828b340aee6a
|
35c07d36820759a0557d50f227456a415fe72e71
|
/tests/test_views_integration.py
|
c73d9c219ead06505e847cfe6b9147d4eefda802
|
[] |
no_license
|
damichael/python_blog
|
https://github.com/damichael/python_blog
|
38646dcab0f36cbc0a14f51bf8f665984c10ebc3
|
7d23d408b4f81cff199bac8a44993bc14cd8abfc
|
refs/heads/master
| 2018-10-29T18:20:19.573280 | 2014-11-12T04:38:27 | 2014-11-12T04:38:27 | null | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null |
__author__ = 'damichael'
from unittest import TestCase
from urlparse import urlparse
from flask import current_app
from bson.objectid import ObjectId
from app import create_app, db
class TestViews(TestCase):
def setUp(self):
# creates an app configured for testing
self.app = create_app('testing')
self.app_context = self.app.app_context()
self.app_context.push()
self.client = self.app.test_client()
# create a user
self.user_id = db.user.seed()
def tearDown(self):
self.app_context.pop()
""" Note:
as a practice, I'm a bit hesitant to drop the collections here...
there is too much chance of dropping production data
if there is a configuration error!
"""
def test_app_exists(self):
self.assertFalse(current_app is None)
def test_app_is_using_testing_config(self):
self.assertTrue(current_app.config['TESTING'])
config = current_app.config['MONGODB_DATABASE']
self.assertEqual(config, 'blog_test')
def test_about_page(self):
response = self.client.get('/about')
self.assertTrue(b'Thinkful' in response.data)
def simulate_login(self):
with self.client.session_transaction() as http_session:
http_session["user_id"] = str(self.user_id)
http_session["_fresh"] = True
def test_add_post(self):
# logs-in and adds a post
self.simulate_login()
title = str(ObjectId())
response = self.client.post("/post/add", data={
"title": title,
"content": "integration test content"
})
self.assertEqual(response.status_code, 302)
self.assertEqual(urlparse(response.location).path, "/posts/")
post = db.post.get_by_title(title)
self.assertEqual(post.title, title)
self.assertEqual(post.content, "<p>integration test content</p>\n")
self.assertEqual(post.user_id, self.user_id)
|
UTF-8
|
Python
| false | false | 2,014 |
11,081,015,626,093 |
19f8b1a497ee895984d3739bc139b5f0d9c3442c
|
e9987d8b88c39c56281c9553142c3a36c66086c5
|
/mysite/customs/ohloh.py
|
f69cabbb43d6a14dea84ec8389825404f3cd07d8
|
[] |
no_license
|
rafpaf/OpenHatch
|
https://github.com/rafpaf/OpenHatch
|
43efad73a9cd7d913285e431ce5a021a1f0cb234
|
2f84ee1d572bb07cbd27e755ecfe786bc09effe1
|
refs/heads/master
| 2016-09-05T14:47:14.654445 | 2010-06-11T17:20:56 | 2010-06-11T17:23:30 | 687,353 | 6 | 1 | null | null | null | null | null | null | null | null | null | null | null | null | null |
import mysite.base.unicode_sanity
import xml.etree.ElementTree as ET
import xml.parsers.expat
import sys, urllib, hashlib
import urllib2
import cStringIO as StringIO
from urlparse import urlparse
from urllib2 import HTTPError
from django.conf import settings
import mysite.customs.models
def uni_text(s):
if type(s) == unicode:
return s
return s.decode('utf-8')
import lxml.html
import mechanize
import re
from typecheck import accepts, returns
from typecheck import Any as __
def mechanize_get(url, referrer=None, attempts_remaining=6, person=None):
"""Input: Some stuff regarding a web URL to request.
Output: A browser instance that just open()'d that, plus an unsaved
WebResponse object representing that browser's final state."""
web_response = mysite.customs.models.WebResponse()
b = mechanize.Browser()
b.set_handle_robots(False)
addheaders = [('User-Agent',
'Mozilla/4.0 (compatible; MSIE 5.0; Windows 98; (compatible;))')]
if referrer is not None:
b.set_handle_referer(False)
addheaders.extend([('Referer',
referrer)])
b.addheaders = addheaders
try:
b.open(url)
except HTTPError, e:
# FIXME: Test with mock object.
if (e.code == 504 or e.code == 502) and attempts_remaining > 0:
message_schema = "Tried to talk to %s, got %d, retrying %d more times..."
long_message = message_schema % (url, e.code, attempts_remaining)
print >> sys.stderr, long_message
if person:
short_message = message_schema % (urlparse(url).hostname,
e.code, attempts_remaining)
person.user.message_set.create(message=short_message)
return mechanize_get(url, referrer, attempts_remaining-1, person)
else:
raise
return b
def generate_contributor_url(project_name, contributor_id):
return 'https://www.ohloh.net/p/%s/contributors/%d' % (
project_name.lower(), contributor_id)
def ohloh_url2data(url, selector, params = {}, many = False, API_KEY = None, person=None):
'''Input: A URL to get,
a bunch of parameters to toss onto the end url-encoded,
many (a boolean) indicating if we should return a list of just one datum,
API_KEY suggesting a key to use with Ohloh, and a
Person object to, if the request is slow, log messages to.
Output: A list/dictionary of Ohloh data plus a saved WebResponse instance that
logs information about the request.'''
if API_KEY is None:
API_KEY = settings.OHLOH_API_KEY
my_params = {u'api_key': unicode(API_KEY)}
my_params.update(params)
params = my_params ; del my_params
# FIXME: We return more than just "ret" these days! Rename this variable.
ret = []
encoded = mysite.base.unicode_sanity.urlencode(params)
url += encoded
try:
b = mechanize_get(url, person)
web_response = mysite.customs.models.WebResponse.create_from_browser(b)
web_response.save() # Always save the WebResponse, even if we don't know
# that any other object will store a pointer here.
except urllib2.HTTPError, e:
# FIXME: Also return a web_response for error cases
if str(e.code) == '404':
if many:
return [], None
return {}, None
else:
raise
try:
s = web_response.text
tree = ET.parse(StringIO.StringIO(s))
except xml.parsers.expat.ExpatError:
# well, I'll be. it doesn't parse.
return None, web_response
# Did Ohloh return an error?
root = tree.getroot()
if root.find('error') is not None:
raise ValueError, "Ohloh gave us back an error. Wonder why."
interestings = root.findall(selector)
for interesting in interestings:
this = {}
for child in interesting.getchildren():
if child.text:
this[unicode(child.tag)] = uni_text(child.text)
ret.append(this)
if many:
return ret, web_response
if ret:
return ret[0], web_response
return None, web_response
class Ohloh(object):
def get_latest_project_analysis_id(self, project_name):
""" Retrieve from Ohloh.net the latest project
analysis id for a given project."""
# {{{
url = 'https://www.ohloh.net/p/%s/analyses/latest.xml?' % urllib.quote(
project_name)
data, web_response = ohloh_url2data(url, 'result/analysis')
return int(data['id'])
# }}}
def project_id2projectdata(self, project_id=None, project_name=None):
if project_name is None:
project_query = str(int(project_id))
else:
project_query = str(project_name)
url = 'http://www.ohloh.net/projects/%s.xml?' % urllib.quote(
project_query)
data, web_response = ohloh_url2data(url=url, selector='result/project')
return data
def project_name2projectdata(self, project_name_query):
url = 'http://www.ohloh.net/projects.xml?'
args = {u'query': unicode(project_name_query)}
data, web_response = ohloh_url2data(url=unicode(url),
selector='result/project',
params= args,
many=True)
# Sometimes when we search Ohloh for e.g. "Debian GNU/Linux", the project it gives
# us back as the top-ranking hit for full-text relevance is "Ubuntu GNU/Linux." So here
# we see if the project dicts have an exact match by project name.
if not data:
return None # If there is no matching project possibilit at all, get out now.
exact_match_on_project_name = [ datum for datum in data
if datum.get('name', None).lower() == project_name_query.lower()]
if exact_match_on_project_name:
# If there's an exact match on the project name, return this datum
return exact_match_on_project_name[0]
# Otherwise, trust Ohloh's full-text relevance ranking and return the first hit
return data[0]
@accepts(object, int)
def analysis2projectdata(self, analysis_id):
data, web_response = self.analysis_id2analysis_data(analysis_id)
proj_id = data['project_id']
return self.project_id2projectdata(int(proj_id))
@accepts(object, int)
def analysis_id2analysis_data(self, analysis_id):
url = 'http://www.ohloh.net/analyses/%d.xml?' % analysis_id
data, web_response = ohloh_url2data(url=url, selector='result/analysis')
return data, web_response
def get_contribution_info_by_username(self, username, person=None):
'''Input: A username. We go out and ask Ohloh, "What repositories
have you indexed where that username was a committer?"
Optional: a Person model, which is used to log messages to the user
in case Ohloh is being slow.
Output: A list of ContributorFact dictionaries, plus an instance (unsaved)
of the WebResponse class, which stores raw information on the response
such as the response data and HTTP status.'''
data = []
url = 'http://www.ohloh.net/contributors.xml?'
c_fs, web_response = ohloh_url2data(
url=url, selector='result/contributor_fact',
params={u'query': unicode(username)}, many=True, person=person)
# For each contributor fact, grab the project it was for
for c_f in c_fs:
if 'analysis_id' not in c_f:
continue # this contributor fact is useless
# Ohloh matches on anything containing the username we asked for as a substring,
# so check that the contributor fact actually matches the whole string (case-insensitive).
if username.lower() != c_f['contributor_name'].lower():
continue
eyedee = int(c_f['analysis_id'])
project_data = self.analysis2projectdata(eyedee)
permalink = generate_contributor_url(
project_data['name'],
int(c_f['contributor_id']))
this = dict(
project=project_data['name'],
project_homepage_url=project_data.get('homepage_url', None),
permalink=permalink,
primary_language=c_f.get('primary_language_nice_name', ''),
man_months=int(c_f['man_months']))
data.append(this)
return data, web_response
def get_name_by_username(self, username):
url = 'https://www.ohloh.net/accounts/%s.xml?' % urllib.quote(username)
account_info, web_response = ohloh_url2data(url, 'result/account')
if 'name' in account_info:
return account_info['name']
raise ValueError
def get_contribution_info_by_username_and_project(self, project, username):
# FIXME: this applies to a whole bunch of methods in this class. this
# logic is extremely duplicated. ech.
ret = []
url = 'http://www.ohloh.net/p/%s/contributors.xml?' % project
c_fs, web_response = ohloh_url2data(url, 'result/contributor_fact',
{'query': username}, many=True)
# Filter these guys down and be sure to only return the ones
# where contributor_name==username
for c_f in c_fs:
if 'analysis_id' not in c_f:
continue # this contributor fact is useless
eyedee = int(c_f['analysis_id'])
project_data = self.analysis2projectdata(eyedee)
this = dict(
project=project_data['name'],
project_homepage_url=project_data.get('homepage_url', None),
primary_language=c_f.get('primary_language_nice_name', ''),
man_months=int(c_f['man_months']))
ret.append(this)
return ret
def get_contribution_info_by_email(self, email):
# FIXME: Return a WebResponse too
ret = []
ret.extend(self.search_contribution_info_by_email(email))
ret.extend(self.get_contribution_info_by_ohloh_username(
self.email_address_to_ohloh_username(email)))
return ret
def email_address_to_ohloh_username(self, email):
hasher = hashlib.md5(); hasher.update(email)
hashed = hasher.hexdigest()
url = 'https://www.ohloh.net/accounts/%s' % urllib.quote(hashed)
try:
b = mechanize_get(url)
except urllib2.HTTPError:
# well, it failed. get outta here
return None
parsed = lxml.html.parse(b.response()).getroot()
one, two = parsed.cssselect('h1 a')[0], parsed.cssselect('a.avatar')[0]
href1, href2 = one.attrib['href'], two.attrib['href']
assert href1 == href2
parts = filter(lambda s: bool(s), href1.split('/'))
assert len(parts) == 2
assert parts[0] == 'accounts'
username = parts[1]
return username
def get_contribution_info_by_ohloh_username(self, ohloh_username, person=None):
# FIXME: This doesn't return any WebResponse. How sad.
# In branch pf2_with_webresponse_m2m, we are working on linking DIAs with multiple WebResponses,
# after which we intend to return a list of WebResponses, or something like that.
if ohloh_username is None:
return [], None
b = mechanize.Browser()
b.set_handle_robots(False)
b.addheaders = [('User-Agent',
'Mozilla/4.0 (compatible; MSIE 5.0; Windows 98; (compatible;))')]
try:
b.open('https://www.ohloh.net/accounts/%s' % urllib.quote(ohloh_username))
except urllib2.HTTPError, e:
if str(e.code) == '404':
return [], None
else:
raise
root = lxml.html.parse(b.response()).getroot()
relevant_links = root.cssselect('a.position')
relevant_hrefs = [link.attrib['href'] for link in relevant_links if '/contributors/' in link.attrib['href']]
relevant_project_and_contributor_id_pairs = []
# FIXME: do more logging here someday?
for href in relevant_hrefs:
project, contributor_id = re.split('[/][a-z]+[/]', href, 1
)[1].split('/contributors/')
relevant_project_and_contributor_id_pairs.append(
(project, int(contributor_id)))
ret = []
for (project, contributor_id) in relevant_project_and_contributor_id_pairs:
url = 'https://www.ohloh.net/p/%s/contributors/%d.xml?' % (
urllib.quote(project), contributor_id)
c_fs, web_response = ohloh_url2data(url, 'result/contributor_fact', many=True)
# For each contributor fact, grab the project it was for
for c_f in c_fs:
if 'analysis_id' not in c_f:
continue # this contributor fact is useless
eyedee = int(c_f['analysis_id'])
project_data = self.analysis2projectdata(eyedee)
permalink = generate_contributor_url(
project, contributor_id)
this = dict(
project=project_data['name'],
project_homepage_url=project_data.get('homepage_url', None),
permalink=permalink,
primary_language=c_f.get(
'primary_language_nice_name',''),
man_months=int(c_f.get('man_months',0)))
ret.append(this)
return ret, None
def search_contribution_info_by_email(self, email):
ret = []
url = 'http://www.ohloh.net/contributors.xml?'
c_fs, web_response = ohloh_url2data(url, 'result/contributor_fact',
{u'query': unicode(email)}, many=True)
# For each contributor fact, grab the project it was for
for c_f in c_fs:
if 'analysis_id' not in c_f:
continue # this contributor fact is useless
eyedee = int(c_f['analysis_id'])
project_data = self.analysis2projectdata(eyedee)
this = dict(
project=project_data['name'],
project_homepage_url=project_data.get('homepage_url', None),
primary_language=c_f.get('primary_language_nice_name', ''),
man_months=int(c_f['man_months']))
ret.append(this)
return ret
def get_icon_for_project(self, project):
try:
return self.get_icon_for_project_by_id(project)
except ValueError:
return self.get_icon_for_project_by_human_name(project)
def get_icon_for_project_by_human_name(self, project):
"""@param project: the name of a project."""
# Do a real search to find the project
try:
data = self.project_name2projectdata(project)
except urllib2.HTTPError, e:
raise ValueError
try:
med_logo = data['medium_logo_url']
except TypeError:
raise ValueError, "Ohloh gave us back nothing."
except KeyError:
raise ValueError, "The project exists, but Ohloh knows no icon."
# The URL is often something like s3.amazonws.com/bits.ohloh.net/...
# But sometimes Ohloh has a typo in their URLs.
if '/bits.ohloh.net/' not in med_logo:
med_logo = med_logo.replace('attachments/',
'bits.ohloh.net/attachments/')
b = mechanize_get(med_logo)
return b.response().read()
def get_icon_for_project_by_id(self, project):
try:
data = self.project_id2projectdata(project_name=project)
except urllib2.HTTPError, e:
raise ValueError
try:
med_logo = data['medium_logo_url']
except KeyError:
raise ValueError, "The project exists, but Ohloh knows no icon."
if '/bits.ohloh.net/' not in med_logo:
med_logo = med_logo.replace('attachments/',
'bits.ohloh.net/attachments/')
b = mechanize_get(med_logo)
return b.response().read()
_ohloh = Ohloh()
def get_ohloh():
return _ohloh
# vim: set nu:
|
UTF-8
|
Python
| false | false | 2,010 |
824,633,755,552 |
8c740ae0a62b2f7937b2ce7ffa12c272c1eb1795
|
764f15f2353cb3a29dae92e2cf91d4f02ba26ea6
|
/juegotruco/truco/test_varios_jugadores.py
|
7427f9236387001191b6b1f491fa851b79847e34
|
[
"MIT"
] |
permissive
|
germanferrero/truco
|
https://github.com/germanferrero/truco
|
f9d7c251485d4260b7a2f69b6ca0beacfea00706
|
b073f1cbb6c44b00a3b6651e7dda0f3a419a9710
|
refs/heads/master
| 2021-01-22T03:53:50.046818 | 2014-11-21T02:01:44 | 2014-11-21T02:01:44 | 81,470,431 | 1 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null |
from django.test import TestCase
from django.contrib.auth import authenticate, login, logout
from django.contrib.auth.models import User
from truco.constants import *
from truco.models import *
class TrucoTests(TestCase):
"""
Creamos nuevos elementos en la base de datos para hacer los tests
"""
def setUp(self):
#Creo usuarios
user1 = User.objects.create_user(username='test_user1', email='email@email.com',
password='asdf', )
user1.save()
user2 = User.objects.create_user(username='test_user2', email='email2@email.com',
password='asdf', )
user2.save()
user3 = User.objects.create_user(username='test_user3', email='email3@email.com',
password='asdf', )
user3.save()
user4 = User.objects.create_user(username='test_user4', email='email4@email.com',
password='asdf', )
user4.save()
user5 = User.objects.create_user(username='test_user5', email='email5@email.com',
password='asdf', )
user5.save()
user6 = User.objects.create_user(username='test_user6', email='email6@email.com',
password='asdf', )
user6.save()
lobby = Lobby()
#Creo partidas
partida1 = lobby.crear_partida(user=user1, nombre='Partida1 a 15 para 4 jugadores con un usuario',
puntos_objetivo=15, cantidad_jugadores=4)
partida1.save()
partida2 = lobby.crear_partida(user=user1, nombre='Partida2 a 30 con 4 jugadores',
puntos_objetivo=15, cantidad_jugadores=4)
# Agrego jugadores a la partida
lobby.unirse_partida(user2, partida2)
lobby.unirse_partida(user3, partida2)
lobby.unirse_partida(user4, partida2)
partida2.save()
# Actualizo el estado de la partida
partida2.actualizar_estado()
partida3 = lobby.crear_partida(user=user1, nombre='Partida3 a 30 con 6 jugadores',
puntos_objetivo=15, cantidad_jugadores=6)
partida3.save()
# Agrego jugadores a la partida
lobby.unirse_partida(user2, partida3)
lobby.unirse_partida(user3, partida3)
lobby.unirse_partida(user4, partida3)
lobby.unirse_partida(user5, partida3)
lobby.unirse_partida(user6, partida3)
# Actualizo el estado de la partida
partida3.actualizar_estado()
#Creo las cartas
valor_otro = 7
for palo_carta in range(1, 5):
for numero in range(1, 13):
if numero != 8 and numero != 9:
nombre_carta = str(numero) + " " + 'de' + "" + str(palo_carta)
if nombre_carta == "1 de 1":
valor_jer = 1
elif nombre_carta == '1 de 2':
valor_jer = 2
elif nombre_carta == '7 de 1':
valor_jer = 3
elif nombre_carta == '7 de 3':
valor_jer = 4
else:
valor_jer = valor_otro
if numero == 10 or numero == 11 or numero == 12:
envido = 0
else:
envido = numero
carta = Carta.objects.create(nombre=nombre_carta, valor_jerarquico=valor_jer,
valor_envido=envido, palo=palo_carta, imagen=nombre_carta)
carta.save()
valor_otro = valor_otro-1
if valor_otro == 4:
valor_otro = 14
"""
Test que verifica que la lista de partidas disponibles se cree cuando se crea
una nueva partida, pero que deje de estar cuando se hayan unido todos los jugadores a la partida
"""
def test_listas_partidas(self):
#Creo una lista para compararla con la real
lista_partidas = []
lobby = Lobby()
partida = Partida.objects.get(nombre='Partida1 a 15 para 4 jugadores con un usuario')
user1 = User.objects.get(username='test_user1')
user2 = User.objects.get(username='test_user2')
user3 = User.objects.get(username='test_user3')
user4 = User.objects.get(username='test_user4')
# Agrego las partidas a la partida para compraralas luego
lista_partidas.append(partida)
# Me fijo que esten las dos partidas
self.assertEqual(lista_partidas, list(lobby.get_lista_partidas()))
# Agrego losjugadores a la partida, por lo tanto debe salir de la lista disponibles
lobby.unirse_partida(user2, partida)
lobby.unirse_partida(user3, partida)
lobby.unirse_partida(user4, partida)
# Actualizo el estado de la partida
partida.actualizar_estado()
# Lo remuevo de la lista auxiliar
lista_partidas.remove(partida)
# Compruebo que no esta en la lista de partidas en espera
self.assertEqual(lista_partidas, list(lobby.get_lista_partidas()))
"""
Test que se fija que una partida creada tiene seteado el estado en "EN_ESPERA".
Luego agrega un jugador nuevo a la partida y testea que se cambie el estado a "EN_CURSO"'''
"""
def test_estado_partidas(self):
lobby = Lobby()
partida = Partida.objects.get(nombre='Partida1 a 15 para 4 jugadores con un usuario')
# Usuarios para agregar a la partida
user2 = User.objects.get(username='test_user2')
user3 = User.objects.get(username='test_user3')
user4 = User.objects.get(username='test_user4')
# La partida esta en espera hasta que se una un nuevo jugador
self.assertEqual(partida.estado, EN_ESPERA)
#Agrego un nuevo jugador
lobby.unirse_partida(user2, partida)
lobby.unirse_partida(user3, partida)
lobby.unirse_partida(user4, partida)
# Seteo el estado de la partida
partida.actualizar_estado()
# La partida debe estar en curso una vez que tenga dos jugadores
self.assertEqual(partida.estado, EN_CURSO)
def test_crear_ronda(self):
user2 = User.objects.get(username='test_user2')
user3 = User.objects.get(username='test_user3')
user4 = User.objects.get(username='test_user4')
partida = Partida.objects.get(nombre='Partida1 a 15 para 4 jugadores con un usuario')
lobby = Lobby()
# Agrego los jugadores a la partida
lobby.unirse_partida(user2, partida)
lobby.unirse_partida(user3, partida)
lobby.unirse_partida(user4, partida)
# Actualizo el estado de la partida
partida.actualizar_estado()
# La partida debe estar lista para crear una ronda
self.assertTrue(partida.is_ready())
#Creo una ronda en la partida
ronda = partida.crear_ronda()
# Testeo que se haya creado una ronda
self.assertNotEqual(list(partida.ronda_set.all()), [])
# Obtengo los jugadores
jugadores = list(partida.jugadores.all())
# Chequeo que se les hayan asignado 3 cartas a cada uno
self.assertEqual(len((jugadores[0].cartas.all())), 3)
self.assertEqual(len((jugadores[1].cartas.all())), 3)
self.assertEqual(len((jugadores[2].cartas.all())), 3)
self.assertEqual(len((jugadores[3].cartas.all())), 3)
# Chequeo que la mano sea el que esta en la posicion 0 (El que creo la partida)
self.assertEqual(ronda.mano_pos, 0)
# Obtengo la ultima ronda
ronda = partida.get_ronda_actual()
# Obtengo las opciones que tengo para cantar
opciones = ronda.get_opciones()
# Chequeo que la opcion que este disponible sea solo cantar envido
self.assertTrue(ENVIDO in opciones)
self.assertTrue(REAL_ENVIDO in opciones)
self.assertTrue(FALTA_ENVIDO in opciones)
self.assertTrue(IRSE_AL_MAZO in opciones)
"""
Verifica que los puntos cuando se canta retruco o vale cuatro se sumen correctamente
"""
def test_truco_retruco_y_valecuatro(self):
# Nueva ronda
ronda, partida, jugadores = self.aux_truco_nueva_ronda()
# Se canta truco, se responde retruco y se acepta
ronda.crear_canto(TRUCO, jugadores[0], partida.get_min_pts_restantes())
canto = ronda.get_ultimo_canto()
canto.aumentar(RETRUCO, jugadores[4].posicion_mesa)
canto = ronda.get_ultimo_canto()
canto.aceptar()
# Obtenemos los puntajes antes y despues de la ronda
puntaje1 = partida.puntos_e1
puntaje2 = partida.puntos_e2
ganador = self.aux_truco_terminar_ronda(ronda, jugadores, partida)
if ganador == jugadores[0].equipo: # Puntos antes de terminar la ronda
puntaje_antes = puntaje1
else:
puntaje_antes = puntaje2
partida.actualizar_puntajes() # Se actualizan los puntajes de la ronda
if ganador == jugadores[0].equipo: # Puntos despues de terminar la ronda
puntaje_despues = partida.puntos_e1
else:
puntaje_despues = partida.puntos_e2
# Verificamos que se le den los 3 puntos al gandor del retruco
self.assertEqual(puntaje_despues, puntaje_antes + 3)
# Nueva ronda
ronda, partida, jugadores = self.aux_truco_nueva_ronda()
puntaje = partida.puntos_e2
# Se canta truco, se responde retruco y se rechaza
ronda.crear_canto(TRUCO, jugadores[0], partida.get_min_pts_restantes())
canto = ronda.get_ultimo_canto()
canto.aumentar(RETRUCO, jugadores[5].posicion_mesa)
canto = ronda.get_ultimo_canto()
canto.rechazar()
# Si se rechaza corresponde 2 punto para el otro jugador
partida.actualizar_puntajes() # Se actualizan los puntajes de la ronda
self.assertEqual(partida.puntos_e2, puntaje + 2)
# Nueva ronda
ronda, partida, jugadores = self.aux_truco_nueva_ronda()
# Se canta truco, se responde retruco y vale cuatro y se acepta
ronda.crear_canto(TRUCO, jugadores[0], partida.get_min_pts_restantes())
canto = ronda.get_ultimo_canto()
canto.aumentar(RETRUCO, jugadores[4].posicion_mesa)
canto = ronda.get_ultimo_canto()
canto.aumentar(VALE_CUATRO, jugadores[5].posicion_mesa)
canto = ronda.get_ultimo_canto()
canto.aceptar()
# Obtenemos los puntajes antes y despues de la ronda
puntaje1 = partida.puntos_e1
puntaje1 = partida.puntos_e1
puntaje2 = partida.puntos_e2
ganador = self.aux_truco_terminar_ronda(ronda, jugadores, partida)
if ganador == jugadores[0].equipo: # Puntos antes de terminar la ronda
puntaje_antes = puntaje1
else:
puntaje_antes = puntaje2
partida.actualizar_puntajes() # Se actualizan los puntajes de la ronda
if ganador == jugadores[0].equipo: # Puntos despues de terminar la ronda
puntaje_despues = partida.puntos_e1
else:
puntaje_despues = partida.puntos_e2
# verificamos que se le den los 4 puntos al ganador del vale cuatro
self.assertEqual(puntaje_despues, puntaje_antes + 4)
# Nueva ronda
ronda, partida, jugadores = self.aux_truco_nueva_ronda()
puntaje = partida.puntos_e1
# Se canta truco, se responde retruco y vale cuatro y se rechaza
ronda.crear_canto(TRUCO, jugadores[0], partida.get_min_pts_restantes())
canto = ronda.get_ultimo_canto()
canto.aumentar(RETRUCO, jugadores[5].posicion_mesa)
canto = ronda.get_ultimo_canto()
canto.aumentar(VALE_CUATRO, jugadores[4].posicion_mesa)
canto = ronda.get_ultimo_canto()
canto.rechazar()
# Si se rechaza corresponde 3 punto para el otro jugador
partida.actualizar_puntajes() # Se actualizan los puntajes de la ronda
self.assertEqual(partida.puntos_e1, puntaje + 3)
# Nueva ronda
ronda, partida, jugadores = self.aux_truco_nueva_ronda()
# Se canta truco, se responde retruco y se canta el vale cuatro luego de que se haya aceptado
ronda.crear_canto(TRUCO, jugadores[0], partida.get_min_pts_restantes())
canto = ronda.get_ultimo_canto()
canto.aumentar(RETRUCO, jugadores[4].posicion_mesa)
canto.aceptar() # El equipo 1 acepta el retruco
canto = ronda.get_ultimo_canto()
# El equipo 1 recanta vale cuatro
canto.aumentar(VALE_CUATRO, jugadores[5].posicion_mesa)
canto = ronda.get_ultimo_canto()
canto.aceptar()
# verificamos que se le den los 4 puntos al jugador que gano
puntaje1 = partida.puntos_e1
puntaje2 = partida.puntos_e2
ganador = self.aux_truco_terminar_ronda(ronda, jugadores, partida)
if ganador == jugadores[0].equipo: # Puntos antes de terminar la ronda
puntaje_antes = puntaje1
else:
puntaje_antes = puntaje2
partida.actualizar_puntajes() # Se actualizan los puntajes de la ronda
if ganador == jugadores[0].equipo: # Puntos despues de terminar la ronda
puntaje_despues = partida.puntos_e1
else:
puntaje_despues = partida.puntos_e2
self.assertEqual(puntaje_despues, puntaje_antes + 4)
"""
Funcion auxiliar que dada la pocision en mesa del jugador devuelve el jugador.
"""
def aux_jugador_en_mesa(self, pos_mesa, partida):
return partida.jugadores.get(posicion_mesa=pos_mesa)
"""
Funcion auxiliar de los test del canto truco. Crea una nueva ronda con dos
jugadores que han tirado cada uno una carta.
"""
def aux_truco_nueva_ronda(self):
# Configuramos una partida donde se termino el primer enfrentamiento
partida = Partida.objects.get(nombre='Partida3 a 30 con 6 jugadores')
partida.crear_ronda()
# La partida ya esta lista para que los jugadores tiren las cartas
jugadores = partida.jugadores.all()
# Guardamos los jugadores en una lista ordenada segun su pocision en la mesa
lista_jugadores = []
for pos_mesa in range(partida.cantidad_jugadores):
lista_jugadores.append(self.aux_jugador_en_mesa(pos_mesa, partida))
ronda = partida.get_ronda_actual()
# Cada jugador tira una carta aleatoriamente
enfrentamiento = ronda.crear_enfrentamiento(self.aux_jugador_en_mesa(0, partida))
for jugador in jugadores:
enfrentamiento.agregar_carta(jugador.cartas_disponibles.order_by('?')[0])
return (ronda, partida, lista_jugadores)
"""
Funcion auxiliar de los test del canto truco. Termina la ronda tirando todas
las cartas restantes de los jugadores.
"""
def aux_truco_terminar_ronda(self, ronda, jugadores, partida):
# Hacemos que los jugadores tiren las 2 cartas que le quedan
enfrentamiento = ronda.crear_enfrentamiento(self.aux_jugador_en_mesa(0, partida))
for jugador in jugadores:
enfrentamiento.agregar_carta(jugador.cartas_disponibles.order_by('?')[1])
ganador_pos = ronda.get_ganador_enfrentamientos()
if ganador_pos < 0:
for jugador in jugadores:
enfrentamiento.agregar_carta(jugador.cartas_disponibles.order_by('?')[2])
ganador_pos = ronda.get_ganador_enfrentamientos()
ganador = self.aux_jugador_en_mesa(ganador_pos, partida)
# Si hay tres enfrentamientos hay un ganador necesariamente
# Se devuelve el objeto jugador que corresponde al ganador de los enfrentamientos
return ganador.equipo
|
UTF-8
|
Python
| false | false | 2,014 |
10,110,353,056,027 |
a86873fa32d727dc7e56eef51f568294f2a7991b
|
49f749b3c6429a668e5bacfe15d089aa3494b619
|
/smewt/base/cache.py
|
b9e0550b6cbc922a7271a2a5d7b58dd098bc90ab
|
[
"GPL-3.0-only"
] |
non_permissive
|
robmcmullen/smewt
|
https://github.com/robmcmullen/smewt
|
91f6272ab6b60380ae14f2cfabaaea82a447479a
|
fedff31667e020e0b8d1955fe153e27f70290766
|
refs/heads/master
| 2019-08-23T14:15:57.641791 | 2012-07-23T20:11:18 | 2012-07-23T20:11:18 | null | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
#
# Smewt - A smart collection manager
# Copyright (c) 2008 Nicolas Wack <wackou@smewt.com>
#
# Smewt 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.
#
# Smewt 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/>.
#
import cPickle
import logging
log = logging.getLogger('smewt.base.cache')
globalCache = {}
def clear():
log.info('Cache: clearing memory cache')
global globalCache
globalCache = {}
def load(filename):
return
log.info('Cache: loading cache from %s' % filename)
global globalCache
try:
globalCache = cPickle.load(open(filename, 'rb'))
except IOError:
log.warning('Cache: Cache file doesn\'t exist')
except EOFError:
log.error('Cache: cache file is corrupted... Please remove it.')
def save(filename):
return
log.info('Cache: saving cache to %s' % filename)
cPickle.dump(globalCache, open(filename, 'wb'))
def cachedmethod(function):
'''Makes a method use the cache. WARNING: this can NOT be used with static functions'''
def cached(*args):
# removed the first element of args for the key, which is the instance pointer
# we don't want the cache to know which instance called it, it is shared among all
# instances of the same class
fkey = str(args[0].__class__), function.__name__
key = (fkey, args[1:])
if key in globalCache:
return globalCache[key]
result = function(*args)
globalCache[key] = result
return result
cached.__doc__ = function.__doc__
cached.__name__ = function.__name__
return cached
|
UTF-8
|
Python
| false | false | 2,012 |
12,214,887,028,185 |
22d64dd422f79d2415fa1ee8cd34cfbd1c6bbfe4
|
06c7bd8a804e141e2793db67fe0a088b1a6ea933
|
/kavinyao/bagsok/keyword_rec/keyword_aggregate_sketch.py
|
7cbea6badd9f0339645f587c7add93d49041375d
|
[] |
no_license
|
xzhch1622/recsys-nju
|
https://github.com/xzhch1622/recsys-nju
|
45a2dca522f3abf1593f815af541a8a9c6fb4263
|
7ecfcb5077eb72270c826ea500276f4538d2203e
|
refs/heads/master
| 2021-01-10T22:01:21.755679 | 2013-03-24T06:05:26 | 2013-03-24T06:05:26 | 35,635,934 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null |
select (keyword_string, uri) from database
#could be done using mysql_array()
for keyword_string, url in keywordstr_uri_mapping:
#deal with generation 1 first
generation1 = expand_dimension(keyword_array(keyword_string))
for keyword_set in generation1:
if kwset_occurrence_mapping[keyword_set] not exist:
kwset_occur = occurrence(???)
kwset_occurrence_mapping[keyword_set] = kw_occur
#to use jaccard index, do trick here
current_generation[keyword_set] = array(keyword_set, keyword_set)
#now can start aggregation process
while current_generation.size > 0:
#the variable name is so bad!!
for keyword_set, child_set:
if kwset_occurrence_mapping[keyword_set] not exist:
kwset_occur = occurrence(???)
kwset_occurrence_mapping[keyword_set] = kw_occur
#calculate ratio here, exciting!
intersection = kwset_occurrence_mapping[keyword_set]
#not so robust here!
union = kwset_occurrence_mapping[child_set[0]] + kwset_occurrence_mapping[child_set[1]] - intersection
ratio = float(intersection) / union
if ration >= THRESHOLD:
add keyword_set, uri to database
candidates[] = keyword_set
current_generation = generate_next(candidates)
|
UTF-8
|
Python
| false | false | 2,013 |
2,052,994,370,111 |
92d25c51029a0e6d49ba2d068e569982ba3ec2c0
|
f3529088b9a79e1ae7c96290b7db2cbd52953644
|
/photo/views.py
|
19f5c4b99d9e29b8aadac52d45a64ebd3a748703
|
[] |
no_license
|
MtMoon/cst25
|
https://github.com/MtMoon/cst25
|
9d01d838df035d6696ccd544508d379e96d3349b
|
b143f4c809e5c523cdf297f7288e2e9f262d6a8b
|
refs/heads/master
| 2020-12-25T09:28:04.825040 | 2013-02-11T15:11:34 | 2013-02-11T15:11:34 | null | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null |
from django.contrib.auth.decorators import login_required
from django.http import HttpResponse, Http404, HttpResponseRedirect
from django.shortcuts import render_to_response
from django.template import RequestContext
from django.utils import timezone
from photo.models import Album, Photo, Comment
from photo.forms import CommentForm
from photo.urls import wrap_photo_url, wrap_album_url, str_album_page
from photo.urls import str_homepage
from photo.settings import *
from libs.page import get_page_dict, apage
@login_required
def show_homepage_first(request):
return show_homepage(request, 1)
@login_required
def show_album_first(request, album_id):
return show_album(request, album_id, 1)
@login_required
def show_homepage(request, nr):
album_list = apage(Album.objects.all(), int(nr), ALBUM_NPP)
# No album actually in this page.
if not album_list and nr != 1:
return HttpResponseRedirect('/photo/1/')
return render_to_response('photo_homepage.html',
{'album_list':album_list,
'page':get_page_dict(Album.objects.all(),
ALBUM_NPP, str_homepage(), int(nr))},
context_instance=RequestContext(request))
@login_required
def show_album(request, album_id, nr):
try:
album = Album.objects.get(pk=album_id)
except Album.DoesNotExist:
return HttpResponseRedirect('/photo/')
photo_list = apage(Photo.objects.filter(album__id=album_id), int(nr), PHOTO_NPP)
if not photo_list and nr != 1:
return HttpResponseRedirect(wrap_album_url(album_id, 1))
return render_to_response('photo_album.html',
{'photo_list':photo_list,
'album':album,
'page':get_page_dict(Photo.objects.filter(album__id=album_id),
PHOTO_NPP,
str_album_page(album_id),
int(nr))},
context_instance=RequestContext(request))
@login_required
def show_photo(request, photo_id):
try:
photo = Photo.objects.get(pk=photo_id)
except Photo.DoesNotExist:
return HttpResponseRedirect('/photo/')
if request.method == 'POST':
form=comment_on_photo(request, photo)
else: # request.method == 'GET'
form=CommentForm()
return show_photo_page(request, photo, form)
def comment_on_photo(request, photo):
form = CommentForm(request.POST)
if form.is_valid():
comment = Comment(uname=request.user.username,
text=form.cleaned_data['comment'],
time=timezone.now(),
photo=photo)
comment.save()
return form
def show_photo_page(request, photo, form):
photo_resp = {}
photo_resp['url'] = photo.url()
photo_resp['img'] = photo.img()
photo_resp['desc'] = photo.desc
# Get the ids of previous and next photos.
photo_list = Photo.objects.filter(album__pk=photo.album.id)
if photo_list.count() == 1:
photo_resp['prev'] = -1
photo_resp['next'] = -1
elif photo_list[0].id == photo.id:
photo_resp['prev'] = -1
photo_resp['next'] = wrap_photo_url(photo_list[1].id)
elif photo_list[photo_list.count()-1].id == photo.id:
photo_resp['prev'] = wrap_photo_url(photo_list[photo_list.count()-2].id)
photo_resp['next'] = -1
else:
for i in range(photo_list.count()):
if photo_list[i].id == photo.id:
photo_resp['prev'] == wrap_photo_url(photo_list[i-1].id)
photo_resp['next'] == wrap_photo_url(photo_list[i+1].id)
break
comment = Comment.objects.filter(photo__pk=photo.id)
return render_to_response('photo_view.html',
{'photo': photo_resp,
'album': photo.album,
'comment_list': comment,
'form': form },
context_instance=RequestContext(request));
|
UTF-8
|
Python
| false | false | 2,013 |
2,920,577,766,507 |
028cd0eeb92e48eca251dfa3288e4830b24cc1c2
|
719bf19e4a4af26c8172f41e82d19485f4ed1445
|
/algorithms/warmup/angry_children.py
|
9cc6adf5799c08978d126edc33b925aef2e144fb
|
[] |
no_license
|
mertkasar/hackerrank-solutions
|
https://github.com/mertkasar/hackerrank-solutions
|
db53a8bcda0c42e98d4ba357b02fcccbb3667d3d
|
dbbe64bb92b86a8e3919fefefcbc8219e2b575e7
|
refs/heads/master
| 2021-01-01T17:27:07.205240 | 2014-06-05T03:53:21 | 2014-06-05T03:53:21 | null | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null |
N, K = int(input()), int(input())
I = [int(input()) for i in range(N)]
I.sort()
m = I[-1] - I[0] #get maximum unfairness
for i in range(N-K+1):
'''for every ith block consisting K element in array,
test it with previous value of m '''
m = min(m, I[i+K-1]-I[i])
print(m)
|
UTF-8
|
Python
| false | false | 2,014 |
19,645,180,445,653 |
a29546f461f98b55aacc099436c44ee299dc9be7
|
f9001e7b4156a2c134041f7a34ae643e4a2003c6
|
/signin_page.py
|
5ee81ceb9c18b607c56c45e515318a4f93065072
|
[] |
no_license
|
barry07/Spreets
|
https://github.com/barry07/Spreets
|
e0a264304e70f812c319a94abd4a57c63ab2373e
|
6e2bac0057db9f5117e7d84ff64729d8a711e9cf
|
refs/heads/master
| 2021-01-22T01:05:57.836596 | 2011-10-25T06:31:52 | 2011-10-25T06:31:52 | 2,559,070 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null |
#!/usr/bin/env python
from selenium.webdriver.common.by import By
import base_page
class SignInPage(base_page.BasePage):
_page_title = "Spreets"
_your_email_locator = (By.ID, "email")
_your_password_locator = (By.ID, "password")
_sign_in_button_locator = (By.ID, "loginBtn")
def sign_in(self, user="default"):
credentials = self.credentials_of_user(user)
self.type_useremail(credentials["useremail"])
self.type_password(credentials["password"])
self.click_sign_in()
def type_usermail(self, useremail):
useremail_field = self.selenium.find_element(*self._your_email_locator)
useremail_field.clear()
useremail_field.send_keys(useremail)
def type_password(self, password):
password_field = self.selenium.find_element(*self._your_password_locator)
password_field.clear()
password_field.send_keys(password)
def click_sign_in(self):
self.selenium.find_element(*self._sign_in_button_locator).click()
|
UTF-8
|
Python
| false | false | 2,011 |
5,892,695,134,943 |
9082d2c802a4bc2d0e1ee3ddde798b2efc1c41e6
|
ffdbb265f5521adcf63869b7aaed3c726a59ad17
|
/demos/psd/run_psd.py
|
d17bf1273c5c1c1e67a5ef093b03c0f7b9f8650a
|
[] |
no_license
|
ysulsky/eblearn-python
|
https://github.com/ysulsky/eblearn-python
|
b5293ba626e82b62b4df9e122aafbf431bfdc0f8
|
6716f9c809c99f075af03acb9d163ae8d421bf55
|
refs/heads/master
| 2021-01-13T01:58:20.772931 | 2013-06-16T06:01:18 | 2013-06-16T06:01:18 | 10,716,272 | 1 | 2 | null | null | null | null | null | null | null | null | null | null | null | null | null |
from params import *
import eblearn as eb
import eblearn.ui as ui
import numpy as np
######################################################################
# DATASOURCE
train_mat = eb.map_matrix('%s/%s' % (data_dir, train_file))
train_ds = eb.dsource_unsup(train_mat)
if bias is None or coeff is None:
train_ds.normalize(scalar_bias = True, scalar_coeff = True)
if bias is not None: train_ds.bias = bias
if coeff is not None: train_ds.coeff = coeff
shape_in, shape_out = train_ds.shape()
######################################################################
# ENCODER
conv_kernel = (ki, kj)
conv_conn_table = eb.convolution.full_table(shape_in[0], size_code)
conv_out_size = (size_code,)+tuple(1+np.subtract(shape_in[1:], conv_kernel))
encoder = None
if encoder_arch == 0:
# LINEAR + BIAS + TANH + DIAG
encoder = eb.layers(eb.convolution (conv_kernel, conv_conn_table),
eb.bias_module (conv_out_size, per_feature = True),
eb.transfer_tanh(),
eb.diagonal (conv_out_size))
else:
raise NotImplementedError("this encoder setup isn't implemented yet")
######################################################################
# DECODER
back_conv_conn_table = eb.back_convolution.decoder_table(conv_conn_table)
decoder = eb.back_convolution(conv_kernel, back_conv_conn_table)
######################################################################
# COSTS
# encoder cost
enc_cost = eb.distance_l2(average=False)
# reconstruction cost
bconv_rec_coeff = eb.bconv_rec_cost.coeff_from_conv(shape_out, (1,)+conv_kernel)
rec_cost = eb.bconv_rec_cost(bconv_rec_coeff, average=False)
# sparsity penalty
sparsity = None
if pool_cost == 0:
sparsity = eb.penalty_l1(0., average=False)
else:
raise NotImplementedError("this code pooling isn't implemented yet")
######################################################################
# TRAINING
machine = eb.psd_codec( encoder, enc_cost,
sparsity,
decoder, rec_cost,
alphae, alphaz, alphad )
if encoder_arch in (1, 2, 4, 6):
# ensure a positive code for these machines
machine.code_parameter.thresh_x = 0.
machine.code_parameter.updater = eb.gd_linesearch_update( machine.code_feval,
stop_batch = 1,
**minimize_code )
machine.code_trainer.keep_log = True
encoder.parameter.updater = eb.gd_update( **train_encoder )
decoder.parameter.updater = eb.gd_update( **train_decoder )
all_params = eb.parameter_container( encoder.parameter, decoder.parameter )
trainer = eb.eb_trainer(all_params, machine, train_ds,
do_normalization = True,
backup_location = savedir,
backup_interval = 20000,
hess_interval = compute_hessian,
verbose = True)
encoder.parameter.name = 'encoder-param'
decoder.parameter.name = 'decoder-param'
print "============================================================"
print "EXPERIMENT: #%d (%s)" % (exper_nr, savedir or 'manual run')
print "============================================================"
trainer.train(train_iters)
if savedir is not None:
trainer.backup_machine(savedir + '/machine.obj')
trainer.backup_stats(savedir + '/train_stats.obj')
def plot():
import plots
ui.new_window()
scale = 3
plots.plot_filters(machine.encoder, conv_kernel, scale=scale)
plots.plot_filters(machine.decoder, conv_kernel,
transpose = True, orig_x=405, scale=scale)
ui.new_window()
plots.plot_reconstructions(train_ds, machine, n=100, scale=scale)
if __name__ == '__main__':
plot()
raw_input('press return to exit> ')
|
UTF-8
|
Python
| false | false | 2,013 |
7,851,200,235,910 |
3c4b1bbfece8ab3306418b9da3b10bdc14b4b29a
|
b68c764000a5be543a1a4f3c7b83c23b47984b30
|
/waiter/views/default.py
|
9c5242a82f58eebbe9452846ddb731b8bb9edd3a
|
[] |
no_license
|
nuannuanwu/weixiao
|
https://github.com/nuannuanwu/weixiao
|
7caea4b791584c595adfefd569e3ad257e21c404
|
1b1fbe4c66df731f63f10c57dee20cb0bb4edb4c
|
refs/heads/master
| 2021-01-06T20:37:12.699189 | 2014-02-18T08:04:10 | 2014-02-18T08:04:10 | 16,940,220 | 1 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null |
# -*- coding: utf-8 -*-
from django.shortcuts import render_to_response, redirect, render, get_object_or_404
from django.contrib.auth.models import User
from django.contrib import messages
from django.utils.translation import ugettext as _
from django.core.exceptions import ObjectDoesNotExist
from waiter.decorators import waiter_required
from waiter.models import WaiterMessage
from kinger.helpers import ajax_ok, ajax_error, pagination
from django.core.urlresolvers import reverse
from django.http import HttpResponse
from django.core.paginator import Paginator, EmptyPage, PageNotAnInteger
from django.db.models import Q
from kinger.models import Waiter
from userena.contrib.umessages.models import Message, MessageRecipient, MessageContact
from userena.utils import get_datetime_now
# 返回向客服人员提问的问题列表
@waiter_required
def index(request,template_name="waiter/default/index.html"):
# 得到筛选的客服人员
try:
the_waiter = int(request.GET['waiter'])
except:
the_waiter = ''
waiters = Waiter.objects.all()
if the_waiter == '':
waiter_id_list = [waiter.user_id for waiter in waiters]
else:
waiter_id_list = [the_waiter]
# 取得跟客服的对话的人
to_waiter_conversation = MessageContact.objects.filter(Q(from_user__in=waiter_id_list))
# 提问总人数
askers_count = to_waiter_conversation.count()
# 筛选出最后一次回复是家长的对话,并构建数据
mes = []
for c in to_waiter_conversation:
# 得到最后一条消息->会话以导师的角度为准
conversation = Message.objects.get_conversation_between(c.from_user,c.to_user)[:3]
last_message = conversation[0]
if not last_message.sender.pk in waiter_id_list:
user = c.to_user
to_user = c.from_user
mes.append({
'contact_id':c.id,
'user':user,
'to_user':to_user,
'last_message':last_message,
'conversation':conversation,
'unread_num': MessageRecipient.objects.count_unread_messages_between(to_user,user)
})
mes_count = len(mes)
mes,query = pagination(request,mes,10)
return render(request,template_name,{'mes':mes,'mes_count':mes_count,'askers_count':askers_count,'waiters': waiters,'query':query})
# 对话记录页
@waiter_required
def history(request,user_id,to_user_id,template_name="waiter/default/history.html"):
if request.method == 'GET':
userid = user_id
to_userid = to_user_id
user = get_object_or_404(User,id=userid)
to_user = get_object_or_404(User,id=to_userid)
conversation = Message.objects.get_conversation_between(to_user,user)
# 分页
conversation,query = pagination(request,conversation,10)
return render(request,template_name,{'conversation':conversation,'user':user})
# 消息保存
@waiter_required
def save_message(request,):
if request.is_ajax():
if request.method == 'POST':
try:
parent_id = request.POST['parent_id']
waiter_id = request.POST['waiter_id']
body = request.POST['body']
parent = get_object_or_404(User,id=parent_id)
waiter = get_object_or_404(User,id=waiter_id)
#验证工作
#添加会话
mes = Message.objects.send_message(waiter,[parent],body)
#客服记录
wm = WaiterMessage(user=request.user,message=mes)
wm.save()
return ajax_ok('消息发送成功')
except:
return ajax_error('消息发送失败')
# 更新某个用户的对某人的所有未读消息
@waiter_required
def update_unread_message(request,):
try:
userid = request.GET['userid']
recipientid = request.GET['recipientid']
user = get_object_or_404(User,pk=userid)
recipient = get_object_or_404(User,pk=recipientid)
# 找到 user 发给 recipient 的消息。
queryset = Message.objects.filter(Q(sender=user, recipients=recipient,
messagerecipient__deleted_at__isnull=True))
message_pks = [m.pk for m in queryset]
# 更新 user 发给 recipient 的未读消息
unread_list = MessageRecipient.objects.filter(message__in=message_pks,
user=recipient,
read_at__isnull=True)
now = get_datetime_now()
unread_list.update(read_at=now)
return ajax_ok('消息发送成功')
except:
return ajax_error('消息发送失败')
def get_unread_waiter_count():
waiters = Waiter.objects.all()
waiter_id_list = [waiter.user_id for waiter in waiters]
# 取得跟客服的对话的人
to_waiter_conversation = MessageContact.objects.filter(Q(from_user__in=waiter_id_list))
# 筛选出最后一次回复是家长的对话,并构建数据
mes = []
for c in to_waiter_conversation:
# 得到最后一条消息->会话以导师的角度为准
conversation = Message.objects.get_conversation_between(c.from_user,c.to_user)[:3]
last_message = conversation[0]
if not last_message.sender.pk in waiter_id_list:
user = c.to_user
to_user = c.from_user
mes.append({
'contact_id':c.id,
'user':user,
'to_user':to_user,
'last_message':last_message,
'conversation':conversation,
'unread_num': MessageRecipient.objects.count_unread_messages_between(to_user,user)
})
mes_count = len(mes)
return mes_count
|
UTF-8
|
Python
| false | false | 2,014 |
5,738,076,328,947 |
263b07fc5a1d68a861f8975dd4c786cc35c5f820
|
1d38ab928e8802c2623261abbac76ddbde7220af
|
/python/operaciones/revision-auditoria-distribuciones.py
|
71a26634524c040e931d22b7540a6ddb113eea90
|
[] |
no_license
|
gameplanet/scripts-gp
|
https://github.com/gameplanet/scripts-gp
|
ef7d0b0139de877e6a7b3092cc25678b1fc0620d
|
32b0c3c8f088b5ef583780dde110ff041c02600c
|
refs/heads/master
| 2015-08-08T12:46:57.354448 | 2014-03-25T20:17:23 | 2014-03-25T20:17:23 | null | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null |
#!/usr/bin/python
# -*- coding: utf-8 -*-
import misc
import MySQLdb
from misc import op_log,op_ejecutar,op_formato_valor,op_archivo_log,op_fecha,op_argumentos,op_excepciones,op_cerrar_conexiones
ip_servidor,user,passwd,db="50.97.144.18",["epod_sync","distbdd"],["naeku7Ko-viGhop0o","distbdd"],["pointbox","pointbox"]
archivo,cursor,cambios,debug=None,None,None,None
conexion_servidor=None
sentencia=""
argumentos=op_argumentos()
if argumentos is not None:
if argumentos.log:
archivo=op_archivo_log("revision-auditoria-distribuciones","rad")
debug=argumentos.dbg
cambios=argumentos.bdd
try:
op_log(misc._msg_greet_,"Revision de auditorias automaticas de distribuciones",archivo)
op_log(misc._msg_serv_op_,"Conectando con el servidor corporativo en IP '%s'..." % ip_servidor,archivo)
conexion_servidor=MySQLdb.connect(ip_servidor,user[0],passwd[0],db[0])
op_log(misc._msg_ok_,"Conexion establecida (%s)." % op_fecha(),archivo)
cursor_servidor=conexion_servidor.cursor()
sentencia="SET autocommit=0"
op_ejecutar(sentencia,cursor_servidor,debug,archivo)
sentencia="SET NAMES utf8"
op_ejecutar(sentencia,cursor_servidor,debug,archivo)
op_log(misc._msg_serv_op_,"Buscando datos inconsistentes auditados...",archivo)
sentencia="select distribucion,id_tienda_destino,upc,stock,stock-cantidad+cantidad_tda,cantidad-cantidad_trans,cantidad_trans-cantidad_tda from movimientos_inventario_corporativo where (cantidad!=cantidad_trans or cantidad_trans!=cantidad_tda) and auditado=1"
op_ejecutar(sentencia,cursor_servidor,debug,archivo)
registros=cursor_servidor.fetchall()
formato="%25s | %15s | %16s | %6s | %6s | %6s | %6s | %s"
op_log(misc._msg_comm_,formato % ("Distribucion","Tienda destino","UPC","Stock","Total","CEDIS","Trans","Estado"),archivo)
for registro in registros:
sentencia="select d.distribucion,h.stock,sum(h.total),h.cedis_alt,h.trans1 from _distribuciones_lista d inner join _historico_ajustes h on d.id=h.id_distribucion where d.distribucion_origen='%s' and d.id_tienda=%s and upc='%s' group by d.distribucion" % tuple(registro[:3])
op_ejecutar(sentencia,cursor_servidor,debug,archivo)
if cursor_servidor.rowcount>0:
resultado=cursor_servidor.fetchone()
if resultado[1]!=registro[3] or resultado[2]!=registro[4] or resultado[3]!=registro[5] or resultado[4]!=registro[6]:
op_log(misc._msg_warn_,formato % (resultado[0],registro[1],registro[2],"%s/%s" % (resultado[1],registro[3]),"%s/%s" % (resultado[2],registro[4]),"%s/%s" % (resultado[3],registro[5]),"%s/%s" % (resultado[4],registro[6]),"Inconsistente"),archivo)
#else:
#op_log(misc._msg_ok_,formato % (resultado[0],registro[1],registro[2],resultado[1],resultado[2],resultado[3],resultado[4],"Correcto"),archivo)
else:
op_log(misc._msg_warn_,formato % (registro+("Falta",)),archivo)
op_log(misc._msg_serv_op_,"Buscando ajustes no programados...",archivo)
sentencia="select distribucion,id,id_tienda,distribucion_origen from _distribuciones_lista where distribucion_origen is not NULL"
op_ejecutar(sentencia,cursor_servidor,debug,archivo)
registros=cursor_servidor.fetchall()
formato="%25s | %5s | %6s | %25s"
op_log(misc._msg_comm_,formato % ("Distribucion","ID","Tienda","Origen"),archivo)
for registro in registros:
sentencia="select count(*) from control_distribuciones where distribucion='%s'" % registro[0]
op_ejecutar(sentencia,cursor_servidor,debug,archivo)
if cursor_servidor.rowcount>0:
resultado=cursor_servidor.fetchone()
if resultado[0]<=0:
op_log(misc._msg_warn_,formato % registro,archivo)
op_log(misc._msg_serv_op_,"Buscando inconsistencias en cantidad de registros agregados...",archivo)
sentencia="select d.distribucion,d.id,d.id_tienda,d.distribucion_origen,d.c_registros,d.c_unidades,count(*) as filas,sum(h.cedis_alt+h.trans1) as cantidades,sum(h.cedis_alt),sum(h.trans1) from _distribuciones_lista d inner join _historico_ajustes h on d.id=h.id_distribucion where distribucion_origen is not NULL group by d.id having filas!=d.c_registros or d.c_unidades!=cantidades"
op_ejecutar(sentencia,cursor_servidor,debug,archivo)
formato="%25s | %5s | %6s | %25s | %10s | %10s | %10s | %10s | %10s | %10s"
op_log(misc._msg_comm_,formato % ("Distribucion","ID","Tienda","Distribucion","Registros","Unidades","Registros","Unidades","Cedis alt","Transport."),archivo)
op_log(misc._msg_tab_,formato % ("generada","","","origen","_dist_list","_dist_list","_hist_ajus","_hist_ajus","",""),archivo)
if cursor_servidor.rowcount>0:
registros=cursor_servidor.fetchall()
for registro in registros:
op_log(misc._msg_warn_,formato % registro,archivo)
print "[O] Revision terminada."
op_log(misc._msg_ok_,"Revision terminada.",archivo)
except Exception, e:
op_excepciones(e,archivo,[[conexion_servidor,misc._conn_close_]])
else:
op_cerrar_conexiones([[conexion_servidor,misc._conn_close_]])
op_log(misc._msg_ok_,"Proceso terminado.",archivo)
|
UTF-8
|
Python
| false | false | 2,014 |
3,848,290,728,478 |
88165f0da0f5572fe034459be15ae8ce808f4fca
|
10a190efddadfaad31372d8a5acf9d76e081f5a7
|
/src/Python/modules/device_info/detect_device_info_linux.py
|
486493a2d3c434db6359200cf7c316d9c40e6c12
|
[] |
no_license
|
Auzzy/personal
|
https://github.com/Auzzy/personal
|
1b410d84f3135ee9b5d271e3a9b71d110273c198
|
e8135c5023ae55b947863d0ab1be94c40591ac58
|
refs/heads/master
| 2016-09-11T04:18:58.934896 | 2014-06-14T05:58:40 | 2014-06-14T05:58:40 | 1,724,124 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null |
from parse_parts import parse_parts
from parse_devs import parse_devs
# Each key must exist as info about the device. If any of these keys doesn't exist, it is not a valid and useful device. The value is the required value. If this value does not match the value given by the device, then it is not a valid device. If the required value is None, then do not check the value given by the device. See the _filter_non_fs() to see its use.
_fs_attribs = {"ID_FS_TYPE":None, "DEVTYPE":"partition"}
# Device info attributes that must be decoded.
_decode_attribs = ["ID_VENDOR_ENC", "ID_MODEL_ENC", "ID_FS_LABEL_ENC"]
# Device info keys and their associated human readable name. These keys will exist in the output dictionary.
_attribs_dict = {"DEVNAME":"device", "ID_VENDOR_DEC":"vendor", "ID_MODEL_DEC":"product", "ID_FS_LABEL_DEC":"label"}
# dict{str:dict{str:str}} -> dict{str:dict{str:str}}
def _filter_attribs(all_dev_info):
new_dev_info = {}
for dev_name in all_dev_info:
new_dev_info[dev_name] = {}
for attrib in _attribs_dict:
new_dev_info[dev_name][_attribs_dict[attrib]] = all_dev_info[dev_name][attrib]
return new_dev_info
# str -> str
def _decode(string):
if string is None:
return None
new_str = ""
hex_marker = r"\x"
while hex_marker in string:
char_start = string.index(hex_marker)
decoded_char = str(unichr(int(string[char_start+2:char_start+4],16)))
new_str += string[:char_start]
new_str += decoded_char
string = string[char_start+4:]
new_str += string
return new_str
# dict{str:dict{str:str}} -> None
def _decode_values(all_dev_info):
for dev_name in all_dev_info:
for encode_key in _decode_attribs:
encoded_val = all_dev_info[dev_name][encode_key]
if encoded_val is not None:
decode_key = encode_key.replace("_ENC","_DEC")
all_dev_info[dev_name][decode_key] = _decode(encoded_val).strip()
# dict{str:dict{str:str}} -> None
def _insert_placeholders(all_dev_info):
for dev_name in all_dev_info:
for attrib in _decode_attribs+_attribs_dict.keys():
if attrib not in all_dev_info[dev_name]:
all_dev_info[dev_name][attrib] = None
# dict{str:dict{str:str}} -> bool
def _valid_fs_val(dev_info, fs_attrib):
if fs_attrib in dev_info.keys():
fs_attrib_val = _fs_attribs[fs_attrib]
if fs_attrib_val is None or dev_info[fs_attrib]==fs_attrib_val:
return True
return False
# dict{str:dict{str:str}} -> bool
def _valid_device(dev_info):
for fs_attrib in _fs_attribs:
if not _valid_fs_val(dev_info,fs_attrib):
return False
return True
# dict{str:dict{str:str}} -> None
def _filter_non_fs(all_dev_info):
for dev in all_dev_info.keys()[:]:
if not _valid_device(all_dev_info[dev]):
del all_dev_info[dev]
# list[str] -> dict{str:dict{str:str}}
def _get_device_info(all_part_names):
all_dev_info = parse_devs(all_part_names)
_filter_non_fs(all_dev_info)
_insert_placeholders(all_dev_info)
_decode_values(all_dev_info)
return _filter_attribs(all_dev_info)
# None -> list[str]
def _get_partition_names():
all_part_info = parse_parts()
if len(all_part_info)==0:
raise OSError("As no partitions were detected, it is likely there was an error with reading /proc/partitions. Please check to see that the file format has not changed.")
if "name" not in all_part_info[0].keys():
raise OSError("The \"name\" property could not be found. Check to see if the format of /proc/partitions has changed.")
return [part_info["name"] for part_info in all_part_info]
# None -> dict{str:dict{str:str}}
def detect_device_info():
all_part_names = _get_partition_names()
all_dev_info = _get_device_info(all_part_names)
return all_dev_info
if __name__=="__main__":
all_dev_info = detect_device_info()
for dev_name in all_dev_info:
print dev_name
for attrib in all_dev_info[dev_name]:
print "{0}: {1}".format(attrib,all_dev_info[dev_name][attrib])
print
|
UTF-8
|
Python
| false | false | 2,014 |
19,000,935,342,115 |
366c25c32bdb05cb1ae469c1cd31b7051330ac04
|
a807c430c41231dc02b0e6e15e19dbf92261c3e4
|
/mysite/lab/migrations/0001_initial.py
|
461e1a56ec67e6f71772303fd9df66233e96b56e
|
[] |
no_license
|
VDenis/Subject-NetworkProgramming-lab
|
https://github.com/VDenis/Subject-NetworkProgramming-lab
|
200fc0fc5c9a39757aa3c4f560b83acf26abe337
|
5056b823cd3ad2eafb255984e2a37d1762b7c260
|
refs/heads/master
| 2016-09-06T09:14:01.607937 | 2014-10-25T08:04:17 | 2014-10-25T08:04:17 | null | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null |
# -*- coding: utf-8 -*-
from __future__ import unicode_literals
from django.db import models, migrations
class Migration(migrations.Migration):
dependencies = [
]
operations = [
migrations.CreateModel(
name='Group',
fields=[
('id', models.AutoField(verbose_name='ID', serialize=False, auto_created=True, primary_key=True)),
('identification', models.CharField(max_length=75)),
('name', models.CharField(max_length=75)),
],
options={
},
bases=(models.Model,),
),
migrations.CreateModel(
name='MadeLaboratoryWork',
fields=[
('id', models.AutoField(verbose_name='ID', serialize=False, auto_created=True, primary_key=True)),
('upload_file', models.FileField(upload_to=b'')),
('date', models.DateTimeField()),
('mark', models.IntegerField(default=0)),
],
options={
},
bases=(models.Model,),
),
migrations.CreateModel(
name='PageLaboratoryWork',
fields=[
('id', models.AutoField(verbose_name='ID', serialize=False, auto_created=True, primary_key=True)),
('name', models.CharField(max_length=200)),
('date', models.DateTimeField()),
('description', models.CharField(max_length=1000)),
('document', models.FileField(upload_to=b'')),
],
options={
},
bases=(models.Model,),
),
migrations.CreateModel(
name='Professor',
fields=[
('id', models.AutoField(verbose_name='ID', serialize=False, auto_created=True, primary_key=True)),
('email', models.EmailField(max_length=75)),
('born', models.DateField()),
('name', models.CharField(max_length=20)),
('surname', models.CharField(max_length=20)),
('identification_card', models.CharField(max_length=75)),
],
options={
'abstract': False,
},
bases=(models.Model,),
),
migrations.CreateModel(
name='Student',
fields=[
('id', models.AutoField(verbose_name='ID', serialize=False, auto_created=True, primary_key=True)),
('email', models.EmailField(max_length=75)),
('born', models.DateField()),
('name', models.CharField(max_length=20)),
('surname', models.CharField(max_length=20)),
('record_book', models.CharField(max_length=75)),
],
options={
'abstract': False,
},
bases=(models.Model,),
),
migrations.CreateModel(
name='Subject',
fields=[
('id', models.AutoField(verbose_name='ID', serialize=False, auto_created=True, primary_key=True)),
('name', models.EmailField(max_length=75)),
],
options={
},
bases=(models.Model,),
),
]
|
UTF-8
|
Python
| false | false | 2,014 |
14,465,449,891,087 |
beff7858a4e5cf45d93afd72fc8139e68ce5bd43
|
965f7b70ac142632f74a7e26bf0bc1707db62491
|
/jabbapylib/console/autoflush.py
|
4726e384569a6413cf01a860827be6cd42c2ebf1
|
[
"GPL-3.0-only"
] |
non_permissive
|
ayoub-benali/jabbapylib
|
https://github.com/ayoub-benali/jabbapylib
|
2e81590ee8a219151194b2c3201e459986f40889
|
2f563db82d34feb55be616ea0bee49ae40115e7b
|
refs/heads/master
| 2021-01-24T04:30:04.328751 | 2012-12-30T21:59:19 | 2012-12-30T21:59:19 | null | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null |
#!/usr/bin/env python
"""
Switch autoflush on.
# from jabbapylib.console.autoflush import unbuffered
"""
import sys
import os
autoflush_on = False
def unbuffered():
"""Switch autoflush on."""
global autoflush_on
# reopen stdout file descriptor with write mode
# and 0 as the buffer size (unbuffered)
if not autoflush_on:
sys.stdout = os.fdopen(sys.stdout.fileno(), 'w', 0)
autoflush_on = True
#############################################################################
if __name__ == "__main__":
unbuffered()
print "unbuffered text"
|
UTF-8
|
Python
| false | false | 2,012 |
16,286,515,991,573 |
9ab11e74ec408f8b82ae37676248ca751682afd7
|
16555b2f6a590edd18e41ea8c9276422ae21f52b
|
/app/index.py
|
06d0736be13a65151f71c8cb27ca4be998c7c911
|
[
"LicenseRef-scancode-warranty-disclaimer",
"CC-BY-NC-SA-3.0",
"CC-BY-NC-4.0",
"LicenseRef-scancode-proprietary-license",
"LicenseRef-scancode-cc-by-nc-sa-3.0-us",
"LicenseRef-scancode-other-copyleft",
"LicenseRef-scancode-unknown-license-reference"
] |
non_permissive
|
Phaxius/multicraft.conf
|
https://github.com/Phaxius/multicraft.conf
|
a86446ce272ad09959b45a7bc46c925059144ece
|
99ad66bb32cb58d9d6865304225b518d20fc09ad
|
refs/heads/master
| 2023-03-16T12:26:19.434081 | 2013-11-23T00:40:50 | 2013-11-23T00:40:50 | null | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null |
from app import app
import flask, flask.views
from database import connection, models
@app.route('/')
def home():
entries = connection.session.query(models.Entry).all()
return flask.render_template('index.html', entries = entries, title = 'All Configs');
@app.route('/about')
def about():
return flask.render_template('about.html');
@app.route('/jar/<int:id>')
def list_by_jar(id):
entries = connection.session.query(models.Entry).filter(models.Entry.jar_id == id).all()
jar = connection.session.query(models.Jar).filter(models.Jar.id == id).first()
return flask.render_template('index.html', entries = entries, title = 'Configs for ' + jar.name);
@app.route('/version/<string:name>')
def list_by_version(name):
entries = connection.session.query(models.Entry).filter(models.Entry.version == name).all()
return flask.render_template('index.html', entries = entries, title = 'Configs for version ' + name);
|
UTF-8
|
Python
| false | false | 2,013 |
8,074,538,560,222 |
567a095bf3193ef44c95cab3ec387a617065d2a6
|
4d3fd43d098d196c10b46006a6605b3fbb630830
|
/tournabot/__init__.py
|
ee1d63b9f658d9613e6b97e4f86ad53abf9e34f6
|
[] |
no_license
|
ihptru/tournabot
|
https://github.com/ihptru/tournabot
|
f884bbd3defb64e33d80f21e74fca96169751461
|
cadb55ecbf28b319feae55a3e7e4e86ff8193277
|
refs/heads/master
| 2021-01-18T12:09:41.993527 | 2014-08-21T17:36:52 | 2014-08-21T17:42:24 | null | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null |
from twisted.internet import reactor
import tournabot
if __name__ == '__main__':
try:
tournabot.load()
except Exception as e:
print(e)
channel = None
nickname = None
bot_config = tournabot.state.get('bot')
if bot_config:
channel = bot_config.get('channel')
nickname = bot_config.get('nick')
channel = channel or '#clembtest'
nickname = nickname or 'tournabot'
if type(channel) is unicode:
channel = channel.encode('utf-8')
if type(nickname) is unicode:
nickname = nickname.encode('utf-8')
print("connecting to {}".format(channel))
reactor.connectTCP(
'irc.freenode.org',
6667,
tournabot.BotFactory(channel)
)
reactor.run()
|
UTF-8
|
Python
| false | false | 2,014 |
11,012,296,171,780 |
af011404759389411f457c455a2c295e92c33e3e
|
98c6ea9c884152e8340605a706efefbea6170be5
|
/examples/data/Assignment_3/ltggar001/question3.py
|
c448ae35ccf03da8891f36b20bc4abe3ababe9fa
|
[] |
no_license
|
MrHamdulay/csc3-capstone
|
https://github.com/MrHamdulay/csc3-capstone
|
479d659e1dcd28040e83ebd9e3374d0ccc0c6817
|
6f0fa0fa1555ceb1b0fb33f25e9694e68b6a53d2
|
refs/heads/master
| 2021-03-12T21:55:57.781339 | 2014-09-22T02:22:22 | 2014-09-22T02:22:22 | 22,372,174 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null |
a=input('Enter the message:\n')
b=eval(input("Enter the message repeat count:\n"))
c=eval(input("Enter the frame thickness:\n"))
for i in range(0,c):
print('|'*i,'+',(len(a)+2*c-2*i)*'-','+','|'*i,sep='')
for i in range(0,b):
print('|'*c,' ',a,' ','|'*c,sep='')
for i in range(c,0,-1):
print('|'*(i-1),'+',(len(a)+2*c-2*(i-1))*'-','+','|'*(i-1),sep='')
|
UTF-8
|
Python
| false | false | 2,014 |
19,078,244,768,246 |
77085e0e41af7b179c2584481eb73d7701ac035b
|
169b0ec41c1fde0b4974b45df8cd21a52e59974b
|
/arrayed_enclosure.py
|
8d7d57970c1d9d7c005ca2d36f787b657f17bba9
|
[
"Apache-2.0"
] |
permissive
|
iorodeo/capillary_sensor_enclosure
|
https://github.com/iorodeo/capillary_sensor_enclosure
|
73ccd8491cdf22e37590c8037beac9c484f183d9
|
31eabacec098ab5600d79cbcdadc03ab42a044d1
|
refs/heads/master
| 2022-11-05T20:49:40.294355 | 2012-03-09T18:31:44 | 2012-03-09T18:31:44 | 273,790,074 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null |
import numpy
from py2scad import *
from capillary_enclosure import Capillary_Enclosure
class Arrayed_Enclosure(Capillary_Enclosure):
def __init__(self,params):
self.params = params
super(Arrayed_Enclosure,self).__init__(self.params)
def make(self):
super(Arrayed_Enclosure,self).make()
self.make_array_bottom()
self.make_bottom_mount_holes()
def make_array_bottom(self):
number_of_sensors = self.params['number_of_sensors']
sensor_spacing = self.params['sensor_spacing']
thickness = self.params['wall_thickness']
lid_radius = self.params['lid_radius']
overhang = self.params['array_bottom_overhang']
bottom_x_overhang = self.params['bottom_x_overhang']
bottom_y_overhang = self.params['bottom_y_overhang']
# Create larger bottom plate for arrayed sensor
plate_x = self.bottom_x
plate_y = self.bottom_y + sensor_spacing*number_of_sensors + 2*overhang
self.array_bottom_size = plate_x, plate_y
self.array_bottom = rounded_box(plate_x,plate_y,thickness,radius=lid_radius,round_z=False)
# Get list of holes in single capillary sensor
hole_list = self.params['hole_list'] + self.tab_hole_list + self.standoff_hole_list
bottom_holes = [hole for hole in hole_list if hole['panel'] == 'bottom']
# Create list of bottom holes for arrayed sensor
array_bottom_holes = []
array_y_values = self.get_array_y_values()
for hole in bottom_holes:
for pos_y in array_y_values:
hole_new = dict(hole)
hole_x, hole_y = hole['location']
hole_new['location'] = hole_x, hole_y + pos_y
hole_new['panel'] = 'array_bottom'
array_bottom_holes.append(hole_new)
self.add_holes(array_bottom_holes)
def make_bottom_mount_holes(self):
hole_diam = self.params['bottom_mount_hole_diam']
hole_spacing = self.params['bottom_mount_hole_spacing']
hole_inset = self.params['bottom_mount_hole_inset']
bottom_x, bottom_y = self.array_bottom_size
hole_list = []
for i in (-1,1):
for j in (-1,1):
x_pos = i*0.5*hole_spacing
y_pos = j*(0.5*bottom_y - hole_inset)
hole = {
'panel' : 'array_bottom',
'type' : 'round',
'location' : (x_pos,y_pos),
'size' : hole_diam,
}
hole_list.append(hole)
self.add_holes(hole_list)
def get_assembly(self,**kwargs):
show_bottom = kwargs['show_bottom']
kwargs['show_bottom'] = False
top_parts = super(Arrayed_Enclosure,self).get_assembly(**kwargs)
parts_list = []
# Array top parts
pos_values = self.get_array_y_values()
for pos in pos_values:
parts_list.append(Translate(top_parts,v=(0,pos,0)))
x,y,z = self.params['inner_dimensions']
thickness = self.params['wall_thickness']
z_shift = -0.5*z - 0.5*thickness
array_bottom = Translate(self.array_bottom,v=(0,0,z_shift))
if show_bottom:
parts_list.append(array_bottom)
return parts_list
def get_box_projection(self,show_ref_cube=True,spacing_factor=4,project=True):
inner_x, inner_y, inner_z = self.params['inner_dimensions']
wall_thickness = self.params['wall_thickness']
top_x_overhang = self.params['top_x_overhang']
top_y_overhang = self.params['top_y_overhang']
bottom_x_overhang = self.params['bottom_x_overhang']
bottom_y_overhang = self.params['bottom_y_overhang']
spacing = spacing_factor*wall_thickness
bottom = self.bottom
# Translate front panel
y_shift = -(0.5*self.bottom_y + 0.5*inner_z + wall_thickness + spacing)
front = Translate(self.front, v=(0,y_shift,0))
# Translate back panel
y_shift = 0.5*self.bottom_y + 0.5*inner_z + wall_thickness + spacing
back = Rotate(self.back,a=180,v=(1,0,0)) # Rotate part so that outside face is up in projection
back = Translate(back, v=(0,y_shift,0))
# Rotate and Translate left panel
left = Rotate(self.left,a=90,v=(0,0,1))
left = Rotate(left,a=180,v=(0,1,0)) # Rotate part so that outside face is up in projection
x_shift = -(0.5*self.bottom_x + 0.5*inner_z + wall_thickness + spacing)
left = Translate(left, v=(x_shift,0,0))
# Rotate and translate right panel
right = Rotate(self.right,a=90,v=(0,0,1))
x_shift = 0.5*self.bottom_x + 0.5*inner_z + wall_thickness + spacing
right = Translate(right,v=(x_shift,0,0))
# Create reference cube
ref_cube = Cube(size=(INCH2MM,INCH2MM,INCH2MM))
y_shift = 0.5*self.bottom_y + 0.5*INCH2MM + inner_z + 2*wall_thickness + 2*spacing
ref_cube = Translate(ref_cube,v=(0,y_shift,0))
# Add capillary clamp
thickness = self.params['wall_thickness']
clamp_x, clamp_y, clamp_z = self.clamp_size
x_shift = 0.5*self.top_x + 0.5*clamp_x + spacing_factor*thickness
y_shift = 0.5*self.top_y + 0.5*clamp_y + spacing_factor*thickness
clamp = Translate(self.capillary_clamp,v=(x_shift,y_shift,0))
# Create part list
part_list = [self.top, front, back, left, right, clamp]
if show_ref_cube == True:
part_list.append(ref_cube)
# Project parts
part_list_proj = []
for part in part_list:
if project:
part_list_proj.append(Projection(part))
else:
part_list_proj.append(part)
return part_list_proj
def get_bottom_projection(self,show_ref_cube=True,spacing_factor=4):
thickness = self.params['wall_thickness']
ref_cube = Cube(size=(INCH2MM,INCH2MM,INCH2MM))
x_shift = 0.5*self.bottom_x + 0.5*INCH2MM + spacing_factor*thickness
ref_cube = Translate(ref_cube,v=(x_shift,0,0))
bottom = Projection(self.array_bottom)
parts_list = [bottom]
if show_ref_cube:
parts_list.append(Projection(ref_cube))
return parts_list
def get_array_y_values(self):
number_of_sensors = self.params['number_of_sensors']
sensor_spacing = self.params['sensor_spacing']
array_length = sensor_spacing*number_of_sensors
pos_values = numpy.linspace(-0.5*array_length, 0.5*array_length, number_of_sensors)
return pos_values
|
UTF-8
|
Python
| false | false | 2,012 |
19,705,309,954,414 |
27bf19568873be03333977327374a348ec94013d
|
073d657d3d2ca0dfdaa21a97378eb3dfbd16934e
|
/setup.py
|
4d2aedafbe975f2cd47f32693255ec157ad506e6
|
[
"MIT"
] |
permissive
|
appliedsec/Powerglove-DNS
|
https://github.com/appliedsec/Powerglove-DNS
|
473863f671a5c5cc954e73fb25a236160374f9ad
|
b78b052c31e6cc4b5414341075013334a28b2c5d
|
refs/heads/master
| 2016-09-15T18:40:26.611076 | 2013-08-25T17:08:54 | 2013-08-25T17:08:54 | 3,466,863 | 2 | 1 | null | false | 2013-03-20T19:55:26 | 2012-02-17T04:01:15 | 2013-03-20T19:55:25 | 2013-03-20T19:55:25 | 116 | null | 1 | 1 |
Python
| null | null |
from os.path import join, dirname
try:
from setuptools import setup, find_packages
except ImportError:
from ez_setup import use_setuptools
use_setuptools()
from setuptools import setup, find_packages
def get_requirements():
reqsFile = open(join(dirname(__file__), 'requirements.txt'), 'r')
reqs = [req.strip() for req in reqsFile if req.strip() != '']
reqs.reverse() # we specify them in dependency resolution order in the file; we need to reverse that for install
reqsFile.close()
return reqs
def read(name, *args):
try:
with open(join(dirname(__file__), name)) as read_obj:
return read_obj.read(*args)
except Exception:
return ''
extra_setup = {}
setup(
name='powerglove-dns',
version='2.0.1',
author='Rob Dennis',
author_email='rdennis+powerglove-dns@gmail.com',
description="Reserves an appropriate ip in a PowerDNS installation for a given hostname, updating reverse/forward/text records as well",
long_description=read('README.rst'),
install_requires=get_requirements(),
tests_require=['unittest2', 'mock'],
url="https://github.com/appliedsec/Powerglove-DNS",
test_suite = 'unittest2.collector',
entry_points="""
[console_scripts]
powerglovedns = powerglove_dns:main
""",
packages=find_packages(exclude=['ez_setup']),
include_package_data=True,
classifiers=[
'License :: OSI Approved :: MIT License',
'Development Status :: 5 - Production/Stable',
],
**extra_setup
)
|
UTF-8
|
Python
| false | false | 2,013 |
1,949,915,184,705 |
1bca0d375f7e15a441d59fa7d53ab93591fafacd
|
a2676d947a1117f55aa56bf204af91e2fc4e14c1
|
/sw/interface/bsvparse.py
|
dabfd331cb972e02768b1b1b76b43bfda412ea13
|
[] |
no_license
|
jwcxz/bt
|
https://github.com/jwcxz/bt
|
1c21a56e0c9ffb8f500122d5f8f860f488f65df7
|
7201f061a3ea2b5d1f8d6f1524c6418feb67ea29
|
refs/heads/master
| 2016-09-06T02:19:13.690233 | 2013-05-15T20:14:17 | 2013-05-15T20:14:17 | null | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null |
import re
re_met = re.compile('.*typedef\s+(?P<num>\d+)\s+NumMetronomes;.*');
re_base = re.compile('.*Real\s+min_tempo\s+=\s+(?P<base>\d+)\s*;.*');
def get_num_base(fname):
f = open(fname, 'r');
num = None;
base = None;
for line in f:
if re_met.search(line):
num = int(re_met.search(line).groupdict()['num']);
elif re_base.search(line):
base = int(re_base.search(line).groupdict()['base']);
if num != None and base != None:
break;
f.close();
return (num, base);
|
UTF-8
|
Python
| false | false | 2,013 |
2,911,987,868,233 |
924f2cdcc3ed74c14388977dd13db38f06cf752a
|
b83bd2709729ac2eb65026ba6e377d619371369a
|
/game/role.py
|
db0a66c66c4e04251b044a8a1b43b82c2549f662
|
[] |
no_license
|
main1015/pygame-demo
|
https://github.com/main1015/pygame-demo
|
cbc36a1066497346a14c016c5904106740ef0aac
|
a6bebfdc7f21ec675f29155f039d410431785050
|
refs/heads/master
| 2021-01-22T05:05:20.932704 | 2013-07-04T09:37:05 | 2013-07-04T09:37:05 | 11,117,996 | 0 | 1 | null | null | null | null | null | null | null | null | null | null | null | null | null |
# -*- coding: utf-8 -*-
import pygame
from wx import Rect
from gameobjects.vector2 import Vector2
from game.util import load_character
__author__ = 'Administrator'
class RoleIcon(pygame.sprite.Sprite):
_rate = 100
_width = 100
_height = 120
_X_STEP = 80
_Y_STEP = 0
X_STEP = _X_STEP
Y_STEP = _Y_STEP
_w_number = 8
_h_number = 4
isOver = False
move_step = 1
step = 0
images = []
MAX = 10
def __init__(self,filename):
self.order = 0
pygame.sprite.Sprite.__init__(self)
if len(self.images) == 0:
self.images = load_character(filename, self._width,self._height,self._w_number,self._h_number)
self.image = self.images[self.order]
self.rect = Rect(0, 0, self._width, self._height)
# self.life = self._life
self.passed_time = 0
self.rect.left = 0
self.rect.top = 0
self.count = 1
def _isRun(self):
self.count += 1
if self.count > self.MAX:
self.count = 1
return True
else:
return False
def update(self,current_time):
self.move()
# if self.passed_time < current_time:
# self.step += 1
# if self.step == self._w_number:
# self.step = 0
# self.order = self.step
# self.image = self.images[self.order]
# self.rect.left,self.rect.top = pygame.mouse.get_pos()
# self.move()
def set_move(self,form_to):
self.form_to = form_to
x,y = self.form_to
start_point = Vector2(self.rect.left,self.rect.top)
end_point = Vector2(x,y)
point = end_point - start_point
if point:
self.isOver = True
self.move_step = self._get_step(point[0])
def move(self):
if self._isRun():
self.step += 1
if self.step == self._w_number:
self.step = 0
self.order = self.step
self.image = self.images[self.order]
if self.isOver:
self._move()
def _move(self):
x,y = self.form_to
start_point = Vector2(self.rect.left,self.rect.top)
end_point = Vector2(x,y)
point = end_point - start_point
self.Y_STEP = (point[1]//self.move_step) if self.move_step else 0
if point[0]*self.X_STEP<0:
self.X_STEP = -self.X_STEP
if point[1]*self.Y_STEP<0:
self.Y_STEP = -self.Y_STEP
self.move_step = self.move_step-1 if self.move_step-1 >=1 else 1
if self.move_step == 1:
self.isOver = False
self.X_STEP = self._X_STEP
self.Y_STEP = self._Y_STEP
self.rect.left = x
# if self.rect.top>=y:
self.rect.top = y
else:
self.rect.left += self.X_STEP
self.rect.top += self.Y_STEP
print '~'*20,self.rect.left,self.rect.top,self.X_STEP,self.Y_STEP,self.move_step,x,y
def _get_step(self,distance):
steps = abs(distance // self.X_STEP)
if distance % self.X_STEP !=0:
steps += 1
return steps
|
UTF-8
|
Python
| false | false | 2,013 |
18,957,985,668,722 |
51f11ea9da9beec21950a275c7e70513ad58a722
|
8b174ba337dfbe3891023f571b70abff07b0dcc8
|
/main.py
|
55148803872aa4f73f3deb4d7b8550a6a2b9e171
|
[] |
no_license
|
zar1n/dir-to-json
|
https://github.com/zar1n/dir-to-json
|
db7d0341b571966c5a7d2ad1963ad48a7814c65a
|
3878c0955417b53f192109492b744eeb2b4c0c2c
|
refs/heads/master
| 2020-05-18T07:53:00.558966 | 2014-07-09T08:49:55 | 2014-07-09T08:49:55 | null | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null |
# -*- coding: utf-8 -*-
__author__ = "Kosovets Sergey @ Zar1n"
import os
import json
import hashlib
class Dirtojson:
configExclude = "exclude.txt"
configExportJson = "export.json"
def walkdir(self, path):
dirJson = []
filesJson = []
dirJson.append({'app_v': 1, 'dbv_v': 1, 'files': filesJson})
fileEx = self.exclude()
for dirRoot, dirDir, dirFile in os.walk(path, topdown=True):
dirDir[:] = [d for d in dirDir if d not in fileEx]
for file in dirFile:
filePath = "%s/%s" % (dirRoot, file)
fileHash = hashlib.md5(filePath).hexdigest()
if file not in fileEx:
if os.path.basename(dirRoot):
filesJson.append({'name': file, 'directory': os.path.basename(dirRoot), 'hash': fileHash})
else:
filesJson.append({'name': file, 'hash': fileHash})
self.writeToFile(json.dumps(dirJson, indent=2, ensure_ascii=False))
def exclude(self):
exList = []
exDesc = open(self.configExclude, 'rb')
for exLine in exDesc:
exList.append(exLine.rstrip('\n'))
return exList
def writeToFile(self, jsonDumps):
exportFileDesc = open(self.configExportJson, 'wb')
exportFileDesc.write(jsonDumps)
main = Dirtojson()
main.walkdir("J:\@Movie\\")
|
UTF-8
|
Python
| false | false | 2,014 |
4,638,564,718,917 |
47d9849f24bc01eb59245534a331729c37ef8241
|
a385c994db96c38646f3b6142e0dc9648b30fa37
|
/plot_output.py
|
6206b7f2c05026edce9f1921c1ac0a29903ad204
|
[] |
no_license
|
glinka/apc523_hw1
|
https://github.com/glinka/apc523_hw1
|
0f36eeef19e14481addbd799f9d10228db79a037
|
f271a17da27f3bcc08d5c83d44715321bfe8fde6
|
refs/heads/master
| 2021-01-19T07:30:38.854367 | 2013-10-09T03:15:06 | 2013-10-09T03:15:06 | null | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null |
import numpy as np
import matplotlib.pyplot as plt
import os
def get_data(filename, header_rows=1, **kwargs):
path_to_file = os.path.realpath(filename)
data = np.genfromtxt(path_to_file, skip_header=header_rows, **kwargs)
if header_rows > 0:
f = open(path_to_file, "r")
params_str = f.readline()
params = get_header_data(params_str)
f.close()
print params
return data, params
else:
return data
def make_filename(base_name, params, unique_id=''):
filename = base_name
for key in params.keys():
filename = filename + '_' + key + '_' + str(params[key])
if not unique_id:
filename = filename + '_' + unique_id
return filename
def plot_grid(data, params):
x_min = params['x_min']
x_max = params['x_max']
y_min = params['y_min']
y_max = params['y_max']
n = params['n']
x_inc = (x_max-x_min)/(n+1)
y_inc = (y_max-y_min)/(n+1)
fig = plt.figure()
ax = fig.add_subplot(111)
ax.set_xlim((x_min, x_max))
ax.set_ylim((y_min, y_max))
x_range = np.linspace(x_min, x_max, n)
y_range = np.linspace(y_min, y_max, n)
xgrid, ygrid = np.meshgrid(x_range, y_range)
ax.contourf(xgrid, ygrid, data)
plt.show()
if __name__=="__main__":
import argparse
parser = argparse.ArgumentParser()
parser.add_argument('input_files', nargs='+')
args = parser.parse_args()
#change after properly including header in data files
for file in args.input_files:
data = get_data(file, header_rows=0)
print data
fig = plt.figure()
ax = fig.add_subplot(111)
ax.scatter(data[:,2], np.reciprocal(data[:,3]))
ax.set_xlabel("total number threads")
ax.set_ylabel("reciprocal time to completion")
plt.savefig(file[:-3] + "png")
|
UTF-8
|
Python
| false | false | 2,013 |
4,810,363,373,427 |
eeb1de37ac86522acc4276844d1204d86e92f1d7
|
bfaf79f294427f7ff89a8ec0f4b43d40e5d43523
|
/everhash/albums/forms.py
|
742456a90fb14514951e1593ef0aebaabf849154
|
[] |
no_license
|
hguochen/everhash
|
https://github.com/hguochen/everhash
|
4e2c857d63f0282e7fc8fb7979e6bcf02733c918
|
45d3f5b66b4fe56899a931c3e87be7ad707c10a8
|
refs/heads/master
| 2021-01-23T05:35:33.686831 | 2014-07-01T08:52:51 | 2014-07-01T08:52:51 | null | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null |
# std lib imports
# django imports
from django import forms
from django.forms import ModelForm
# 3rd party app imports
# app imports
class AlbumForm(forms.Form):
"""
Album forms capture only a single hashtag field. Users who submit to this field will indicate a new album setup.
"""
hashtag = forms.CharField(max_length = 254,
widget=forms.TextInput(attrs={'type':'text',
'class': 'form-control',
'placeholder':'Enter an album name here. eg. apple, orange etc.'}))
|
UTF-8
|
Python
| false | false | 2,014 |
17,463,337,027,308 |
5a36f7bcdd126242bb6aab17703adbbba3d0b0d5
|
ea3edf571c25c29501dc05eadaa0143ec5723ffc
|
/p4a/subtyper/submenu.py
|
3996875068678a510b73db3d61dc7f39dd2089eb
|
[] |
no_license
|
ploneUN/ilo.compatplone3
|
https://github.com/ploneUN/ilo.compatplone3
|
d24b59562ba9ac030cb6ae9519e039b9903d336a
|
df837d775ec82c0c857ff5a27091598cd84ba65f
|
refs/heads/master
| 2020-05-20T07:28:27.902904 | 2014-01-24T08:52:52 | 2014-01-24T08:52:52 | null | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null |
from plone.app.contentmenu.interfaces import IActionsSubMenuItem
from zope.app.publisher.browser.menu import BrowserSubMenuItem
from zope import interface
import warnings
class SubtypesSubMenuItem(BrowserSubMenuItem):
interface.implements(IActionsSubMenuItem)
title = u'Sub-types'
description = u''
submenuId = u'subtypes'
order = 9
extra = {'id': 'subtypes'}
@property
def action(self):
return self.context.absolute_url()+ '/subtypes'
def available(self):
warnings.warn('Subtyper is no longer available',
DeprecationWarning)
return False
|
UTF-8
|
Python
| false | false | 2,014 |
8,246,337,238,406 |
c2b60fc5448a11b26ae1cfb4efe2ac23c07acdab
|
c54f5a7cf6de3ed02d2e02cf867470ea48bd9258
|
/pyobjc/pyobjc-framework-Quartz/PyObjCTest/test_qcrenderer.py
|
a33b6fa4899f1c2b09bd32bf467f41f141a8a374
|
[
"MIT"
] |
permissive
|
orestis/pyobjc
|
https://github.com/orestis/pyobjc
|
01ad0e731fbbe0413c2f5ac2f3e91016749146c6
|
c30bf50ba29cb562d530e71a9d6c3d8ad75aa230
|
refs/heads/master
| 2021-01-22T06:54:35.401551 | 2009-09-01T09:24:47 | 2009-09-01T09:24:47 | 16,895 | 8 | 5 | null | null | null | null | null | null | null | null | null | null | null | null | null |
from PyObjCTools.TestSupport import *
from Quartz.QuartzComposer import *
class TestQCRendererHelper (NSObject):
def setValue_forInputKey_(self, v, k): return 1
class TestQCRenderer (TestCase):
def testConstants(self):
self.failUnlessIsInstance(QCRendererEventKey, unicode)
self.failUnlessIsInstance(QCRendererMouseLocationKey, unicode)
def testMethods(self):
self.failUnlessResultIsBOOL(TestQCRendererHelper.setValue_forInputKey_)
self.failUnlessResultIsBOOL(QCRenderer.renderAtTime_arguments_)
if __name__ == "__main__":
main()
|
UTF-8
|
Python
| false | false | 2,009 |
14,276,471,338,882 |
a6c2e9b93745562143bb08c654220f04adcfafc6
|
a803b0acb7a41bd5ca6d7bfcecc7cee10ba4e0da
|
/plugin/customAuthPlugin/project/projectFactory.py
|
31f490211a61ea8066558e963e5cd93cf7553084
|
[] |
no_license
|
SimonEbner/CustomAuthPlugin
|
https://github.com/SimonEbner/CustomAuthPlugin
|
cc91208c994c228b1765cd3d536707018030dad2
|
6196ac23ce95f7d62a0492247bcf192a06df5e70
|
refs/heads/master
| 2018-12-28T08:14:15.977558 | 2013-05-07T14:04:05 | 2013-05-07T14:04:05 | null | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null |
from project import Project
class ProjectFactory( object ):
_cache = {}
def __init__( self, config ):
self._config = config
def getByName( self, name ):
if not name in ProjectFactory._cache:
ProjectFactory._cache[ name ] = Project( name )
return ProjectFactory._cache[ name ]
def getAllByNames( self, names ):
return [ self.getByName( name ) for name in names ]
def getAll( self ):
return self.getAllByNames( self.getAllIDs() )
def getAllIDs( self ):
concatenatedProjects = self._config.get( 'ticket-custom', 'project.options' )
return concatenatedProjects.split( '|' )
|
UTF-8
|
Python
| false | false | 2,013 |
1,743,756,765,575 |
a1c73d4eefd6ca07a1855ce10e50b307c32a7b1b
|
981c3c57ca103324fbd227a720a6ceebccc74e22
|
/galleryget.py
|
3276a90f724809f114a4fc43699fc115385b14b9
|
[
"GPL-3.0-or-later"
] |
non_permissive
|
jgoerzen/gallery2flickr
|
https://github.com/jgoerzen/gallery2flickr
|
acc71f890577285d2e973020a9734565965e704a
|
bc6016b8a6c60db1179eadc2835956181eba3086
|
refs/heads/master
| 2020-04-23T03:07:09.529607 | 2010-04-20T20:22:08 | 2010-04-20T20:22:08 | null | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null |
import simplejson
from galleryremote import Gallery
import sys
import os
import urllib
galleryurl = sys.argv[1]
outputdir = sys.argv[2]
print galleryurl
g = Gallery(galleryurl, 2)
albums = g.fetch_albums()
os.mkdir(outputdir)
open(outputdir + "/albums.info", "w").write(simplejson.dumps(albums, indent=4))
for (album, albuminfo) in albums.items():
print " *** Processing album %s\n" % album
images = g.fetch_album_images(album)
albumpath = "%s/%s" % (outputdir, album)
os.mkdir(albumpath)
open("%s/images.info" % albumpath, "w").write(simplejson.dumps(images, indent=4))
for image in images:
print "Downloading image " + image['name']
urllib.urlretrieve(galleryurl +
"/main.php?g2_view=core%3ADownloadItem&g2_itemId=" +
image['name'],
albumpath + "/" + image['name'] + ".data")
|
UTF-8
|
Python
| false | false | 2,010 |
10,874,857,194,971 |
e08cec3f6d8b1bdbf5715c0a065a6a33265090f2
|
377eaa1ab07adc858f80b858a24af92b36265aac
|
/upload-image/tags/v.0.2/upimg/featurechecker.py
|
b6f07e534f7705e48028d91d1cc0293b763940b6
|
[
"GPL-2.0-only"
] |
non_permissive
|
pombreda/upload-image
|
https://github.com/pombreda/upload-image
|
61a9e5d7e3849e03a155482d4b6da05629f6db27
|
a57b854e22f9481945be17619086874dd0d5804c
|
refs/heads/master
| 2021-01-23T11:55:12.564936 | 2010-08-30T16:19:55 | 2010-08-30T16:19:55 | 32,209,236 | 1 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null |
# vim: expandtab sw=4 ts=4 :
__author__ = "Sergei Stolyarov"
__email__ = "sergei@regolit.com"
import sys
import os
import stat
import gettext
_ = gettext.gettext
supported_features = ("filesize_limit")#, "supported_formats", "max_img_width", "max_img_height")
# throw when feature is unknown
class UnknownFeature(Exception):
pass
class NotConform(Exception):
def __init__(self, value):
self.value = value
def __str__(self):
return self.value
pass
def check_feature(feature_name, feature_data, filename):
'''
Check that given file conform given feature. If doesn't function
will throw an exception.
'''
if not feature_name in supported_features:
raise UnknownFeature()
function_name = "checker_%s" % feature_name
function = globals()[function_name]
function(feature_data, filename)
def checker_filesize_limit(data, filename):
filesize = os.stat(filename)[stat.ST_SIZE]
if data < filesize:
raise NotConform(_("file `%s' is too large, it should be less than %d bytes") % (filename, data) )
|
UTF-8
|
Python
| false | false | 2,010 |
5,488,968,236,802 |
49747799f8450e7e559fb97edeeb5b8c44b56bde
|
61da92907fc371aaca0a280cc3539a02b61805fe
|
/shr_settings_modules/shr_device_timeouts.py
|
775e473df2ddfe3ad6733615abca0e68f36bf475
|
[
"GPL-2.0-only"
] |
non_permissive
|
OpenPhoenux/shr-settings
|
https://github.com/OpenPhoenux/shr-settings
|
c4749686cac68e9c74a934d4f22dcdd63f8627e5
|
c60ab60d781ad478b55073ee696d629faa434a93
|
refs/heads/master
| 2023-05-29T14:37:12.400568 | 2014-05-19T22:14:02 | 2014-05-19T22:14:02 | null | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null |
import module, elementary
import dbus
from helper import getDbusObject
# Locale support
import gettext
try:
cat = gettext.Catalog("shr-settings")
_ = cat.gettext
except IOError:
_ = lambda x: x
def dbus_ok(*args, **kargs):
pass
def dbus_err(x, *args, **kargs):
print str(x)
class ValueLabel( elementary.Label ):
""" Label that displays current timeout """
def __init__(self, win):
self._value = None
super(ValueLabel, self).__init__(win)
def get_value(self):
return self._value
def set_value(self, val):
self.text_set(str(val) + _(" sec."))
self._value = val
class IncDecButton(elementary.Button):
"""
Button that add/substracts from the value label
"""
def set_Delta(self, delta):
self._delta = delta
self.text_set("{0:+d}".format(delta))
def get_Delta( self ):
return self._delta
class IncDecButtonBox(elementary.Box):
"""
Object which shows an increment/decrement button set to alter int
Preferences values
"""
def IncDecButtonClick(self, obj, *args, **kargs):
"""
Callback function when +-[1,10] timeout buttons have been pressed
"""
cur_val = self.cur_value
delta = obj.get_Delta()
new_val = max(-1, cur_val + delta)
self.dbusObj.SetTimeout(self.item_name,int(new_val), reply_handler=dbus_ok, error_handler=dbus_err)
self.cur_value = new_val
self.itemValue.set_value(self.cur_value)
def update(self):
"""
Updates the displayed value to the current profile
"""
timeouts = self.dbusObj.GetTimeouts()
self.cur_value = timeouts[self.item_name]
self.itemValue.set_value(self.cur_value) #implicitely sets label too
def setup(self):
"""
Function to show a increment/decrement button set to alter int
Preferences values
Layout developed from shr_device_timeouts.py
"""
self.horizontal_set(True)
self.size_hint_align_set(-1.0, 0.0)
self.size_hint_weight_set(1.0, 0.0)
itemLabel = elementary.Label(self.window)
itemLabel.size_hint_weight_set(1.0, 0.0)
itemLabel.text_set(self.item_name.replace("_"," ").title())
itemLabel.show()
itemFrame = elementary.Frame(self.window)
itemFrame.style_set("outdent_top")
itemFrame.content_set(itemLabel)
itemFrame.show()
self.itemValue = ValueLabel(self.window)
self.itemValue.size_hint_weight_set(1.0, 0.0)
self.itemValue.set_value(self.cur_value) #implicitely sets label too
self.itemValue.show()
boxbox = elementary.Box(self.window)
boxbox.pack_start(itemFrame)
boxbox.pack_end(self.itemValue)
boxbox.size_hint_weight_set(1.0, 0.0)
boxbox.show()
buttons = []
for step in [-10, -1, 1, 10]:
btn = IncDecButton(self.window)
btn.set_Delta( step )
btn._callback_add('clicked', self.IncDecButtonClick)
btn.size_hint_align_set(-1.0, 0.0)
btn.show()
buttons.append(btn)
self.pack_end(buttons[0])
self.pack_end(buttons[1])
self.pack_end(boxbox)
self.pack_end(buttons[2])
self.pack_end(buttons[3])
self.show()
def __init__(self, win, dbusObj, item_name, initial_value):
"""
initialize the box and load objects
"""
super(IncDecButtonBox, self).__init__(win)
self.window = win
self.dbusObj = dbusObj
self.item_name = item_name
self.cur_value = initial_value
self.setup()
class Timeouts(module.AbstractModule):
name = _("Timeouts settings")
def error(self):
label = elementary.Label(self.window)
label.text_set(_("Couldn't connect to FSO"))
label.show()
self.main.pack_start(label)
def createView(self):
self.main = elementary.Box(self.window)
self.dbus_state = 0
try:
self.dbusObj = getDbusObject( self.dbus,
"org.freesmartphone.odeviced",
"/org/freesmartphone/Device/IdleNotifier/0",
"org.freesmartphone.Device.IdleNotifier")
self.timeouts = self.dbusObj.GetTimeouts()
self.dbus_state = 1
except:
self.dbus_state = 0
self.error()
tmptimeouts = sorted(self.timeouts.iteritems(), key=lambda (k,v): (v,k))
if self.dbus_state:
for i in tmptimeouts:
if not str(i[0]) in ("awake","busy","none"):
box = IncDecButtonBox(self.window, self.dbusObj, i[0], i[1])
self.main.pack_end(box)
self.main.show()
return self.main
|
UTF-8
|
Python
| false | false | 2,014 |
8,160,437,908,833 |
c1480f749ab981bd99a2fd6ae9e2077c5b19d02a
|
e751fe231e4d64a37a8b6acea7c5ffbe6348086e
|
/烽烟OL/fengyanOL - v1.7.0/sanguo - v1.70/app/scense/publicnodeapp/restart.py
|
f051ed6c9fa96e724539c0a099cfd5541ff0aae9
|
[] |
no_license
|
guitao/crossapp-demo
|
https://github.com/guitao/crossapp-demo
|
f2efce013bb0604ae47eee9196f8e6998de1deb3
|
7413d98d1bc38ba66ef937842488d0b661378765
|
refs/heads/master
| 2021-01-16T19:50:08.151025 | 2014-05-23T00:17:49 | 2014-05-23T00:17:49 | null | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null |
##coding:utf8
#'''
#Created on 2012-8-7
#动态重启模块
#@author: Administrator
#'''
#
#def ModuleLoader():
# '''重新加载模块'''
## from chatnodeapp import gmapp
## from chatnodeapp import gmcommand
## reload(gmapp)
## reload(gmcommand)
# from app.scense.applyInterface import configure
# reload(configure)
# from app.scense.component.pack import CharacterPackComponent
# reload(CharacterPackComponent)
# from app.scense.core.character import PlayerCharacter
# reload(PlayerCharacter)
# try:
# from app.scense.nodeapp import entrance
# reload(entrance)
# from app.scense.publicnodeapp import admin
# reload(admin)
# from app.scense.applyInterface import playerInfo,shop,login,InstanceColonizeGuerdon
# reload(playerInfo)
# reload(shop)
# reload(login)
# reload(InstanceColonizeGuerdon)
# except Exception,e:
# pass
#
#
#
#
#
#
#
#
|
UTF-8
|
Python
| false | false | 2,014 |
11,845,519,822,993 |
8816d5ae94dba33053a785b9a3a0eea81bc7b90c
|
5862f1076e51336ff0e47d807ac61165c913cd27
|
/common/migrations/0003_auto__add_deletedcounter__add_unique_deletedcounter_target_date_type__.py
|
610fece3476fe6d4ea8b2fb9bf59bc10406ad9d2
|
[] |
no_license
|
lipengbo/portal
|
https://github.com/lipengbo/portal
|
416e4d14e2eba3c2b49c0c32fb9a8753c2f85b9d
|
6560afe6f2f36bf72b68068ea3ff0c0ddcd38042
|
refs/heads/master
| 2020-05-20T00:30:53.075217 | 2014-07-08T08:03:01 | 2014-07-08T08:03:01 | null | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null |
# -*- coding: utf-8 -*-
import datetime
from south.db import db
from south.v2 import SchemaMigration
from django.db import models
class Migration(SchemaMigration):
def forwards(self, orm):
# Adding model 'DeletedCounter'
db.create_table('common_deletedcounter', (
('id', self.gf('django.db.models.fields.AutoField')(primary_key=True)),
('target', self.gf('django.db.models.fields.IntegerField')()),
('count', self.gf('django.db.models.fields.PositiveIntegerField')(default=0)),
('date', self.gf('django.db.models.fields.DateField')(auto_now_add=True, blank=True)),
('type', self.gf('django.db.models.fields.IntegerField')()),
))
db.send_create_signal('common', ['DeletedCounter'])
# Adding unique constraint on 'DeletedCounter', fields ['target', 'date', 'type']
db.create_unique('common_deletedcounter', ['target', 'date', 'type'])
# Adding model 'FailedCounter'
db.create_table('common_failedcounter', (
('id', self.gf('django.db.models.fields.AutoField')(primary_key=True)),
('target', self.gf('django.db.models.fields.IntegerField')()),
('count', self.gf('django.db.models.fields.PositiveIntegerField')(default=0)),
('date', self.gf('django.db.models.fields.DateField')(auto_now_add=True, blank=True)),
('type', self.gf('django.db.models.fields.IntegerField')()),
))
db.send_create_signal('common', ['FailedCounter'])
# Adding unique constraint on 'FailedCounter', fields ['target', 'date', 'type']
db.create_unique('common_failedcounter', ['target', 'date', 'type'])
def backwards(self, orm):
# Removing unique constraint on 'FailedCounter', fields ['target', 'date', 'type']
db.delete_unique('common_failedcounter', ['target', 'date', 'type'])
# Removing unique constraint on 'DeletedCounter', fields ['target', 'date', 'type']
db.delete_unique('common_deletedcounter', ['target', 'date', 'type'])
# Deleting model 'DeletedCounter'
db.delete_table('common_deletedcounter')
# Deleting model 'FailedCounter'
db.delete_table('common_failedcounter')
models = {
'common.counter': {
'Meta': {'unique_together': "(('target', 'date', 'type'),)", 'object_name': 'Counter'},
'count': ('django.db.models.fields.PositiveIntegerField', [], {'default': '0'}),
'date': ('django.db.models.fields.DateField', [], {'auto_now_add': 'True', 'blank': 'True'}),
'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}),
'target': ('django.db.models.fields.IntegerField', [], {}),
'type': ('django.db.models.fields.IntegerField', [], {})
},
'common.deletedcounter': {
'Meta': {'unique_together': "(('target', 'date', 'type'),)", 'object_name': 'DeletedCounter'},
'count': ('django.db.models.fields.PositiveIntegerField', [], {'default': '0'}),
'date': ('django.db.models.fields.DateField', [], {'auto_now_add': 'True', 'blank': 'True'}),
'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}),
'target': ('django.db.models.fields.IntegerField', [], {}),
'type': ('django.db.models.fields.IntegerField', [], {})
},
'common.failedcounter': {
'Meta': {'unique_together': "(('target', 'date', 'type'),)", 'object_name': 'FailedCounter'},
'count': ('django.db.models.fields.PositiveIntegerField', [], {'default': '0'}),
'date': ('django.db.models.fields.DateField', [], {'auto_now_add': 'True', 'blank': 'True'}),
'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}),
'target': ('django.db.models.fields.IntegerField', [], {}),
'type': ('django.db.models.fields.IntegerField', [], {})
}
}
complete_apps = ['common']
|
UTF-8
|
Python
| false | false | 2,014 |
13,297,218,748,953 |
235154bd02d6d45b52008dc036575f3125c5a5b8
|
7678733a4d920abd948c3b44c89e52e277d0a7d4
|
/hello.py
|
e6411586de1bb37611b3c66f052f7f5c0e41c0e1
|
[] |
no_license
|
hsamra/CT_python
|
https://github.com/hsamra/CT_python
|
080cb1daa3fa67c4c6af52b86eee67ef127d505b
|
b8c6663c30fc0ca3eda1e24bf072b7310cbb8a11
|
refs/heads/master
| 2020-06-04T14:47:17.681381 | 2011-10-22T11:54:48 | 2011-10-22T11:54:48 | 2,625,718 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null |
samrin_babo = "hernad"
# samrin_babo = "huso"
if samrin_babo == "hernad":
print "hello from Samra Husremovic"
else:
print "hello from neka druga Samra"
|
UTF-8
|
Python
| false | false | 2,011 |
8,589,948,038 |
06492fd8c4055eca4cf13aaed14c8ef201e027f1
|
153ecce57c94724d2fb16712c216fb15adef0bc4
|
/grok/branches/0.10/doc/examples/adder/src/adder/tests/test_adder.py
|
410a106feb2f454415b3c2cb9406202a65a65a82
|
[
"ZPL-2.1"
] |
permissive
|
pombredanne/zope
|
https://github.com/pombredanne/zope
|
10572830ba01cbfbad08b4e31451acc9c0653b39
|
c53f5dc4321d5a392ede428ed8d4ecf090aab8d2
|
refs/heads/master
| 2018-03-12T10:53:50.618672 | 2012-11-20T21:47:22 | 2012-11-20T21:47:22 | null | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null |
import unittest
from pkg_resources import resource_listdir
from zope.testing import doctest, cleanup
from adder import app
def cleanUpZope(test):
cleanup.cleanUp()
def test_suite():
suite = unittest.TestSuite()
test = doctest.DocTestSuite(app,
tearDown=cleanUpZope,
optionflags=doctest.ELLIPSIS+
doctest.NORMALIZE_WHITESPACE)
suite.addTest(test)
return suite
if __name__ == '__main__':
unittest.main(defaultTest='test_suite')
|
UTF-8
|
Python
| false | false | 2,012 |
5,763,846,157,807 |
7a6a5b083a6085b657788aceed2df57b9554bc31
|
0481210c9d8a3c296303d9e616862b6e7af49025
|
/msd/researchtheme/content/researchtheme.py
|
09dfc54386a75ad5c9bbcdd44155b148817d1103
|
[] |
no_license
|
envycontent/msd.researchtheme
|
https://github.com/envycontent/msd.researchtheme
|
fd3e6134ee228df5b4494a201b04ed6eedced7a2
|
b8acf9e7903fa50eec5e3ec65a4b453fcd15a48d
|
refs/heads/master
| 2020-05-21T13:17:15.605360 | 2013-08-08T13:13:04 | 2013-08-08T13:13:04 | null | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null |
"""Definition of the Research Theme content type
"""
from zope.interface import implements, directlyProvides
from Products.Archetypes import atapi
from Products.ATContentTypes.content import folder
from Products.ATContentTypes.content import schemata
from Products.ATReferenceBrowserWidget.ATReferenceBrowserWidget import ReferenceBrowserWidget
from Products.CMFPlone.interfaces import INonStructuralFolder
from msd.picturelink.content import picturelink
from msd.researchbase.content.researchschemas import SideBoxSchema
from msd.researchtheme import researchthemeMessageFactory as _
from msd.researchtheme.interfaces import IResearchTheme
from msd.researchtheme.config import PROJECTNAME
from msd.researchbase.interfaces import IResearcher
ResearchThemeSchema = picturelink.PictureLinkSchema.copy() + SideBoxSchema.copy() + atapi.Schema((
# -*- Your Archetypes field definitions here ... -*-
atapi.StringField(
name='linkCaption',
storage = atapi.AnnotationStorage(),
required=False,
#searchable=1,
default = "Read more ...",
#schemata ='default',
widget=atapi.StringWidget(
description = 'E.g.:"Read more ..." or "Personal Website", leave blank to show the link itself',
label = _(u'label_url', default=u'Link Caption'),
),
),
atapi.ReferenceField(
name='researchers',
widget=ReferenceBrowserWidget(
label="Researchers",
description="Researchers associated with this theme",
base_query={'object_provides': IResearcher.__identifier__ },
allow_browse=0,
show_results_without_query=1,
),
multiValued=1,
relationship="researchers_in_theme"
),
))
ResearchThemeSchema['remoteUrl'].widget.description = 'Website or page to link to, set to blank for no link'
ResearchThemeSchema.addField(schemata.relatedItemsField.copy())
schemata.finalizeATCTSchema(
ResearchThemeSchema,
moveDiscussion=False
)
class ResearchTheme(picturelink.PictureLink):
"""A researchtheme or short summary with image and link"""
implements(IResearchTheme)
meta_type = "ResearchTheme"
schema = ResearchThemeSchema
# -*- Your ATSchema to Python Property Bridges Here ... -*-
def getResearchThemeTitle(self):
return self.Title()
atapi.registerType(ResearchTheme, PROJECTNAME)
|
UTF-8
|
Python
| false | false | 2,013 |
10,282,151,711,544 |
10c834f2cbdd6a7f214176f7451f8cb6d32f1765
|
ee4b84b3d5de1658e7b26ff689c2ec27d9499fcf
|
/list_bad_l3_agents.py
|
746fb97f76e832b556f0a019d1b67d3a264f9e7e
|
[] |
no_license
|
falfaro/openstack-tools
|
https://github.com/falfaro/openstack-tools
|
9ead65456ef23d38988a2bd5c9ccc128696829b6
|
6ea81d7197da53c66f8d303dafc40d25c8d7a978
|
refs/heads/master
| 2020-05-17T17:27:20.965087 | 2014-10-28T10:59:13 | 2014-10-28T10:59:13 | null | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null |
#!/usr/bin/python
# Copyright 2014 Felipe Alfaro Solana
# All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License"); you may
# not use this file except in compliance with the License. You may obtain
# a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
# WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
# License for the specific language governing permissions and limitations
# under the License.
"""
list_bad_l3_agents.py is a Python tool that relies on the OpenStack API to
gather a list of Neutron L3 agents that are being reported as bad by Neutron
Server.
This tool reads DEBUG log lines from stdin (usually piped from neutron-server
log files in /var/log/neutron/server.log) to find those L3 agents that are
not reporting their state at the right rate. L3 agents report their state back
to Neutron server every report_interval seconds (defined inside the AGENT
section in /etc/neutron/neutron.conf).
"""
import collections
import datetime
import re
import sys
NEUTRON_BINARY = 'neutron-l3-agent'
# Regular expression used to match DEBUG log lines corresponding to the
# report_state RPC method call
REPORT_STATE_RE = re.compile(r"""
# GROUP 1
(
\d{4}-\d{2}-\d{2} # YYYY-MM-DD
\s
\d{2}:\d{2}:\d{2} # HH:MM:SS
)
\.\d{3} # Miliseconds
\s\d+\sDEBUG\sneutron.openstack.common.rpc.amqp\s\[-\]\sreceived\s
# GROUP 2
(
{.*u'method':\su\'report_state\'.*} # Log data (Pytthon dict as str)
)
""", re.VERBOSE)
def is_report_interval(ts1, ts2, report_interval=60, epsilon=1):
"""Returns whether (ts1 - ts2) is less than report_interval seconds."""
tdelta = abs(ts1 - ts2)
report_interval = datetime.timedelta(seconds=report_interval)
epsilon = datetime.timedelta(seconds=epsilon)
return abs(report_interval - tdelta) <= epsilon
def parse_log_line(line):
"""Parses data from a DEBUG log line."""
m = REPORT_STATE_RE.match(line)
if not m:
return None, None, None
log_data = eval(m.group(2))
ts = datetime.datetime.strptime(m.group(1), '%Y-%m-%d %H:%M:%S')
binary = log_data['args']['agent_state']['agent_state']['binary']
vhost = log_data['args']['agent_state']['agent_state']['host']
return ts, binary, vhost
def main():
ts_vhosts = {}
bad_ts_vhosts = collections.defaultdict(list)
processed = collections.defaultdict(lambda: 0)
bad = collections.defaultdict(lambda: 0)
for line in sys.stdin.readlines():
ts, binary, vhost = parse_log_line(line)
if not ts:
continue
if binary != NEUTRON_BINARY:
continue
if vhost in ts_vhosts:
if not is_report_interval(ts_vhosts[vhost], ts):
bad_ts_vhosts[vhost].append((ts_vhosts[vhost], ts))
bad[vhost] += 1
ts_vhosts[vhost] = ts
processed[vhost] += 1
for vhost in sorted(processed):
for ts1, ts2 in bad_ts_vhosts[vhost]:
print '+ %-20s (%s, %s) (%s)' % (vhost, ts1, ts2, ts2-ts1)
print '= %-20s process events: %d bad events: %d' % (
vhost, processed[vhost], bad[vhost])
if __name__ == "__main__":
sys.exit(main())
|
UTF-8
|
Python
| false | false | 2,014 |
10,797,547,789,028 |
0a6231b1cd4b854074abd858812f2d6296580fbf
|
6af23801afb0f6236cedc191ae541c76967398dc
|
/bin/python/getdata.py
|
0b889513035612fac2e66a3525251f745f78d3e3
|
[] |
no_license
|
HaohanWang/EEGExperiment
|
https://github.com/HaohanWang/EEGExperiment
|
59da2b2a8f4a8f6fd67fd65a2e3724f50754388b
|
e6a593b9ec18008f1b51b96f7bed57f640f79175
|
refs/heads/master
| 2020-05-29T13:18:07.097707 | 2013-04-18T03:33:27 | 2013-04-18T03:33:27 | null | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null |
import sys
import os
path = sys.argv[1]
a = sys.argv[2]
b = []
if len(a)==2:
b.append(a[0]+'.txt')
b.append(a[1]+'.txt')
else:
b.append(a+'.txt')
attri = ['ATTENTION','MEDITATION','RAW','DELTA','THETA','ALPHA1','ALPHA2','BETA1','BETA2','GAMMA1','GAMMA2','CONFUSION']
trText = []
teText = []
Nume = [[],[],[],[],[],[],[],[],[],[],[],[]]
def findpassage(path):
f = []
for (d, p, fl) in os.walk(path):
f.extend(fl)
break
return f
def getArff(filename):
if filename in b:
getTest(filename)
else:
getTrain(filename)
def getTest(title):
text = [line.strip() for line in open(path+title)]
for i in range(len(text)/4, len(text)*3/4):
s = ""
w = text[i].split(',')
for j in range(3,len(w)):
s+=str(int(float(w[j])))+','
if int(float(w[j])) not in Nume[j-3]:
Nume[j-3].append(int(float(w[j])))
teText.append(s[:-1])
def getTrain(title):
text = [line.strip() for line in open(path+title)]
for i in range(len(text)/4, len(text)*3/4):
s = ""
w = text[i].split(',')
for j in range(3,len(w)):
s+=str(int(float(w[j])))+','
if int(float(w[j])) not in Nume[j-3]:
Nume[j-3].append(int(float(w[j])))
trText.append(s[:-1])
def outTest():
f = open('testingdata/testdata.arff', 'w')
f.writelines('@relation 2013-03-24-weka.filters.unsupervised.attribute.NumericToNominal-Rfirst-last\n\n')
for i in range(12):
l = sorted(Nume[i])
s = str(l)[1:-1]
f.writelines('@attribute '+attri[i]+' {'+s+'}\n')
f.writelines('\n')
f.writelines('@data\n')
for i in teText:
f.writelines(i+'\n')
def outTrain():
f = open('trainingdata/traindata.arff', 'w')
f.writelines('@relation 2013-03-24-weka.filters.unsupervised.attribute.NumericToNominal-Rfirst-last\n\n')
for i in range(12):
l = sorted(Nume[i])
s = str(l)[1:-1]
f.writelines('@attribute '+attri[i]+' {'+s+'}\n')
f.writelines('\n')
f.writelines('@data\n')
for i in trText:
f.writelines(i+'\n')
print "do I start?"
titles = findpassage(path)
for t in titles:
getArff(t)
outTest()
outTrain()
|
UTF-8
|
Python
| false | false | 2,013 |
2,671,469,685,884 |
70a38e212a8a5b091eda9ec23a9d719f1e20c239
|
c65be76c99956b7cfeba46101857eed816f94316
|
/HW3/Ford_HW1_Fibonnaci.py
|
d38b5ecafcd1c8fab983b7c67ff7072559238e2f
|
[] |
no_license
|
nasmd/pg2014_Ford
|
https://github.com/nasmd/pg2014_Ford
|
0f64670fc1765587b67b45db29b2a9f9fae9477d
|
3cc1e9ce66145ce8b8bae168110623cc1146265d
|
refs/heads/master
| 2021-01-23T11:56:04.384069 | 2014-12-10T14:00:51 | 2014-12-10T14:00:51 | null | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null |
# -*- coding: utf-8 -*-
# Trent Ford
# 2014-10-20
#Fibonnaci Sequence Function
"""
Created on Tue Sep 23 07:42:55 2014
@author: Trent
"""
def fib(N):
"""Return N Fibonacci numbers
This function takes in the N number of values and outputs N Fibonacci
numbers"""
a,b = 0,1
fibArray = []
fibArray.append(b)
for i in range(N-1):
c = a+b
a = b
b = c
fibArray.append(c)
return fibArray
if __name__ == '__main__':
N = 5
sequence = fib(N)
|
UTF-8
|
Python
| false | false | 2,014 |
3,676,492,046,645 |
29594f34f78822b91d24176044e7dbc463e48f64
|
1067bf0eb2e8b471a2a1dfe92c4865a26578167c
|
/blackjack.py
|
b66490437142ed499aa7a34abb7e25c829a17c1f
|
[] |
no_license
|
virattt/intro-interactive-python
|
https://github.com/virattt/intro-interactive-python
|
fd1e2b936f1b12f81585700f10b44de8d94a22d3
|
42861b59a474c5add28828d4f95feeba39fecc49
|
refs/heads/master
| 2021-01-23T22:11:32.323583 | 2013-07-29T00:45:26 | 2013-07-29T00:45:26 | null | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null |
# Blackjack, the game, by Virat Singh
# This game is written entirely in Python and utilizes the simplegui module
# developed by Scott Rixner, professor of Computer Science at Rice University.
# To most easily launch my Asteroids game, utilize his CodeSkulptor IDE,
# which implements the simplegui module and can be launched via browser
# (Chrome or Firefox highly recommended. CodeSkulptor will NOT work on
# Internet Explorer).
# Blackjack game: http://www.codeskulptor.org/#user16_kjRQMfpYLy_127.py
# To launch game, press the play button (right-facing triangle) at the
# top left of the CodeSkulptor window.
import simplegui
import random
# load card sprite - 949x392 - source: jfitz.com
CARD_SIZE = (73, 98)
CARD_CENTER = (36.5, 49)
card_images = simplegui.load_image("http://commondatastorage.googleapis.com/codeskulptor-assets/cards.jfitz.png")
CARD_BACK_SIZE = (71, 96)
CARD_BACK_CENTER = (35.5, 48)
card_back = simplegui.load_image("http://commondatastorage.googleapis.com/codeskulptor-assets/card_back.png")
# initialize some useful global variables
in_play = False
outcome = ""
score = 0
card_spacing = 50
deck = None
player_hand_value = 0
dealer_hand_value = 0
# define globals for cards
SUITS = ('C', 'S', 'H', 'D')
RANKS = ('A', '2', '3', '4', '5', '6', '7', '8', '9', 'T', 'J', 'Q', 'K')
VALUES = {'A':1, '2':2, '3':3, '4':4, '5':5, '6':6, '7':7, '8':8, '9':9, 'T':10, 'J':10, 'Q':10, 'K':10}
# define card class
class Card:
def __init__(self, suit, rank):
if (suit in SUITS) and (rank in RANKS):
self.suit = suit
self.rank = rank
else:
self.suit = None
self.rank = None
print "Invalid card: ", suit, rank
def __str__(self):
return self.suit + self.rank
def get_suit(self):
return self.suit
def get_rank(self):
return self.rank
def draw(self, canvas, pos):
card_loc = (CARD_CENTER[0] + CARD_SIZE[0] * RANKS.index(self.rank),
CARD_CENTER[1] + CARD_SIZE[1] * SUITS.index(self.suit))
canvas.draw_image(card_images, card_loc, CARD_SIZE, [pos[0] + CARD_CENTER[0], pos[1] + CARD_CENTER[1]], CARD_SIZE)
# define hand class
class Hand:
def __init__(self):
# create Hand object
self.hand = []
def __str__(self):
# return a string representation of a hand
hand_string = ""
for i in range(len(self.hand)):
hand_string += str(self.hand[i]) + " "
return "Hand contains %s" % hand_string
def add_card(self, card):
# add a card object to a hand
self.hand.append(card)
def get_value(self):
# count aces as 1, if the hand has an ace, then add 10 to hand value if it doesn't bust
hand_value = 0
num_of_aces = 0
# traverse through Hand object
# and sum the values of its cards
for value in self.hand:
hand_value += VALUES[Card.get_rank(value)]
# loop through Hand and check if there are
# any aces in it. If there are aces,
# increment the num_of_aces variable by 1
for card in self.hand:
if card.get_rank() == 'A':
num_of_aces += 1
# if the hand has no aces, return hand value
# else if there are aces, add 10 to the hand
# value as long as adding 10 doesn't make the
# hand bust
if num_of_aces == 0:
return hand_value
else:
if hand_value + 10 <= 21:
return hand_value + 10
else:
return hand_value
# helper method that returns true if the hand has
# busted
def busted(self):
if self.get_value() > 21:
return True
else:
return False
def draw(self, canvas, pos):
# draw a hand on the canvas, use the draw method for cards
for card in self.hand:
card.draw(canvas, pos)
pos[0] += 20
# define deck class
class Deck:
def __init__(self):
self.reset_deck()
def reset_deck(self):
self.deck = []
for i in SUITS: # traverse through SUITS list
for j in RANKS: # traverse through RANKS list
self.deck.append(Card(i, j)) # add Card object to list
def shuffle(self):
# use random.shuffle() to shuffle the deck
self.reset_deck() # add cards back to deck and shuffle
random.shuffle(self.deck)
def deal_card(self):
# deal a card object from the deck
return self.deck.pop()
def __str__(self):
# return a string representing the deck
deck_string = ""
for i in range(len(self.deck)):
deck_string += str(self.deck[i]) + " "
return "Deck contains %s" % str(deck_string)
#define event handlers for buttons
def deal():
global outcome, in_play
global deck, player_hand, dealer_hand
deck = Deck()
deck.shuffle()
player_hand = Hand()
dealer_hand = Hand()
player_hand.add_card(deck.deal_card())
player_hand.add_card(deck.deal_card())
dealer_hand.add_card(deck.deal_card())
dealer_hand.add_card(deck.deal_card())
in_play = True
def hit():
global player_hand
global in_play, outcome, score
# if the hand is in play, hit the player
# if busted, assign a message to outcome,
# update in_play and score
if in_play == True:
player_hand.add_card(deck.deal_card())
if player_hand.busted() == True:
outcome = "You have busted."
in_play = False
score -= 1
def stand():
global dealer_hand, player_hand
global outcome, score, in_play
# if hand is in play, repeatedly hit
# dealer until his hand has value 17 or more
if in_play == True:
while dealer_hand.get_value() < 17:
dealer_hand.add_card(deck.deal_card())
if dealer_hand.busted() == True:
outcome = "You win!"
in_play = False
score += 1
else:
if dealer_hand.get_value() >= player_hand.get_value():
outcome = "You lose."
in_play = False
score -= 1
else:
outcome = "You win!"
in_play = False
score += 1
# assign a message to outcome, update in_play and score
# draw handler
def draw(canvas):
# test to make sure that card.draw works, replace with your code below
global player_hand, dealer_hand
global outcome, score
player_hand.draw(canvas, [250, 400])
canvas.draw_text("BLACKJACK", [25, 75], 36, "Blue", "sans-serif")
canvas.draw_text("Score: " + str(score), [25,575], 30, "Black", "sans-serif")
if in_play == True:
canvas.draw_text("Hit or Stand?", [200, 300], 30, "Blue", "sans-serif")
canvas.draw_text("Dealer", [250, 75], 30, "Black", "sans-serif")
canvas.draw_text("Player", [250, 550], 30, "Black", "sans-serif")
dealer_hand.draw(canvas, [250, 100])
canvas.draw_image(card_back, CARD_BACK_CENTER, CARD_BACK_SIZE, [305, 150], CARD_SIZE)
else:
canvas.draw_text(outcome + " New deal?", [200, 300], 30, "Black", "sans-serif")
dealer_hand.draw(canvas, [250, 100])
# card = Card("S", "A")
# card.draw(canvas, [300, 300])
# initialization frame
frame = simplegui.create_frame("Blackjack", 600, 600)
frame.set_canvas_background("Green")
#create buttons and canvas callback
frame.add_button("Deal", deal, 200)
frame.add_button("Hit", hit, 200)
frame.add_button("Stand", stand, 200)
frame.set_draw_handler(draw)
# get things rolling
frame.start()
player_hand = Hand()
dealer_hand = Hand()
# remember to review the gradic rubric
|
UTF-8
|
Python
| false | false | 2,013 |
5,274,219,853,116 |
57a06fd8e8b92bca99663169631f43291c6b393f
|
bc115f7f78168dee790d0cdbb50b68a0a65ef7d1
|
/collimator.py
|
6ebcc20c25b13f02114c9a43f05df18439550ca9
|
[] |
no_license
|
aheiberg10X/gleeson
|
https://github.com/aheiberg10X/gleeson
|
13b569c1ea1eb9ebf528359721b24f88c73087bf
|
b1b472f2ab9d6552bbe4870afbc87a595d5fbeca
|
refs/heads/master
| 2021-05-26T13:37:53.642463 | 2012-03-28T01:08:11 | 2012-03-28T01:08:11 | null | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null |
#A Source is something that the Collimator can operate on
class CollimatorSource :
#iterator: is something we can call next on, will provide the data
# For example, iterating the lines of a file, or rows of a db
#eqkey: is a function that takes an item from iterator
# and returns a sort key. The intent is that heterogenous Sources
# will all produce the same kind of key, so Collimator can compare.
# ***self.iterator is expected to be sorted with respect to eqkey***
#integrator: is a function that takes a list of items from iterator
# and merges it into some data structure called 'target'
#allow_absent: Collimator will find the minimum set of items across multipl
# Sources. Do we ever let this Source be absent from this
# minimum set?
#group_repeats: if there are multiple entries with the same key,
# do we treat them as one unit and give them all
# to integrator at once?
def __init__(self, \
iterator, \
eqkey, \
integrator, \
allow_absent = True, \
group_repeats = True) :
self.iterator = iterator
self.eqkey = eqkey
self.integrator = integrator
self.allow_absent = allow_absent
self.group_repeats = group_repeats
# the default way to handle AbsentExceptions
def raiseAE( ae ) : raise ae
#Collimator takes multiple Sources and coalesces their equivalent entries
#Equivalence among the Source entries is defined by self.comparator, which
#operates on the source.eqkey( source.iteritem ) of two Sources
#comparator - inputs: itemA, itemB
# output: -1 iff itemA < itemB
# 0 iff itemA = itemB
# +1 iff itemA > itemB
#targetCreator: a function returning a data structure that the Sources expect
# as the first parameter in their respective integrator functions
class Collimator :
def __init__(self, \
sources, \
comparator, \
targetCreator, \
absentHandler=raiseAE) :
self.sources = sources
self.nsources = len(sources)
self.comparator = comparator
self.count = 0
self.targetCreator = targetCreator
self.absentHandler = absentHandler
self.exhausted_sources = [False]*self.nsources
self.next_entry = [self.sources[i].iterator.next() \
for i in range(self.nsources)]
self.entries = [ [] for i in range(self.nsources) ]
for i in range(self.nsources) :
self.fillEntry(i)
#get the next
def fillEntry( self, source_ix ) :
if not self.next_entry[source_ix] :
self.exhausted_sources[source_ix] = True
return
entry = self.next_entry[source_ix]
key = self.sources[source_ix].eqkey(entry)
entries = [key, entry]
try :
grouping = self.sources[source_ix].group_repeats
while True :
next_entry = self.sources[source_ix].iterator.next()
self.next_entry[source_ix] = next_entry
if grouping :
next_key = self.sources[source_ix].eqkey( next_entry )
comp = self.comparator( key, next_key )
if comp == 0 :
entries.append( next_entry )
elif comp == -1 : break
else :
message = "Source %d has %s before %s" \
% (source_ix, str(key), str(next_key))
print message
assert False
else :
break
except StopIteration :
self.next_entry[source_ix] = False
self.entries[source_ix] = entries
#print "source %d new entries" % source_ix, entries
def __iter__(self) :
while True :
non_exhausted = [ i for i in range(self.nsources) \
if not self.exhausted_sources[i] ]
#print "nonexhauted", non_exhausted
if len(non_exhausted) == 0 :
raise StopIteration
current_min = self.entries[non_exhausted[0]][0]
min_sources = []
for i in non_exhausted :
#print "comparing", current_min, "to entrie", i, self.entries[i][0]
comp = self.comparator( current_min, self.entries[i][0] )
if comp == 1 :
current_min = self.entries[i][0]
min_sources = [i]
elif comp == 0 :
min_sources.append(i)
#print min_sources
target = self.targetCreator()
for i in range(self.nsources) :
if i in min_sources :
#print i, self.entries[i][0]
target = self.sources[i].integrator( target, \
self.entries[i][1:] )
self.fillEntry(i)
else :
if not self.sources[i].allow_absent :
ae = AbsentException(i,current_min,target)
self.absentHandler( ae )
self.count += 1
yield target
#except StopIteration :
#print "All sources have been exhausted"
class AbsentException(Exception) :
def __init__(self, src_ix, missed_target_key, missed_target) :
self.ix = src_ix
self.missed_target_key = missed_target_key
self.missed_target = missed_target
def __str__(self) :
print 'called'
print self.missed_target_key
return "Source %d is not allowed to be unmatched with: %s|| " % (self.ix, self.missed_target_key)
def test() :
source1 = [1,2,2,3,4]
source2 = [3,3,3,4,5]
def eqk( entry ) :
return entry
def intg( target, entries ) :
target.extend(entries)
return target
def blankTarget() : return []
source1 = Source( iter(source1), eqk, intg )
source2 = Source( iter(source2), eqk, intg )
c = Collimator( [source1,source2], equiComp, blankTarget )
for t in c :
print t
#c.fillEntry( 0 )
#print c.entries, c.next_entry
#c.fillEntry(0)
#print c.entries, c.next_entry
#c.fillEntry(1)
#print c.entries, c.next_entry
##########################################################################
######## Helpers / Simple Defaults ####################################
##########################################################################
def equiComp( x, y ) :
if x < y : return -1
elif x==y : return 0
else : return 1
if __name__ == '__main__' :
test()
|
UTF-8
|
Python
| false | false | 2,012 |
6,889,127,548,360 |
52684a4aa32142e40dd162a128e98fd3136e875b
|
df432bb7f873e8c17f27ce38c23e6d75a6b7ba8b
|
/scripts/Maelstrom/Episode4/E4M5/HybridAI.py
|
d8edc8a9f250297245867c302ad4b26716992abe
|
[] |
no_license
|
tnu1997/bridgecommander2013
|
https://github.com/tnu1997/bridgecommander2013
|
9e4e1c15f32436f61d61276cb8b3d4fe97d73c8a
|
81da2e13a031881b9ae88cd0c0467e341f46150d
|
refs/heads/master
| 2021-01-23T13:31:36.327437 | 2013-02-19T13:36:05 | 2013-02-19T13:36:05 | null | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null |
import App
def CreateAI(pShip):
#########################################
# Creating PlainAI Scripted at (164, 196)
pScripted = App.PlainAI_Create(pShip, "Scripted")
pScripted.SetScriptModule("Flee")
pScripted.SetInterruptable(1)
pScript = pScripted.GetScriptInstance()
pScript.SetFleeFromGroup("player", "USS Enterprise")
pScript.SetSpeed(1)
# Done creating PlainAI Scripted
#########################################
#########################################
# Creating ConditionalAI Wait at (165, 156)
## Conditions:
#### Condition TimePassed
pTimePassed = App.ConditionScript_Create("Conditions.ConditionTimer", "ConditionTimer", 10, 1)
## Evaluation function:
def EvalFunc(bTimePassed):
ACTIVE = App.ArtificialIntelligence.US_ACTIVE
DORMANT = App.ArtificialIntelligence.US_DORMANT
DONE = App.ArtificialIntelligence.US_DONE
if bTimePassed:
return DONE
return ACTIVE
## The ConditionalAI:
pWait = App.ConditionalAI_Create(pShip, "Wait")
pWait.SetInterruptable(1)
pWait.SetContainedAI(pScripted)
pWait.AddCondition(pTimePassed)
pWait.SetEvaluationFunction(EvalFunc)
# Done creating ConditionalAI Wait
#########################################
#########################################
# Creating PlainAI WarpOut at (331, 157)
pWarpOut = App.PlainAI_Create(pShip, "WarpOut")
pWarpOut.SetScriptModule("Warp")
pWarpOut.SetInterruptable(1)
# Done creating PlainAI WarpOut
#########################################
#########################################
# Creating SequenceAI HybridFlee at (245, 80)
pHybridFlee = App.SequenceAI_Create(pShip, "HybridFlee")
pHybridFlee.SetInterruptable(1)
pHybridFlee.SetLoopCount(1)
pHybridFlee.SetResetIfInterrupted(1)
pHybridFlee.SetDoubleCheckAllDone(0)
pHybridFlee.SetSkipDormant(0)
# SeqBlock is at (271, 109)
pHybridFlee.AddAI(pWait)
pHybridFlee.AddAI(pWarpOut)
# Done creating SequenceAI HybridFlee
#########################################
return pHybridFlee
|
UTF-8
|
Python
| false | false | 2,013 |
6,399,501,286,497 |
386f8197667b850f96bd5d92e0532ce062eb3de6
|
385d8fae22433d1e608db4d61b02ad3d7cda76af
|
/MakeStudentCSV.py
|
82905f727c20946e8089285727c032e6ddb7dae9
|
[
"LicenseRef-scancode-warranty-disclaimer",
"GPL-3.0-only",
"GPL-3.0-or-later",
"LGPL-2.1-or-later",
"LGPL-2.0-or-later",
"GPL-1.0-or-later"
] |
non_permissive
|
hckiang/DBLite
|
https://github.com/hckiang/DBLite
|
1800f2304aa7956459945fbcddc5fcac73148f8c
|
bb4a35e7efc525be13ec3de9ddf7f3a2b11d3486
|
refs/heads/master
| 2019-07-18T05:03:08.734865 | 2013-11-04T13:43:48 | 2013-11-04T13:43:48 | null | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null |
#!/usr/bin/env python
#
# Make a random list of students, with random names, student ID, and gpa.
# I'm sorry for a bit messy codes, and extremely slow speed. But at lest
# it works. And at this stage I don't have time to refactor this.
#
# Example of usage:
#
# <$0> 10000
#
# Will generate 10000 random records.
#
# Note that this script uses COMPRESSED STUDENT ID by default. If you want
# student IDs in normal string form (like 'DB123456'), use the option -n
# or --normal-student-id
#
# Example:
#
# <$0> -n 10000
#
# TODO:
# Use FFI to call the compressor instead. Currently this program is very,
# very slow because it invoke another process to compress student ID.
#
import sys
sys.path.append( "./name_gen/" )
import os
import string
import random
from optparse import OptionParser
from namegen import NameGen
from subprocess import Popen, PIPE, STDOUT, call
def gen_id():
return ''.join(random.choice("DABSYE")) + "B" + ''.join(random.choice("0123456789") for i in range(6))
def gen_fac():
return random.choice(["FST", "FBA", "FAH", "FSS", "FLL", "FED"])
def gen_gpa():
r = random.normalvariate(2.8, 0.51)
if( r <= 4.0 ):
return r
else:
return gen_gpa()
compressor_name = "sid_compress"
compressor_dir = "sid_compress/"
compressor_path = compressor_dir + compressor_name
def compress_sid( sid ):
p = Popen( [ "./" + compressor_name, "-ei"],
stdout=PIPE,
stdin=PIPE,
stderr=STDOUT )
id = p.communicate( input = sid )[0]
return id
def compile_compressor():
if not (os.path.isfile(compressor_path) and os.access(compressor_path, os.X_OK)):
call(["make"], stdout = sys.stderr)
def main():
parser = OptionParser( usage = "Generate N random student records in " +
"CSV format.\nUsage: %prog [options] n" )
parser.add_option( "-n", "--normal-student-id", action="store_false",
dest="compress_sid", default=True )
(options, args) = parser.parse_args()
# load generator data from language file
generator = NameGen('name_gen/Languages/japanese.txt')
os.chdir( compressor_dir )
# compile the compressor which is written in C++
compile_compressor()
compress_if_needed = (lambda sid: compress_sid(sid)) if options.compress_sid else (lambda sid: sid)
for i in range( int(args[0]) ): #generate a few words
print "%s,%s,%s %s,%.1f" % ( compress_if_needed(gen_id()),
gen_fac(),
generator.gen_word(),
generator.gen_word(),
gen_gpa() )
main()
|
UTF-8
|
Python
| false | false | 2,013 |
16,853,451,706,423 |
ac31af650c63d46975f7ddd388b83874e6f94beb
|
3634156e458ccea1c525987124284513a797b1f6
|
/scripts/ngram.py
|
b04ccf883ed65a7c7e1c8bbc70aa8a06cd0951df
|
[] |
no_license
|
kylejshaffer/ideological_opinion_corpus
|
https://github.com/kylejshaffer/ideological_opinion_corpus
|
0bea47754016012aadb392a2a1c7762930fc2aa9
|
f45c562a250589846451631f8539cb3fc804c47a
|
refs/heads/master
| 2016-08-08T11:38:49.580596 | 2014-05-08T22:38:52 | 2014-05-08T22:38:52 | null | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null |
import os, re, nltk, json
from nltk.collocations import *
from nltk.tokenize import word_tokenize
# from itertools import tee, islice, izip
os.chdir('/Users/kylefth/Desktop/SILS Courses/Fall2013/613/Datasets/SomasundaranWiebe-politicalDebates')
# cd to further specific directory of posts
# PMI Bigram Association Measures
text = # the text as a string that you want analyzed
bgm_measures = nltk.collocations.BigramAssocMeasures()
finder = BigramCollocationFinder.from_words(word_tokenize(text))
scored = finder.score_ngrams(bgm_measures.likelihood_ratio)
for i in finder.score_ngrams(bgm_measures.likeliehood_ratio): # .pmi for MI
print i # or do something else, these are the PMI bigram scores
bigrams = nltk.bigrams(tokens)
trigrams = nltk.trigrams(tokens)
bigram_dist = nltk.FreqDist(bigrams)
# Top-10 bigrams
fdist.items()[:10]
|
UTF-8
|
Python
| false | false | 2,014 |
11,321,533,803,113 |
58c85090a927d095e75dd5ad0e5569088b41c3c4
|
018165b3cfdc0183bcedd6499b64faa9a8609d17
|
/crack.py
|
ec85385e6f8e59dff0dd479168abeb1a2eaa48d1
|
[] |
no_license
|
loganfreeman/challenge
|
https://github.com/loganfreeman/challenge
|
99b56394df1fcba018423f9a913610c465d197fc
|
81875f968ff129346e76d24664358d23594051d7
|
refs/heads/master
| 2016-09-02T18:47:47.107880 | 2014-10-30T06:32:10 | 2014-10-30T06:32:10 | 25,949,824 | 1 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null |
words = open('WordList.txt', 'r')
valid_handles = sorted([word.replace('at', '@').rstrip() for word in words if 'at' in word[:2] if "'" not in word], lambda x,y: cmp(len(x), len(y)))
print 'Short handles'
for i in range(0, 20):
print valid_handles[i] + ' : ' + valid_handles[i].replace('@', 'at')
print '\nLong handles'
for i in range(0, 20):
i += 1
print valid_handles[-i] + ' : ' + valid_handles[-i].replace('@', 'at')
|
UTF-8
|
Python
| false | false | 2,014 |
18,657,337,957,624 |
617638e34fd21387fd7efab7cb150a132ac80fdf
|
47d5b269ca3974bdd8eaa9786c8b8134277d3ec3
|
/backend.py
|
8fa25d551b6ab047b02d886fe3a821162ade59e7
|
[] |
no_license
|
ChrisBoesch/awesome-start
|
https://github.com/ChrisBoesch/awesome-start
|
f63d2a0dddd425b63c4ab959f6e623d42130d9d7
|
89947c4aba6cb2860d70feaf60e9d0544f0e8baf
|
refs/heads/gh-pages
| 2016-09-08T02:59:59.793078 | 2013-04-26T22:10:16 | 2013-04-26T22:10:16 | 7,533,853 | 0 | 1 | null | false | 2013-01-15T08:52:40 | 2013-01-10T03:36:33 | 2013-01-15T08:52:39 | 2013-01-15T08:52:39 | 136 | null | 1 | 0 | null | null | null |
"""Backend Module
Created on Dec 6, 2012
@author: Chris Boesch
"""
"""
Note to self: json.loads = json string to objects. json.dumps is object to json string.
"""
import datetime
import logging
import webapp2 as webapp
from google.appengine.api import memcache
from google.appengine.ext import db
from google.appengine.ext.webapp.util import run_wsgi_app
import json
class Backend(db.Model):
apikey = db.StringProperty(required=True,default='Default-APIKey')
model = db.StringProperty(required=True,default='Default-Model')
#Use backend record id as the model id for simplicity
jsonString = db.TextProperty(required=True,default='{}')
created = db.DateTimeProperty(auto_now_add=True) #The time that the model was created
modified = db.DateTimeProperty(auto_now=True)
def to_dict(self):
d = dict([(p, unicode(getattr(self, p))) for p in self.properties()])
d["id"] = self.key().id()
return d
@staticmethod
def add(apikey, model, data):
#update ModelCount when adding
jsonString = data
entity = Backend(apikey=apikey,
model=model,
jsonString=jsonString)
entity.put()
modelCount = ModelCount.all().filter('apikey',apikey).filter('model', model).get()
if modelCount:
modelCount.count += 1
modelCount.put()
else:
modelCount = ModelCount(apikey=apikey, model=model, count=1)
modelCount.put()
result = {'model':model,
'apikey': apikey,
'id': entity.key().id(),
'data': json.loads(jsonString)} #this would also check if the json submitted was valid
return result
@staticmethod
def get_entities(apikey, model=None, offset=0, limit=50):
#update ModelCount when adding
theQuery = Backend.all().filter('apikey',apikey)
if model:
theQuery = theQuery.filter('model', model)
objects = theQuery.fetch(limit=limit, offset=offset)
entities = []
for object in objects:
entity = {'model':object.model,
'apikey': apikey,
'id': object.key().id(),
'created': object.created,
'modified': object.modified,
'data': json.loads(object.jsonString)}
entities.append(entity)
count = 0
modelCount = ModelCount.all().filter('apikey',apikey).filter('model', model).get()
if modelCount:
count = modelCount.count
result = {'method':'get_entities',
'apikey': apikey,
'model': model,
'count': count,
'offset': offset,
'limit':limit,
'entities': entities}
return result
@staticmethod
def get_entity(apikey,model,model_id):
theobject = Backend.get_by_id(int(model_id))
result = {'method':'get_model',
'apikey': apikey,
'model': model,
'id': model_id,
'data': json.loads(theobject.jsonString)
}
return result
@staticmethod
def clear(apikey, model):
#update model count when clearing model on api
count = 0
for object in Backend.all().filter('apikey',apikey).filter('model', model):
count += 1
object.delete()
modelCount = ModelCount.all().filter('apikey',apikey).filter('model', model).get()
if modelCount:
modelCount.delete()
result = {'items_deleted': count}
return result
@staticmethod
def clearapikey(apikey):
#update model count when clearing model on api
count = 0
for object in Backend.all().filter('apikey',apikey):
count += 1
object.delete()
modelCount = ModelCount.all().filter('apikey',apikey).get()
if modelCount:
modelCount.delete()
result = {'items_deleted': count}
return result
#You can't name it delete since db.Model already has a delete method
@staticmethod
def remove(apikey, model, model_id):
#update model count when deleting
entity = Backend.get_by_id(int(model_id))
if entity and entity.apikey == apikey and entity.model == model:
entity.delete()
result = {'method':'delete_model_success',
'apikey': apikey,
'model': model,
'id': model_id
}
else:
result = {'method':'delete_model_not_found'}
modelCount = ModelCount.all().filter('apikey',apikey).filter('model', model).get()
if modelCount:
modelCount.count -= 1
modelCount.put()
return result
#data is a dictionary that must be merged with current json data and stored.
@staticmethod
def edit_entity(apikey, model, model_id, data):
jsonString = data
entity = Backend.get_by_id(int(model_id))
entity.jsonString = jsonString
entity.put()
if entity.jsonString:
data = json.loads(entity.jsonString)
else:
data = {}
result = {'model':model,
'apikey': apikey,
'id': entity.key().id(),
'data': data #this would also check if the json submitted was valid
}
return result
#Quick retrieval for supported models metadata and count stats
class ModelCount(db.Model):
apikey = db.StringProperty(required=True,default='Default-APIKey')
model = db.StringProperty(required=True,default='Default-Model')
count = db.IntegerProperty(required=True, default=0)
created = db.DateTimeProperty(auto_now_add=True) #The time that the model was created
modified = db.DateTimeProperty(auto_now=True)
class ActionHandler(webapp.RequestHandler):
"""Class which handles bootstrap procedure and seeds the necessary
entities in the datastore.
"""
def respond(self,result):
"""Returns a JSON response to the client.
"""
callback = self.request.get('callback')
self.response.headers['Content-Type'] = 'application/json'
#self.response.headers['Content-Type'] = '%s; charset=%s' % (config.CONTENT_TYPE, config.CHARSET)
self.response.headers['Access-Control-Allow-Origin'] = '*'
self.response.headers['Access-Control-Allow-Methods'] = 'GET, POST, PUT, DELETE, OPTIONS, PATCH, HEAD'
self.response.headers['Access-Control-Allow-Headers'] = 'Origin, Content-Type, X-Requested-With'
self.response.headers['Access-Control-Allow-Credentials'] = 'True'
#Add a handler to automatically convert datetimes to ISO 8601 strings.
dthandler = lambda obj: obj.isoformat() if isinstance(obj, datetime.datetime) else None
if callback:
content = str(callback) + '(' + json.dumps(result,default=dthandler) + ')'
return self.response.out.write(content)
return self.response.out.write(json.dumps(result,default=dthandler))
def metadata(self,apikey):
#Fetch all ModelCount records for apikey to produce metadata on currently supported models.
models = []
for mc in ModelCount.all().filter('apikey',apikey):
models.append({'model':mc.model, 'count': mc.count})
result = {'method':'metadata',
'apikey': apikey,
'model': "metadata",
'count': len(models),
'entities': models
}
return self.respond(result)
#Dump apikey table
def backup(self,apikey):
#Fetch all ModelCount records for apikey to produce metadata on currently supported models.
dthandler = lambda obj: obj.isoformat() if isinstance(obj, datetime.datetime) else None
offset = 0
new_offset = self.request.get("offset")
if new_offset:
offset = int(new_offset)
result = Backend.get_entities(apikey,offset=offset)
filename = "Backup_"+apikey+"_offset_"+str(offset)+".json"
self.response.headers['Content-Type'] = 'application/streaming-json'
self.response.content_disposition = 'attachment; filename="'+filename+'"'
for obj in result['entities']:
self.response.out.write(json.dumps(obj,default=dthandler)+"\n")
return
#Delete this experimental backup method
def backup_test(self,apikey):
#Fetch all ModelCount records for apikey to produce metadata on currently supported models.
dthandler = lambda obj: obj.isoformat() if isinstance(obj, datetime.datetime) else None
offset = 0
new_offset = self.request.get("offset")
if new_offset:
offset = int(new_offset)
filename = "Backup_test_"+apikey+"_offset_"+str(offset)+".json"
self.response.headers['Content-Type'] = 'application/streaming-json'
self.response.content_disposition = 'attachment; filename="'+filename+'"'
for entity in Backend.all():
self.response.out.write(json.dumps(entity.to_dict(),default=dthandler)+"\n")
return
#return self.respond(result)
def clear_apikey(self,apikey):
"""Clears the datastore for a an apikey.
"""
result = Backend.clearapikey(apikey)
return self.respond({'method':'clear_apikey'})
def clear_model(self,apikey, model):
"""Clears the datastore for a model and apikey.
"""
result = Backend.clear(apikey, model)
return self.respond(result)
def add_or_list_model(self,apikey,model):
#Check for GET paramenter == model to see if this is an add or list.
#Call Backend.add(apikey, model, data) or
#Fetch all models for apikey and return a list.
#Todo - Check for method.
logging.info(self.request.method)
if self.request.method=="POST":
logging.info("in POST")
logging.info(self.request.body)
result = Backend.add(apikey, model, self.request.body)
#logging.info(result)
return self.respond(result)
else:
data = self.request.get("obj")
if data:
logging.info("Adding new data: "+data)
result = Backend.add(apikey, model, data)
else:
offset = 0
new_offset = self.request.get("offset")
if new_offset:
offset = int(new_offset)
result = Backend.get_entities(apikey, model,offset=offset)
return self.respond(result)
def delete_model(self,apikey,model, model_id):
result = Backend.remove(apikey,model, model_id)
return self.respond(result)
def get_or_edit_model(self,apikey,model, model_id):
#Check for GET parameter == model to see if this is a get or an edit
#technically the apikey and model are not required.
#To create an error message if the id is not from this apikey?
logging.info("**********************")
logging.info(self.request.method)
logging.info("**********************")
if self.request.method=="DELETE":
logging.info("It was options")
result = Backend.remove(apikey,model, model_id)
logging.info(result)
return self.respond(result)#(result)
elif self.request.method=="PUT":
logging.info("It was PUT")
logging.info(self.request.body)
result = Backend.edit_entity(apikey,model,model_id,self.request.body)
#result = Backend.remove(apikey,model, model_id)
#result = json.loads(self.request.body)
#logging.info(result)
return self.respond(result)#(result)
else:
data = self.request.get("obj")
if data:
result = Backend.edit_entity(apikey,model,model_id,data)
else:
result = Backend.get_entity(apikey,model,model_id)
return self.respond(result)
application = webapp.WSGIApplication([
webapp.Route('/<apikey>/metadata', handler=ActionHandler, handler_method='metadata'),
webapp.Route('/<apikey>/backup_test', handler=ActionHandler, handler_method='backup_test'),
webapp.Route('/<apikey>/backup', handler=ActionHandler, handler_method='backup'),
webapp.Route('/<apikey>/clear', handler=ActionHandler, handler_method='clear_apikey'),
webapp.Route('/<apikey>/<model>/clear', handler=ActionHandler, handler_method='clear_model'),
webapp.Route('/<apikey>/<model>/<model_id>/delete', handler=ActionHandler, handler_method='delete_model'),
webapp.Route('/<apikey>/<model>/<model_id>', handler=ActionHandler, handler_method='get_or_edit_model'),
webapp.Route('/<apikey>/<model>', handler=ActionHandler, handler_method='add_or_list_model'),
],
debug=True)
|
UTF-8
|
Python
| false | false | 2,013 |
11,948,599,066,644 |
14960b82588d317ae9a3c4358d36753819ad2797
|
3d19e1a316de4d6d96471c64332fff7acfaf1308
|
/Users/B/beatricefantoni/windsor_star_scraper.py
|
7b7848c4681d9b4f8f8915c90f46b1b838acdba4
|
[] |
no_license
|
BerilBBJ/scraperwiki-scraper-vault
|
https://github.com/BerilBBJ/scraperwiki-scraper-vault
|
4e98837ac3b1cc3a3edb01b8954ed00f341c8fcc
|
65ea6a943cc348a9caf3782b900b36446f7e137d
|
refs/heads/master
| 2021-12-02T23:55:58.481210 | 2013-09-30T17:02:59 | 2013-09-30T17:02:59 | null | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null |
import scraperwiki
import re
import time
# Blank Python
def our_scraper(Toronto_Craigslist):
the_page = scraperwiki.scrape(Toronto_Craigslist)
for every_post in re.finditer('<p><a href="http://toronto.en.craigslist.ca/tor/mis/.+?html">(.+?) <font size="-1">', the_page):
every_post = every_post.group(1)
print every_post
scraperwiki.sqlite.save(unique_keys=["listing"],data={"listing": every_post})
base_link = "http://toronto.craigslist.ca/mis/index"
base_number = 0
while base_number < 500:
Toronto_Craigslist = base_link + str(base_number) + ".html"
our_scraper(Toronto_Craigslist)
base_number = base_number + 100
time.sleep(2)
import scraperwiki
import re
import time
# Blank Python
def our_scraper(Toronto_Craigslist):
the_page = scraperwiki.scrape(Toronto_Craigslist)
for every_post in re.finditer('<p><a href="http://toronto.en.craigslist.ca/tor/mis/.+?html">(.+?) <font size="-1">', the_page):
every_post = every_post.group(1)
print every_post
scraperwiki.sqlite.save(unique_keys=["listing"],data={"listing": every_post})
base_link = "http://toronto.craigslist.ca/mis/index"
base_number = 0
while base_number < 500:
Toronto_Craigslist = base_link + str(base_number) + ".html"
our_scraper(Toronto_Craigslist)
base_number = base_number + 100
time.sleep(2)
|
UTF-8
|
Python
| false | false | 2,013 |
7,352,984,013,031 |
4d7e4593395a98dc736ef5c65e67c2fc575eeb5c
|
4e4e8224375aad9cb1bf976efc09fbeeb706ca18
|
/code 2/chapter10/cball3.py
|
b4735581e8aa39e05bf35713dc3e91a680d03160
|
[] |
no_license
|
HiroIshikawa/python
|
https://github.com/HiroIshikawa/python
|
0d1d118d33f04e21ec312efd13fd991a986dab57
|
34d8d60913b06334699706bf2988242b92482df7
|
refs/heads/master
| 2015-08-01T13:57:02.881443 | 2012-09-15T00:43:41 | 2012-09-15T00:43:41 | null | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null |
# cball3.py
# Simulation of the flight of a cannon ball (or other projectile)
# Illustrates use of a class/object to organize data
from math import pi, sin, cos
class Projectile:
def __init__(self, angle, velocity, height):
self.xpos = 0.0
self.ypos = height
radians = pi * angle / 180.0
self.xvel = velocity * cos(radians)
self.yvel = velocity * sin(radians)
def update(self, time):
self.xpos = self.xpos + time * self.xvel
yvel1 = self.yvel - 9.8 * time
self.ypos = self.ypos + time * (self.yvel + yvel1) / 2.0
self.yvel = yvel1
def getY(self):
return self.ypos
def getX(self):
return self.xpos
def getInputs():
a = input("Enter the launch angle (in degrees): ")
v = input("Enter the initial velocity (in meters/sec): ")
h = input("Enter the initial height (in meters): ")
t = input("Enter the time interval between position calculations: ")
return a,v,h,t
def main():
angle, vel, h0, time = getInputs()
cball = Projectile(angle, vel, h0)
while cball.getY() >= 0:
cball.update(time)
print "\nDistance traveled: %0.1f meters." % (cball.getX())
main()
|
UTF-8
|
Python
| false | false | 2,012 |
11,630,771,483,845 |
1fb6d2965f0f8dfa47f6c7ea6d320467394fc4c8
|
63f399879e89f7fcb066dd7b2d98e75a28dbf346
|
/notes/views.py
|
a33e4de64faa0c659b76c67ca2303d5f0a82a771
|
[] |
no_license
|
rasstreli/django-task-manager
|
https://github.com/rasstreli/django-task-manager
|
ca162059ee8930cc9703da9e9534495830d7b3c0
|
bbb4fff1d44bcece462353442ab59e44d9be4dfe
|
refs/heads/master
| 2020-09-12T15:13:39.266658 | 2012-05-02T15:25:22 | 2012-05-02T15:25:22 | null | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null |
# Create your views here.
from notes.models import Jobs
from notes.forms import JobForm, UpdateJobForm
from django.shortcuts import render_to_response,RequestContext
from django.http import HttpResponseRedirect
from django.core.mail import send_mail
def create_job(request):
template = "jobs/create_job.html"
if request.method == 'POST':
form = JobForm(request.POST)
if form.is_valid():
form.save()
return HttpResponseRedirect('/')
else:
form = JobForm
dict_to_return = {'form':form}
return render_to_response(template,dict_to_return,context_instance=RequestContext(request))
def job(request, job_id):
if job_id:
job = Jobs.objects.filter(id = job_id)
else:
job = ''
template = "jobs/job.html"
form = UpdateJobForm()
dict_to_return = {'job':job, 'form':form}
return render_to_response(template, dict_to_return, context_instance=RequestContext(request))
def job_list(request):
template = "jobs/job_list.html"
jobs_list = Jobs.objects.all()
dict_to_return = {'jobs':jobs_list}
return render_to_response(template, dict_to_return, context_instance=RequestContext(request))
|
UTF-8
|
Python
| false | false | 2,012 |
18,983,755,477,944 |
49691df3e6dc0cb21f73dfadf80267046fc714b0
|
b024f39244870f7c0d14c768debf300f75e18d10
|
/XMLHandler.py
|
05ea457422355609bc77553b240411b109971211
|
[
"MIT"
] |
permissive
|
nemothekid/Colosseum--Year-3XXX
|
https://github.com/nemothekid/Colosseum--Year-3XXX
|
dd2c3f6e55af93e0eb84eaa67ec8f632e185dbd8
|
93cd723e60f2f8fe57637cdabad2b1a644c9c279
|
refs/heads/master
| 2020-05-19T14:00:23.257119 | 2012-04-16T06:17:38 | 2012-04-16T06:17:38 | 2,110,655 | 1 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null |
import xml.sax
class XMLNode(object):
attrs = {}
data = []
parent = None
children = []
name = ""
data = ""
def __init__(self, name, parent=None, children=[], data = ""):
self.name = name
self.parent = parent
self.children = list(children)
self.attrs = dict({})
def setAttr(self, key, val):
self.attrs[key] = val
def getAttr(self, key):
return self.attrs[key]
def __getitem__(self, key):
return self.attrs[key]
def __setitem__(self, key, val):
self.attrs[key] = val
def addChild(self, child):
self.children.append(child)
def getChildren(self):
return self.children
def setData(self, data):
self.data = data
def getData(self):
return self.data
def setParent(self, parent):
self.parent = parent
def getParent(self):
return self.parent
class XMLHandler(xml.sax.handler.ContentHandler):
root = {}
parentTag = {}
buff = ""
parentMap = None
buffMapping = None
def __init__(self):
self.inTitle = 0
self.root = XMLNode("root")
#{'children':[], 'parent':None}
self.parentMap = self.root
def startElement(self, name, attributes):
self.buffMapping = XMLNode(name, self.parentMap)
#print self.buffMapping.name, "has parent", self.parentMap.name
#print "A", name
#print "\tB", self.parentMap.name
#self.buffMapping['parent'] = self.parentMap
self.buff = ""
for attr in attributes.getNames():
self.buffMapping[str(attr)] = str(attributes[attr])
self.parentMap.addChild(self.buffMapping)
#print "Adding child %s to parent %s" % (self.buffMapping.name, self.parentMap.name)
self.parentMap = self.buffMapping
#print "Setting parent to", self.parentMap.name
def characters(self, data):
self.buff += data
def endElement(self, name):
if name != self.buffMapping.name:
self.buffMapping = self.buffMapping.getParent()
#print "end", name
#print "end", self.buffMapping.name
self.buffMapping.setData(str(self.buff).strip())
self.parentMap = self.buffMapping.getParent()
#print "Set parent to", self.parentMap.name
def parse(self, filen):
parser = xml.sax.make_parser( )
parser.setContentHandler(self)
parser.parse(filen)
def getMap(self):
return self.root.getChildren()[0]
if __name__ == "__main__":
wh = XMLHandler()
f = raw_input("File:")
wh.parse(f)
print wh.getMap()
raw_input()
|
UTF-8
|
Python
| false | false | 2,012 |
3,977,139,763,895 |
86b444585d1d7c5269f188d6308ad49147325e24
|
97d273793d49f0ec395c222fefde53a46073499d
|
/mongo/rest_interface.py
|
73c63ace7b607ab6f16e468ccf4553c7aa56ee13
|
[] |
no_license
|
vaishaksuresh/cmpe226nosql
|
https://github.com/vaishaksuresh/cmpe226nosql
|
e57165730a233b5de7494fe0fc8148b191e697d6
|
ebec91e779223d5a280fc09a4f208b906af30dda
|
refs/heads/master
| 2021-01-22T11:51:23.511202 | 2013-12-05T03:46:02 | 2013-12-05T03:46:02 | null | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null |
__author__ = 'vaishaksuresh'
import bottle
from bottle import route, run, request, response, abort, static_file
from pymongo import Connection, ASCENDING
from json import JSONEncoder
from bson.objectid import ObjectId
from bson.son import SON
from bson.code import Code
from pprint import pprint
import urlparse
import json
from bson import json_util
connection = Connection('localhost', 27017)
db = connection.github_events
class MongoEncoder(JSONEncoder):
def default(self,obj,**kwargs):
if isinstance(obj,ObjectId):
return str(obj)
else:
return JSONEncoder.default(obj,**kwargs)
@route('/push', method='GET')
def get_push_events():
if not request.query.limit:
limit = 100
else:
limit = int(request.query.limit)
if not request.query.skip:
skip = 0
else:
skip = int(request.query.skip)
cursor = db['push_events'].find({}, {"repo": 1, "created_at": 1, "actor": 1, "payload.commits": 1})\
.limit(limit).skip(skip)
if not cursor:
abort(404, 'No document with id')
response.content_type = 'application/json'
entries = [entry for entry in cursor]
return MongoEncoder().encode(entries)
@route('/watch', method='GET')
def get_push_events():
if not request.query.limit:
limit = 100
else:
limit = int(request.query.limit)
if not request.query.skip:
skip = 0
else:
skip = int(request.query.skip)
cursor = db['watch_events'].find({}, {"repo": 1, "created_at": 1, "actor": 1}).limit(limit).skip(skip)
if not cursor:
abort(404, 'No document with id')
response.content_type = 'application/json'
entries = [entry for entry in cursor]
return MongoEncoder().encode(entries)
@route('/follow', method='GET')
def get_push_events():
if not request.query.limit:
limit = 100
else:
limit = int(request.query.limit)
if not request.query.skip:
skip = 0
else:
skip = int(request.query.skip)
cursor = db['follow_events'].find({}, {"repo": 1, "created_at": 1, "actor": 1}).limit(limit).skip(skip)
if not cursor:
abort(404, 'No document with id')
response.content_type = 'application/json'
entries = [entry for entry in cursor]
return MongoEncoder().encode(entries)
@route('/issue', method='GET')
def get_push_events():
if not request.query.limit:
limit = 100
else:
limit = int(request.query.limit)
if not request.query.skip:
skip = 0
else:
skip = int(request.query.skip)
cursor = db['issues_events'].find({}, {"repo": 1, "created_at": 1, "actor": 1}).limit(limit).skip(skip)
if not cursor:
abort(404, 'No document with id')
response.content_type = 'application/json'
entries = [entry for entry in cursor]
return MongoEncoder().encode(entries)
@route('/repo/top', method='GET')
def get_push_events():
if not request.query.limit:
limit = 10
else:
limit = int(request.query.limit)
reducer = Code("""
function(obj, prev){
prev.count++;
}
""")
cursor = db['push_events'].aggregate([
{"$group": {"_id": "$repo.name", "count": {"$sum": 1}}},
{"$sort": SON([("count", -1), ("_id", -1)])},
{"$limit": limit}
])
if not cursor:
abort(404, 'No document with id')
response.content_type = 'application/json'
entries = [entry for entry in cursor['result']]
return MongoEncoder().encode(entries)
@route('/user/top', method='GET')
def get_push_events():
if not request.query.limit:
limit = 10
else:
limit = int(request.query.limit)
cursor = db['push_events'].aggregate([
{"$group": {"_id": {"username": "$actor.login", "profileurl": "$actor.url"}, "commits": {"$sum": 1}}},
{"$sort": SON([("commits", -1), ("_id", -1)])},
{"$limit": limit},
])
if not cursor:
abort(404, 'No document with id')
response.content_type = 'application/json'
entries = [entry for entry in cursor['result']]
return MongoEncoder().encode(entries)
@route('/watch/top', method='GET')
def get_push_events():
if not request.query.limit:
limit = 10
else:
limit = int(request.query.limit)
reducer = Code("""
function(obj, prev){
prev.count++;
}
""")
cursor = db['watch_events'].aggregate([
{"$group": {"_id": {"repository": "$repo.name"}, "count": {"$sum": 1}}},
{"$sort": SON([("count", -1), ("_id", -1)])},
{"$limit": limit}
])
if not cursor:
abort(404, 'No document with id')
response.content_type = 'application/json'
entries = [entry for entry in cursor['result']]
return MongoEncoder().encode(entries)
@route('/issues/top', method='GET')
def get_push_events():
if not request.query.limit:
limit = 10
else:
limit = int(request.query.limit)
reducer = Code("""
function(obj, prev){
prev.count++;
}
""")
cursor = db['issues_events'].aggregate([
{"$group": {"_id": {"repository": "$repo.name"}, "count": {"$sum": 1}}},
{"$sort": SON([("count", -1), ("_id", -1)])},
{"$limit": limit}
])
if not cursor:
abort(404, 'No document with id')
response.content_type = 'application/json'
entries = [entry for entry in cursor['result']]
return MongoEncoder().encode(entries)
@route('/getfile', method='GET')
def get_index():
f = open('../visualization/index.html').read()
print f
return static_file("index.html", "/Users/vaishaksuresh/Semester3/cmpe226/dev/cmpe226nosql/visualization")
run(host='localhost', port=8080, reloader=True)
|
UTF-8
|
Python
| false | false | 2,013 |
10,393,820,887,801 |
892ff93a49c9d2e6204d49b7fbe1719fc8c1b556
|
21a77ed3498e649ecc7446584edf46b62c361d59
|
/orange/models/myf_operate.py
|
ebaab61f78e828ab9f073019d91e00f29c03f0eb
|
[] |
no_license
|
kejukeji/heart_counsel_py
|
https://github.com/kejukeji/heart_counsel_py
|
e45419d9b2baf3fe392d64c5596a45e96f96a280
|
3fa2dbdad43b0c12da6130d6e634e6c7003fd1f0
|
refs/heads/master
| 2021-01-13T02:11:00.869579 | 2013-11-28T08:08:15 | 2013-11-28T08:08:15 | 14,770,940 | 0 | 1 | null | null | null | null | null | null | null | null | null | null | null | null | null |
# coding: utf-8
from sqlalchemy import Column, Integer, String, Boolean, DATETIME, ForeignKey, text
from .database import Base
myf_operate_table = 'myf_operate'
class Myf_operate(Base):
__tablename__ = myf_operate_table
#__table_args__ = {
# 'mysql_engine': 'InnoDB',
# 'mysql_charset': 'utf8'
#}
id = Column(Integer, primary_key=True)
browse_content = Column(String(512), nullable=False)
user_id = Column(Integer, nullable=False)
user_name = Column(String(20), nullable=False)
browse_date = Column(DATETIME, nullable=False)
ip_address = Column(String(20), nullable=False)
|
UTF-8
|
Python
| false | false | 2,013 |
7,902,739,861,998 |
166e9cef34efdfc25ff85947847fbcf0eb21757e
|
36b8294e8a51a57ade185fb6ba83e158cee6b809
|
/Unit4-19_OptimumPolicy2D.py
|
02b497bbc61f5e291a036e4fd2e4546fcb7bc394
|
[] |
no_license
|
Dmdv/CS373
|
https://github.com/Dmdv/CS373
|
317e73632e687f49b7b355269cad4942a9d2c247
|
b0dd9dec4d1ce28fb2bbdb69eb85dfe74299d615
|
refs/heads/master
| 2020-06-04T06:20:05.469823 | 2012-04-16T20:57:01 | 2012-04-16T20:57:01 | null | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null |
__author__ = 'Dyachkov'
# ----------
# User Instructions:
#
# Implement the function optimum_policy2D() below.
#
# You are given a car in a grid with initial state
# init = [x-position, y-position, orientation]
# where x/y-position is its position in a given
# grid and orientation is 0-3 corresponding to 'up',
# 'left', 'down' or 'right'.
#
# Your task is to compute and return the car's optimal
# path to the position specified in `goal'; where
# the costs for each motion are as defined in `cost'.
#These dimensions are for the 4 possible orientations that robot can be [up, down, left, right],
# these are not state variables
# EXAMPLE INPUT:
# grid format:
# 0 = navigable space
# 1 = occupied space
grid = [[1, 1, 1, 0, 0, 0],
[1, 1, 1, 0, 1, 0],
[0, 0, 0, 0, 0, 0],
[1, 1, 1, 0, 1, 1],
[1, 1, 1, 0, 1, 1]]
goal = [2, 0] # final position
init = [4, 3, 0] # first 2 elements are coordinates, third is direction
cost = [2, 1, 20] # the cost field has 3 values: right turn, no turn, left turn
grid1 = [[0, 0, 0, 0, 0, 0],
[0, 0, 0, 0, 0, 0],
[0, 0, 0, 0, 0, 0]]
goal1 = [1, 5] # final position
init1 = [1, 0, 3] # first 2 elements are coordinates, third is direction
cost1 = [0.1, 1, 1] # the cost field has 3 values: right turn, no turn, left turn
# EXAMPLE OUTPUT:
# calling optimum_policy2D() should return the array
#
# [[' ', ' ', ' ', 'R', '#', 'R'],
# [' ', ' ', ' ', '#', ' ', '#'],
# ['*', '#', '#', '#', '#', 'R'],
# [' ', ' ', ' ', '#', ' ', ' '],
# [' ', ' ', ' ', '#', ' ', ' ']]
#
# ----------
# there are four motion directions: up/left/down/right
# increasing the index in this array corresponds to
# a left turn. Decreasing is is a right turn.
forward = [[-1, 0], # go up
[0, -1], # go left
[1, 0], # go down
[0, 1]] # do right
forward_name = ['up', 'left', 'down', 'right']
# the cost field has 3 values: right turn, no turn, left turn
action = [-1, 0, 1]
action_name = ['R', '#', 'L']
# ----------------------------------------
# modify code below
# ----------------------------------------
def optimum_policy2D():
#for orientation in range(4):
# for i in range(len(action)): # iteration by action
# o2 = (orientation + action[i]) % 4
# x2 = forward[o2][0]
# y2 = forward[o2][1]
# #print (forward_name[o2], forward[o2], action_name[i])
global o2
value = [[[999 for col in row ] for row in grid] for f in forward]
policy = [[[' ' for col in row ] for row in grid] for f in forward]
policy2D = [[' ' for row in range(len(grid[0]))] for col in range(len(grid))]
change = True
while change:
change = False
for x in range(len(grid)):
for y in range(len(grid[0])):
for orientation in range(4):
if goal[0] == x and goal[1] == y:
if value[orientation][x][y] > 0:
value[orientation][x][y] = 0
policy[orientation][x][y] = '*'
change = True
elif not grid[x][y]:
# calculate 3 ways to propagate value
for i in range(len(action)): # iteration by action
# to keep orientation within 3.
# left + up = right
o2 = (orientation + action[i]) % 4
x2 = x + forward[o2][0]
y2 = y + forward[o2][1]
#print ("o2 = ", o2, "x2 = ", x2, "y2 = ", y2)
if len(grid) > x2 >= 0 <= y2 < len(grid[0]) and grid[x2][y2] == 0:
v2 = value[o2][x2][y2] + cost[i]
if v2 < value[orientation][x][y]:
change = True
value[orientation][x][y] = v2
policy[orientation][x][y] = action_name[i]
x = init[0]
y = init[1]
orientation = init[2]
policy2D[x][y] = policy[orientation][x][y]
while policy[orientation][x][y] != '*':
if policy[orientation][x][y] == '#':
o2 = orientation
elif policy[orientation][x][y] == 'R':
o2 = (orientation - 1) % 4
elif policy[orientation][x][y] == 'L':
o2 = (orientation + 1) % 4
x = x + forward[o2][0]
y = y + forward[o2][1]
orientation = o2
policy2D[x][y] = policy[orientation][x][y]
return policy2D # Make sure your function returns the expected grid.
for row in optimum_policy2D():
print(row)
# You can move through the list of forward actions.
# If your direction is forward[i], forward[i-1]
# is the direction of a left turn and forward[i+1]
# is the direction of the right turn. Of course you should make this cyclic using % len(forward).
|
UTF-8
|
Python
| false | false | 2,012 |
4,320,737,135,768 |
7171460da27418853f33c317714da7ea0ce5d0d9
|
258faed17e99faf5250b0d245d6317f9dce35096
|
/vkapi.py
|
4ebcfd2c0d86d9a765ed1d9fc2bcfb9a283fd482
|
[
"GPL-2.0-only"
] |
non_permissive
|
masterx2/PythonVKTool
|
https://github.com/masterx2/PythonVKTool
|
38cfdbd5be0c45ce348983a48409957baf9b0ec3
|
bd6fad3391fdbc3cc96721f095cc2ca76c7f73f3
|
refs/heads/master
| 2021-01-22T09:13:19.729212 | 2014-08-03T21:00:43 | 2014-08-03T21:00:43 | null | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
__author__ = 'MasterX2'
from re import findall
from json import loads
from os import remove
from urllib import urlencode, urlopen, urlretrieve
from mechanize import Browser, _http
from antigate import AntiGate
class vkApi(object):
def __init__(self, appkey, email, password, scope, antiGateKey):
self.appkey = appkey
self.email = email
self.password = password
self.scope = scope
self.antiGateKey = antiGateKey
self.br = Browser()
self.getToken()
def getToken(self):
self.br.set_handle_robots(False)
self.br.set_handle_refresh(_http.HTTPRefreshProcessor(), max_time=1)
self.br.addheaders = [('User-agent', 'Mozilla/5.0 (Linux; U; Android 3.0; \
ru-RU; Xoom Build/HRI39) AppleWebKit/534.13 KHTML, like Gecko Version/4.0 \
Safari/534.13')]
authparams = {
'client_id': self.appkey,
'scope': self.scope,
'redirect_uri': 'https://oauth.vk.com/blank.html',
'display': 'mobile',
'v': '5.23',
'response_type': 'token'
}
self.br.open('https://oauth.vk.com/authorize?' + urlencode(authparams))
self.br.select_form(nr=0)
self.br.form['email'] = self.email
self.br.form['pass'] = self.password
self.br.submit()
if 'grant_access' in self.br.response().read():
self.br.select_form(nr=0)
self.br.submit()
self.token = self.parseResponse
else:
self.token = self.parseResponse
@property
def parseResponse(self):
return dict([x.split('=') for x in findall('\w+=\w+', self.br.geturl())])
def call(self, method, p):
strresponse = urlopen(
'https://api.vk.com/method/'+method+'?'+urlencode(p)+'&access_token='+self.token['access_token']).read()
ret = loads(strresponse)
try:
return ret['response']
except KeyError:
if ret['error']['error_code'] == 14:
print 'Captcha Need'
urlretrieve(ret['error']['captcha_img'], "cap_file.jpg")
captcha = AntiGate(self.antiGateKey, 'cap_file.jpg')
remove('cap_file.jpg')
p['captcha_sid'] = ret['error']['captcha_sid']
p['captcha_key'] = captcha
print 'Another Try...'
self.call(method, p)
else:
print "Unknow Error"
print ret
|
UTF-8
|
Python
| false | false | 2,014 |
13,374,528,162,065 |
5fbaf52ad7fbb61f9b2aaed3b563cfb2fb69d24c
|
bd2567fe24a029b231f097ab457163cc34b4a2e1
|
/bayfiles.py
|
df8f65150ae49d46bb9c863e804a11f4de5fa2f0
|
[] |
no_license
|
Anvil/python-bayfiles
|
https://github.com/Anvil/python-bayfiles
|
92f4f38a30b2c2f3798c6ab40f78167478d0026e
|
d4961bdaaa84968ff54abf811854ce79024b1031
|
refs/heads/master
| 2021-01-16T00:46:41.998190 | 2013-03-10T20:45:17 | 2013-03-10T20:45:17 | null | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null |
#!/usr/bin/env python
# coding:utf-8
#
import requests
import sys
class BasicException(requests.ConnectionError):
pass
class UploadException(BasicException):
pass
class DeleteException(BasicException):
pass
class File(object):
"""
File instance represent
"""
BASE_URL = "http://api.bayfiles.com/v1"
def __init__(self, filepath, session=''):
self.metadata = {}
self.filepath = filepath
self.session = session
# ask for an upload URL
self.__register_url()
def __register_url(self):
"""
This function will request an upload url to post the file you need to
store and a progress url that can be polled to know the progress of the
upload.
"""
url = self.BASE_URL + '/file/uploadUrl'
#if self.session:
# url += '?session={0}'.format(self.session)
r = requests.get(url)
if not r.ok:
r.raise_for_status()
self.metadata = r.json()
if self.metadata['error'] != u'':
raise UploadException(self.metadata['error'])
def __get_sha1hash(self):
"""Return the sha1 hash on the entire content of the file passed."""
# Don't know if it's "right" to import a module in a function
import hashlib
SHA1 = hashlib.sha1()
with open(self.filepath, 'rb') as file:
while True:
buffr = file.read(0x100000)
if not buffr:
break
SHA1.update(buffr)
sha1hash = SHA1.hexdigest()
return sha1hash
def upload(self, validate=True):
"""Upload the file to bayfiles server.
Keywords arguments:
validate -- a boolean, if set to True, it will ensure there was no
corruption during the transfert by comparing the sha1 hash of the local
file and the one computed by bayfile.
"""
with open(self.filepath, 'rb') as file_fd:
files = {'file': file_fd}
r = requests.post(self.metadata['uploadUrl'], files=files)
if not r.ok:
r.raise_for_status()
json = r.json()
if json['error'] == '':
self.metadata.update(json)
else:
raise UploadException(json['error'])
# If we ask the sha1 hash validation
if validate:
sha1hash = self.__get_sha1hash()
if not self.metadata['sha1'] == sha1hash:
raise UploadException(
"The file was corrupted during the upload")
def delete(self):
"""Delete the download url and the file stored in bayfiles."""
url = self.BASE_URL + '/file/delete/{0}/{1}'.format(
self.metadata['fileId'],
self.metadata['deleteToken'])
try:
r = requests.get(url)
if not r.ok:
r.raise_for_status()
json = r.json()
if json['error'] == u'':
return
else:
print json['error']
raise DeleteException(json['error'])
except:
print sys.exc_info()[0]
raise BaseException
def info(self):
"""Return public information about the file instance."""
url = self.BASE_URL + '/file/info/{0}/{1}'.format(
self.metadata['fileId'],
self.metadata['infoToken'])
try:
r = requests.get(url)
if not r.ok:
r.raise_for_status()
return r.json()
except KeyError:
print "Need to use upload() before info()"
except:
print sys.exc_info()[0]
raise BaseException
class Account(object):
pass
|
UTF-8
|
Python
| false | false | 2,013 |
14,164,802,156,387 |
45e8e6e952945671c01084c45425b1644b142072
|
ea3ac2f0d10aedd8a38212ad1d87647206b7c8db
|
/apps/orders/models.py
|
2a7e19d994c714cb974edb3885ab35aa726d6ed3
|
[] |
no_license
|
wd5/kaskad
|
https://github.com/wd5/kaskad
|
b2d7f60c9b812183dcefa63c03eaa9d51bb1095c
|
a1366cad04fc0aa93634a34abb464f4b73e23a12
|
refs/heads/master
| 2021-01-10T01:37:41.425139 | 2012-07-04T06:56:45 | 2012-07-04T06:56:45 | null | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null |
# -*- coding: utf-8 -*-
from django.utils.translation import ugettext_lazy as _
from django.db import models
from apps.catalog.models import Product
import datetime
import os
class Cart(models.Model):
create_date = models.DateTimeField(verbose_name=u'Дата создания', default=datetime.datetime.now)
sessionid = models.CharField(max_length=50, verbose_name=u'ID сессии')
class Meta:
verbose_name = _(u'cart')
verbose_name_plural = _(u'carts')
def __unicode__(self):
return u'%s - %s' % (self.sessionid,self.create_date)
def get_products(self):
return CartProduct.objects.select_related().filter(cart=self)
def get_products_count(self):
return self.get_products().count()
def get_total(self):
sum = 0
for cart_product in self.cartproduct_set.select_related().all():
sum += cart_product.get_total()
return sum
def get_str_total(self):
total = self.get_total()
value = u'%s' %total
if total._isinteger():
value = u'%s' %value[:len(value)-3]
count = 3
else:
count = 6
if len(value)>count:
ends = value[len(value)-count:]
starts = value[:len(value)-count]
return u'%s %s' %(starts, ends)
else:
return value
class CartProduct(models.Model):
cart = models.ForeignKey(Cart, verbose_name=u'Корзина')
count = models.PositiveIntegerField(default=1, verbose_name=u'Количество')
product = models.ForeignKey(Product, verbose_name=u'Товар')
class Meta:
verbose_name =_(u'product_item')
verbose_name_plural =_(u'product_items')
def get_total(self):
total = self.product.price * self.count
return total
def get_str_total(self):
total = self.get_total()
value = u'%s' %total
if total._isinteger():
value = u'%s' %value[:len(value)-3]
count = 3
else:
count = 6
if len(value)>count:
ends = value[len(value)-count:]
starts = value[:len(value)-count]
return u'%s %s' %(starts, ends)
else:
return value
def __unicode__(self):
return u'на %s руб.' % self.get_str_total()
from django.db.models.signals import post_save
def delete_old_carts(sender, instance, created, **kwargs):
if created:
now = datetime.datetime.now()
day_ago30 = now - datetime.timedelta(days=30)
carts = Cart.objects.filter(create_date__lte=day_ago30)
if carts:
carts.delete()
post_save.connect(delete_old_carts, sender=CartProduct)
class Order(models.Model):
fullname = models.CharField(max_length=150, verbose_name=u'Фамилия Имя Отчество')
create_date = models.DateTimeField(verbose_name=u'Дата оформления', default=datetime.datetime.now)
contact_info = models.CharField(max_length=255, verbose_name=u'Контактная информация')
class Meta:
verbose_name = _(u'order_item')
verbose_name_plural = _(u'order_items')
ordering = ('-create_date',)
def __unicode__(self):
return u'%s - %s' % (self.fullname,self.create_date)
def get_products(self):
return self.orderproduct_set.select_related().all()
def get_products_count(self):
return self.get_products().count()
def get_total(self):
sum = 0
for order_product in self.orderproduct_set.select_related().all():
sum += order_product.get_total()
return sum
def get_str_total(self):
total = self.get_total()
value = u'%s' %total
if total._isinteger():
value = u'%s' %value[:len(value)-3]
count = 3
else:
count = 6
if len(value)>count:
ends = value[len(value)-count:]
starts = value[:len(value)-count]
return u'%s %s' %(starts, ends)
else:
return value
def admin_summary(self):
return '<span>%s</span>' % self.get_str_total()
admin_summary.allow_tags = True
admin_summary.short_description = 'Сумма'
class OrderProduct(models.Model):
order = models.ForeignKey(Order, verbose_name=u'Заказ')
count = models.PositiveIntegerField(default=1, verbose_name=u'Количество')
product = models.ForeignKey(Product, verbose_name=u'Товар')
def __unicode__(self):
return u'на сумму %s руб.' % self.get_str_total()
class Meta:
verbose_name =_(u'product_item')
verbose_name_plural =_(u'product_items')
def get_total(self):
total = self.product.price * self.count
return total
def get_str_total(self):
total = self.get_total()
value = u'%s' %total
if total._isinteger():
value = u'%s' %value[:len(value)-3]
count = 3
else:
count = 6
if len(value)>count:
ends = value[len(value)-count:]
starts = value[:len(value)-count]
return u'%s %s' %(starts, ends)
else:
return value
|
UTF-8
|
Python
| false | false | 2,012 |
12,094,627,935,389 |
63c0946f796f9e72b5495f36eb08f60bca979645
|
3f8ac65ed68c6a043c1037fa6852c29361e61080
|
/bin/services/microblogging.py
|
5c6e1a40fc1d9ac858bfa54eda211596dfb23029
|
[
"AGPL-3.0-only",
"AGPL-3.0-or-later"
] |
non_permissive
|
pramos/bgp-ranking
|
https://github.com/pramos/bgp-ranking
|
488dd59ae6bb3fd99a242a7dc55b56e4c68ac379
|
2c594f8356341f8164a642242a5148ee1929b76d
|
refs/heads/master
| 2017-04-30T03:18:46.750414 | 2013-02-13T15:35:33 | 2013-02-13T15:35:33 | null | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null |
#!/usr/bin/python
# -*- coding: utf-8 -*-
"""
:file:`bin/services/microblog.py` - Microblogging client
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
Start the microblogging client which posts on twitter and identica
"""
import os
import sys
import ConfigParser
import time
from pubsublogger import publisher
dev_mode = True
if __name__ == '__main__':
config = ConfigParser.RawConfigParser()
config_file = "/etc/bgpranking/bgpranking.conf"
config.read(config_file)
root_dir = config.get('directories','root')
sys.path.append(os.path.join(root_dir,config.get('directories','libraries')))
from microblog.micro_blog import MicroBlog
sleep_timer = int(config.get('sleep_timers','intermediate'))
publisher.channel = 'Ranking'
mb = MicroBlog()
while 1:
try:
if mb.post_last_top(dev_mode):
publisher.info('New Ranking posted on twitter and identica.')
mb.grab_dms(mb.twitter_api, mb.last_dm_twitter_key)
mb.grab_dms(mb.identica_api, mb.last_dm_identica_key)
except:
pass
time.sleep(sleep_timer)
|
UTF-8
|
Python
| false | false | 2,013 |
2,757,369,047,072 |
8997ef74c6e4df5faa05b94625d4bfd4d7537678
|
571240c7643d52738ae556bdeb051ac114211a77
|
/zcli/Zabbix.py
|
2236800a975146c7bcc760f220e25b787d218400
|
[
"Apache-2.0",
"LicenseRef-scancode-unknown-license-reference"
] |
non_permissive
|
dingus9/python-zcli
|
https://github.com/dingus9/python-zcli
|
140656cdf887db5e0f39dfb7a8dce45430ec0567
|
0401ba32a07a273500022de61d6e059fef24a339
|
refs/heads/master
| 2020-02-01T05:55:34.976449 | 2014-07-04T17:09:57 | 2014-07-04T17:09:57 | null | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null |
from ClsDict import ClsDict
from Tools import *
## Object Generator Methods ##
@register_object
def template(rpc_callback, obj=None, id=None, parent=None):
if id:
templateObj = Template(rpc_callback=rpc_callback, parent=parent)
templateObj[templateObj._zid] = id
templateObj.load()
elif obj:
if isinstance(obj, dict):
templateObj = Template(obj, rpc_callback=rpc_callback, parent=parent)
templateObj.load(local=True)
return templateObj
@register_object
def httptest(rpc_callback, obj=None, id=None, parent=None):
if id:
httptestObj = HttpTest(rpc_callback=rpc_callback, parent=parent)
httptestObj[httptestObj._zid] = id
httptestObj.load()
elif obj:
if isinstance(obj, dict):
httptestObj = HttpTest(obj, rpc_callback=rpc_callback, parent=parent)
httptestObj.load(local=True)
return httptestObj
@register_object
def trigger(rpc_callback, obj=None, id=None, parent=None):
if id:
triggerObj = Trigger(rpc_callback=rpc_callback, parent=parent)
triggerObj[triggerObj._zid] = id
triggerObj.load()
elif obj:
if isinstance(obj, dict):
triggerObj = Trigger(obj, rpc_callback=rpc_callback, parent=parent)
triggerObj.load(local=True)
return triggerObj
@register_object
def application(rpc_callback, obj=None, id=None, parent=None):
if id:
applicationObj = Application(rpc_callback=rpc_callback, parent=parent)
applicationObj[applicationObj._zid] = id
applicationObj.load()
elif obj:
if isinstance(obj, dict):
applicationObj = Application(obj, rpc_callback=rpc_callback, parent=parent)
applicationObj.load(local=True)
return applicationObj
def objects():
return globs(__name__, 'object')
#### Base Class ####
class ZabbixObjBase(ClsDict):
def __init__(self, *args, **kwargs):
"""Class takes zapi instance and an rpc helper function"""
# rpc callback takes
# str: object.action example: template.get
# str: query options query string
if 'rpc_callback' not in kwargs:
raise ValueError('rpc_callback is None')
super(ZabbixObjBase, self).__init__(*args, cls_properties=['rpc',
'loaded',
'parent',
'_objects_plural',
'_objects',
'_zdependants',
'_callback_ran'])
self.rpc = kwargs['rpc_callback']
if 'parent' in kwargs:
self.parent = kwargs['parent']
else:
self.parent = None
self._zdependants = {} # store deps as sub-object deps are created
self._callback_ran = False
global objects
self._objects_plural = [x.lower() + 's' for x in objects()]
self._objects = [x.lower() for x in objects()]
def load(self, local=False):
try:
# rpc callback with rpc method[object.get], and params sub'd for id field
if not local:
resp = self.rpc(self._zget['method'],
[x.format(id=self[self._zid])
for x in self._zget['params']])
self._callback_ran = True
else:
resp = [self]
for obj in resp:
for param, val in obj.iteritems():
# look for sub structures and instantiate as Zabbix.Object classes
if param.lower() in self._objects_plural:
obj_funct = globals()[param.lower()[:-1]]
if isinstance(val, list):
for i, item in enumerate(val): # update with Zabbix.Object
val[i] = self.add_child(obj_funct, item, parent=self)
self[param] = val
else:
self[param] = self.add_child(obj_funct, val, parent=self)
elif param.lower() in self._objects:
print(param)
else:
self[param] = val
except:
raise
def save(self, update=True):
"""Save self to target rpc endpoint.
update: overwrite existing if they exist, match on self.exists"""
if update and self.exists():
self.create(update)
else:
self.create(update)
for key, child in self.children.iteritems():
child.save()
def create(self, update=True):
for key, value in self.iteritems():
if isinstance(value, ZabbixObjBase):
pass
elif isinstance(value, list):
for obj in value:
#TODO: flesh this out
# begin create/update self
# generate dep list for dependant fields
# get new id's to propigate updated values resolve_dependancy
# 1. dep_list: things that must exist first
# 2. check if dep is loaded, else create deps first
# a. Deadlock/inf dep loop resolution
# 3. update/create dep fkeys fields
# a. new object... propigate id/fkey fields in self
# b. existing... update non _zid fkey fields with propigate self
# 4. save self - rpc.update to remote
# 5. set self._callback_ran = True indicating we are now reflecting
# accurate values that can be used to propigate dependies
# 6. return
# end create/update self
print obj
def resolve_dependancy(self, dependancy, parent=None):
"""Greedily ask self and parent if it has a dependancy.
Looks through self, children and parents and returns first object that
satifies dependancy by class.__name__.lower().
"""
if not parent:
parent = self.parent
if dependancy.lower() == self.__class__.__name__.lower():
return self
for key, child in self.children.iteritems():
dep = child.resolve_dependancy(dependancy)
if dep:
return dep
if parent:
return parent.resolve_depenancy(dependancy)
else:
return None
@property
def children(self):
"""A list of dependancies"""
return self._zdependants # initialized in __init__
@children.setter
def children(self, children):
self._zdependants = children
def add_child(self, object_function, val, parent=None):
"""Add a sub item and track it as a dependancy"""
if not id(val) in self._zdependants:
obj = object_function(self.rpc, obj=val, parent=parent)
self._zdependants[id(val)] = obj
return obj
@property
def loaded(self):
"""Loaded if true"""
if self[self._zid] and self._callback_ran:
return True
else:
return False
@property
def id(self):
return self[self._zid]
def exists(self, by_zid=False):
"""Look for existance by unique fields in _zexists or zid if by_zid=True"""
# build options
if not isinstance(self._zpkey, list):
keys = [self._zpkey]
else:
keys = self._zpkey
kvp = {}
for key in keys:
kvp[key] = self[key]
options = []
# format opt strings
for opt in self._zexists['params']:
options.append(opt.format((), **kvp))
return self.rpc(self._zexists['method'], options)
#class CreatePairs(ZabbixObjBase):
#
#
class Application(ZabbixObjBase):
# pkey specifies fields that make an entry unique, but not an internal auto inc key
_zpkey = 'name'
_zfkeys = [{'hostid': '{obj._zid}'}]
_zid = 'applicationid'
_zget = {'method': 'application.get',
'params': ['output=extend',
'applicationids=[{id}]',
'selectItems=extend']}
_zexists = {'method': 'template.exists',
'params': ['name={name}']}
_zupdate = {'method': 'application.update',
'params': ''}
_zcreate = {'method': 'application.create',
'params': ''}
class Template(ZabbixObjBase):
_zid = 'templateid'
# Database independant unique name or field/s list[strings] or string
_zpkey = 'host'
_zget = {'method': 'template.get',
'params': ['output=extend',
'templateids=[{id}]',
'selectHttpTests=extend',
'selectTriggers=extend',
'selectScreens=extend',
'selectMacros=extend',
'selectApplications=extend',
'selectItems=extend']}
_zupdate = {'method': 'template.update',
'params': ''}
_zcreate = {'method': 'template.create',
'params': ''}
_zexists = {'method': 'template.exists',
'params': ['host={host}']}
class HttpTest(ZabbixObjBase):
# Database independant unique name or field/s list[strings] or string
_zpkey = 'name'
_zid = 'httptestid'
# get options
_zget = {'method': 'httptest.get',
'params': ['output=extend',
'httptestids=[{id}]',
'selectSteps=extend']}
_zupdate = {'method': 'httptest.update',
'params': ''}
_zcreate = {'method': 'httptest.create',
'params': ''}
_zexists = {'method': 'template.get',
'params': ['filter={{"name": "{name}"}}']}
def exists(self, by_zid=False):
"""Handle exists with a httptest.get instead of exists."""
result = super(HttpTest, self).exists()
return isinstance(result, list) and len(result)
class Trigger(ZabbixObjBase):
_zget = {'method': 'trigger.get',
'params': ['output=extend',
'triggerids=[{id}]',
'selectFunctions=extend',
'expandExpression=True',
'expandComment=True',
'expandDescription=True']}
_zupdate = {'method': 'trigger.update',
'params': ''}
_zcreate = {'method': 'trigger.create',
'params': ''}
_zid = 'triggerid'
_subordinates = [{'param': 'functions',
'type': list,
'createmap': {'triggerid': 'triggerid',
'functionid': 'create',
'itemid': 'create'}}]
_zexists = {'method': 'template.exists',
'params': ['description={description}',
'expression=={expression}']}
# Database independant unique name or field/s list[strings] or string
_zpkey = ['description', 'expression']
def create_subordinates(self):
"""Create subordinates with new data"""
pass
def update_subordinates(self, values):
pass
|
UTF-8
|
Python
| false | false | 2,014 |
8,126,078,145,424 |
cf7f3309265d66ee99aa8585d34923dc0f3c1344
|
d5214b1331c9dae59d95ba5b3aa3e9f449ad6695
|
/qSiloGroup/tags/0.3.0/SiloSiteMap.py
|
296a790f2903b416916bc3a0f83d0878bccc1caa
|
[] |
no_license
|
kroman0/products
|
https://github.com/kroman0/products
|
1661ee25a224c4b5f172f98110944f56136c77cf
|
f359bb64db22f468db5d1e411638790e94d535a2
|
refs/heads/master
| 2021-01-10T07:58:04.579234 | 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 AccessControl import ClassSecurityInfo
from Products.Archetypes.public import Schema
from Products.qSiloGroup.config import PROJECTNAME
from Products.ATContentTypes.content.base import registerATCT
from Products.ATContentTypes.content.base import ATCTContent
from Products.ATContentTypes.content.schemata import ATContentTypeSchema
from Products.ATContentTypes.content.schemata import finalizeATCTSchema
from Products.ATContentTypes.lib.historyaware import HistoryAwareMixin
SiloSiteMapSchema = ATContentTypeSchema.copy()
SiloSiteMapSchema['id'].default = 'sitemap.htm'
SiloSiteMapSchema['id'].default_method = 'getDefaultId'
SiloSiteMapSchema['title'].default_method = 'getDefaultTitle'
SiloSiteMapSchema['allowDiscussion'].schemata = 'metadata'
SiloSiteMapSchema['relatedItems'].schemata = 'metadata'
SiloSiteMapSchema['description'].schemata = 'metadata'
class SiloSiteMap(ATCTContent, HistoryAwareMixin):
""" Silo Site Map """
schema = SiloSiteMapSchema
content_icon = 'document_icon.gif'
meta_type = 'SiloSiteMap'
portal_type = 'SiloSiteMap'
archetype_name = 'Silo Sitemap'
default_view = 'silositemap_view'
immediate_view = 'silositemap_view'
suppl_views = ()
typeDescription= 'Silo Sitemap'
typeDescMsgId = 'description_edit_document'
security = ClassSecurityInfo()
def getDefaultTitle(self):
""" Buid default title """
return self.aq_parent.Title() + ' Sitemap'
def getDefaultId(self):
""" """
return 'sitemap.htm'
registerATCT(SiloSiteMap, PROJECTNAME)
|
UTF-8
|
Python
| false | false | 2,014 |
9,560,597,222,541 |
47413110b720649e773cb3f544a4c3810c3c8115
|
50c68e1bd6e421af0b79ff50080995a87bd78b0c
|
/main.py
|
81d117e3541d47ae4bbcab03be37d373b4591967
|
[] |
no_license
|
spacekate/imok
|
https://github.com/spacekate/imok
|
a0e3ab4dab693fc736e40fa953cc6c5f6fb0c4bc
|
73d071b7378f9a80a3b26d8052703ec84a854670
|
refs/heads/master
| 2021-01-23T11:34:00.080644 | 2010-01-05T03:06:22 | 2010-01-05T03:06:22 | null | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null |
#!/usr/bin/env python
#
# I'm OK! website
import cgi
import os
import re
import wsgiref.handlers
import logging
import mimetypes
import urllib
import demjson
import logging
import random
import base64
import Cookie
from datetime import datetime
from html2text import html2text
from google.appengine.ext import webapp
from google.appengine.ext.webapp import template
from google.appengine.ext import db
from google.appengine.api import users
from google.appengine.api import urlfetch
from google.appengine.api import mail
from google.appengine.api import memcache
from models import *
from constants import *
from util import *
from CustomerLogic import *
### Base Classes
class RedirectException(Exception):
def __init__(self, url):
self.url = url
def __str__(self):
return repr(self.url)
class ReqHandler(webapp.RequestHandler):
def post(self):
self.get()
def get(self):
try:
self.process()
except RedirectException, e:
self.redirect(e.url)
def setCookie(self, key, value, expires=Constants().loginCookieExpiry()):
simpleCookie = Cookie.SimpleCookie()
simpleCookie[key] = str(base64.b64encode(value))
simpleCookie[key]['expires'] = expires
simpleCookie[key]['path'] = '/'
#simpleCookie[key]['domain'] = Constants().domain()
# Get the cookie without the header name as that is
# supplied to the add_header call separately.
cookie = simpleCookie.output(header='')
self.response.headers.add_header('Set-Cookie', cookie)
def logout(self, sucessUrl):
cookieKey = self.getLoginCookie()
if (cookieKey):
accountKey = memcache.delete(cookieKey, namespace='imok-token')
self.setCookie('imok-token', '', -99999)
self.redirect(sucessUrl)
def login(self, email, password, sucessUrl):
account= self.getAccountFromLogin(email, password)
if (account):
# create a cookie key
rnd = random.random()
id = account.key().id()
cookieKey = "%s-%s" %(rnd, id)
# set the cookie on the web client
logging.debug("setting cookie: imok-token=%s" % cookieKey)
self.setCookie('imok-token', cookieKey)
memcache.add(namespace='imok-token', key=cookieKey, value=account.key(), time=3600)
self.redirect(sucessUrl)
else:
params={
'message' : "The email and password did not match",
'sucessUrl': sucessUrl,
}
url = "/login.html?%s" %(urllib.urlencode(params))
self.redirect(url)
def getAccountFromLogin(self, email, password):
accountQuery = Customer.gql("WHERE email = :1 LIMIT 1",
email)
account = accountQuery.get()
logging.debug("getAccountFromLogin email: %s"% str(email))
if account:
passwordHash = getHash(password, account.passwordSeed)
if (passwordHash != account.passwordHash):
logging.debug("password and password hash did not match")
logging.debug("passwordHash: %s" % account.passwordHash)
logging.debug("passwordSeed: %s" % account.passwordSeed)
account = None
return account
def getLoginCookie(self):
# get the cookie
cookieKey =''
try:
cookieKey = str(base64.b64decode(self.request.cookies['imok-token']))
except KeyError:
#There wasn't a Cookie called that
pass
logging.debug("found cookie: imok-token=%s" % cookieKey)
return cookieKey
def getAccount(self, redirectOnFailure=True):
cookieKey = self.getLoginCookie()
# get the account from memcache
account=None
if (cookieKey):
accountKey = memcache.get(cookieKey, namespace='imok-token')
account=None
if (accountKey):
account = db.get(accountKey)
if (account):
return account
if (redirectOnFailure):
self.redirectToLogin("/account.html", "login timed out")
else:
return None
def redirectToLogin(self, sucessUrl, message=''):
params={
'message' : message,
'sucessUrl': sucessUrl,
}
url = "/login.html?%s" %(urllib.urlencode(params))
raise RedirectException(url)
#self.redirect(url)
def getJsonContacts(self, message=''):
account = self.getAccount()
contacts = []
for contact in account.contact_set:
contacts.append( {'email': contact.email, 'key': str(contact.key()), 'status': contact.status })
result = {'contacts': contacts}
result['message'] = message
return(demjson.encode(result))
def template(self, templateName, values):
self.response.out.write(self.getTemplate(templateName, values))
def getTemplate(self, templateName, values):
values['domain'] = Constants().domain()
account = values.get('account')
if (account):
values['logoutLink'] = '/logout/'
# if account.username =='hamish' or account.username =='spacekate':
# values['isAdmin'] = True
path = os.path.join(os.path.dirname(__file__),'templates', templateName)
return (template.render(path, values))
### Save Handlers
class NotificationHandler(ReqHandler):
pass
class WebNotificationHandler(NotificationHandler):
def process(self):
customer = self.getAccount()
logging.debug("Customer: %s" %str(customer))
deviceId = str(customer.key().id())
notify("website", deviceId, customer)
self.redirect('/account.html')
class ExternalNotificationHandler(NotificationHandler):
def process(self):
vendorId = self.request.get('vendorId')
deviceId = self.request.get('deviceId')
result = notify(vendorId, deviceId)
values = {
'vendorId': vendorId,
'deviceId': deviceId,
'Result' : result,
}
self.template("external_notification_responce.txt", values)
class SaveSettingsHandler(ReqHandler):
def process(self):
customer = self.getAccount()
customer.name = self.request.get('name', customer.name)
customer.phone = self.request.get('phone', customer.phone)
customer.mobile = self.request.get('mobile', customer.mobile)
customer.email = self.request.get('email', customer.email)
customer.timeout= int(self.request.get('timeout', customer.timeout))
customer.comment = self.request.get('comment', customer.comment)
customer.put()
self.redirect('/settings.html')
class NewContactHandler(ReqHandler):
def process(self):
contact = Contact()
contact.customer=self.getAccount()
contact.email=self.request.get('newContact')
contact.status='pending'
message=self.verifyContact(contact)
if (not message):
contact.put()
self.sendVerificationMessage(contact)
self.response.out.write(self.getJsonContacts(message))
def verifyContact(self, contact):
contactQuery = Contact.gql("WHERE customer = :1 AND email = :2 LIMIT 1",
contact.customer, contact.email)
storedContact = contactQuery.get()
if (storedContact):
return "Contact already exists"
else:
return None
def sendVerificationMessage(self, contact):
message=mail.EmailMessage()
message.sender=Constants().adminFrom()
message.to=contact.email
message.subject = "[imok] Are you willing to help monitor %s " %(contact.customer.name)
htmlBody = self.getTemplate("email/new_contact_verification.txt", {'contact': contact})
message.html=htmlBody
message.body = html2text(htmlBody)
message.send()
class UpdateContactHandler(ReqHandler):
def update(self, status):
contact_key = self.request.get('contactId')
contact= db.get(db.Key(contact_key))
if (contact):
contact.status=status
contact.put()
values={
'contact': contact,
}
self.template("%s.html" % status, values)
class ContactDeclineHandler(UpdateContactHandler):
def process(self):
self.update('declined')
class ContactAcceptHandler(UpdateContactHandler):
def process(self):
self.update('active')
class DeleteContactHandler(ReqHandler):
def process(self):
contact_key = self.request.get('contactId')
contact= db.get(db.Key(contact_key))
message=None
if (contact):
contact.delete()
else:
message="No contact with that key"
self.response.out.write(self.getJsonContacts(message))
### Web Handlers
class ListContactHandler(ReqHandler):
def process(self):
self.response.out.write(self.getJsonContacts(message=''))
class AlertPageHandler(ReqHandler):
def process(self):
alertId = self.request.get('alertId')
(alertKey, a, alertCheck) = alertId.partition('-')
key = db.Key.from_path('Alert', int(alertKey))
alert= db.get(key)
if (alertCheck == alert.check):
values={'alert': alert}
self.template('alert.html', values)
else:
self.error(404)
self.template('alert_not_found.html', {})
#class FrontPageHandler(ReqHandler):
# def process(self):
# if (users.get_current_user()):
# self.redirect('/account.html')
# else:
# self.template('index.html', {})
class RegisterHandler(NotificationHandler):
def process(self):
# username = self.request.get('username')
email = self.request.get('email')
logging.debug("Register email: %s" % email)
password = self.request.get('password')
retypePassword = self.request.get('retypePassword')
# passwordHash = getHash(password)
name = self.request.get('name')
sucessUrl= self.request.get('sucess_url')
phone = self.request.get('phone')
mobile = self.request.get('mobile')
if (password != retypePassword):
params={
'message' : Constants().passwordsDontMatchError(),
'sucessUrl': sucessUrl,
}
url = "/register.html?%s" %(urllib.urlencode(params))
self.redirect(url)
return
try:
createAccount(email, password, name, phone, mobile)
self.login(email, password, sucessUrl)
except AccountExistsException, e:
params={
'message' : "The email address has already been registered",
'sucessUrl': sucessUrl,
}
url = "/register.html?%s" %(urllib.urlencode(params))
self.redirect(url)
self.redirect(sucessUrl)
class LoginHandler(ReqHandler):
def process(self):
email = self.request.get('email')
password = self.request.get('password')
sucessUrl= self.request.get('sucess_url')
self.login(email, password, sucessUrl)
class LogoutHandler(ReqHandler):
def process(self):
sucessUrl= self.request.get('sucess_url', '/index.html')
self.logout(sucessUrl)
class AdminHandler(ReqHandler):
def process(self):
email = self.request.get('email')
values={}
values['isAdmin'] = True
self.template('adminDashboard.html', values)
class AdminButtonRegistrationHandler(ReqHandler):
def process(self):
email = self.request.get('email')
vendorId = self.request.get('vendorId')
deviceId = self.request.get('deviceId')
accountQuery = Customer.gql("WHERE email = :1 LIMIT 1",
email)
account = accountQuery.get()
if (account):
source=Source()
source.customer = account
source.vendorId=vendorId
source.deviceId=deviceId
source.put()
self.redirect('/admin/')
class FallbackHandler(ReqHandler):
def process(self):
authRequired = ('account.html', 'settings.html')
template_name = 'index.html'
values = {}
url = self.request.path
match = re.match("/(.*)$", url)
if match:
name=match.groups()[0]
if name:
template_name=name
logging.debug ("template: %s" % template_name)
account = self.getAccount(redirectOnFailure=False)
if (not account and template_name in authRequired):
self.redirectToLogin("/%s"%template_name, "login required")
if (account):
logging.debug('looking for notifications')
notificationQuery = Notification.gql("WHERE customer =:1 ORDER BY dateTime DESC", account)
notificationResults = notificationQuery.fetch(10)
values={
'notifications': notificationResults,
'account': account,
'customer': Constants().fakeCustomer(account),
'alert': Constants().fakeAlert(account),
'timeSinceNotification': (datetime.utcnow() - self.getAccount().lastNotificationDate)
}
values['args'] = self.getArgs()
self.template(template_name, values)
def getArgs(self):
args={}
for i in self.request.arguments():
args[i] = self.request.get(i)
return args
def main():
application = webapp.WSGIApplication(
[
# ('/signup/save/', SignupHandler),
#('/signup.html', SignupPageHandler),
('/notify', WebNotificationHandler),
# ('/', FrontPageHandler),
('/contact/list/', ListContactHandler),
('/contact/add/', NewContactHandler),
('/contact/delete/', DeleteContactHandler),
('/contact/decline', ContactDeclineHandler),
('/contact/accept', ContactAcceptHandler),
('/settings/save/', SaveSettingsHandler),
('/alert', AlertPageHandler),
('/login/', LoginHandler),
('/logout/', LogoutHandler),
('/register/', RegisterHandler),
('/notification/', ExternalNotificationHandler),
('/admin/registerButton/', AdminButtonRegistrationHandler),
('/admin/', AdminHandler),
('.*', FallbackHandler),
]
)
wsgiref.handlers.CGIHandler().run(application)
if __name__ == '__main__':
main()
|
UTF-8
|
Python
| false | false | 2,010 |
8,693,013,842,656 |
23c63b6d291f1b82e99b6beef3ccc27aca95012b
|
0b29c9a9ab5942210e3bd5d6d77e0849b4d72ac9
|
/books/models.py
|
2146e026292d4148266cf8cdc2382f0533475467
|
[] |
no_license
|
enim/bp_project
|
https://github.com/enim/bp_project
|
fd1ec1a86e9138542055b946cd011343000cf9d7
|
61dd95d316680bd5dd05deb66fc555e9d8979ee8
|
refs/heads/master
| 2016-09-09T17:42:49.217482 | 2012-12-05T14:15:10 | 2012-12-05T14:15:10 | null | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null |
from django.db import models
from django.contrib.auth.models import User
class Book(models.Model):
title = models.CharField(max_length=200)
def __unicode__(self):
return self.title
class BookStand(models.Model):
owner = models.ForeignKey(User)
books = models.ForeignKey(Book)
register_date = models.DateTimeField('register date')
vote = models.IntegerField()
|
UTF-8
|
Python
| false | false | 2,012 |
5,162,550,731,060 |
840395384b11f7e9589e26d17361b6a3971b7543
|
23bd9e476637e40b083428b141a4fa4929e05f25
|
/nicovideo_comment_distance/service/nicovideo.py
|
39d2cc19b3bdfc595a4d9cf76ee9a8b2c96c1a48
|
[] |
no_license
|
Hi-king/niconico_comment_distance
|
https://github.com/Hi-king/niconico_comment_distance
|
493c58fd4dca2b36edbd067dce68492dcaef1a5c
|
f5b3979c28a368090bbf7761297df2775023c172
|
refs/heads/master
| 2020-05-19T12:47:25.447462 | 2014-12-20T11:17:14 | 2014-12-20T11:54:50 | 28,262,350 | 1 | 1 | null | null | null | null | null | null | null | null | null | null | null | null | null |
# -*- coding: utf-8 -*-
__author__ = 'ogaki'
import urllib2
from BeautifulSoup import BeautifulSoup
import mechanize
import re
import htmlentitydefs
import time
import unicodedata
import itertools
import os
import pickle
class Config:
MAIL = os.environ.get("MAIL")
PASS = os.environ.get("PASS")
DIR = os.path.dirname(__file__)+"/../../static"
@staticmethod
def comment_cache_filepath(video_id):
return Config.DIR + "/{}".format(video_id)
@staticmethod
def has_comment_cache(video_id):
return os.path.isfile(Config.comment_cache_filepath(video_id))
@staticmethod
def comment_from_cache(video_id):
with open(Config.comment_cache_filepath(video_id)) as f:
return pickle.load(f)
@staticmethod
def set_comment_cache(video_id, data):
with open(Config.comment_cache_filepath(video_id), "w+") as f:
return pickle.dump(data, f)
@staticmethod
def videoinfo_cache_filepath(video_id):
return Config.DIR + "/info/{}".format(video_id)
@staticmethod
def has_videoinfo_cache(video_id):
return os.path.isfile(Config.videoinfo_cache_filepath(video_id))
@staticmethod
def videoinfo_from_cache(video_id):
with open(Config.videoinfo_cache_filepath(video_id)) as f:
return pickle.load(f)
@staticmethod
def set_videoinfo_cache(video_id, data):
with open(Config.videoinfo_cache_filepath(video_id), "w+") as f:
return pickle.dump(data, f)
@staticmethod
def videometa_cache_filepath(video_id):
return Config.DIR + "/meta/{}".format(video_id)
@staticmethod
def has_videometa_cache(video_id):
return os.path.isfile(Config.videometa_cache_filepath(video_id))
@staticmethod
def videometa_from_cache(video_id):
with open(Config.videometa_cache_filepath(video_id)) as f:
return pickle.load(f)
@staticmethod
def set_videometa_cache(video_id, data):
with open(Config.videometa_cache_filepath(video_id), "w+") as f:
return pickle.dump(data, f)
Browser = mechanize.Browser()
Browser.set_handle_robots(False)
class Comment:
def __init__(self, text, date):
self.text = self.normalize(text)
self.date = date
def cyclic_normalize(self, text):
"""
(1,2,3,4)文字の連続を吸収
e.g. wwwwww -> w
"""
lasts = [" ", " ", " ", " ", " "]
i = 0
ret = ""
while i < len(text):
ret += text[i]
for j in xrange(1, len(lasts)):
lasts[j] = lasts[j][1:]
lasts[j] += text[i]
while True:
if text[i:i+1] == lasts[1]: i+=1
elif text[i:i+2] == lasts[2]: i+=2
elif text[i:i+3] == lasts[3]: i+=3
elif text[i:i+4] == lasts[4]: i+=4
else: break
return ret
def normalize(self, text):
"""
正規化
参考: http://d.hatena.ne.jp/torasenriwohashiru/20110806/1312558290
"""
# 空白除去
if text is None: return None
unicode_normalized = unicodedata.normalize('NFKC', text)
normalized = "".join(unicode_normalized.split())
cyclic_normalized = self.cyclic_normalize(normalized)
return cyclic_normalized
class VideoMeta:
def __init__(self, video_id, title, description, comment_num, thumbnail_url, **lest_dict):
self.video_id = video_id
self.title = title
self.description = description
self.comment_num = comment_num
self.thumbnail_url = thumbnail_url
class VideoInfo:
def __init__(self, video_id, thread_id, ms, user_id, **lest_dict):
# url = "http://flapi.nicovideo.jp/api/getflv/{}".format(video_id)
self.video_id = video_id
self.thread_id = thread_id
self.ms = ms
self.user_id = user_id
threadkeyinfo = self.__getthreadkey()
self.threadkey = threadkeyinfo["threadkey"]
self.force_184 = threadkeyinfo["force_184"]
self.waybackkey = self.__getwaybackkey()["waybackkey"]
def comments(self, size=10):
# cache
if Config.has_comment_cache(video_id=self.video_id):
# return Config.comment_from_cache(video_id=self.video_id)[:size]
return Config.comment_from_cache(video_id=self.video_id) #キャッシュがあるときは全部使う
def comments_generator():
response = self.__fetch_comment()
comments_soup = list(reversed(response.find("packet").findAll("chat")[:-2]))
if len(comments_soup) == 0: raise StopIteration
for chat in comments_soup:
# print chat
comment = Comment(chat.string, int(chat["date"]))
if comment.text is None: continue
yield comment
while True:
print comment.date
response = self.__fetch_comment(date=comment.date)
comments_soup = list(reversed(response.find("packet").findAll("chat")[:-2]))
if len(comments_soup) == 0: raise StopIteration
for chat in comments_soup:
comment = Comment(chat.string, int(chat["date"]))
if comment.text is None: continue
yield comment
ret = list(itertools.islice(comments_generator(), 0, size))
Config.set_comment_cache(self.video_id, ret)
return ret
def __fetch_comment(self, date=None):
if date is None: date = int(time.time())
xml = '''
<thread
thread="{0}"
version="20061206"
res_from="-1000"
waybackkey="{1}"
when="{2}"
user_id="{3}"
threadkey="{4}"
scores="1"
force_184="{5}"
/>
'''.format(self.thread_id, self.waybackkey, date, self.user_id, self.threadkey, self.force_184)
# print xml
body = Browser.open(self.ms, xml).read()
return BeautifulSoup(body)
def __getwaybackkey(self):
url = "http://flapi.nicovideo.jp/api/getwaybackkey?thread={}".format(self.thread_id)
return self.__urlquoted2dict(Browser.open(url).read())
def __getthreadkey(self):
url = "http://flapi.nicovideo.jp/api/getthreadkey?thread={}".format(self.thread_id)
return self.__urlquoted2dict(Browser.open(url).read())
def __urlquoted2dict(self, response_string):
raw_list = [token.split("=") for token in response_string.split("&")]
unquoted_dict = dict([[k, urllib2.unquote(v)] for k,v in raw_list])
return unquoted_dict
class Nicovideo:
def __init__(self):
self.browser = Browser
self.log_in()
def log_in(self):
print "login"
print Config.MAIL
print Config.PASS
self.browser.open("https://secure.nicovideo.jp/secure/login?site=niconico")
self.browser.select_form(nr=0)
self.browser["mail_tel"]=Config.MAIL
self.browser["password"]=Config.PASS
self.browser.submit()
def getvideoinfo(self, video_id):
if Config.has_videoinfo_cache(video_id=video_id):
return Config.videoinfo_from_cache(video_id=video_id)
else:
print "video id =",video_id
flvinfo = self.__getflvinfo(video_id)
vinfo = VideoInfo(video_id, **flvinfo)
Config.set_videoinfo_cache(video_id, vinfo)
return vinfo
def getvideometa(self, video_id):
if Config.has_videometa_cache(video_id=video_id):
return Config.videometa_from_cache(video_id=video_id)
else:
url = "http://ext.nicovideo.jp/api/getthumbinfo/{}".format(video_id)
video_meta_soup = BeautifulSoup(self.browser.open(url).read())
thumb_dict = {item.name: item.text for item in video_meta_soup.find("thumb").findChildren(recursive=False)}
thumb_dict["video_id"] = video_id
vmeta = VideoMeta(**thumb_dict)
Config.set_videometa_cache(video_id, vmeta)
return vmeta
def __getflvinfo(self, video_id):
url = "http://flapi.nicovideo.jp/api/getflv/{}".format(video_id)
response_string = self.browser.open(url).readline()
raw_list = [token.split("=") for token in response_string.split("&")]
unquoted_dict = dict([[k, urllib2.unquote(v)] for k,v in raw_list])
print unquoted_dict
return unquoted_dict
def __htmlentity2unicode(self, text):
# 正規表現のコンパイル
reference_regex = re.compile(r'&(#x?[0-9a-f]+|[a-z]+);', re.IGNORECASE)
num16_regex = re.compile(r'#x\d+', re.IGNORECASE)
num10_regex = re.compile(r'#\d+', re.IGNORECASE)
result = u''
i = 0
while True:
# 実体参照 or 文字参照を見つける
match = reference_regex.search(text, i)
print "text"
print text
print "match", match
if match is None:
result += text[i:]
break
result += text[i:match.start()]
i = match.end()
name = match.group(1)
# 実体参照
if name in htmlentitydefs.name2codepoint.keys():
result += unichr(htmlentitydefs.name2codepoint[name])
# 文字参照
elif num16_regex.match(name):
# 16進数
result += unichr(int(u'0'+name[1:], 16))
elif num10_regex.match(name):
# 10進数
result += unichr(int(name[1:]))
return result
|
UTF-8
|
Python
| false | false | 2,014 |
352,187,357,154 |
22fe69c6c0100c33e320c24790c892384e65d0f8
|
891887ad3296b11df8417b97a655f2197eba448f
|
/knotportfolio.py
|
4d410500eaf9e1e570a409c795816f3dce5570b9
|
[] |
no_license
|
ShayanArman/knotPortfolio
|
https://github.com/ShayanArman/knotPortfolio
|
5c5c5d6253b447898399e0dae0a5daf387c74904
|
f988f972b3bfede54b89747f7096ef32e6510d80
|
refs/heads/master
| 2016-09-06T10:34:58.234915 | 2013-12-26T02:03:06 | 2013-12-26T02:03:06 | null | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null |
#//================================================================================================
import webapp2
from DBUserSavedStocks import SavedUserStocks
from GetStockAndUpdateUserInfo import asyncUpdate
from Login import login
from MainPage import main
from SellPage import sell
from LogOut import logout
from BuyStocksHandler import buyHandler
from SellStocksHandler import sellHandler
from DataHandler import data
from Settings import settings
from GetStockPrice import stockPriceHandler
from Login import register
from Contests import contest
#//================================================================================================
app = webapp2.WSGIApplication([('/',login.LoginUser),
('/render/(.*)/(.*)',asyncUpdate.RenderDynamic), # Buy stocks here.
('/portfolio/(.*)', main.MainPage), # Render the main page.
('/renderUserStocksDB',SavedUserStocks.getUserStocks), # Render the users stocks when they log in.
('/sell/(.*)/(.*)', sell.SellStocksPage),
('/logout', logout.LogOut),
('/settings', settings.Settings),
('/getPrice/(.*)', stockPriceHandler.GetPriceHandler),
('/data', data.Data),
('/contests', contest.ContestPage),
('/buystocks', buyHandler.BuyHandler),
('/sellstocks',sellHandler.SellHandler),
('/register',register.RegisterUser)], debug=True) # Sell / Ticker / Number Of Shares
|
UTF-8
|
Python
| false | false | 2,013 |
12,773,232,779,269 |
614e0efb510a87e8cb96e8576fda09d2d5bf74a7
|
e7ae4e3cca8f5f27e463bee6cdd4ebd1dc156751
|
/housing.py
|
b5a236219e92f6ad38397f32e2e40caa3446d5e4
|
[] |
no_license
|
Phelimb/fitzmcr2
|
https://github.com/Phelimb/fitzmcr2
|
f542888ff7e48b7dc5801a8de565f8c40a5bdc10
|
42235d0f175ff36aa425c396ab2e18f069def886
|
refs/heads/master
| 2016-09-05T17:46:20.568114 | 2013-05-15T22:10:40 | 2013-05-15T22:10:40 | null | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null |
from utils import *
from main import Handler
# housing
def housing_key(name = 'default'):
return db.Key.from_path('housing', name)
class housingPost(db.Model):
title = db.StringProperty(required = True)
content = db.TextProperty(required = True)
username = db.StringProperty(required = False)
created = db.DateTimeProperty(auto_now_add = True)
last_modified = db.DateTimeProperty(auto_now = True)
def render(self,login):
self._render_text = self.content.replace('\n', '<br>')
return render_str("housing_post.html", p = self, login = login)
class HousingHandler(Handler):
def get(self):
posts = db.GqlQuery("select * from housingPost order by created limit 10")
self.render('housing.html', posts = posts,login=self.user)
def post(self):
if self.user:
delHousing = int(self.request.get('deleteHousing'))
delKey = db.Key.from_path('housingPost',delHousing,parent=housing_key())
db.delete(delKey)
self.write(delKey)
self.redirect('/housing')
class HousingPostPage(Handler):
def get(self, post_id):
key = db.Key.from_path('housingPost', int(post_id), parent=housing_key())
post = db.get(key)
if not post:
self.error(404)
return
self.render("permalink.html", post = post,login=self.user)
class HousingNewPost(Handler):
def get(self):
self.render("newpost.html")
def post(self):
title = self.request.get('title')
content = self.request.get('content')
# Check the user is signed in
if not self.user:
self.redirect('/login')
if title and content and self.user:
cm = db.GqlQuery("SELECT * from CM WHERE ravenID = '%s'" % (self.user.name))
p = housingPost(parent = housing_key(), title = title, content = content,username = cm[0].firstname + ' ' + cm[0].lastname)
p.put()
self.redirect('/housing/%s' % str(p.key().id()))
else:
error = "title and content, please!"
self.render("newpost.html", title=title, content=content, error=error)
|
UTF-8
|
Python
| false | false | 2,013 |
8,804,682,996,801 |
8744322344617be1831a064902f28b0d556c17e2
|
02b891381b3cdef28439b172ef98264d068a9661
|
/lib/actions.py
|
e019def58f738a7b54240588119d3e5533290896
|
[] |
no_license
|
CNXTEoE/polerunner
|
https://github.com/CNXTEoE/polerunner
|
7e2f24b97256616f4f04afb7b8d09f6c44dc44a3
|
3e18d8003f023d1b751436f10b57f29a7232ba26
|
refs/heads/master
| 2017-06-23T17:53:27.928664 | 2012-12-14T22:25:34 | 2012-12-14T22:25:34 | 83,179,550 | 1 | 0 | null | true | 2017-02-26T03:18:04 | 2017-02-26T03:18:04 | 2016-09-01T18:42:49 | 2012-12-14T22:28:57 | 4,166 | 0 | 0 | 0 | null | null | null |
"""
All actions that can be executed by the player or NPCS will be added here.
These can be used with a pygoap context manager or lib2d fsm.
Clients who wish to use them may import them in their module.
"""
from pygoap import ActionContext
from lib2d.fsm import State
from lib2d.buttons import *
import pymunk
class HoverAction(ActionContext):
"""
hover in air and attempt to stay in one spot
includes some physics calculations that let body slowly come to stop
"""
max_power = 100
max_horiz_force = 40
hover_height = 32.0
tolerance = 2.0
def enter(self):
self.entity = self.parent.entity
self.body = self.entity.body
self.intended_position = pymunk.Vec2d(self.body.position)
self.space = self.entity.parent.space
for shape in self.space.shapes:
if shape.body is self.body:
self.shape = shape
break
self.weight = self.body.mass * self.entity.parent.gravity[1]
self.body.apply_impulse((0, -self.weight*.8))
self.entity.avatar.play('hover')
def update(self, time):
if round(self.body.velocity.y) >= 0:
gravity = self.entity.parent.gravity[1]
start = self.body.position
end = self.body.position + (4, self.hover_height)
height = -1
for hit in self.space.segment_query(start, end):
if hit.shape is not self.shape:
height = self.hover_height - hit.get_hit_distance()
# object is now above the floating height
if height == -1:
power = 0
else:
power = -(height / self.hover_height) * self.max_power * gravity
else:
power = 0
forces = self.body.force + (self.body.velocity * self.body.mass)
accel = forces / self.body.mass
deaccel = -self.max_horiz_force / self.body.mass
try:
t = self.body.velocity / -deaccel
disp = self.body.velocity * t + .5 * deaccel * t * t
except ZeroDivisionError:
disp = pymunk.Vec2d(0,0)
dist = self.intended_position - self.body.position
if abs(dist.x) < self.tolerance:
if self.body.velocity.x > 0:
self.body.velocity.x = 0
v = 0
elif abs(disp.x) >= abs(dist.x):
self.body.reset_forces()
if self.body.velocity.x > 0:
v = -self.max_horiz_force
elif self.body.velocity.x < 0:
v = self.max_horiz_force
else:
v = 0
else:
if dist.x > self.tolerance:
v = self.max_horiz_force
elif dist.x < self.tolerance:
v = -self.max_horiz_force
else:
v = 0
new_force = pymunk.Vec2d(v, power) * self.body.mass
delta_force = self.body.force - new_force
self.body.reset_forces()
self.body.apply_force(new_force)
if self.body.velocity.y > 0:
self.entity.avatar.play('hover')
elif self.entity.grounded:
#self.finish()
pass
else:
self.entity.avatar.play('idle')
class MoveAction(State):
"""
Move left or right for wheel-based-movement entities
This includes the player and most NPC/enemies
"""
def enter(self):
self.body = self.parent.entity.body
self.motor = self.parent.entity.motor
self.direction = self.trigger.cmd
if self.direction == P1_LEFT:
self.parent.entity.avatar.flip = 1
self.maxSpeed = self.parent.entity.max_speed
elif self.direction == P1_RIGHT:
self.parent.entity.avatar.flip = 0
self.maxSpeed = -self.parent.entity.max_speed
self.motor.rate = self.maxSpeed
def update(self, time):
vel = abs(self.body.velocity.x)
speed = abs(self.maxSpeed)
if 0 < vel < speed / 2:
self.parent.entity.avatar.play('walk')
elif vel >= speed / 2 and vel < speed*2:
self.parent.entity.avatar.play('run')
def exit(self):
self.motor.rate = 0
class CrouchAction(State):
def enter(self):
entity = self.parent.entity
body = self.parent.entity.body
entity.avatar.play('crouch', loop_frame=4)
w, h = entity.size
old_shape = entity.shapes[0]
entity.parent.space.remove(entity.shapes)
shape = pymunk.Poly.create_box(body, size=(w, h/2))
shape.collision_type = 0
shape.friction = old_shape.friction
entity.shapes = [shape]
body.position += (0, 16)
body.velocity.x = 0
entity.parent.space.add(shape)
class UncrouchAction(State):
def enter(self):
self.parent.entity.avatar.play('uncrouch', callback=self.stop, loop=0)
self.parent.entity.position -= (0, 8)
self.parent.entity.rebuild()
class JumpAction(State):
max_jumps = 2
def init(self):
self.body = self.parent.entity.body
self.jumps = 0
def enter(self):
self.parent.entity.avatar.play('jumping')
if not self.jumps == 0:
return
if self.parent.entity.grounded:
self.jumps = 1
self.body.apply_impulse((0, -self.parent.entity.jump_strength))
else:
if self.jumps <= self.max_jumps:
self.jumps += 2
self.body.apply_impulse((0, -self.parent.entity.jump_strength))
def update(self, time):
if self.body.velocity.y > 0:
self.stop()
if self.parent.entity.grounded:
self.stop()
class FallAction(State):
def enter(self):
self.parent.entity.avatar.play('falling')
def update(self, time):
if self.parent.entity.landed_previous or self.parent.entity.grounded:
self.stop()
class FallRecoverAction(State):
def enter(self):
self.parent.entity.avatar.play('crouch', loop_frame=4)
self.body = self.parent.entity.body
self.body.velocity.x /= 3.0
space = self.parent.entity.parent.space
for old_shape in space.shapes:
if old_shape.body is self.body:
break
space.remove(old_shape)
w, h = self.parent.entity.size
shape = pymunk.Poly.create_box(self.body, size=(w, h/2))
shape.collision_type = old_shape.collision_type
shape.friction = old_shape.friction
self.parent.entity.parent.shapes[self.parent.entity] = shape
self.body.position.y += 8
space.add(shape)
def update(self, time):
if abs(self.body.velocity.x) < INITIAL_WALK_SPEED:
self.stop()
class DieAction(State):
def enter(self):
self.parent.entity.avatar.play('die', loop_frame=2)
class AirMoveAction(State):
RIGHT = 0
LEFT = 1
def init(self):
self.body = self.parent.entity.body
def enter(self):
if self.trigger.cmd == P1_LEFT:
self.parent.entity.avatar.flip = self.LEFT
self.maxSpeed = -self.parent.entity.max_speed * 3
elif self.trigger.cmd == P1_RIGHT:
self.parent.entity.avatar.flip = self.RIGHT
self.maxSpeed = self.parent.entity.max_speed * 3
force = (self.maxSpeed * self.body.mass, 0)
self.body.apply_force(force)
def update(self, time):
self.body.reset_forces()
deltaVelocity = self.maxSpeed - self.body.velocity.x
force = (deltaVelocity * self.body.mass, 0)
self.body.apply_force(force)
if self.parent.entity.landed_previous or self.parent.entity.grounded:
self.stop()
if self.body.velocity.y == 0:
self.stop()
def exit(self):
self.body.reset_forces()
class IdleAction(State):
def enter(self):
self.parent.entity.avatar.play('idle')
class BrakeAction(State):
def enter(self):
self.body = self.parent.entity.body
self.parent.entity.avatar.play('brake', loop_frame=5)
self.parent.entity.parent.emitSound('stop.wav', entity=self.parent.entity)
def update(self, time):
if abs(self.body.velocity.x) < 1:
self.stop()
class UnbrakeAction(State):
def enter(self):
self.parent.entity.avatar.play('unbrake', callback=self.stop, loop=0)
body = self.parent.entity.body
class wallGrabState(State):
"""
allows player to stick to walls by applying horizontal force against a
wall. player will stick to wall by the friction of the wall
TODO: calculate force needed to let play slide down wall slowly
"""
RIGHT = 0
LEFT = 1
def init(self):
# since init is called before this context is added to the stack, we
# can safely get the values from the previous context, which in this
# case will always be airMoveState
self.trigger = self.parent.current_context.trigger
self.body = self.parent.entity.body
def enter(self):
if self.trigger.cmd == P1_LEFT:
self.maxSpeed = -WALLGRAB_FORCE
elif self.trigger.cmd == P1_RIGHT:
self.maxSpeed = WALLGRAB_FORCE
force = (self.maxSpeed * self.body.mass, 0)
self.body.apply_force(force)
def update(self, time):
self.body.reset_forces()
deltaVelocity = self.maxSpeed - self.body.velocity.x
force = (deltaVelocity * self.body.mass, 0)
self.body.apply_force(force)
def exit(self):
self.body.reset_forces()
class wallJumpState(State):
max_jumps = 2
def init(self):
# since init is called before this context is added to the stack, we
# can safely get the values from the previous context, which in this
# case will always be wallGrabState
self.trigger = self.parent.current_context.trigger
self.body = self.parent.entity.body
def enter(self):
if self.trigger.cmd == P1_LEFT:
force = WALLJUMP_FORCE
elif self.trigger.cmd == P1_RIGHT:
force = -WALLJUMP_FORCE
self.body.reset_forces()
force = (force * self.body.mass, -self.parent.entity.jump_strength)
self.body.apply_impulse(force)
def update(self, time):
if self.body.velocity.y > 0:
self.stop()
class RollAction(State):
def enter(self):
self.original = self.parent.entity.avatar.animations['roll'].surface
self.original = self.original.convert_alpha()
self.parent.entity.avatar.play('roll')
entity = self.parent.entity
old_body = entity.body
entity.parent.space.remove(entity.bodies, entity.shapes, entity.joints)
w, h = entity.size
r = w * .5
m = pymunk.moment_for_circle(entity.mass*5, 0, r)
body = pymunk.Body(entity.mass, m)
body.position = old_body.position + (0, r*2)
body.velocity = old_body.velocity
shape = pymunk.Circle(body, r)
shape.friction = .5
entity.bodies = [body]
entity.shapes = [shape]
entity.joints = []
entity.parent.space.add(entity.bodies, entity.shapes)
self.body = body
def update(self, time):
self.body.velocity.x *= .998
if abs(self.body.velocity.x) < 30:
self.parent.entity.avatar.animations['roll'].image = self.original
self.body.reset_forces()
self.body.velocity.x = 0
self.stop()
|
UTF-8
|
Python
| false | false | 2,012 |
8,358,006,360,600 |
841d4a9c7060dda40295a9984efa1528f0b66bfe
|
1c0993639db29d6965cb7102e4a6c0c161d75643
|
/deltaV/deltaV.py
|
acd15a46e818087bca37fe25e0c869dfa79c1b98
|
[] |
no_license
|
oodeagleoo/Rockets
|
https://github.com/oodeagleoo/Rockets
|
382f063c0d8f1667a839d5bb9c50027c13a3ceb9
|
e13c69365498544148edde0ae369477a40cecc22
|
refs/heads/master
| 2021-01-10T18:36:59.690128 | 2014-09-23T00:01:58 | 2014-09-23T00:01:58 | null | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null |
import tsiolkovsky
import terminate
term = 'n'
while term == 'n':
dV = tsiolkovsky.dV()
dV = round(dV, 3)
print()
print(dV,'m/s deltaV')
print()
term = terminate.terminate()
print()
|
UTF-8
|
Python
| false | false | 2,014 |
12,446,815,267,251 |
a0e50a22015f4c76e2a9675e9cb41ba4241b928c
|
7225a228c5258c66fc38ac9f888efeb9a9607117
|
/scenable/places/viewmodels.py
|
600644ab1abefe93d98e31e4d034195e3b049300
|
[] |
no_license
|
gregarious/betasite
|
https://github.com/gregarious/betasite
|
84f07b04072622c89cdb5f7066af5e7713c1babd
|
3ed85e856a026001a1d91d09d31d944c64704824
|
refs/heads/master
| 2021-01-01T15:51:21.779486 | 2014-09-05T01:45:53 | 2014-09-05T01:45:53 | null | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null |
from scenable.events.models import Event
from scenable.specials.models import Special
from django.contrib.auth.models import User
from scenable.events.viewmodels import EventData
from scenable.specials.viewmodels import SpecialData
from scenable.common.utils import get_cached_thumbnail
from django.template.defaultfilters import truncatewords
class PlaceData(object):
def __init__(self, place, user=None):
fields = ('id', 'name', 'location', 'description', 'tags', 'image', 'hours',
'url', 'fb_id', 'twitter_username', 'listed', 'get_absolute_url')
if isinstance(user, User):
self.is_favorite = place.favorite_set.filter(user=user).count() > 0
else:
self.is_favorite = False
for attr in fields:
setattr(self, attr, getattr(place, attr))
# do hours and parking separately
#self.parking = place.parking_unpacked()
self.pk = self.id
def serialize(self):
'''
Temporary method to take the place of TastyPie serialization
functionality. Will remove later in place of TastyPie functionality,
but too many special issues (e.g. thumbnails) to worry about
doing "right" at the moment.
'''
thumb_small = get_cached_thumbnail(self.image, 'small') if self.image else None
thumb_standard = get_cached_thumbnail(self.image, 'standard') if self.image else None
return {
'name': self.name,
'description': truncatewords(self.description, 15),
'location': {
'address': self.location.address,
'latitude': float(self.location.latitude) if self.location.latitude is not None else None,
'longitude': float(self.location.longitude) if self.location.longitude is not None else None,
'is_gecoded': self.location.latitude is not None and self.location.longitude is not None,
} if self.location else None,
'tags': [{
'name': tag.name,
'permalink': tag.get_absolute_url(),
} for tag in self.tags.all()[:4]],
'hours': [{
'days': listing.days,
'hours': listing.hours
} for listing in self.hours],
'image': self.image.url if self.image else '',
# special fields only for JSON output
'permalink': self.get_absolute_url(),
'thumb_small': thumb_small.url if thumb_small else '',
'thumb_standard': thumb_standard.url if thumb_standard else '',
}
class PlaceRelatedFeeds(object):
def __init__(self, place, user=None):
self.events_feed = [EventData(e, user) for e in Event.objects.filter(place=place)]
self.specials_feed = [SpecialData(s, user) for s in Special.objects.filter(place=place)]
|
UTF-8
|
Python
| false | false | 2,014 |
3,848,290,744,739 |
2cbce889ec8cdb7ffac65cdc841eabaf76852d01
|
6da549d8afe183d1c5fde6dc8cb6bd6f7d4079c9
|
/wpl/blog/views.py
|
0ba13612fb16fd75ca4a03bb076f5bd9fbec8c96
|
[] |
no_license
|
goldhand/django-spa
|
https://github.com/goldhand/django-spa
|
233c8997f42685741b5be17b1f9af8ddb2dba9ae
|
1d39fbecb16f9e5eddbae67bae6f22927b6cbbd0
|
refs/heads/master
| 2023-05-16T04:43:58.218859 | 2013-09-18T08:21:24 | 2013-09-18T08:21:24 | 12,482,748 | 1 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null |
from django.shortcuts import render
from rest_framework.response import Response
from rest_framework.reverse import reverse
from rest_framework.decorators import api_view
from rest_framework import generics, permissions, viewsets
from .models import Post
from .serializers import PostSerializer
from .permissions import IsOwnerOrReadOnly
@api_view(('GET',))
def blog(request, format=None):
return Response({
'posts': reverse('post-list', request=request, format=format)
})
class PostList(generics.ListCreateAPIView):
"""
Class based view using generic views
List all snippets, or create a new snippet.
"""
queryset = Post.objects.all()
serializer_class = PostSerializer
permission_classes = (permissions.IsAuthenticatedOrReadOnly,
IsOwnerOrReadOnly)
def pre_save(self, obj):
obj.owner = self.request.user
class PostDetail(generics.RetrieveUpdateDestroyAPIView):
"""
Class based view using generic views
Retrieve, update or delete a code snippet.
"""
queryset = Post.objects.all()
serializer_class = PostSerializer
def pre_save(self, obj):
obj.owner = self.request.user
class PostViewSet(viewsets.ModelViewSet):
"""
This viewset automatically provides 'list', 'create', 'retrieve',
'update', and 'destroy' actions.
Additionally we also provide an extra 'highlight' action.
"""
queryset = Post.objects.all()
serializer_class = PostSerializer
permission_classes = (permissions.IsAuthenticatedOrReadOnly, IsOwnerOrReadOnly,)
def pre_save(self, obj):
obj.owner = self.request.user
def angular_view(request, templateUrl=None):
if templateUrl:
return render(request, templateUrl)
def angular_view(request):
return render(request, 'blog/angular/index.html')
def angular_view_post_list(request):
return render(request, 'blog/angular/partials/post-list.html')
def angular_view_post_detail(request):
return render(request, 'blog/angular/partials/post-detail.html')
|
UTF-8
|
Python
| false | false | 2,013 |
8,667,244,044,066 |
0e73e46a6b04bec969f6624b596a7025d25c027a
|
6156be4600932e863f38abd61ed2c433ceeb140c
|
/CST-186-14FA(Intro Game Prog)/Nathan Gaffney CHapter 4/N.G.Project2.py
|
4b118b57143f6704d74ac046874a061132c1ad67
|
[] |
no_license
|
Gafficus/Delta-Fall-Semester-2014
|
https://github.com/Gafficus/Delta-Fall-Semester-2014
|
137ebbc0a49e002c7b9fb9944598228168abf18c
|
85cf929b72c02d3f0f2e9f6e4712254c8d353fe2
|
refs/heads/master
| 2021-01-01T15:50:24.734956 | 2014-12-26T01:25:24 | 2014-12-26T01:25:24 | 27,015,869 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null |
#Created by: Nathan Gaffney
#14-Sep-2014
#Chapter 4 Project 2
#THis program will reverse a string
phrase = raw_input("Enter a phrase: ")
strLen = len(phrase)
while strLen > 0:
print phrase[strLen-1]
strLen-=1
|
UTF-8
|
Python
| false | false | 2,014 |
13,537,736,939,003 |
808df90cb94a2faddb39ebe6f5da083cd60228de
|
1694e5db78ed6adf38a407b2d84c49a0723fa934
|
/tutablr_app/__init__.py
|
cf7c287ba247077475c2e59797ef0e04797600c6
|
[] |
no_license
|
bidhanvaidya/Tutablr
|
https://github.com/bidhanvaidya/Tutablr
|
cf88fe89d702661aace4c8ccf5f175c1ed5da0ca
|
07fb26c6487562f690959e2eb0f35e121e12ce0f
|
refs/heads/master
| 2021-01-19T07:39:08.818101 | 2012-10-25T08:15:59 | 2012-10-25T08:15:59 | null | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null |
from tutablr_app.models import Booking, SessionTime
from tutablr_app.views import *
#initialize the locks from the database
bookings = Booking.objects.all()
sessions = SessionTime.objects.all()
for b in bookings:
booking_locks[str(b.id)] = False
for s in sessions:
session_locks[str(s.id)] = False
|
UTF-8
|
Python
| false | false | 2,012 |
16,595,753,651,776 |
92121ccbb1d64fa9bfe016c9d5d93d98bd2f4081
|
ce2504408f5964acf66afbf5cf54df7878190067
|
/intermol/Types/HarmonicBondType.py
|
b9ea56eb2dd64e07853f2631b039ad09ad3c4ee6
|
[
"MIT"
] |
permissive
|
jandom/InterMol
|
https://github.com/jandom/InterMol
|
06e6ece361f9b71812d715b2b3fe3eb9bdd10d06
|
859e0ac3905bddd738a57154e6ccdc52b0f3bb80
|
refs/heads/master
| 2016-12-25T21:47:37.557103 | 2014-03-12T20:35:34 | 2014-03-12T20:35:34 | null | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null |
import sys
sys.path.append('..')
from intermol.Decorators import *
from AbstractBondType import *
class HarmonicBondType(AbstractBondType):
@accepts_compatible_units(None, None, None, units.nanometers, units.kilojoules_per_mole * units.nanometers**(-2))
def __init__(self, atom1, atom2, type, length, k):
AbstractBondType.__init__(self, atom1, atom2, type)
self.length = length
self.k = k
|
UTF-8
|
Python
| false | false | 2,014 |
1,254,130,451,134 |
6c8a67183ec9863f6b57a6d4d1bbcceab2fb1d36
|
db8d159512c92cc55611e5e50bc9ac372e484534
|
/python/009_Special_Pythagorean_triplet.py
|
9f9f20b020fac15bb88be61e281c0a49fa3e3b57
|
[] |
no_license
|
johnalexwelch/Euler
|
https://github.com/johnalexwelch/Euler
|
28225156074a0750bd93f0f0dbb390af29f42433
|
7f3163824aa43ffc7fcfe2d1bffda12d4cf83ab9
|
refs/heads/master
| 2016-09-09T21:11:42.163742 | 2014-02-01T02:10:57 | 2014-02-01T02:10:57 | null | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null |
'''
A Pythagorean triplet is a set of three natural numbers, a < b < c, for which,
a2 + b2 = c2
For example, 3^2 + 4^2 = 9 + 16 = 25 = 5^2.
There exists exactly one Pythagorean triplet for which a + b + c = 1000.
Find the product abc.
'''
import math
'''
If a is odd, then b = a2/2 ? 1/2 and c = b + 1
If a is even, then b = a2/4 ? 1 and c = b + 2
a=2n+1
b=2n(n+1)
c=2n(n+1)+1
'''
import time
def triple():
start = time.time()
for a in range (1,1000):
for b in range(1,1000):
for c in range(1,1000):
if a+b+c ==1000:
if (a**2) + (b**2) == (c**2):
return "%s found in %s seconds" % (a*b*c,time.time() -start)
print triple()
#def triplet(a,n):
# #a = (2.0*n) +1.0
# b = (2.0*n)*(n+1.0)
# c = (2.0*n)*(n+1.0) +1.0
#
# '''
# if 1000 % (a+b+c) ==0
# '''
#
# if a+b+c == 1000:
# return a*b*c
# elif a+b+c > 1000:
# return 'no triplet found -> ' + str(a+b+c) + " -> " + str(n)
# else:
# print "a = " + str(a) + " b = " + str(b) + " c = " + str(c) + " -> " + str(a+b+c)+ " -> " + str(n)
# return triplet(a+1,((a+1)-1)/2)
#
#n = 1
#a = 1
#n=(a-1)/2
#print triplet(a,n)
|
UTF-8
|
Python
| false | false | 2,014 |
1,254,130,499,466 |
32ca57b2366e0aafd668dd1fa22c9e13c80743f0
|
a2d8269099ab1579c63474b87f1e68763272d494
|
/lib/ergo/commands.py
|
378a2ee0c5c9cd89bfd83cdcb3bd374f56a946e9
|
[] |
no_license
|
nlilja/ergo
|
https://github.com/nlilja/ergo
|
abc561664a410c6b9cdc98cf742620cd8185ee8a
|
c9712b45919266a0312afc0dc105aa77ff35539f
|
refs/heads/master
| 2020-03-24T19:36:46.284427 | 2011-11-01T17:42:46 | 2011-11-01T17:42:46 | null | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null |
#!/usr/bin/python
# -*- coding: utf-8 -*-
"""
Commands.
"""
from ergo.core import Command, COMMANDS
from aochat.aoml import *
### CALLBACKS ##################################################################
def help_callback(chat, player, args):
if args and args[0] in COMMANDS:
command = COMMANDS[args[0]]
window = text(
"Help on %s command:%s%s%s%s" % (
command.name, br(2),
command.desc, br(2),
command.help() if command.help else "No help available."
),
command.name
)
return "Help on command: %s" % window
return "Type 'help <command>' for command specified help: %s." % text(help_help(), "available commands")
def help_help():
return "Available commands:%s%s" % (
br(),
br().join(map(lambda name: text(COMMANDS[name].help(), name), filter(lambda name: name != "help", sorted(COMMANDS))))
),
def join_callback(chat, player, args):
chat.private_channel_invite(player.id)
def join_help():
return "Bot will invite you to private channel."
def leave_callback(chat, player, args):
chat.private_channel_kick(player.id)
def leave_help():
return "Bot will kick you from private channel."
def ban_callback(chat, player, args):
pass
def ban_help():
return ""
### COMMANDS ###################################################################
help = Command(
name = "help",
desc = "Usage information",
callback = help_callback,
help = help_help,
)
join = Command(
name = "join",
desc = "Join private channel",
callback = join_callback,
help = join_help,
)
leave = Command(
name = "leave",
desc = "Leave private channel",
callback = leave_callback,
help = leave_help,
)
|
UTF-8
|
Python
| false | false | 2,011 |
13,606,456,425,850 |
f8667a1d8b529b09df0f53e5a062f106bea86465
|
4a71b2c28bef4f145173aeb56c3cdb764dd56ad1
|
/exercise/submission_models.py
|
50c765bb21da79d4cd7fc19a55c7beb753f7ca98
|
[] |
no_license
|
shadikka/a-plus
|
https://github.com/shadikka/a-plus
|
27026dcee36b0d11a0f2825608a9ef4411831f25
|
c9666a73e9c8d23e4d593f2056431997781c9ea2
|
refs/heads/master
| 2019-12-16T10:03:25.868737 | 2013-04-24T17:33:44 | 2013-04-24T17:33:44 | null | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null |
# Django
from django.db import models
from django.utils.translation import ugettext_lazy as _
from django.http import HttpResponseBadRequest, HttpResponse
from django.db.models.signals import post_init, pre_save
from django.core.urlresolvers import reverse
from django.core.files.storage import default_storage
from django.db.models.signals import post_delete
# A+
from exercise import exercise_models
from lib import MultipartPostHandler
from lib.fields import JSONField
from lib.helpers import get_random_string
from userprofile.models import UserProfile
# Python 2.6+
from datetime import datetime, timedelta
import simplejson, os
class Submission(models.Model):
_status_choices = (("initialized", _(u"Initialized")),
("waiting", _(u"Waiting")),
("ready", _(u"Ready")),
("error", _(u"Error")))
submission_time = models.DateTimeField(auto_now_add=True)
hash = models.CharField(max_length=32, default=get_random_string)
# Relations
exercise = models.ForeignKey(exercise_models.BaseExercise,
related_name="submissions")
submitters = models.ManyToManyField(UserProfile,
related_name="submissions")
grader = models.ForeignKey(UserProfile,
related_name="graded_submissions",
blank=True,
null=True)
# Grading specific
feedback = models.TextField(blank=True)
status = models.CharField(max_length=32,
default=_status_choices[0][0],
choices=_status_choices)
grade = models.IntegerField(default=0)
grading_time = models.DateTimeField(blank=True, null=True)
# Points received from assessment, before scaled to grade
service_points = models.IntegerField(default=0)
service_max_points = models.IntegerField(default=0)
# Additional submission and grading data
submission_data = JSONField(blank=True)
grading_data = JSONField(blank=True)
def add_submitter(self, user_profile):
"""
Adds a new student to the submitters of this exercise.
@param user_profiles: a UserProfile that is submitting the exercise
"""
self.submitters.add(user_profile)
def add_submitters(self, user_profiles):
"""
Adds students for this submission.
@param user_profiles: an iterable with UserProfile objects
"""
for u_p in user_profiles:
self.add_submitter(u_p)
def add_files(self, files):
"""
Adds the given files to this submission as SubmittedFile objects.
@param files: a QueryDict containing files from a POST request
"""
for key in files:
for uploaded_file in files.getlist(key):
userfile = SubmittedFile()
userfile.file_object = uploaded_file
userfile.param_name = key
# Add the SubmittedFile to the submission
self.files.add(userfile)
def check_user_permission(self, profile):
"""
Checks if the given user is allowed to access this submission.
Superusers and staff are allowed to access all submissions, course
personnel is allowed to access submissions for that course and students
are allowed to access their own submissions.
@param profile: UserProfile model
"""
# Superusers and staff are allowed to view all submissions
if profile.user.is_superuser or profile.user.is_staff:
return True
# Check if the user has submitted this submission him/herself
if profile in self.submitters.all():
return True
# Check if the user belongs to the course staff
if self.get_course_instance().is_staff(profile):
return True
return False
def get_course(self):
return self.get_course_instance().course
def get_course_instance(self):
return self.exercise.course_module.course_instance
def set_points(self, points, max_points, no_penalties=False):
"""
Sets the points and maximum points for this submissions. If the given
maximum points are different than the ones for the exercise this
submission is for, the points will be scaled.
The method also checks if the submission is late and if it is, by
default applies the late_submission_penalty set for the
exercise.course_module. If no_penalties is True, the penalty is not
applied.
@param points: the amount of points received from assessment
@param max_points: the total amount of points available in assessment
@param no_penalties: If True, the possible late_submission_penalty is
not applied.
"""
# The given points must be between zero and max points
assert 0 <= points <= max_points
# If service max points is zero, then exercise max points must be zero
# too because otherwise adjusted_grade would be ambiguous.
assert not (max_points == 0 and self.exercise.max_points != 0)
self.service_points = points
self.service_max_points = max_points
# Scale the given points to the maximum points for the exercise
if max_points > 0:
adjusted_grade = (1.0 * self.exercise.max_points
* points / max_points)
else:
adjusted_grade = 0.0
# Check if this submission was done late. If it was, reduce the points
# with late submission penalty. No less than 0 points are given. This
# is not done if no_penalties is True.
if not no_penalties and self.is_submitted_late():
adjusted_grade -= (adjusted_grade
* self.exercise.get_late_submission_penalty())
self.grade = round(adjusted_grade)
# Finally check that the grade is in bounds after all the hardcore
# math!
assert 0 <= self.grade <= self.exercise.max_points
def is_submitted_late(self):
if not self.id and not self.submission_time:
# The submission is not saved and the submission_time field is not
# set yet so this method takes the liberty to set it.
self.submission_time = datetime.now()
return not self.exercise.is_open_for(students=self.submitters.all(),
when=self.submission_time)
def set_grading_data(self, grading_dict):
self.grading_data = grading_dict
def submitter_string(self):
# TODO: Write a version of this method that has the names wrapped in
# html anchors pointing to the profile page of the user.
"""
Returns a comma separated string containing full names and possibly the
student ids of all the submitters of this submission.
"""
submitter_strs = []
for profile in self.submitters.all():
if profile.student_id:
student_id_str = " (%s)" % profile.student_id
else:
student_id_str = ""
submitter_strs.append(profile.user.get_full_name()
+ student_id_str)
return ", ".join(submitter_strs)
def __unicode__(self):
return str(self.id)
# Status methods. The status indicates whether this submission is just
# created, waiting for grading, ready or erroneous.
def _set_status(self, new_status):
self.status = new_status
def set_waiting(self):
self._set_status("waiting")
def is_graded(self):
return self.status == "ready"
def set_ready(self):
self.grading_time = datetime.now()
self._set_status("ready")
def set_error(self):
self._set_status("error")
def get_absolute_url(self):
return reverse("exercise.views.view_submission", kwargs={"submission_id": self.id})
def get_callback_url(self):
identifier = "s.%d.%d.%s" % (self.id, self.exercise.id, self.hash)
return reverse("exercise.async_views.grade_async_submission",
kwargs={"submission_id": self.id,
"hash": self.hash})
def get_staff_url(self):
return reverse("exercise.staff_views.inspect_exercise_submission",
kwargs={"submission_id": self.id})
def submit_to_service(self, files=None):
# Get the exercise as an instance of its real leaf class
exercise = self.exercise.as_leaf_class()
return exercise.submit(self)
def get_breadcrumb(self):
"""
Returns a list of tuples containing the names and url
addresses of parent objects and self.
"""
crumb = self.exercise.get_breadcrumb()
crumb_tuple = (_("Submission"), self.get_absolute_url())
crumb.append(crumb_tuple)
return crumb
class Meta:
app_label = 'exercise'
ordering = ['-submission_time']
def build_upload_dir(instance, filename):
"""
Returns the path to a directory where the file should be saved.
This is called every time a new SubmittedFile model is created.
The file paths include IDs for the course instance, the exercise,
the users who submitted the file and the submission the file belongs to.
@param instance: the new SubmittedFile object
@param filename: the actual name of the submitted file
@return: a path where the file should be stored, relative to MEDIA_ROOT directory
"""
exercise = instance.submission.exercise
course_instance = exercise.course_module.course_instance
# Collect submitter ids in a list of strings
submitter_ids = [str(profile.id) for profile in instance.submission.submitters.all()]
return "submissions/course_instance_%d/exercise_%d/users_%s/submission_%d/%s" % \
(course_instance.id,
exercise.id,
"-".join(submitter_ids), # Join submitter ids using dash as a separator
instance.submission.id,
filename)
class SubmittedFile(models.Model):
"""
Submitted file represents a file submitted by the student as a solution
to an exercise. Submitted files are always linked to a certain submission
through a foreign key relation. The files are stored on the disk while
SubmittedFile models are stored in the database.
"""
submission = models.ForeignKey(Submission, related_name="files")
param_name = models.CharField(max_length=128)
file_object = models.FileField(upload_to=build_upload_dir)
def _get_filename(self):
""" Returns the actual name of the file on the disk. """
return os.path.basename(self.file_object.path)
# filename property is used to hide the logic in _get_filename
filename = property(_get_filename)
def get_absolute_url(self):
"""
Returns the url for downloading this file. The url contains both the id of this model and the
name of the file on the disk. Only the file id is used in the URL pattern and the view that returns
the file.
"""
view_url = reverse('exercise.views.view_submitted_file', kwargs={"submitted_file_id": self.id})
return view_url + self.filename
class Meta:
app_label = 'exercise'
def _delete_file(sender, instance, **kwargs):
"""
This function deletes the actual files referenced by SubmittedFile
objects after the objects are deleted from database.
"""
default_storage.delete(instance.file_object.path)
# Connect signal to deleting a SubmittedFile
post_delete.connect(_delete_file, SubmittedFile)
|
UTF-8
|
Python
| false | false | 2,013 |
2,997,887,193,632 |
76b2573487b0c7a90ea81fb86717081f50d89803
|
01b3ecbd4579c3b5c5557fbe4c524982c81f4709
|
/tests/bots/oldman/oldman.py
|
4ddbd8a84540b8f89f1aa03ff701843860a1edda
|
[] |
no_license
|
ZhanruiLiang/kothlib
|
https://github.com/ZhanruiLiang/kothlib
|
bd74b52f2984924bdaebac0f278aeddde6b25aad
|
7d59448dbf1b5dde84e0df6c735d5d744df5d20e
|
refs/heads/master
| 2021-01-13T02:03:03.138552 | 2014-08-08T17:16:12 | 2014-08-08T17:16:12 | null | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null |
from time import sleep
while True:
sleep(3)
print('rock')
|
UTF-8
|
Python
| false | false | 2,014 |
8,993,661,533,605 |
483e219864292d4e75cb36c0e55c8a7f37263073
|
58034a8b190655c6a6d65a10b66c9ecd8e26cd08
|
/python/wxpythontest/testMouseEvent.py
|
157e3542b8d46b116f4423d4105e08c64f95f8b9
|
[] |
no_license
|
xiaoxin628/WillScript
|
https://github.com/xiaoxin628/WillScript
|
559e3ca3d1315ac8cd235e30997ff78f9ac78f90
|
90c005113b2217cdbbe2156881b281b1c0164c2b
|
refs/heads/master
| 2019-01-02T03:47:05.000258 | 2013-07-11T14:51:38 | 2013-07-11T14:51:38 | null | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null |
#!/usr/bin/env python
# -*- coding: UTF-8 -*-
#Filename : toolbarFrame.py
#Author : Will
#Email : lishuzu@gmail.com
import wx
class TwoButtonEvent(wx.PyCommandEvent):
def __init__(self, evtType, id):
wx.PyCommandEvent.__init__(self,evtType,id)
self.clickCount = 0
def GetClickCount(self):
return self.clickCount
def SetClickCount(self, count):
self.clickCount = count
myEVT_TWO_BUTTON = wx.NewEventType()
EVT_TWO_BUTTON = wx.PyEventBinder(myEVT_TWO_BUTTON, 1)
class TwoButtonPanel(wx.Panel):
def __init__(self, parent, id=-1, leftText="Left", rightText="Right"):
wx.Panel.__init__(self,parent,id)
self.leftButton = wx.Button(self, label=leftText)
self.rightButton = wx.Button(self, label=rightText, pos=(100,0))
self.leftClick = False
self.rightClick = False
self.clickCount = 0
self.leftButton.Bind(wx.EVT_LEFT_DOWN,self.OnLeftClick)
self.rightButton.Bind(wx.EVT_LEFT_DOWN,self.OnRightClick)
def OnLeftClick(self,event):
self.leftClick = True
self.OnClick()
event.Skip()
def OnRightClick(self,event):
self.rightClick = True
self.OnClick()
event.Skip()
def OnClick(self):
self.clickCount += 1
if self.leftClick and self.rightClick:
self.leftClick = False
self.rightClick = False
evt = TwobuttonEvent(myEVT_TWO_BUTTON, self.GetId())
evt.SetClickCount(self.clickCount)
self.GetEventHandler().ProcessEvent(evt)
class CustomEventFrame(wx.Frame):
"""docstring for CustomEventFrame"""
def __init__(self, parent,id):
wx.Frame.__init__(self,parent,id,'Click Count:0', size=(300,100))
panel = TwoButtonPanel(self)
self.Bind(EVT_TWO_BUTTON, self.OnTwoClick, panel)
def OnTwoClick(self, event):
self.SetTitle('Click Count:%s' % event.GetClickCount())
if __name__=='__main__':
app = wx.PySimpleApp()
frame = CustomEventFrame(parent = None, id =1)
frame.Show()
app.MainLoop()
|
UTF-8
|
Python
| false | false | 2,013 |
11,982,958,792,232 |
9588a22798ad98188e484e1605cf5f32a9195226
|
b39d9ef9175077ac6f03b66d97b073d85b6bc4d0
|
/Sequidot_transdermal_patch_SmPC.py
|
faa47c5b63eb4f51e470519cd2e98a1ae3899e44
|
[] |
no_license
|
urudaro/data-ue
|
https://github.com/urudaro/data-ue
|
2d840fdce8ba7e759b5551cb3ee277d046464fe0
|
176c57533b66754ee05a96a7429c3e610188e4aa
|
refs/heads/master
| 2021-01-22T12:02:16.931087 | 2013-07-16T14:05:41 | 2013-07-16T14:05:41 | null | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null |
{'_data': [['Very common',
[['Nervous system', u'Huvudv\xe4rk'],
['Skin', u'Reaktioner p\xe5 applikations -st\xe4llet, erytem'],
['Reproductive system',
<<<<<<< HEAD
u'Br\xf6st-sp\xe4nn ing och v\xe4rk, dysmenorr\xe9, menstrua-tio ns-rubbning'],
['General', u'vid ']]],
['Common',
[['Psychiatric', u'Depression, nervositet, affektlabilitet'],
['Nervous system', u'S\xf6mnsv\xe5rig-het'],
['GI', u'Illam\xe5ende, diarr\xe9, dyspepsi, buksm\xe4rta, flatulens'],
['Skin', u'Akne, utslag, pruritus, torr hud'],
['Reproductive system',
u'Br\xf6stf\xf6rstoring, menorragi, vaginal flytning oregelbunden vaginal bl\xf6dning, uterinspasm, vaginal infektion, endometrie-hyp erplasi'],
=======
u'Br\xf6st-sp\xe4nning och v\xe4rk, menstrua-tions-rubbning'],
['General', u'vid ']]],
['Common',
[['Psychiatric', u'Depression, nervositet, affektlabilitet'],
['Nervous system', u'S\xf6mnsv\xe5rig-heter'],
['GI', u'Illam\xe5ende, diarr\xe9, dyspepsi, buksm\xe4rta, flatulens'],
['Skin', u'Akne, utslag, pruritus, torr hud'],
['Reproductive system',
u'Br\xf6stf\xf6rstoring, menorragi, vaginal oregelbunden vaginal bl\xf6dning, uterinspasm, vaginal infektion, endometrie-hyperplasi'],
>>>>>>> eb0dbf7cfbd3e1c8a568eedcf6ca5658233104cc
['General', u'V\xe4rk, ryggv\xe4rk, asteni, perifert \xf6dem, vikt\xf6kning']]],
['Uncommon',
[['Nervous system', u'Migr\xe4n, yrsel'],
['Vascular', u'F\xf6rh\xf6jt blodtryck'],
['GI', u'Kr\xe4kning'],
['Skin', u'Missf\xe4rg-ning av huden'],
<<<<<<< HEAD
['Investigations', u'Transaminas\xf6 kning']]],
['Rare',
[['Immune system', u'\xd6verk\xe4nslighet'],
['Psychiatric', u'Libidof\xf6r\xe4ndrin'],
['Nervous system', u'Parestesi'],
['Vascular', u'Ven\xf6s emboli'],
['Hepato', u'Gallbl\xe5sesjukd om, kolelitiasis'],
=======
['Investigations', u'Transaminas-\xf6kning']]],
['Rare',
[['Immune system', u'\xd6verk\xe4nslighet'],
['Psychiatric', u'Libido-f\xf6r\xe4ndringar,'],
['Nervous system', u'Parestesi'],
['Vascular', u'Ven\xf6s emboli'],
['Hepato', u'Gallbl\xe5se-sjukdom, kolelitiasis'],
>>>>>>> eb0dbf7cfbd3e1c8a568eedcf6ca5658233104cc
['Skin', u'Alopeci'],
['Musculoskeletal', u'Myasteni'],
['Reproductive system', u'Myom, cystor p\xe5 \xe4ggledare, cervixpolyper']]],
['Very rare',
[['Metabolism', u'Nedsatt kolhydrat-tolerans'],
['Nervous system', u'Korea'],
<<<<<<< HEAD
['Eye', u'\xd6verk\xe4nslig-h et f\xf6r kontaktlinser'],
['Hepato', u'Kolestatisk gulsot'],
['Skin', u'Hirsutism, hudnekros']]],
['Unknown', [['Musculoskeletal', u'Extremitetss * m\xe4rta']]]],
=======
['Eye', u'\xd6verk\xe4nslig-het f\xf6r kontaktlinser'],
['Hepato', u'Kolestatisk gulsot'],
['Skin', u'Hirsutism, hudnekros']]],
['Unknown', [['Musculoskeletal', u'Extremitets-* sm\xe4rta']]]],
>>>>>>> eb0dbf7cfbd3e1c8a568eedcf6ca5658233104cc
'_note': u' ?MSFU',
'_pages': [7, 10],
u'_rank': 29,
u'_type': u'MSFU'}
|
UTF-8
|
Python
| false | false | 2,013 |
8,555,574,876,876 |
a0e7eb5a2217b2248e90b9de8b340d600d279a99
|
337250ba29fc65e7652fb1a22d653770a3421e52
|
/appengine-web/src/goldenweb.py
|
c527ec3e5199b67dcc2d4925f21e566435c7f37b
|
[
"MIT",
"LicenseRef-scancode-unknown-license-reference"
] |
non_permissive
|
ollej/GoldQuest
|
https://github.com/ollej/GoldQuest
|
4dc2e527debc76558f9032bac2f88abb5d8f5f6e
|
b9913815bd1d1f304c34c3a3cc643b64310e66c6
|
refs/heads/master
| 2021-01-22T21:32:27.876981 | 2012-12-19T08:35:06 | 2012-12-19T08:35:06 | 1,999,071 | 1 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
"""
The MIT License
Copyright (c) 2011 Olle Johansson
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.
"""
import setup_django_version
import os
import logging
import simplejson
import Py2XML
import httpheader
from httpheader import ParseError
from django.conf import settings
from google.appengine.ext import webapp
from google.appengine.ext.webapp import template
from django.template import TemplateDoesNotExist
from decorators import *
DEBUG = os.environ['SERVER_SOFTWARE'].startswith('Development')
class PageHandler(webapp.RequestHandler):
"""
Default page handler, supporting html templates, layouts, output formats etc.
"""
_basepath = os.path.dirname(__file__)
@LogUsageCPU
def get_template(self, page, values, layout='default', basepath=None):
"""
TODO: use django template include.
"""
page = "%s.html" % page
path = ''
if not values:
values = {}
if basepath:
path = os.path.join(basepath, 'views', page)
if not basepath or not os.path.exists(path):
path = os.path.join(self._basepath, 'views', page)
if layout:
layout = os.path.join('layouts', '%s.html' % layout)
values['layout'] = layout
logging.info('template pathname: %s layout: %s', path, layout)
template_file = open(path)
# TODO: cache compiled template
compiled_template = template.Template(template_file.read())
template_file.close()
content = compiled_template.render(template.Context(values))
return content
def parse_pagename(self, page):
(pagename, ext) = os.path.splitext(page)
logging.debug("page: %s pagename: %s ext: %s" % (page, pagename, ext))
# TODO: filter unwanted characters
return (pagename, ext)
@LogUsageCPU
def show_page(self, page, template_values=None, layout='default', default_format=None, basepath=None):
"""
Select output format based on Accept headers.
"""
#logging.debug(template_values)
accept = None
acceptparams = None
try:
accept = self.request.headers['Accept']
except KeyError, ke:
logging.debug('Request contained no Accept header.')
logging.debug('Accept content-type: %s' % accept)
#(mime, parms, qval, accept_parms) = httpheader.parse_accept_header(accept)
try:
if accept:
acceptparams = httpheader.parse_accept_header(accept)
except ParseError, e:
logging.error('Error parsing HTTP Accept header: %s', e)
logging.debug(acceptparams)
#logging.debug('mime: %s, parms: %s, qval: %s, accept_parms: %s' % (mime, parms, qval, accept_parms))
format = self.request.get("format")
if not format and default_format:
format = default_format
logging.debug('selected format: %s' % format)
if format == 'html' or ((not acceptparams or not accept or accept == '*/*' or httpheader.acceptable_content_type(accept, 'text/html')) and not format):
self.output_html(page, template_values=template_values, layout=layout, basepath=basepath)
elif format == 'json' or httpheader.acceptable_content_type(accept, 'application/json'):
self.output_json(template_values)
elif format == 'xml' or (httpheader.acceptable_content_type(accept, 'application/xml') and not format):
self.output_xml(template_values)
elif format == 'text' or httpheader.acceptable_content_type(accept, 'text/plain'):
#elif httpheader.acceptable_content_type(accept, 'text/plain'):
if isinstance(template_values, basestring):
self.output_text(template_values)
else:
try:
self.output_text(template_values['message'])
except KeyError, e:
self.output_text(str(template_values))
else:
logging.debug('Defaulting output to html.')
self.output_html(page, template_values, layout=layout, basepath=basepath)
@LogUsageCPU
def output_json(self, template_values=None):
self.response.headers.add_header('Content-Type', 'application/json', charset='utf-8')
jsondata = simplejson.dumps(template_values)
self.response.out.write(jsondata)
@LogUsageCPU
def output_xml(self, template_values=None):
self.response.headers.add_header('Content-Type', 'application/xml', charset='utf-8')
serializer = Py2XML.Py2XML()
values = { 'response': template_values }
xmldata = serializer.parse(values)
self.response.out.write(xmldata)
@LogUsageCPU
def output_text(self, content):
self.response.headers.add_header('Content-Type', 'text/plain', charset='utf-8')
self.response.out.write(content)
@LogUsageCPU
def output_html(self, page, template_values=None, layout='default', basepath=None):
try:
content = self.get_template(page, template_values, layout, basepath=basepath)
self.response.out.write(content)
except TemplateDoesNotExist:
self.response.set_status(404)
@LogUsageCPU
def get_page(self, page):
template_values = {}
(pagename, ext) = self.parse_pagename(page)
if not pagename or pagename == 'index':
self.show_page('index')
else:
func_name = 'page_%s' % pagename
logging.debug('loading page: %s' % func_name)
try:
func = getattr(self, func_name)
except AttributeError:
self.show_page(pagename, None, 'default')
else:
func()
|
UTF-8
|
Python
| false | false | 2,012 |
7,808,250,563,971 |
6234d881377b6a0b6d9c85ea02c9f26e985b3cdf
|
f0601100b39b0a9c556f76ed82f4f62d939dfd7a
|
/polls/api.py
|
02ee604bafcbcb691fae038a9e5a6b79e4e7249c
|
[] |
no_license
|
herrmendez/poll-app-backbone
|
https://github.com/herrmendez/poll-app-backbone
|
4a400b67e85e431004271a87c1460786a61f6cba
|
523d222282d6261fde1dc83a41ad84fdd77608df
|
refs/heads/master
| 2021-01-15T13:01:49.808983 | 2013-02-08T21:35:58 | 2013-02-08T21:35:58 | 7,963,476 | 1 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null |
#from tastypie.authorization import Authorization
from tastypie import fields
from tastypie.resources import ModelResource
from tastypie.authentication import ApiKeyAuthentication
from tastypie.authorization import DjangoAuthorization, Authorization
from polls.models import Poll, Choice
import pdb
class PollResource(ModelResource):
#choices = fields.ToManyField('polls.api.ChoiceResource', 'choice_set', full=True)
def __init__(self, api_name=None):
super(PollResource, self).__init__(api_name=None)
class Meta:
queryset = Poll.objects.all()
resource_name = 'poll'
allowed_methods = ['get', 'post', 'put', 'delete']
trailing_slash = False
authentication = ApiKeyAuthentication()
authorization = DjangoAuthorization()
class ChoiceResource(ModelResource):
poll = fields.ForeignKey(PollResource, 'poll')
class Meta:
queryset = Choice.objects.all()
resource_name = 'choice'
allowed_methods = ['get', 'post', 'put', 'delete']
from django.db import models
from django.contrib.auth.models import User
from tastypie.models import create_api_key
models.signals.post_save.connect(create_api_key, sender=User)
|
UTF-8
|
Python
| false | false | 2,013 |
9,783,935,544,692 |
542ee14264dc7be165fdd4a390134619ee850568
|
e867517068ade1572691ac86c6f2ad6596c0d559
|
/film20/recommendations/urls.py
|
bf1d27b2d25dfb4479cd22de1405ff1bd81a92c8
|
[] |
no_license
|
manlan2/filmaster
|
https://github.com/manlan2/filmaster
|
044ec124d91da0b6dcf2eb5b8af5aec6f0fffd53
|
90b2bb72c2bab9dfea0c0837971a625bc6880630
|
refs/heads/master
| 2021-05-26T22:24:55.012908 | 2012-05-27T09:30:37 | 2012-05-27T09:30:37 | 107,661,541 | 1 | 0 | null | true | 2017-10-20T09:51:53 | 2017-10-20T09:51:53 | 2017-10-20T09:51:53 | 2012-05-27T09:38:13 | 9,548 | 0 | 0 | 0 | null | null | null |
#-------------------------------------------------------------------------------
# Filmaster - a social web network and recommendation engine
# Copyright (c) 2009 Filmaster (Borys Musielak, Adam Zielinski).
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU Affero General Public License as
# published by the Free Software Foundation, either version 3 of the
# License, or (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU Affero General Public License for more details.
#
# You should have received a copy of the GNU Affero General Public License
# along with this program. If not, see <http://www.gnu.org/licenses/>.
#-------------------------------------------------------------------------------
from django.conf.urls.defaults import *
from django.contrib.auth.decorators import login_required
from film20.config.urls import *
from film20.recommendations.views import *
ranking_view = RankingListView.as_view()
recommendations_view = RecommendationsListView.as_view()
genre = r"/(?P<genre>.+)/$"
recompatterns = patterns('',
### RANKING ###
url(r'^%(RANKING)s/$' % urls, ranking_view, name='rankings'),
url(r"^%(RANKING)s/(?P<type_as_str>['\w\-_]+)/$" % urls, ranking_view, name='rankings'),
url(r'^%(RANKING)s/%(GENRE)s' % urls + genre, ranking_view, name='rankings_menu'),
url(r'^%(TV_SERIES_RANKING)s/$' % urls, ranking_view, {'tv_series': True}, name='series_rankings'),
url(r"^%(TV_SERIES_RANKING)s/(?P<type_as_str>['\w\-_]+)/$" % urls, ranking_view, {'tv_series': True}, name='series_rankings'),
url(r'^%(TV_SERIES_RANKING)s/%(GENRE)s' % urls + genre, ranking_view, {'tv_series': True}, name='series_rankings_menu'),
url(r'^'+urls['MOVIES']+'/$', MoviesMainListView.as_view(), name='movies'),
url(r'^'+urls['MOVIES']+'/'+urls['GENRE']+ genre, MoviesGenreListView.as_view(), name='movies_menu'),
url(r'^'+urls['REVIEWS']+'/$', ReviewsListView.as_view(), name='reviews'),
url(r'^'+urls['REVIEWS']+'/(?P<notes_type>[\w\-_]+)/$', login_required(ReviewsListView.as_view()), name='reviews'),
url(r'^'+urls['REVIEWS']+'/'+urls['GENRE']+ genre, ReviewsListView.as_view(), name='reviews_menu'),
url(r'^'+urls["RECOMMENDATIONS"]+'/$', recommendations_view, name='my_recommendations'),
url(r'^'+urls["RECOMMENDATIONS"] + "/" + urls["GENRE"] + genre, recommendations_view, name='recommendations_menu'),
# These are old views, not (yet) implemented in filmaster-reloaded
### TOP USERS ###
# (r'^'+urls["TOP_USERS"]+'/$', top_users),
# (r'^'+urls["TOP_USERS"]+'/(?P<page_id>\d{1,3})/$', top_users),
### TAG PAGE ###
url(r'^'+urls['SHOW_TAG_PAGE']+ genre, MoviesGenreListView.as_view(), name='show_tag_page'),
### FILMS FOR TAG ###
# (r'^'+urls['SHOW_TAG_PAGE']+'/(?P<tag>[\w\-_ ]+)/'+urls['FILMS_FOR_TAG']+'/$', show_films_for_tag),
# (r'^'+urls['SHOW_TAG_PAGE']+'/(?P<tag>[\w\-_ ]+)/'+urls['FILMS_FOR_TAG']+'/(?P<page_id>\d{1,3})/$', show_films_for_tag),
)
|
UTF-8
|
Python
| false | false | 2,012 |
19,215,683,686,462 |
9cc6a6a109c6ce6b98bbf2f945d5e3dc6b0b3f0f
|
f68a9cd8b64f94f9011ed535826a9dd3baa71bef
|
/src/main/java/edu/emory/clir/realqa/web/realqawebapp/realqa/tests.py
|
f070c1727216b6548bc46e5724554395b9b8024f
|
[] |
no_license
|
clir/realqa-web
|
https://github.com/clir/realqa-web
|
a969502c49a9b8d9d20b712afaf51a465806108e
|
f409138585d6b0ae6f2ce705bc4ebeae5c7c0d51
|
refs/heads/master
| 2021-01-01T05:11:03.803173 | 2014-12-09T20:58:09 | 2014-12-09T20:58:09 | 24,179,851 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null |
#import datetime
#from django.utils import timezone
import os
from realqawebapp import settings
from django.test import TestCase
from django.test import Client
from realqa.models import Question
from realqa import views
from django.test.client import RequestFactory #allows use of dummy requests
from django.http import HttpResponseRedirect
from django.db import models
#------------------------------------------------------- ----------------------------------------#
List1 = ['django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles',
'realqa',]
traverseUnit = 0
List2 = (
'django.contrib.sessions.middleware.SessionMiddleware',
'django.middleware.common.CommonMiddleware',
'django.middleware.csrf.CsrfViewMiddleware',
'django.contrib.auth.middleware.AuthenticationMiddleware',
'django.contrib.messages.middleware.MessageMiddleware',
'django.middleware.clickjacking.XFrameOptionsMiddleware',
)
traverseUnit2 = 0
class Client_Test(TestCase):
#---------------------------------------------------------------------------------------------------#
def test_checksizeOfApps(self):
self.assertNotEqual(len(settings.INSTALLED_APPS),0)
#----------------------------------------------------------------------------------------------------#
def test_tupleObjectsMatchMIDDLEWARE(self):
for each in range(0, len(List2)):
foundMatch = False
traverseUnit = 0
for i in range(0, len(settings.MIDDLEWARE_CLASSES)):
if List2[each] == settings.MIDDLEWARE_CLASSES[traverseUnit]:
foundMatch = True
traverseUnit += 1
self.assertEqual(foundMatch, True) #fails, cannot find why
#-------------------------------------------------------------------------------------------------------#
def test_tupleObjectsMatchINSTALLED_APPS(self):
for each in range(0, len(List1)):
foundMatch = False
traverseUnit = 0
for i in range(0, len(settings.INSTALLED_APPS)):
if List1[each] == settings.INSTALLED_APPS[traverseUnit]:
foundMatch = True
traverseUnit += 1
self.assertEqual(foundMatch, True)
#--------------------------------------------------------------------------------------------------------#
def test_WelcomeToQA(self):
response = self.client.get('/realqa/')
self.assertEqual(response.status_code, 200)
self.assertIn('Dashboard', response.content.decode('utf-8')) #fails, needs solution
#----------------------------------------------------------------------------------------------------------#
def test_loginPage(self):
response = self.client.get('/realqa/login')
self.assertEqual(response.status_code, 200)
self.assertIn('Welcome to QA!', response.content.decode('utf-8'))
#----------------------------------------------------------------------------------------------------------#
def test_inboxPage(self):
response = self.client.get('/realqa/inbox')
self.assertEqual(response.status_code, 200)
self.assertIn('Inbox', response.content.decode('utf-8'))
#----------------------------------------------------------------------------------------------------------#
#----------------------------------------------------------------------------------------------------------#
def test_profilePage(self):
response = self.client.get('/realqa/profile')
self.assertEqual(response.status_code, 200)
self.assertIn('Your Questions and Answers', response.content.decode('utf-8'))
#----------------------------------------------------------------------------------------------------------#
def test_yourQuestionsPage(self):
response = self.client.get('/realqa/5')
self.assertEqual(response.status_code, 200)
self.assertIn('Your Questions', response.content.decode('utf-8')) #fails because 'Dashboard' is set to everything
#----------------------------------------------------------------------------------------------------------#
def test_yourSubscribedQsPage(self):
response = self.client.get('/realqa/6')
self.assertEqual(response.status_code, 200)
self.assertIn('Your Subscribed Questions', response.content.decode('utf-8')) #fails because 'Dashboard' is set to everything
#----------------------------------------------------------------------------------------------------------#
def test_yourAnsweredQsPage(self):
response = self.client.get('/realqa/7')
self.assertEqual(response.status_code, 200)
self.assertIn('Questions You Answered', response.content.decode('utf-8')) #fails because 'Dashboard' is set to everything
#----------------------------------------------------------------------------------------------------------#
def test_login(self): #not sure if this is the exact way to make tests of this kind. results can be either pass or fail
#response = self.client.get('/realqa/login')
self.factory = RequestFactory() #dummy request according to tutorial
request1 = self.factory.get('/realqa/login')
response = HttpResponseRedirect('/realqa/')
self.assertEquals(views.login(request1), response)
#'WSGI Request' object has no attribute 'session'
#----------------------------------------------------------------------------------------------------------#
def test_post(self):
self.factory = RequestFactory() #dummy request according to tutorial
request2 = self.factory.get('/realqa/')
response = HttpResponseRedirect('/realqa/')
self.assertEquals(views.askQuestion(request2), response)
#response = self.client.post('/realqa/', {''})
#received = json.loads(response.content.decode('utf-8'))
#self.assertIn('a', received)
#doesnt post if there is no '#' need to find a way to include this in testing
#----------------------------------------------------------------------------------------------------------#
def test_register(self): #test is not correct
self.factory = RequestFactory() #dummy request according to tutorial
request1 = self.factory.get('/realqa/')
request1.post['username'] = 'JohnDoe1'
request1.post['password'] = 'JohnDoe2'
#register_data = { #not going to work
# 'username': 'JohnDoe1',
# 'password': 'JohnDoe2',
# }
response = HttpResponseRedirect('/realqa/login')
self.assertEquals(views.register(request1), response) #not working
#----------------------------------------------------------------------------------------------------------#
#----------------------------------------------------------------------------------------------------------#
#----------------------------------------------------------------------------------------------------------#
|
UTF-8
|
Python
| false | false | 2,014 |
16,595,753,633,770 |
ed81601b77edae3ee8781415fb30f74be8d1ef91
|
8f88689dbfb15642306ecccaa439ed21dff4517c
|
/tools/gen_tree_site.py
|
21392b4bfc055af1da43df28fb1a8d114196be0f
|
[
"GPL-3.0-or-later"
] |
non_permissive
|
matm/collorg
|
https://github.com/matm/collorg
|
d03590879f2af1963dc92b81ea9530211cfb6c76
|
6c08b1122b59a20c16679aa377846ceb388206c5
|
refs/heads/master
| 2020-12-02T16:31:31.813675 | 2014-04-07T13:00:54 | 2014-04-07T13:00:54 | null | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null |
#!/usr/bin/env python
#-*- coding: utf-8 -*-
import sys
import os
if __name__ == '__main__':
lines = open(sys.argv[1]).readlines()
l_path = []
for line in lines:
l_items = line.rstrip().split('\t')
item = l_items[-1]
depth = len(l_items)
while len(l_path) >= len(l_items) and len(l_path):
l_path.pop()
l_path.append(item)
path = "collorg/_cog_web_site/__src/%s"%(
"/".join(l_path)).replace(" ", "_").lower()
file_name = "%s/=%s=" % (path, item.capitalize())
os.makedirs(path)
open(file_name,"w").write(item)
|
UTF-8
|
Python
| false | false | 2,014 |
15,805,479,656,639 |
9e2c315dfe91ca44e5c5f5b270e7fbc343f5e29d
|
c78025e319eec372898c851c0f95715757c14cc5
|
/rgba2png.py
|
edbcc7c93370e3b7bb8088bcea021fa953692998
|
[] |
no_license
|
DamienCassou/proteus
|
https://github.com/DamienCassou/proteus
|
017df3acad26fe881716a8c4d4cb8aa8fdc78530
|
dac9866918dd74c931e503396b6e3e93a5cd70cc
|
refs/heads/master
| 2021-01-19T21:28:35.219362 | 2011-06-16T12:28:24 | 2011-06-16T12:28:24 | 1,831,141 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null |
#!/usr/bin/env python
import sys
import png
import math
import numpy
import struct
def rgba8_png(raw_file):
fd = open(raw_file, 'rb')
buff = fd.read()
fd.close()
# buff: bytes(VideoTexture.ImageRender.image) (cf. Blender 2.5 API & MORSE )
image_size = int(math.sqrt(len(buff) / 4))
image2d = numpy.reshape([struct.unpack('B', b)[0] for b in buff], (-1, image_size * 4))
png_writer = png.Writer(width = image_size, height = image_size, alpha = True)
out_png = open(raw_file + '.png', 'wb')
png_writer.write(out_png, image2d)
out_png.close()
#("mencoder", "mf://*.png", "-mf", "fps="+fps+":type=png", "-sws", "6", "-o", videoname, "-ovc", "x264", "-x264encopts", "bitrate="+x264bitrate)
def main(args):
for f in args[1:]:
rgba8_png(f)
help()
def help():
print('Convert RAW RGBA8 bytes to PNG image')
print('usage: '+sys.argv[0]+' file1 [file2 [file3 [...]]]')
print('TIPS: use MEncoder to build a video:')
print('mencoder mf://*.png -mf fps=2:type=png -sws 6 -o rgba8.avi -ovc x264')
print('mencoder mf:///tmp/morse_camera*.png -mf fps=2:type=png -flip -o rgba8.avi -ovc x264')
if __name__ == '__main__':
main(sys.argv)
|
UTF-8
|
Python
| false | false | 2,011 |
10,325,101,382,445 |
aa8a442bbd7478cead8723918d7ab1f04a3acbc2
|
9d8d0114266b0524d8fbf6761d004ac1098c5801
|
/genfatr.py
|
aafe2a35ea09beb5bc5015cf412f15c3d25b836f
|
[] |
no_license
|
rapidhere/fdu-acm-report-generator
|
https://github.com/rapidhere/fdu-acm-report-generator
|
b732463704873dda8de01c8d8d241a994f99b594
|
f3c6e721c215fadce9594eab4e9d000f2cf3dbf2
|
refs/heads/master
| 2016-09-06T16:14:43.256705 | 2014-08-11T03:22:49 | 2014-08-11T03:22:49 | null | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null |
from report import Report
import sys
import os
import simplejson
WORK_DIR = os.getcwd()
if len(sys.argv) > 1:
WORK_DIR = sys.argv[1]
if not os.path.isdir(WORK_DIR):
sys.stderr.write("Wrong working directory!\n")
exit(1)
rep = Report()
# discover the directory
def discover():
# discover the problem problems
def discover_problems(dpath):
meta_file = os.path.join(dpath, "meta.json")
if not os.path.isfile(meta_file):
sys.stderr.write("Cannot find problem meta file\n")
exit(1)
try:
_meta = simplejson.load(file(meta_file))
except Exception as e:
raise Exception("Failed to load problem json file: %s" % str(e))
_list = _meta.get("list", None)
if _list is None:
sys.stderr.write("Cannot find key `list` in meta file\n")
exit(1)
for p in _list:
pfile = os.path.join(dpath, p + ".md")
if not os.path.isfile(pfile):
sys.stderr.write("Cannot find md file for problem `%s`\n" % p)
exit(1)
rep.add_problem(pfile, file(pfile).read())
# List up the directory
for f in os.listdir(WORK_DIR):
fpath = os.path.join(WORK_DIR, f)
if os.path.isfile(fpath):
if f == "meta.json":
_meta = simplejson.load(file(fpath))
rep.update_meta(_meta)
elif f == "overview.md":
rep.set_section("overview", file(fpath).read())
elif f == "process.md":
rep.set_section("process", file(fpath).read())
elif f == "summary.md":
rep.set_section("summary", file(fpath).read())
else:
sys.stderr.write("Warning: Unkown section file: %s\n" % fpath)
elif os.path.isdir(fpath):
if f == "problems":
discover_problems(fpath)
else:
sys.stderr.write("Warning: Unkown directory: %s\n" % fpath)
else:
sys.stderr.write("Warning: Unkown file type: %s\n" % fpath)
# use xelatex to compile
def make():
_latex = rep.generate_latex()
lfile = os.path.join(WORK_DIR, rep.get_report_file_name() + ".tex")
file(lfile, "w").write(_latex)
import subprocess
p = subprocess.Popen(["xelatex", lfile])
p.wait()
def run():
discover()
make()
if __name__ == "__main__":
run()
|
UTF-8
|
Python
| false | false | 2,014 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.