text stringlengths 0 1.05M | meta dict |
|---|---|
from fooapp import FooApp, start_app
import feedparser
import logging
from time import sleep, time
from ncore.data import FileStore
from ncore.daemon import become_daemon
from ncore.rest import request, tinyurl
try:
import json
except ImportError:
import simplejson as json
class Digg(FooApp):
name = 'digg'
config_opts = {
'digg_threshold': 'Sets the minimum number of diggs a story must have before it will be relayed to foobox.',
}
def __init__(self, server=None):
FooApp.__init__(self, server)
self.data = FileStore('/tmp/apps/digg')
try:
self.cache = json.loads(self.data['cache'])
except:
self.cache = []
def send(self, msg):
self.update()
return
def run(self):
while True:
self.update()
sleep(1500)
def get_last_update(self):
try:
return self.data['last_update']
except:
return 0
def update(self):
status, response = request('GET', 'http://services.digg.com/stories/top?type=json&appkey=http%3A%2F%2Fwww.neohippie.net%2Ffoobox' + str(self.get_last_update()), headers={'User-Agent': 'foobox/0.1'})
if status != 200:
logging.warning('digg recieved error from server: %s, %s' % (status, response))
return
response = json.loads(response)
for story in response['stories']:
if story['diggs'] < int(self.data['digg_threshold']):
continue
if story['id'] in self.cache:
continue
msg = '%s: %i - %s (%s) :: %s' % (self.name, story['diggs'], story['title'], tinyurl(story['link']), story['description'])
self.recv(msg)
self.cache.append(story['id'])
self.data['cache'] = json.dumps(self.cache)
self.data['last_update'] = str(int(time()))
if __name__ == '__main__':
become_daemon()
start_app(Digg)
| {
"repo_name": "JeremyGrosser/foobox",
"path": "digg.py",
"copies": "1",
"size": "1697",
"license": "bsd-3-clause",
"hash": 1995740602596490200,
"line_mean": 25.9365079365,
"line_max": 200,
"alpha_frac": 0.6700058928,
"autogenerated": false,
"ratio": 2.9108061749571186,
"config_test": false,
"has_no_keywords": false,
"few_assignments": false,
"quality_score": 0.8609915760865641,
"avg_score": 0.09417926137829567,
"num_lines": 63
} |
from fooapp import FooApp, start_app
import feedparser
import sys
from time import sleep
from ncore.data import FileStore
from ncore.daemon import become_daemon
try:
import json
except ImportError:
import simplejson as json
class RSS(FooApp):
name = 'rss'
config_opts = {}
def __init__(self, user):
FooApp.__init__(self, user)
try:
self.feeds = json.loads(self.data['feeds'])
except:
self.feeds = []
try:
self.cache = json.loads(self.data['cache'])
except:
self.cache = {}
def send(self, msg):
if not msg['text'] in self.feeds:
self.feeds.append(msg['text'])
self.data['feeds'] = json.dumps(self.feeds)
self.update()
def run(self):
while True:
self.update()
sleep(3600)
def update(self):
for url in self.feeds:
if not url in self.cache:
self.cache[url] = []
cache = self.cache[url]
d = feedparser.parse(url)
for entry in d.entries:
msg = '%s: %s' % (d.feed.title, entry.title)
if msg in cache:
continue
self.recv(msg)
cache.append(msg)
self.data['cache'] = json.dumps(self.cache)
if __name__ == '__main__':
become_daemon()
start_app(RSS, user=sys.argv[1])
| {
"repo_name": "JeremyGrosser/foobox",
"path": "rss.py",
"copies": "1",
"size": "1159",
"license": "bsd-3-clause",
"hash": -5944064984405658000,
"line_mean": 18.9827586207,
"line_max": 48,
"alpha_frac": 0.6453839517,
"autogenerated": false,
"ratio": 2.840686274509804,
"config_test": false,
"has_no_keywords": false,
"few_assignments": false,
"quality_score": 0.39860702262098036,
"avg_score": null,
"num_lines": null
} |
from fooapp import FooApp, start_app
import logging
import sys
from time import sleep
from urllib import urlopen, quote
import re
from ncore.data import FileStore
from ncore.daemon import become_daemon
from ncore.rest import request
try:
import json
except ImportError:
import simplejson as json
class GoogleSMS(FooApp):
name = 'google'
config_opts = {}
def __init__(self, user):
FooApp.__init__(self, user)
self.searchurl = 'http://www.google.com/sms/demo?hl=en&country=US&q='
try:
self.queries = json.loads(self.data['queries'])
except:
self.queries = []
try:
self.cache = json.loads(self.data['cache'])
except:
self.cache = []
def send(self, msg):
cmd, msg = msg['text'].split(' ', 1)
cmd = cmd.lower()
if cmd == 'add':
if not msg in self.queries:
self.queries.append(msg)
self.data['queries'] = json.dumps(self.queries)
logging.info('Registered new SMS query: %s' % msg)
self.update()
elif cmd == 'remove':
if msg in self.queries:
self.queries.remove(msg)
logging.info('Removed SMS query: %s' % msg)
else:
msg.insert(0, cmd)
messages = list(self.query(' '.join(msg)))
msg = '\n'.join(messages)
if not msg in self.cache:
self.recv(msg)
self.cache.append(msg)
def query(self, query):
query = quote(query)
response = urlopen(self.searchurl + query)
count = 0
messages = []
for line in response:
if not count and 'var resultSize' in line:
count = line.split('=', 1)[1].strip(' ;\n')
count = int(count)
continue
for i in range(count):
if 'var message%i' % (i + 1) in line:
msg = line.split('=', 1)[1].strip(" ;'\n")
msg = [x for x in msg.split('<br>') if x]
msg = '; '.join(msg)
yield msg
if count > 0 and len(messages) == count:
break
response.close()
return
def run(self):
while True:
self.update()
sleep(300)
def update(self):
for q in self.queries:
messages = list(self.query(q))
msg = '\n'.join(messages)
if not msg in self.cache:
self.recv(msg)
self.cache.append(msg)
self.data['cache'] = json.dumps(self.cache)
if __name__ == '__main__':
become_daemon()
start_app(GoogleSMS, sys.argv[1])
| {
"repo_name": "JeremyGrosser/foobox",
"path": "google_sms.py",
"copies": "1",
"size": "2759",
"license": "bsd-3-clause",
"hash": 5721953248445456000,
"line_mean": 29.3186813187,
"line_max": 77,
"alpha_frac": 0.5030808264,
"autogenerated": false,
"ratio": 4.0101744186046515,
"config_test": false,
"has_no_keywords": false,
"few_assignments": false,
"quality_score": 0.5013255245004652,
"avg_score": null,
"num_lines": null
} |
from fooapp import FooApp, start_app
import pownce
import logging
from time import sleep
from ncore.data import FileStore
from ncore.daemon import become_daemon
try:
import json
except ImportError:
import simplejson as json
class Pownce(FooApp):
name = 'pownce'
def __init__(self, server=None):
FooApp.__init__(self, server)
self.data = FileStore('/tmp/apps/pownce')
self.api = pownce.Api(self.data['username'], self.data['password'], self.data['apikey'])
try:
self.cache = json.loads(self.data['cache'])
except:
self.cache = []
def send(self, msg):
while True:
try:
status = self.api.post_message('public', msg['text'])
break
except:
logging.error(format_exc())
sleep(30)
continue
def run(self):
while True:
try:
timeline = self.api.get_notes(self.data['username'])
except:
logging.error(format_exc())
sleep(30)
continue
for note in timeline:
msg = '%s %s' % (note.sender.short_name, note.body)
if not msg in self.cache:
self.recv(msg)
self.cache.append(msg)
self.data['cache'] = json.dumps(self.cache)
sleep(120)
if __name__ == '__main__':
become_daemon()
start_app(Pownce, listen_port=9993)
| {
"repo_name": "JeremyGrosser/foobox",
"path": "powncer.py",
"copies": "1",
"size": "1204",
"license": "bsd-3-clause",
"hash": 1297975981814700800,
"line_mean": 21.7169811321,
"line_max": 90,
"alpha_frac": 0.6602990033,
"autogenerated": false,
"ratio": 2.9152542372881354,
"config_test": false,
"has_no_keywords": false,
"few_assignments": false,
"quality_score": 0.4075553240588135,
"avg_score": null,
"num_lines": null
} |
from fooapp import FooApp, start_app
import twitter
import logging
import sys
from time import sleep
from traceback import format_exc
from ncore.data import FileStore
from ncore.daemon import become_daemon
try:
import json
except ImportError:
import simplejson as json
class Twitter(FooApp):
name = 'twitter'
def __init__(self, user):
FooApp.__init__(self, user)
self.api = twitter.Api(username=self.config['twitter']['username'], password=self.config['twitter']['password'])
try:
self.cache = json.loads(self.data['cache'])
except:
self.cache = []
def send(self, msg):
msg = msg['text']
if len(msg) > 140:
logging.warning('Message is > 140 characters. Truncating to 140')
msg = msg[:140]
sent = False
while not sent:
try:
sleep(1)
status = self.api.PostUpdate(msg)
sent = True
except HTTPError:
logging.error('Error sending twitter update... Retrying...')
def run(self):
while True:
try:
timeline = self.api.GetFriendsTimeline()
except:
logging.warning('Unable to fetch twitter timeline. Retrying in 5 minutes')
logging.warning(format_exc())
sleep(300)
continue
#timeline.reverse()
for status in timeline:
if not status.id in self.cache:
msg = '%s: %s' % (status.user.screen_name, status.text)
self.recv(msg)
self.cache.append(status.id)
self.data['cache'] = json.dumps(self.cache)
sleep(self.config['twitter']['interval'])
if __name__ == '__main__':
become_daemon()
start_app(Twitter, user=sys.argv[1])
| {
"repo_name": "JeremyGrosser/foobox",
"path": "tweet.py",
"copies": "1",
"size": "1880",
"license": "bsd-3-clause",
"hash": -105390752623963140,
"line_mean": 29.8196721311,
"line_max": 120,
"alpha_frac": 0.5505319149,
"autogenerated": false,
"ratio": 4.32183908045977,
"config_test": false,
"has_no_keywords": false,
"few_assignments": false,
"quality_score": 0.537237099535977,
"avg_score": null,
"num_lines": null
} |
from fooapp import FooApp, start_app
import xmpp
from time import sleep
from ncore.data import FileStore
from ncore.daemon import become_daemon
from traceback import format_exc
import logging
class Jabber(FooApp):
name = 'jabber'
config_opts = {
'username': 'The User ID to connect to the Jabber service with. (eg. me@example.com',
'password': 'Sets the password to be used when connecting to the Jabber service.',
'target': 'Sets the Jabber user to interact with. This will probably be your personal jabber account.',
}
def __init__(self, server=None):
FooApp.__init__(self, server)
self.data = FileStore('/tmp/apps/jabber')
self.jabberid = self.data['username']
self.password = self.data['password']
jid = xmpp.protocol.JID(self.jabberid)
self.client = xmpp.Client(jid.getDomain(), debug=[])
self.client.connect()
self.client.auth(jid.getNode(), self.password, resource='script')
self.client.RegisterHandler('message', self.recv)
self.client.sendInitPresence(requestRoster=0)
def send(self, msg):
try:
jid = xmpp.protocol.JID(self.data['target'])
self.client.send(xmpp.protocol.Message(jid, msg['text']))
except:
pass
sleep(0.4)
def recv(self, client, msg):
logging.debug('Jabber got message')
if not str(msg.getFrom()).startswith(self.data['target']):
return
if not msg.getBody().startswith('!'):
FooApp.recv(self, msg.getBody())
else:
prefix, msg = msg.getBody().split(' ', 1)
prefix = prefix.lstrip('!')
FooApp.recv(self, msg, dst=prefix)
return
def DisconnectHandler(self):
logging.info('Jabber disconnected from server. Reconnecting...')
try:
self.reconnectAndReauth()
logging.info('Connected to server.')
except:
logging.error('Error attempting to reconnect: %s' % format_exc())
def run(self):
while self.client.isConnected():
self.client.Process(1)
if __name__ == '__main__':
become_daemon()
start_app(Jabber)
| {
"repo_name": "JeremyGrosser/foobox",
"path": "jabber.py",
"copies": "1",
"size": "2218",
"license": "bsd-3-clause",
"hash": 3250420646786223600,
"line_mean": 34.2063492063,
"line_max": 111,
"alpha_frac": 0.6082055906,
"autogenerated": false,
"ratio": 3.9256637168141593,
"config_test": false,
"has_no_keywords": false,
"few_assignments": false,
"quality_score": 0.5033869307414159,
"avg_score": null,
"num_lines": null
} |
from foodgame.entities import EntityLiving
from foodgame.util import Point
from pygame.locals import K_UP, K_DOWN, K_LEFT, K_RIGHT
## Class for the player.
class Player():
## Player Constructor.
def __init__(self, game):
self.game = game
self.entity = EntityLiving(game)
self.entity.sprite = "player"
self.game.world.move(self.entity, Point(103, 103))
## Updates the player.
def update(self, dt):
self.entity.update()
## Draws the player entity.
def draw(self):
self.entity.draw()
## Moves the player, according to the key pressed.
# @param key The key pressed.
def move(self, key):
newpos = self.entity.pos
if key == K_UP:
newpos = newpos + Point(0, -1)
elif key == K_DOWN:
newpos = newpos + Point(0, 1)
elif key == K_LEFT:
newpos = newpos + Point(-1, 0)
elif key == K_RIGHT:
newpos = newpos + Point(1, 0)
self.game.world.move(self.entity, newpos)
self.game.camera.track_player(self.entity.pos)
self.game.pass_time(1)
## Gets a list of entities on the player's tile (minus itself).
# @todo TODO: currently lists all EntityStatic's, it should list only the one with the highest priority.
def get_standing_on(self):
return [e.name for e in self.game.world.at_pos(self.entity.pos) if e != self.entity] | {
"repo_name": "trashbyte/hungryboys",
"path": "foodgame/player.py",
"copies": "1",
"size": "1425",
"license": "mit",
"hash": -1862558126061115100,
"line_mean": 30,
"line_max": 108,
"alpha_frac": 0.6077192982,
"autogenerated": false,
"ratio": 3.527227722772277,
"config_test": false,
"has_no_keywords": false,
"few_assignments": false,
"quality_score": 0.9583749242981007,
"avg_score": 0.010239555598254032,
"num_lines": 46
} |
from foodgame.util import Point
from .asset_manager import AssetManager
## A structure representing the state of the world viewport.
class Camera():
## Camera constructor.
# @param game The owning Game
def __init__(self, game):
## The owning Game.
self.game = game
## Position of the camera.
self.pos = Point(90, 90)
## (internal)
self._zoom = 16
AssetManager.rescale(self.zoom)
## Curent zoom level, expressed as the tile width in pixels.
@property
def zoom(self):
return self._zoom
## Sets zoom level for camera and rescales tile sprites to match.
# @param value The new zoom value.
@zoom.setter
def zoom(self, value):
self._zoom = value
AssetManager.rescale(value)
## Track the player if they move off-screen.
# @param e_pos The player's position as a Point
def track_player(self, e_pos):
temp_x = self.pos.x
temp_y = self.pos.y
while e_pos.x < temp_x + 5:
temp_x -= 1
while e_pos.x > temp_x + self.game.ui_manager.num_tiles[0] - 5:
temp_x += 1
while e_pos.y < temp_y + 5:
temp_y -= 1
while e_pos.y > temp_y + self.game.ui_manager.num_tiles[1] - 5:
temp_y += 1
self.pos = Point(temp_x, temp_y)
| {
"repo_name": "trashbyte/hungryboys",
"path": "foodgame/camera.py",
"copies": "1",
"size": "1341",
"license": "mit",
"hash": 8526434206727395000,
"line_mean": 28.152173913,
"line_max": 71,
"alpha_frac": 0.5779269202,
"autogenerated": false,
"ratio": 3.5196850393700787,
"config_test": false,
"has_no_keywords": false,
"few_assignments": false,
"quality_score": 0.4597611959570078,
"avg_score": null,
"num_lines": null
} |
from foo import Foo
import types
def external_document():
return document.getElementById('a')
def require_file_module():
f = Foo()
return f.bar()
def require_sub_file_module():
f = Foo()
return f.yum()
def test_window_global():
return my_global_foo('suck ass')
def what_is_love():
f = Foo()
return f.what_is_love(my_global_var)
def test_document_title():
return document.title
def test_external_module():
return Foo().go_google()
def test_type_string():
return 'i am %s' % 'string'
def test_type_int():
return 1
def test_type_float():
return 1.1
def test_type_long():
return 10**100 #<= google
def test_type_scientific_notation_large():
return 1.7e19
def test_type_scientific_notation_small():
return 3.21e-13
def test_type_boolean_false():
return False
def test_type_boolean_true():
return True
def test_type_map():
return {'a':'b'}
def test_type_tuple():
return ('a','b')
def test_type_none():
return None
def test_type_dict():
return dict(one=2,two=3)
def test_type_function():
return test_type_dict
def test_type_anonymous_function():
def anonymous(*args):
return 'foobar'
return anonymous
# tests for conversion from JS into Python
def test_js_type_string(t):
return type(t) == types.StringType
def test_js_type_int(t):
return type(t) == types.IntType
def test_js_type_function(t):
return type(t) == types.FunctionType
def test_js_type_float(t):
return type(t) == types.FloatType
def test_js_type_list(t):
return type(t) == types.ListType
def test_js_type_klist(t):
return type(t).__name__ == 'KList'
def test_js_type_kmethod(t):
return type(t).__name__ == 'KMethod'
def test_js_type_kobject(t):
return type(t).__name__ == 'KObject'
def test_js_type_dict(t):
return type(t) == types.DictType
def test_js_type_bool(t):
return type(t) == types.BooleanType
def test_js_type_none(t):
return type(t) == types.NoneType
| {
"repo_name": "marshall/titanium",
"path": "apps/drillbit/Resources/tests/python/python.py",
"copies": "1",
"size": "1902",
"license": "apache-2.0",
"hash": 5293610270457126000,
"line_mean": 17.2884615385,
"line_max": 42,
"alpha_frac": 0.683491062,
"autogenerated": false,
"ratio": 2.697872340425532,
"config_test": true,
"has_no_keywords": false,
"few_assignments": false,
"quality_score": 0.3881363402425532,
"avg_score": null,
"num_lines": null
} |
from foo.project_settings import *
from foo.audio_video import excerpt_and_compile_video_file
import sys
# import json # DEPRECATED
import csv
import re
MIN_CONFIDENCE = 0.0
"""
TODO
refactor into separate CLI-subcommands
CSV makes for bad numerical data...
"""
if __name__ == '__main__':
"""
usage:
python supercut.py republican-debate-sc-2016-02-13 'Obama|Bush'
Expects: The following routines have already been run:
python go.py ~/Downloads/republican-debate-sc-2016-02-13.mp4
python compile.py republican-debate-sc-2016-02-13
Produces: a movie file in the project's supercuts directory, e.g.
projects/republican-debate-sc-2016-02-13/supercuts/obama-bush.mp4
"""
pslug, word_pattern = sys.argv[1:3]
is_dryrun = True if not sys.argv[-1] == '--produce' else False
if not does_project_exist(pslug):
raise NameError(project_dir(pslug) + " does not exist")
print("Extracting case-insensitive pattern:", word_pattern)
print(" from project:", pslug)
print(" with a minimum confidence of:", MIN_CONFIDENCE)
# create a filename based on the word_pattern
supercut_slug = re.sub('[^A-z0-9_\.-]+', '-', word_pattern.replace('\\', '')).strip('-').lower()
supercut_fname = join(supercuts_dir(pslug), supercut_slug + '.mp4')
re_pattern = re.compile(word_pattern, re.IGNORECASE)
word_matches = []
with open(words_transcript_path(pslug)) as f:
transcribed_words = list(csv.DictReader(f))
for t_word in transcribed_words:
if re_pattern.search(t_word['text']) and float(t_word['confidence']) >= MIN_CONFIDENCE:
word_matches.append(t_word)
timestamps = []
for n, word in enumerate(word_matches):
print("\t", str(n) + ':', word['text'], word['confidence'], word['start'], word['end'])
timestamps.append((float(word['start']), float(word['end'])))
if is_dryrun:
print("...just a dry run...Use: --produce to create the video file")
else:
excerpt_and_compile_video_file(
src_path=full_video_path(pslug),
dest_path=supercut_fname,
timestamps=timestamps
)
print("Wrote", len(timestamps), "cuts to:\n\t", supercut_fname)
| {
"repo_name": "audip/youtubeseek",
"path": "watsoncloud/supercut.py",
"copies": "1",
"size": "2262",
"license": "mit",
"hash": 3367027846565816000,
"line_mean": 33.2727272727,
"line_max": 100,
"alpha_frac": 0.6383731211,
"autogenerated": false,
"ratio": 3.381165919282511,
"config_test": false,
"has_no_keywords": false,
"few_assignments": false,
"quality_score": 0.9513694472535119,
"avg_score": 0.0011689135694783683,
"num_lines": 66
} |
from foosball.games.models import Game, Team, Player
def update_player_stats(instance):
"""
Update player win and played counts for players of a Team.
:param instance: Team that will be used to update players.
:type instance: Team
"""
for user in instance.players.all():
totals = {1: 0, 2: 0}
wins = {1: 0, 2: 0}
teams = Team.objects.filter(players__id=user.id).prefetch_related("players")
for team in teams:
player_count = len(team.players.all())
totals[player_count] += 1
if team.score == 10:
wins[player_count] += 1
player, _created = Player.objects.get_or_create(user=user)
player.singles_wins = wins[1]
player.doubles_wins = wins[2]
player.singles_played = totals[1]
player.doubles_played = totals[2]
if totals[1]:
player.singles_win_percentage = round((wins[1]/totals[1])*100, 2)
else:
player.singles_win_percentage = 0
if totals[2]:
player.doubles_win_percentage = round((wins[2] / totals[2])*100, 2)
else:
player.doubles_win_percentage = 0
player.total_played = totals[1] + totals[2]
player.save()
def stats_red_or_blue(params):
"""
Return statistics on the most important question.
"""
red_wins = Game.objects.filter(teams__side=Team.RED, teams__score=10).count()
blue_wins = Game.objects.filter(teams__side=Team.BLUE, teams__score=10).count()
return {
"type": "pie",
"data": {
"labels": [
"Red",
"Blue",
],
"datasets": [
{
"data": [red_wins, blue_wins],
"backgroundColor": [
"#FF6384",
"#36A2EB",
],
}]
},
"options": {}
}
def stats_players(params):
"""
Return statistics on player singles and doubles win percentages.
"""
players = Player.objects.filter(total_played__gt=5).order_by("user__username").values_list(
"user__username", "singles_win_percentage", "doubles_win_percentage"
)
if players:
usernames, singles_win_percentages, doubles_win_percentages = zip(*players)
else:
usernames = singles_win_percentages = doubles_win_percentages = []
return {
"type": "bar",
"data": {
"labels": usernames,
"datasets": [
{
"label": "Win % - singles",
"data": singles_win_percentages,
"backgroundColor": "#2E5168",
},
{
"label": "Win % - doubles",
"data": doubles_win_percentages,
"backgroundColor": "#65923B",
},
]
},
"options": {}
}
| {
"repo_name": "andersinno/foosball",
"path": "foosball/games/stats.py",
"copies": "1",
"size": "2969",
"license": "mit",
"hash": 4522383374713182700,
"line_mean": 31.2717391304,
"line_max": 95,
"alpha_frac": 0.5025261031,
"autogenerated": false,
"ratio": 3.891218872870249,
"config_test": false,
"has_no_keywords": false,
"few_assignments": false,
"quality_score": 0.4893744975970249,
"avg_score": null,
"num_lines": null
} |
from fooster.web import web
import mock
test_request = 'GET / HTTP/1.1\r\n' + '\r\n'
def bad_read(self):
raise Exception()
def run(request, handler=None, timeout=None, keepalive=True, initial_timeout=None, read_exception=False, close=True, skip=False):
if not isinstance(request, bytes):
request = request.encode(web.http_encoding)
if not handler:
handler = mock.MockHTTPHandler
server = mock.MockHTTPServer(routes={'/': handler, '/named/(?P<named>.+)': handler})
socket = mock.MockSocket(request)
request_obj = web.HTTPRequest(socket, ('127.0.0.1', 1337), server, timeout)
request_obj.response = mock.MockHTTPResponse(socket, ('127.0.0.1', 1337), server, request_obj)
request_obj.skip = skip
if read_exception:
request_obj.rfile.read = bad_read
request_obj.rfile.readline = bad_read
request_obj.handle(keepalive, initial_timeout)
if close:
request_obj.close()
return request_obj
def test_http_version_one():
request = run('GET / HTTP/1.0\r\n' + '\r\n')
assert request.request_http == 'HTTP/1.0'
def test_initial_timeout():
request = run('', initial_timeout=5)
assert request.connection.timeout == 5
def test_timeout():
request = run(test_request, timeout=8, initial_timeout=5)
assert request.connection.timeout == 8
def test_read_exception():
request = run(test_request, timeout=8, initial_timeout=5, read_exception=True)
assert request.connection.timeout == 5
assert not request.keepalive
def test_no_request():
request = run('')
# if no request, do not keepalive
assert not request.keepalive
def test_request_too_large():
# request for 'GET aaaaaaa... HTTP/1.1\r\n' where it's length is one over the maximum line size
long_request = 'GET ' + 'a' * (web.max_line_size - 4 - 9 - 2 + 1) + ' HTTP/1.1\r\n\r\n'
request = run(long_request)
assert request.handler.error.code == 414
assert not request.keepalive
def test_no_newline():
request = run(test_request[:-4])
assert request.handler.error.code == 400
assert not request.keepalive
def test_bad_request_line():
request = run('GET /\r\n' + '\r\n')
assert request.handler.error.code == 400
assert not request.keepalive
def test_wrong_http_version():
request = run('GET / HTTP/9000\r\n' + '\r\n')
assert request.handler.error.code == 505
assert not request.keepalive
def test_header_too_large():
# create a header for 'TooLong: aaaaaaa...\r\n' where it's length is one over the maximum line size
test_header_too_long = 'TooLong: ' + 'a' * (web.max_line_size - 9 - 2 + 1) + '\r\n'
request = run('GET / HTTP/1.1\r\n' + test_header_too_long + '\r\n')
assert request.handler.error.code == 431
assert request.handler.error.status_message == 'TooLong Header Too Large'
assert not request.keepalive
def test_too_many_headers():
# create a list of headers '1: test\r\n2: test\r\n...' where the number of them is one over the maximum number of headers
headers = ''.join(str(i) + ': test\r\n' for i in range(web.max_headers + 1))
request = run('GET / HTTP/1.1\r\n' + headers + '\r\n')
assert request.handler.error.code == 431
assert not request.keepalive
def test_header_no_newline():
request = run('GET / HTTP/1.1\r\n' + 'Test: header')
assert request.handler.error.code == 400
assert not request.keepalive
def test_header_no_colon():
request = run('GET / HTTP/1.1\r\n' + 'Test header\r\n' + '\r\n')
assert request.handler.error.code == 400
assert not request.keepalive
def test_connection_close():
request = run('GET / HTTP/1.1\r\n' + 'Connection: close\r\n' + '\r\n')
assert not request.keepalive
def test_handler_not_found():
request = run('GET /nonexistent HTTP/1.1\r\n' + '\r\n')
assert request.handler.error.code == 404
assert request.keepalive
def test_handler_quoted():
request = run('GET %2f HTTP/1.1\r\n' + '\r\n')
assert request.handler.error.code == 404
assert request.keepalive
def test_keepalive():
request = run(test_request)
assert request.keepalive
def test_no_keepalive():
request = run(test_request, keepalive=False)
assert not request.keepalive
def test_handler():
request = run(test_request, handler=web.HTTPHandler)
assert isinstance(request.handler, web.HTTPHandler)
def test_read_pipelining():
request = run('GET / HTTP/1.1\r\n' + '\r\n' + 'GET /nonexistent HTTP/1.1\r\n' + '\r\n', close=False)
assert request.rfile.read() == b'GET /nonexistent HTTP/1.1\r\n\r\n'
request.close()
def test_close():
request = run('GET / HTTP/1.1\r\n' + '\r\n')
assert request.rfile.closed
assert request.response.closed
def test_skip():
request = run('', skip=True)
assert request.headers is None
def test_named_groups():
request = run('GET /named/asdf HTTP/1.1\r\n' + '\r\n')
assert request.handler.groups['named'] == 'asdf'
assert request.response.closed
| {
"repo_name": "fkmclane/web.py",
"path": "tests/test_request.py",
"copies": "1",
"size": "5050",
"license": "mit",
"hash": 4769360395781526000,
"line_mean": 24,
"line_max": 129,
"alpha_frac": 0.6532673267,
"autogenerated": false,
"ratio": 3.2496782496782495,
"config_test": true,
"has_no_keywords": false,
"few_assignments": false,
"quality_score": 0.44029455763782493,
"avg_score": null,
"num_lines": null
} |
from fooster.web import web
import pytest
test_key = 'Magical'
test_value = 'header'
test_header = test_key + ': ' + test_value + '\r\n'
poor_key = 'not'
poor_value = 'good'
poor_header = poor_key + ':' + poor_value + '\r\n'
good_header = poor_key + ': ' + poor_value + '\r\n'
case_key = 'wEIrd'
case_key_title = case_key.title()
case_value = 'cAse'
case_header = case_key + ': ' + case_value + '\r\n'
case_header_test = case_key + ': ' + test_value + '\r\n'
nonstr_key = 6
nonstr_value = None
def test_add_get():
headers = web.HTTPHeaders()
headers.add(test_header)
assert headers.get(test_key) == test_value
def test_add_getlist():
headers = web.HTTPHeaders()
headers.add(test_header)
assert headers.getlist(test_key) == [test_value]
def test_add_getitem():
headers = web.HTTPHeaders()
headers.add(test_header)
assert headers[test_key] == test_value
def test_getitem_empty():
headers = web.HTTPHeaders()
with pytest.raises(KeyError):
headers[test_key]
def test_getlist_empty():
headers = web.HTTPHeaders()
with pytest.raises(KeyError):
headers.getlist(test_key)
def test_getlist_default():
headers = web.HTTPHeaders()
assert headers.getlist(test_key, []) == []
def test_set_remove():
headers = web.HTTPHeaders()
headers.set(test_key, test_value)
assert headers.get(test_key) == test_value
headers.remove(test_key)
def test_set_multiple():
headers = web.HTTPHeaders()
headers.set(test_key, test_value)
headers.set(test_key, test_value)
assert headers.get(test_key) == test_value
assert headers.getlist(test_key) == [test_value] * 2
def test_set_overwrite():
headers = web.HTTPHeaders()
headers.set(test_key, test_value, True)
headers.set(test_key, test_value, True)
assert headers.get(test_key) == test_value
assert headers.getlist(test_key) == [test_value]
def test_setitem_delitem():
headers = web.HTTPHeaders()
headers[test_key] = test_value
assert headers[test_key] == test_value
del headers[test_key]
def test_remove_empty():
headers = web.HTTPHeaders()
with pytest.raises(KeyError):
headers.remove(test_key)
def test_delitem_empty():
headers = web.HTTPHeaders()
with pytest.raises(KeyError):
del headers[test_key]
def test_retrieve():
headers = web.HTTPHeaders()
headers.set(test_key, test_value)
assert headers.retrieve(test_key) == test_header
def test_len():
headers = web.HTTPHeaders()
headers.set(test_key, test_value)
assert len(headers) == 1
headers.set(poor_key, poor_value)
assert len(headers) == 2
def test_multiple_add_get_len_retrieve():
headers = web.HTTPHeaders()
headers.add(case_header)
assert len(headers) == 1
assert headers.get(case_key) == case_value
assert headers.getlist(case_key) == [case_value]
assert headers.retrieve(case_key) == case_header
headers.add(case_header)
assert len(headers) == 1
assert headers.get(case_key) == case_value
assert headers.getlist(case_key) == [case_value] * 2
assert headers.retrieve(case_key) == case_header + case_header
headers.add(case_header_test)
assert len(headers) == 1
assert headers.get(case_key) == test_value
assert headers.getlist(case_key) == [case_value] * 2 + [test_value]
assert headers.retrieve(case_key) == case_header + case_header + case_header_test
def test_multiple_set_get_len_retrieve():
headers = web.HTTPHeaders()
headers.set(case_key, case_value)
assert len(headers) == 1
assert headers.get(case_key) == case_value
assert headers.getlist(case_key) == [case_value]
assert headers.retrieve(case_key) == case_header
headers.set(case_key, case_value)
assert len(headers) == 1
assert headers.get(case_key) == case_value
assert headers.getlist(case_key) == [case_value] * 2
assert headers.retrieve(case_key) == case_header + case_header
headers.set(case_key, test_value)
assert len(headers) == 1
assert headers.get(case_key) == test_value
assert headers.getlist(case_key) == [case_value] * 2 + [test_value]
assert headers.retrieve(case_key) == case_header + case_header + case_header_test
def test_clear():
headers = web.HTTPHeaders()
headers.set(test_key, test_value)
headers.set(poor_key, poor_value)
headers.clear()
assert len(headers) == 0
def test_case():
headers = web.HTTPHeaders()
headers.set(case_key, case_value)
assert headers.get(case_key_title) == case_value
assert headers.retrieve(case_key_title) == case_header
def test_iter():
headers = web.HTTPHeaders()
headers.set(test_key, test_value)
headers.set(poor_key, poor_value)
headers.set(case_key, case_value)
header_list = []
for header in headers:
header_list.append(header)
assert test_header in header_list
assert good_header in header_list
assert case_header in header_list
def test_contains():
headers = web.HTTPHeaders()
headers.set(test_key, test_value)
headers.set(poor_key, poor_value)
headers.set(case_key, case_value)
assert test_key in headers
assert poor_key in headers
assert case_key in headers
assert test_key.upper() in headers
assert poor_key.upper() in headers
assert case_key.upper() in headers
assert test_key.lower() in headers
assert poor_key.lower() in headers
assert case_key.lower() in headers
def test_poor_header():
headers = web.HTTPHeaders()
headers.add(poor_header)
assert headers.get(poor_key) == poor_value
def test_set_key_nonstr():
headers = web.HTTPHeaders()
with pytest.raises(TypeError):
headers.set(nonstr_key, test_value)
def test_set_value_nonstr():
headers = web.HTTPHeaders()
with pytest.raises(TypeError):
headers.set(test_key, nonstr_value)
| {
"repo_name": "fkmclane/web.py",
"path": "tests/test_header.py",
"copies": "1",
"size": "5961",
"license": "mit",
"hash": -7112483124708896000,
"line_mean": 20.9963099631,
"line_max": 85,
"alpha_frac": 0.6594531119,
"autogenerated": false,
"ratio": 3.295190713101161,
"config_test": true,
"has_no_keywords": false,
"few_assignments": false,
"quality_score": 0.9454214750942979,
"avg_score": 0.00008581481163648846,
"num_lines": 271
} |
from football.models import Score, Team
from django.views.generic import TemplateView
from datetime import date, timedelta
from pylab import figure, barh, yticks, xlabel, title, grid, savefig, arange, ylabel, clf
from functions import append, add
class WeekOverview(TemplateView):
# overview of all the data for the past week.
template_name = "overview.html"
def getPoints(sewlf, scores):
points = {}
for score in scores:
if score.home_score > score.away_score:
points = add(points, score.home.id, 2)
points = add(points, score.away.id, 0)
elif score.home_score == score.away_score:
points = add(points, score.home.id, 1)
points = add(points, score.away.id, 1)
else:
points = add(points, score.home.id, 0)
points = add(points, score.away.id, 2)
return points
# getRanks and updateChart are different here due to date interval of a week
def getRanks(self, scores):
points = self.getPoints(scores)
games = {}
for score in scores:
games = add(games,score.home.id,1)
games = add(games,score.away.id,1)
rankDict = []
for i in range(len(points)):
team = 0
pts = -1
for t, p in points.items():
if p > pts:
team = t
pts = p
elif p == pts and team!=0 and games[t] < games[team]:
team = t
pts = p
teamObj = Team.objects.get(pk=team)
rankDict.append({'id': team, 'team': teamObj.name, 'pt': pts, 'games': games[team]})
del points[team]
return rankDict #returning a dictionary with limitted data instead of full team object
# Updates chart
def updateChart(self, ranks):
teams = []
points = []
for rank in reversed(ranks):
teams.append(rank["team"])
points.append(rank["pt"])
pos = arange(len(teams))+.5 # the bar centers on the y axis
figure(1)
barh(pos, points, align='center')
yticks(pos, teams)
xlabel('Points')
ylabel('Team')
title('Ranking')
grid(True)
savefig("pics/overviewChart.png", dpi=60) # saving into different pic
clf()
def get_context_data(self, **kwargs):
context = super(WeekOverview, self).get_context_data(**kwargs)
start = date.today() + timedelta(weeks=-1) # week limit
scores = Score.objects.filter(when__gt=start)
ranks = self.getRanks(scores)
self.updateChart(ranks)
context['scores'] = scores
context['ranks'] = ranks
context["title"] = 'Week Overview'
return context
| {
"repo_name": "keizik/table-football",
"path": "src/table-football/football/overview.py",
"copies": "1",
"size": "2363",
"license": "bsd-3-clause",
"hash": 7649948659652685000,
"line_mean": 29.7012987013,
"line_max": 89,
"alpha_frac": 0.6707575116,
"autogenerated": false,
"ratio": 3.0608808290155443,
"config_test": false,
"has_no_keywords": false,
"few_assignments": false,
"quality_score": 0.42316383406155444,
"avg_score": null,
"num_lines": null
} |
from football.models import Score, Team
from django.views.generic import TemplateView
from django.db.models import Q
class TeamProfile(TemplateView):
# shows team info
template_name = "team.html"
def get_context_data(self, **kwargs):
context = super(TeamProfile, self).get_context_data(**kwargs)
teamId = kwargs['team'] # team id is passed by argument
team = Team.objects.get(pk=teamId) # teams is selected by id
if team: # if team was successfully selected its profile is shown
context['team'] = team # to gather data from team object
scores = Score.objects.filter(Q(home=teamId) | Q(away=teamId) ) # scores, where team is either home team or away team.
context['scores'] = scores
stats = {} # dict for different statistics
stats["games"] = team.games;
won = 0
lost = 0
draw = 0
goals_scored = 0
opponent_goals = 0
milestones = {} # dict for interesting events
biggestWin = "" # for corresponding score object
bw = 0 # the biggest win counter
biggestLoss = ""
bl = 0
mostGoalsScored = ""
mgs = 0
mostGoalsReceived = ""
mgr = 0
for score in scores:
# local variables, compared with the biggest/most values.
w = 0
l = 0
gs = 0
og = 0
if str(score.home.id) == teamId:
if score.home_score > score.away_score:
w = 1
elif score.home_score < score.away_score:
l = 1
gs = score.home_score
og = score.away_score
else:
if score.home_score < score.away_score:
w = 1
elif score.home_score > score.away_score:
l = 1
gs = score.away_score
og = score.home_score
dif = abs(score.home_score - score.away_score) # the difference between scores.
if w:
won = won + 1
score.color = "green" # green color for victory. Color is passed on to the view to determine the color of the text
if dif > bw:
bw = dif
biggestWin = score
elif l:
lost = lost + 1
score.color = "red" # red for loss
if dif > bl:
bl = dif
biggestLoss = score
else:
draw = draw + 1
score.color = "blue" # blue for draw
goals_scored = goals_scored + gs
opponent_goals = opponent_goals + og
if gs > mgs:
mgs = gs
mostGoalsScored = score
if og > mgr:
mgr = og
mostGoalsReceived = score
stats["won"] = won
stats["lost"] = lost
stats["draw"] = draw
stats["gs"] = goals_scored
stats["og"] = opponent_goals
context['stats'] = stats
milestones['bw'] = biggestWin
milestones['bl'] = biggestLoss
milestones['mgs'] = mostGoalsScored
milestones['mgr'] = mostGoalsReceived
context["milestones"] = milestones
context["points"] = team.points
else:
context['error'] = 'No team with Id <b>' + teamId + '</b>'
context['title'] = 'Team Profile: ' + team.name
return context
| {
"repo_name": "keizik/table-football",
"path": "src/table-football/football/team.py",
"copies": "1",
"size": "2836",
"license": "bsd-3-clause",
"hash": 8109352818469288000,
"line_mean": 29.8260869565,
"line_max": 122,
"alpha_frac": 0.6272919605,
"autogenerated": false,
"ratio": 3.1233480176211454,
"config_test": false,
"has_no_keywords": false,
"few_assignments": false,
"quality_score": 0.4250639978121145,
"avg_score": null,
"num_lines": null
} |
from football.models import Team
from django.db.models import Count
# appends new value to the dictionary (unless it is already there)
def append(dict, key, val):
if dict.has_key(key):
return dict
else:
dict[key] = val
return dict
# does addition to the dictionary item based on key (team)
def add(dict, team, pt):
if dict.has_key(team):
dict[team] += pt
else:
dict[team] = pt
return dict
# extract every team's number of players from list of scores
def getTeamPlayers(scores):
teamPlayers = {} # key: team name. value: number of players
for score in scores:
if not teamPlayers.has_key(score.home.name):
teamPlayers[score.home.name] = score.home.players.count()
if not teamPlayers.has_key(score.away.name):
teamPlayers[score.away.name] = score.away.players.count()
return teamPlayers
# gets ranking dictionary for all the teams:
# result: {team name, scored points, played games}
def getRanks(teams=[]):
if not teams:
teams = list(Team.objects.all()) # if no teams are passed, all teams in database are analyzed.
ranks = [] # the result list
for i in range(len(teams)): # iterating over the teams. Indexes are used here due to dynamicly changed teams list content. Algorithm - simple bubble sort
team = teams[0] # best ranked team. Team number 1 in beginning.
pts = -1 # starting points are set to -1
for t in teams: # now checking every team
if t.points > pts: # if it's points are greater than current best rank value - this team is recognized as the top team.
team = t
pts = team.points
elif t.points == pts and team!="" and t.games < team.games: # otherwise, checking games (less games, same points -> higher place)
team = t
pts = team.points
ranks.append(team)
del teams[teams.index(team)] # deleting ranked team and moving on.
return ranks
# gets list of teams by team's players. Only the exact match matters.
def get_teams_by_players(ids):
query = Team.objects.annotate(count=Count("players")).filter(count=len(ids)) # first teams with correct number of players are received
for _id in ids:
query = query.filter(players=_id) # then teams are filtered by players ids to get the exact match.
return query | {
"repo_name": "keizik/table-football",
"path": "src/table-football/football/functions.py",
"copies": "1",
"size": "2191",
"license": "bsd-3-clause",
"hash": -4655959975855434000,
"line_mean": 38.8545454545,
"line_max": 154,
"alpha_frac": 0.7183934277,
"autogenerated": false,
"ratio": 3.3146747352496218,
"config_test": false,
"has_no_keywords": false,
"few_assignments": false,
"quality_score": 0.9134378644381684,
"avg_score": 0.07973790371358734,
"num_lines": 55
} |
from forbiddenfruit import curse as improve
import sys
from functools import reduce, partial
from itertools import *
import operator as op
from collections import abc
# import all the modules before extending types
import requests
import json
# types
ITERABLE = {tuple, list, set, str, dict, abc.Iterable, range, map, filter, zip}
SEQUENCE = {tuple, list, str, abc.Sequence}
SIZED = ITERABLE | {abc.Sized}
NUMERIC = {int, float} # complex?
def _easter_eggs():
improve(int, "fractional", lambda self, other: float("{}.{}".format(self, other)))
def _better_formatting():
FMT_LIKE_LIST = ITERABLE - {str}
improve(str, "fmt", lambda self, fmt: fmt.format(self))
for t in FMT_LIKE_LIST:
improve(t, "fmt", lambda self, fmt: list(map(lambda q: fmt.format(q), self)))
def _functional_iterables():
improve(dict, "merge", lambda self, other: {**self, **other})
for t in SIZED:
improve(t, "size", lambda self: len(self) if hasattr(self, "__len__") else len(list(self)))
improve(t, "len", lambda self: len(self) if hasattr(self, "__len__") else len(list(self)))
improve(t, "length", lambda self: len(self) if hasattr(self, "__len__") else len(list(self)))
for t in ITERABLE:
improve(t, "map", lambda self, f: map(f, self))
improve(t, "filter", lambda self, f: filter(f, self))
improve(t, "reduce", lambda self, f: reduce(f, self))
improve(t, "join", lambda self, sep: reduce(lambda a, b: a+[sep]+b, self).reduce(op.add))
improve(t, "any", lambda self, f=None: any(self) if f is None else any(map(f, self)))
improve(t, "exists", lambda self, f=None: any(self) if f is None else any(map(f, self)))
improve(t, "all", lambda self, f=None: all(self) if f is None else all(map(f, self)))
improve(t, "every", lambda self, f=None: all(self) if f is None else all(map(f, self)))
improve(t, "contains", lambda self, q=None: q in self)
improve(t, "min", lambda self: min(self))
improve(t, "max", lambda self: max(self))
improve(t, "sum", lambda self: reduce(op.add, self))
improve(t, "product", lambda self: reduce(op.mul, self))
for t in SEQUENCE:
improve(t, "head", lambda self: self[0])
improve(t, "first", lambda self: self[0])
improve(t, "last", lambda self: self[-1])
improve(t, "init", lambda self: self[:-1])
improve(t, "tail", lambda self: self[1:])
improve(t, "drop", lambda self, n: self[n:])
improve(t, "take", lambda self, n: self[:n])
improve(t, "dropwhile", lambda self, f: dropwhile(f, self))
improve(t, "takewhile", lambda self, f: takewhile(f, self))
improve(t, "cycle", lambda self: cycle(self))
improve(t, "repeat", lambda self, n=None: repeat(self, None))
improve(t, "reversed", lambda self: reversed(self))
improve(t, "sorted", lambda self: sorted(self))
improve(t, "zip", lambda self, other: zip(self, other))
improve(t, "unzip", lambda self: zip(*self))
improve(t, "index_zip", lambda self, other: zip(range(len(self)), self))
def _json():
JSON_ROOT_TYPES = [dict, list]
improve(str, "json", property(lambda self: json.loads(self)))
for t in JSON_ROOT_TYPES:
improve(t, "asjson", property(lambda self: json.dumps(self)))
def _requests():
class RequestsWrapper(object):
def __init__(self, url):
self.url = url
get = property(lambda self: partial(requests.get, (self.url)))
post = property(lambda self: partial(requests.post, (self.url)))
head = property(lambda self: partial(requests.head, (self.url)))
options = property(lambda self: partial(requests.options, (self.url)))
improve(str, "request", property(lambda self: RequestsWrapper(self)))
improve(str, "fetch", property(lambda self: requests.get(self).text))
DEFAULT_FEATURES = [
"better_formatting",
"functional_iterables"
]
EXTRA_FEATURES = [
"easter_eggs",
"json",
"requests",
]
class Installer(list):
"""Manages installed features."""
def install(self, feature):
if feature not in self:
try:
installer = getattr(sys.modules[__name__], "_"+feature)
except AttributeError:
raise ValueError("Invalid feature: '{}'".format(feature))
installer()
self.append(feature)
installer = Installer()
def install(extras=False):
features = DEFAULT_FEATURES[:]
if isinstance(extras, bool):
if extras:
features += EXTRA_FEATURES[:]
elif isinstance(extras, (tuple, list)):
features += extras[:]
elif isinstance(extras, str):
features += [extras]
else:
raise ValueError("Extras must be either bool or list")
for feature in features:
if feature not in DEFAULT_FEATURES+EXTRA_FEATURES:
raise ValueError("Unknown feature: '{}'".format(feature))
installer.install(feature)
if __name__ == "__main__":
pass
else:
install()
| {
"repo_name": "Dentosal/ImbaPython",
"path": "imba.py",
"copies": "1",
"size": "5086",
"license": "mit",
"hash": -4348412748602824700,
"line_mean": 34.8169014085,
"line_max": 101,
"alpha_frac": 0.6148250098,
"autogenerated": false,
"ratio": 3.536856745479833,
"config_test": false,
"has_no_keywords": false,
"few_assignments": false,
"quality_score": 0.9630114145762962,
"avg_score": 0.004313521903374031,
"num_lines": 142
} |
from forbiddenfruit import curse
from forbiddenfruit import reverse as reverse_the_curse
import inspect
import abc
import re
from types import FunctionType, CodeType
# this whole bit does unspeakable things,
# but so does the rest of this library.
# if there's an issue with extension methods
# not appearing, check here.
def getRegisteredABCsPurePython(cls):
return cls._abc_registry
if not hasattr(abc, 'ABC'):
getRegisteredABCs = getRegisteredABCsPurePython
else:
# detect python 3.7 C abc issues
class _ABCTester(abc.ABC):
pass
if hasattr(_ABCTester, '_abc_registry'):
# python <= 3.6, python 3.7 pure-Python ABCs
getRegisteredABCs = getRegisteredABCsPurePython
else:
# python 3.7 C abcs
def getRegisteredABCs(cls):
import _abc
dump = _abc._get_dump(cls)
for cls_ref in dump[0]:
# dereference the weakref,
# since this is a normal set of weakrefs,
# not a weak set
yield cls_ref()
def findObjectName(mname=None):
stack = inspect.stack()
if mname is None:
if 'should' not in stack[2][3]:
# go up a level if we've wrapped this method
mname = stack[3][3]
else:
mname = stack[2][3]
for frame in stack:
frame_info = inspect.getframeinfo(frame[0])
code = frame_info.code_context
if code is not None:
code = code[0]
if ('.'+mname) in code:
trimmed = code.strip()
idx = trimmed.index('.'+mname)
return trimmed[0:idx]
return None
def methodsToAvoid(subclasses):
res = []
for cls in subclasses:
res.extend([n for n, o
in cls.__dict__.items()
if inspect.ismethod(o) or inspect.isfunction(o)])
return res
def buildFunction(baseFunc, code=None, glbls=None,
name=None, defaults=None,
kwdefaults=None, closure=None,
annotations=None, doc=None, dct=None):
resf = None
def _f():
pass
if hasattr(_f, 'func_code'):
# Python 2.x
resf = FunctionType(code or baseFunc.func_code,
glbls or baseFunc.func_globals,
name or baseFunc.func_name,
defaults or baseFunc.func_defaults,
closure or baseFunc.func_closure)
resf.func_dict = dct or baseFunc.func_dict
resf.func_doc = doc or baseFunc.func_doc
else:
# Python 3.x
resf = FunctionType(code or baseFunc.__code__,
glbls or baseFunc.__globals__,
name or baseFunc.__name__,
defaults or baseFunc.__defaults__,
closure or baseFunc.__closure__)
resf.__kwdefaults__ = kwdefaults or baseFunc.__kwdefaults__
resf.__annotations__ = annotations or baseFunc.__annotations__
resf.__dict__ = dct or baseFunc.__dict__
resf.__doc__ = doc or baseFunc.__doc__
return resf
def buildCode(baseCode, argcount=None, kwonlyargcount=None,
nlocals=None, stacksize=None, flags=None,
code=None, consts=None, names=None,
varnames=None, filename=None, name=None,
firstlineno=None, lnotab=None, freevars=None,
cellvars=None):
resc = None
def _f():
pass
if hasattr(_f, 'func_code'):
# Python 2.x
resc = CodeType(argcount or baseCode.co_argcount,
nlocals or baseCode.co_nlocals,
stacksize or baseCode.co_stacksize,
flags or baseCode.co_flags,
code or baseCode.co_code,
consts or baseCode.co_consts,
names or baseCode.co_names,
varnames or baseCode.co_varnames,
filename or baseCode.co_filename,
name or baseCode.co_name,
firstlineno or baseCode.co_firstlineno,
lnotab or baseCode.co_lnotab,
freevars or baseCode.co_freevars,
cellvars or baseCode.co_cellvars)
else:
# Python 3.x
resc = CodeType(argcount or baseCode.co_argcount,
kwonlyargcount or baseCode.co_kwonlyargcount,
nlocals or baseCode.co_nlocals,
stacksize or baseCode.co_stacksize,
flags or baseCode.co_flags,
code or baseCode.co_code,
consts or baseCode.co_consts,
names or baseCode.co_names,
varnames or baseCode.co_varnames,
filename or baseCode.co_filename,
name or baseCode.co_name,
firstlineno or baseCode.co_firstlineno,
lnotab or baseCode.co_lnotab,
freevars or baseCode.co_freevars,
cellvars or baseCode.co_cellvars)
return resc
def getFunctionCode(func):
try:
return func.func_code
except AttributeError:
return func.__code__
# actually copy the method contents so that
# we can have a different name
def alias_method(new_name, f):
fr = inspect.currentframe().f_back # the current class
# duplicate the code with the new name
oc = getFunctionCode(f)
new_code = buildCode(oc, name=new_name)
# duplicate the function with the new name and add it to the class
fr.f_locals[new_name] = buildFunction(f, name=new_name, code=new_code)
class BaseMixin(object):
target_class = object
@staticmethod
def mix_method(target, method_name, method, method_type=None):
if method_type == 'static':
method = staticmethod(method)
elif method_type == 'class':
method = classmethod(method)
if method_name in target.__dict__:
reverse_the_curse(target, method_name)
if method_type is None and hasattr(method, '__func__'):
curse(target, method_name, method.__func__)
else:
curse(target, method_name, method)
@classmethod
def __mixin__(cls, target, method_type=None, avoid_list=[]):
# methods = inspect.getmembers(cls, inspect.ismethod)
methods = [(method_name, method) for method_name, method
in cls.__dict__.items()
if inspect.isfunction(method)]
try:
methods.append(('should_follow', cls.should_follow.__func__))
except AttributeError:
methods.append(('should_follow', cls.should_follow))
for method_name, method in methods:
in_base = method_name in BaseMixin.__dict__
is_should_follow = method_name == 'should_follow'
sf_in_target = 'should_follow' in dir(target)
if not in_base or (is_should_follow and not sf_in_target):
if method_name not in avoid_list:
cls.mix_method(target, method_name, method, method_type)
@classmethod
def mix(cls, target=None):
if target is None:
target = cls.target_class
cls.__mixin__(target)
attr_name = '_should_be_{0}.{1}'
attr_name = attr_name.format(cls.__module__,
cls.__name__)
cls.mix_method(target, attr_name, lambda: cls)
def submix(target_cls):
if issubclass(type(target_cls), abc.ABCMeta):
# print 'submixing {0}'.format(target_cls)
for impl_cls in getRegisteredABCs(target_cls):
if 'UserDict' in str(impl_cls):
pass # for some reason this class segfaults
else:
attr_name = '_should_be_{0}.{1}'
attr_name = attr_name.format(cls.__module__,
cls.__name__)
if attr_name not in dir(impl_cls):
subclasses = target.__subclasses__()
mta = methodsToAvoid(subclasses)
cls.__mixin__(impl_cls,
avoid_list=mta)
cls.mix_method(impl_cls, attr_name,
lambda: target_cls)
for subcls in target_cls.__subclasses__():
submix(subcls)
submix(target)
def should_follow(self, assertion, msg=None, **kwargs):
if msg is None:
# TODO(sross): figure out what the assertion was
msg = '{txt} failed to follow an assertion'
if not assertion:
obj_name = findObjectName()
if obj_name is None:
obj_name = '(unknown)'
raise AssertionError(msg.format(txt=obj_name,
self=self,
**kwargs))
class ObjectMixin(BaseMixin):
def should_be(self, target, method_name=None):
msg = '{txt} should have been {val}, but was {self}'
self.should_follow(self == target, msg, val=target)
def shouldnt_be(self, target):
msg = '{txt} should not have been {val}, but was anyway'
self.should_follow(self != target, msg, val=target)
def should_be_exactly(self, target):
msg = '{txt} should have been exactly {val}, but was {self}'
self.should_follow(self is target, msg, val=target)
def shouldnt_be_exactly(self, target):
msg = '{txt} should not have been exactly {val}, but was anyway'
self.should_follow(self is not target, msg, val=target)
def should_be_none(self):
msg = '{txt} should have been {val}, but was {self}'
self.should_follow(self is None, msg, val=None)
def shouldnt_be_none(self):
msg = '{txt} should not have been {val}, but was anyway'
self.should_follow(self is not None, msg, val=None)
def should_be_in(self, target):
msg = '{txt} should have been in {val}, but was not'
self.should_follow(self in target, msg, val=target)
def shouldnt_be_in(self, target):
msg = '{txt} should not have been in {val}, but was anyway'
self.should_follow(self not in target, msg, val=target)
def should_be_a(self, target):
msg = '{txt} should have been a {val}, but was a {self_class}'
if inspect.isclass(target):
self.should_follow(isinstance(self, target), msg,
val=target, self_class=type(self))
else:
# treat target as a string
str_target = str(target)
if '.' in str_target:
self_name = type(self).__module__ + '.' + type(self).__name__
self.should_follow(self_name == str_target, msg,
val=str_target, self_class=type(self))
else:
self.should_follow(type(self).__name__ == str_target, msg,
val=str_target, self_class=type(self))
def shouldnt_be_a(self, target):
msg = '{txt} should not have been a {val}, but was anyway'
if inspect.isclass(target):
self.should_follow(not isinstance(self, target), msg, val=target)
else:
# treat target as a string
str_target = str(target)
if '.' in str_target:
self_name = type(self).__module__ + '.' + type(self).__name__
self.should_follow(self_name != str_target, msg,
val=str_target)
else:
self.should_follow(type(self).__name__ != str_target, msg,
val=str_target)
def should_be_truthy(self):
msg = '{txt} should have been truthy, but was {self}'
self.should_follow(bool(self) is True, msg, val=True)
alias_method('should_be_true', should_be_truthy)
def should_be_falsy(self):
msg = '{txt} should not have falsy, but was anyway'
self.should_follow(bool(self) is False, msg, val=False)
alias_method('should_be_false', should_be_falsy)
def should_raise(self, target, *args, **kwargs):
if not hasattr(self, '__call__'):
msg_not_callable = ("{txt} ({self}) should have "
"been callable, but was not")
self.should_follow(False, msg_not_callable)
msg = "{txt}({args}, {kwargs}) should have raise {val}, but did not"
try:
self(*args, **kwargs)
except target:
pass
else:
kwa = ', '.join('{0}={1}'.format(k, v) for k, v in kwargs.items())
self.should_follow(False, msg,
val=target,
args=', '.join(repr(a) for a in args),
kwargs=kwa)
def should_raise_with_message(self, target, tmsg, *args, **kwargs):
if not hasattr(self, '__call__'):
msg_not_callable = ("{txt} ({self}) should have "
"been callable, but was not")
self.should_follow(False, msg_not_callable)
try:
self(*args, **kwargs)
except target as ex:
msg = ("{txt}({args}, {kwargs}) should have raised {val} "
"with a message matching /{re}/, but had a message of "
"'{act_msg}' instead")
kwa = ', '.join('{0}={1}'.format(k, v) for k, v in kwargs.items())
self.should_follow(re.match(tmsg, str(ex)), msg,
val=target.__name__,
re=tmsg,
act_msg=str(ex),
args=', '.join(repr(a) for a in args),
kwargs=kwa)
else:
msg = ("{txt}({args}, {kwargs}) should have raised "
"{val}, but did not")
kwa = ', '.join('{0}={1}'.format(k, v) for k, v in kwargs.items())
self.should_follow(False, msg,
val=target.__name__,
args=', '.join(repr(a) for a in args),
kwargs=kwa)
class NoneTypeMixin(BaseMixin):
target_class = type(None)
source_class = ObjectMixin
_already_loaded = False
# this works around None methods being 'unbound'
@classmethod
def _load_methods(cls, src=ObjectMixin):
# python doesn't close in loops, grumble...
def factory(method_name, method):
if hasattr(method, '__func__'):
# Python 2.x
def new_method(*args, **kwargs):
method.__func__(None, *args, **kwargs)
return new_method
else:
# Python 3.x
def new_method(*args, **kwargs):
method(None, *args, **kwargs)
return new_method
methods = [(method_name, method) for method_name, method
in src.__dict__.items()
if inspect.isfunction(method)]
try:
methods.append(('should_follow', cls.should_follow.__func__))
except AttributeError:
methods.append(('should_follow', cls.should_follow))
for method_name, method in methods:
new_method = factory(method_name, method)
setattr(cls, method_name, staticmethod(new_method))
@classmethod
def __mixin__(cls, target):
if not cls._already_loaded:
cls._load_methods(src=cls.source_class)
methods = [(meth_name, meth) for (meth_name, meth)
in cls.__dict__.items()
if isinstance(meth, staticmethod)]
for method_name, method in methods:
if (method_name not in dir(BaseMixin)
or method_name == 'should_follow'):
cls.mix_method(target, method_name, method,
method_type='keep')
| {
"repo_name": "DirectXMan12/should_be",
"path": "should_be/core.py",
"copies": "1",
"size": "16377",
"license": "isc",
"hash": 3052333326164620000,
"line_mean": 36.2204545455,
"line_max": 78,
"alpha_frac": 0.5220125786,
"autogenerated": false,
"ratio": 4.191707192219094,
"config_test": false,
"has_no_keywords": false,
"few_assignments": false,
"quality_score": 0.5213719770819094,
"avg_score": null,
"num_lines": null
} |
from forcegp_module import GaussianProcess
from quippy import AtomsList
import random
import pickle
from forcegp_module import GaussianProcess, iv_default_params
import numpy as np
tmp = iv_default_params()
exps = tmp[:,0]
r_cuts = tmp[:,1]
database_whole = AtomsList('silicon_db.xyz')
teach_idx = random.sample(range(len(database_whole)), 40)
teaching_data = database_whole[teach_idx]
gp = GaussianProcess(theta0 = 2.0, nugget = 0.01, iv_params=[exps, r_cuts])
ivs_db, eigs_db, y_db, iv_corr_db, iv_means, eig_means, eig_stds = gp.atomsdb_get_features(teaching_data, return_features=True)
results = {}
results['ivs_db'] = ivs_db
results['eigs_db'] = eigs_db
results['y_db'] = y_db
results['iv_corr_db'] = iv_corr_db
pickle.dump(results, open('Si-50db.pkl', 'w'))
1/0
gp.ivs = ivs_db
gp.eigs = eigs_db
gp.iv_corr = iv_corr_db
gp.y = y_db
gp.iv_means, gp.eig_means, gp.eig_stds = iv_means, eig_means, eig_stds
pf = []
for corr in [0.1]: #in np.linspace(0.1,10,2, endpoint=True):
gp.theta0 = corr
gp.fit_sollich()
pred_idx = random.sample(range(len(database_whole)), 2)
pred_data = database_whole[pred_idx]
predicted_forces = gp.predict_sollich(atomslist=pred_data)
pf.append(predicted_forces)
# actual_forces =
#print predicted_forces
| {
"repo_name": "marcocaccin/MarcoGP",
"path": "gogogo.py",
"copies": "1",
"size": "1277",
"license": "apache-2.0",
"hash": 2170469560537993500,
"line_mean": 27.3777777778,
"line_max": 127,
"alpha_frac": 0.6961628818,
"autogenerated": false,
"ratio": 2.6114519427402865,
"config_test": false,
"has_no_keywords": false,
"few_assignments": false,
"quality_score": 0.38076148245402863,
"avg_score": null,
"num_lines": null
} |
from forecaster import Forecaster
from time_series.fuzzy_time_series import Fuzzy_time_series
from time_series.time_series import Time_Series
from time_series.forex_tick import Forex_Tick
from time_series.enrollment_tick import Enrollment_tick
from time_series.taiex_tick import Taiex_tick
from random_walk.random_walk import Random_walk
import itertools
class Results(object):
def __init__(self):
self.moving_window_max = 2
self.order_max = 2
def get_results(self):
#eurusd = self.__eval("EURUSD","data/EURUSD_day.csv", "data/eval.csv", Forex_Tick, False, 1)
#taiex = self.__eval("TAIEX","data/taiex/taiex.json", "data/taiex/eval_taiex.json", Taiex_tick, False, 1)
#enrollment = self.__eval("ENROLLMENT","data/enrollment/alabama.csv", "data/enrollment/alabama.csv", Enrollment_tick, False, 1)
#eurusd_changes = self.__eval("EURUSD Changes","data/EURUSD_day.csv", "data/eval.csv", Forex_Tick, False, 1)
taiex_changes = self.__eval("TAIEX Changes","data/taiex/taiex.json", "data/taiex/eval_taiex.json", Taiex_tick, False, 1)
#enrollment_changes = self.__eval("ENROLLMENT Changes","data/enrollment/alabama.csv", "data/enrollment/alabama.csv", Enrollment_tick, False, 1)
analyse = taiex_changes
actual = self.__result(analyse, "actual")
formatted = self.__formatted(actual)
print formatted
def __formatted(self, data):
tabbed = '\t'.join(data)
return '\n'.join([line[1:] if line[0:1] == '\t' else line for line in tabbed.split('\n')])
def __result(self, data, attr):
for idx, orders in enumerate(data):
for order in orders:
if order:
if idx == 0:
yield order.title
else:
yield str(getattr(order, attr))
yield '\n'
def __eval(self, name, training_file_loc, eval_file_loc, tick_builder, analyse_changes, confidence_threshold):
results = []
for window_len in xrange(1,self.order_max):
time_series = Time_Series(tick_builder, window_len)
time_series.import_history(training_file_loc, analyse_changes)
forecaster = Forecaster(analyse_changes)
fts = Fuzzy_time_series(confidence_threshold)
fts.build_fts(0, time_series)
for order in xrange(1,self.moving_window_max):
results.append(self.__get_resuts(name, order, window_len, forecaster, fts, eval_file_loc))
return itertools.izip_longest(*results, fillvalue=None)
def __get_resuts(self, name, order, window_len, forecaster, fts, eval_file_loc):
fts.add_order(order)
title = name + ": moving window length: " + str(window_len) +", order: " + str(order)
for result in forecaster.evaluate_model(fts, eval_file_loc, order=order):
result.title = title
yield result
if __name__ == "__main__":
results = Results()
results.get_results() | {
"repo_name": "mikesligo/FYP-fuzzy-time-series",
"path": "results.py",
"copies": "1",
"size": "3021",
"license": "mit",
"hash": 515681836008360500,
"line_mean": 44.1044776119,
"line_max": 151,
"alpha_frac": 0.6285998014,
"autogenerated": false,
"ratio": 3.4058624577226606,
"config_test": false,
"has_no_keywords": false,
"few_assignments": false,
"quality_score": 0.453446225912266,
"avg_score": null,
"num_lines": null
} |
from forecast import make_job_file, JobState, process_arguments, load_sys_cfg
import json
import logging
import sys,glob
import os.path as osp
simulations_path = osp.abspath('simulations') # copy here job_id/wfc
catalog_path = osp.join(simulations_path,'catalog.json')
try:
catalog = json.load(open(catalog_path,'r'))
except:
print('Cannot open catalog at %s, creating new.' % catalog_path)
catalog={}
if __name__ == '__main__':
if len(sys.argv) < 2:
print('Usage: ./recover_catalog.sh 1.json 2.json ....')
print('x.json are inputs to forecast.sh as from wrfxctrl, starting with /, no spaces')
print('Example: ./recover_catalog.sh ~/Projects/wrfxctrl/jobs/*.json')
print('Important: must be run from the wrfxpy directory. Before using:')
print('In wrfxweb/fdds/simulations: tar cvfz ~/c.tgz <simulations to recove>/*.json catalog.json')
print('Transfer the file c.tgz and untar here')
print('On exit, ./simulations/catalog.json will be updated')
sys.exit(1)
sims = glob.glob(osp.join(simulations_path,'wfc-*'))
state = {}
desc = {}
for s in sims:
job_id = osp.basename(s)
if job_id in catalog:
state[job_id]='Already in catalog'
desc[job_id] = catalog[job_id]['description']
else:
state[job_id]='No catalog entry'
desc[job_id] = 'Unknown'
for js_path in sys.argv[1:]:
# print js_path
js = json.load(open(js_path,'r'))
description = js['postproc']['description']
#print json.dumps(js, indent=4, separators=(',', ': '))
jsb=osp.basename(js_path)
m=glob.glob(osp.join(simulations_path,'*','wfc-'+jsb))
print('%s simulations found for %s file %s' %
(len(m), description, js_path))
for mf in m:
#print mf
manifest=osp.basename(mf)
job_id=osp.basename(osp.split(mf)[0])
print '%s found in %s' % (manifest, job_id)
manifest_js=json.load(open(mf,'r'))
from_utc = '999-99-99_99:99:99'
to_utc = '0000-00-00_00:00:00'
for domain in manifest_js:
for time in manifest_js[domain]:
from_utc = min(from_utc,time)
to_utc = max(to_utc,time)
new={'manifest_path':osp.join(job_id,manifest),
'description':js['postproc']['description'],
'from_utc':from_utc,
'to_utc':to_utc}
if job_id in catalog:
if catalog[job_id]==new:
print('Catalog entry already exists, no change.')
state[job_id] = 'No change'
else:
print('Replacing catalog entry %s' % job_id)
print('Old value:\n%s' %
json.dumps(catalog[job_id], indent=4, separators=(',', ': ')))
print('New value:\n%s' %
json.dumps(new, indent=4, separators=(',', ': ')))
state[job_id] = 'Replaced'
else:
print('Creating catalog entry %s' % job_id)
print('New value:\n%s' %
json.dumps(new, indent=4, separators=(',', ': ')))
state[job_id] = 'Recovered'
catalog[job_id]=new
desc[job_id] = catalog[job_id]['description']
print 'Writing catalog at %s' % catalog_path
json.dump(catalog, open(catalog_path,'w'), indent=4, separators=(',', ': '))
for job_id in sorted(state):
print '%s: %s: %s' % (job_id, desc[job_id], state[job_id])
| {
"repo_name": "vejmelkam/wrfxpy",
"path": "src/recover_catalog.py",
"copies": "1",
"size": "3721",
"license": "mit",
"hash": 1975557905202621400,
"line_mean": 42.7764705882,
"line_max": 106,
"alpha_frac": 0.5283525934,
"autogenerated": false,
"ratio": 3.564176245210728,
"config_test": false,
"has_no_keywords": false,
"few_assignments": false,
"quality_score": 0.45925288386107277,
"avg_score": null,
"num_lines": null
} |
from forecastio.utils import UnicodeMixin, PropertyUnavailable
import datetime
import requests
class Forecast(UnicodeMixin):
def __init__(self, data, response, headers):
self.response = response
self.http_headers = headers
self.json = data
self._alerts = []
for alertJSON in self.json.get('alerts', []):
self._alerts.append(Alert(alertJSON))
def update(self):
r = requests.get(self.response.url)
self.json = r.json()
self.response = r
def currently(self):
return self._forcastio_data('currently')
def minutely(self):
return self._forcastio_data('minutely')
def hourly(self):
return self._forcastio_data('hourly')
def daily(self):
return self._forcastio_data('daily')
def offset(self):
return self.json['offset']
def alerts(self):
return self._alerts
def _forcastio_data(self, key):
keys = ['minutely', 'currently', 'hourly', 'daily']
try:
if key not in self.json:
keys.remove(key)
url = "%s&exclude=%s%s" % (self.response.url.split('&')[0],
','.join(keys), ',alerts,flags')
response = requests.get(url).json()
self.json[key] = response[key]
if key == 'currently':
return ForecastioDataPoint(self.json[key])
else:
return ForecastioDataBlock(self.json[key])
except:
if key == 'currently':
return ForecastioDataPoint()
else:
return ForecastioDataBlock()
class ForecastioDataBlock(UnicodeMixin):
def __init__(self, d=None):
d = d or {}
self.summary = d.get('summary')
self.icon = d.get('icon')
self.data = [ForecastioDataPoint(datapoint)
for datapoint in d.get('data', [])]
def __unicode__(self):
return '<ForecastioDataBlock instance: ' \
'%s with %d ForecastioDataPoints>' % (self.summary,
len(self.data),)
class ForecastioDataPoint(UnicodeMixin):
def __init__(self, d={}):
self.d = d
try:
self.time = datetime.datetime.utcfromtimestamp(int(d['time']))
self.utime = d['time']
except:
pass
try:
sr_time = int(d['sunriseTime'])
self.sunriseTime = datetime.datetime.utcfromtimestamp(sr_time)
except:
self.sunriseTime = None
try:
ss_time = int(d['sunsetTime'])
self.sunsetTime = datetime.datetime.utcfromtimestamp(ss_time)
except:
self.sunsetTime = None
def __getattr__(self, name):
try:
return self.d[name]
except KeyError:
raise PropertyUnavailable(
"Property '{}' is not valid"
" or is not available for this forecast".format(name)
)
def __unicode__(self):
return '<ForecastioDataPoint instance: ' \
'%s at %s>' % (self.summary, self.time,)
class Alert(UnicodeMixin):
def __init__(self, json):
self.json = json
def __getattr__(self, name):
try:
return self.json[name]
except KeyError:
raise PropertyUnavailable(
"Property '{}' is not valid"
" or is not available for this forecast".format(name)
)
def __unicode__(self):
return '<Alert instance: {0} at {1}>'.format(self.title, self.time)
| {
"repo_name": "treeeferrrr/frogcast",
"path": "app/lib/forecastio/models.py",
"copies": "5",
"size": "3642",
"license": "apache-2.0",
"hash": -6635552961171510000,
"line_mean": 27.2325581395,
"line_max": 75,
"alpha_frac": 0.5345963756,
"autogenerated": false,
"ratio": 4.157534246575342,
"config_test": false,
"has_no_keywords": false,
"few_assignments": false,
"quality_score": 1,
"avg_score": 0.0020789288231148695,
"num_lines": 129
} |
from forecast.ZipCodeUtil import latLonNameForZipcode
class Location(object):
"""
A latitude/longitude-based location with optional zip code and name information.
"""
def __init__(self, zipOrLatLon):
"""
:param zipOrLatLon: location to get the forecast for. either a zip code string or a 2-tuple of latitude and
longitude strings. ex: '01002' or ('42.375370', '-72.519249').
"""
if type(zipOrLatLon) == str:
(lat, lon, name) = latLonNameForZipcode(zipOrLatLon)
self.zipcode = zipOrLatLon
self.latitude = lat
self.longitude = lon
self.name = name
elif (type(zipOrLatLon) == list or type(zipOrLatLon) == tuple) and len(zipOrLatLon) == 2 \
and type(zipOrLatLon[0]) == str \
and type(zipOrLatLon[1]) == str:
self.zipcode = None
self.latitude = zipOrLatLon[0]
self.longitude = zipOrLatLon[1]
self.name = None
else:
raise ValueError("location wasn't a zip code or comma-separated lat/lon: {}".format(zipOrLatLon))
def __repr__(self):
zipOrLatLon = self.zipcode if self.zipcode else (self.latitude, self.longitude)
return '{cls}({zipOrLatLon!r})'.format(cls=self.__class__.__name__, zipOrLatLon=zipOrLatLon)
def latLonTruncated(self):
# truncate to four digits after decimal
latStr = self.latitude[:self.latitude.index('.') + 5]
lonStr = self.longitude[:self.longitude.index('.') + 5]
return '{}, {}'.format(latStr, lonStr)
| {
"repo_name": "matthewcornell/peepweather",
"path": "forecast/Location.py",
"copies": "1",
"size": "1605",
"license": "apache-2.0",
"hash": -8864812896521764000,
"line_mean": 38.1463414634,
"line_max": 115,
"alpha_frac": 0.600623053,
"autogenerated": false,
"ratio": 3.75,
"config_test": false,
"has_no_keywords": false,
"few_assignments": false,
"quality_score": 0.4850623053,
"avg_score": null,
"num_lines": null
} |
from foreman import define_parameter
from templates import pods
(define_parameter('image-version')
.with_doc('HAProxy image version.')
.with_default('2.0.3'))
@pods.app_specifier
def haproxy_app(_):
return pods.App(
name='haproxy',
exec=[
'/usr/local/sbin/haproxy',
'-f', '/etc/haproxy/haproxy.cfg',
],
volumes=[
pods.Volume(
name='etc-hosts-volume',
path='/etc/hosts',
host_path='/etc/hosts',
),
pods.Volume(
name='haproxy-volume',
path='/etc/haproxy',
data='haproxy-volume/haproxy-config.tar.gz',
),
],
ports=[
pods.Port(
name='web',
protocol='tcp',
port=8443,
host_port=443,
),
],
)
@pods.image_specifier
def haproxy_image(parameters):
return pods.Image(
image_build_uri='docker://haproxy:%s' % parameters['image-version'],
name='haproxy',
app=parameters['haproxy_app'],
)
haproxy_image.specify_image.depend('haproxy_app/specify_app')
haproxy_image.build_image.depend('//host/docker2aci:install')
| {
"repo_name": "clchiou/garage",
"path": "shipyard/rules/third-party/haproxy/build.py",
"copies": "1",
"size": "1265",
"license": "mit",
"hash": -5341915690565625000,
"line_mean": 22.4259259259,
"line_max": 76,
"alpha_frac": 0.5122529644,
"autogenerated": false,
"ratio": 3.6142857142857143,
"config_test": false,
"has_no_keywords": false,
"few_assignments": false,
"quality_score": 0.9626538678685714,
"avg_score": 0,
"num_lines": 54
} |
from foreman import get_relpath, rule
from garage import scripts
from templates.common import define_distro_packages
GRAFANA_DEB = 'grafana_5.1.4_amd64.deb'
GRAFANA_DEB_URI = 'https://s3-us-west-2.amazonaws.com/grafana-releases/release/grafana_5.1.4_amd64.deb'
GRAFANA_DEB_CHECKSUM = 'sha256-bbec4cf6112c4c2654b679ae808aaad3b3e4ba39818a6d01f5f19e78946b734e'
define_distro_packages([
'adduser',
'libfontconfig',
])
@rule
@rule.depend('//base:build')
@rule.depend('install_packages')
def build(parameters):
drydock_src = parameters['//base:drydock'] / get_relpath()
scripts.mkdir(drydock_src)
with scripts.directory(drydock_src):
deb_path = drydock_src / GRAFANA_DEB
if not deb_path.exists():
scripts.wget(GRAFANA_DEB_URI, deb_path)
scripts.ensure_checksum(deb_path, GRAFANA_DEB_CHECKSUM)
with scripts.using_sudo():
scripts.execute(['dpkg', '--install', deb_path])
@rule
@rule.depend('build')
@rule.reverse_depend('//base:tapeout')
def tapeout(parameters):
with scripts.using_sudo():
rootfs = parameters['//base:drydock/rootfs']
scripts.rsync(
[
'/usr/sbin/grafana-server',
'/usr/share/grafana',
],
rootfs,
relative=True,
)
@rule
@rule.depend('//base:tapeout')
def trim_usr(parameters):
rootfs = parameters['//base:drydock/rootfs']
with scripts.using_sudo():
scripts.rm(rootfs / 'usr/lib', recursive=True)
scripts.rm(rootfs / 'usr/local/lib', recursive=True)
| {
"repo_name": "clchiou/garage",
"path": "shipyard/rules/third-party/grafana/build.py",
"copies": "1",
"size": "1581",
"license": "mit",
"hash": -5107738849125998000,
"line_mean": 27.2321428571,
"line_max": 103,
"alpha_frac": 0.6470588235,
"autogenerated": false,
"ratio": 3.0403846153846152,
"config_test": false,
"has_no_keywords": false,
"few_assignments": false,
"quality_score": 0.41874434388846155,
"avg_score": null,
"num_lines": null
} |
from forestry_game.models import Level, Report
from django.contrib.auth.models import User
from rest_framework import serializers
class RegisterSerializer(serializers.ModelSerializer):
class Meta:
model = User
fields = ('id', 'username', 'password', 'email')
def create(self, validated_data):
user = User.objects.create(**validated_data)
user.set_password(validated_data["password"])
user.save()
return user
class LoginSerializer(serializers.ModelSerializer):
class Meta:
model = User
fields = ('id', 'username', 'email', 'password')
# LEVELSERIALIZER NOT IN USE RIGHT NOW
class LevelSerializer(serializers.ModelSerializer):
class Meta:
model = Level
fields = ('id', 'name', 'timestamp', 'last_edited', 'mapdata', 'mapinfo', 'creator')
class MapInfoSerializer(serializers.ModelSerializer):
creator = serializers.CharField(source='creator.username', read_only=True)
class Meta:
model = Level
fields = ('id', 'name', 'mapinfo', 'creator', 'last_edited')
class MapDataSerializer(serializers.ModelSerializer):
class Meta:
model = Level
fields = ('id', 'name', 'mapdata')
class ReportSerializer(serializers.ModelSerializer):
user = serializers.CharField(source='user.username', read_only=True)
level = serializers.CharField(source='level.name', read_only=True)
m_score = serializers.CharField(source='score', read_only=True)
class Meta:
model = Report
fields = ('id', 'timestamp', 'distance',
'gas_consumption', 'duration', 'logs',
'user', 'level', 'm_score',
'driving_unloaded_time', 'driving_loaded_time',
'loading_and_unloading', 'idling', 'driving_forward',
'reverse', 'driving_unloaded_distance', 'driving_loaded_distance',
'fuel_cost', 'worker_salary', 'loads_transported',
'logs_deposited', 'total_volume', 'productivity')
| {
"repo_name": "nime88/forestry-game",
"path": "forestry_game/serializers.py",
"copies": "1",
"size": "1801",
"license": "mit",
"hash": -7813334450411069000,
"line_mean": 31.7636363636,
"line_max": 86,
"alpha_frac": 0.7196002221,
"autogenerated": false,
"ratio": 3.3538175046554937,
"config_test": false,
"has_no_keywords": false,
"few_assignments": false,
"quality_score": 0.4573417726755493,
"avg_score": null,
"num_lines": null
} |
from forge import Forge
import logging
import waiting
import pytest
_logger = logging.getLogger(__name__)
@pytest.fixture
def forge(request):
returned = Forge()
@request.addfinalizer
def cleanup():
returned.verify()
returned.restore_all_replacements()
return returned
@pytest.fixture
def timeline(forge):
class VirtualTimeline(object):
class FirstTestException(Exception):
pass
class SecondTestException(Exception):
pass
def __init__(self):
super(VirtualTimeline, self).__init__()
self.virtual_time = 0
self.sleeps_performed = []
self.predicate_satisfied = False
self.satisfy_at_time = None
self.satisfy_after_time = None
self.predicate_sleep = 0
def sleep(self, delta):
self.sleeps_performed.append(delta)
self.virtual_time += delta
assert 1000 > len(self.sleeps_performed), 'Infinite loop'
def time(self):
return self.virtual_time
def predicate(self):
if self.satisfy_at_time is not None and self.satisfy_at_time == self.virtual_time:
self.predicate_satisfied = True
if self.satisfy_after_time is not None and self.satisfy_after_time <= self.virtual_time:
self.predicate_satisfied = True
self.virtual_time += self.predicate_sleep
_logger.debug('Predicate: time is now %s', self.virtual_time)
return self.predicate_satisfied
def raising_predicate(self):
if self.virtual_time == 0:
raise self.FirstTestException()
return self.predicate()
def raising_two_exceptions_predicate(self):
if self.virtual_time == 1:
raise self.SecondTestException()
return self.raising_predicate()
returned = VirtualTimeline()
forge.replace_with(waiting.time_module, "sleep", returned.sleep)
forge.replace_with(waiting.time_module, "time", returned.time)
forge.replace_with(waiting.deadlines.time_module, "time", returned.time)
return returned
@pytest.fixture
def predicates(forge):
return [forge.create_wildcard_mock() for i in range(5)]
| {
"repo_name": "vmalloc/waiting",
"path": "tests/conftest.py",
"copies": "1",
"size": "2293",
"license": "bsd-3-clause",
"hash": 3010993035834325500,
"line_mean": 26.2976190476,
"line_max": 100,
"alpha_frac": 0.617531618,
"autogenerated": false,
"ratio": 4.238447319778189,
"config_test": true,
"has_no_keywords": false,
"few_assignments": false,
"quality_score": 0.5355978937778189,
"avg_score": null,
"num_lines": null
} |
from forge import UnexpectedCall, ExpectedEventsNotFound, SignatureException
from .ut_utils import ForgeTestCase
class RecordReplayTest(ForgeTestCase):
def setUp(self):
super(RecordReplayTest, self).setUp()
def some_function(a, b, c):
raise NotImplementedError()
self.stub = self.forge.create_function_stub(some_function)
def tearDown(self):
self.assertNoMoreCalls()
super(RecordReplayTest, self).tearDown()
def test__record_replay_valid(self):
self.stub(1, 2, 3)
self.forge.replay()
self.stub(1, 2, 3)
self.forge.verify()
def test__call_counts(self):
for i in range(2):
self.stub(1, 2, 3)
self.stub(1, 2, 3)
self.assertEqual(self.stub.__forge__.call_count, 0)
self.forge.replay()
self.stub(1, 2, 3)
self.assertEqual(self.stub.__forge__.call_count, 1)
self.stub(1, 2, 3)
self.assertEqual(self.stub.__forge__.call_count, 2)
self.assertIn("2 times", str(self.stub))
self.forge.reset()
self.assertEqual(self.stub.__forge__.call_count, 0)
def test__record_replay_different_not_equal_value(self):
self.stub(1, 2, 3)
self.forge.replay()
with self.assertRaises(UnexpectedCall) as caught:
self.stub(1, 2, 6)
exc = caught.exception
self.assertEqual(len(exc.expected), 1)
self.assertEqual(exc.expected[0].args, dict(a=1, b=2, c=3))
self.assertEqual(exc.got.args, dict(a=1, b=2, c=6))
self.assertExpectedNotMet([self.stub])
def test__record_replay_different_more_args(self):
self.stub(1, 2, 3)
self.forge.replay()
with self.assertRaises(SignatureException):
self.stub(1, 2, 3, 4, 5)
self.assertExpectedNotMet([self.stub])
def test__record_replay_different_less_args(self):
self.stub(1, 2, 3)
self.forge.replay()
with self.assertRaises(SignatureException):
self.stub()
self.assertExpectedNotMet([self.stub])
def test__record_replay_no_actual_call(self):
self.stub(1, 2, 3)
self.forge.replay()
self.assertExpectedNotMet([self.stub])
def test__replay_queue_empty(self):
self.stub(1, 2, 3)
self.forge.replay()
self.stub(1, 2, 3)
with self.assertRaises(UnexpectedCall) as caught:
self.stub(1, 2, 3)
self.assertEqual(caught.exception.expected, [])
self.assertIs(caught.exception.got.target, self.stub)
self.assertNoMoreCalls()
self.forge.verify()
def test__naming_stubs(self):
def some_other_function():
raise NotImplementedError()
stub2 = self.forge.create_function_stub(some_other_function)
self.stub(1, 2, 3)
self.forge.replay()
with self.assertRaises(UnexpectedCall) as caught:
stub2()
exc = caught.exception
for r in (str, repr):
self.assertIn('some_function', r(exc.expected))
self.assertIn('some_other_function', r(exc.got))
self.assertIn('some_function', str(exc))
self.assertIn('some_other_function', str(exc))
self.forge.reset()
def test__record_self_argument(self):
def some_func(bla, self, bla2):
pass
stub = self.forge.create_function_stub(some_func)
stub(bla=1, self=2, bla2=3)
stub(1, 2, 3)
self.forge.replay()
stub(bla=1, self=2, bla2=3)
stub(1, 2, 3)
def assertExpectedNotMet(self, stubs):
self.assertGreater(len(stubs), 0)
with self.assertRaises(ExpectedEventsNotFound) as caught:
self.forge.verify()
self.assertEqual(len(caught.exception.events), len(stubs))
expected = self.forge.queue.get_expected()
for stub, exception_call in zip(stubs, caught.exception.events):
expected_call = expected.pop()
self.assertIs(expected_call, exception_call)
self.assertIs(expected_call.target, stub)
self.assertEqual(len(expected), 0)
self.forge.queue.clear()
| {
"repo_name": "vmalloc/pyforge",
"path": "tests/test__record_replay.py",
"copies": "1",
"size": "4152",
"license": "bsd-3-clause",
"hash": 905600240153797400,
"line_mean": 38.1698113208,
"line_max": 76,
"alpha_frac": 0.6078998073,
"autogenerated": false,
"ratio": 3.6135770234986944,
"config_test": true,
"has_no_keywords": false,
"few_assignments": false,
"quality_score": 0.9710725594528977,
"avg_score": 0.0021502472539434055,
"num_lines": 106
} |
from forgewiki.command.base import WikiCommand
from forgewiki.command.wiki2markdown.extractors import MySQLExtractor
from forgewiki.command.wiki2markdown.loaders import MediawikiLoader
from allura.command import base as allura_base
class Wiki2MarkDownCommand(WikiCommand):
"""Import MediaWiki to Allura Wiki tool"""
min_args = 1
max_args = None
summary = 'Import wiki from mediawiki-dump to allura wiki'
parser = WikiCommand.standard_parser(verbose=True)
parser.add_option('-e', '--extract-only', action='store_true',
dest='extract',
help='Store data from the mediawiki-dump '
'on the local filesystem; not load into Allura')
parser.add_option('-l', '--load-only', action='store_true', dest='load',
help='Load into Allura previously-extracted data')
parser.add_option('-d', '--dump-dir', dest='dump_dir', default='',
help='Directory for dump files')
parser.add_option('-n', '--neighborhood', dest='nbhd', default='',
help='Neighborhood name to load data')
parser.add_option('-p', '--project', dest='project', default='',
help='Project shortname to load data into')
parser.add_option('-s', '--source', dest='source', default='',
help='Database type to extract from (only mysql for now)')
parser.add_option('--db_name', dest='db_name', default='mediawiki',
help='Database name')
parser.add_option('--host', dest='host', default='localhost',
help='Database host')
parser.add_option('--port', dest='port', type='int', default=0,
help='Database port')
parser.add_option('--user', dest='user', default='',
help='User for database connection')
parser.add_option('--password', dest='password', default='',
help='Password for database connection')
parser.add_option('-a', '--attachments-dir', dest='attachments_dir',
help='Path to directory with mediawiki attachments dump',
default='')
def command(self):
self.basic_setup()
self.handle_options()
if self.options.extract:
self.extractor.extract()
if self.options.load:
self.loader = MediawikiLoader(self.options)
self.loader.load()
def handle_options(self):
if not self.options.dump_dir:
allura_base.log.error('You must specify directory for dump files')
exit(2)
if not self.options.extract and not self.options.load:
# if action doesn't specified - do both
self.options.extract = True
self.options.load = True
if self.options.load and (not self.options.project
or not self.options.nbhd):
allura_base.log.error('You must specify neighborhood and project '
'to load data')
exit(2)
if self.options.extract:
if self.options.source == 'mysql':
self.extractor = MySQLExtractor(self.options)
elif self.options.source in ('sqlite', 'postgres', 'sql-dump'):
allura_base.log.error('This source not implemented yet.'
'Only mysql for now')
exit(2)
else:
allura_base.log.error('You must specify valid data source')
exit(2)
if not self.options.attachments_dir:
allura_base.log.error('You must specify path to directory '
'with mediawiki attachmets dump.')
exit(2)
| {
"repo_name": "Bitergia/allura",
"path": "ForgeWiki/forgewiki/command/wiki2markdown/__init__.py",
"copies": "2",
"size": "3724",
"license": "apache-2.0",
"hash": 8130948789373191000,
"line_mean": 44.4146341463,
"line_max": 78,
"alpha_frac": 0.5797529538,
"autogenerated": false,
"ratio": 4.386336866902238,
"config_test": false,
"has_no_keywords": false,
"few_assignments": false,
"quality_score": 0.5966089820702238,
"avg_score": null,
"num_lines": null
} |
from formaggio.models import get_formaggio_form_model
from rest_framework import serializers
from ..models import FormaggioField
FormaggioForm = get_formaggio_form_model()
class FormaggioFieldReadSerializer(serializers.ModelSerializer):
class Meta:
model = FormaggioField
fields = (
'id',
'index',
'label',
'kind',
'hint',
'extra',
'mandatory',
)
class FormaggioFormReadSerializer(serializers.ModelSerializer):
fields = serializers.SerializerMethodField(method_name='get_fields_field')
class Meta:
model = FormaggioForm
fields = (
'id',
'title',
'fields',
)
def get_fields_field(self, form):
queryset = FormaggioField.objects.filter(form=form)
return FormaggioFieldReadSerializer(
instance=queryset,
many=True,
read_only=True
).data
class FormaggioFieldSerializer(serializers.ModelSerializer):
form = serializers.PrimaryKeyRelatedField(
queryset=get_formaggio_form_model().objects.all()
)
class Meta:
model = FormaggioField
fields = [
'id',
'form',
'index',
'label',
'kind',
'hint',
'mandatory'
]
| {
"repo_name": "scotu/django-formaggio",
"path": "formaggio/drf_serializers/form_builder.py",
"copies": "1",
"size": "1375",
"license": "bsd-3-clause",
"hash": -5073388909864157000,
"line_mean": 24.9433962264,
"line_max": 78,
"alpha_frac": 0.5650909091,
"autogenerated": false,
"ratio": 4.217791411042945,
"config_test": false,
"has_no_keywords": false,
"few_assignments": false,
"quality_score": 0.5282882320142945,
"avg_score": null,
"num_lines": null
} |
#from formalchemy import FieldSet
from flask.ext.wtf import (Form, TextField, Required,
TextAreaField, FloatField,
BooleanField, DateTimeField, widgets, validators)
from wtforms.ext.sqlalchemy.fields import QuerySelectField
from cfmi.billing.models import User, Session, Problem, Project, Subject
# class DatePickerWidget(widgets.TextInput):
# """
# TextInput widget that adds a 'datepicker' class to the html input
# element; this makes it easy to write a jQuery selector that adds a
# UI widget for date picking.
# """
# def __call__(self, field, **kwargs):
# c = kwargs.pop('class', '') or kwargs.pop('class_', '')
# kwargs['class'] = u'datepicker %s' % c
# return super(DatePickerWidget, self).__call__(field, **kwargs)
class SessionForm(Form):
user = QuerySelectField("Scan booked by")
sched_start = DateTimeField("Scheduled start")
sched_end = DateTimeField("Scheduled end")
approved = BooleanField()
cancelled = BooleanField()
project = QuerySelectField()
subject = QuerySelectField()
start = DateTimeField("Actual start time", validators=[validators.optional()])
end = DateTimeField("Actual end time", validators=[validators.optional()])
notes = TextAreaField()
def __init__(self, *args, **kwargs):
Form.__init__(self, *args, **kwargs)
self.user.query = User.query.order_by(User.name)
self.project.query = Project.query.order_by(Project.name)
self.subject.query = Subject.query.order_by(Subject.name)
class ROSessionForm(SessionForm):
pass
class ProblemRequestForm(Form):
problem = TextAreaField("Describe the nature of our error:", [Required()])
duration = FloatField("What is the accurate duration, in hours, of this scan?", [Required()])
class ProblemForm(Form):
description = TextAreaField("What went wrong that extended the scan?")
duration = FloatField("Enter the accurate total duration:")
| {
"repo_name": "nocko/cfmi",
"path": "cfmi/billing/forms.py",
"copies": "1",
"size": "2014",
"license": "bsd-3-clause",
"hash": 4112521522753452000,
"line_mean": 40.9583333333,
"line_max": 97,
"alpha_frac": 0.6742800397,
"autogenerated": false,
"ratio": 4.036072144288577,
"config_test": false,
"has_no_keywords": false,
"few_assignments": false,
"quality_score": 0.5210352183988577,
"avg_score": null,
"num_lines": null
} |
from formalchemy.tests import *
def test_rebind_and_render(self):
"""Explicitly test rebind + render:
>>> g = Grid(User, session=session)
>>> g.rebind([bill, john])
>>> print(pretty_html(g.render()))
<thead>
<tr>
<th>
Email
</th>
<th>
Password
</th>
<th>
Name
</th>
<th>
Orders
</th>
</tr>
</thead>
<tbody>
<tr class="even">
<td>
<input id="User-1-email" maxlength="40" name="User-1-email" type="text" value="bill@example.com" />
</td>
<td>
<input id="User-1-password" maxlength="20" name="User-1-password" type="text" value="1234" />
</td>
<td>
<input id="User-1-name" maxlength="30" name="User-1-name" type="text" value="Bill" />
</td>
<td>
<select id="User-1-orders" multiple="multiple" name="User-1-orders" size="5">
<option value="2">
Quantity: 5
</option>
<option value="3">
Quantity: 6
</option>
<option selected="selected" value="1">
Quantity: 10
</option>
</select>
</td>
</tr>
<tr class="odd">
<td>
<input id="User-2-email" maxlength="40" name="User-2-email" type="text" value="john@example.com" />
</td>
<td>
<input id="User-2-password" maxlength="20" name="User-2-password" type="text" value="5678" />
</td>
<td>
<input id="User-2-name" maxlength="30" name="User-2-name" type="text" value="John" />
</td>
<td>
<select id="User-2-orders" multiple="multiple" name="User-2-orders" size="5">
<option selected="selected" value="2">
Quantity: 5
</option>
<option selected="selected" value="3">
Quantity: 6
</option>
<option value="1">
Quantity: 10
</option>
</select>
</td>
</tr>
</tbody>
"""
def test_extra_field():
"""
Test rendering extra field:
>>> g = Grid(User, session=session)
>>> g.add(Field('edit', types.String, 'fake edit link'))
>>> g._set_active(john)
>>> print(g.edit.render())
<input id="User-2-edit" name="User-2-edit" type="text" value="fake edit link" />
And extra field w/ callable value:
>>> g = Grid(User, session=session)
>>> g.add(Field('edit', types.String, lambda o: 'fake edit link for %s' % o.id))
>>> g._set_active(john)
>>> print(g.edit.render())
<input id="User-2-edit" name="User-2-edit" type="text" value="fake edit link for 2" />
Text syncing:
>>> g = Grid(User, [john, bill], session=session)
>>> g.rebind(data={'User-1-email': '', 'User-1-password': '1234_', 'User-1-name': 'Bill_', 'User-1-orders': '1', 'User-2-email': 'john_@example.com', 'User-2-password': '5678_', 'User-2-name': 'John_', 'User-2-orders': ['2', '3'], })
>>> g.validate()
False
>>> g.errors[bill]
{AttributeField(email): ['Please enter a value']}
>>> g.errors[john]
{}
>>> g.sync_one(john)
>>> session.flush()
>>> session.refresh(john)
>>> john.email == 'john_@example.com'
True
>>> session.rollback()
Test preventing user from binding to the wrong kind of object:
>>> g = g.bind([john])
>>> g.rows == [john]
True
>>> g.rebind(User)
Traceback (most recent call last):
...
Exception: instances must be an iterable, not <class 'formalchemy.tests.User'>
>>> g = g.bind(User)
Traceback (most recent call last):
...
Exception: instances must be an iterable, not <class 'formalchemy.tests.User'>
Simulate creating a grid in a different thread than the one it's used in:
>>> _Session = sessionmaker(bind=engine)
>>> _old_session = _Session()
>>> assert _old_session != object_session(john)
>>> g = Grid(User, session=_old_session)
>>> g2 = g.bind([john])
>>> _ = g2.render()
"""
def test_rebind_render():
"""
Explicitly test rebind + render:
>>> g = Grid(User, session=session, prefix="myprefix")
>>> g.rebind([bill, john])
>>> print(pretty_html(g.render()))
<thead>
<tr>
<th>
Email
</th>
<th>
Password
</th>
<th>
Name
</th>
<th>
Orders
</th>
</tr>
</thead>
<tbody>
<tr class="even">
<td>
<input id="myprefix-User-1-email" maxlength="40" name="myprefix-User-1-email" type="text" value="bill@example.com" />
</td>
<td>
<input id="myprefix-User-1-password" maxlength="20" name="myprefix-User-1-password" type="text" value="1234" />
</td>
<td>
<input id="myprefix-User-1-name" maxlength="30" name="myprefix-User-1-name" type="text" value="Bill" />
</td>
<td>
<select id="myprefix-User-1-orders" multiple="multiple" name="myprefix-User-1-orders" size="5">
<option value="2">
Quantity: 5
</option>
<option value="3">
Quantity: 6
</option>
<option selected="selected" value="1">
Quantity: 10
</option>
</select>
</td>
</tr>
<tr class="odd">
<td>
<input id="myprefix-User-2-email" maxlength="40" name="myprefix-User-2-email" type="text" value="john@example.com" />
</td>
<td>
<input id="myprefix-User-2-password" maxlength="20" name="myprefix-User-2-password" type="text" value="5678" />
</td>
<td>
<input id="myprefix-User-2-name" maxlength="30" name="myprefix-User-2-name" type="text" value="John" />
</td>
<td>
<select id="myprefix-User-2-orders" multiple="multiple" name="myprefix-User-2-orders" size="5">
<option selected="selected" value="2">
Quantity: 5
</option>
<option selected="selected" value="3">
Quantity: 6
</option>
<option value="1">
Quantity: 10
</option>
</select>
</td>
</tr>
</tbody>
>>> g.rebind(data={'myprefix-User-1-email': 'updatebill_@example.com', 'myprefix-User-1-password': '1234_', 'myprefix-User-1-name': 'Bill_', 'myprefix-User-1-orders': '1', 'myprefix-User-2-email': 'john_@example.com', 'myprefix-User-2-password': '5678_', 'myprefix-User-2-name': 'John_', 'myprefix-User-2-orders': ['2', '3'], })
>>> g.validate()
True
>>> g.sync()
>>> bill.email
'updatebill_@example.com'
"""
if __name__ == '__main__':
import doctest
doctest.testmod()
| {
"repo_name": "camptocamp/formalchemy",
"path": "formalchemy/tests/test_tables.py",
"copies": "2",
"size": "6525",
"license": "mit",
"hash": 7764258895122546000,
"line_mean": 29.7783018868,
"line_max": 332,
"alpha_frac": 0.5377777778,
"autogenerated": false,
"ratio": 3.2641320660330164,
"config_test": true,
"has_no_keywords": false,
"few_assignments": false,
"quality_score": 0.9793273827975248,
"avg_score": 0.0017272031715537236,
"num_lines": 212
} |
from formalchemy.tests import *
from formalchemy.fields import DateTimeFieldRenderer
import datetime
class Dt(Base):
__tablename__ = 'dts'
id = Column('id', Integer, primary_key=True)
foo = Column('foo', Date, nullable=True)
bar = Column('bar', Time, nullable=True)
foobar = Column('foobar', DateTime, nullable=True)
class DateTimeFieldRendererFr(DateTimeFieldRenderer):
edit_format = 'd-m-y'
__doc__ = r"""
>>> fs = FieldSet(Dt)
>>> fs.configure(options=[fs.foobar.with_renderer(DateTimeFieldRendererFr)])
>>> print pretty_html(fs.foobar.with_html(lang='fr').render()) #doctest: +ELLIPSIS
<span id="Dt--foobar">
<select id="Dt--foobar__day" lang="fr" name="Dt--foobar__day">
<option value="DD">
Jour
</option>
...
<select id="Dt--foobar__month" lang="fr" name="Dt--foobar__month">
<option value="MM">
Mois
</option>
<option value="1">
Janvier
</option>
...
>>> fs = FieldSet(Dt)
>>> print pretty_html(fs.foobar.render())
<span id="Dt--foobar">
<select id="Dt--foobar__month" name="Dt--foobar__month">
<option value="MM">
Month
</option>
<option value="1">
January
</option>
<option value="2">
February
</option>
<option value="3">
March
</option>
<option value="4">
April
</option>
<option value="5">
May
</option>
<option value="6">
June
</option>
<option value="7">
July
</option>
<option value="8">
August
</option>
<option value="9">
September
</option>
<option value="10">
October
</option>
<option value="11">
November
</option>
<option value="12">
December
</option>
</select>
<select id="Dt--foobar__day" name="Dt--foobar__day">
<option value="DD">
Day
</option>
<option value="1">
1
</option>
<option value="2">
2
</option>
<option value="3">
3
</option>
<option value="4">
4
</option>
<option value="5">
5
</option>
<option value="6">
6
</option>
<option value="7">
7
</option>
<option value="8">
8
</option>
<option value="9">
9
</option>
<option value="10">
10
</option>
<option value="11">
11
</option>
<option value="12">
12
</option>
<option value="13">
13
</option>
<option value="14">
14
</option>
<option value="15">
15
</option>
<option value="16">
16
</option>
<option value="17">
17
</option>
<option value="18">
18
</option>
<option value="19">
19
</option>
<option value="20">
20
</option>
<option value="21">
21
</option>
<option value="22">
22
</option>
<option value="23">
23
</option>
<option value="24">
24
</option>
<option value="25">
25
</option>
<option value="26">
26
</option>
<option value="27">
27
</option>
<option value="28">
28
</option>
<option value="29">
29
</option>
<option value="30">
30
</option>
<option value="31">
31
</option>
</select>
<input id="Dt--foobar__year" maxlength="4" name="Dt--foobar__year" size="4" type="text" value="YYYY" />
<select id="Dt--foobar__hour" name="Dt--foobar__hour">
<option value="HH">
HH
</option>
<option value="0">
0
</option>
<option value="1">
1
</option>
<option value="2">
2
</option>
<option value="3">
3
</option>
<option value="4">
4
</option>
<option value="5">
5
</option>
<option value="6">
6
</option>
<option value="7">
7
</option>
<option value="8">
8
</option>
<option value="9">
9
</option>
<option value="10">
10
</option>
<option value="11">
11
</option>
<option value="12">
12
</option>
<option value="13">
13
</option>
<option value="14">
14
</option>
<option value="15">
15
</option>
<option value="16">
16
</option>
<option value="17">
17
</option>
<option value="18">
18
</option>
<option value="19">
19
</option>
<option value="20">
20
</option>
<option value="21">
21
</option>
<option value="22">
22
</option>
<option value="23">
23
</option>
</select>
:
<select id="Dt--foobar__minute" name="Dt--foobar__minute">
<option value="MM">
MM
</option>
<option value="0">
0
</option>
<option value="1">
1
</option>
<option value="2">
2
</option>
<option value="3">
3
</option>
<option value="4">
4
</option>
<option value="5">
5
</option>
<option value="6">
6
</option>
<option value="7">
7
</option>
<option value="8">
8
</option>
<option value="9">
9
</option>
<option value="10">
10
</option>
<option value="11">
11
</option>
<option value="12">
12
</option>
<option value="13">
13
</option>
<option value="14">
14
</option>
<option value="15">
15
</option>
<option value="16">
16
</option>
<option value="17">
17
</option>
<option value="18">
18
</option>
<option value="19">
19
</option>
<option value="20">
20
</option>
<option value="21">
21
</option>
<option value="22">
22
</option>
<option value="23">
23
</option>
<option value="24">
24
</option>
<option value="25">
25
</option>
<option value="26">
26
</option>
<option value="27">
27
</option>
<option value="28">
28
</option>
<option value="29">
29
</option>
<option value="30">
30
</option>
<option value="31">
31
</option>
<option value="32">
32
</option>
<option value="33">
33
</option>
<option value="34">
34
</option>
<option value="35">
35
</option>
<option value="36">
36
</option>
<option value="37">
37
</option>
<option value="38">
38
</option>
<option value="39">
39
</option>
<option value="40">
40
</option>
<option value="41">
41
</option>
<option value="42">
42
</option>
<option value="43">
43
</option>
<option value="44">
44
</option>
<option value="45">
45
</option>
<option value="46">
46
</option>
<option value="47">
47
</option>
<option value="48">
48
</option>
<option value="49">
49
</option>
<option value="50">
50
</option>
<option value="51">
51
</option>
<option value="52">
52
</option>
<option value="53">
53
</option>
<option value="54">
54
</option>
<option value="55">
55
</option>
<option value="56">
56
</option>
<option value="57">
57
</option>
<option value="58">
58
</option>
<option value="59">
59
</option>
</select>
:
<select id="Dt--foobar__second" name="Dt--foobar__second">
<option value="SS">
SS
</option>
<option value="0">
0
</option>
<option value="1">
1
</option>
<option value="2">
2
</option>
<option value="3">
3
</option>
<option value="4">
4
</option>
<option value="5">
5
</option>
<option value="6">
6
</option>
<option value="7">
7
</option>
<option value="8">
8
</option>
<option value="9">
9
</option>
<option value="10">
10
</option>
<option value="11">
11
</option>
<option value="12">
12
</option>
<option value="13">
13
</option>
<option value="14">
14
</option>
<option value="15">
15
</option>
<option value="16">
16
</option>
<option value="17">
17
</option>
<option value="18">
18
</option>
<option value="19">
19
</option>
<option value="20">
20
</option>
<option value="21">
21
</option>
<option value="22">
22
</option>
<option value="23">
23
</option>
<option value="24">
24
</option>
<option value="25">
25
</option>
<option value="26">
26
</option>
<option value="27">
27
</option>
<option value="28">
28
</option>
<option value="29">
29
</option>
<option value="30">
30
</option>
<option value="31">
31
</option>
<option value="32">
32
</option>
<option value="33">
33
</option>
<option value="34">
34
</option>
<option value="35">
35
</option>
<option value="36">
36
</option>
<option value="37">
37
</option>
<option value="38">
38
</option>
<option value="39">
39
</option>
<option value="40">
40
</option>
<option value="41">
41
</option>
<option value="42">
42
</option>
<option value="43">
43
</option>
<option value="44">
44
</option>
<option value="45">
45
</option>
<option value="46">
46
</option>
<option value="47">
47
</option>
<option value="48">
48
</option>
<option value="49">
49
</option>
<option value="50">
50
</option>
<option value="51">
51
</option>
<option value="52">
52
</option>
<option value="53">
53
</option>
<option value="54">
54
</option>
<option value="55">
55
</option>
<option value="56">
56
</option>
<option value="57">
57
</option>
<option value="58">
58
</option>
<option value="59">
59
</option>
</select>
</span>
>>> fs = FieldSet(Dt)
>>> dt = fs.model
>>> dt.foo = datetime.date(2008, 6, 3); dt.bar=datetime.time(14, 16, 18); dt.foobar=datetime.datetime(2008, 6, 3, 14, 16, 18)
>>> print pretty_html(fs.foo.render())
<span id="Dt--foo">
<select id="Dt--foo__month" name="Dt--foo__month">
<option value="MM">
Month
</option>
<option value="1">
January
</option>
<option value="2">
February
</option>
<option value="3">
March
</option>
<option value="4">
April
</option>
<option value="5">
May
</option>
<option value="6" selected="selected">
June
</option>
<option value="7">
July
</option>
<option value="8">
August
</option>
<option value="9">
September
</option>
<option value="10">
October
</option>
<option value="11">
November
</option>
<option value="12">
December
</option>
</select>
<select id="Dt--foo__day" name="Dt--foo__day">
<option value="DD">
Day
</option>
<option value="1">
1
</option>
<option value="2">
2
</option>
<option value="3" selected="selected">
3
</option>
<option value="4">
4
</option>
<option value="5">
5
</option>
<option value="6">
6
</option>
<option value="7">
7
</option>
<option value="8">
8
</option>
<option value="9">
9
</option>
<option value="10">
10
</option>
<option value="11">
11
</option>
<option value="12">
12
</option>
<option value="13">
13
</option>
<option value="14">
14
</option>
<option value="15">
15
</option>
<option value="16">
16
</option>
<option value="17">
17
</option>
<option value="18">
18
</option>
<option value="19">
19
</option>
<option value="20">
20
</option>
<option value="21">
21
</option>
<option value="22">
22
</option>
<option value="23">
23
</option>
<option value="24">
24
</option>
<option value="25">
25
</option>
<option value="26">
26
</option>
<option value="27">
27
</option>
<option value="28">
28
</option>
<option value="29">
29
</option>
<option value="30">
30
</option>
<option value="31">
31
</option>
</select>
<input id="Dt--foo__year" maxlength="4" name="Dt--foo__year" size="4" type="text" value="2008" />
</span>
>>> print pretty_html(fs.bar.render())
<span id="Dt--bar">
<select id="Dt--bar__hour" name="Dt--bar__hour">
<option value="HH">
HH
</option>
<option value="0">
0
</option>
<option value="1">
1
</option>
<option value="2">
2
</option>
<option value="3">
3
</option>
<option value="4">
4
</option>
<option value="5">
5
</option>
<option value="6">
6
</option>
<option value="7">
7
</option>
<option value="8">
8
</option>
<option value="9">
9
</option>
<option value="10">
10
</option>
<option value="11">
11
</option>
<option value="12">
12
</option>
<option value="13">
13
</option>
<option value="14" selected="selected">
14
</option>
<option value="15">
15
</option>
<option value="16">
16
</option>
<option value="17">
17
</option>
<option value="18">
18
</option>
<option value="19">
19
</option>
<option value="20">
20
</option>
<option value="21">
21
</option>
<option value="22">
22
</option>
<option value="23">
23
</option>
</select>
:
<select id="Dt--bar__minute" name="Dt--bar__minute">
<option value="MM">
MM
</option>
<option value="0">
0
</option>
<option value="1">
1
</option>
<option value="2">
2
</option>
<option value="3">
3
</option>
<option value="4">
4
</option>
<option value="5">
5
</option>
<option value="6">
6
</option>
<option value="7">
7
</option>
<option value="8">
8
</option>
<option value="9">
9
</option>
<option value="10">
10
</option>
<option value="11">
11
</option>
<option value="12">
12
</option>
<option value="13">
13
</option>
<option value="14">
14
</option>
<option value="15">
15
</option>
<option value="16" selected="selected">
16
</option>
<option value="17">
17
</option>
<option value="18">
18
</option>
<option value="19">
19
</option>
<option value="20">
20
</option>
<option value="21">
21
</option>
<option value="22">
22
</option>
<option value="23">
23
</option>
<option value="24">
24
</option>
<option value="25">
25
</option>
<option value="26">
26
</option>
<option value="27">
27
</option>
<option value="28">
28
</option>
<option value="29">
29
</option>
<option value="30">
30
</option>
<option value="31">
31
</option>
<option value="32">
32
</option>
<option value="33">
33
</option>
<option value="34">
34
</option>
<option value="35">
35
</option>
<option value="36">
36
</option>
<option value="37">
37
</option>
<option value="38">
38
</option>
<option value="39">
39
</option>
<option value="40">
40
</option>
<option value="41">
41
</option>
<option value="42">
42
</option>
<option value="43">
43
</option>
<option value="44">
44
</option>
<option value="45">
45
</option>
<option value="46">
46
</option>
<option value="47">
47
</option>
<option value="48">
48
</option>
<option value="49">
49
</option>
<option value="50">
50
</option>
<option value="51">
51
</option>
<option value="52">
52
</option>
<option value="53">
53
</option>
<option value="54">
54
</option>
<option value="55">
55
</option>
<option value="56">
56
</option>
<option value="57">
57
</option>
<option value="58">
58
</option>
<option value="59">
59
</option>
</select>
:
<select id="Dt--bar__second" name="Dt--bar__second">
<option value="SS">
SS
</option>
<option value="0">
0
</option>
<option value="1">
1
</option>
<option value="2">
2
</option>
<option value="3">
3
</option>
<option value="4">
4
</option>
<option value="5">
5
</option>
<option value="6">
6
</option>
<option value="7">
7
</option>
<option value="8">
8
</option>
<option value="9">
9
</option>
<option value="10">
10
</option>
<option value="11">
11
</option>
<option value="12">
12
</option>
<option value="13">
13
</option>
<option value="14">
14
</option>
<option value="15">
15
</option>
<option value="16">
16
</option>
<option value="17">
17
</option>
<option value="18" selected="selected">
18
</option>
<option value="19">
19
</option>
<option value="20">
20
</option>
<option value="21">
21
</option>
<option value="22">
22
</option>
<option value="23">
23
</option>
<option value="24">
24
</option>
<option value="25">
25
</option>
<option value="26">
26
</option>
<option value="27">
27
</option>
<option value="28">
28
</option>
<option value="29">
29
</option>
<option value="30">
30
</option>
<option value="31">
31
</option>
<option value="32">
32
</option>
<option value="33">
33
</option>
<option value="34">
34
</option>
<option value="35">
35
</option>
<option value="36">
36
</option>
<option value="37">
37
</option>
<option value="38">
38
</option>
<option value="39">
39
</option>
<option value="40">
40
</option>
<option value="41">
41
</option>
<option value="42">
42
</option>
<option value="43">
43
</option>
<option value="44">
44
</option>
<option value="45">
45
</option>
<option value="46">
46
</option>
<option value="47">
47
</option>
<option value="48">
48
</option>
<option value="49">
49
</option>
<option value="50">
50
</option>
<option value="51">
51
</option>
<option value="52">
52
</option>
<option value="53">
53
</option>
<option value="54">
54
</option>
<option value="55">
55
</option>
<option value="56">
56
</option>
<option value="57">
57
</option>
<option value="58">
58
</option>
<option value="59">
59
</option>
</select>
</span>
>>> print pretty_html(fs.foobar.render())
<span id="Dt--foobar">
<select id="Dt--foobar__month" name="Dt--foobar__month">
<option value="MM">
Month
</option>
<option value="1">
January
</option>
<option value="2">
February
</option>
<option value="3">
March
</option>
<option value="4">
April
</option>
<option value="5">
May
</option>
<option value="6" selected="selected">
June
</option>
<option value="7">
July
</option>
<option value="8">
August
</option>
<option value="9">
September
</option>
<option value="10">
October
</option>
<option value="11">
November
</option>
<option value="12">
December
</option>
</select>
<select id="Dt--foobar__day" name="Dt--foobar__day">
<option value="DD">
Day
</option>
<option value="1">
1
</option>
<option value="2">
2
</option>
<option value="3" selected="selected">
3
</option>
<option value="4">
4
</option>
<option value="5">
5
</option>
<option value="6">
6
</option>
<option value="7">
7
</option>
<option value="8">
8
</option>
<option value="9">
9
</option>
<option value="10">
10
</option>
<option value="11">
11
</option>
<option value="12">
12
</option>
<option value="13">
13
</option>
<option value="14">
14
</option>
<option value="15">
15
</option>
<option value="16">
16
</option>
<option value="17">
17
</option>
<option value="18">
18
</option>
<option value="19">
19
</option>
<option value="20">
20
</option>
<option value="21">
21
</option>
<option value="22">
22
</option>
<option value="23">
23
</option>
<option value="24">
24
</option>
<option value="25">
25
</option>
<option value="26">
26
</option>
<option value="27">
27
</option>
<option value="28">
28
</option>
<option value="29">
29
</option>
<option value="30">
30
</option>
<option value="31">
31
</option>
</select>
<input id="Dt--foobar__year" maxlength="4" name="Dt--foobar__year" size="4" type="text" value="2008" />
<select id="Dt--foobar__hour" name="Dt--foobar__hour">
<option value="HH">
HH
</option>
<option value="0">
0
</option>
<option value="1">
1
</option>
<option value="2">
2
</option>
<option value="3">
3
</option>
<option value="4">
4
</option>
<option value="5">
5
</option>
<option value="6">
6
</option>
<option value="7">
7
</option>
<option value="8">
8
</option>
<option value="9">
9
</option>
<option value="10">
10
</option>
<option value="11">
11
</option>
<option value="12">
12
</option>
<option value="13">
13
</option>
<option value="14" selected="selected">
14
</option>
<option value="15">
15
</option>
<option value="16">
16
</option>
<option value="17">
17
</option>
<option value="18">
18
</option>
<option value="19">
19
</option>
<option value="20">
20
</option>
<option value="21">
21
</option>
<option value="22">
22
</option>
<option value="23">
23
</option>
</select>
:
<select id="Dt--foobar__minute" name="Dt--foobar__minute">
<option value="MM">
MM
</option>
<option value="0">
0
</option>
<option value="1">
1
</option>
<option value="2">
2
</option>
<option value="3">
3
</option>
<option value="4">
4
</option>
<option value="5">
5
</option>
<option value="6">
6
</option>
<option value="7">
7
</option>
<option value="8">
8
</option>
<option value="9">
9
</option>
<option value="10">
10
</option>
<option value="11">
11
</option>
<option value="12">
12
</option>
<option value="13">
13
</option>
<option value="14">
14
</option>
<option value="15">
15
</option>
<option value="16" selected="selected">
16
</option>
<option value="17">
17
</option>
<option value="18">
18
</option>
<option value="19">
19
</option>
<option value="20">
20
</option>
<option value="21">
21
</option>
<option value="22">
22
</option>
<option value="23">
23
</option>
<option value="24">
24
</option>
<option value="25">
25
</option>
<option value="26">
26
</option>
<option value="27">
27
</option>
<option value="28">
28
</option>
<option value="29">
29
</option>
<option value="30">
30
</option>
<option value="31">
31
</option>
<option value="32">
32
</option>
<option value="33">
33
</option>
<option value="34">
34
</option>
<option value="35">
35
</option>
<option value="36">
36
</option>
<option value="37">
37
</option>
<option value="38">
38
</option>
<option value="39">
39
</option>
<option value="40">
40
</option>
<option value="41">
41
</option>
<option value="42">
42
</option>
<option value="43">
43
</option>
<option value="44">
44
</option>
<option value="45">
45
</option>
<option value="46">
46
</option>
<option value="47">
47
</option>
<option value="48">
48
</option>
<option value="49">
49
</option>
<option value="50">
50
</option>
<option value="51">
51
</option>
<option value="52">
52
</option>
<option value="53">
53
</option>
<option value="54">
54
</option>
<option value="55">
55
</option>
<option value="56">
56
</option>
<option value="57">
57
</option>
<option value="58">
58
</option>
<option value="59">
59
</option>
</select>
:
<select id="Dt--foobar__second" name="Dt--foobar__second">
<option value="SS">
SS
</option>
<option value="0">
0
</option>
<option value="1">
1
</option>
<option value="2">
2
</option>
<option value="3">
3
</option>
<option value="4">
4
</option>
<option value="5">
5
</option>
<option value="6">
6
</option>
<option value="7">
7
</option>
<option value="8">
8
</option>
<option value="9">
9
</option>
<option value="10">
10
</option>
<option value="11">
11
</option>
<option value="12">
12
</option>
<option value="13">
13
</option>
<option value="14">
14
</option>
<option value="15">
15
</option>
<option value="16">
16
</option>
<option value="17">
17
</option>
<option value="18" selected="selected">
18
</option>
<option value="19">
19
</option>
<option value="20">
20
</option>
<option value="21">
21
</option>
<option value="22">
22
</option>
<option value="23">
23
</option>
<option value="24">
24
</option>
<option value="25">
25
</option>
<option value="26">
26
</option>
<option value="27">
27
</option>
<option value="28">
28
</option>
<option value="29">
29
</option>
<option value="30">
30
</option>
<option value="31">
31
</option>
<option value="32">
32
</option>
<option value="33">
33
</option>
<option value="34">
34
</option>
<option value="35">
35
</option>
<option value="36">
36
</option>
<option value="37">
37
</option>
<option value="38">
38
</option>
<option value="39">
39
</option>
<option value="40">
40
</option>
<option value="41">
41
</option>
<option value="42">
42
</option>
<option value="43">
43
</option>
<option value="44">
44
</option>
<option value="45">
45
</option>
<option value="46">
46
</option>
<option value="47">
47
</option>
<option value="48">
48
</option>
<option value="49">
49
</option>
<option value="50">
50
</option>
<option value="51">
51
</option>
<option value="52">
52
</option>
<option value="53">
53
</option>
<option value="54">
54
</option>
<option value="55">
55
</option>
<option value="56">
56
</option>
<option value="57">
57
</option>
<option value="58">
58
</option>
<option value="59">
59
</option>
</select>
</span>
>>> fs.rebind(dt, data={'Dt--foo__day': 'DD', 'Dt--foo__month': '2', 'Dt--foo__year': '', 'Dt--bar__hour': 'HH', 'Dt--bar__minute': '6', 'Dt--bar__second': '8'})
>>> print pretty_html(fs.foo.render())
<span id="Dt--foo">
<select id="Dt--foo__month" name="Dt--foo__month">
<option value="MM">
Month
</option>
<option value="1">
January
</option>
<option value="2" selected="selected">
February
</option>
<option value="3">
March
</option>
<option value="4">
April
</option>
<option value="5">
May
</option>
<option value="6">
June
</option>
<option value="7">
July
</option>
<option value="8">
August
</option>
<option value="9">
September
</option>
<option value="10">
October
</option>
<option value="11">
November
</option>
<option value="12">
December
</option>
</select>
<select id="Dt--foo__day" name="Dt--foo__day">
<option value="DD" selected="selected">
Day
</option>
<option value="1">
1
</option>
<option value="2">
2
</option>
<option value="3">
3
</option>
<option value="4">
4
</option>
<option value="5">
5
</option>
<option value="6">
6
</option>
<option value="7">
7
</option>
<option value="8">
8
</option>
<option value="9">
9
</option>
<option value="10">
10
</option>
<option value="11">
11
</option>
<option value="12">
12
</option>
<option value="13">
13
</option>
<option value="14">
14
</option>
<option value="15">
15
</option>
<option value="16">
16
</option>
<option value="17">
17
</option>
<option value="18">
18
</option>
<option value="19">
19
</option>
<option value="20">
20
</option>
<option value="21">
21
</option>
<option value="22">
22
</option>
<option value="23">
23
</option>
<option value="24">
24
</option>
<option value="25">
25
</option>
<option value="26">
26
</option>
<option value="27">
27
</option>
<option value="28">
28
</option>
<option value="29">
29
</option>
<option value="30">
30
</option>
<option value="31">
31
</option>
</select>
<input id="Dt--foo__year" maxlength="4" name="Dt--foo__year" size="4" type="text" value="" />
</span>
>>> print pretty_html(fs.bar.render())
<span id="Dt--bar">
<select id="Dt--bar__hour" name="Dt--bar__hour">
<option value="HH" selected="selected">
HH
</option>
<option value="0">
0
</option>
<option value="1">
1
</option>
<option value="2">
2
</option>
<option value="3">
3
</option>
<option value="4">
4
</option>
<option value="5">
5
</option>
<option value="6">
6
</option>
<option value="7">
7
</option>
<option value="8">
8
</option>
<option value="9">
9
</option>
<option value="10">
10
</option>
<option value="11">
11
</option>
<option value="12">
12
</option>
<option value="13">
13
</option>
<option value="14">
14
</option>
<option value="15">
15
</option>
<option value="16">
16
</option>
<option value="17">
17
</option>
<option value="18">
18
</option>
<option value="19">
19
</option>
<option value="20">
20
</option>
<option value="21">
21
</option>
<option value="22">
22
</option>
<option value="23">
23
</option>
</select>
:
<select id="Dt--bar__minute" name="Dt--bar__minute">
<option value="MM">
MM
</option>
<option value="0">
0
</option>
<option value="1">
1
</option>
<option value="2">
2
</option>
<option value="3">
3
</option>
<option value="4">
4
</option>
<option value="5">
5
</option>
<option value="6" selected="selected">
6
</option>
<option value="7">
7
</option>
<option value="8">
8
</option>
<option value="9">
9
</option>
<option value="10">
10
</option>
<option value="11">
11
</option>
<option value="12">
12
</option>
<option value="13">
13
</option>
<option value="14">
14
</option>
<option value="15">
15
</option>
<option value="16">
16
</option>
<option value="17">
17
</option>
<option value="18">
18
</option>
<option value="19">
19
</option>
<option value="20">
20
</option>
<option value="21">
21
</option>
<option value="22">
22
</option>
<option value="23">
23
</option>
<option value="24">
24
</option>
<option value="25">
25
</option>
<option value="26">
26
</option>
<option value="27">
27
</option>
<option value="28">
28
</option>
<option value="29">
29
</option>
<option value="30">
30
</option>
<option value="31">
31
</option>
<option value="32">
32
</option>
<option value="33">
33
</option>
<option value="34">
34
</option>
<option value="35">
35
</option>
<option value="36">
36
</option>
<option value="37">
37
</option>
<option value="38">
38
</option>
<option value="39">
39
</option>
<option value="40">
40
</option>
<option value="41">
41
</option>
<option value="42">
42
</option>
<option value="43">
43
</option>
<option value="44">
44
</option>
<option value="45">
45
</option>
<option value="46">
46
</option>
<option value="47">
47
</option>
<option value="48">
48
</option>
<option value="49">
49
</option>
<option value="50">
50
</option>
<option value="51">
51
</option>
<option value="52">
52
</option>
<option value="53">
53
</option>
<option value="54">
54
</option>
<option value="55">
55
</option>
<option value="56">
56
</option>
<option value="57">
57
</option>
<option value="58">
58
</option>
<option value="59">
59
</option>
</select>
:
<select id="Dt--bar__second" name="Dt--bar__second">
<option value="SS">
SS
</option>
<option value="0">
0
</option>
<option value="1">
1
</option>
<option value="2">
2
</option>
<option value="3">
3
</option>
<option value="4">
4
</option>
<option value="5">
5
</option>
<option value="6">
6
</option>
<option value="7">
7
</option>
<option value="8" selected="selected">
8
</option>
<option value="9">
9
</option>
<option value="10">
10
</option>
<option value="11">
11
</option>
<option value="12">
12
</option>
<option value="13">
13
</option>
<option value="14">
14
</option>
<option value="15">
15
</option>
<option value="16">
16
</option>
<option value="17">
17
</option>
<option value="18">
18
</option>
<option value="19">
19
</option>
<option value="20">
20
</option>
<option value="21">
21
</option>
<option value="22">
22
</option>
<option value="23">
23
</option>
<option value="24">
24
</option>
<option value="25">
25
</option>
<option value="26">
26
</option>
<option value="27">
27
</option>
<option value="28">
28
</option>
<option value="29">
29
</option>
<option value="30">
30
</option>
<option value="31">
31
</option>
<option value="32">
32
</option>
<option value="33">
33
</option>
<option value="34">
34
</option>
<option value="35">
35
</option>
<option value="36">
36
</option>
<option value="37">
37
</option>
<option value="38">
38
</option>
<option value="39">
39
</option>
<option value="40">
40
</option>
<option value="41">
41
</option>
<option value="42">
42
</option>
<option value="43">
43
</option>
<option value="44">
44
</option>
<option value="45">
45
</option>
<option value="46">
46
</option>
<option value="47">
47
</option>
<option value="48">
48
</option>
<option value="49">
49
</option>
<option value="50">
50
</option>
<option value="51">
51
</option>
<option value="52">
52
</option>
<option value="53">
53
</option>
<option value="54">
54
</option>
<option value="55">
55
</option>
<option value="56">
56
</option>
<option value="57">
57
</option>
<option value="58">
58
</option>
<option value="59">
59
</option>
</select>
</span>
>>> fs.rebind(dt, data={'Dt--foo__day': '11', 'Dt--foo__month': '2', 'Dt--foo__year': '1951', 'Dt--bar__hour': '4', 'Dt--bar__minute': '6', 'Dt--bar__second': '8', 'Dt--foobar__day': '11', 'Dt--foobar__month': '2', 'Dt--foobar__year': '1951', 'Dt--foobar__hour': '4', 'Dt--foobar__minute': '6', 'Dt--foobar__second': '8'})
>>> fs.sync()
>>> dt.foo
datetime.date(1951, 2, 11)
>>> dt.bar
datetime.time(4, 6, 8)
>>> dt.foobar
datetime.datetime(1951, 2, 11, 4, 6, 8)
>>> session.rollback()
>>> fs.rebind(dt, data={'Dt--foo__day': 'DD', 'Dt--foo__month': 'MM', 'Dt--foo__year': 'YYYY', 'Dt--bar__hour': 'HH', 'Dt--bar__minute': 'MM', 'Dt--bar__second': 'SS', 'Dt--foobar__day': 'DD', 'Dt--foobar__month': 'MM', 'Dt--foobar__year': '', 'Dt--foobar__hour': 'HH', 'Dt--foobar__minute': 'MM', 'Dt--foobar__second': 'SS'})
>>> fs.validate()
True
>>> fs.sync()
>>> dt.foo is None
True
>>> dt.bar is None
True
>>> dt.foobar is None
True
>>> session.rollback()
>>> fs.rebind(dt, data={'Dt--foo__day': '1', 'Dt--foo__month': 'MM', 'Dt--foo__year': 'YYYY', 'Dt--bar__hour': 'HH', 'Dt--bar__minute': 'MM', 'Dt--bar__second': 'SS', 'Dt--foobar__day': 'DD', 'Dt--foobar__month': 'MM', 'Dt--foobar__year': '', 'Dt--foobar__hour': 'HH', 'Dt--foobar__minute': 'MM', 'Dt--foobar__second': 'SS'})
>>> fs.validate()
False
>>> fs.errors
{AttributeField(foo): [ValidationError('Invalid date',)]}
>>> fs.rebind(dt, data={'Dt--foo__day': 'DD', 'Dt--foo__month': 'MM', 'Dt--foo__year': 'YYYY', 'Dt--bar__hour': 'HH', 'Dt--bar__minute': '1', 'Dt--bar__second': 'SS', 'Dt--foobar__day': 'DD', 'Dt--foobar__month': 'MM', 'Dt--foobar__year': '', 'Dt--foobar__hour': 'HH', 'Dt--foobar__minute': 'MM', 'Dt--foobar__second': 'SS'})
>>> fs.validate()
False
>>> fs.errors
{AttributeField(bar): [ValidationError('Invalid time',)]}
>>> fs.rebind(dt, data={'Dt--foo__day': 'DD', 'Dt--foo__month': 'MM', 'Dt--foo__year': 'YYYY', 'Dt--bar__hour': 'HH', 'Dt--bar__minute': 'MM', 'Dt--bar__second': 'SS', 'Dt--foobar__day': '11', 'Dt--foobar__month': '2', 'Dt--foobar__year': '1951', 'Dt--foobar__hour': 'HH', 'Dt--foobar__minute': 'MM', 'Dt--foobar__second': 'SS'})
>>> fs.validate()
False
>>> fs.errors
{AttributeField(foobar): [ValidationError('Incomplete datetime',)]}
"""
if __name__ == '__main__':
import doctest
doctest.testmod()
| {
"repo_name": "abourget/formalchemy-abourget",
"path": "formalchemy/tests/test_dates.py",
"copies": "1",
"size": "36613",
"license": "mit",
"hash": 6779505472491679000,
"line_mean": 13.8772856562,
"line_max": 329,
"alpha_frac": 0.5363668642,
"autogenerated": false,
"ratio": 2.977877185847906,
"config_test": false,
"has_no_keywords": false,
"few_assignments": false,
"quality_score": 0.9013779375090645,
"avg_score": 0.00009293499145214747,
"num_lines": 2461
} |
from formalchemy.tests import *
from formalchemy.fields import DateTimeFieldRenderer
import datetime
class Dt(Base):
__tablename__ = 'dts'
id = Column('id', Integer, primary_key=True)
foo = Column('foo', Date, nullable=True)
bar = Column('bar', Time, nullable=True)
foobar = Column('foobar', DateTime, nullable=True)
class DateTimeFieldRendererFr(DateTimeFieldRenderer):
edit_format = 'd-m-y'
def test_dt_hang_up():
"""
>>> class MyClass(object):
... td = Field(type=types.DateTime, value=datetime.datetime.now())
... t = Field().required()
>>> MyFS = FieldSet(MyClass)
>>> fs = MyFS.bind(model=MyClass, data={
... 'MyClass--td__year': '2011',
... 'MyClass--td__month': '12',
... 'MyClass--td__day': '12',
... 'MyClass--td__hour': '17',
... 'MyClass--td__minute': '28',
... 'MyClass--td__second': '49',
... 'MyClass--t': ""})
>>> fs.validate()
False
>>> print(pretty_html(fs.td.render())) #doctest: +ELLIPSIS
<span id="MyClass--td">
<select id="MyClass--td__month" name="MyClass--td__month">
...
<option selected="selected" value="12">
December
</option>
</select>
<select id="MyClass--td__day" name="MyClass--td__day">
<option value="DD">
Day
</option>
...
<option selected="selected" value="12">
12
</option>
...
</select>
<input id="MyClass--td__year" maxlength="4" name="MyClass--td__year" size="4" type="text" value="2011" />
<select id="MyClass--td__hour" name="MyClass--td__hour">
<option value="HH">
HH
</option>
...
<option selected="selected" value="17">
17
</option>
...
</select>
:
<select id="MyClass--td__minute" name="MyClass--td__minute">
<option value="MM">
MM
</option>
...
<option selected="selected" value="28">
28
</option>
...
</select>
:
<select id="MyClass--td__second" name="MyClass--td__second">
<option value="SS">
SS
</option>
...
<option selected="selected" value="49">
49
</option>
...
</select>
</span>
>>> fs.td.value
datetime.datetime(2011, 12, 12, 17, 28, 49)
"""
def test_hidden():
"""
>>> fs = FieldSet(Dt)
>>> _ = fs.foo.set(hidden=True)
>>> print(pretty_html(fs.foo.render())) #doctest: +ELLIPSIS
<div style="display:none;">
<span id="Dt--foo">
...
>>> _ = fs.bar.set(hidden=True)
>>> print(pretty_html(fs.bar.render())) #doctest: +ELLIPSIS
<div style="display:none;">
<span id="Dt--bar">
...
>>> _ = fs.foobar.set(hidden=True)
>>> print(pretty_html(fs.foobar.render())) #doctest: +ELLIPSIS
<div style="display:none;">
<span id="Dt--foobar">
...
"""
__doc__ = r"""
>>> fs = FieldSet(Dt)
>>> fs.configure(options=[fs.foobar.with_renderer(DateTimeFieldRendererFr)])
>>> print(pretty_html(fs.foobar.with_html(lang='fr').render())) #doctest: +ELLIPSIS
<span id="Dt--foobar">
<select id="Dt--foobar__day" lang="fr" name="Dt--foobar__day">
<option selected="selected" value="DD">
Jour
</option>
...
<select id="Dt--foobar__month" lang="fr" name="Dt--foobar__month">
<option selected="selected" value="MM">
Mois
</option>
<option value="1">
Janvier
</option>
...
>>> fs = FieldSet(Dt)
>>> print(pretty_html(fs.foobar.render())) #doctest: +ELLIPSIS
<span id="Dt--foobar">
<select id="Dt--foobar__month" name="Dt--foobar__month">
<option selected="selected" value="MM">
Month
</option>
...
</select>
<select id="Dt--foobar__day" name="Dt--foobar__day">
<option selected="selected" value="DD">
Day
</option>
...
</select>
<input id="Dt--foobar__year" maxlength="4" name="Dt--foobar__year" size="4" type="text" value="YYYY" />
<select id="Dt--foobar__hour" name="Dt--foobar__hour">
<option selected="selected" value="HH">
HH
</option>
...
</select>
:
<select id="Dt--foobar__minute" name="Dt--foobar__minute">
<option selected="selected" value="MM">
MM
</option>
...
</select>
:
<select id="Dt--foobar__second" name="Dt--foobar__second">
<option selected="selected" value="SS">
SS
</option>
...
</select>
</span>
>>> fs = FieldSet(Dt)
>>> dt = fs.model
>>> dt.foo = datetime.date(2008, 6, 3); dt.bar=datetime.time(14, 16, 18); dt.foobar=datetime.datetime(2008, 6, 3, 14, 16, 18)
>>> print(pretty_html(fs.foo.render())) #doctest: +ELLIPSIS
<span id="Dt--foo">
<select id="Dt--foo__month" name="Dt--foo__month">
<option value="MM">
Month
</option>
...
<option selected="selected" value="6">
June
</option>
...
</select>
<select id="Dt--foo__day" name="Dt--foo__day">
<option value="DD">
Day
</option>
...
<option selected="selected" value="3">
3
</option>
...
<option value="31">
31
</option>
</select>
<input id="Dt--foo__year" maxlength="4" name="Dt--foo__year" size="4" type="text" value="2008" />
</span>
>>> print(pretty_html(fs.bar.render())) #doctest: +ELLIPSIS
<span id="Dt--bar">
<select id="Dt--bar__hour" name="Dt--bar__hour">
<option value="HH">
HH
</option>
<option value="0">
0
</option>
...
<option value="13">
13
</option>
<option selected="selected" value="14">
14
</option>
...
<option value="23">
23
</option>
</select>
:
<select id="Dt--bar__minute" name="Dt--bar__minute">
<option value="MM">
MM
</option>
<option value="0">
0
</option>
...
<option value="15">
15
</option>
<option selected="selected" value="16">
16
</option>
<option value="17">
17
</option>
...
<option value="59">
59
</option>
</select>
:
<select id="Dt--bar__second" name="Dt--bar__second">
<option value="SS">
SS
</option>
<option value="0">
0
</option>
...
<option value="17">
17
</option>
<option selected="selected" value="18">
18
</option>
<option value="19">
19
</option>
...
<option value="59">
59
</option>
</select>
</span>
>>> print(pretty_html(fs.foobar.render())) #doctest: +ELLIPSIS
<span id="Dt--foobar">
<select id="Dt--foobar__month" name="Dt--foobar__month">
<option value="MM">
Month
</option>
...
<option selected="selected" value="6">
June
</option>
...
</select>
<select id="Dt--foobar__day" name="Dt--foobar__day">
<option value="DD">
Day
</option>
...
<option selected="selected" value="3">
3
</option>
...
</select>
<input id="Dt--foobar__year" maxlength="4" name="Dt--foobar__year" size="4" type="text" value="2008" />
<select id="Dt--foobar__hour" name="Dt--foobar__hour">
<option value="HH">
HH
</option>
...
<option selected="selected" value="14">
14
</option>
...
</select>
:
<select id="Dt--foobar__minute" name="Dt--foobar__minute">
<option value="MM">
MM
</option>
...
<option selected="selected" value="16">
16
</option>
...
</select>
:
<select id="Dt--foobar__second" name="Dt--foobar__second">
<option value="SS">
SS
</option>
...
<option selected="selected" value="18">
18
</option>
...
</select>
</span>
>>> fs.rebind(dt, data={'Dt--foo__day': 'DD', 'Dt--foo__month': '2', 'Dt--foo__year': '', 'Dt--bar__hour': 'HH', 'Dt--bar__minute': '6', 'Dt--bar__second': '8'})
>>> print(pretty_html(fs.foo.render())) #doctest: +ELLIPSIS
<span id="Dt--foo">
<select id="Dt--foo__month" name="Dt--foo__month">
<option value="MM">
Month
</option>
<option value="1">
January
</option>
<option selected="selected" value="2">
February
</option>
...
</select>
<select id="Dt--foo__day" name="Dt--foo__day">
<option value="DD">
Day
</option>
<option value="1">
1
</option>
...
<option value="31">
31
</option>
</select>
<input id="Dt--foo__year" maxlength="4" name="Dt--foo__year" size="4" type="text" value="" />
</span>
>>> print(pretty_html(fs.bar.render())) #doctest: +ELLIPSIS
<span id="Dt--bar">
<select id="Dt--bar__hour" name="Dt--bar__hour">
<option value="HH">
HH
</option>
...
<option selected="selected" value="14">
14
</option>
...
</select>
:
<select id="Dt--bar__minute" name="Dt--bar__minute">
<option value="MM">
MM
</option>
...
<option selected="selected" value="6">
6
</option>
...
</select>
:
<select id="Dt--bar__second" name="Dt--bar__second">
<option value="SS">
SS
</option>
...
<option selected="selected" value="8">
8
</option>
...
</select>
</span>
>>> fs.rebind(dt, data={'Dt--foo__day': '11', 'Dt--foo__month': '2', 'Dt--foo__year': '1951', 'Dt--bar__hour': '4', 'Dt--bar__minute': '6', 'Dt--bar__second': '8', 'Dt--foobar__day': '11', 'Dt--foobar__month': '2', 'Dt--foobar__year': '1951', 'Dt--foobar__hour': '4', 'Dt--foobar__minute': '6', 'Dt--foobar__second': '8'})
>>> fs.sync()
>>> dt.foo
datetime.date(1951, 2, 11)
>>> dt.bar
datetime.time(4, 6, 8)
>>> dt.foobar
datetime.datetime(1951, 2, 11, 4, 6, 8)
>>> session.rollback()
>>> fs.rebind(dt, data={'Dt--foo__day': 'DD', 'Dt--foo__month': 'MM', 'Dt--foo__year': 'YYYY', 'Dt--bar__hour': 'HH', 'Dt--bar__minute': 'MM', 'Dt--bar__second': 'SS', 'Dt--foobar__day': 'DD', 'Dt--foobar__month': 'MM', 'Dt--foobar__year': '', 'Dt--foobar__hour': 'HH', 'Dt--foobar__minute': 'MM', 'Dt--foobar__second': 'SS'})
>>> fs.validate()
True
>>> fs.sync()
>>> dt.foo is None
True
>>> dt.bar is None
True
>>> dt.foobar is None
True
>>> session.rollback()
>>> fs.rebind(dt, data={'Dt--foo__day': '1', 'Dt--foo__month': 'MM', 'Dt--foo__year': 'YYYY', 'Dt--bar__hour': 'HH', 'Dt--bar__minute': 'MM', 'Dt--bar__second': 'SS', 'Dt--foobar__day': 'DD', 'Dt--foobar__month': 'MM', 'Dt--foobar__year': '', 'Dt--foobar__hour': 'HH', 'Dt--foobar__minute': 'MM', 'Dt--foobar__second': 'SS'})
>>> fs.validate()
False
>>> fs.errors
{AttributeField(foo): ['Invalid date']}
>>> fs.rebind(dt, data={'Dt--foo__day': 'DD', 'Dt--foo__month': 'MM', 'Dt--foo__year': 'YYYY', 'Dt--bar__hour': 'HH', 'Dt--bar__minute': '1', 'Dt--bar__second': 'SS', 'Dt--foobar__day': 'DD', 'Dt--foobar__month': 'MM', 'Dt--foobar__year': '', 'Dt--foobar__hour': 'HH', 'Dt--foobar__minute': 'MM', 'Dt--foobar__second': 'SS'})
>>> fs.validate()
False
>>> fs.errors
{AttributeField(bar): ['Invalid time']}
>>> fs.rebind(dt, data={'Dt--foo__day': 'DD', 'Dt--foo__month': 'MM', 'Dt--foo__year': 'YYYY', 'Dt--bar__hour': 'HH', 'Dt--bar__minute': 'MM', 'Dt--bar__second': 'SS', 'Dt--foobar__day': '11', 'Dt--foobar__month': '2', 'Dt--foobar__year': '1951', 'Dt--foobar__hour': 'HH', 'Dt--foobar__minute': 'MM', 'Dt--foobar__second': 'SS'})
>>> fs.validate()
False
>>> fs.errors
{AttributeField(foobar): ['Incomplete datetime']}
>>> fs.rebind(dt)
>>> dt.bar = datetime.time(0)
>>> print(fs.bar.render()) #doctest: +ELLIPSIS
<span id="Dt--bar"><select id="Dt--bar__hour" name="Dt--bar__hour">
<option value="HH">HH</option>
<option selected="selected" value="0">0</option>
...
>>> print(fs.bar.render_readonly())
00:00:00
>>> fs = FieldSet(Dt)
>>> print(fs.bar.render()) #doctest: +ELLIPSIS
<span id="Dt--bar"><select id="Dt--bar__hour" name="Dt--bar__hour">
<option selected="selected" value="HH">HH</option>
<option value="0">0</option>
...
"""
if __name__ == '__main__':
import doctest
doctest.testmod()
| {
"repo_name": "camptocamp/formalchemy",
"path": "formalchemy/tests/test_dates.py",
"copies": "2",
"size": "11395",
"license": "mit",
"hash": 292626834294125200,
"line_mean": 23.9343544858,
"line_max": 329,
"alpha_frac": 0.5598946907,
"autogenerated": false,
"ratio": 2.8782520838595604,
"config_test": true,
"has_no_keywords": false,
"few_assignments": false,
"quality_score": 0.44381467745595604,
"avg_score": null,
"num_lines": null
} |
from .formatbase import FormatBase
from .microdvd import MicroDVDFormat
from .subrip import SubripFormat
from .jsonformat import JSONFormat
from .substation import SubstationFormat
from .txt_generic import TXTGenericFormat, MPL2Format
from .exceptions import *
#: Dict mapping file extensions to format identifiers.
FILE_EXTENSION_TO_FORMAT_IDENTIFIER = {
".srt": "srt",
".ass": "ass",
".ssa": "ssa",
".sub": "microdvd",
".json": "json",
".txt": "txt_generic",
}
#: Dict mapping format identifiers to implementations (FormatBase subclasses).
FORMAT_IDENTIFIER_TO_FORMAT_CLASS = {
"srt": SubripFormat,
"ass": SubstationFormat,
"ssa": SubstationFormat,
"microdvd": MicroDVDFormat,
"json": JSONFormat,
"txt_generic": TXTGenericFormat,
"mpl2": MPL2Format,
}
def get_format_class(format_):
"""Format identifier -> format class (ie. subclass of FormatBase)"""
try:
return FORMAT_IDENTIFIER_TO_FORMAT_CLASS[format_]
except KeyError:
raise UnknownFormatIdentifierError(format_)
def get_format_identifier(ext):
"""File extension -> format identifier"""
try:
return FILE_EXTENSION_TO_FORMAT_IDENTIFIER[ext]
except KeyError:
raise UnknownFileExtensionError(ext)
def get_file_extension(format_):
"""Format identifier -> file extension"""
if format_ not in FORMAT_IDENTIFIER_TO_FORMAT_CLASS:
raise UnknownFormatIdentifierError(format_)
for ext, f in FILE_EXTENSION_TO_FORMAT_IDENTIFIER.items():
if f == format_:
return ext
raise RuntimeError("No file extension for format %r" % format_)
def autodetect_format(content):
"""Return format identifier for given fragment or raise FormatAutodetectionError."""
formats = set()
for impl in FORMAT_IDENTIFIER_TO_FORMAT_CLASS.values():
guess = impl.guess_format(content)
if guess is not None:
formats.add(guess)
if len(formats) == 1:
return formats.pop()
elif not formats:
raise FormatAutodetectionError("No suitable formats")
else:
raise FormatAutodetectionError("Multiple suitable formats (%r)" % formats)
| {
"repo_name": "pannal/Subliminal.bundle",
"path": "Contents/Libraries/Shared/pysubs2/formats.py",
"copies": "1",
"size": "2172",
"license": "mit",
"hash": -4306110457341772000,
"line_mean": 30.9411764706,
"line_max": 88,
"alpha_frac": 0.6855432781,
"autogenerated": false,
"ratio": 4.007380073800738,
"config_test": false,
"has_no_keywords": false,
"few_assignments": false,
"quality_score": 1,
"avg_score": 0.0021815476859768155,
"num_lines": 68
} |
from .format_edges import format_edge
def adj_matrix(vertices, formatted_edges, visual = False):
"""
Generates an adjacency matrix for a graph G with n vertices and E edges
Args:
vertices: The number of vertices (should be numbered 0 to n - 1 / 1 to n)
formatted_edges: List of edges of graph G (formatted)
visual: Set to True for additional screen output
Returns:
The adjacency matrix representing the graph G
Time:
O(E)
"""
am = [[0 for i in range(vertices + 1)] for i in range(vertices + 1)]
if visual:
visual_string = "Adjacency Matrix:\n/\t"
for v in range(vertices + 1):
visual_string += "{}\t".format(v)
visual_string += "\n " + "--------" * (vertices + 1)
for e in formatted_edges:
am[e.start][e.end] = 1
if not e.directed:
am[e.end][e.start] = 1
if visual:
for v in range(vertices + 1):
visual_string += "\n{} |\t".format(v)
for v2 in range(vertices + 1):
visual_string += "{}\t".format(am[v][v2])
print(visual_string)
return am
def adj_list(vertices, formatted_edges, visual = False):
"""
Generates an adjacency list for a graph G with n vertices and E edges
Args:
vertices: The number of vertices (should be numbered 0 to n - 1 / 1 to n)
formatted_edges: List of edges of graph G (formatted)
visual: Set to True for additional screen output
Returns:
The adjacency list representing the graph G
Time:
O(E)
"""
al = [[] for i in range (vertices + 1)]
if visual:
print("Adjacency List:\nVertex\t| Connected vertices")
for e in formatted_edges:
al[e.start].append(e.end)
if not e.directed:
al[e.end].append(e.start)
if visual:
for v in range(vertices + 1):
print("{}\t| {}".format(v, al[v]))
return al
def adj_list_with_edges(vertices, formatted_edges, visual = False):
"""
Generates a modified adjacency list for a graph G with n vertices and E edges
Args:
vertices: The number of vertices (should be numbered 0 to n - 1 / 1 to n)
formatted_edges: List of edges of graph G (formatted)
visual: Set to True for additional screen output
Returns:
The adjacency matrix representing the graph G. Instead of a list of vertices
connected to each vertex, a list of the connecting edges is provided instead
Time:
O(E)
"""
al = [[] for i in range (vertices + 1)]
if visual:
print("Adjacency List:\nVertex\t| Connected vertices")
for e in formatted_edges:
al[e.start].append(e)
if not e.directed:
al[e.end].append(format_edge(e.end, e.start, False, e.weight))
if visual:
for v in range(vertices + 1):
visual_string = "{}\t|".format(v)
for e in al[v]:
visual_string += " [{} --> {}, weight {}]\t".format(e.start, e.end, e.weight)
print(visual_string)
return al | {
"repo_name": "aryrobocode/apothecary",
"path": "apothecary/cs/graphs/adjacency.py",
"copies": "1",
"size": "2720",
"license": "mit",
"hash": -269178116481824830,
"line_mean": 24.6698113208,
"line_max": 81,
"alpha_frac": 0.6650735294,
"autogenerated": false,
"ratio": 3.0425055928411635,
"config_test": false,
"has_no_keywords": false,
"few_assignments": false,
"quality_score": 0.42075791222411635,
"avg_score": null,
"num_lines": null
} |
from .format import DrmFormat
from .framebuffer import DrmFramebuffer
from .buffer import DrmDumbBuffer
class DrmImageFramebuffer(DrmFramebuffer):
def __init__(self, drm=None, format_=None, width=None, height=None, bo=None):
if drm and format_ and width and height and bo is None:
bo = DrmDumbBuffer(drm, format_, width, height)
elif (drm or format_ or width or height) and bo is None:
raise TypeError()
super(DrmImageFramebuffer, self).__init__(bo)
self._setup()
def _setup(self):
from PIL import Image
self.bo.mmap()
if self.format.name == 'XR24':
# didn't find an XRGB format
self.image = Image.new("RGBX", (self.width, self.height))
else:
raise ValueError("DrmImageFramebuffer does not support format '%s'" % self.format.name)
def flush(self, x1=None, y1=None, x2=None, y2=None):
# FIXME: Revisit and see if this can be sped up and support big endian
# Convert RGBX -> Little Endian XRGB
b = bytearray(self.image.tobytes())
b[0::4], b[2::4] = b[2::4], b[0::4]
self.bo.map[:] = bytes(b)
super(DrmImageFramebuffer, self).flush(x1, y1, x2, y2)
| {
"repo_name": "notro/pydrm",
"path": "pydrm/image.py",
"copies": "1",
"size": "1233",
"license": "mit",
"hash": 3732994123326634000,
"line_mean": 40.1,
"line_max": 99,
"alpha_frac": 0.6163828062,
"autogenerated": false,
"ratio": 3.378082191780822,
"config_test": false,
"has_no_keywords": false,
"few_assignments": false,
"quality_score": 0.44944649979808216,
"avg_score": null,
"num_lines": null
} |
from format import Format
from message import MessageType
from random import randint
class Processor(object):
def __init__(self):
pass
def process_message(self, data):
m = Format.format(data)
m_type = m.get_type()
body = m.get_body()
cert = "123456"
if self.identify(cert):
if m_type == MessageType.REG:
result = self.register(body)
if m_type == MessageType.STRA:
result = self.process_strategy(body)
return result
def identify(self, cert):
return True
def register(self, body):
uuid = self.create_uuid()
agent_ip = body['sps_agent_ip']
agent_port = body['sps_agent_port']
cert_type = body['certificate_type']
cert_value = body['certificate_value']
info = (uuid, agent_ip, agent_port, cert_type, cert_value)
self.sync_ckm(info)
if self.sync_database(info):
return {'return':'success', 'sps_agent_uuid':uuid}
def create_uuid(self):
uuid = randint(1, 1000)
return uuid
def sync_ckm(self, info):
print "send info %s to ckm success" % str(info)
return True
def sync_database(self, info):
print "write %s to database success" % str(info)
return True
def process_strategy(self, body):
vm_uuid = body['vm_uuid']
vm_info = self.get_info_from_nova(vm_uuid)
self.get_strategy_from_database()
self.send_info_to_ckm()
strategy = self.packet_strategy()
return strategy
| {
"repo_name": "tantexian/sps-2014-12-4",
"path": "sps/api/v1/socket/processor.py",
"copies": "1",
"size": "1597",
"license": "apache-2.0",
"hash": 707956436318831000,
"line_mean": 29.1320754717,
"line_max": 66,
"alpha_frac": 0.5754539762,
"autogenerated": false,
"ratio": 3.7843601895734595,
"config_test": false,
"has_no_keywords": false,
"few_assignments": false,
"quality_score": 0.48598141657734595,
"avg_score": null,
"num_lines": null
} |
from format import REXByte
from io import BytesIO
import xml.etree.ElementTree as ET
opCodeData = ET.fromstring(open("x86-64-ref.xml").read())
bytesToName = {}
prefixes = []
def extactOpCodes(superHeading):
ocs = {}
superGroup = opCodeData.find(superHeading)
for ocXML in superGroup.findall(".//pri_opcd"):
vStr = ocXML.get("value")
group = ocXML.find(".//grp1")
if (group is not None) and (group.text == "prefix"):
prefixes.append(vStr)
continue
ocs[vStr] = ocXML.find(".//mnem").text
return ocs
oneByteCodes = extactOpCodes(".//one-byte")
twoByteCodes = extactOpCodes(".//two-byte")
twoByteCodes = {"0F" + code: nm for code, nm in twoByteCodes.items()}
allCodes = {}
allCodes.update(oneByteCodes)
allCodes.update(twoByteCodes)
for code, nm in sorted(allCodes.items()):
print(code, nm)
_qryResult = {}
def queryCodeByBytes(bytez, extInt=None):
assert len(bytez) in [1, 2]
if bytez in _qryResult:
return _qryResult
if len(bytez) == 1:
sg = opCodeData.find(".//one-byte")
if len(bytez) == 2:
sg = opCodeData.find(".//two-byte")
# MRG NOTE: Stupid and slow
for ocXML in sg.findall(".//pri_opcd"):
# rightOC = int(ocXML.get("value"), base=16) == bytez[-1]
for ent in ocXML.findall(".//entry"):
if extInt is None:
return ent
entryExt = int(ent.find(".//opcd_ext").text)
if entryExt == extInt:
return ent
return None
def ocBytesToName(bytez):
ocXML = queryCodeByBytes(bytez)
return ocXML.find(".//mnem").text
possiblePrefixes = {0xF0: "LOCK", 0xF2: "REP/REPE", 0xF3: "REPNE",
0x2E: "CS", 0x36: "SS", 0x3E: "DS",
0x26: "ES", 0x64: "FS", 0x65: "GS",
0x66: "DATA", 0x67: "ADDR"}
for i in range(16):
possiblePrefixes[0x40 + i] = "REX?"
def readOpCode(flo):
oc1 = flo.read(1)
if oc1[0] == 0x0F:
return oc1 + flo.read(1)
else:
return oc1
def floPeek(flo):
before = flo.tell()
b = flo.read(1)
flo.seek(before)
return b
def detectPrefixes(flo):
"""
Given a FLO, read it forward until there are no prefixes remaining.
Return a list of single byte prefix codes.
"""
pfx = []
while True:
# Inspect the byte, and decide if it is a possible prefix
byte = floPeek(flo)
if byte[0] not in possiblePrefixes:
break
# If it is, add it to the list
pfx.append(flo.read(1)[0])
# Sanity check!
assert len(pfx) <= 4
return pfx
# [['40', . . . '4f']]
rexPrefixes = ["%x" % i for i in range(0x40, 0x50)]
# Vex prefixes
vexPrefixes = [0xC4, 0xC5]
def processPrefixes(flo):
# Pull the prefixes off of the flo
pfxs = detectPrefixes(flo)
print("%i prefixes detected." % len(pfxs))
# Check if this OP is "locked"
lock = 0xf0 in pfxs
# Decode all rex bytes. Use only the last
rexByte = REXByte(0x40) # MRG NOTE: This changes for i386
vex = None
for pfx in pfxs:
if pfx in rexPrefixes:
rexByte = REXByte(pfx)
continue
# Barf on VEX, NotImplemented
if pfx in vexPrefixes:
raise RuntimeError("VEX NOT IMPLEMENTED")
# Decode the address/register sizes
aSize = 32
dSize = 32
if 0x67 in pfxs:
aSize = 64
if rexByte and rexByte.w:
dSize = 64
else:
if 0x66 in pfxs:
dSize = 16
else:
dSize = 32
return lock, rexByte, vex, dSize, aSize
def decodeOpCodeName(ocBytes):
pass
def readMODRM(flo, rexByte):
modrmByte = flo.read(1)[0]
# MRG TODO:
rex_r = 0
reg = ((modrmByte >> 3) & 7) | rex_r
mod = (modrmByte >> 6) & 3
return mod, reg
def decodeML(bytez):
bio = BytesIO(bytez)
pfxs = processPrefixes(bio)
print(len(pfxs), "prefixes detected", repr(pfxs))
opCode = readOpCode(bio)
print(opCode, ocBytesToName(opCode))
# needsMODRM(opCode)
if __name__ == "__main__":
decodeML(b"\x55") # PUSH EBP
decodeML(b"\x8B\xEC") # MOV EBP, ESP
decodeML(b"\x66\x00")
decodeML(b"\x0F\x58")
| {
"repo_name": "meawoppl/purgatory",
"path": "tape/disasm/hardway.py",
"copies": "1",
"size": "4260",
"license": "bsd-2-clause",
"hash": -8217833880980387000,
"line_mean": 20.9587628866,
"line_max": 71,
"alpha_frac": 0.5774647887,
"autogenerated": false,
"ratio": 3.0559540889526544,
"config_test": false,
"has_no_keywords": false,
"few_assignments": false,
"quality_score": 0.4133418877652654,
"avg_score": null,
"num_lines": null
} |
from formation_flight.aircraft.models import Aircraft
from lib.geo.waypoint import Waypoint
from lib.geo.route import Route
from lib.geo.visualization import GCMapper
from formation_flight.hub.builders import Builder
import config
def run():
planes = [
Aircraft('FLT001', Route([Waypoint('AMS'), Waypoint('JFK')]), 12),
Aircraft('FLT001', Route([Waypoint('AMS'), Waypoint('ORD')]), 12),
Aircraft('FLT001', Route([Waypoint('AMS'), Waypoint('EWR')]), 12),
Aircraft('FLT002', Route([Waypoint('DUS'), Waypoint('BOS')]), 12),
Aircraft('FLT003', Route([Waypoint('FRA'), Waypoint('EWR')]), 0),
Aircraft('FLT004', Route([Waypoint('BRU'), Waypoint('LAX')]), 11),
Aircraft('FLT005', Route([Waypoint('AMS'), Waypoint('SFO')]), 7),
Aircraft('FLT007', Route([Waypoint('AMS'), Waypoint('LAX')]), 100),
Aircraft('FLT008', Route([Waypoint('BRU'), Waypoint('SFO')]), 100),
Aircraft('FLT009', Route([Waypoint('CDG'), Waypoint('LAX')]), 100),
]
routes = []
for flight in planes:
routes.append(flight.route)
builder = Builder(routes)
builder.build_hubs(config.count_hubs, config.Z)
for flight in planes:
# Find the hub belonging to this route
hub = builder.get_hub_by_route(flight.route)
# Assign hub by injecting into route
flight.route.waypoints = [flight.route.waypoints[0],
hub,
flight.route.waypoints[1]]
#viz = GCMapper()
#for plane in planes:
# viz.plot_route(plane.route)
# viz.plot_point(plane.route.waypoints[0])
# viz.plot_point(plane.route.waypoints[-1])
#
#for hub in builder.hubs:
# viz.plot_point(hub, formatting = 'bo')
#
#viz.render() | {
"repo_name": "mauzeh/formation-flight",
"path": "sandbox/locate_hubs.py",
"copies": "1",
"size": "1834",
"license": "mit",
"hash": 1209329474908266500,
"line_mean": 34.2884615385,
"line_max": 75,
"alpha_frac": 0.592693566,
"autogenerated": false,
"ratio": 3.257548845470693,
"config_test": false,
"has_no_keywords": false,
"few_assignments": false,
"quality_score": 0.9259085893277976,
"avg_score": 0.01823130363854346,
"num_lines": 52
} |
from formative.models import FormativeBlob, InlineFormativeBlob
from formative.registry import FormativeType
from tests.testproject.testapp.forms import (
SimpleForm, FieldsetForm, FancyForm, BookRelatedForm)
class SimpleType(FormativeType):
name = 'simple'
form_class = SimpleForm
class FieldsetIdentifier(FormativeType):
name = 'fieldset-identifier'
form_class = FieldsetForm
fieldsets = [
(None, {'fields': ['unique_identifier']}),
('Title', {'fields': ['title']}),
('Body', {'fields': ['body']})
]
class FieldsetNoIdentifier(FormativeType):
name = 'fieldset-no-identifier'
form_class = FieldsetForm
fieldsets = [
('Title', {'fields': ['title']}),
('Body', {'fields': ['body']})
]
class FancyType(FormativeType):
name = 'fancy'
form_class = FancyForm
fieldsets = [
(None, {'fields': ['is_fancy']}),
('Dates & Time', {'fields': ['date_of_birth', 'time_of_day']}),
('Numbers', {'fields': ['number_of_fingers', 'income']}),
('Selects', {'fields': ['favorite_color', 'family_members']}),
]
class RelatedType(FormativeType):
name = 'related'
form_class = BookRelatedForm
FormativeBlob.register(
SimpleType, FieldsetIdentifier,
FieldsetNoIdentifier, FancyType, RelatedType)
InlineFormativeBlob.register(SimpleType, FancyType)
| {
"repo_name": "jaap3/django-formative",
"path": "tests/testproject/testapp/formative_types.py",
"copies": "1",
"size": "1384",
"license": "mit",
"hash": 2060930273480630800,
"line_mean": 26.137254902,
"line_max": 71,
"alpha_frac": 0.6437861272,
"autogenerated": false,
"ratio": 3.512690355329949,
"config_test": false,
"has_no_keywords": false,
"few_assignments": false,
"quality_score": 0.965647648252995,
"avg_score": 0,
"num_lines": 51
} |
from formatter2 import Formatter
def test_assignment():
assert Formatter.format_string('a = 1') == 'a = 1\n\n'
assert Formatter.format_string('a != b') == 'a != b\n\n'
assert Formatter.format_string('a % b') == 'a % b\n\n'
assert Formatter.format_string('a %= b') == 'a %= b\n\n'
assert Formatter.format_string('a & b') == 'a & b\n\n'
assert Formatter.format_string('a &= b') == 'a &= b\n\n'
assert Formatter.format_string('a * b') == 'a * b\n\n'
assert Formatter.format_string('a ** b') == 'a ** b\n\n'
assert Formatter.format_string('a **= b') == 'a **= b\n\n'
assert Formatter.format_string('a *= b') == 'a *= b\n\n'
assert Formatter.format_string('a + b') == 'a + b\n\n'
assert Formatter.format_string('a += b') == 'a += b\n\n'
assert Formatter.format_string('a - b') == 'a - b\n\n'
assert Formatter.format_string('a -= b') == 'a -= b\n\n'
assert Formatter.format_string('a / b') == 'a / b\n\n'
assert Formatter.format_string('a // b') == 'a // b\n\n'
assert Formatter.format_string('a //= b') == 'a //= b\n\n'
assert Formatter.format_string('a /= b') == 'a /= b\n\n'
assert Formatter.format_string('a < b') == 'a < b\n\n'
assert Formatter.format_string('a << b') == 'a << b\n\n'
assert Formatter.format_string('a <<= b') == 'a <<= b\n\n'
assert Formatter.format_string('a <= b') == 'a <= b\n\n'
assert Formatter.format_string('a == b') == 'a == b\n\n'
assert Formatter.format_string('a > b') == 'a > b\n\n'
assert Formatter.format_string('a >= b') == 'a >= b\n\n'
assert Formatter.format_string('a >> b') == 'a >> b\n\n'
assert Formatter.format_string('a >>= b') == 'a >>= b\n\n'
assert Formatter.format_string('a ^ b') == 'a ^ b\n\n'
assert Formatter.format_string('a ^= b') == 'a ^= b\n\n'
assert Formatter.format_string('a is b') == 'a is b\n\n'
assert Formatter.format_string('a is not b') == 'a is not b\n\n'
assert Formatter.format_string('a | b') == 'a | b\n\n'
assert Formatter.format_string('a |= b') == 'a |= b\n\n'
assert Formatter.format_string('a = b') == 'a = b\n\n'
if __name__ == '__main__':
for k, v in list(globals().items()):
if k.startswith('test_') and hasattr(v, '__call__'):
print(('Running %r' % k))
v()
| {
"repo_name": "WoLpH/python-formatter",
"path": "tests/test_operators.py",
"copies": "1",
"size": "2309",
"license": "bsd-3-clause",
"hash": 3700016719945067500,
"line_mean": 50.3111111111,
"line_max": 68,
"alpha_frac": 0.5465569511,
"autogenerated": false,
"ratio": 2.8021844660194173,
"config_test": false,
"has_no_keywords": false,
"few_assignments": false,
"quality_score": 0.38487414171194173,
"avg_score": null,
"num_lines": null
} |
from formatter2 import (TokenOffsets, TokenOffset, TOKEN_OFFSETS, tokens,
_stringio)
import pytest
import logging
def test_default_type():
TOKEN_OFFSETS['something_not_existing'] = None
def test_token_offsets():
t = TokenOffsets(None)
assert repr(t)
assert TOKEN_OFFSETS['='].surround
TOKEN_OFFSETS['='].surround = 0, 0
TOKEN_OFFSETS[':'] = TokenOffset(
t,
t.parent.type,
t.parent.token,
children=t,
)
x = tokens.SmartList(1, 2)
assert str(x)
x.copy()
x + x
x.set(5)
y = tokens.Tokens(_stringio.StringIO('a=1\nb=1').readline)
y = list(y)
y[-1] -= y[-1]
y[0].line = ' ' + y[0].line + ' '
str(y[0])
repr(y[0])
logging.error('token: %r :: %s', y[0], y[0])
def test_add():
with pytest.raises(TypeError):
x = tokens.SmartList(1, 2)
x + 'a'
def test_sub():
with pytest.raises(TypeError):
x = tokens.SmartList(1, 2)
x - 1
x - (1, 1)
x - 'a'
| {
"repo_name": "WoLpH/python-formatter",
"path": "tests/test_tokens.py",
"copies": "1",
"size": "1033",
"license": "bsd-3-clause",
"hash": -1013690508562720800,
"line_mean": 19.66,
"line_max": 73,
"alpha_frac": 0.5343659245,
"autogenerated": false,
"ratio": 3.011661807580175,
"config_test": true,
"has_no_keywords": false,
"few_assignments": false,
"quality_score": 0.40460277320801746,
"avg_score": null,
"num_lines": null
} |
from formatter.AbstractFormatter import AbstractFormatter
import html
import os
class IndexElement:
anchor = 0
def __init__(self, content):
self.content = content
self.a = IndexElement.anchor
self.node_list = []
IndexElement.anchor += 1
def addNode(self, e):
self.node_list.append(e)
def getHtmlIndex(index):
html = "<li><a href=\"#%d\">%s</a></li>" % (index.a, index.content)
if len(index.node_list) > 0:
html += "<ol>"
for node in index.node_list:
html += IndexElement.getHtmlIndex(node)
html += "</ol>"
return html
class ResultElement:
def __init__(self):
self.content = ""
class HtmlFormatter(AbstractFormatter):
def make_file(self):
of = open(self.output_file, 'w', encoding="utf-8")
of.write('<!DOCTYPE html><html><head>')
of.write('<meta charset="utf-8">')
of.write('<title>%s</title>' % os.path.basename(self.result_file))
of.write('</head><body>')
# Main data
of.write("<table>")
of.write("<tr><td><b>Author:</b></td><td>%s</td></tr>" % self.result_data['author'])
of.write("<tr><td><b>Config file:</b></td><td>%s</td></tr>" % self.result_data['config']['file'])
of.write("<tr><td><b>Config file SHA256:</b></td><td>%s</td></tr>" % self.result_data['config']['sha256'])
of.write("<tr><td><b>Evidence folder path:</b></td><td>%s</td></tr>" % self.result_data['evidence_folder'])
of.write("</table>")
of.write("<hr>")
result_element = ResultElement()
result_element.content = "<h1>Result</h1>"
index_list = []
index_content = "<h1>Index</h1>"
#of.write("<h2>Result</h2>")
for mc in self.result_data['result']:
index_elem = IndexElement(mc['module_chain_id'])
index_list.append(index_elem)
self.traverse_chain(result_element, index_elem, mc)
index_content += "<ol>"
for node in index_list:
index_content += IndexElement.getHtmlIndex(node)
index_content += "</ol>"
#result_element.content += "<hr />"
of.write(index_content)
of.write(result_element.content)
of.write('</body></html>')
of.close()
def traverse_chain(self, result: ResultElement, index: IndexElement, mc):
result.content += "<h2 id=\"%d\">%s</h2>" % (index.a, mc['module_chain_id'])
for mod in mc['modules']:
mod_id_index = IndexElement(mod['title'])
index.addNode(mod_id_index)
result.content += "<h3 id=\"%d\" style=\"background-color: #ccc;\">%s</h3>" % (mod_id_index.a, mod['title'])
result.content += "<table>"
result.content += "<tr><td><b>Module ID</b></td><td>%s</td></tr>" % mod['mod']
result.content += "<tr><td><b>File count</b></td><td>%s</td></tr>" % mod['files_count']
result.content += "</table>"
if len(mod['data']) > 0:
result.content += "<h4 id=\"%d\" style=\"background-color: #ccc;\">Collected data</h4>" % IndexElement.anchor
mod_id_index.addNode(IndexElement("Collected data"))
file_list = sorted(mod['data'].keys())
for file_name in file_list:
file_data = mod['data'][file_name]
result.content += "<b>%s</b>" % file_name
if len(file_data) > 0:
is_tuple = isinstance(file_data[0], tuple)
if not is_tuple:
result.content += "<ul>"
else:
result.content += "<table>"
for file_data_elem in file_data:
if is_tuple:
result.content += "<tr>"
result.content += "<td style=\"background-color: #ccc;\"><b>%s</b></td><td>%s</td>" % (file_data_elem[0], file_data_elem[1])
result.content += "</tr>"
else:
result.content += "<li>%s</li>" % file_data_elem
if not is_tuple:
result.content += "</ul>"
else:
result.content += "</table>"
try:
if len(mod['extract_data']) > 0:
result.content += "<h4 id=\"%d\">Extracted data</h4>" % IndexElement.anchor
mod_id_index.addNode(IndexElement("Extracted data"))
file_list = sorted(mod['extract_data'].keys())
for file_name in file_list:
file_data = mod['extract_data'][file_name]
table_views = sorted(file_data.keys())
result.content += "<b style=\"background-color: #ccc;\">%s</b><br />" % file_name
for table in table_views:
table_info = file_data[table]
result.content += "<b>%s</b>" % table
result.content += "<table style=\"white-space: nowrap;\">"
for col in table_info[0]:
result.content += "<th style=\"background-color: #ccc;\">%s</th>" % col
for row in table_info[1]:
result.content += "<tr>"
for col_data in row:
cell_data = col_data
if isinstance(col_data, bytes):
cell_data = col_data.decode('utf-8', 'ignore')
elif col_data == None:
cell_data = "NULL"
else:
cell_data = col_data
if isinstance(cell_data, str):
cell_data = html.escape(cell_data)
result.content += "<td style=\"min-width: 100px;\">%s</td>" % cell_data
result.content += "</tr>"
result.content += "</table>"
result.content += '<hr style="margin-bottom: 100px;" />'
except KeyError:
pass
sub_module_chain = None
try:
sub_module_chain = mod['module_chain']
except KeyError:
continue
if sub_module_chain:
result.content += '<hr />'
result.content += "<div style=\"padding-left: 5px; border-left: 3px; border-left-style: dotted; border-left-color: #ccc\""
self.traverse_chain(result, index, sub_module_chain)
result.content += "</div>"
| {
"repo_name": "vdjagilev/desefu-export",
"path": "formatter/html/HtmlFormatter.py",
"copies": "1",
"size": "7031",
"license": "mit",
"hash": 8867363136421968000,
"line_mean": 39.1771428571,
"line_max": 156,
"alpha_frac": 0.456976248,
"autogenerated": false,
"ratio": 4.185119047619048,
"config_test": false,
"has_no_keywords": false,
"few_assignments": false,
"quality_score": 0.5142095295619047,
"avg_score": null,
"num_lines": null
} |
>>> from formatter import AbstractFormatter , NullWriter
>>> from htmllib import HTMLParser
>>> from string import join
>>> class myWriter ( NullWriter ):
... def send_flowing_data( self, str ):
... self . _bodyText . append ( str )
... def __init__ ( self ):
... NullWriter.__init__ ( self )
... self . _bodyText = [ ]
... def _get_bodyText ( self ):
... return join ( self . _bodyText, " " )
... bodyText = property ( _get_bodyText, None, None, "plain text from body" )
...
>>> class MilenaHTMLParser (HTMLParser):
... def do_meta(self, attrs):
... self . metas = attrs
...
>>> mywriter = myWriter ( )
>>> abstractformatter = AbstractFormatter ( mywriter )
>>> parser = MilenaHTMLParser( abstractformatter )
>>> parser . feed ( open ( r'c:\temp.htm' ) . read ( ) )
>>> parser . title
'Astronomical Summary: Hamilton, Ontario'
>>> parser . metas
[('http-equiv', 'REFRESH'), ('content', '1800')]
>>> parser.formatter.writer.bodyText
'Hamilton, Ontario Picture of Earth Local Date 31 October 2001 Temperature 10.8 \xb0C Observation Location 43.17 N, 79.93 W Sunrise: Sunset: 6:53 am 5:13 pm The Moon is Waxing Gibbous (98% of Full) Image created with xearth [1] . Page inspired by design at AUSOM.'
| {
"repo_name": "ActiveState/code",
"path": "recipes/Python/135005_Simple_Applicatihtmllib_Parsing/recipe-135005.py",
"copies": "1",
"size": "1259",
"license": "mit",
"hash": 7350155516825687000,
"line_mean": 45.6296296296,
"line_max": 265,
"alpha_frac": 0.6314535346,
"autogenerated": false,
"ratio": 3.2872062663185377,
"config_test": false,
"has_no_keywords": false,
"few_assignments": false,
"quality_score": 0.44186598009185374,
"avg_score": null,
"num_lines": null
} |
from .formatter import ExternalFormatter, Formatter
from .formatters import format_json
class FormatterRegistry:
def __init__(self):
self.__formatters = []
def populate(self):
self.__formatters = [
ExternalFormatter('Clang', command='clang-format'),
ExternalFormatter('Elm', command='elm-format', args='--stdin'),
ExternalFormatter('Go', command='gofmt'),
ExternalFormatter('Haskell', command='hindent'),
ExternalFormatter(
'JavaScript', command='prettier', args='--stdin'),
Formatter('JSON', formatter=format_json),
ExternalFormatter('Python', command='yapf'),
ExternalFormatter('Rust', command='rustfmt'),
ExternalFormatter('Swift', command='swiftformat'),
ExternalFormatter('Terraform', command='terraform fmt', args='-'),
]
def clear(self):
self.formatters = []
@property
def all(self):
return self.__formatters
def by(self, predicate):
return filter(predicate, self.all)
def by_view(self, view):
source = view.scope_name(0).split(' ')[0].split('.')[1]
return next(self.by(lambda f: source in f.sources), None)
def by_name(self, name):
return next(self.by(lambda f: f.name == name), None)
| {
"repo_name": "Rypac/sublime-format",
"path": "plugin/registry.py",
"copies": "1",
"size": "1341",
"license": "mit",
"hash": 4896026770688036000,
"line_mean": 33.3846153846,
"line_max": 78,
"alpha_frac": 0.5973154362,
"autogenerated": false,
"ratio": 4.339805825242719,
"config_test": false,
"has_no_keywords": false,
"few_assignments": false,
"quality_score": 1,
"avg_score": 0,
"num_lines": 39
} |
from formatter import format_string
import pyparsing as pp
DEBUG = True
def debug(*args, **kwargs):
if DEBUG:
print(*args, **kwargs)
class no_depth_list(list):
"""Class that does not allow any nested lists to be appended, any iterables appended will be unpacked first """
def __lshift__(self, other):
self.append(other)
class ParseException(Exception):
pass
class languageSyntaxOBbase:
"""Base class for language objects"""
JID = 0 # label counter
def __init__(self, *children):
self.parent = None
self.children = children
def parent_own_children(self):
"""Initiates filling of child parents (for codegen callbacks)"""
# debug("{0} parenting children: {0.children}".format(self))
self.parent_children(self.children)
def parent_children(self, *children):
for i in children:
if isinstance(i, languageSyntaxOBbase):
i.set_parent(self)
i.parent_own_children()
elif isinstance(i, (list, tuple, pp.ParseResults)):
self.parent_children(*i)
def set_parent(self, parent):
self.parent = parent
def get_variable(self, VarName, asref=False):
"""Finds stack position of a variable, bubbles up to the parent function"""
if isinstance(VarName, int):
return f"{VarName}"
if not self.parent:
raise ParseException(
"object: {} attempted to gain variable {}, but it has no parent".
format(self, VarName))
else:
# this should bubble up to the parent function
return self.parent.get_variable(VarName, asref)
@classmethod
def assemble_list(cls, cmds):
if isinstance(cmds, (list, tuple)):
for i in cmds:
yield from cls.assemble_list(i)
elif isinstance(cmds, languageSyntaxOBbase):
yield from cmds.assemble()
def assemble(self):
yield from self.assemble_list(self.children)
@property
def num_params(self):
return self.parent.num_params
def __str__(self):
return "<{0.__class__.__name__} object: <parent: {0.parent.__class__.__name__}> <children: {1}>>".format(
self, ", ".join("{}".format(str(i)) for i in self.children))
class mathOP(languageSyntaxOBbase):
def __init__(self, children): # , op, b):
debug(f"Mathop: {children}")
super().__init__(children)
def __str__(self):
return "<{0.__class__.__name__} object: <parent: {0.parent.__class__.__name__}> <children: {1}>>".format(
self, ", ".join("{}".format(str(i)) for i in self.children))
def assemble(self):
"""
Use stack, infix -> postfix -> the stack machine -> return variable in @RET
"""
asm_map = {
"+": "ADD",
"-": "SUB",
"*": "MUL",
"/": "DIV"
}
def parse(expr):
debug(f"parsing: {expr}")
resolved = []
if isinstance(expr, mathOP):
return parse(expr.children)
if isinstance(expr, (int, str, listIndexOB)):
debug(f"ret str: {expr}")
return expr
if isinstance(expr, tuple):
expr = list(expr)
while expr:
i = expr.pop()
if isinstance(i, list):
for i in parse(i):
resolved.append(i)
elif isinstance(i, mathOP):
for i in parse(i.children):
resolved.append(i)
elif i in ["+", "-", "*", "/"]:
next_ = parse(expr.pop())
if isinstance(next_, (str, int)):
next_ = [next_]
prev = resolved.pop()
resolved += next_
resolved.append(prev)
resolved.append(i)
else: # string or int
resolved.append(i)
return resolved
parsed = parse(self.children)
debug(parsed)
for i in parsed:
if isinstance(i, int):
yield f"PUSH {i}"
elif i in ["+", "-", "*", "/"]:
yield "POP @EAX"
yield "POP @ACC"
yield f"{asm_map[i]} @EAX"
yield "PUSH @ACC"
elif isinstance(i, str):
yield f"PUSH {self.get_variable(i)}"
elif isinstance(i, functionCallOB):
yield from i.assemble()
yield "PUSH @RET"
elif isinstance(i, listIndexOB):
yield f"PUSH [{i.location}]"
yield "POP @ACC"
class assignOP(languageSyntaxOBbase):
def __init__(self, setter, val):
self.setter = setter
self.val = val
super().__init__(setter, val)
def __str__(self):
return "<{0.__class__.__name__} object: <parent: {0.parent.__class__.__name__}> <setter: {0.setter}> <val: {0.val}>>".format(
self)
def assemble(self):
if isinstance(self.setter, str):
variable = self.get_variable(self.setter, asref=True)
elif isinstance(self.setter, listIndexOB):
variable = self.setter.location
else:
raise Exception(f"Undefined item to define to, itemtype = {type(self.setter)}")
right_side = self.val.assemble()
# output of right_side always ends in @ACC
yield from right_side
yield f"MOV @ACC {variable}"
class variableOB(languageSyntaxOBbase):
def escape_char(self, char):
d = {
"n": "\n",
"r": "\r"
}
return d.get(char, char)
def escape_string(self, string):
i = 0
while i < len(string):
if string[i] == "\\":
i += 1
yield self.escape_char(string[i])
else:
yield string[i]
i += 1
def __init__(self, type, name, part=None, listinitial=None, *rest):
# if int: (type=type, name=name, part=initial)
# if list: (type=type, name=name, part=length, listinitial=default)
super().__init__()
print(f"VARIABLE: name {name}, type {type}, part {part}, lstninit {listinitial}, rest: {rest}")
self.type = type
self.name = name
if self.type == "list":
if part is None and listinitial is not None:
self.length = len(listinitial) + 1
self.initial = map(ord, self.escape_string(listinitial + "\0"))
elif listinitial is not None and part is not None:
self.length = part
self.initial = [listinitial] * part
else:
self.length = None
self.initial = [None]
self.isref = True
else:
self.isref = False
self.initial = 0 if part is None else part
self.length = 1
def create(self):
if self.type == "list":
for i in self.initial:
yield f"PUSH {i}" # create stack space
else:
yield f"PUSH {self.initial}"
def __str__(self):
return "<{0.__class__.__name__} object: <parent: {0.parent.__class__.__name__}> <name: {0.name}> <initial: {0.initial}> <type: {0.type}> <len: {0.length}>>".format(
self)
def __eq__(self, other):
return self.name == other
class programList(languageSyntaxOBbase):
def __init__(self, *children):
super().__init__(*children)
def assemble(self):
yield from self.assemble_list(self.children)
class comparisonOB(languageSyntaxOBbase):
replaceMap = { # inversed, skips
"<": "meje",
">": "leje",
"==": "nqje",
"!=": "eqje",
">=": "lje",
"<=": "mje"
}
def __init__(self, left, comp, right):
super().__init__()
self.comp = self.replaceMap[comp]
self.left = left
self.right = right
def __str__(self):
return "<{0.__class__.__name__}:{0.comp} <parent: {0.parent.__class__.__name__}> <lhs: {0.left}> <rhs: {0.right}>>".format(
self)
class ComparisonVar(languageSyntaxOBbase):
def parseitem(self, item):
if isinstance(item, str):
return self.get_variable(item)
elif isinstance(item, int):
return f"{item}"
elif isinstance(item, listIndexOB):
return item.location
else:
raise Exception("Error parsing var of comparison")
class whileTypeOB(ComparisonVar):
def __init__(self, comp, *codeblock):
super().__init__()
self.comp = comp
self.codeblock = codeblock
self.children = [self.codeblock, self.comp]
def __str__(self):
return "<{0.__class__.__name__} object: <parent: {0.parent.__class__.__name__}> <comparison: {0.comp}> <codeblock: {1}>>".format(
self, ", ".join(str(i) for i in self.codeblock))
def assemble(self):
yield f"_jump_start_{self.JID} CMP {self.parseitem(self.comp.left)} {self.parseitem(self.comp.right)}"
yield f"{self.comp.comp} jump_end_{self.JID}"
yield from self.assemble_list(self.codeblock)
yield f"JUMP jump_start_{self.JID}"
yield f"_jump_end_{self.JID} NOP"
languageSyntaxOBbase.JID += 1
class ifTypeOB(ComparisonVar):
def __init__(self, comp, *codeblock):
super().__init__()
self.comp = comp
self.codeblock = codeblock
self.children = [self.codeblock, self.comp]
def assemble(self):
yield f"CMP {self.parseitem(self.comp.left)} {self.parseitem(self.comp.right)}"
yield f"{self.comp.comp} jump_end_{self.JID}"
yield from self.assemble_list(self.codeblock)
yield f"_jump_end_{self.JID} NOP"
languageSyntaxOBbase.JID += 1
def __str__(self):
print(type(self.codeblock))
return "<{0.__class__.__name__} object: <parent: {0.parent.__class__.__name__}> <comparison: {0.comp}> <codeblock: {1}>>".format(
self, ", ".join(str(i) for i in self.codeblock))
def languageSyntaxOB(type_, *children):
types = { # TODO: correct parser to do any form of "word (stuff) {code}"
"while": whileTypeOB,
"if": ifTypeOB
}
return types[type_](*children)
class functionCallOB(languageSyntaxOBbase):
def __init__(self, functionName, params=[]):
super().__init__(*params)
self.params = params
self.functionName = functionName
def __str__(self):
return "<{0.__class__.__name__} object: <parent: {0.parent.__class__.__name__}> <name: {0.functionName}> <args: {1}>>".format(
self, ", ".join("{}".format(str(i)) for i in self.params))
def assemble(self):
vars_ = no_depth_list()
stack_pos = 0
out = no_depth_list()
debug(f"functioncallOB_vals: {self.params}")
for i in self.params:
debug(f"valinst: {i}")
if isinstance(i, int):
vars_ << ("val", f"{i}")
elif isinstance(i, str):
vars_ << ("var", self.get_variable(i))
elif isinstance(i, listIndexOB):
vars_ << ("var", "[" + i.location + "]")
elif isinstance(i, mathOP):
for k in i.assemble():
yield k
yield "PUSH @ACC"
vars_ << ("stpos", stack_pos)
stack_pos += 1
elif isinstance(i, functionCallOB):
for k in i.assemble():
yield k
yield "PUSH @RET" # functions end up in the ret register
vars_ << ("stpos", stack_pos)
stack_pos += 1
# decide on vars
debug(f"VARS FOR FUNC CALL: {vars_}")
assembled_vars = no_depth_list()
for j, k in vars_:
debug(f"varsdebug: name->{j}: val->{k}")
if j == "stpos":
assembled_vars << f"[@STK+{stack_pos+k}]"
else:
assembled_vars << k
#
#
# Turn list of vars_ into: `CALL arg1 [arg2 [...]]
#
#
yield "CALL {} {}".format(self.functionName, " ".join(assembled_vars))
yield "MOV @STK @ACC" # we need to clean up our stack located arguments
yield f"ADD {stack_pos}"
yield "MOV @ACC @STK"
debug(f"FUNCcOP: {out}")
def varList(*vars): # idk TODO: Fuck this
return vars
class listIndexOB(languageSyntaxOBbase):
def __init__(self, name, index):
super().__init__(index)
self.name = name
self.index = index
@property
def location(self): # resolves index to the value at the index
base = self.get_variable(self.name)
if isinstance(self.index, int): # static
return f"{base}-{self.index}"
if isinstance(self.index, str): # vars
return f"{base}-{self.get_variable(self.index)}"
class functionDefineOB(languageSyntaxOBbase):
def __init__(self, name, params, vars_, program):
super().__init__(program)
self.name = name
self.params = [] if params is None else params[::-1]
self.vars_ = [] if vars_ is None else vars_
def __str__(self):
return "<{0.__class__.__name__} object: <parent: {0.parent.__class__.__name__}> <name: {0.name}> <params: {1}> <vars: {2}> <children: {3}>>".format(
self, [str(i) for i in self.params], [str(i) for i in self.vars_], [str(i) for i in self.children])
# gets the position of a local variable/ passed arg
def get_variable(self, VarName, asref=False):
'''
returns a variables location in memory
func wew(a,b,c){
vars{
d:=0;
e:=4;
}
program{
return a
}
}
stack; |var| position relative to @LSTK, position in var/ param list:
|return address| + 4
|a| + 3, 0
|b| + 2, 1
|c| + 1, 2
|old local stack pointer| +- 0
|d| - 1, 0
|e| - 2, 1
'''
if VarName in self.params:
index = sum(i.length for i in self.params[
:self.params.index(VarName)]) + 1
# if var was passed to program as a reference, just return it
if asref:
return f"@lstk+{index}"
return f"[@lstk+{index}]"
elif VarName in self.vars_:
index = sum(i.length for i in self.vars_[
:self.vars_.index(VarName)]) + 1
var = self.vars_[self.vars_.index(VarName)]
if var.isref or asref:
# variable is located on the local stack frame, get a
# reference to it
return f"@lstk-{index}"
else: # is a non pass by ref, so just get the value itself
return f"[@lstk-{index}]"
else:
debug(f"GETPASSVAR FAILED: {VarName}")
raise ParseException(
f"Attempt to access variable not in scope. Current function: {self.name}, variable: {VarName}")
@property
def num_params(self):
return len(self.params)
def assemble(self):
# functions are jumped to with stack looking like: [ret, a, b, c]
# we push lstk, then the function args
yield f"_{self.name} NOP"
# save previous base pointer [ret, a, b, c, lstk]
yield "PUSH @LSTK"
yield "MOV @STK @LSTK" # copy current stack pointer to base pointer
if self.vars_:
for i in self.vars_: # insert our function local vars
yield from i.create()
yield from self.assemble_list(self.children)
yield "MOV 0 @RET" # setup fall through return function
yield "MOV @LSTK @STK" # pull stack pointer back to base pointer
# restore base pointer of previous function
yield "MOV [@STK] @LSTK"
yield "MOV @STK @ACC"
yield f"ADD {self.num_params+1}"
yield "MOV @ACC @STK"
yield "RET"
class returnStmtOB(languageSyntaxOBbase):
def __init__(self, returnVar):
super().__init__(returnVar)
self.returnVar = returnVar
def assemble(self):
"""
how to return:
move returned variable to @RET
move @LSTK to @STK (reset stack pointer)
move [@LSTK] to @STK (return old pointer)
add <number of vars> to @STK (push stack above pointer)
call RET
"""
if isinstance(self.returnVar, str): # assume variable name
yield f"MOV {self.get_variable(self.returnVar)} @RET"
elif isinstance(self.returnVar, int):
yield f"MOV {self.returnVar} @RET"
elif isinstance(self.returnVar, listIndexOB):
yield f"MOV [{self.returnVar.location}] @RET"
yield "MOV @LSTK @STK"
yield "MOV [@STK] @LSTK"
yield "MOV @STK @ACC"
yield f"ADD {self.num_params+1}"
yield "MOV @ACC @STK"
yield "RET"
class inlineAsmOB(languageSyntaxOBbase):
def __init__(self, *asm):
debug(f"asm = {asm}")
super().__init__(asm)
self.asm = asm
def assemble(self):
return self.asm
def wrapped_elem(wrapper, elem):
wrap = pp.Literal(wrapper).suppress()
return wrap + elem + wrap
class atoms:
integer = pp.Word(pp.nums).setParseAction(lambda t: int(t[0]))
variable = pp.Word(pp.alphas + "_", pp.alphanums + "_", exact=0)
semicol = pp.Literal(";").suppress()
equals = pp.Literal(":=").suppress()
opening_curly_bracket = pp.Literal("{").suppress()
closing_curly_bracket = pp.Literal("}").suppress()
lparen = pp.Literal("(").suppress()
rparen = pp.Literal(")").suppress()
lsqrbrk = pp.Literal("[").suppress()
rsqrbrk = pp.Literal("]").suppress()
comma = pp.Literal(",").suppress()
comparison = pp.oneOf("== != > < >= <=")
addsub = pp.oneOf("+ -")
muldiv = pp.oneOf("* /")
oplist = [(muldiv, 2, pp.opAssoc.LEFT),
(addsub, 2, pp.opAssoc.LEFT)]
intvar = pp.Keyword("int") + variable # ['int', name]
listype = pp.Keyword("list") + variable
listvar = (listype + lsqrbrk +
pp.Optional(integer, default=None) + rsqrbrk) # ['list', name, size]
typedvar = listvar | intvar
initTypedVar = (intvar | listype).setParseAction(lambda t: variableOB(*t))
listindex = variable + lsqrbrk + (integer | variable) + rsqrbrk
listindex.setParseAction(lambda t: listIndexOB(*t))
# attempt to parse a listindex first, since otherwise a variable will be
# parsed by mistake
operand = listindex | integer | variable
text = pp.Word(pp.alphanums + "_ $[]+-@\\")
class FuncCallSolver:
functionCall = pp.Forward()
arg = functionCall | atoms.operand
args = arg + pp.ZeroOrMore(atoms.comma + arg)
args.setParseAction(lambda t: varList(*t))
functionCall << atoms.variable + atoms.lparen + \
pp.Optional(args) + atoms.rparen
functionCall.setParseAction(lambda s, l, t: functionCallOB(*t))
functionCallInline = functionCall + atoms.semicol
class AssignmentSolver:
operator = FuncCallSolver.functionCall | atoms.operand
expr = pp.infixNotation(
operator, atoms.oplist).setParseAction(lambda s, l, t: mathOP(t.asList()))
assign = (atoms.listindex | atoms.variable) + atoms.equals + expr
assignmentCall = assign + atoms.semicol
assignmentCall.setParseAction(lambda s, l, t: assignOP(*t))
class returnStatement:
returnStmnt = (pp.Keyword("return").suppress() +
atoms.operand + atoms.semicol).setParseAction(lambda t: returnStmtOB(*t))
class inlineAsm:
asm = (pp.Keyword("_asm").suppress() + atoms.opening_curly_bracket +
atoms.text + pp.ZeroOrMore(atoms.comma + atoms.text) +
atoms.closing_curly_bracket()).setParseAction(lambda t: inlineAsmOB(*t))
class SyntaxBlockParser:
program = AssignmentSolver.assignmentCall | FuncCallSolver.functionCallInline | returnStatement.returnStmnt | inlineAsm.asm
syntaxBlock = pp.Forward()
Syntaxblk = pp.OneOrMore(syntaxBlock | program)
condition = atoms.lparen + atoms.operand + \
atoms.comparison + atoms.operand + atoms.rparen
condition.setParseAction(lambda s, l, t: comparisonOB(*t))
blockTypes = pp.Keyword("if") | pp.Keyword("while")
syntaxBlock << blockTypes + condition + \
atoms.opening_curly_bracket + Syntaxblk + atoms.closing_curly_bracket
syntaxBlock.setParseAction(
lambda t: languageSyntaxOB(*t))
class OperationsObjects:
SyntaxBlocks = SyntaxBlockParser.syntaxBlock
assignBlocks = AssignmentSolver.assignmentCall
functionCallBlocks = FuncCallSolver.functionCallInline
statements = returnStatement.returnStmnt
asm = inlineAsm.asm
operation = SyntaxBlocks | assignBlocks | functionCallBlocks | statements | asm
@classmethod
def parse(cls, string):
return cls.operation.parseString(string).asList()
class ProgramObjects:
program = pp.Keyword("program").suppress() + atoms.opening_curly_bracket + \
pp.OneOrMore(OperationsObjects.operation) + atoms.closing_curly_bracket
program.setParseAction(lambda s, l, t: programList(*t))
class FunctionDefineParser:
var_assign_line = atoms.typedvar + atoms.equals + (atoms.integer | wrapped_elem('"', atoms.text)) + atoms.semicol
var_assign_line.setParseAction(lambda s, l, t: variableOB(*t))
var_noassign_line = atoms.typedvar + atoms.semicol
var_noassign_line.setParseAction(lambda s, l, t: variableOB(*t, 0))
# init params that start with nothing to 0 with 0
varline = var_assign_line | var_noassign_line
varsblock = pp.Keyword("vars").suppress() + atoms.opening_curly_bracket + \
pp.OneOrMore(varline) + atoms.closing_curly_bracket
varsblock.setParseAction(lambda s, l, t: varList(*t))
args = atoms.initTypedVar + \
pp.ZeroOrMore(atoms.comma + atoms.initTypedVar)
argblock = atoms.lparen + pp.Optional(args) + atoms.rparen
argblock.setParseAction(lambda t: varList(*t))
startblock = pp.Keyword("func").suppress() + atoms.variable + \
argblock + atoms.opening_curly_bracket
function = startblock + \
pp.Optional(varsblock, default=None) + \
ProgramObjects.program + atoms.closing_curly_bracket
function.setParseAction(lambda s, l, t: functionDefineOB(*t))
@classmethod
def parse(cls, string):
return cls.function.parseString(string).asList()
class ProgramSolver:
functions = pp.OneOrMore(FunctionDefineParser.function)
@classmethod
def parse(cls, string):
return cls.functions.parseString(string).asList()
def load_parse(fname):
with open(fname) as f:
program = f.read()
functions = ProgramSolver.parse(program) # .strip("\n"))
compiled = ["call main", "halt"]
debug(f"functions = {functions}")
for i in functions:
i.parent_own_children()
print(format_string(str(i)))
compiled += i.assemble()
with open(f"{fname}.compiled", "w+") as f:
f.writelines("\n".join(compiled))
if __name__ == "__main__":
import sys
for i in sys.argv[1:]:
print(f"compiling {i}")
load_parse(i)
| {
"repo_name": "nitros12/Cpu_emulator",
"path": "wew compiler/compiler.py",
"copies": "1",
"size": "23625",
"license": "mit",
"hash": -2343393302166887400,
"line_mean": 31.2305593452,
"line_max": 172,
"alpha_frac": 0.5578835979,
"autogenerated": false,
"ratio": 3.8049605411499434,
"config_test": false,
"has_no_keywords": false,
"few_assignments": false,
"quality_score": 0.9861006991322765,
"avg_score": 0.0003674295454357486,
"num_lines": 733
} |
from .formatter import Formatter
from .token import TokenGenerator
class NamedTuple(object):
"""\
Make our own version of namedtuple that isn't so ugly.
If the class name is not given, all attributes are
capitalized and concatenated to 'NamedTuple' as the
class name. ::
HelloWorldNamedTuple = NamedTuple('hello', 'world')
# 'HelloWorldNamedTuple'
HelloWorldNamedTuple.__name__
:param name: the name of the class to create. If not
given, a name is created from the
parameters (see above).
"""
def __new__(cls, *attrs, **kwargs):
cls_name = '{0}NamedTuple'.format(
''.join([a.capitalize() for a in attrs]))
new_name = kwargs.get('name', cls_name)
def __new__(cls, *args):
return tuple.__new__(cls, args)
def __getnewargs__(self):
return tuple(self)
def __repr__(self):
args = ['{0}={1}'.format(attr,
repr(self[i])) for (i, attr) in enumerate(attrs)]
pairs = ', '.join(args)
return '{name}({pairs})'.format(
name=self.__class__.__name__, pairs=pairs)
new_attrs = {
'__new__': __new__,
'__getnewargs__': __getnewargs__,
'__repr__': __repr__,
}
def make_attr(i):
return lambda self: tuple.__getitem__(self, i)
# Create an attribute with the names
for i, attr in enumerate(attrs):
new_attrs[attr] = property(make_attr(i))
return type(new_name, (tuple,), new_attrs)
class Pair(NamedTuple('key', 'token')):
"""\
A named tuple that contains :attr key <Pair.key>: and
:attr token <Pair.token>: attributes.
The key and token can be accessed by indexing or
destructuring, just like a normal tuple.
"""
pass
class FormattedPair(NamedTuple('key', 'token', 'formatted_key', 'formatted_token')):
"""\
The same as Pair, but also containing the formatted key and token.
"""
pass
class BaseStore(object):
"""\
Stores allow insertion, deletion and lookup of data through an interface similar
to a Python :class:`dict`, the primary difference being that store `keys`
are generated automatically by a `key generator` (or `keygen`). `tokens` are
used to delete values from the store and are supplied by a `token generator`.
Because they are closely associated, keys and tokens are returned
in a :class:`Pair <shorten.Pair>`. A pair is a named :class:`tuple`
containing a `key` and `token` (in that order) as well `key` and `token`
attributes.
::
s = Store()
key, token = pair = s.insert('aardvark')
# 'aardvark'
s[pair.key]
# True
pair.key == pair[0] == key
# True
pair.token == pair[1] == token
# Removes 'aardvark'
del s[pair.token]
Unlike a Python :class:`dict`, a :class:`BaseStore <BaseStore>` allows
insertion but no modification of its values. Some stores may provide
:meth:`__len__` and :meth:`__iter__` methods if the underlying storage
mechanism makes it feasible.
.. admonition:: Subclassing
Subclasses should implement
:meth:`insert() <shorten.BaseStore.insert>`,
:meth:`revoke() <shorten.BaseStore.revoke>`,
:meth:`get_value() <shorten.BaseStore.get_value>`,
:meth:`has_key() <shorten.BaseStore.has_key>`,
:meth:`has_token() <shorten.BaseStore.has_token>`,
:meth:`get_token() <shorten.BaseStore.get_token>` and
:meth:`get_value() <shorten.BaseStore.get_value>`
:param key_gen: a :class:`Keygen` that generates unique keys.
:param formatter: a :class:`Formatter` used to transform keys and
tokens for storage in a backend.
:param token_gen: an object with a :meth:`create_token` method
that returns unique revokation tokens.
"""
def __init__(self, key_gen=None, formatter=None, token_gen=None):
formatter = formatter or Formatter()
token_gen = token_gen or TokenGenerator()
key_gen = iter(key_gen)
self.key_gen = key_gen
self.token_gen = token_gen
self.formatter = formatter
def __contains__(self, key):
return self.has_key(key)
def __getitem__(self, key):
return self.get_value(key)
def __delitem__(self, token):
return self.revoke(token)
def next_formatted_pair(self):
"""\
Returns a :class:`FormattedPair <shorten.store.FormattedPair>` containing
attributes `key`, `token`, `formatted_key` and `formatted_token`.
Calling this method will always consume a key and token.
"""
key = self.key_gen.next()
token = self.token_gen.create_token(key)
fkey = self.formatter.format_key(key)
ftoken = self.formatter.format_token(token)
return FormattedPair(key, token, fkey, ftoken)
def get(self, key, default=None):
"""\
Get the value for :attr:`key` or :attr:`default` if the
key does not exist.
"""
try:
return self[key]
except KeyError:
return default
# Methods that should be implemented if you create your own class.
def insert(self, val):
"""\
Insert a val and return a :class:`Pair <shorten.Pair>`, which
is a :class:`tuple`. It contains a key and token (in
that order) as well `key` and `token` attributes.
::
pair = store.insert('aardvark')
key, token = pair
# True
pair.key == pair[0] == key
# True
pair.token == pair[1] == token
If the generated key exists or the cannot be stored, a
:class:`KeyInsertError <shorten.KeyInsertError>` is raised
(or a :class:`TokenInsertError <shorten.TokenInsertError>` for tokens).
::
try:
store.insert('bonobo')
except (KeyInsertError, TokenInsertError):
print('Cannot insert')
"""
raise NotImplementedError
def revoke(self, token):
"""\
Revokes the :attr:`token`. A
:class:`RevokeError <shorten.RevokeError>` is raised if the token
is not found or the underlying storage cannot complete the revokation.
::
try:
store.revoke(token)
print('Revoked!')
except RevokeError:
print('Could not revoke')
"""
raise NotImplementedError
def get_value(self, key):
"""\
Gets the value for :attr:`key` or raise a :class:`KeyError <KeyError>`
if it doesn't exist.
:meth:`get` and `store[key]` will call this method.
"""
raise NotImplementedError
def has_key(self, key):
"""\
Returns `True` if the key exists in this store, `False` otherwise.
"""
raise NotImplementedError
def has_token(self, token):
"""\
Returns `True` if the token exists in this store, `False` otherwise.
"""
raise NotImplementedError
def get_token(self, key):
"""\
Returns the token for :attr:`key`.
"""
raise NotImplementedError
| {
"repo_name": "clibc/shorten",
"path": "shorten/base.py",
"copies": "1",
"size": "7178",
"license": "mit",
"hash": 7354647855316033000,
"line_mean": 27.4841269841,
"line_max": 84,
"alpha_frac": 0.5929228197,
"autogenerated": false,
"ratio": 3.9966592427616927,
"config_test": false,
"has_no_keywords": false,
"few_assignments": false,
"quality_score": 0.9996119289433734,
"avg_score": 0.01869255460559197,
"num_lines": 252
} |
from ..formatter import QuestionFormatter, QuizFormatter
from ._utils import _escape_special_chars, CORRECT_ANSWER_CHAR, WRONG_ANSWER_CHAR
class GiftQuestionFormatter(QuestionFormatter):
pass
class DefaultGiftQuestionFormatter(GiftQuestionFormatter):
def to_string(self, question):
if question.comment is not None and question.comment != "":
s = "/// %s" % question.comment
else:
s = ""
s += "\n" + "::%s::%s{" % (_escape_special_chars(question.name), _escape_special_chars(question.stem))
is_bin = question.is_binary()
sum_values = question.sum_values
for i, distractor in enumerate(question.iter_distractors()):
if is_bin:
if distractor.value == sum_values:
c = CORRECT_ANSWER_CHAR
else:
c = WRONG_ANSWER_CHAR
s += "\n\t%s%s" % (c, _escape_special_chars(distractor.text))
else:
val_pct = distractor.value / sum_values * 100.0
if val_pct != 0:
s_val_pct = "%.5f" % val_pct
else:
s_val_pct = "0"
s += "\n\t%s%s%%%s" % (WRONG_ANSWER_CHAR, s_val_pct, distractor.text)
s += "\n" + "}"
return s[1:]
class GiftQuizFormatter(QuizFormatter):
pass
class DefaultGiftQuizFormatter(GiftQuizFormatter):
pass
| {
"repo_name": "scls19fr/python-lms-tools",
"path": "lms_tools/gift/formatter.py",
"copies": "1",
"size": "1424",
"license": "mit",
"hash": 9004563526854232000,
"line_mean": 33.7317073171,
"line_max": 110,
"alpha_frac": 0.5526685393,
"autogenerated": false,
"ratio": 3.595959595959596,
"config_test": false,
"has_no_keywords": false,
"few_assignments": false,
"quality_score": 0.4648628135259596,
"avg_score": null,
"num_lines": null
} |
from .formatters import default_formatters
class Formatter(object):
formatters = default_formatters()
def __init__(self, imports=None):
self.htchar = " " * 4
self.lfchar = "\n"
self.indent = 0
self.imports = imports
def __call__(self, value, **args):
return self.format(value, self.indent)
def format(self, value, indent):
formatter = self.get_formatter(value)
for module, import_name in formatter.get_imports():
self.imports[module].add(import_name)
return formatter.format(value, indent, self)
def normalize(self, value):
formatter = self.get_formatter(value)
return formatter.normalize(value, self)
@staticmethod
def get_formatter(value):
for formatter in Formatter.formatters:
if formatter.can_format(value):
return formatter
# This should never happen as GenericFormatter is registered by default.
raise RuntimeError("No formatter found for value")
@staticmethod
def register_formatter(formatter):
Formatter.formatters.insert(0, formatter)
| {
"repo_name": "syrusakbary/snapshottest",
"path": "snapshottest/formatter.py",
"copies": "1",
"size": "1142",
"license": "mit",
"hash": 2714265830756193000,
"line_mean": 29.8648648649,
"line_max": 80,
"alpha_frac": 0.642732049,
"autogenerated": false,
"ratio": 4.47843137254902,
"config_test": false,
"has_no_keywords": false,
"few_assignments": false,
"quality_score": 0.562116342154902,
"avg_score": null,
"num_lines": null
} |
from formatting import print_call
import credentials
import os.path
import re
import xmlrpclib
def api_call(method_name, endpoint, params=[], user_name="alice", verbose=False):
key_path, cert_path = "%s-key.pem" % (user_name,), "%s-cert.pem" % (user_name,)
res = ssl_call(method_name, params, endpoint, key_path=key_path, cert_path=cert_path)
if verbose:
print_call(method_name, params, res)
return res.get("code", None), res.get("value", None), res.get("output", None)
def ch_call(method_name, endpoint="", params=[], user_name="alice", verbose=False):
key_path, cert_path = "%s-key.pem" % (user_name,), "%s-cert.pem" % (user_name,)
res = ssl_call(method_name, params, endpoint, key_path=key_path, cert_path=cert_path, host="127.0.0.1", port=8000)
return res
def handler_call(method_name, params=[], user_name="alice", arg=[]):
if arg in ["-v", "--verbose"]:
verbose = True
else:
verbose = False
return api_call(method_name, "/xmlrpc/geni/3/", params=params, user_name=user_name, verbose=verbose)
class SafeTransportWithCert(xmlrpclib.SafeTransport):
"""Helper class to force the right certificate for the transport class."""
def __init__(self, key_path, cert_path):
xmlrpclib.SafeTransport.__init__(self) # no super, because old style class
self._key_path = key_path
self._cert_path = cert_path
def make_connection(self, host):
"""This method will automatically be called by the ServerProxy class when a transport channel is needed."""
host_with_cert = (host, {"key_file" : self._key_path, "cert_file" : self._cert_path})
return xmlrpclib.SafeTransport.make_connection(self, host_with_cert) # no super, because old style class
def ssl_call(method_name, params, endpoint, key_path="alice-key.pem",
cert_path="alice-cert.pem", host="127.0.0.1", port=8440):
creds_path = os.path.normpath(os.path.join(os.path.dirname(__file__), "../../..", "cert"))
if not os.path.isabs(key_path):
key_path = os.path.join(creds_path, key_path)
if not os.path.isabs(cert_path):
cert_path = os.path.join(creds_path, cert_path)
key_path = os.path.abspath(os.path.expanduser(key_path))
cert_path = os.path.abspath(os.path.expanduser(cert_path))
if not os.path.isfile(key_path) or not os.path.isfile(cert_path):
raise RuntimeError("Key or cert file not found (%s, %s)" % (key_path, cert_path))
transport = SafeTransportWithCert(key_path, cert_path)
if endpoint:
if endpoint[0] == "/":
endpoint = endpoint[1:]
proxy = xmlrpclib.ServerProxy("https://%s:%s/%s" % (host, str(port), endpoint), transport=transport)
# return proxy.get_version()
method = getattr(proxy, method_name)
return method(*params)
def getusercred(user_cert_filename = "alice-cert.pem", geni_api = 3):
"""Retrieve your user credential. Useful for debugging.
If you specify the -o option, the credential is saved to a file.
If you specify --usercredfile:
First, it tries to read the user cred from that file.
Second, it saves the user cred to a file by that name (but with the appropriate extension)
Otherwise, the filename is <username>-<framework nickname from config file>-usercred.[xml or json, depending on AM API version].
If you specify the --prefix option then that string starts the filename.
If instead of the -o option, you supply the --tostdout option, then the usercred is printed to STDOUT.
Otherwise the usercred is logged.
The usercred is returned for use by calling scripts.
e.g.:
Get user credential, save to a file:
omni.py -o getusercred
Get user credential, save to a file with filename prefix mystuff:
omni.py -o -p mystuff getusercred
"""
creds_path = os.path.normpath(os.path.join(os.path.dirname(__file__), "../../..", "cert"))
cert_path = os.path.join(creds_path, user_cert_filename)
user_cert = open(cert_path, "r").read()
# Contacting GCH for it by passing the certificate
cred = ch_call("CreateUserCredential", params = [user_cert])
#(cred, message) = ch_call(method_name = "CreateUserCredential", endpoint = "", params = {"params": user_cert})
if geni_api >= 3:
if cred:
cred = credentials.wrap_cred(cred)
credxml = credentials.get_cred_xml(cred)
# pull the username out of the cred
# <owner_urn>urn:publicid:IDN+geni:gpo:gcf+user+alice</owner_urn>
user = ""
usermatch = re.search(r"\<owner_urn>urn:publicid:IDN\+.+\+user\+(\w+)\<\/owner_urn\>", credxml)
if usermatch:
user = usermatch.group(1)
return "Retrieved %s user credential" % user, cred
| {
"repo_name": "ict-felix/stack",
"path": "modules/resource/manager/stitching-entity/src/core/utils/calls.py",
"copies": "2",
"size": "4733",
"license": "apache-2.0",
"hash": 3555748959167627300,
"line_mean": 46.8080808081,
"line_max": 132,
"alpha_frac": 0.6598351997,
"autogenerated": false,
"ratio": 3.442181818181818,
"config_test": false,
"has_no_keywords": false,
"few_assignments": false,
"quality_score": 0.5102017017881818,
"avg_score": null,
"num_lines": null
} |
from formatting import print_call
import credentials
import os.path
import re
import xmlrpclib
def _get_ch_params():
# Initialise variables when required
from core.config import FullConfParser
fcp = FullConfParser()
username = fcp.get("auth.conf").get("certificates").get("username")
ch_host = fcp.get("auth.conf").get("clearinghouse").get("host")
ch_port = fcp.get("auth.conf").get("clearinghouse").get("port")
ch_end = fcp.get("auth.conf").get("clearinghouse").get("endpoint")
return (username, ch_host, ch_port, ch_end)
def api_call(method_name, endpoint=None, params=[], username=None, verbose=False):
user, _, _, ch_end = _get_ch_params()
username = username or user
endpoint = endpoint or ch_end
key_path, cert_path = "%s-key.pem" % (username,), "%s-cert.pem" % (username,)
res = ssl_call(method_name, params, endpoint, key_path=key_path, cert_path=cert_path)
if verbose:
print_call(method_name, params, res)
return res.get("code", None), res.get("value", None), res.get("output", None)
def ch_call(method_name, endpoint=None, params=[], username=None, verbose=False):
user, ch_host, ch_port, ch_end = _get_ch_params()
username = username or user
endpoint = endpoint or ch_end
key_path, cert_path = "%s-key.pem" % (username,), "%s-cert.pem" % (username,)
res = ssl_call(method_name, params, endpoint, key_path=key_path, cert_path=cert_path, host=ch_host, port=ch_port)
return res
def handler_call(method_name, params=[], username=None, arg=[]):
if username is None:
user, _, _, _ = _get_ch_params()
verbose = False
if arg in ["-v", "--verbose"]:
verbose = True
return api_call(method_name, "/xmlrpc/geni/3/", params=params, username=username, verbose=verbose)
class SafeTransportWithCert(xmlrpclib.SafeTransport):
"""Helper class to force the right certificate for the transport class."""
def __init__(self, key_path, cert_path):
xmlrpclib.SafeTransport.__init__(self) # no super, because old style class
self._key_path = key_path
self._cert_path = cert_path
def make_connection(self, host):
"""This method will automatically be called by the ServerProxy class when a transport channel is needed."""
host_with_cert = (host, {"key_file" : self._key_path, "cert_file" : self._cert_path})
return xmlrpclib.SafeTransport.make_connection(self, host_with_cert) # no super, because old style class
def ssl_call(method_name, params, endpoint, key_path=None, cert_path=None, host=None, port=None):
username, ch_host, ch_port, ch_end = _get_ch_params()
key_path = key_path or ("%-key.pem" % username)
cert_path = cert_path or ("%-cert.pem" % username)
host = host or ch_host
port = port or ch_port
endpoint = endpoint or ch_end
# Start logic
creds_path = os.path.normpath(os.path.join(os.path.dirname(__file__), "../../..", "cert"))
if not os.path.isabs(key_path):
key_path = os.path.join(creds_path, key_path)
if not os.path.isabs(cert_path):
cert_path = os.path.join(creds_path, cert_path)
key_path = os.path.abspath(os.path.expanduser(key_path))
cert_path = os.path.abspath(os.path.expanduser(cert_path))
if not os.path.isfile(key_path) or not os.path.isfile(cert_path):
raise RuntimeError("Key or cert file not found (%s, %s)" % (key_path, cert_path))
transport = SafeTransportWithCert(key_path, cert_path)
if endpoint and len(endpoint):
if endpoint[0] == "/":
endpoint = endpoint[1:]
proxy = xmlrpclib.ServerProxy("https://%s:%s/%s" % (host, str(port), endpoint), transport=transport)
# return proxy.get_version()
method = getattr(proxy, method_name)
return method(*params)
def getusercred(geni_api = 3):
"""Retrieve your user credential. Useful for debugging.
If you specify the -o option, the credential is saved to a file.
If you specify --usercredfile:
First, it tries to read the user cred from that file.
Second, it saves the user cred to a file by that name (but with the appropriate extension)
Otherwise, the filename is <username>-<framework nickname from config file>-usercred.[xml or json, depending on AM API version].
If you specify the --prefix option then that string starts the filename.
If instead of the -o option, you supply the --tostdout option, then the usercred is printed to STDOUT.
Otherwise the usercred is logged.
The usercred is returned for use by calling scripts.
e.g.:
Get user credential, save to a file:
omni.py -o getusercred
Get user credential, save to a file with filename prefix mystuff:
omni.py -o -p mystuff getusercred
"""
from core.config import FullConfParser
fcp = FullConfParser()
username = fcp.get("auth.conf").get("certificates").get("username")
creds_path = os.path.normpath(os.path.join(os.path.dirname(__file__), "../../..", "cert"))
cert_path = os.path.join(creds_path, "%s-cert.pem" % username)
# Retrieve new credential by contacting with GCF CH
try:
user_cert = open(cert_path, "r").read()
cred = ch_call("CreateUserCredential", params = [user_cert])
# Exception? -> Retrieve already existing credential from disk (CBAS)
except:
cred_path = os.path.join(creds_path, "%s-cred.xml" % username)
cred = open(cred_path).read()
if geni_api >= 3:
if cred:
cred = credentials.wrap_cred(cred)
credxml = credentials.get_cred_xml(cred)
# pull the username out of the cred
# <owner_urn>urn:publicid:IDN+geni:gpo:gcf+user+alice</owner_urn>
user = ""
usermatch = re.search(r"\<owner_urn>urn:publicid:IDN\+.+\+user\+(\w+)\<\/owner_urn\>", credxml)
if usermatch:
user = usermatch.group(1)
return ("Retrieved %s user credential" % user, cred)
| {
"repo_name": "dana-i2cat/felix",
"path": "modules/resource/orchestrator/src/core/utils/calls.py",
"copies": "1",
"size": "5912",
"license": "apache-2.0",
"hash": -1136094323294068000,
"line_mean": 44.8294573643,
"line_max": 132,
"alpha_frac": 0.6579837618,
"autogenerated": false,
"ratio": 3.4512551079976648,
"config_test": false,
"has_no_keywords": false,
"few_assignments": false,
"quality_score": 0.4609238869797665,
"avg_score": null,
"num_lines": null
} |
from .formatting import svenv_flavored_markdown
from markdown2 import Markdown
from textwrap import dedent
from unittest import TestCase
class MarkdownTest(TestCase):
"""
Tests svenv flavored markdown against specification found on: http://daringfireball.net/projects/markdown/basics
Newlines are ignored
"""
def setUp(self):
self.md = Markdown(extras=['fenced-code-blocks'])
self.mdf = svenv_flavored_markdown(extras=['fenced-code-blocks'])
def test_paragraphs_headers_blockquotes(self):
markdown = dedent(
"""
A First Level Header
====================
A Second Level Header
---------------------
Now is the time for all good men to come to
the aid of their country. This is just a
regular paragraph.
The quick brown fox jumped over the lazy
dog's back.
### Header 3
> This is a blockquote.
>
> This is the second paragraph in the blockquote.
>
> ## This is an H2 in a blockquote
"""
)
html = dedent(
"""
<h1>A First Level Header</h1>
<h2>A Second Level Header</h2>
<p>Now is the time for all good men to come to
the aid of their country. This is just a
regular paragraph.</p>
<p>The quick brown fox jumped over the lazy
dog's back.</p>
<h3>Header 3</h3>
<blockquote>
<p>This is a blockquote.</p>
<p>This is the second paragraph in the blockquote.</p>
<h2>This is an H2 in a blockquote</h2>
</blockquote>
"""
)
self.assert_markdown(markdown, html)
def test_phrase_emphasis(self):
markdown = dedent(
"""
Some of these words *are emphasized*.
Some of these words _are emphasized also_.
Use two asterisks for **strong emphasis**.
Or, if you prefer, __use two underscores instead__.
"""
)
html = dedent(
"""
<p>Some of these words <em>are emphasized</em>.
Some of these words <em>are emphasized also</em>.</p>
<p>Use two asterisks for <strong>strong emphasis</strong>.
Or, if you prefer, <strong>use two underscores instead</strong>.</p>
"""
)
self.assert_markdown(markdown, html)
def test_unordered_lists(self):
asterisk = dedent(
"""
* Candy.
* Gum.
* Booze.
"""
)
plus = dedent(
"""
+ Candy.
+ Gum.
+ Booze.
"""
)
hyphen = dedent(
"""
- Candy.
- Gum.
- Booze.
"""
)
html = dedent(
"""
<ul>
<li>Candy.</li>
<li>Gum.</li>
<li>Booze.</li>
</ul>
"""
)
self.assert_markdown(asterisk, html, 'Asterisk style list did not parse correctly')
self.assert_markdown(plus, html, 'Plus style list did not parse correctly')
self.assert_markdown(hyphen, html, 'Hyphen style list did not parse correctly')
def test_ordered_lists(self):
"""
Svenv flavored markdown respects list start
"""
markdown = dedent(
"""
1. Red
2. Green
3. Blue
4. Red
5. Green
6. Blue
"""
)
html = dedent(
"""
<ol start="1">
<li>Red</li>
<li>Green</li>
<li>Blue</li>
</ol>
<ol start="4">
<li>Red</li>
<li>Green</li>
<li>Blue</li>
</ol>
"""
)
self.assert_svenv_flavored_markdown(markdown, html)
def test_paragraph_list(self):
markdown = dedent(
"""
* A list item.
With multiple paragraphs.
* Another item in the list.
"""
)
html = dedent(
"""
<ul>
<li><p>A list item.</p>
<p>With multiple paragraphs.</p></li>
<li><p>Another item in the list.</p></li>
</ul>
"""
)
self.assert_markdown(markdown, html)
def test_links_no_title(self):
markdown = dedent(
"""
This is an [example link](http://example.com/).
"""
)
html = dedent(
"""
<p>This is an <a href="http://example.com/">
example link</a>.</p>
"""
)
self.assert_markdown(markdown, html)
def test_links_title(self):
markdown = dedent(
"""
This is an [example link](http://example.com/ "With a Title").
"""
)
html = dedent(
"""
<p>This is an <a href="http://example.com/" title="With a Title">
example link</a>.</p>
"""
)
self.assert_markdown(markdown, html)
def test_reference_links(self):
markdown = dedent(
"""
I get 10 times more traffic from [Google][1] than from
[Yahoo][2] or [MSN][3].
[1]: http://google.com/ "Google"
[2]: http://search.yahoo.com/ "Yahoo Search"
[3]: http://search.msn.com/ "MSN Search"
"""
)
html = dedent(
"""
<p>I get 10 times more traffic from <a href="http://google.com/"
title="Google">Google</a> than from <a href="http://search.yahoo.com/"
title="Yahoo Search">Yahoo</a> or <a href="http://search.msn.com/"
title="MSN Search">MSN</a>.</p>
"""
)
self.assert_markdown(markdown, html)
def test_images(self):
"""
Paragraphs seem to be added by Markdown2
"""
markdown = dedent(
"""

"""
)
html = dedent(
"""
<p><img src="/path/to/img.jpg" alt="alt text" title="Title" /></p>
"""
)
self.assert_markdown(markdown, html)
def test_code_backticks(self):
markdown = dedent(
"""
I strongly recommend against using any `<blink>` tags.
I wish SmartyPants used named entities like `—`
instead of decimal-encoded entites like `—`.
"""
)
html = dedent(
"""
<p>I strongly recommend against using any
<code><blink></code> tags.</p>
<p>I wish SmartyPants used named entities like
<code>&mdash;</code> instead of decimal-encoded
entites like <code>&#8212;</code>.</p>
"""
)
self.assert_markdown(markdown, html)
def test_code_indent(self):
markdown = """
If you want your page to validate under XHTML 1.0 Strict,
you've got to put paragraph tags in your blockquotes:
<blockquote>
<p>For example.</p>
</blockquote>
"""
html = dedent(
"""
<p>If you want your page to validate under XHTML 1.0 Strict,
you've got to put paragraph tags in your blockquotes:</p>
<pre><code><blockquote>
<p>For example.</p>
</blockquote>
</code></pre>
"""
)
self.assert_markdown(markdown, html)
def test_fenched_code_blocks(self):
"""
Basic test for the Markdown2 fenched code blocks extra
"""
markdown = dedent(
"""
```
some code
```
"""
)
html = dedent(
"""
<pre><code>some code</code></pre>
"""
)
self.assert_markdown(markdown, html)
def test_svenv_flavored_markdown(self):
"""
Tests "svenv flavored" markdown
"""
markdown = dedent(
"""

"""
)
html = dedent(
"""
<p><img src="/path/to/img.jpg" alt="alt text" title="Title" class="Class" /></p>
"""
)
self.assert_svenv_flavored_markdown(markdown, html)
def test_list(self):
"""
Tests an issue with lists and headings
"""
markdown = '### 1. Bad code'
html = '<h3><ol start="1"><li>Bad code</li></ol></h3>'
self.assert_svenv_flavored_markdown(markdown, html)
def assert_markdown(self, markdown, html, msg=None):
"""
Tests both markdown2 and "svenv flavored markdown"
"""
self.assert_markdown2(markdown, html, msg)
self.assert_svenv_flavored_markdown(markdown, html, msg)
def assert_markdown2(self, markdown, html, msg=None):
"""
Converts markdown and asserts against given html
Newlines and spaces are ignored for test (so are in-text spaces)
"""
result = self.md.convert(markdown)
result = result.replace('\n', '')
result = result.replace(' ', '')
html = html.replace('\n', '')
html = html.replace(' ', '')
self.assertEqual(result, html, msg)
def assert_svenv_flavored_markdown(self, markdown, html, msg=None):
"""
Converts markdown and asserts against given html
Newlines and spaces are ignored for test (so are in-text spaces)
"""
result = self.mdf.convert(markdown)
result = result.replace('\n', '')
result = result.replace(' ', '')
html = html.replace('\n', '')
html = html.replace(' ', '')
self.assertEqual(result, html, msg) | {
"repo_name": "svenvandescheur/svenv.nl-app",
"path": "svenv/blog/templatetags/test.py",
"copies": "1",
"size": "10230",
"license": "mit",
"hash": -2556824872725748000,
"line_mean": 26.4289544236,
"line_max": 116,
"alpha_frac": 0.4746823069,
"autogenerated": false,
"ratio": 4.177215189873418,
"config_test": true,
"has_no_keywords": false,
"few_assignments": false,
"quality_score": 1,
"avg_score": 0.00027070497491168076,
"num_lines": 373
} |
from formcreator import Text, Integer, TextArea, File
def transform_id_form():
return Text("Transform Id", "The unique id / alias for a node corresponding to a transform, its input, and its parameters.", cmd_opt="transform_id")
def data_namespace_form():
return Text("Data Namespace", "The namespace of the data to be used for the input of the transform.", cmd_opt="data_namespace")
def train_namespace_form():
return Text("Train Namespace", "The namespace of the data for the transform and its ancestors to be trained on.", cmd_opt="train_namespace")
def alias_form():
return Text("Alias", "Optional. A unique shortcut that can be used to refer to this node.", cmd_opt="alias")
def tags_form():
return Text("Tags", "Optional. White space separated tags to aid search.", cmd_opt="tags")
def query_form():
return Text(cmd_opt="query")
def random_seed_form():
return Integer("Random Seed", "Seed for initialization of random number generators.", cmd_opt="random_seed")
def parameters_form():
return TextArea("Parameters", "JSON encoded input parameters to the transform.", cmd_opt="parameters")
def data_ids_form():
return Text("Data Ids", "Whitespace separated data ids as input to the transform. Note that order matters.", cmd_opt="data_ids")
def transform_form():
return Text("Transform", "The name of the transform to apply.", cmd_opt="transform")
def input_data_form():
return File("Input Data", "External data to add as input.", upload_directory="uploads", cmd_opt="input_data")
def data_type_form():
return Text("Data Type", "The major exclusive type of the input data. (e.g. Categorical, Ordinal, etc.)", cmd_opt="data_type")
def number_columns_form():
return Integer("Number of Columns", "Have -1 for not specified, 0 for none, or a positive number for a specific number.", cmd_opt="number_columns")
| {
"repo_name": "diogo149/ProtoML-clojure",
"path": "client/forms.py",
"copies": "1",
"size": "1872",
"license": "apache-2.0",
"hash": -5837854314565340000,
"line_mean": 45.8,
"line_max": 152,
"alpha_frac": 0.7142094017,
"autogenerated": false,
"ratio": 3.8282208588957056,
"config_test": false,
"has_no_keywords": false,
"few_assignments": false,
"quality_score": 0.9956531132281751,
"avg_score": 0.01717982566279082,
"num_lines": 40
} |
from .form_data import FormData
import uuid
try: # pragma: no cover
from urllib import quote_plus
except ImportError: # pragma: no cover
from urllib.parse import quote_plus
class Form(object):
def __init__(self, data=None, boundary=None):
"""
Creates a new Form object, which is used to generate the
multipart http form response.
:param data: The data parameter should be left blank, or if you
have pre-existing FormData objects, you can pass them
in as a list.
Example:
>>> form = Form([FormData('a', 'b')])
:type data: list
"""
# See if the user provided data, otherwise fallback
self.data = data or []
if boundary and isinstance(boundary, str):
# Use the user provided boundary
self.boundary = quote_plus(boundary.replace(' ', '+'))
else:
# Generate a new unique random string for the boundary
self.boundary = quote_plus(uuid.uuid4().hex)
# Check that the parameters given is a list
if not isinstance(self.data, list):
raise ValueError('data list must be of type list, is type {}'.format(type(self.data).__name__))
# Check that all of the items are the FormData type
if not all([isinstance(x, FormData) for x in self.data]):
raise TypeError('All objects in list must be of type FormData')
def add_file(self, name, fh, filename=None, mime_type=None):
"""
Adds a new FormData object that uses a file handler for the content,
allowing for buffered input.
:param name: A name used by multipart to identify the content
:param fh: The file(-like) handler that allows for buffered reading
:param filename: If not provided, will attempt to determine it automatically
:param mime_type: The MIME type of the document, with also automatically detect
based on the file extension of the ``filename``
:returns: The new FormData obejct
:rtype: FormData
"""
# Validate that the name is valid
if not name or not isinstance(name, str):
raise ValueError('You must provide a valid name')
# Validate that the file buffer is valid
if not fh or not hasattr(fh, 'read'):
raise ValueError('You must provide a valid file handler')
# Create a new FormData object
data = FormData(name, fh, filename=filename, mime_type=mime_type)
# Add to this form
self.add_form_data(data)
return data
def add_data(self, name, content):
"""
Adds a new FormData object to the Form, and accepts the value to
be any arbitrary string.
This data has no Content-Type applied to it.
:param name: The name to identify the content
:param content: The content to encode
:returns: The FormData object
:rtype: FormData
"""
# Validate that the name is valid
if not name or not isinstance(name, str):
raise ValueError('You must provide a valid name')
# Validate that the file buffer is valid
if not content or not isinstance(content, str):
raise ValueError('You must provide a valid content as a string')
# Create a new FormData object
data = FormData(name, content)
# Add to this form
self.add_form_data(data)
return data
def add_form_data(self, form_data):
"""
Adds a FormData object directly to our list of data.
:param form_data: The FormData object to add
:type form_data: FormData
"""
# Check that it's the correct instance type
if not isinstance(form_data, FormData):
raise ValueError(
'Multipart requires form_data to be of type FormData, is \'{}\''.format(type(form_data).__name__))
# Add the FormData to our data
self.data.append(form_data)
def encode(self, cb=None):
"""
Encodes the FormData object into something that can be joined together to
make a valid, encoded multipart form.
The resulting output should be something similar to:
>>> --EXAMPLE
>>> Content-Disposition: form-data; name="foo"
>>>
>>> bar
>>> --EXAMPLE
>>> Content-Disposition: form-data; name="profile"; filename="profile.jpg"
>>> Content-Type: image/jpg
>>>
>>> IMAGE_DATA_HERE
>>> --EXAMPLE--
:param cb: The callback function, can be used to track the process
of reading the buffered content, especially for larger
files.
"""
content = ''
position = 0
# The sum of all of our data + 38
# -- (2) + [uuid boundary] (32) + -- (2) + \r\n (2) = 38 bytes
total = sum(len(p) for p in self.data) + 38
# Iterate through the data
for field in self.data:
# Set the boundary for this Form on the FormData
field.set_boundary(self.boundary)
# Get the encoded output of the data
block = field.encode()
# Track the size of our output
position += len(block)
# Add the content to our result
content += block
# If we have a callback, call it
if cb:
cb(field, position, total)
# Print a --[boundary]-- at the end to terminate the sequence
content += '--{}--'.format(self.boundary)
headers = {
'Content-Type': 'multipart/form-data; boundary=--{}'.format(self.boundary),
'Content-Length': str(len(content)),
}
return content, headers
| {
"repo_name": "EvanDarwin/poster3",
"path": "poster/form.py",
"copies": "1",
"size": "5976",
"license": "mit",
"hash": 1962025438484965600,
"line_mean": 32.5730337079,
"line_max": 114,
"alpha_frac": 0.5724564926,
"autogenerated": false,
"ratio": 4.593389700230592,
"config_test": false,
"has_no_keywords": false,
"few_assignments": false,
"quality_score": 1,
"avg_score": 0.0004901537976331001,
"num_lines": 178
} |
from form_designer.contrib.cms_plugins.form_designer_form.models import CMSFormDefinition
from form_designer.exceptions import HttpRedirectException
from form_designer.views import process_form
from form_designer import settings
from cms.plugin_base import CMSPluginBase
from cms.plugin_pool import plugin_pool
from django.conf import settings as django_settings
from django.http import HttpResponseRedirect
from django.utils.translation import ugettext as _
class FormDesignerPlugin(CMSPluginBase):
model = CMSFormDefinition
module = _('Form Designer')
name = _('Form')
admin_preview = False
text_enabled = True
# the form renders to plugin_detail.html, which then uses
# {% include form_template_name %}
render_template = "html/formdefinition/plugin_detail.html"
def render(self, context, instance, placeholder):
context.update({
'form_template_name':instance.form_definition.form_template_name or settings.DEFAULT_FORM_TEMPLATE,
})
disable_redirection = 'form_designer.middleware.RedirectMiddleware' not in django_settings.MIDDLEWARE_CLASSES
response = process_form(
context['request'],
instance.form_definition,
context,
disable_redirection=disable_redirection
)
if isinstance(response, HttpResponseRedirect):
raise HttpRedirectException(
response,
"Redirect"
)
return response
def icon_src(self, instance):
return "/static/plugin_icons/form.png"
plugin_pool.register_plugin(FormDesignerPlugin)
| {
"repo_name": "guilleCoro/django-form-designer",
"path": "form_designer/contrib/cms_plugins/form_designer_form/cms_plugins.py",
"copies": "1",
"size": "1659",
"license": "bsd-3-clause",
"hash": 7454906697719100000,
"line_mean": 32.8571428571,
"line_max": 117,
"alpha_frac": 0.6889692586,
"autogenerated": false,
"ratio": 4.508152173913044,
"config_test": false,
"has_no_keywords": false,
"few_assignments": false,
"quality_score": 0.5697121432513044,
"avg_score": null,
"num_lines": null
} |
from form_designer.contrib.cms_plugins.form_designer_form.models import CMSFormDefinition
from form_designer.views import process_form
from form_designer import settings
from cms.plugin_base import CMSPluginBase
from cms.plugin_pool import plugin_pool
from django.utils.translation import ugettext as _
class FormDesignerPlugin(CMSPluginBase):
model = CMSFormDefinition
module = _('Form Designer')
name = _('Form')
admin_preview = False
render_template = False
text_enabled = True
cache = False
def render(self, context, instance, placeholder):
if instance.form_definition.form_template_name:
self.render_template = instance.form_definition.form_template_name
else:
self.render_template = settings.DEFAULT_FORM_TEMPLATE
# Redirection does not work with CMS plugin, hence disable:
return process_form(context['request'], instance.form_definition, context, disable_redirection=True)
plugin_pool.register_plugin(FormDesignerPlugin)
| {
"repo_name": "housleyjk/django-form-designer",
"path": "form_designer/contrib/cms_plugins/form_designer_form/cms_plugins.py",
"copies": "1",
"size": "1025",
"license": "bsd-3-clause",
"hash": 8222598476270492000,
"line_mean": 33.1666666667,
"line_max": 108,
"alpha_frac": 0.7385365854,
"autogenerated": false,
"ratio": 4.116465863453815,
"config_test": false,
"has_no_keywords": false,
"few_assignments": false,
"quality_score": 0.5355002448853815,
"avg_score": null,
"num_lines": null
} |
from form_designer.contrib.exporters import FormLogExporterBase
from form_designer import settings
from django.http import HttpResponse
from django.utils.encoding import smart_str, smart_unicode
try:
import xlwt
except ImportError:
XLWT_INSTALLED = False
else:
XLWT_INSTALLED = True
class XlsExporter(FormLogExporterBase):
@staticmethod
def export_format():
return 'XLS'
@staticmethod
def is_enabled():
return XLWT_INSTALLED
def init_writer(self):
self.wb = xlwt.Workbook(encoding="UTF-8")
self.ws = self.wb.add_sheet(smart_str(self.model._meta.verbose_name_plural))
self.rownum = 0
def init_response(self):
self.response = HttpResponse(mimetype='application/ms-excel')
self.response['Content-Disposition'] = 'attachment; filename=%s.xls' % \
smart_str(self.model._meta.verbose_name_plural)
def writerow(self, row):
for i, f in enumerate(row):
self.ws.write(self.rownum, i, smart_unicode(f, encoding=settings.CSV_EXPORT_ENCODING))
self.rownum += 1
def close(self):
self.wb.save(self.response)
def export(self, request, queryset=None):
return super(XlsExporter, self).export(request, queryset)
| {
"repo_name": "MagicSolutions/django-form-designer",
"path": "form_designer/contrib/exporters/xls_exporter.py",
"copies": "1",
"size": "1265",
"license": "bsd-3-clause",
"hash": 9056056076651971000,
"line_mean": 28.4186046512,
"line_max": 98,
"alpha_frac": 0.6758893281,
"autogenerated": false,
"ratio": 3.677325581395349,
"config_test": false,
"has_no_keywords": false,
"few_assignments": false,
"quality_score": 0.48532149094953486,
"avg_score": null,
"num_lines": null
} |
from form_designer.contrib.exporters import FormLogExporterBase
from form_designer import settings
from django.utils.translation import ugettext_lazy as _
from django.http import HttpResponse
from django.utils.encoding import smart_unicode
try:
import xlwt
except ImportError:
XLWT_INSTALLED = False
else:
XLWT_INSTALLED = True
class XlsExporter(FormLogExporterBase):
@staticmethod
def export_format():
return 'XLS'
@staticmethod
def is_enabled():
return XLWT_INSTALLED
def init_writer(self):
self.wb = xlwt.Workbook()
self.ws = self.wb.add_sheet(unicode(self.model._meta.verbose_name_plural))
self.rownum = 0
def init_response(self):
self.response = HttpResponse(content_type='application/ms-excel')
self.response['Content-Disposition'] = 'attachment; filename=%s.xls' % \
unicode(self.model._meta.verbose_name_plural)
def writerow(self, row):
for i, f in enumerate(row):
self.ws.write(self.rownum, i, smart_unicode(f, encoding=settings.CSV_EXPORT_ENCODING))
self.rownum += 1
def close(self):
self.wb.save(self.response)
def export(self, request, queryset=None):
return super(XlsExporter, self).export(request, queryset)
| {
"repo_name": "darbula/django-form-designer",
"path": "form_designer/contrib/exporters/xls_exporter.py",
"copies": "3",
"size": "1294",
"license": "bsd-3-clause",
"hash": -6555176945188220000,
"line_mean": 28.4090909091,
"line_max": 98,
"alpha_frac": 0.6816074189,
"autogenerated": false,
"ratio": 3.7507246376811594,
"config_test": false,
"has_no_keywords": false,
"few_assignments": false,
"quality_score": 0.5932332056581159,
"avg_score": null,
"num_lines": null
} |
from form_designer import settings as app_settings
from django.core.files.base import File
from django.forms.forms import NON_FIELD_ERRORS
from django.utils.translation import ugettext_lazy as _
from django.db.models.fields.files import FieldFile
from django.template.defaultfilters import filesizeformat
import os
import hashlib, uuid
def get_storage():
return app_settings.FILE_STORAGE_CLASS()
def clean_files(form):
total_upload_size = 0
for field in form.file_fields:
uploaded_file = form.cleaned_data.get(field.name, None)
msg = None
if uploaded_file is None:
if field.required:
msg = _('This field is required.')
else:
continue
else:
total_upload_size += uploaded_file._size
if not os.path.splitext(uploaded_file.name)[1].lstrip('.').lower() in \
app_settings.ALLOWED_FILE_TYPES:
msg = _('This file type is not allowed.')
elif uploaded_file._size > app_settings.MAX_UPLOAD_SIZE:
msg = _('Please keep file size under %(max_size)s. Current size is %(size)s.') % \
{'max_size': filesizeformat(app_settings.MAX_UPLOAD_SIZE),
'size': filesizeformat(uploaded_file._size)}
if msg:
form._errors[field.name] = form.error_class([msg])
if total_upload_size > app_settings.MAX_UPLOAD_TOTAL_SIZE:
msg = _('Please keep total file size under %(max)s. Current total size is %(current)s.') % \
{"max": filesizeformat(app_settings.MAX_UPLOAD_TOTAL_SIZE), "current": filesizeformat(total_upload_size)}
if NON_FIELD_ERRORS in form._errors:
form._errors[NON_FIELD_ERRORS].append(msg)
else:
form._errors[NON_FIELD_ERRORS] = form.error_class([msg])
return form.cleaned_data
def handle_uploaded_files(form_definition, form):
files = []
if form_definition.save_uploaded_files and len(form.file_fields):
storage = get_storage()
secret_hash = hashlib.sha1(str(uuid.uuid4())).hexdigest()[:10]
for field in form.file_fields:
uploaded_file = form.cleaned_data.get(field.name, None)
if uploaded_file is None:
continue
valid_file_name = storage.get_valid_name(uploaded_file.name)
root, ext = os.path.splitext(valid_file_name)
filename = storage.get_available_name(
os.path.join(app_settings.FILE_STORAGE_DIR,
form_definition.name,
'%s_%s%s' % (root, secret_hash, ext)))
storage.save(filename, uploaded_file)
form.cleaned_data[field.name] = StoredUploadedFile(filename)
files.append(storage.path(filename))
return files
class StoredUploadedFile(FieldFile):
"""
A wrapper for uploaded files that is compatible to the FieldFile class, i.e.
you can use instances of this class in templates just like you use the value
of FileFields (e.g. `{{ my_file.url }}`)
"""
def __init__(self, name):
File.__init__(self, None, name)
self.field = self
@property
def storage(self):
return get_storage()
def save(self, *args, **kwargs):
raise NotImplementedError('Static files are read-only')
def delete(self, *args, **kwargs):
raise NotImplementedError('Static files are read-only')
def __unicode__(self):
return self.name
| {
"repo_name": "garmoncheg/django-form-designer",
"path": "form_designer/uploads.py",
"copies": "8",
"size": "3516",
"license": "bsd-3-clause",
"hash": 7221352123959527000,
"line_mean": 37.6373626374,
"line_max": 117,
"alpha_frac": 0.6157565415,
"autogenerated": false,
"ratio": 3.9863945578231292,
"config_test": false,
"has_no_keywords": false,
"few_assignments": false,
"quality_score": 0.8602151099323129,
"avg_score": null,
"num_lines": null
} |
from form_designer import settings as app_settings
from django.core.files.base import File
from django.utils.translation import ugettext_lazy as _
from django.db.models.fields.files import FieldFile
from django.template.defaultfilters import filesizeformat
import os
import hashlib, uuid
def get_storage():
return app_settings.FILE_STORAGE_CLASS()
def clean_files(form):
for field in form.file_fields:
uploaded_file = form.cleaned_data.get(field.name, None)
msg = None
if uploaded_file is None:
if field.required:
msg = _('This field is required.')
else:
continue
elif not os.path.splitext(uploaded_file.name)[1].lstrip('.').lower() in \
app_settings.ALLOWED_FILE_TYPES:
msg = _('This file type is not allowed.')
elif uploaded_file._size > app_settings.MAX_UPLOAD_SIZE:
msg = _('Please keep file size under %(max_size)s. Current size is %(size)s.') % \
{'max_size': filesizeformat(app_settings.MAX_UPLOAD_SIZE),
'size': filesizeformat(uploaded_file._size)}
if msg:
form._errors[field.name] = form.error_class([msg])
return form.cleaned_data
def handle_uploaded_files(form_definition, form):
files = []
if form_definition.save_uploaded_files and len(form.file_fields):
storage = get_storage()
secret_hash = hashlib.sha1(str(uuid.uuid4())).hexdigest()[:10]
for field in form.file_fields:
uploaded_file = form.cleaned_data.get(field.name, None)
if uploaded_file is None:
continue
valid_file_name = storage.get_valid_name(uploaded_file.name)
root, ext = os.path.splitext(valid_file_name)
filename = storage.get_available_name(
os.path.join(app_settings.FILE_STORAGE_DIR,
form_definition.name,
'%s_%s%s' % (root, secret_hash, ext)))
storage.save(filename, uploaded_file)
form.cleaned_data[field.name] = StoredUploadedFile(filename)
files.append(storage.path(filename))
return files
class StoredUploadedFile(FieldFile):
"""
A wrapper for uploaded files that is compatible to the FieldFile class, i.e.
you can use instances of this class in templates just like you use the value
of FileFields (e.g. `{{ my_file.url }}`)
"""
def __init__(self, name):
File.__init__(self, None, name)
self.field = self
@property
def storage(self):
return get_storage()
def save(self, *args, **kwargs):
raise NotImplementedError('Static files are read-only')
def delete(self, *args, **kwargs):
raise NotImplementedError('Static files are read-only')
def __unicode__(self):
return self.name
| {
"repo_name": "guilleCoro/django-form-designer",
"path": "form_designer/uploads.py",
"copies": "2",
"size": "2882",
"license": "bsd-3-clause",
"hash": -8693968141143415000,
"line_mean": 35.9487179487,
"line_max": 95,
"alpha_frac": 0.6179736294,
"autogenerated": false,
"ratio": 4.013927576601671,
"config_test": false,
"has_no_keywords": false,
"few_assignments": false,
"quality_score": 0.5631901206001672,
"avg_score": null,
"num_lines": null
} |
from form_designer import settings
from form_designer.templatetags.friendly import friendly
from django.db.models import Count
from django.utils.translation import ugettext as _
from django.utils.encoding import smart_str
class ExporterBase(object):
def __init__(self, model):
self.model = model
@staticmethod
def is_enabled():
return True
@staticmethod
def export_format():
raise NotImplemented()
def init_writer(self):
raise NotImplemented()
def init_response(self):
raise NotImplemented()
def writerow(self, row):
raise NotImplemented()
def close(self):
pass
@classmethod
def export_view(cls, modeladmin, request, queryset):
return cls(modeladmin.model).export(request, queryset)
def export(self, request, queryset=None):
raise NotImplemented()
class FormLogExporterBase(ExporterBase):
def export(self, request, queryset=None):
self.init_response()
self.init_writer()
distinct_forms = queryset.aggregate(Count('form_definition', distinct=True))['form_definition__count']
include_created = settings.CSV_EXPORT_INCLUDE_CREATED
include_pk = settings.CSV_EXPORT_INCLUDE_PK
include_header = settings.CSV_EXPORT_INCLUDE_HEADER and distinct_forms == 1
include_form = settings.CSV_EXPORT_INCLUDE_FORM and distinct_forms > 1
if queryset.count():
fields = queryset[0].form_definition.get_field_dict()
if include_header:
header = []
if include_form:
header.append(_('Form'))
if include_created:
header.append(_('Created'))
if include_pk:
header.append(_('ID'))
# Form fields might have been changed and not match
# existing form logs anymore.
# Hence, use current form definition for header.
# for field in queryset[0].data:
# header.append(field['label'] if field['label'] else field['key'])
for field_name, field in fields.items():
header.append(field.label if field.label else field.key)
self.writerow([smart_str(cell, encoding=settings.CSV_EXPORT_ENCODING) for cell in header])
for entry in queryset:
row = []
if include_form:
row.append(entry.form_definition)
if include_created:
row.append(entry.created)
if include_pk:
row.append(entry.pk)
for item in entry.data:
value = friendly(item['value'], null_value=settings.CSV_EXPORT_NULL_VALUE)
value = smart_str(
value, encoding=settings.CSV_EXPORT_ENCODING)
row.append(value)
self.writerow(row)
self.close()
return self.response
| {
"repo_name": "darbula/django-form-designer",
"path": "form_designer/contrib/exporters/__init__.py",
"copies": "10",
"size": "3048",
"license": "bsd-3-clause",
"hash": -7609809991245582000,
"line_mean": 32.4945054945,
"line_max": 110,
"alpha_frac": 0.5784120735,
"autogenerated": false,
"ratio": 4.71097372488408,
"config_test": false,
"has_no_keywords": false,
"few_assignments": false,
"quality_score": 1,
"avg_score": null,
"num_lines": null
} |
from formencode.api import FancyValidator, NoDefault
class JSONTyped(FancyValidator):
"""
Wrap formencode validator with JSON schema's types & properties. ::
validator = JSONTyped(
{'type': 'string'},
validators.UnicodeString(),
required=True,
description="Some important field",
)
"""
__unpackargs__ = ('json_type', 'validator')
required = NoDefault
description = None
def _convert_to_python(self, value, state=None):
return self.validator.to_python(value, state)
def _convert_from_python(self, value, state=None):
return self.validator.from_python(value, state)
class ObjectTyped(JSONTyped):
"""Wrap formencode validator with object type of JSON Schema"""
def __init__(self, validator, *args, **kwargs):
super().__init__({
'type': 'object',
}, validator, *args, **kwargs)
class ArrrayTyped(JSONTyped):
"""Wrap formencode validator with array type of JSON Schema"""
def __init__(self, validator, *args, **kwargs):
super().__init__({
'type': 'array',
}, validator, *args, **kwargs)
class DateTyped(JSONTyped):
"""Wrap formencode validator with date type of JSON Schema"""
def __init__(self, validator, *args, **kwargs):
super().__init__({
'type': 'string',
'format': 'date',
}, validator, *args, **kwargs)
class TimeTyped(JSONTyped):
"""Wrap formencode validator with time type of JSON Schema"""
def __init__(self, validator, *args, **kwargs):
super().__init__({
'type': 'string',
'format': 'time',
}, validator, *args, **kwargs)
class DateTimeTyped(JSONTyped):
"""Wrap formencode validator with date-time type of JSON Schema"""
def __init__(self, validator, *args, **kwargs):
super().__init__({
'type': 'string',
'format': 'date-time',
}, validator, *args, **kwargs)
class UUIDTyped(JSONTyped):
"""Wrap formencode validator with uuid type of JSON Schema"""
def __init__(self, validator, *args, **kwargs):
super().__init__({
'type': 'string',
'format': 'uuid',
}, validator, *args, **kwargs)
class StringTyped(JSONTyped):
"""Wrap formencode validator with string type of JSON Schema"""
def __init__(self, validator, *args, **kwargs):
super().__init__({
'type': 'string',
'format': 'uuid',
}, validator, *args, **kwargs)
class DecimalTyped(JSONTyped):
"""Wrap formencode validator with decimal type of JSON Schema"""
def __init__(self, validator, *args, **kwargs):
super().__init__({
'type': 'number',
'format': 'decimal',
}, validator, *args, **kwargs)
class FloatTyped(JSONTyped):
"""Wrap formencode validator with float type of JSON Schema"""
def __init__(self, validator, *args, **kwargs):
super().__init__({
'type': 'number',
'format': 'float',
}, validator, *args, **kwargs)
class IntegerTyped(JSONTyped):
"""Wrap formencode validator with integer type of JSON Schema"""
def __init__(self, validator, *args, **kwargs):
super().__init__({
'type': 'integer',
}, validator, *args, **kwargs)
class BooleanTyped(JSONTyped):
"""Wrap formencode validator with boolean type of JSON Schema"""
def __init__(self, validator, *args, **kwargs):
super().__init__({
'type': 'boolean',
}, validator, *args, **kwargs)
| {
"repo_name": "Hardtack/formencode_jsonschema",
"path": "formencode_jsonschema/typed.py",
"copies": "1",
"size": "3627",
"license": "mit",
"hash": 1161015243006551600,
"line_mean": 29.225,
"line_max": 71,
"alpha_frac": 0.5690653433,
"autogenerated": false,
"ratio": 4.089064261555806,
"config_test": false,
"has_no_keywords": false,
"few_assignments": false,
"quality_score": 0.5158129604855806,
"avg_score": null,
"num_lines": null
} |
from formencode import All, Schema
from formencode.validators import FieldsMatch, UnicodeString, OneOf, Email
from tw2 import forms
import pytz
from kai.lib.highlight import langdict
from kai.model.validators import ExistingSnippetTitle, ExistingEmail, UniqueDisplayname, UniqueEmail, ValidLogin, ValidPassword
class FilteringSchema(Schema):
filter_extra_fields = False
allow_extra_fields = True
ignore_key_missing = False
class AutoComplete(forms.TextField):
template = 'mako:kai.model.widgets.autocomplete'
class SecureToken(forms.HiddenField):
template = 'mako:kai.model.widgets.secure'
class BotsAreLame(forms.HiddenField):
template = 'mako:kai.model.widgets.notabot'
class CommentForm(forms.TableForm):
comment = forms.TextArea(
id = 'comment_form_comment',
label='Comment',
validator = UnicodeString(not_empty=True))
preview = forms.Button(
id='preview',
label='',
value='Preview')
comment_form = CommentForm()
class SnippetForm(forms.TableForm):
title = forms.TextField(
validator = ExistingSnippetTitle(not_empty=True))
description = forms.TextArea(
help_text = "ONE paragraph summarizing the snippet. NO FORMATTING IS APPLIED",
validator = UnicodeString())
content = forms.TextArea(
id = 'snippet_form_content',
name = 'content',
help_text = "The full content of the snippet. Restructured Text formatting is used.",
validator = UnicodeString(not_empty=True))
tags = AutoComplete(
validator = UnicodeString())
preview = forms.Button(
id='preview',
label='',
value='Preview')
snippet_form = SnippetForm()
class PastebinForm(forms.TableForm):
title = forms.TextField(
validator = UnicodeString(not_empty=True))
language = forms.SingleSelectField(
options = sorted(langdict.items(), cmp=lambda x,y: cmp(x[1], y[1])),
validator = OneOf(langdict.keys(), not_empty=True))
code = forms.TextArea(
validator = UnicodeString(not_empty=True))
tags = AutoComplete(
validator = UnicodeString(not_empty=False))
notabot = BotsAreLame(
validator = UnicodeString(not_empty=True),
value = 'most_likely')
pastebin_form = PastebinForm()
class NewArticleForm(forms.TableForm):
css_class = 'new_article'
title = forms.TextField(
css_class = 'textfield',
validator = UnicodeString(not_empty=True))
summary = forms.TextField(
css_class = 'textfield',
validator = UnicodeString())
body = forms.TextArea(
rows = 15,
validator = UnicodeString(not_empty=True))
publish_date = forms.CalendarDateTimePicker()
preview = forms.Button(id='Preview', label='', value='Preview')
new_article_form = NewArticleForm()
class ChangePasswordForm(forms.TableForm):
password = forms.PasswordField(
validator = ValidPassword(not_empty=True))
confirm_password = forms.PasswordField(
validator = ValidPassword(not_empty=True))
authentication_token = SecureToken()
class child(forms.TableLayout):
validator = FilteringSchema(
chained_validators=[FieldsMatch('password', 'confirm_password')],
msgs=dict(childerror=''))
change_password_form = ChangePasswordForm()
class ForgotPasswordForm(forms.TableForm):
email_address = forms.TextField(
label_text = 'Email',
validator = ExistingEmail(not_empty=True))
authentication_token = SecureToken()
forgot_password_form = ForgotPasswordForm()
class LoginForm(forms.TableForm):
email_address = forms.TextField(
validator = Email(not_empty=True))
password = forms.PasswordField(
validator = UnicodeString(not_empty=True))
authentication_token = SecureToken()
class child(forms.TableLayout):
validator = FilteringSchema(
chained_validators=[ValidLogin(email='email_address', password='password')],
msgs=dict(childerror=''))
submit = forms.SubmitButton(css_class='submit', value='Login')
login_form = LoginForm()
class OpenIDLogin(forms.TableForm):
openid_identifier = forms.TextField(
label_text="OpenID Identifier",
validator = UnicodeString(not_empty=True))
authentication_token = SecureToken()
submit = forms.SubmitButton(css_class='submit', value='Login')
openid_login_form = OpenIDLogin()
class OpenIDRegistrationForm(forms.TableForm):
displayname = forms.TextField(
label_text = "Display Name",
help_text = "Name that will appear when posting/commenting",
validator = All(UnicodeString(not_empty=True), UniqueDisplayname()))
email_address = forms.TextField(
validator = All(Email(not_empty=True), UniqueEmail()))
timezone = forms.SingleSelectField(
options = pytz.common_timezones,
validator = OneOf(pytz.common_timezones, not_empty=True))
openid_registration_form = OpenIDRegistrationForm()
class RegistrationForm(forms.TableForm):
displayname = forms.TextField(
label_text = "Display Name",
help_text = "Name that will appear when posting/commenting",
validator = All(UnicodeString(not_empty=True), UniqueDisplayname()))
email_address = forms.TextField(
validator = All(Email(not_empty=True), UniqueEmail()))
timezone = forms.SingleSelectField(
options = pytz.common_timezones,
validator = OneOf(pytz.common_timezones, not_empty=True))
password = forms.PasswordField(
validator = ValidPassword(not_empty=True))
confirm_password = forms.PasswordField(
validator = ValidPassword(not_empty=True))
authentication_token = SecureToken()
class child(forms.TableLayout):
validator = FilteringSchema(
chained_validators=[FieldsMatch('password', 'confirm_password')],
msgs=dict(childerror=''))
registration_form = RegistrationForm()
| {
"repo_name": "Pylons/kai",
"path": "kai/model/forms.py",
"copies": "1",
"size": "5976",
"license": "bsd-3-clause",
"hash": 1818508038353289000,
"line_mean": 34.1529411765,
"line_max": 127,
"alpha_frac": 0.6849062918,
"autogenerated": false,
"ratio": 4.018829858776059,
"config_test": false,
"has_no_keywords": false,
"few_assignments": false,
"quality_score": 0.5203736150576059,
"avg_score": null,
"num_lines": null
} |
from formencode import htmlfill
from formencode import variabledecode
from formencode import Invalid
from pyramid.i18n import get_localizer, TranslationStringFactory, TranslationString
from pyramid.renderers import render
class State(object):
"""
Default "empty" state object.
Keyword arguments are automatically bound to properties, for
example::
obj = State(foo="bar")
obj.foo == "bar"
"""
def __init__(self, **kwargs):
for k, v in kwargs.items():
setattr(self, k, v)
def __contains__(self, k):
return hasattr(self, k)
def __getitem__(self, k):
try:
return getattr(self, k)
except AttributeError:
raise KeyError
def __setitem__(self, k, v):
setattr(self, k, v)
def get(self, k, default=None):
return getattr(self, k, default)
fe_tsf = TranslationStringFactory('FormEncode')
def get_default_translate_fn(request):
pyramid_translate = get_localizer(request).translate
def translate(s):
if not isinstance(s, TranslationString):
s = fe_tsf(s)
return pyramid_translate(s)
return translate
class Form(object):
"""
Legacy class for validating FormEncode schemas and validators.
`request` : Pyramid request instance
`schema` : FormEncode Schema class or instance
`validators` : a dict of FormEncode validators i.e. { field : validator }
`defaults` : a dict of default values
`obj` : instance of an object (e.g. SQLAlchemy model)
`state` : state passed to FormEncode validators.
`method` : HTTP method
`variable_decode` : will decode dict/lists
`dict_char` : variabledecode dict char
`list_char` : variabledecode list char
Also note that values of ``obj`` supercede those of ``defaults``. Only
fields specified in your schema or validators will be taken from the
object.
"""
default_state = State
def __init__(self, request, schema=None, validators=None, defaults=None,
obj=None, extra=None, include=None, exclude=None, state=None,
method="POST", variable_decode=False, dict_char=".",
list_char="-", multipart=False):
self.request = request
self.schema = schema
self.validators = validators or {}
self.method = method
self.variable_decode = variable_decode
self.dict_char = dict_char
self.list_char = list_char
self.multipart = multipart
self.state = state
self.is_validated = False
self.errors = {}
self.data = {}
if self.state is None:
self.state = self.default_state()
if not hasattr(self.state, '_'):
self.state._ = get_default_translate_fn(request)
if defaults:
self.data.update(defaults)
if obj:
fields = self.schema.fields.keys() + self.validators.keys()
for f in fields:
if hasattr(obj, f):
self.data[f] = getattr(obj, f)
def is_error(self, field):
"""
Checks if individual field has errors.
"""
return field in self.errors
def all_errors(self):
"""
Returns all errors in a single list.
"""
if isinstance(self.errors, basestring):
return [self.errors]
if isinstance(self.errors, list):
return self.errors
errors = []
for field in self.errors.iterkeys():
errors += self.errors_for(field)
return errors
def errors_for(self, field):
"""
Returns any errors for a given field as a list.
"""
errors = self.errors.get(field, [])
if isinstance(errors, basestring):
errors = [errors]
return errors
def validate(self, force_validate=False, params=None):
"""
Runs validation and returns True/False whether form is
valid.
This will check if the form should be validated (i.e. the
request method matches) and the schema/validators validate.
Validation will only be run once; subsequent calls to
validate() will have no effect, i.e. will just return
the original result.
The errors and data values will be updated accordingly.
`force_validate` : will run validation regardless of request method.
`params` : dict or MultiDict of params. By default
will use **request.json_body** (if JSON body), **request.POST** (if HTTP POST) or **request.params**.
"""
assert self.schema or self.validators, \
"validators and/or schema required"
if self.is_validated:
return not(self.errors)
if not force_validate:
if self.method and self.method != self.request.method:
return False
if params is None:
if hasattr(self.request, 'json_body') and self.request.json_body:
params = self.request.json_body
elif self.method == "POST":
params = self.request.POST
else:
params = self.request.params
if self.variable_decode and not (hasattr(self.request, 'json_body') and self.request.json_body):
decoded = variabledecode.variable_decode(
params, self.dict_char, self.list_char)
else:
decoded = params
if hasattr(decoded, "mixed"):
decoded = decoded.mixed()
self.data.update(decoded)
if self.schema:
try:
self.data = self.schema.to_python(decoded, self.state)
except Invalid, e:
self.errors = e.unpack_errors(self.variable_decode,
self.dict_char,
self.list_char)
if self.validators:
for field, validator in self.validators.iteritems():
try:
self.data[field] = validator.to_python(decoded.get(field),
self.state)
except Invalid, e:
self.errors[field] = unicode(e)
self.is_validated = True
return not(self.errors)
def bind(self, obj, include=None, exclude=None):
"""
Binds validated field values to an object instance, for example a
SQLAlchemy model instance.
`include` : list of included fields. If field not in this list it
will not be bound to this object.
`exclude` : list of excluded fields. If field is in this list it
will not be bound to the object.
Returns the `obj` passed in.
Note that any properties starting with underscore "_" are ignored
regardless of ``include`` and ``exclude``. If you need to set these
do so manually from the ``data`` property of the form instance.
Calling bind() before running validate() will result in a RuntimeError
"""
if not self.is_validated:
raise RuntimeError, \
"Form has not been validated. Call validate() first"
if self.errors:
raise RuntimeError, "Cannot bind to object if form has errors"
items = [(k, v) for k, v in self.data.items() if not k.startswith("_")]
for k, v in items:
if include and k not in include:
continue
if exclude and k in exclude:
continue
setattr(obj, k, v)
return obj
def htmlfill(self, content, **htmlfill_kwargs):
"""
Runs FormEncode **htmlfill** on content.
"""
charset = getattr(self.request, 'charset', 'utf-8')
htmlfill_kwargs.setdefault('encoding', charset)
return htmlfill.render(content,
defaults=self.data,
errors=self.errors,
**htmlfill_kwargs)
def render(self, template, extra_info=None, htmlfill=True,
**htmlfill_kwargs):
"""
Renders the form directly to a template,
using Pyramid's **render** function.
`template` : name of template
`extra_info` : dict of extra data to pass to template
`htmlfill` : run htmlfill on the result.
By default the form itself will be passed in as `form`.
htmlfill is automatically run on the result of render if
`htmlfill` is **True**.
This is useful if you want to use htmlfill on a form,
but still return a dict from a view. For example::
@view_config(name='submit', request_method='POST')
def submit(request):
form = Form(request, MySchema)
if form.validate():
# do something
return dict(form=form.render("my_form.html"))
"""
extra_info = extra_info or {}
extra_info.setdefault('form', self)
result = render(template, extra_info, self.request)
if htmlfill:
result = self.htmlfill(result, **htmlfill_kwargs)
return result
| {
"repo_name": "vsobolmaven/pyramid_simpleform",
"path": "pyramid_simpleform/__init__.py",
"copies": "1",
"size": "9358",
"license": "bsd-3-clause",
"hash": 564750223374279550,
"line_mean": 29.5816993464,
"line_max": 109,
"alpha_frac": 0.5684975422,
"autogenerated": false,
"ratio": 4.529525653436592,
"config_test": false,
"has_no_keywords": false,
"few_assignments": false,
"quality_score": 1,
"avg_score": 0.002160766988549725,
"num_lines": 306
} |
from formencode import Invalid, htmlfill, Schema, validators
from WebKit.Page import Page
page_style = '''
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
<head>
<meta http-equiv="content-type" content="text/html; charset=UTF-8">
<title>Tell me about yourself</title>
<style type="text/css">
.error {background-color: #ffdddd}
.error-message {border: 2px solid #f00}
</style>
</head>
<body>
<h1>Tell me about yourself</h1>
<p><i>A FormEncode example</i></p>
%s
</body></html>'''
form_template = '''
<form action="" method="POST">
<p>Your name:<br>
<form:error name="name">
<input type="text" name="name"></p>
<p>Your age:<br>
<form:error name="age">
<input type="text" name="age"></p>
<p>Your favorite color:<br>
<form:error name="color">
<input type="checkbox" value="red" name="color"> Red<br>
<input type="checkbox" value="blue" name="color"> Blue<br>
<input type="checkbox" value="black" name="color"> Black<br>
<input type="checkbox" value="green" name="color"> Green<br>
<input type="checkbox" value="pink" name="color"> Pink</p>
<input type="submit" name="_action_save" value="Submit">
</form>'''
response_template = '''
<h2>Hello, %(name)s!</h2>
<p>You are %(age)d years old
and your favorite color is %(color)s.</p>'''
class FormSchema(Schema):
name = validators.String(not_empty=True)
age = validators.Int(min=13, max=99)
color = validators.OneOf(['red', 'blue', 'black', 'green'])
filter_extra_fields = True
allow_extra_fields = True
class index(Page):
def awake(self, trans):
Page.awake(self, trans)
self.rendered_form = None
def actions(self):
return ['save']
def save(self):
fields = self.request().fields()
try:
fields = FormSchema.to_python(fields, self)
except Invalid, e:
errors = dict((k, v.encode('utf-8'))
for k, v in e.unpack_errors().iteritems())
print "Errors:", errors
self.rendered_form = htmlfill.render(form_template,
defaults=fields, errors=errors)
self.writeHTML()
else:
self.doAction(fields)
def doAction(self, fields):
print "Fields:", fields
self.rendered_form = response_template % fields
self.writeHTML()
def writeHTML(self):
if self.rendered_form is None:
self.rendered_form = htmlfill.render(form_template,
defaults=self.getDefaults())
self.write(page_style % self.rendered_form)
def getDefaults(self):
return dict(age='enter your age', color=['blue'])
def preAction(self, trans):
pass
postAction = preAction
| {
"repo_name": "genixpro/formencode",
"path": "examples/WebwareExamples/index.py",
"copies": "1",
"size": "2711",
"license": "mit",
"hash": -8601894768953122000,
"line_mean": 25.8415841584,
"line_max": 69,
"alpha_frac": 0.6189597934,
"autogenerated": false,
"ratio": 3.3677018633540374,
"config_test": false,
"has_no_keywords": false,
"few_assignments": false,
"quality_score": 0.948369112665018,
"avg_score": 0.0005941060207715687,
"num_lines": 101
} |
from formencode import Invalid
from tw2.core import Widget, Param, DisplayOnlyWidget, ValidationError, RepeatingWidget
from tw2.forms import (CalendarDatePicker, CalendarDateTimePicker, TableForm, DataGrid,
SingleSelectField, MultipleSelectField, InputField, HiddenField,
TextField, FileField, CheckBox, PasswordField, TextArea, ListLayout,
StripBlanks)
from tw2.forms import Label as tw2Label
from tw2.core import validation as tw2v
from sprox._compat import unicode_text
class Label(tw2Label):
def prepare(self):
self.text = unicode_text(self.value)
super(Label, self).prepare()
class SproxMethodPutHiddenField(HiddenField):
name = '_method'
def prepare(self):
self.value = 'PUT'
super(SproxMethodPutHiddenField, self).prepare()
class ContainerWidget(DisplayOnlyWidget):
template = "genshi:sprox.widgets.tw2widgets.templates.container"
controller = Param('controller', attribute=False, default=None)
css_class = "containerwidget"
id_suffix = 'container'
class TableLabelWidget(Widget):
template = "genshi:sprox.widgets.tw2widgets.templates.tableLabel"
controller = Param('controller', attribute=False, default=None)
identifier = Param('identifier', attribute=False)
class ModelLabelWidget(Widget):
template = "genshi:sprox.widgets.tw2widgets.templates.modelLabel"
controller = Param('controller', attribute=False, default=None)
identifier = Param('identifier', attribute=False)
class EntityLabelWidget(Widget):
template = "genshi:sprox.widgets.tw2widgets.templates.entityLabel"
controller = Param('controller', attribute=False, default=None)
entity = Param('entity', attribute=False)
css_class = "entitylabelwidget"
class RecordViewWidget(Widget):
template = "genshi:sprox.widgets.tw2widgets.templates.recordViewTable"
entity = Param('entity', attribute=False, default=None)
class RecordFieldWidget(Widget):
template = "genshi:sprox.widgets.tw2widgets.templates.recordField"
field_name = Param('field_name', attribute=False)
css_class = "recordfieldwidget"
class TableDefWidget(Widget):
template = "genshi:sprox.widgets.tw2widgets.templates.tableDef"
identifier = Param('identifier', attribute=False)
class EntityDefWidget(Widget):
template = "genshi:sprox.widgets.tw2widgets.templates.entityDef"
entity = Param('entity', attribute=False)
class TableWidget(Widget):
template = "genshi:sprox.widgets.tw2widgets.templates.table"
class SproxCalendarDatePicker(CalendarDatePicker):
date_format = '%Y-%m-%d'
class SproxTimePicker(CalendarDateTimePicker):
date_format = '%H:%M:%S'
class SproxCalendarDateTimePicker(CalendarDateTimePicker):
date_format = '%Y-%m-%d %H:%M:%S'
class SproxDataGrid(DataGrid):
template = "sprox.widgets.tw2widgets.templates.datagrid"
pks = Param('pks', attribute=False),
xml_fields = Param('xml_fields', attribute=False, default=['actions'])
value = []
class SproxCheckBox(CheckBox):
def prepare(self):
super(SproxCheckBox, self).prepare()
self.attrs['value'] = 'true'
class PropertySingleSelectField(SingleSelectField):
entity = Param('entity', attribute=False, default=None)
provider = Param('provider', attribute=False, default=None)
field_name = Param('field_name', attribute=False, default=None)
dropdown_field_names = Param('dropdown_field_names', attribute=False, default=None)
nullable = Param('nullable', attribute=False, default=False)
disabled = Param('disabled', attribute=False, default=False)
prompt_text = None
def prepare(self):
#This is required for ming
entity = self.__class__.entity
options = self.provider.get_dropdown_options(entity, self.field_name, self.dropdown_field_names)
self.options = [(unicode_text(k), unicode_text(v)) for k,v in options]
if self.nullable:
self.options.append(['', "-----------"])
if not self.value:
self.value = ''
self.value = unicode_text(self.value)
super(PropertySingleSelectField, self).prepare()
class PropertyMultipleSelectField(MultipleSelectField):
entity = Param('entity', attribute=False, default=None)
provider = Param('provider', attribute=False, default=None)
field_name = Param('field_name', attribute=False, default=None)
dropdown_field_names = Param('dropdown_field_names', attribute=False, default=None)
nullable = Param('nullable', attribute=False, default=False)
disabled = Param('disabled', attribute=False, default=False)
def _safe_from_validate(self, validator, value, state=None):
try:
return validator.from_python(value, state=state)
except Invalid:
return Invalid
def _safe_to_validate(self, validator, value, state=None):
try:
return validator.to_python(value, state=state)
except Invalid:
return Invalid
def _validate(self, value, state=None):
# Work around a bug in tw2.core <= 2.2.2 where twc.safe_validate
# doesn't work with formencode validators.
value = value or []
if not isinstance(value, (list, tuple)):
value = [value]
if self.validator:
self.validator.to_python(value, state)
if self.item_validator:
value = [self._safe_to_validate(self.item_validator, v) for v in value]
self.value = [v for v in value if v is not Invalid]
return self.value
def prepare(self):
# This is required for ming
entity = self.__class__.entity
options = self.provider.get_dropdown_options(entity, self.field_name, self.dropdown_field_names)
self.options = [(unicode_text(k), unicode_text(v)) for k,v in options]
if not self.value:
self.value = []
if not hasattr(self, '_validated') and self.item_validator:
self.value = [self._safe_from_validate(self.item_validator, v) for v in self.value]
self.value = [unicode_text(v) for v in self.value if v is not Invalid]
super(PropertyMultipleSelectField, self).prepare()
class SubDocument(ListLayout):
direct = Param('direct', attribute=False, default=False)
children_attrs = Param('children_attrs', attribute=False, default={})
@classmethod
def post_define(cls):
if not cls.css_class:
cls.css_class = ''
if 'subdocument' not in cls.css_class:
cls.css_class += ' subdocument'
for c in getattr(cls, 'children', []):
# SubDocument always propagates its template to nested subdocuments
if issubclass(c, SubDocument):
c.children_attrs = cls.children_attrs
c.template = cls.template
elif issubclass(c, SubDocumentsList):
c.children_attrs = cls.children_attrs
c.child = c.child(template=cls.template)
else:
for name, value in cls.children_attrs.items():
setattr(c, name, value)
if cls.direct:
# In direct mode we just act as a proxy to the real field
# so we set the field key equal to our own
c.compound_key = ':'.join(c.compound_key.split(':')[:-1])
if not hasattr(cls, 'children'):
cls.children = []
@tw2v.catch_errors
def _validate(self, value, state=None):
if self.direct:
# In direct mode we just act as a proxy to the real field
# so we directly validate the field
return self.children[0]._validate(value, state)
else:
return super(SubDocument, self)._validate(value, state)
def prepare(self):
if self.direct:
# In direct mode we just act as a proxy to the real field
# so we provide the value to the field and throw away error messages
# to avoid duplicating them (one for us and one for the field).
self.children[0].value = self.value
self.error_msg = ''
super(SubDocument, self).prepare()
class SubDocumentsList(RepeatingWidget):
template = 'sprox.widgets.tw2widgets.templates.subdocuments'
child = SubDocument
children_attrs = Param('children_attrs', attribute=False, default={})
direct = Param('direct', attribute=False, default=False)
extra_reps = 1
@classmethod
def post_define(cls):
if not cls.css_class:
cls.css_class = ''
if 'subdocuments' not in cls.css_class:
cls.css_class += ' subdocuments'
cls.child.children_attrs = cls.children_attrs
if cls.direct:
cls.child.direct = True
def prepare(self):
super(SubDocumentsList, self).prepare()
# Hide the last element, used to add new entries
self.children[len(self.children)-1].attrs['style'] = 'display: none'
def _validate(self, value, state=None):
return super(SubDocumentsList, self)._validate(
StripBlanks().to_python(value, state), state
) | {
"repo_name": "TurboGears/sprox",
"path": "sprox/widgets/tw2widgets/widgets.py",
"copies": "1",
"size": "9167",
"license": "mit",
"hash": -3165932233127691000,
"line_mean": 37.359832636,
"line_max": 104,
"alpha_frac": 0.657794262,
"autogenerated": false,
"ratio": 3.9701169337375486,
"config_test": false,
"has_no_keywords": false,
"few_assignments": false,
"quality_score": 0.5127911195737549,
"avg_score": null,
"num_lines": null
} |
from formencode import Invalid
from nomenklatura.core import db
from nomenklatura.core import celery as app
from nomenklatura.model import Dataset, Entity, Account, Upload
def apply_mapping(row, mapping):
out = {'attributes': {}, 'reviewed': mapping['reviewed']}
for column, prop in mapping['columns'].items():
value = row.get(column)
if value is None or not len(value.strip()):
continue
if prop.startswith('attributes.'):
a, prop = prop.split('.', 1)
out[a][prop] = value
else:
out[prop] = value
return out
@app.task
def import_upload(upload_id, account_id, mapping):
upload = Upload.all().filter_by(id=upload_id).first()
account = Account.by_id(account_id)
mapped = mapping['columns'].values()
rows = [apply_mapping(r, mapping) for r in upload.tab.dict]
# put aliases second.
rows = sorted(rows, key=lambda r: 2 if r.get('canonical') else 1)
for i, row in enumerate(rows):
try:
entity = None
if row.get('id'):
entity = Entity.by_id(row.get('id'))
if entity is None:
entity = Entity.by_name(upload.dataset, row.get('name'))
if entity is None:
entity = Entity.create(upload.dataset, row, account)
# restore some defaults:
if entity.canonical_id and 'canonical' not in mapped:
row['canonical'] = entity.canonical_id
if entity.invalid and 'invalid' not in mapped:
row['invalid'] = entity.invalid
if entity.attributes:
attributes = entity.attributes.copy()
else:
attributes = {}
attributes.update(row['attributes'])
row['attributes'] = attributes
entity.update(row, account)
print entity
if i % 100 == 0:
print 'COMMIT'
db.session.commit()
except Invalid, inv:
# TODO: logging.
print inv
db.session.commit() | {
"repo_name": "robbi5/nomenklatura",
"path": "nomenklatura/importer.py",
"copies": "1",
"size": "2093",
"license": "mit",
"hash": -1740905002808424000,
"line_mean": 32.2380952381,
"line_max": 72,
"alpha_frac": 0.5609173435,
"autogenerated": false,
"ratio": 4.2028112449799195,
"config_test": false,
"has_no_keywords": false,
"few_assignments": false,
"quality_score": 0.5263728588479919,
"avg_score": null,
"num_lines": null
} |
from formencode import Schema, validators as v, compound
from formencode_jsonschema import JSONSchema, typed
from .utils import compare_schema
def test_simple_dump():
class UserCreate(Schema):
username = v.PlainText(not_empty=True)
name = v.UnicodeString(not_empty=True)
description = v.UnicodeString(if_missing=None)
password = v.PlainText(not_empty=True)
json_schema = JSONSchema()
formencode_schema = UserCreate()
result = json_schema.dump(formencode_schema)
compare_schema({
'required': ['name', 'password', 'username'],
'type': 'object',
'properties': {
'username': {
'type': 'string'
},
'name': {
'type': 'string'
},
'description': {
'type': 'string'
},
'password': {
'type': 'string'
}
}
}, result.data)
def test_compound_dump():
class UserDescribe(Schema):
name = compound.All(
v.UnicodeString(not_empty=True),
v.PlainText(),
)
description = v.UnicodeString(if_missing=None)
json_schema = JSONSchema()
formencode_schema = UserDescribe()
result = json_schema.dump(formencode_schema)
compare_schema({
'required': ['name'],
'type': 'object',
'properties': {
'name': {
'type': 'string'
},
'description': {
'type': 'string'
}
}
}, result.data)
def test_typed_dump():
class UserReally(Schema):
really = typed.BooleanTyped(v.UnicodeString(if_missing=None),
required=True)
json_schema = JSONSchema()
formencode_schema = UserReally()
result = json_schema.dump(formencode_schema)
compare_schema({
'required': ['really'],
'type': 'object',
'properties': {
'really': {
'type': 'boolean'
}
}
}, result.data)
| {
"repo_name": "Hardtack/formencode_jsonschema",
"path": "tests/test_dump.py",
"copies": "1",
"size": "2089",
"license": "mit",
"hash": -6164299019328259000,
"line_mean": 24.4756097561,
"line_max": 69,
"alpha_frac": 0.5122067975,
"autogenerated": false,
"ratio": 4.128458498023716,
"config_test": false,
"has_no_keywords": false,
"few_assignments": false,
"quality_score": 0.5140665295523716,
"avg_score": null,
"num_lines": null
} |
from formencode import Schema, validators, FancyValidator, All, Invalid
from models import DBSession, User
class UniqueEmail(FancyValidator):
def to_python(self, value, state):
if DBSession.query(User).filter(User.email == value).count():
raise Invalid(
'That email already exists', value, state
)
return value
class EmailExists(FancyValidator):
def to_python(self, value, state):
if not DBSession.query(User).filter(User.email == value).count():
raise Invalid(
'That email doesnt exist', value, state
)
return value
class PasswordCorrect(FancyValidator):
def to_python(self, value, state):
if not state.user.check_password(value):
raise Invalid(
'Current password is not correct', value, state
)
return value
class OneOfPad(FancyValidator):
def to_python(self, value, state):
value = int(value)
if value != 0 and value not in [p.id for p in state.user.pads.all()]:
raise Invalid(
'Selected pad is not correct', value, state
)
return value
class SignupSchema(Schema):
allow_extra_fields = True
filter_extra_fields = True
email = All(UniqueEmail(), validators.Email(not_empty=True))
password = validators.UnicodeString(min=6)
confirm_password = validators.UnicodeString(min=6)
chained_validators = [
validators.FieldsMatch('password', 'confirm_password')
]
class SigninSchema(Schema):
allow_extra_fields = True
filter_extra_fields = True
email = validators.Email(not_empty=True)
password = validators.UnicodeString(min=6)
class PadSchema(Schema):
allow_extra_fields = True
name = validators.UnicodeString(not_empty=True)
class NoteSchema(Schema):
allow_extra_fields = True
name = validators.UnicodeString(not_empty=True)
text = validators.UnicodeString(not_empty=True)
pad_id = OneOfPad()
class ForgotPasswordSchema(Schema):
allow_extra_fields = False
email = All(EmailExists(), validators.Email(not_empty=True))
class ChangePasswordSchema(Schema):
allow_extra_fields = False
old_password = All(PasswordCorrect(), validators.UnicodeString(min=6))
password = validators.UnicodeString(min=6)
confirm_password = validators.UnicodeString(min=6)
passwords_match = [
validators.FieldsMatch('password', 'confirm_password')
]
| {
"repo_name": "nadavge/notejam",
"path": "pyramid/notejam/forms.py",
"copies": "6",
"size": "2508",
"license": "mit",
"hash": 5661195763243191000,
"line_mean": 26.5604395604,
"line_max": 77,
"alpha_frac": 0.6574960128,
"autogenerated": false,
"ratio": 4.019230769230769,
"config_test": false,
"has_no_keywords": false,
"few_assignments": false,
"quality_score": 0.7676726782030768,
"avg_score": null,
"num_lines": null
} |
from formencode import validators as fev
from dateutil import parser
class DateTime(fev.FancyValidator):
def _to_python(self, value, state=None):
return parser.parse(value)
def _from_python(self, value, state=None):
return value.isoformat()
class Object(fev.FancyValidator):
'''Basic do-nothing validator'''
def _to_python(self, value, state=None):
return value
def _from_python(self, value, state=None):
return value
def order_models(models):
'''Yields the models in order so $refs are always defined before being
used'''
yielded = set([
'string',
'boolean',
'integer',
'array',
'date-time',
'object'
])
model_deps = {}
for key, model in models.items():
assert model['id'] == key, 'Model name/id mismatch: %s != %s' % (
model['id'], key)
model_deps[key] = set(model_depends(model))
while model_deps:
len_yielded = len(yielded)
for key, deps in model_deps.items():
if not deps - yielded:
yielded.add(key)
yield models[key]
model_deps.pop(key)
if len(yielded) == len_yielded:
import ipdb; ipdb.set_trace();
assert len(yielded) > len_yielded, \
"Can't make forward progress; deps are %s" % model_deps
def model_depends(model):
for k, v in model.items():
if k == '$ref':
yield v
elif k == 'type':
yield v
elif isinstance(v, dict):
for dep in model_depends(v):
yield dep
| {
"repo_name": "synappio/swagger-pyramid",
"path": "swagger/lib.py",
"copies": "1",
"size": "1633",
"license": "apache-2.0",
"hash": -1173662895910071000,
"line_mean": 24.9206349206,
"line_max": 74,
"alpha_frac": 0.5535823637,
"autogenerated": false,
"ratio": 3.8605200945626477,
"config_test": false,
"has_no_keywords": false,
"few_assignments": false,
"quality_score": 0.4914102458262648,
"avg_score": null,
"num_lines": null
} |
from formencode import validators, NoDefault, Invalid, Schema, NestedVariables, ForEach, All, Any
from columns.lib import rfc3339
__all__ = [
'Invalid',
'CreateArticle', 'UpdateArticle',
'CreatePage', 'UpdatePage',
'CreateUser', 'UpdateUser',
'CreateAccount', 'UpdateAccount',
'CreateComment', 'UpdateComment',
'CreateUpload', 'UpdateUpload',
'CreateTag',
]
class DateTimeValidator(validators.FancyValidator):
format = ""
tzinfo = None
messages = {'bad_format': 'Date/Time stamp must be in the format %(format)s',}
def to_python(self, value, state):
import datetime
import pytz
UTC = pytz.timezone('UTC')
EST = pytz.timezone('US/Eastern')
try:
if isinstance(value, basestring):
value = datetime.datetime.strptime(value,self.format)
dt = EST.localize(value).astimezone(UTC).replace(tzinfo=None)
except ValueError:
raise Invalid(self.message("bad_format", state, format=self.format), value, state)
return dt
def from_python(self, value, state):
return value.strftime(self.format)
class UniqueUserName(validators.FancyValidator):
messages = {'user_name_taken': 'The name %(name)s is unavailable',}
def to_python(self, value, state):
from columns.model import User, meta
if meta.Session.query(User).filter(User.name == value).count() > 0:
raise validators.Invalid(self.message("user_name_taken",state,name=value),value,state)
return value
class StringListValidator(validators.FancyValidator):
messages = {'bad_string': 'Value %(value)s is not a valid string',}
def to_python(self, value, state):
try:
return [unicode(x.strip()) for x in value.split(",") if x.strip() != ""]
except (TypeError, ValueError, AttributeError):
raise Invalid(self.message("bad_string", state, value=str(value)), value, state)
def from_python(self, value, state):
return unicode(", ".join(value))
class HTMLValidator(validators.UnicodeString):
def to_python(self, value, state):
try:
from lxml import etree
soup = etree.fromstring("<div>%s</div>"%value)
return etree.tostring(soup, encoding=unicode)[5:-6]
except:
from BeautifulSoup import BeautifulSoup
soup = BeautifulSoup(value)
return unicode(soup)
class CreateArticle(Schema):
allow_extra_fields = True
title = validators.UnicodeString(max=255, strip=True, not_empty=True)
page_id = validators.Int(if_empty=None)
can_comment = validators.StringBool(if_missing=False)
sticky = validators.StringBool(if_missing=False)
published = DateTimeValidator(format=rfc3339.RFC3339_wo_Timezone, if_empty=None)
content = HTMLValidator()
tags = StringListValidator()
class UpdateArticle(CreateArticle):
allow_extra_fields = True
filter_extra_fields = True
class CreatePage(Schema):
allow_extra_fields = True
filter_extra_fields = True
title = validators.UnicodeString(max=255, strip=True, not_empty=True)
can_post = validators.StringBool(if_missing=False)
content = HTMLValidator(if_empty=u'')
template = validators.UnicodeString(if_empty=u'/blog/blank')
visible = validators.StringBool(if_missing=False)
in_main = validators.StringBool(if_missing=False)
in_menu = validators.StringBool(if_missing=False)
stream_comment_style = validators.UnicodeString(max=20, strip=True)
story_comment_style = validators.UnicodeString(max=20, strip=True)
class UpdatePage(CreatePage):
allow_extra_fields = True
filter_extra_fields = True
class CreateUser(Schema):
allow_extra_fields = True
filter_extra_fields = True
name = validators.UnicodeString(max=255, strip=True, not_empty=True)
open_id = validators.UnicodeString(max=255, if_empty=None, strip=True)
fb_id = validators.UnicodeString(max=255, if_empty=None, strip=True)
twitter_id = validators.UnicodeString(max=255, if_empty=None, strip=True)
profile = validators.URL(add_http=True, max=255, strip=True, if_empty=None)
type = validators.Int()
class UpdateUser(CreateUser):
allow_extra_fields = True
filter_extra_fields = True
class CreateAccount(Schema):
allow_extra_fields = True
filter_extra_fields = True
name = validators.UnicodeString(max=255, strip=True, not_empty=True)
profile = validators.URL(add_http=True, max=255, strip=True, if_empty=None)
class UpdateAccount(Schema):
allow_extra_fields = True
filter_extra_fields = True
profile = validators.URL(add_http=True, max=255, strip=True, if_empty=None)
class CreateTag(Schema):
allow_extra_fields = True
filter_extra_fields = True
label = validators.UnicodeString(max=255, strip=True)
class UpdateTag(CreateTag):
allow_extra_fields = True
filter_extra_fields = True
class CreateComment(Schema):
allow_extra_fields = True
filter_extra_fields = True
parent = validators.Int(if_missing=None, if_empty=None)
title = validators.UnicodeString(max=255, if_empty='No Subject', strip=True)
content = validators.UnicodeString()
class UpdateComment(CreateComment):
allow_extra_fields = True
filter_extra_fields = True
class CreateUpload(Schema):
allow_extra_fields = True
filter_extra_fields = True
upload = validators.FieldStorageUploadConverter()
title = validators.UnicodeString(max=255, strip=True)
content = validators.UnicodeString(if_empty=None, if_missing=u'', strip=True)
tags = StringListValidator(if_missing=[])
class UpdateUpload(Schema):
allow_extra_fields = True
filter_extra_fields = True
title = validators.UnicodeString(max=255, strip=True)
content = validators.UnicodeString(if_empty=None, if_missing=u'', strip=True)
tags = StringListValidator(if_missing=[])
class CreateSetting(Schema):
pre_validators = [NestedVariables()]
allow_extra_fields = True
filter_extra_fields = True
module = validators.UnicodeString(max=255, strip=True)
values = NestedVariables()
class UpdateSetting(CreateSetting):
pre_validators = [NestedVariables()]
allow_extra_fields = True
filter_extra_fields = True
values = NestedVariables()
class LoginForm(Schema):
allow_extra_fields = True
filter_extra_fields = True
auth_type = validators.UnicodeString(max=255)
auth_id = validators.UnicodeString(max=255, if_empty=None, if_missing=None)
class UpdateProfile(Schema):
allow_extra_fields = True
filter_extra_fields = True
profile = validators.URL(add_http=True, max=255, strip=True, if_empty=None)
class SaveQuickUser(Schema):
allow_extra_fields = True
filter_extra_fields = True
name = All(validators.UnicodeString(max=255,min=3,strip=True),UniqueUserName())
profile = validators.URL(add_http=True, max=255, strip=True, if_empty=None)
class Delete(Schema):
allow_extra_fields = True
filter_extra_fields = True
obj_type = validators.UnicodeString(max=255)
id = validators.Int(max=255)
| {
"repo_name": "yoshrote/Columns",
"path": "columns/model/form.py",
"copies": "1",
"size": "6640",
"license": "bsd-3-clause",
"hash": 2075385405344402200,
"line_mean": 29.0452488688,
"line_max": 97,
"alpha_frac": 0.7447289157,
"autogenerated": false,
"ratio": 3.2453567937438903,
"config_test": false,
"has_no_keywords": false,
"few_assignments": false,
"quality_score": 0.44900857094438906,
"avg_score": null,
"num_lines": null
} |
from formencode.validators import FancyValidator
from formencode.api import *
import formencode
import re
_ = lambda s: s
class Utf8MaxLength(FancyValidator):
"""
Invalid if the value is longer than `maxLength`. Uses len(),
so it can work for strings, lists, or anything with length.
Examples::
>>> max5 = MaxLength(5)
>>> max5.to_python('12345')
'12345'
>>> max5.from_python('12345')
'12345'
>>> max5.to_python('123456')
Traceback (most recent call last):
...
Invalid: Enter a value less than 5 characters long
>>> max5(accept_python=False).from_python('123456')
Traceback (most recent call last):
...
Invalid: Enter a value less than 5 characters long
>>> max5.to_python([1, 2, 3])
[1, 2, 3]
>>> max5.to_python([1, 2, 3, 4, 5, 6])
Traceback (most recent call last):
...
Invalid: Enter a value less than 5 characters long
>>> max5.to_python(5)
Traceback (most recent call last):
...
Invalid: Invalid value (value with length expected)
"""
__unpackargs__ = ('maxLength',)
messages = dict(
tooLong=_('Enter a value less than %(maxLength)i characters long'),
invalid=_('Invalid value (value with length expected)'))
def validate_python(self, value, state):
try:
if value and len(value.decode('utf8')) > self.maxLength:
raise Invalid(
self.message('tooLong', state,
maxLength=self.maxLength), value, state)
else:
return None
except TypeError:
raise Invalid(
self.message('invalid', state), value, state)
class Utf8MinLength(FancyValidator):
"""
Invalid if the value is longer than `maxLength`. Uses len(),
so it can work for strings, lists, or anything with length.
Examples::
>>> max5 = MaxLength(5)
>>> max5.to_python('12345')
'12345'
>>> max5.from_python('12345')
'12345'
>>> max5.to_python('123456')
Traceback (most recent call last):
...
Invalid: Enter a value less than 5 characters long
>>> max5(accept_python=False).from_python('123456')
Traceback (most recent call last):
...
Invalid: Enter a value less than 5 characters long
>>> max5.to_python([1, 2, 3])
[1, 2, 3]
>>> max5.to_python([1, 2, 3, 4, 5, 6])
Traceback (most recent call last):
...
Invalid: Enter a value less than 5 characters long
>>> max5.to_python(5)
Traceback (most recent call last):
...
Invalid: Invalid value (value with length expected)
"""
__unpackargs__ = ('minLength',)
messages = dict(
tooShort=_('Enter a value less than %(minLength)i characters long'),
invalid=_('Invalid value (value with length expected)'))
def validate_python(self, value, state):
try:
if value and len(value.decode('utf8')) < self.minLength:
raise Invalid(
self.message('tooShort', state,
minLength=self.minLength), value, state)
else:
return None
except TypeError:
raise Invalid(
self.message('invalid', state), value, state)
class Utf8String(FancyValidator):
"""
Converts things to string, but treats empty things as the empty string.
Also takes a `max` and `min` argument, and the string length must fall
in that range.
Also you may give an `encoding` argument, which will encode any unicode
that is found. Lists and tuples are joined with `list_joiner`
(default ``', '``) in ``from_python``.
::
>>> String(min=2).to_python('a')
Traceback (most recent call last):
...
Invalid: Enter a value 2 characters long or more
>>> String(max=10).to_python('xxxxxxxxxxx')
Traceback (most recent call last):
...
Invalid: Enter a value not more than 10 characters long
>>> String().from_python(None)
''
>>> String().from_python([])
''
>>> String().to_python(None)
''
>>> String(min=3).to_python(None)
Traceback (most recent call last):
...
Invalid: Please enter a value
>>> String(min=1).to_python('')
Traceback (most recent call last):
...
Invalid: Please enter a value
"""
min = None
max = None
not_empty = None
encoding = None
list_joiner = ', '
messages = dict(
tooLong=_('Enter a value not more than %(max)i characters long'),
tooShort=_('Enter a value %(min)i characters long or more'))
def __initargs__(self, new_attrs):
if self.not_empty is None and self.min:
self.not_empty = True
def _to_python(self, value, state):
raise Invalid(
self.message('tooLong', state, max=self.max), value, state)
if value is None:
value = ''
elif not isinstance(value, basestring):
try:
value = str(value)
except UnicodeEncodeError:
value = unicode(value)
if self.encoding is not None and isinstance(value, unicode):
value = value.encode(self.encoding)
return value
def _from_python(self, value, state):
if value is None:
value = ''
elif not isinstance(value, basestring):
if isinstance(value, (list, tuple)):
value = self.list_joiner.join([
self._from_python(v, state) for v in value])
try:
value = str(value)
except UnicodeEncodeError:
value = unicode(value)
if self.encoding is not None and isinstance(value, unicode):
value = value.encode(self.encoding)
if self.strip:
value = value.strip()
return value
def validate_python(self, value, state):
if self.max is None and self.min is None:
return
if value is None:
value = ''
elif not isinstance(value, basestring):
try:
value = str(value)
except UnicodeEncodeError:
value = unicode(value)
if self.max is not None and len(value.decode('utf8')) > self.max:
raise Invalid(
self.message('tooLong', state, max=self.max), value, state)
if self.min is not None and len(value) < self.min:
raise Invalid(
self.message('tooShort', state, min=self.min), value, state)
def empty_value(self, value):
return ''
class URL(formencode.validators.URL):
url_re = re.compile(r'''
^(http|https)://
(?:[%:\w]*@)? # authenticator
(?P<domain>[a-z0-9][a-z0-9\-]{0,62}\.)* # (sub)domain - alpha followed by 62max chars (63 total)
(?P<tld>[a-z]{2,}) # TLD
(?::[0-9]+)? # port
# files/delims/etc
(?P<path>/[a-z0-9\-\._~:/\?#\[\]@!%\$&\'\(\)\*\+,;=]*)?
$
''', re.I | re.VERBOSE)
| {
"repo_name": "feilaoda/FlickBoard",
"path": "project/app/base/validator.py",
"copies": "1",
"size": "7398",
"license": "mit",
"hash": 5601747957358838000,
"line_mean": 32.0267857143,
"line_max": 104,
"alpha_frac": 0.5363611787,
"autogenerated": false,
"ratio": 4.1843891402714934,
"config_test": false,
"has_no_keywords": false,
"few_assignments": false,
"quality_score": 0.5220750318971493,
"avg_score": null,
"num_lines": null
} |
from formencode.validators import Invalid as InvalidForm
from tornado.web import authenticated
from amonone.web.apps.core.baseview import BaseView
from amonone.web.apps.alerts.models import alerts_model, alerts_group_model
from amonone.web.apps.core.models import server_model
from amonone.web.apps.settings.forms import ServerForm
class ServersBaseView(BaseView):
def initialize(self):
self.current_page = 'settings:servers'
super(ServersBaseView, self).initialize()
class ServersView(ServersBaseView):
@authenticated
def get(self):
errors = self.session.get('errors',None)
all_servers = server_model.get_all()
servers = []
if all_servers:
for server in all_servers.clone():
alert_group = server.get('alert_group', None)
server['alert_group'] = alerts_group_model.get_by_id(alert_group)
servers.append(server)
self.render('settings/servers/view.html',
servers=servers)
class ServersDeleteView(ServersBaseView):
@authenticated
def get(self, param=None):
server = server_model.get_by_id(param)
alerts_model.delete_server_alerts(param)
server_model.delete(param)
self.redirect(self.reverse_url('settings_servers'))
class ServersUpdateView(ServersBaseView):
@authenticated
def get(self, param=None):
errors = self.session.get('errors',None)
server = server_model.get_by_id(param)
groups = alerts_group_model.get_all()
self.delete_session_key('errors')
self.render('settings/servers/edit.html',
server=server,
groups=groups,
errors=errors)
@authenticated
def post(self, param=None):
self.check_xsrf_cookie()
form_data = {
"name": self.get_argument('name', ''),
"notes": self.get_argument('notes', ''),
"alert_group": self.get_argument('alert_group', ''),
}
try:
valid_data = ServerForm.to_python(form_data)
server_model.update(valid_data, param)
self.delete_session_key('errors')
self.delete_session_key('form_data')
self.redirect(self.reverse_url('settings_servers'))
except InvalidForm, e:
self.session['errors'] = e.unpack_errors()
self.session['form_data'] = form_data
self.redirect(self.reverse_url('update_server', param))
class ServersAddView(ServersBaseView):
@authenticated
def get(self):
errors = self.session.get('errors',None)
form_data = self.session.get('form_data',None)
groups = alerts_group_model.get_all()
self.delete_session_key('errors')
self.render('settings/servers/add.html',
groups=groups,
errors=errors,
form_data=form_data)
@authenticated
def post(self):
self.check_xsrf_cookie()
form_data = {
"name": self.get_argument('name', ''),
"notes": self.get_argument('notes', ''),
"alert_group": self.get_argument('alert_group', ''),
}
try:
valid_data = ServerForm.to_python(form_data)
server_model.add(valid_data['name'],
valid_data['notes'],
valid_data['alert_group'])
self.delete_session_key('errors')
self.delete_session_key('form_data')
self.redirect(self.reverse_url('settings_servers'))
except InvalidForm, e:
self.session['errors'] = e.unpack_errors()
self.session['form_data'] = form_data
self.redirect(self.reverse_url('settings_servers_add')) | {
"repo_name": "m2lan/amonone",
"path": "amonone/web/apps/settings/views/servers.py",
"copies": "5",
"size": "3224",
"license": "mit",
"hash": 6903149213229823000,
"line_mean": 23.8076923077,
"line_max": 75,
"alpha_frac": 0.7006823821,
"autogenerated": false,
"ratio": 3.0881226053639845,
"config_test": false,
"has_no_keywords": false,
"few_assignments": false,
"quality_score": 0.6288804987463984,
"avg_score": null,
"num_lines": null
} |
from formencode.validators import Invalid as InvalidForm
from tornado.web import authenticated
from amonone.web.apps.core.baseview import BaseView
from amonone.web.apps.auth.models import user_model
from amonone.web.apps.core.models import server_model
from amonone.web.apps.settings.forms import CreateUserForm
class BaseUsersView(BaseView):
def initialize(self):
self.current_page = 'settings:users'
super(BaseUsersView, self).initialize()
class UsersView(BaseUsersView):
@authenticated
def get(self):
users = user_model.get_all()
all_servers = server_model.get_all()
if all_servers:
all_servers = dict((str(record['_id']), record['name']) for record in all_servers)
self.render('/settings/users/view.html',
users=users,
all_servers=all_servers)
class DeleteUserView(BaseUsersView):
@authenticated
def get(self, id=None):
if self.current_user['type'] == 'admin':
user_model.delete(id)
self.redirect(self.reverse_url('settings_users'))
class EditUserView(BaseUsersView):
@authenticated
def get(self, id=None):
user = user_model.get(id)
all_servers = server_model.get_all()
errors = self.session.get('errors',None)
form_data = self.session.get('form_data',None)
self.delete_session_key('errors')
self.delete_session_key('form_data')
self.render('/settings/users/edit.html',
user=user,
all_servers=all_servers,
errors=errors,
form_data=form_data)
@authenticated
def post(self, id):
form_data = {
"servers": self.get_arguments('servers[]',None)
}
# Remove all other values if all in the list
if len(form_data['servers']) > 0:
form_data['servers'] = ['all'] if 'all' in form_data['servers'] else form_data['servers']
user_model.update(form_data, id)
self.redirect(self.reverse_url('settings_users'))
class UpdatePasswordUserView(BaseUsersView):
@authenticated
def post(self, id):
form_data = {
"password" : self.get_argument('password', None),
}
if len(form_data['password']) > 0:
user_model.update(form_data, id)
self.redirect(self.reverse_url('settings_users'))
class CreateUserView(BaseUsersView):
@authenticated
def get(self):
all_servers = server_model.get_all()
errors = self.session.get('errors',None)
form_data = self.session.get('form_data',None)
self.delete_session_key('errors')
self.delete_session_key('form_data')
self.render('settings/users/create.html',
all_servers=all_servers,
errors=errors,
form_data=form_data)
@authenticated
def post(self):
form_data = {
"username": self.get_argument('username', None),
"password" : self.get_argument('password', None),
"type": self.get_argument('type', None),
"servers": self.get_arguments('servers[]',None)
}
try:
CreateUserForm.to_python(form_data)
self.delete_session_key('errors')
self.delete_session_key('form_data')
user_model.create_user(form_data)
self.redirect(self.reverse_url('settings_users'))
except InvalidForm, e:
self.session['errors'] = e.unpack_errors()
self.session['form_data'] = form_data
self.redirect(self.reverse_url('settings_create_user')) | {
"repo_name": "m2lan/amonone",
"path": "amonone/web/apps/settings/views/users.py",
"copies": "5",
"size": "3161",
"license": "mit",
"hash": -6348052461937233000,
"line_mean": 24.9180327869,
"line_max": 92,
"alpha_frac": 0.6972477064,
"autogenerated": false,
"ratio": 3.0570599613152805,
"config_test": false,
"has_no_keywords": false,
"few_assignments": false,
"quality_score": 0.6254307667715281,
"avg_score": null,
"num_lines": null
} |
from formencode.validators import Invalid as InvalidForm
from tornado.web import authenticated
from amonone.web.apps.core.baseview import BaseView
from amonone.web.apps.settings.models import data_model
from amonone.web.apps.core.models import server_model
from amonone.utils.dates import utc_now_to_localtime, datestring_to_utc_datetime, datetime_to_unixtime
from amonone.web.apps.settings.forms import DataCleanupForm
class DataBaseView(BaseView):
def initialize(self):
self.current_page = 'settings:data'
super(DataBaseView, self).initialize()
class DataView(DataBaseView):
@authenticated
def get(self):
database_info = data_model.get_database_info()
server_data = data_model.get_server_collection_stats()
self.render('settings/data.html',
database_info=database_info,
server_data=server_data
)
class DataDeleteSystemCollectionView(DataBaseView):
@authenticated
def get(self, server_id=None):
server = server_model.get_by_id(server_id)
data_model.delete_system_collection(server)
self.redirect(self.reverse_url('settings_data'))
class DataDeleteProcessCollectionView(DataBaseView):
@authenticated
def get(self, server_id=None):
server = server_model.get_by_id(server_id)
data_model.delete_process_collection(server)
self.redirect(self.reverse_url('settings_data'))
class DataCleanupProcessView(DataBaseView):
@authenticated
def get(self, server_id=None):
errors = self.session.get('errors',None)
# Get the max date - utc, converted to localtime
max_date = utc_now_to_localtime()
server = server_model.get_by_id(server_id)
self.render('settings/data/process_cleanup.html',
server=server,
errors=errors,
max_date=max_date)
@authenticated
def post(self, server_id=None):
form_data = {
"server": server_id,
"date" : self.get_argument('date', None),
}
try:
DataCleanupForm.to_python(form_data)
self.delete_session_key('errors')
self.delete_session_key('form_data')
# Convert to unix utc
date = datestring_to_utc_datetime(form_data['date'])
date = datetime_to_unixtime(date)
server = server_model.get_by_id(form_data['server'])
data_model.cleanup_process_collection(server, date)
self.redirect(self.reverse_url('settings_data'))
except InvalidForm, e:
self.session['errors'] = e.unpack_errors()
self.session['form_data'] = form_data
self.redirect(self.reverse_url('cleanup_process' ,server_id))
class DataCleanupSystemView(DataBaseView):
@authenticated
def get(self, server_id=None):
errors = self.session.get('errors',None)
# Get the max date - utc, converted to localtime
max_date = utc_now_to_localtime()
server = server_model.get_by_id(server_id)
self.render('settings/data/system_cleanup.html',
server=server,
errors=errors,
max_date=max_date)
@authenticated
def post(self, server_id=None):
form_data = {
"server": server_id,
"date" : self.get_argument('date', None),
}
try:
DataCleanupForm.to_python(form_data)
self.delete_session_key('errors')
self.delete_session_key('form_data')
# Convert to unix utc
date = datestring_to_utc_datetime(form_data['date'])
date = datetime_to_unixtime(date)
server = server_model.get_by_id(form_data['server'])
data_model.cleanup_system_collection(server, date)
self.redirect(self.reverse_url('settings_data'))
except InvalidForm, e:
self.session['errors'] = e.unpack_errors()
self.session['form_data'] = form_data
self.redirect(self.reverse_url('cleanup_system', server_id)) | {
"repo_name": "outbounder/amonone",
"path": "amonone/web/apps/settings/views/data.py",
"copies": "5",
"size": "3592",
"license": "mit",
"hash": 8788766434757221000,
"line_mean": 25.2262773723,
"line_max": 102,
"alpha_frac": 0.7152004454,
"autogenerated": false,
"ratio": 3.099223468507334,
"config_test": false,
"has_no_keywords": false,
"few_assignments": false,
"quality_score": 0.6314423913907334,
"avg_score": null,
"num_lines": null
} |
from formencode.validators import Invalid as InvalidForm
from tornado.web import authenticated
from tornado import escape as tornado_escape
from amonone.web.apps.core.baseview import BaseView
from amonone.sms.models import sms_model, sms_recepient_model
from amonone.web.apps.settings.forms import SMSForm, SMSRecepientForm
from amonone.sms.sender import send_test_sms
class SMSBaseView(BaseView):
def initialize(self):
self.current_page = 'settings:sms'
super(SMSBaseView, self).initialize()
class SMSView(SMSBaseView):
@authenticated
def get(self, param=None):
details = sms_model.get()
recepients = sms_recepient_model.get_all()
self.render('settings/sms/sms.html', details=details,
recepients=recepients)
class SMSTestView(SMSBaseView):
@authenticated
def get(self, param=None):
recepients = sms_recepient_model.get_all()
self.render('settings/sms/test.html',
recepients=recepients)
@authenticated
def post(self):
post_data = tornado_escape.json_decode(self.request.body)
recepient_param = post_data.get('recepient')
recepient = sms_recepient_model.get_by_id(recepient_param)
response = send_test_sms(recepient=recepient['phone'])
class SMSUpdateView(SMSBaseView):
@authenticated
def get(self, param=None):
errors = self.session.get('errors',None)
form_data = self.session.get('form_data',None)
details = sms_model.get()
self.delete_session_key('errors')
self.delete_session_key('form_data')
self.render('settings/sms/update_sms_details.html',
details=details,
errors=errors,
form_data=form_data)
@authenticated
def post(self):
form_data = {
"account": self.get_argument('account', None),
"token" : self.get_argument('token', None),
"from_" : self.get_argument('from', None),
}
try:
SMSForm.to_python(form_data)
self.delete_session_key('errors')
self.delete_session_key('form_data')
sms_model.save(form_data)
self.redirect(self.reverse_url('settings_sms'))
except InvalidForm, e:
self.session['errors'] = e.unpack_errors()
self.session['form_data'] = form_data
self.redirect('/settings/sms/edit')
class SMSAddRecepient(SMSBaseView):
@authenticated
def get(self):
errors = self.session.get('errors',None)
form_data = self.session.get('form_data',None)
self.render('settings/sms/add_recepient.html',
errors=errors,
form_data=form_data)
@authenticated
def post(self):
form_data = {
"name": self.get_argument('name', None),
"phone" : self.get_argument('phone', None),
}
try:
SMSRecepientForm.to_python(form_data)
self.delete_session_key('errors')
self.delete_session_key('form_data')
sms_recepient_model.insert(form_data)
self.redirect(self.reverse_url('settings_sms'))
except InvalidForm, e:
self.session['errors'] = e.unpack_errors()
self.session['form_data'] = form_data
self.redirect(self.reverse_url('sms_add_recepient'))
class SMSEditRecepientView(SMSBaseView):
@authenticated
def get(self, recepient_id=None):
errors = self.session.get('errors',None)
form_data = self.session.get('form_data',None)
recepient = sms_recepient_model.get_by_id(recepient_id)
self.render('settings/sms/edit_recepient.html',
recepient=recepient,
errors=errors,
form_data=form_data)
@authenticated
def post(self, recepient_id):
form_data = {
"name": self.get_argument('name', None),
"phone" : self.get_argument('phone', None),
}
try:
SMSRecepientForm.to_python(form_data)
self.delete_session_key('errors')
self.delete_session_key('form_data')
sms_recepient_model.update(form_data, recepient_id)
self.redirect(self.reverse_url('settings_sms'))
except InvalidForm, e:
self.session['errors'] = e.unpack_errors()
self.session['form_data'] = form_data
self.redirect(self.reverse_url('sms_edit_recepient', recepient_id))
class SMSDeleteRecepientView(SMSBaseView):
@authenticated
def get(self, recepient_id=None):
sms_recepient_model.delete(recepient_id)
self.redirect(self.reverse_url('settings_sms')) | {
"repo_name": "Ju2ender/amonone",
"path": "amonone/web/apps/settings/views/sms.py",
"copies": "5",
"size": "4094",
"license": "mit",
"hash": 1483659119272334000,
"line_mean": 24.917721519,
"line_max": 70,
"alpha_frac": 0.7093307279,
"autogenerated": false,
"ratio": 2.790729379686435,
"config_test": false,
"has_no_keywords": false,
"few_assignments": false,
"quality_score": 0.6000060107586436,
"avg_score": null,
"num_lines": null
} |
from formencode.validators import StringBool
from formencode import Invalid
from tw2.core import Widget, Param, DisplayOnlyWidget, ValidationError
from tw2.forms import (CalendarDatePicker, CalendarDateTimePicker, TableForm, DataGrid,
SingleSelectField, MultipleSelectField, InputField, HiddenField,
TextField, FileField, CheckBox, PasswordField, TextArea)
from tw2.forms import Label as tw2Label
class Label(tw2Label):
def prepare(self):
self.text = str(self.value)
super(Label, self).prepare()
class SproxMethodPutHiddenField(HiddenField):
name = '_method'
def prepare(self):
self.value = 'PUT'
super(SproxMethodPutHiddenField, self).prepare()
class ContainerWidget(DisplayOnlyWidget):
template = "genshi:sprox.widgets.tw2widgets.templates.container"
controller = Param('controller', attribute=False, default=None)
css_class = "containerwidget"
id_suffix = 'container'
class TableLabelWidget(Widget):
template = "genshi:sprox.widgets.tw2widgets.templates.tableLabel"
controller = Param('controller', attribute=False, default=None)
identifier = Param('identifier', attribute=False)
class ModelLabelWidget(Widget):
template = "genshi:sprox.widgets.tw2widgets.templates.modelLabel"
controller = Param('controller', attribute=False, default=None)
identifier = Param('identifier', attribute=False)
class EntityLabelWidget(Widget):
template = "genshi:sprox.widgets.tw2widgets.templates.entityLabel"
controller = Param('controller', attribute=False, default=None)
entity = Param('entity', attribute=False)
css_class = "entitylabelwidget"
class RecordViewWidget(Widget):
template = "genshi:sprox.widgets.tw2widgets.templates.recordViewTable"
entity = Param('entity', attribute=False, default=None)
class RecordFieldWidget(Widget):
template = "genshi:sprox.widgets.tw2widgets.templates.recordField"
field_name = Param('field_name', attribute=False)
css_class = "recordfieldwidget"
class TableDefWidget(Widget):
template = "genshi:sprox.widgets.tw2widgets.templates.tableDef"
identifier = Param('identifier', attribute=False)
class EntityDefWidget(Widget):
template = "genshi:sprox.widgets.tw2widgets.templates.entityDef"
entity = Param('entity', attribute=False)
class TableWidget(Widget):
template = "genshi:sprox.widgets.tw2widgets.templates.table"
class SproxCalendarDatePicker(CalendarDatePicker):
date_format = '%Y-%m-%d'
class SproxTimePicker(CalendarDateTimePicker):
date_format = '%H:%M:%S'
class SproxCalendarDateTimePicker(CalendarDateTimePicker):
date_format = '%Y-%m-%d %H:%M:%S'
class SproxDataGrid(DataGrid):
template = "sprox.widgets.tw2widgets.templates.datagrid"
pks = Param('pks', attribute=False),
xml_fields = Param('xml_fields', attribute=False, default=['actions'])
value = []
class SproxCheckBox(CheckBox):
def prepare(self):
super(SproxCheckBox, self).prepare()
self.attrs['value'] = 'true'
class PropertySingleSelectField(SingleSelectField):
entity = Param('entity', attribute=False, default=None)
provider = Param('provider', attribute=False, default=None)
field_name = Param('field_name', attribute=False, default=None)
dropdown_field_names = Param('dropdown_field_names', attribute=False, default=None)
nullable = Param('nullable', attribute=False, default=False)
disabled = Param('disabled', attribute=False, default=False)
prompt_text = None
def prepare(self):
#This is required for ming
entity = self.__class__.entity
options = self.provider.get_dropdown_options(entity, self.field_name, self.dropdown_field_names)
self.options = [(str(k), str(v)) for k,v in options]
if self.nullable:
self.options.append(['', "-----------"])
if not self.value:
self.value = ''
self.value = str(self.value)
super(PropertySingleSelectField, self).prepare()
class PropertyMultipleSelectField(MultipleSelectField):
entity = Param('entity', attribute=False, default=None)
provider = Param('provider', attribute=False, default=None)
field_name = Param('field_name', attribute=False, default=None)
dropdown_field_names = Param('dropdown_field_names', attribute=False, default=None)
nullable = Param('nullable', attribute=False, default=False)
disabled = Param('disabled', attribute=False, default=False)
def _safe_validate(self, validator, value, state=None):
try:
value = validator.to_python(value, state=state)
validator.validate_python(value, state=state)
return value
except Invalid:
return Invalid
def _validate(self, value, state=None):
value = value or []
if not isinstance(value, (list, tuple)):
value = [value]
if self.validator:
value = [self._safe_validate(self.validator, v) for v in value]
self.value = [v for v in value if v is not Invalid]
return self.value
def prepare(self):
#This is required for ming
entity = self.__class__.entity
options = self.provider.get_dropdown_options(entity, self.field_name, self.dropdown_field_names)
self.options = [(str(k), str(v)) for k,v in options]
if not self.value:
self.value = []
self.value = [str(v) for v in self.value]
super(PropertyMultipleSelectField, self).prepare()
| {
"repo_name": "gjhiggins/sprox",
"path": "sprox/widgets/tw2widgets/widgets.py",
"copies": "1",
"size": "5546",
"license": "mit",
"hash": 4766875585835166000,
"line_mean": 37.5138888889,
"line_max": 104,
"alpha_frac": 0.6923909124,
"autogenerated": false,
"ratio": 3.875611460517121,
"config_test": false,
"has_no_keywords": false,
"few_assignments": false,
"quality_score": 1,
"avg_score": 0.004582506597512734,
"num_lines": 144
} |
from formencode.variabledecode import variable_encode
from allura.tests import decorators as td
from allura.tests import TestController
class TestUserProfile(TestController):
@td.with_user_project('test-admin')
def test_profile(self):
response = self.app.get('/u/test-admin/profile/')
assert '<h2 class="dark title">Test Admin' in response
assert 'OpenIDs' in response
response = self.app.get('/u/test-admin/profile/configuration')
assert 'Configure Dashboard' in response
@td.with_user_project('test-admin')
def test_profile_config(self):
# Not fully implemented, just do coverage
response = self.app.post('/u/test-admin/profile/update_configuration', params=variable_encode({
'layout_class': 'something', 'divs': [{'name': 'foo', 'content': [{'widget': 'lotsa/content'}]}],
'new_div': {'name': 'bar', 'new_widget': 'widg'}}))
def test_wrong_profile(self):
response = self.app.get('/u/no-such-user/profile/', status=404)
@td.with_user_project('test-admin')
@td.with_user_project('test-user')
def test_seclusion(self):
response = self.app.get('/u/test-admin/profile/')
assert 'Email Addresses' in response
self.app.get('/u/test-user', extra_environ=dict(
username='test-user'))
response = self.app.get('/u/test-user/profile/')
assert 'Email Addresses' not in response
@td.with_user_project('test-admin')
@td.with_wiki
def test_feed(self):
response = self.app.get('/u/test-admin/profile/feed')
assert 'Recent posts by Test Admin' in response
assert '[test:wiki] test-admin created page Home' in response
| {
"repo_name": "leotrubach/sourceforge-allura",
"path": "Allura/allura/tests/functional/test_user_profile.py",
"copies": "1",
"size": "1773",
"license": "apache-2.0",
"hash": 2588032493818614300,
"line_mean": 41.2142857143,
"line_max": 134,
"alpha_frac": 0.6288776086,
"autogenerated": false,
"ratio": 3.7643312101910826,
"config_test": true,
"has_no_keywords": false,
"few_assignments": false,
"quality_score": 0.976774456013394,
"avg_score": 0.02509285173142851,
"num_lines": 42
} |
from formexample.models import *
from django.shortcuts import render
from django.http import HttpResponseRedirect
def freeCropView(request):
if request.method == 'POST': # If the form has been submitted...
form = freeCrop(request.POST) # A form bound to the POST data
if form.is_valid(): # All validation rules pass
new_event = form.save()
return HttpResponseRedirect('/cicu-freecrop/?id='+str(new_event.id))
else:
if request.GET.get('id',None):
form = freeCrop(instance=testModel.objects.get(id=request.GET.get('id',None)))
else:
form = freeCrop()
return render(request, 'example/example.html', {
'form': form,
})
def fixedRatioView(request):
if request.method == 'POST': # If the form has been submitted...
form = fixedRatioCrop(request.POST) # A form bound to the POST data
if form.is_valid(): # All validation rules pass
new_event = form.save()
return HttpResponseRedirect('/cicu-fixedratio/?id='+str(new_event.id))
else:
if request.GET.get('id',None):
form = fixedRatioCrop(instance=testModel.objects.get(id=request.GET.get('id',None)))
else:
form = fixedRatioCrop()
return render(request, 'example/example.html', {
'form': form,
})
def warningSizeView(request):
if request.method == 'POST': # If the form has been submitted...
form = warningSizeCrop(request.POST) # A form bound to the POST data
if form.is_valid(): # All validation rules pass
new_event = form.save()
return HttpResponseRedirect('/cicu-warningsize/?id='+str(new_event.id))
else:
if request.GET.get('id',None):
form = warningSizeCrop(instance=testModel.objects.get(id=request.GET.get('id',None)))
else:
form = warningSizeCrop()
return render(request, 'example/example.html', {
'form': form,
})
| {
"repo_name": "DOOMer/clean-image-crop-uploader-v3",
"path": "example/formexample/views.py",
"copies": "1",
"size": "2000",
"license": "bsd-3-clause",
"hash": -4323749356261229000,
"line_mean": 36.037037037,
"line_max": 97,
"alpha_frac": 0.6165,
"autogenerated": false,
"ratio": 3.8314176245210727,
"config_test": false,
"has_no_keywords": false,
"few_assignments": false,
"quality_score": 0.4947917624521073,
"avg_score": null,
"num_lines": null
} |
from formica.s3 import temporary_bucket
import pytest
from .constants import STACK
@pytest.fixture
def bucket(mocker, boto_resource, boto_client):
return boto_resource.return_value.Bucket
STRING_BODY = "string"
# MD5 hash of body
STRING_KEY = "b45cffe084dd3d20d928bee85e7b0f21"
BINARY_BODY = "binary".encode()
BINARY_KEY = "9d7183f16acce70658f686ae7f1a4d20"
BUCKET_NAME = "formica-deploy-88dec80484e3155b2c8cf023b635fb31"
FILE_NAME = "testfile"
FILE_BODY = "file-body"
FILE_KEY = "de858a1b070b29a579e2d8861b53ad20"
def test_s3_bucket_context(mocker, bucket, uuid4, boto_client):
bucket.return_value.objects.all.return_value = [mocker.Mock(key=STRING_KEY), mocker.Mock(key=BINARY_KEY)]
boto_client.return_value.meta.region_name = "eu-central-1"
boto_client.return_value.get_caller_identity.return_value = {'Account': '1234'}
mock_open = mocker.mock_open(read_data=FILE_BODY.encode())
mocker.patch('formica.s3.open', mock_open)
with temporary_bucket(seed=STACK) as temp_bucket:
string_return = temp_bucket.add(STRING_BODY)
binary_return = temp_bucket.add(BINARY_BODY)
file_return = temp_bucket.add_file(FILE_NAME)
temp_bucket.upload()
bucket_name = temp_bucket.name
assert string_return == STRING_KEY
assert binary_return == BINARY_KEY
assert file_return == FILE_KEY
assert bucket_name == BUCKET_NAME
bucket.assert_called_once_with(BUCKET_NAME)
assert bucket.call_count == 1
assert mock_open.call_count == 2
location_parameters = {'CreateBucketConfiguration': dict(LocationConstraint='eu-central-1')}
calls = [mocker.call(Body=STRING_BODY.encode(), Key=STRING_KEY), mocker.call(Body=BINARY_BODY, Key=BINARY_KEY), mocker.call(Body=mock_open(), Key=FILE_KEY)]
bucket.return_value.create.assert_called_once_with(**location_parameters)
bucket.return_value.put_object.assert_has_calls(calls)
assert bucket.return_value.put_object.call_count == 3
bucket.return_value.delete_objects.assert_called_once_with(
Delete={'Objects': [{'Key': STRING_KEY}, {'Key': BINARY_KEY}]})
bucket.return_value.delete.assert_called_once_with()
def test_does_not_delete_objects_if_empty(bucket):
bucket.return_value.objects.all.return_value = []
with temporary_bucket(seed=STACK):
pass
bucket.return_value.delete_objects.assert_not_called()
def test_does_not_use_s3_api_when_planning(bucket):
bucket.return_value.objects.all.return_value = []
with temporary_bucket(seed=STACK) as temp_bucket:
temp_bucket.add(STRING_BODY)
temp_bucket.add(BINARY_BODY)
bucket.return_value.create.assert_not_called()
bucket.return_value.put_object.assert_not_called()
bucket.return_value.delete_objects.assert_not_called()
| {
"repo_name": "flomotlik/formica",
"path": "tests/unit/test_s3.py",
"copies": "1",
"size": "2780",
"license": "mit",
"hash": -8662619227889192000,
"line_mean": 37.6111111111,
"line_max": 160,
"alpha_frac": 0.721942446,
"autogenerated": false,
"ratio": 3.169897377423033,
"config_test": true,
"has_no_keywords": false,
"few_assignments": false,
"quality_score": 0.4391839823423033,
"avg_score": null,
"num_lines": null
} |
from formidable.forms import (
FormidableForm, fields
)
from formidable import constants
class DropdownConditionsTestCaseTestForm(FormidableForm):
checkbox_a = fields.BooleanField(
label='My checkbox',
accesses={'padawan': constants.EDITABLE,
'jedi': constants.EDITABLE,
'human': constants.EDITABLE,
'robot': constants.REQUIRED}
)
checkbox_ab = fields.BooleanField(
label='My checkbox 2',
accesses={'padawan': constants.EDITABLE,
'jedi': constants.EDITABLE,
'human': constants.EDITABLE,
'robot': constants.REQUIRED}
)
a = fields.CharField(
label='a',
accesses={'padawan': constants.EDITABLE,
'jedi': constants.EDITABLE,
'human': constants.REQUIRED,
'robot': constants.REQUIRED}
)
b = fields.CharField(
label='b',
accesses={'padawan': constants.EDITABLE,
'jedi': constants.EDITABLE,
'human': constants.READONLY,
'robot': constants.REQUIRED}
)
class DropdownConditionsTestCaseDropDownForm(FormidableForm):
main_dropdown = fields.ChoiceField(
choices=(
('ab', 'AB'),
('b', 'B'),
('no_condition', 'No_condition')
),
accesses={'padawan': constants.EDITABLE}
)
a = fields.CharField(
accesses={'padawan': constants.EDITABLE})
b = fields.CharField(
accesses={'padawan': constants.EDITABLE})
c = fields.CharField(
accesses={'padawan': constants.EDITABLE})
class ConditionTestCaseTestForm(FormidableForm):
checkbox = fields.BooleanField(
label='My checkbox',
accesses={'padawan': constants.EDITABLE,
'jedi': constants.EDITABLE,
'human': constants.EDITABLE,
'robot': constants.REQUIRED}
)
foo = fields.CharField(
label='Foo',
accesses={'padawan': constants.EDITABLE,
'jedi': constants.REQUIRED,
'human': constants.REQUIRED,
'robot': constants.REQUIRED}
)
bar = fields.CharField(
label='Bar',
accesses={'padawan': constants.EDITABLE,
'jedi': constants.REQUIRED,
'human': constants.READONLY,
'robot': constants.REQUIRED}
)
| {
"repo_name": "novafloss/django-formidable",
"path": "demo/tests/fixtures/test_conditions.py",
"copies": "1",
"size": "2470",
"license": "mit",
"hash": -3841909132110610000,
"line_mean": 31.5,
"line_max": 61,
"alpha_frac": 0.5546558704,
"autogenerated": false,
"ratio": 4.371681415929204,
"config_test": false,
"has_no_keywords": false,
"few_assignments": false,
"quality_score": 0.5426337286329204,
"avg_score": null,
"num_lines": null
} |
from .form import Form
from django.contrib.auth.models import User
from django.contrib.postgres.fields import JSONField
from django.core.exceptions import ValidationError
from django.db import models
import re
class FormSubmission(models.Model):
"""
Form Submission Database Model
A Form Submission instance is a particular version of a form that is
partially filled out by a user of the system. Form Submissions may
have statuses attached to them such as Draft or Submitted. A
submission is frozen in time to a particular version of the form so
that if a later version of a form is released, the version that was
started remains available.
Attributes:
* form - the specific form instance that the submission references
* state - the state field as specified by the "states" list below
* modified - last date modified
* owner - user submitting the form
* submission - serialized submission information
"""
states = (
(0, "draft"),
(1, "submitted"),
(2, "changes requested"),
(3, "approved"),
(4, "denied"),
)
form = models.ForeignKey(Form)
state = models.IntegerField(choices=states)
modified = models.DateField()
owner = models.ForeignKey(User, blank=True, null=True)
submission = JSONField()
@classmethod
def can_view(cls, user, form_submission_id):
form_submission = cls.objects.get(pk=form_submission_id)
if user == form_submission.owner:
return True
else:
return user.has_perm("constellation_forms.form_owned_by",
form_submission.form)
@classmethod
def can_approve(cls, user, form_submission_id):
form_submission = cls.objects.get(pk=form_submission_id)
return user.has_perm("constellation_forms.form_owned_by",
form_submission.form)
class Meta:
db_table = "form_submission"
ordering = ("-modified",)
def __str__(self):
"""<form name>: <modified date> <owner> <state>"""
return "{0}: {1} {2} {3}".format(self.form, self.modified, self.owner,
self.state)
def clean(self):
if len(self.form.elements) != len(self.submission):
raise ValidationError("Number of submission elements must match.")
for index, element in enumerate(self.form.elements):
sub_element = self.submission[index]
if ("required" in element and element["required"]) and (
sub_element is None and self.state > 0):
raise ValidationError("Required element blank.")
if "validator" in element and sub_element is not None:
regex = re.compile(element["validator"])
if not regex.match(sub_element):
raise ValidationError("Validator did not match entry.")
if "choices" in element and sub_element:
if ("other_choice" not in element or
not element["other_choice"]):
if (element["type"] == "dropdown"):
if sub_element not in element["choices"]:
raise ValidationError("Invalid choice.")
elif (element["type"] == "radio"):
if sub_element[0] not in element["choices"]:
raise ValidationError("Invalid choice.")
elif element["type"] == "checkbox":
for c in sub_element:
if c not in element["choices"]:
raise ValidationError("Invalid choice.")
| {
"repo_name": "ConstellationApps/Forms",
"path": "constellation_forms/models/formSubmission.py",
"copies": "1",
"size": "3719",
"license": "isc",
"hash": 6676341954146598000,
"line_mean": 38.9892473118,
"line_max": 78,
"alpha_frac": 0.5877924173,
"autogenerated": false,
"ratio": 4.7436224489795915,
"config_test": false,
"has_no_keywords": false,
"few_assignments": false,
"quality_score": 0.5831414866279592,
"avg_score": null,
"num_lines": null
} |
from form import Form
from wtforms.fields import (
Field,
IntegerField,
StringField,
SelectField,
)
from wtforms.validators import (
ValidationError,
StopValidation,
InputRequired,
EqualTo,
Length,
)
import models
from .. import baseForms
from .. import baseValidators
class RegisterForm(Form):
"""
Used in:
User.RegisterHandler
method=['POST']
Create a new user.
User.ProfileHandler
method=['PATCH']
Edit profile.
Additional params:
current_user models.User()
username_ignore models.User().username
"""
username = StringField('username', [
InputRequired(),
Length(max=20),
])
password = StringField('password', [
InputRequired(),
Length(min=8),
])
password2 = StringField('password2', [
InputRequired(),
EqualTo('password'),
])
# used in user.ProfileHandler
self_password = StringField('self_password')
def validate_self_password(form, field):
current_user = form.kwargs.get("current_user", None)
if current_user is None:
return
if not current_user.check_password(field.data):
_ = field.gettext
raise StopValidation(_("Invalid password."))
def validate_username(form, field):
if field.data is None:
return
if baseValidators.ignore_match('username_ignore', form, field):
return
_ = field.gettext
count = models.User.query\
.filter(models.User.username == field.data)\
.count()
if count != 0:
raise ValidationError(_('Already exists.'))
class LoginForm(Form):
"""
Used in:
User.LoginHandler
method=['POST']
Get auth token.
"""
username = StringField('username', [
InputRequired(),
Length(max=20),
])
password = StringField('password', [
InputRequired(),
])
def validate_username(form, field):
_ = field.gettext
try:
user = models.User.query\
.filter_by(username=form.username.data)\
.first()
assert user.check_password(form.password.data) is True
form.kwargs['user'] = user
except Exception:
raise ValidationError(_('Invalid username or password.'))
validate_password = validate_username
| {
"repo_name": "hrl/Protoend",
"path": "generator/template/api/User/forms.py",
"copies": "1",
"size": "2475",
"license": "mit",
"hash": 7110372259973493000,
"line_mean": 24,
"line_max": 71,
"alpha_frac": 0.5729292929,
"autogenerated": false,
"ratio": 4.608938547486034,
"config_test": false,
"has_no_keywords": false,
"few_assignments": false,
"quality_score": 0.5681867840386033,
"avg_score": null,
"num_lines": null
} |
from .form import (PointAnnotation, PointAnnotationType, IntervalAnnotation,
IntervalAnnotationType)
from .content import (OrthographyAnnotation, OrthographyAnnotationType,
TranscriptionAnnotation, TranscriptionAnnotationType,
NumericAnnotation, NumericAnnotationType,
GroupingAnnotation, GroupingAnnotationType,
MorphemeAnnotation, MorphemeAnnotationType)
class Tobi(OrthographyAnnotation, PointAnnotation):
def __init__(self, label, time):
OrthographyAnnotation.__init__(self, label)
PointAnnotation.__init__(self, time)
class TobiTier(OrthographyAnnotationType, PointAnnotationType):
annotation_class = Tobi
class Orthography(OrthographyAnnotation, IntervalAnnotation):
def __init__(self, label, begin, end):
OrthographyAnnotation.__init__(self, label)
IntervalAnnotation.__init__(self, begin, end)
class OrthographyTier(OrthographyAnnotationType, IntervalAnnotationType):
annotation_class = Orthography
class Morpheme(MorphemeAnnotation, IntervalAnnotation):
def __init__(self, morphemes, begin, end):
MorphemeAnnotation.__init__(self, morphemes)
IntervalAnnotation.__init__(self, begin, end)
class MorphemeTier(MorphemeAnnotationType, IntervalAnnotationType):
annotation_class = Morpheme
class Transcription(TranscriptionAnnotation, IntervalAnnotation):
def __init__(self, segments, begin, end, morpheme_breaks=None, stress=None, tone=None):
TranscriptionAnnotation.__init__(self, segments, morpheme_breaks, stress, tone)
IntervalAnnotation.__init__(self, begin, end)
class TranscriptionTier(TranscriptionAnnotationType, IntervalAnnotationType):
annotation_class = Transcription
class Segment(Orthography):
pass
class SegmentTier(IntervalAnnotationType, OrthographyAnnotationType):
annotation_class = Segment
class Grouping(IntervalAnnotation, GroupingAnnotation):
def __init__(self, begin, end):
IntervalAnnotation.__init__(self, begin, end)
class GroupingTier(GroupingAnnotationType, IntervalAnnotationType):
annotation_class = Grouping
def add(self, annotations, save=True):
for a in annotations:
if len(a) > 2:
label = a.pop(0)
if save or len(self._list) < 10:
# If save is False, only the first 10 annotations are saved
annotation = self.annotation_class(*a)
self._list.append(annotation)
class TextOrthography(OrthographyAnnotation, PointAnnotation):
def __init__(self, label, time):
OrthographyAnnotation.__init__(self, label)
PointAnnotation.__init__(self, time)
class TextOrthographyTier(OrthographyAnnotationType, PointAnnotationType):
annotation_class = TextOrthography
class TextMorpheme(MorphemeAnnotation, PointAnnotation):
def __init__(self, morphemes, time):
MorphemeAnnotation.__init__(self, morphemes)
PointAnnotation.__init__(self, time)
class TextMorphemeTier(MorphemeAnnotationType, PointAnnotationType):
annotation_class = TextMorpheme
class TextTranscription(TranscriptionAnnotation, PointAnnotation):
def __init__(self, segments, time, morpheme_breaks=None, stress=None, tone=None):
TranscriptionAnnotation.__init__(self, segments, morpheme_breaks, stress, tone)
PointAnnotation.__init__(self, time)
class TextTranscriptionTier(TranscriptionAnnotationType, PointAnnotationType):
annotation_class = TextTranscription
class BreakIndex(NumericAnnotation, PointAnnotation):
def __init__(self, value, time):
NumericAnnotation.__init__(self, value)
PointAnnotation.__init__(self, time)
class BreakIndexTier(NumericAnnotationType, PointAnnotationType):
annotation_class = BreakIndex
| {
"repo_name": "PhonologicalCorpusTools/PolyglotDB",
"path": "polyglotdb/io/types/parsing.py",
"copies": "4",
"size": "3870",
"license": "mit",
"hash": -7044705793791638000,
"line_mean": 32.9473684211,
"line_max": 91,
"alpha_frac": 0.7162790698,
"autogenerated": false,
"ratio": 4.073684210526316,
"config_test": false,
"has_no_keywords": false,
"few_assignments": false,
"quality_score": 1,
"avg_score": 0.00039670828878428263,
"num_lines": 114
} |
from formlayout import fedit
from StringIO import StringIO
class recommended_learning:
def __init__(self):
#initalize filenames
self.skills_db = './knowledge_base/skills.csv'
self.robot_features_db = './knowledge_base/robot_features.csv'
self.environment_features_db = './knowledge_base/environment_features.csv'
self.templates_db = './knowledge_base/templates.csv'
self.read_database()
datagroup = self.create_initial_datagroup()
result = fedit(datagroup, title="Recommended Learning YouBot ")
print result
self.edit_database(result[1])
self.edit_templates(result[3])
def edit_database(self, data):
if (data[0] != ''):
with open(self.skills_db, 'ab') as f:
print "Adding to skill database : ",data[0]
f.write(data[0])
f.close()
if (data[1] != ''):
if (data[2] == 0 ):
print "Adding to Robot Feature database : ",data[1]
with open(self.robot_features_db, 'ab') as f:
f.write(data[1])
f.close()
if (data[2] == 1 ):
print "Adding to Environemnt Feature database : ",data[1]
with open(self.environment_features_db, 'ab') as f:
f.write(data[1])
f.close()
def edit_templates(self, data):
print data
with open(self.templates_db, 'ab') as f:
f.write(self.skills[data[0]])
f.close()
with open(self.templates_db, 'a') as f:
for d in data[1:]:
if d != 0:
f.write(" " + self.robot_features[d])
f.write("\n")
f.close()
def read_database(self):
self.skills = []
self.robot_features = []
self.environment_features = []
self.templates = []
with open(self.skills_db, 'rb') as f:
for line in f:
self.skills.append(line.rstrip('\n'))
with open(self.robot_features_db, 'rb') as f:
for line in f:
self.robot_features.append(line.rstrip('\n'))
with open(self.environment_features_db, 'rb') as f:
for line in f:
self.environment_features.append(line.rstrip('\n'))
with open(self.templates_db, 'rb') as f:
for line in f:
self.templates.append(line.rstrip('\n'))
#appending none in database initial
self.robot_features = ['none']+self.robot_features
self.environment_features = ['none']+self.environment_features
def create_initial_datagroup(self):
learn_list = self.create_learning_datalist()
edit_list = self.create_edit_datalist()
show_list = self.create_show_datalist()
edit_template_list = self.create_edit_template_datalist()
return ((learn_list, "Learn", "Start Learning "),
(edit_list, "Edit","Edit Skill or features" ),
(show_list, "Show", "Display all the skill "),
(edit_template_list, "Add Template", "Add Template for each skills"))
def create_learning_datalist(self):
return [('Start Learning', False),
('Skill', [0]+[(i, s) for i, s in enumerate(self.skills)]),
('Name', '')]
def create_edit_template_datalist(self):
return [('Skill', [0]+[(i, s) for i, s in enumerate(self.skills)]),
('Robot Feature',[0]+[(i,f) for i , f in enumerate(self.robot_features)]),
('Robot Feature',[0]+[(i,f) for i , f in enumerate(self.robot_features)]),
('Robot Feature',[0]+[(i,f) for i , f in enumerate(self.robot_features)]),
('Robot Feature',[0]+[(i,f) for i , f in enumerate(self.robot_features)]),
('Robot Feature',[0]+[(i,f) for i , f in enumerate(self.robot_features)]),
('Robot Feature',[0]+[(i,f) for i , f in enumerate(self.robot_features)]),
('Robot Feature',[0]+[(i,f) for i , f in enumerate(self.robot_features)]),
('Robot Feature',[0]+[(i,f) for i , f in enumerate(self.robot_features)]),
('Robot Feature',[0]+[(i,f) for i , f in enumerate(self.robot_features)]),
('Robot Feature',[0]+[(i,f) for i , f in enumerate(self.robot_features)])]
def create_edit_datalist(self):
return [('Add Skill', ''),
('Add Feature', ''),
('Type of Feature', [0, "Robot Feature", "Environment Feature"])]
def create_show_datalist(self):
return [('Skills', '\n'.join(self.skills)),
('Robot Features', '\n'.join(self.robot_features)),
('Environment Features', '\n'.join(self.environment_features)),
('Templates', '\n'.join(self.templates))]
if __name__ == "__main__":
recommended_learning()
| {
"repo_name": "deebuls/RecommenderSystemInRobotics",
"path": "code/knowledge_base_creator/recommended_learning.py",
"copies": "1",
"size": "4956",
"license": "mit",
"hash": -8553862642907119000,
"line_mean": 42.8584070796,
"line_max": 90,
"alpha_frac": 0.5367231638,
"autogenerated": false,
"ratio": 3.806451612903226,
"config_test": false,
"has_no_keywords": false,
"few_assignments": false,
"quality_score": 0.4843174776703226,
"avg_score": null,
"num_lines": null
} |
from .form_output import *
from .singleton_form import is_singleton_form
from sympy import Pow, Mul,Number,Integer,log
import itertools
def minimised_exp_bases(expr):
'''Determines whether individual bases in a term can be broken down. \
Ex: 8^3 = 2^(3*3) = 2^9 = 512, where 2^9 has minimized expression
bases, and 8^3 does not. minimised_exp_bases requires
simplified_exp_bases(expr) to be true as a prerequisite.
Args:
expr: A standard sympy expression
Returns:
A tuple containing:
[0] - boolean result of the function
[1] - string describing result of the function
'''
result = simplified_exp_bases(expr)
if not result[0]:
return False, result[1]
bases = _exp_collect_bases(expr)
for i in bases:
if isinstance(i, (int,Number)):
n = 2
while (n < i):
if isinstance(log(i,n), (Integer, int)):
return False, NumBaseOutput.strout("SMALLER_BASE_EXISTS")
n += 1
return True, NumBaseOutput.strout("SMALLEST_BASE")
def simplified_exp_bases(expr):
'''Determines whether bases in an expression are simplified.
Current definition of "simplified": can two bases in the expression
be combined?
Args:
expr: A Standard Sympy expression
Returns:
A tuple containing:
[0] - boolean result of the function
[1] - String describing result of the function
'''
if isinstance(expr, Pow):
result = _exp_0_or_1(expr)
return not result[0], result[1]
elif is_singleton_form(expr)[0]:
return True, NumBaseOutput.strout('SINGLETON')
elif not isinstance(expr, Mul):
return False, NumBaseOutput.strout('MULTIPLE_TERMS')
for i in expr.args:
result = _exp_0_or_1(i)
if result[0]:
return False, result[1]
bases = _exp_collect_bases(expr)
for i,j in itertools.combinations(bases, 2):
if isinstance(log(i,j), Integer):
return False, NumBaseOutput.strout('NOT_SIMPLE_BASES')
elif isinstance(log(j,i), Integer):
return False, NumBaseOutput.strout('NOT_SIMPLE_BASES')
return True, NumBaseOutput.strout('SIMPLE_BASES')
def _exp_collect_bases(expr):
'''Collects all of the bases in a function.
Args:
expr: A standard sympy expression
Returns:
A tuple containing:
[0] - boolean result of the function
[1] - string describing the result
'''
bases = []
for i in expr.args:
if isinstance(i, Pow):
bases.append(i.args[0])
elif isinstance(i,Mul):
bases += _exp_collect_bases(i)
else:
bases.append(i)
return bases
def _exp_0_or_1(expr):
'''Determines whether a given expression is raised to 0 or 1, which is \
redundant algebraically.
Args:
expr: A standard Sympy expression
Returns:
A tuple containing:
[0] - boolean result of the function
[1] - string describing the result
'''
if not isinstance(expr, Pow):
return False, NumBaseOutput.strout('NOT_POW')
if expr.args[1] == 0:
return True, NumBaseOutput.strout('EXP_0')
elif expr.args[1] == 1:
return True, NumBaseOutput.strout('EXP_1')
return False, NumBaseOutput.strout("EXP_OK")
| {
"repo_name": "lemmalearning/sympy-form-analysis",
"path": "numerical_base_form.py",
"copies": "2",
"size": "3547",
"license": "bsd-3-clause",
"hash": -5770947104762320000,
"line_mean": 31.5412844037,
"line_max": 77,
"alpha_frac": 0.5847194813,
"autogenerated": false,
"ratio": 3.9542920847268674,
"config_test": false,
"has_no_keywords": false,
"few_assignments": false,
"quality_score": 1,
"avg_score": 0.006540757212305207,
"num_lines": 109
} |
from form_parser import form_parser
from filing import filing
# load up a form parser
fp = form_parser()
filingnumbers=(767585, 800502, 808218, 842576, 841933)
for filingnum in filingnumbers:
# read from cache if it's available; by default it won't save to cache
f1 = filing(filingnum, True)
#f1.download()
formtype = f1.get_form_type()
version = f1.version
print "Got form number %s - type=%s version=%s is_amended: %s" % (f1.filing_number, formtype, version, f1.is_amendment)
if f1.is_amendment:
print "Original filing is: %s" % (filing.headers['filing_amended'])
# If it's a F24 save it to cache; this won't overwrite if it's already there
if formtype=='F24':
f1.save_to_cache()
if not fp.is_allowed_form(formtype):
print "skipping form %s - %s isn't parseable" % (f1.filing_number, formtype)
continue
firstrow = fp.parse_form_line(f1.get_first_row(), version)
print "First row is: %s" % (firstrow)
schedule_e_lines = f1.get_rows('SE')
for e_line in schedule_e_lines:
firstrow = fp.parse_form_line(e_line, version)
print "\nGot sked E line: %s\n" % (firstrow) | {
"repo_name": "sunlightlabs/read_FEC",
"path": "fecreader/parsing/read_FEC_demo.py",
"copies": "1",
"size": "1209",
"license": "bsd-3-clause",
"hash": 1818428572899600600,
"line_mean": 32.6111111111,
"line_max": 123,
"alpha_frac": 0.6368899917,
"autogenerated": false,
"ratio": 3.1,
"config_test": false,
"has_no_keywords": false,
"few_assignments": false,
"quality_score": 0.42368899917,
"avg_score": null,
"num_lines": null
} |
from forms.forms import FormDetailSet
from forms.models import TurnexForm
import requests
from django.conf import settings
def get_forms():
return TurnexForm.objects.published().order_by('order')
def get_forms_config():
"""return the details of the form (should have a better name for this)"""
# I know, details is a very terrible name, need to rethink this properly
details = get_forms().values_list('details')
rows = [FormDetailSet(initial=detail) for detail in details]
return rows
def get_weather():
"""
The information comes with this format:
{
"coord": {
"lon": -0.13,
"lat": 51.51
},
"weather": [
{
"id": 500,
"main": "Rain",
"description": "light rain",
"icon": "10n"
}
],
"base": "cmc stations",
"main": {
"temp": 286.164,
"pressure": 1017.58,
"humidity": 96,
"temp_min": 286.164,
"temp_max": 286.164,
"sea_level": 1027.69,
"grnd_level": 1017.58
},
"wind": {
"speed": 3.61,
"deg": 165.001
},
"rain": {
"3h": 0.185
},
"clouds": {
"all": 80
},
"dt": 1446583128,
"sys": {
"message": 0.003,
"country": "GB",
"sunrise": 1446533902,
"sunset": 1446568141
},
"id": 2643743,
"name": "London",
"cod": 200
}
"""
data = requests.get(getattr(settings, 'WEATHER_API', ''))
return extract_info(data.json())
def extract_info(data):
weather = {}
icon = data['weather'][0]['icon']
temp = "{0:.2f}".format(data['main']['temp'] - 273.15)
# weather['url'] = 'http://openweathermap.org/img/w/{}.png'.format(icon)
weather['url'] = getattr(settings, 'WEATHER_API_URL', '{}').format(icon)
weather['temperature'] = temp
weather['humidity'] = data['main']['humidity']
return weather
| {
"repo_name": "mleger45/turnex",
"path": "msn/services.py",
"copies": "1",
"size": "1930",
"license": "mit",
"hash": -4515018830828206000,
"line_mean": 23.125,
"line_max": 77,
"alpha_frac": 0.5352331606,
"autogenerated": false,
"ratio": 3.356521739130435,
"config_test": false,
"has_no_keywords": false,
"few_assignments": false,
"quality_score": 0.43917548997304345,
"avg_score": null,
"num_lines": null
} |
from forms.haiku import HaikuForm
from forms.because import BecauseForm
from forms.acrostic import AcrosticForm
from forms.atoz import AtozForm
from forms.rhymingcouplet import RhymingCoupletForm
from forms.iambicpentameter import IambicPentameterForm
from forms.limerick import LimerickForm
from forms.alliterative import AlliterativeForm
from forms.ihate import IHateForm
from forms.roses import RosesForm
from forms.tanka import TankaForm
from forms.iambicpentameter_strict import IambicPentameterStrictForm
from forms.markov import MarkovForm
from forms.markov2 import Markov2Form
from forms.markovsounds import MarkovSoundsForm
from forms.all import AllForm
from forms.generate_dataset import GenerateDatasetForm
from forms.speedtest import SpeedtestForm
poem_forms = ["haiku","because","acrostic","atoz","couplet",
"iambicpentameter","limerick","alliterative", "ihate",
"roses","tanka","iambicpentameter_strict"]
tool_forms = ["all","generate_dataset","speedtest"]
other_forms = ["markov","markov2","markovsounds"]
def getForm(form):
## POEMS
if form==poem_forms[0]:
return HaikuForm()
elif form==poem_forms[1]:
return BecauseForm()
elif form==poem_forms[2]:
return AcrosticForm()
elif form==poem_forms[3]:
return AtozForm()
elif form==poem_forms[4]:
return RhymingCoupletForm()
elif form=="rhymingcouplet":
return RhymingCoupletForm()
elif form==poem_forms[5]:
return IambicPentameterForm()
elif form==poem_forms[6]:
return LimerickForm()
elif form==poem_forms[7]:
return AlliterativeForm()
elif form==poem_forms[8]:
return IHateForm()
elif form==poem_forms[9]:
return RosesForm()
elif form==poem_forms[10]:
return TankaForm()
elif form==poem_forms[11]:
return IambicPentameterStrictForm()
## TOOLS
elif form==tool_forms[0]:
return AllForm()
elif form==tool_forms[1]:
return GenerateDatasetForm()
elif form==tool_forms[2]:
return SpeedtestForm()
## OTHER THINGS
elif form==other_forms[0]:
return MarkovForm()
elif form==other_forms[1]:
return Markov2Form()
elif form==other_forms[2]:
return MarkovSoundsForm()
else:
return None
| {
"repo_name": "mlesicko/automaticpoetry",
"path": "handle_forms.py",
"copies": "1",
"size": "2308",
"license": "mit",
"hash": 6035794087332188000,
"line_mean": 31.0555555556,
"line_max": 68,
"alpha_frac": 0.7006065858,
"autogenerated": false,
"ratio": 3.320863309352518,
"config_test": false,
"has_no_keywords": false,
"few_assignments": false,
"quality_score": 0.4521469895152518,
"avg_score": null,
"num_lines": null
} |
from .forms import BirthdayWRandomNumberExtForm
from .models import BirthdayWRandomNumberExt
from django.core.urlresolvers import reverse_lazy
from django.http import HttpResponse
from django.views import generic
import csv
class AddView(generic.edit.CreateView):
model = BirthdayWRandomNumberExt
form_class = BirthdayWRandomNumberExtForm
template_name = 'user/edit.html'
success_url = reverse_lazy('br_users:index')
class DeleteView(generic.edit.DeleteView):
model = BirthdayWRandomNumberExt
form_class = BirthdayWRandomNumberExtForm
template_name = 'user/delete.html'
success_url = reverse_lazy('br_users:index')
class DetailView(generic.DetailView):
model = BirthdayWRandomNumberExt
template_name = 'user/detail.html'
class EditView(generic.edit.UpdateView):
model = BirthdayWRandomNumberExt
form_class = BirthdayWRandomNumberExtForm
template_name = 'user/edit.html'
class IndexView(generic.ListView):
template_name = 'user/index.html'
context_object_name = 'user_list'
def get_queryset(self):
return BirthdayWRandomNumberExt.objects.all()
def csv_view(request):
'''Generate csv data.
'''
response = HttpResponse(content_type='text/csv')
response['Content-Disposition'] = 'attachment; filename="birthday_w_random_number_ext.csv"'
writer = csv.writer(response)
writer.writerow(['Username', 'Birthday', 'Eligible', 'Random Number', 'BizzFuzz'])
for usr in BirthdayWRandomNumberExt.objects.all():
writer.writerow([usr.username, usr.birthday, usr.is_thirteen(),
usr.random_number_field, usr.bizz_fuzz()])
return response
| {
"repo_name": "luke-powers/django_exercise",
"path": "birthday_w_random_number_ext/views.py",
"copies": "1",
"size": "1674",
"license": "unlicense",
"hash": 5436038560735109000,
"line_mean": 28.8928571429,
"line_max": 95,
"alpha_frac": 0.7275985663,
"autogenerated": false,
"ratio": 3.631236442516269,
"config_test": false,
"has_no_keywords": false,
"few_assignments": false,
"quality_score": 0.9856878676714462,
"avg_score": 0.0003912664203612479,
"num_lines": 56
} |
from .forms import BlockForm
from django.core.urlresolvers import reverse
from django.forms.models import inlineformset_factory
from django.views.generic import (
ListView,
CreateView,
UpdateView,
)
from nested_formset import nestedformset_factory
from blocks import models
class BlockView(object):
model = models.Block
# don't conflict with django's block template context variable
context_object_name = "Block"
form_class = BlockForm
def get_success_url(self):
return reverse('blocks-list')
class ListBlocksView(ListView):
model = models.Block
class CreateBlockView(BlockView, CreateView):
pass
NestedBlockFormSet = nestedformset_factory(
models.Block,
models.Building,
nested_formset=inlineformset_factory(
models.Building,
models.Tenant,
fields='__all__'
)
)
BlockFormSet = inlineformset_factory(models.Block, models.Building, fields='__all__')
class EditBuildingsView(BlockView, UpdateView):
template_name = 'blocks/building_form.html'
form_class = NestedBlockFormSet
class EditBuildingsDynamicView(BlockView, UpdateView):
template_name = 'blocks/building_form_dynamic.html'
form_class = BlockFormSet
class EditBuildingsDynamicTabsView(BlockView, UpdateView):
template_name = 'blocks/building_form_dynamic_tabs.html'
form_class = BlockFormSet
class EditBuildingsDynamicTabsNestedView(BlockView, UpdateView):
template_name = 'blocks/building_form_dynamic_tabs_nested.html'
form_class = NestedBlockFormSet
| {
"repo_name": "mbertheau/jquery.django-formset-example",
"path": "blocks/views.py",
"copies": "1",
"size": "1550",
"license": "mit",
"hash": -1221237639473224700,
"line_mean": 23.21875,
"line_max": 85,
"alpha_frac": 0.7419354839,
"autogenerated": false,
"ratio": 3.9440203562340965,
"config_test": false,
"has_no_keywords": false,
"few_assignments": false,
"quality_score": 1,
"avg_score": 0.0001816860465116279,
"num_lines": 64
} |
from .forms import BlogPostForm
from .models import QandA, Answer, Page, ContentBlock
from django.contrib.auth.decorators import login_required
from django.contrib.auth.models import User
from django.http import HttpResponseRedirect
from django.shortcuts import render, get_object_or_404
from what_apps.utility.models import FixedObject
AUTO_TASK_CREATOR = FixedObject.objects.get(name="User__auto_task_creator")
@login_required
def edit_content_block(request, content_block_id=None):
cust = {'auto_resize': True,
'rows':15,
'cols':65,
}
if content_block_id:
blog_post = get_object_or_404(ContentBlock, id=content_block_id)
else:
blog_post = None
if request.POST:
form = BlogPostForm(request.POST, instance=blog_post)
if form.is_valid():
form.instance.creator = request.user
form.save()
else:
form.fields['content'].widget.attrs = cust
else:
form = BlogPostForm(instance=blog_post)
form.fields['content'].widget.attrs = cust
return render(request, 'forms/utility_form.html', locals())
def q_and_a_form(request, q_and_a_id):
if "completed" in request.GET:
pass
if request.user.is_authenticated():
applicant = request.user
else:
applicant = AUTO_TASK_CREATOR
q_and_a = QandA.objects.get(id=q_and_a_id)
questions = q_and_a.questions.order_by('id')
#TODO: Get this fucking thing using the regular forms API.
if request.POST:
incomplete = False #A flag to figure out whether the form is complete
completed_answers = {} #A dict that we'll populate in a bit here.
for question in questions: #We know that the various questions will be named "question_<n>" in request.POST, where n is the id of the question. Let's start making our own dict of the answers and deal with something being blank.
answer_text = request.POST['question_' + str(question.id)]
if answer_text:
question.answer_text = answer_text
else:
incomplete = True
if incomplete:
return render(request, 'main/q_and_a.html', locals())
else: #The form is not incomplete; let's save everything.
for question in questions:
Answer.objects.create(application = q_and_a, question = question, answer = question.answer_text, creator=applicant)
return render(request, 'cms/q_and_a_thankyou.html', locals())
return render(request, 'main/q_and_a.html', locals())
def blog(request, headline_slug=None):
if headline_slug: # If we have a headline slug, we know that we're looking for an individual blog post.
blog_post = get_object_or_404(ContentBlock, slug=headline_slug)
return render(request, 'cms/blog/blog_single_post.html', locals())
else: # If we don't have a headline slug, we're just headed to the front page of the bloody blog.
blog_blocks = ContentBlock.objects.filter(published=True, tags__name__in=["public","blog"]).order_by('-created').distinct()
return render(request,'cms/blog/blog_front_page.html', locals()) | {
"repo_name": "SlashRoot/WHAT",
"path": "what_apps/cms/views.py",
"copies": "1",
"size": "3295",
"license": "mit",
"hash": -3168314428516615000,
"line_mean": 38.2380952381,
"line_max": 248,
"alpha_frac": 0.6391502276,
"autogenerated": false,
"ratio": 3.904028436018957,
"config_test": false,
"has_no_keywords": false,
"few_assignments": false,
"quality_score": 0.5043178663618957,
"avg_score": null,
"num_lines": null
} |
from .forms import ContactForm
from django.shortcuts import render
from django.http import HttpResponseBadRequest, HttpResponse
from django.core.mail import mail_admins
def contact_view(request):
if request.method == "POST":
form = ContactForm(request.POST or None)
# Have Django validate the form for you
if form.is_valid():
# Imaginable form purpose. Post to admins.
message = """From: %s <%s>\r\nMessage:\r\n%s\r\n""" % (
form.cleaned_data["name"],
form.cleaned_data["company"],
form.cleaned_data["phone"],
form.cleaned_data["service"],
form.cleaned_data["budget"],
form.cleaned_data["message"],
form.cleaned_data["cc_myself"]
)
mail_admins('Contact form', message)
# Only executed with jQuery form request
if request.is_ajax():
return HttpResponse('OK')
else:
# render() a form with data (No AJAX)
# redirect to results ok, or similar may go here
pass
else:
if request.is_ajax():
# Prepare JSON for parsing
errors_dict = {}
if form.errors:
for error in form.errors:
e = form.errors[error]
errors_dict[error] = unicode(e)
return HttpResponseBadRequest(json.dumps(errors_dict))
else:
# render() form with errors (No AJAX)
pass
else:
form = ContactForm() # An unbound form
# This will display the blank form for a GET request
# or show the errors on a POSTed form that was invalid
if request.LANGUAGE_CODE == 'de':
return render(request, 'request_de.html', {'form': form})
else:
return render(request, 'request.html', {'form': form})
def faq_view(request):
return render(request, 'faq.html', {})
# To make rendering specific request languages (in our case English and German), we'll do the lazy and simple
# approach of rendering different html files
def support_index_view(request):
if request.LANGUAGE_CODE == 'de':
return render(request, 'support_index_de.html', {})
else:
return render(request, 'support_index.html', {})
def support_search(request):
return render(request, 'support_search.html', {})
def support_pricing(request):
return render(request, 'support_pricing.html', {})
| {
"repo_name": "neldom/qessera",
"path": "support/views.py",
"copies": "1",
"size": "2559",
"license": "mit",
"hash": 2794806888442130000,
"line_mean": 36.0869565217,
"line_max": 109,
"alpha_frac": 0.5740523642,
"autogenerated": false,
"ratio": 4.33728813559322,
"config_test": false,
"has_no_keywords": false,
"few_assignments": false,
"quality_score": 1,
"avg_score": 0.003029013405786166,
"num_lines": 69
} |
from .forms import CustomAuthenticationForm
from django.conf import settings
from django.conf.urls import patterns, include, url
from django.conf.urls.i18n import i18n_patterns
from django.contrib.staticfiles.urls import staticfiles_urlpatterns
from django.contrib.auth import views as auth_views
### Static url patterns; these urls aren't handled by navigation system
static_patterns = patterns('',
url(r'^admin/', include('bangoo.admin.urls')),
url(r'^media/', include('bangoo.media.admin.urls')),
url(r'^accounts/login/$', auth_views.login, {'authentication_form': CustomAuthenticationForm}, name='login'),
url(r'^accounts/logout/$', auth_views.logout_then_login, name='logout'),
url(r'^accounts/change_password/$', auth_views.password_change, {'post_change_redirect' : '/accounts/change_password/done/'}, name='change-password'),
url(r'^accounts/change_password/done/$', auth_views.password_change_done),
url(r'^accounts/reset_password/$', auth_views.password_reset, name='password-reset'),
url(r'^accounts/reset_password/done/$', auth_views.password_reset_done),
url(r'^accounts/reset_password/(?P<uidb36>[0-9A-Za-z]+)-(?P<token>.+)/$', auth_views.password_reset_confirm),
url(r'^accounts/reset_password/complete/$', auth_views.password_reset_complete),
)
### If we are in DEBUG mode, then handle static files also
if settings.DEBUG:
static_patterns += staticfiles_urlpatterns()
static_patterns += patterns('',
url(r'^uploads/(?P<path>.*)$', 'django.views.static.serve',
{'document_root': settings.MEDIA_ROOT})
)
### Any other urls handled by the menu system.
menu_patterns = i18n_patterns('',
url(r'', include('bangoo.navigation.urls')),
)
### Concatenate url configs
urlpatterns = static_patterns + menu_patterns
| {
"repo_name": "bangoocms/bangoo",
"path": "examplesite/examplesite/urls.py",
"copies": "3",
"size": "1801",
"license": "mit",
"hash": 945964436526820200,
"line_mean": 50.4571428571,
"line_max": 154,
"alpha_frac": 0.7129372571,
"autogenerated": false,
"ratio": 3.6531440162271807,
"config_test": false,
"has_no_keywords": true,
"few_assignments": false,
"quality_score": 1,
"avg_score": 0.006250648957470552,
"num_lines": 35
} |
from .forms import DrawAttentionAjaxForm, MessageForm
from .models import DrawAttention, TopLevelMessage, Acknowledgement, \
FileAttachedToMessage, TopLevelMessageManager
from django.contrib.auth.decorators import login_required
from django.contrib.auth.models import User
from django.contrib.contenttypes.models import ContentType
from django.db.models import Sum
from django.http import HttpResponse, HttpResponseRedirect, \
HttpResponseForbidden
from django.shortcuts import render, get_object_or_404
from django.utils import simplejson
from what_apps.do.models import Task, TaskResolution
from what_apps.people.models import UserProfile, GenericParty, Group
from what_apps.presence.models import AnchorTime, MediaURL
from what_apps.social.functions import get_messages_for_user
import datetime
import json
def draw_attention_ajax(request):
form = DrawAttentionAjaxForm(request.POST)
form.full_clean()
if form.is_valid():
app_name = form.cleaned_data['app']
object_type = form.cleaned_data['model']
object_id = form.cleaned_data['object_id']
Model=ContentType.objects.get(app_label=app_name, model=object_type.lower()).model_class()
object = Model.objects.get(id=object_id)
target = form.cleaned_data['share_with']
DrawAttention.objects.create(
creator = request.user,
target = target,
content_object = object,
)
object.save() #Cause any post-save hooks to fire.
alert_message = "You have alerted %s to %s." % (target, object)
response_dict = dict(success=True, alert=alert_message)
response_dict_json = json.dumps(response_dict)
return HttpResponse(response_dict_json)
else:
errors = []
for error in form.errors:
errors.append(error)
dumps = simplejson.dumps(errors)
return HttpResponse(dumps)
@login_required
def dashboard(request):
tasks = Task.objects.filter(ownership__owner=request.user, resolutions__isnull = True).reverse()[:5]
completed = TaskResolution.objects.filter(creator=request.user, type=2).reverse()[:10]
points_aggregate = Task.objects.filter(resolutions__creator=request.user, resolutions__type=2).aggregate(Sum('weight'))
points = points_aggregate['weight__sum']
anchors = AnchorTime.objects.filter(member=request.user)
count = get_messages_for_user(request.user)
inbox_messages = get_messages_for_user(request.user)[-5:]
try:
media = MediaURL.objects.get(pk=1)
except:
pass
unnecessary = True #Removes the login box without affecting the entire brown_and_bubble_driven template so that it looks more appealing in the dashboard
user_party = GenericParty.objects.get(party=request.user)
log_for_user = TopLevelMessage.objects.complete_log(party=user_party).order_by('-created')[:10]
return render(request, 'social/dashboard.html', locals())
def profile(request, username):
person = get_object_or_404(User, username = username)
completed = TaskResolution.objects.filter(creator=person, type=2).reverse()[:10]
return render(request, 'social/profile.html',locals())
def post_top_level_message(request, object_info):
app_name = object_info.split('__')[0]
model_name = object_info.split('__')[1]
object_id = object_info.split('__')[2]
Model = ContentType.objects.get(app_label=app_name, model=model_name.lower()).model_class()
object = Model.objects.get(id=object_id)
if request.POST['message']:
message = TopLevelMessage.objects.create(content_object = object, creator=request.user, message=request.POST['message'])
if request.FILES:
for filename, file_object in request.FILES.items():
FileAttachedToMessage.objects.create(message=message, creator=request.user, file=file_object)
return HttpResponseRedirect(object.get_absolute_url())
def acknowledge_notification(request, attention_id):
attention = DrawAttention.objects.get(id=attention_id)
attention.acknowledge()
#TODO: Maybe the pushy stuff?
return HttpResponse(json.dumps({'success': True}))
@login_required
def log(request, username=None, group_name=None):
if request.POST: #they are trying to post a log.
form = MessageForm(request.POST)
if form.is_valid():
message_kwargs = { #This will become the kwargs of our create method.
'user': request.user,
'message': form.cleaned_data['message']
}
if group_name: #They're trying to post to a group.
group = get_object_or_404(Group, name=group_name) #Let's make sure the group exists.
message_kwargs['group'] = group #Add the group to the message kwargs.
message = TopLevelMessage.objects.make_log(**message_kwargs)
if not message: #message will be False if the User is not a member of the group.
return HttpResponseForbidden()
else: #No POST.
form = MessageForm()
#Three scenarios: They specified a group, or a user, or neither. For neither, we give them the log landing page.
#TODO:
# if not username and not group_name:
# return render(request, 'social/log_landing.html', locals())
if group_name:
log_owner = get_object_or_404(Group, name=group_name)
if not request.user in log_owner.users().all():
return HttpResponseForbidden()
if username:
if username == request.user.username:
log_owner = User.objects.get(username=username)
else:
return HttpResponseForbidden()
log_party = GenericParty.objects.get(party=log_owner)
return render(request, 'social/log.html', locals())
def media_player(request):
return render(request, 'social/media_player.html', locals())
| {
"repo_name": "SlashRoot/WHAT",
"path": "what_apps/social/views.py",
"copies": "1",
"size": "6433",
"license": "mit",
"hash": -1268960824327955000,
"line_mean": 34.9441340782,
"line_max": 156,
"alpha_frac": 0.6269236748,
"autogenerated": false,
"ratio": 4.215596330275229,
"config_test": false,
"has_no_keywords": false,
"few_assignments": false,
"quality_score": 0.5342520005075229,
"avg_score": null,
"num_lines": null
} |
from ..forms import ExtensionForm
from ..database import db, Extension
from flask_login import login_required, current_app
from flask import Blueprint, render_template, redirect, url_for, flash, request
blueprint = Blueprint('extensions', __name__, url_prefix='/extensions')
@blueprint.route('/')
def index():
extensions = Extension.query.order_by(Extension.name)
page = request.args.get('page', 1, type=int)
per_page = current_app.config['EXTENSIONS_PER_PAGE']
pagination = extensions.paginate(page, per_page, error_out=False)
extensions = pagination.items
return render_template('extensions/index.html', extensions=extensions,
pagination=pagination)
@blueprint.route('/<extension_name>')
def show_extension(extension_name):
extension = Extension.query.filter_by(name=extension_name).first_or_404()
watchers = extension.watchers.count()
return render_template('extensions/extension.html', extension=extension,
watchers=watchers)
@blueprint.route('/new', methods=['GET', 'POST'])
@login_required
def add_extension():
form = ExtensionForm()
if form.validate_on_submit():
if Extension.query.filter_by(name=form.name.data).first() is None:
extension = Extension(name=form.name.data,
author=form.author.data,
description=form.description.data,
category=form.category.data,
github=form.github.data,
bitbucket=form.bitbucket.data,
docs=form.docs.data,
website=form.website.data,
approved=form.approved.data)
db.session.add(extension)
flash('New extension added successfully!', 'success')
return redirect(url_for('.show_extension',
extension_name=form.name.data))
flash('This extension already exists.', 'info')
return render_template('extensions/new.html', form=form)
@blueprint.route('/<extension_name>/edit', methods=['GET', 'POST'])
@login_required
def update_extension(extension_name):
form = ExtensionForm()
extension = Extension.query.filter_by(name=extension_name).first_or_404()
if form.validate_on_submit():
flash('Extension updated successfully!', 'success')
return redirect(url_for('.index'))
form.name.data = extension.name
form.author.data = extension.author
form.description.data = extension.description
form.category.data = extension.category
form.github.data = extension.github
form.bitbucket.data = extension.bitbucket
form.docs.data = extension.docs
form.website.data = extension.website
form.approved.data = extension.approved
return render_template('extensions/update.html', form=form)
@blueprint.route('/<extension_name>/watchers')
def show_watchers(extension_name):
extension = Extension.query.filter_by(name=extension_name).first_or_404()
page = request.args.get('page', 1, type=int)
per_page = current_app.config['WATCHERS_PER_PAGE']
pagination = extension.watchers.paginate(page, per_page, error_out=False)
watchers = pagination.items
return render_template('extensions/watchers.html', extension=extension,
pagination=pagination, watchers=watchers)
| {
"repo_name": "john-wei/flaskr",
"path": "package/views/extensions.py",
"copies": "1",
"size": "3473",
"license": "mit",
"hash": -6117145816885268000,
"line_mean": 42.4125,
"line_max": 79,
"alpha_frac": 0.6443996545,
"autogenerated": false,
"ratio": 4.256127450980392,
"config_test": false,
"has_no_keywords": false,
"few_assignments": false,
"quality_score": 1,
"avg_score": 0,
"num_lines": 80
} |
from .forms import FilterForm
from .helpers import (connect_n_parse, format_date, get_filters, remove_tags,
test_conditions, url_vars, word_wrap)
from filterss import app
from flask import (Blueprint, abort, make_response, redirect, render_template,
request, send_from_directory)
from urllib.parse import quote
site = Blueprint('site', __name__)
@app.route('/')
def index():
return render_template('form.html',
js='init',
title=app.config['TITLE'],
form=FilterForm())
@app.route('/filter', methods=('GET', 'POST'))
def filter():
form = FilterForm()
if form.validate_on_submit():
url_query = url_vars(get_filters(form))
return redirect('/info?{}'.format(url_query))
return render_template('form.html',
js='init',
title=app.config['TITLE'],
form=FilterForm())
@app.route('/info')
def info():
# load GET vars
values = get_filters(request)
url_vars_encoded = url_vars(values)
rss_url = '{}rss?{}'.format(request.url_root, url_vars_encoded)
edit_url = '{}edit?{}'.format(request.url_root, url_vars_encoded)
rss_url_encoded = quote(values['url'])
# load orginal RSS (xml)
try:
dom = connect_n_parse(values['url'])
except:
return redirect('/error?{}'.format(url_vars_encoded))
# get title
rss_title = remove_tags(dom.getElementsByTagName('title')[0].toxml())
# loop items
all_items = []
for item in dom.getElementsByTagName('item'):
# get title & link
title = item.getElementsByTagName('title')[0].toxml()
link = item.getElementsByTagName('link')[0].toxml()
date = item.getElementsByTagName('pubDate')[0].toxml()
title = remove_tags(title)
link = remove_tags(link)
date = remove_tags(date)
# test conditions
conditions = test_conditions(values, title, link)
# create item
item = {'title': title,
'title_wrap': word_wrap(title),
'url': link,
'date': format_date(date),
'css_class': '' if conditions else 'skip'}
all_items.append(item)
return render_template(
'info.html',
js='info',
title='#filterss {}'.format(rss_title),
url=values['url'],
rss_title=rss_title,
rss_url=rss_url,
rss_url_encoded=rss_url_encoded,
edit_url=edit_url,
all_items=all_items)
@app.route('/edit', methods=('GET', 'POST'))
def edit():
# load GET vars
values = get_filters(request)
values['rss_url'] = values['url']
# insert values into form
form = FilterForm()
for field in form:
if field.name in values.keys():
field.data = values[field.name]
# render the form with loaded data
return render_template('form.html',
js='init',
title=app.config['TITLE'],
form=form)
@app.route('/rss')
def rss():
# load GET vars
values = get_filters(request)
# load orginal RSS (xml)
try:
dom = connect_n_parse(values['url'])
except:
return abort(500)
# change title
title_node = dom.getElementsByTagName('title')[0]
rss_title = remove_tags(title_node.toxml())
title_node.firstChild.replaceWholeText('#filterss {}'.format(rss_title))
# change link
link_node = dom.getElementsByTagName('link')[0]
url_vars_encoded = url_vars(values)
link_node.firstChild.replaceWholeText('{}info?{}'.format(request.url_root,
url_vars_encoded))
# remove feedburner tags
channel = dom.getElementsByTagName('channel')
for n in channel[0].getElementsByTagName('feedburner:info'):
channel[0].removeChild(n)
for n in channel[0].getElementsByTagName('feedburner:feedFlare'):
channel[0].removeChild(n)
for n in channel[0].getElementsByTagName('atom10:link'):
channel[0].removeChild(n)
# loop items
for item in dom.getElementsByTagName('item'):
# get title & link
title = remove_tags(item.getElementsByTagName('title')[0].toxml())
link = remove_tags(item.getElementsByTagName('link')[0].toxml())
# test conditions
conditions = test_conditions(values, title, link)
# delete undesired nodes
if not conditions:
item.parentNode.removeChild(item)
# print RSS (xml)
filtered = dom.toxml()
response = make_response(filtered)
response.headers["Content-Type"] = "application/xml"
return response
@app.route('/robots.txt', methods=['GET'])
def robots():
return send_from_directory(app.static_folder, request.path[1:])
@app.route('/error')
def error():
url = str(request.args.get("url"))
return render_template('error.html', url=url)
@app.errorhandler(500)
def page_not_found(e):
return render_template('error.html'), 500
| {
"repo_name": "cuducos/filterss",
"path": "filterss/views.py",
"copies": "1",
"size": "5131",
"license": "mit",
"hash": 5887096396654332000,
"line_mean": 28.8313953488,
"line_max": 79,
"alpha_frac": 0.5864353927,
"autogenerated": false,
"ratio": 3.9469230769230768,
"config_test": false,
"has_no_keywords": false,
"few_assignments": false,
"quality_score": 0.5033358469623077,
"avg_score": null,
"num_lines": null
} |
from .forms import ForgotUsernameForm
from django.conf import settings
from django.core.urlresolvers import reverse
from django.contrib.auth.models import User
from django.http import HttpResponseRedirect
from django.shortcuts import render
from django.views.generic import View
class ForgotUsername(View):
form_class = ForgotUsernameForm
template_name = 'registration/forgot_username.html'
def get(self, request, *args, **kwargs):
form = self.form_class()
return render(request, self.template_name, {'form': form})
def post(self, request, *args, **kwargs):
form = self.form_class(request.POST)
if form.is_valid():
user = User.objects.filter(email=form.cleaned_data['email']).first()
if user:
context = {'username': user.username,
'login': request.build_absolute_uri(reverse('login'))}
form.send_mail('Your FireCARES Username',
'registration/forgot_username_email.txt',
context,
settings.DEFAULT_FROM_EMAIL,
user.email)
return HttpResponseRedirect(reverse('username_sent'))
return render(request, self.template_name, {'form': form})
| {
"repo_name": "garnertb/firecares",
"path": "firecares/firecares_core/views.py",
"copies": "1",
"size": "1312",
"license": "mit",
"hash": 2843902704960215600,
"line_mean": 41.3225806452,
"line_max": 81,
"alpha_frac": 0.6150914634,
"autogenerated": false,
"ratio": 4.493150684931507,
"config_test": false,
"has_no_keywords": false,
"few_assignments": false,
"quality_score": 1,
"avg_score": 0.0007916387407601674,
"num_lines": 31
} |
from forms import Form
from airy.core.exceptions import ValidationError
from airy.utils.encoding import StrAndUnicode
from airy.utils.safestring import mark_safe
from airy.utils.translation import ugettext as _
from fields import IntegerField, BooleanField
from widgets import Media, HiddenInput
from util import ErrorList
__all__ = ('BaseFormSet', 'all_valid')
# special field names
TOTAL_FORM_COUNT = 'TOTAL_FORMS'
INITIAL_FORM_COUNT = 'INITIAL_FORMS'
MAX_NUM_FORM_COUNT = 'MAX_NUM_FORMS'
ORDERING_FIELD_NAME = 'ORDER'
DELETION_FIELD_NAME = 'DELETE'
class ManagementForm(Form):
"""
``ManagementForm`` is used to keep track of how many form instances
are displayed on the page. If adding new forms via javascript, you should
increment the count field of this form as well.
"""
def __init__(self, *args, **kwargs):
self.base_fields[TOTAL_FORM_COUNT] = IntegerField(widget=HiddenInput)
self.base_fields[INITIAL_FORM_COUNT] = IntegerField(widget=HiddenInput)
self.base_fields[MAX_NUM_FORM_COUNT] = IntegerField(required=False, widget=HiddenInput)
super(ManagementForm, self).__init__(*args, **kwargs)
class BaseFormSet(StrAndUnicode):
"""
A collection of instances of the same Form class.
"""
def __init__(self, data=None, files=None, auto_id='id_%s', prefix=None,
initial=None, error_class=ErrorList):
self.is_bound = data is not None or files is not None
self.prefix = prefix or self.get_default_prefix()
self.auto_id = auto_id
self.data = data or {}
self.files = files or {}
self.initial = initial
self.error_class = error_class
self._errors = None
self._non_form_errors = None
# construct the forms in the formset
self._construct_forms()
def __unicode__(self):
return self.as_table()
def __iter__(self):
"""Yields the forms in the order they should be rendered"""
return iter(self.forms)
def __getitem__(self, index):
"""Returns the form at the given index, based on the rendering order"""
return list(self)[index]
def __len__(self):
return len(self.forms)
def _management_form(self):
"""Returns the ManagementForm instance for this FormSet."""
if self.is_bound:
form = ManagementForm(self.data, auto_id=self.auto_id, prefix=self.prefix)
if not form.is_valid():
raise ValidationError('ManagementForm data is missing or has been tampered with')
else:
form = ManagementForm(auto_id=self.auto_id, prefix=self.prefix, initial={
TOTAL_FORM_COUNT: self.total_form_count(),
INITIAL_FORM_COUNT: self.initial_form_count(),
MAX_NUM_FORM_COUNT: self.max_num
})
return form
management_form = property(_management_form)
def total_form_count(self):
"""Returns the total number of forms in this FormSet."""
if self.is_bound:
return self.management_form.cleaned_data[TOTAL_FORM_COUNT]
else:
initial_forms = self.initial_form_count()
total_forms = initial_forms + self.extra
# Allow all existing related objects/inlines to be displayed,
# but don't allow extra beyond max_num.
if initial_forms > self.max_num >= 0:
total_forms = initial_forms
elif total_forms > self.max_num >= 0:
total_forms = self.max_num
return total_forms
def initial_form_count(self):
"""Returns the number of forms that are required in this FormSet."""
if self.is_bound:
return self.management_form.cleaned_data[INITIAL_FORM_COUNT]
else:
# Use the length of the inital data if it's there, 0 otherwise.
initial_forms = self.initial and len(self.initial) or 0
if initial_forms > self.max_num >= 0:
initial_forms = self.max_num
return initial_forms
def _construct_forms(self):
# instantiate all the forms and put them in self.forms
self.forms = []
for i in xrange(self.total_form_count()):
self.forms.append(self._construct_form(i))
def _construct_form(self, i, **kwargs):
"""
Instantiates and returns the i-th form instance in a formset.
"""
defaults = {'auto_id': self.auto_id, 'prefix': self.add_prefix(i)}
if self.is_bound:
defaults['data'] = self.data
defaults['files'] = self.files
if self.initial:
try:
defaults['initial'] = self.initial[i]
except IndexError:
pass
# Allow extra forms to be empty.
if i >= self.initial_form_count():
defaults['empty_permitted'] = True
defaults.update(kwargs)
form = self.form(**defaults)
self.add_fields(form, i)
return form
def _get_initial_forms(self):
"""Return a list of all the initial forms in this formset."""
return self.forms[:self.initial_form_count()]
initial_forms = property(_get_initial_forms)
def _get_extra_forms(self):
"""Return a list of all the extra forms in this formset."""
return self.forms[self.initial_form_count():]
extra_forms = property(_get_extra_forms)
def _get_empty_form(self, **kwargs):
defaults = {
'auto_id': self.auto_id,
'prefix': self.add_prefix('__prefix__'),
'empty_permitted': True,
}
defaults.update(kwargs)
form = self.form(**defaults)
self.add_fields(form, None)
return form
empty_form = property(_get_empty_form)
# Maybe this should just go away?
def _get_cleaned_data(self):
"""
Returns a list of form.cleaned_data dicts for every form in self.forms.
"""
if not self.is_valid():
raise AttributeError("'%s' object has no attribute 'cleaned_data'" % self.__class__.__name__)
return [form.cleaned_data for form in self.forms]
cleaned_data = property(_get_cleaned_data)
def _get_deleted_forms(self):
"""
Returns a list of forms that have been marked for deletion. Raises an
AttributeError if deletion is not allowed.
"""
if not self.is_valid() or not self.can_delete:
raise AttributeError("'%s' object has no attribute 'deleted_forms'" % self.__class__.__name__)
# construct _deleted_form_indexes which is just a list of form indexes
# that have had their deletion widget set to True
if not hasattr(self, '_deleted_form_indexes'):
self._deleted_form_indexes = []
for i in range(0, self.total_form_count()):
form = self.forms[i]
# if this is an extra form and hasn't changed, don't consider it
if i >= self.initial_form_count() and not form.has_changed():
continue
if self._should_delete_form(form):
self._deleted_form_indexes.append(i)
return [self.forms[i] for i in self._deleted_form_indexes]
deleted_forms = property(_get_deleted_forms)
def _get_ordered_forms(self):
"""
Returns a list of form in the order specified by the incoming data.
Raises an AttributeError if ordering is not allowed.
"""
if not self.is_valid() or not self.can_order:
raise AttributeError("'%s' object has no attribute 'ordered_forms'" % self.__class__.__name__)
# Construct _ordering, which is a list of (form_index, order_field_value)
# tuples. After constructing this list, we'll sort it by order_field_value
# so we have a way to get to the form indexes in the order specified
# by the form data.
if not hasattr(self, '_ordering'):
self._ordering = []
for i in range(0, self.total_form_count()):
form = self.forms[i]
# if this is an extra form and hasn't changed, don't consider it
if i >= self.initial_form_count() and not form.has_changed():
continue
# don't add data marked for deletion to self.ordered_data
if self.can_delete and self._should_delete_form(form):
continue
self._ordering.append((i, form.cleaned_data[ORDERING_FIELD_NAME]))
# After we're done populating self._ordering, sort it.
# A sort function to order things numerically ascending, but
# None should be sorted below anything else. Allowing None as
# a comparison value makes it so we can leave ordering fields
# blank.
def compare_ordering_key(k):
if k[1] is None:
return (1, 0) # +infinity, larger than any number
return (0, k[1])
self._ordering.sort(key=compare_ordering_key)
# Return a list of form.cleaned_data dicts in the order spcified by
# the form data.
return [self.forms[i[0]] for i in self._ordering]
ordered_forms = property(_get_ordered_forms)
#@classmethod
def get_default_prefix(cls):
return 'form'
get_default_prefix = classmethod(get_default_prefix)
def non_form_errors(self):
"""
Returns an ErrorList of errors that aren't associated with a particular
form -- i.e., from formset.clean(). Returns an empty ErrorList if there
are none.
"""
if self._non_form_errors is not None:
return self._non_form_errors
return self.error_class()
def _get_errors(self):
"""
Returns a list of form.errors for every form in self.forms.
"""
if self._errors is None:
self.full_clean()
return self._errors
errors = property(_get_errors)
def _should_delete_form(self, form):
# The way we lookup the value of the deletion field here takes
# more code than we'd like, but the form's cleaned_data will
# not exist if the form is invalid.
field = form.fields[DELETION_FIELD_NAME]
raw_value = form._raw_value(DELETION_FIELD_NAME)
should_delete = field.clean(raw_value)
return should_delete
def is_valid(self):
"""
Returns True if form.errors is empty for every form in self.forms.
"""
if not self.is_bound:
return False
# We loop over every form.errors here rather than short circuiting on the
# first failure to make sure validation gets triggered for every form.
forms_valid = True
err = self.errors
for i in range(0, self.total_form_count()):
form = self.forms[i]
if self.can_delete:
if self._should_delete_form(form):
# This form is going to be deleted so any of its errors
# should not cause the entire formset to be invalid.
continue
if bool(self.errors[i]):
forms_valid = False
return forms_valid and not bool(self.non_form_errors())
def full_clean(self):
"""
Cleans all of self.data and populates self._errors.
"""
self._errors = []
if not self.is_bound: # Stop further processing.
return
for i in range(0, self.total_form_count()):
form = self.forms[i]
self._errors.append(form.errors)
# Give self.clean() a chance to do cross-form validation.
try:
self.clean()
except ValidationError, e:
self._non_form_errors = self.error_class(e.messages)
def clean(self):
"""
Hook for doing any extra formset-wide cleaning after Form.clean() has
been called on every form. Any ValidationError raised by this method
will not be associated with a particular form; it will be accesible
via formset.non_form_errors()
"""
pass
def add_fields(self, form, index):
"""A hook for adding extra fields on to each form instance."""
if self.can_order:
# Only pre-fill the ordering field for initial forms.
if index is not None and index < self.initial_form_count():
form.fields[ORDERING_FIELD_NAME] = IntegerField(label=_(u'Order'), initial=index+1, required=False)
else:
form.fields[ORDERING_FIELD_NAME] = IntegerField(label=_(u'Order'), required=False)
if self.can_delete:
form.fields[DELETION_FIELD_NAME] = BooleanField(label=_(u'Delete'), required=False)
def add_prefix(self, index):
return '%s-%s' % (self.prefix, index)
def is_multipart(self):
"""
Returns True if the formset needs to be multipart-encrypted, i.e. it
has FileInput. Otherwise, False.
"""
return self.forms and self.forms[0].is_multipart()
def _get_media(self):
# All the forms on a FormSet are the same, so you only need to
# interrogate the first form for media.
if self.forms:
return self.forms[0].media
else:
return Media()
media = property(_get_media)
def as_table(self):
"Returns this formset rendered as HTML <tr>s -- excluding the <table></table>."
# XXX: there is no semantic division between forms here, there
# probably should be. It might make sense to render each form as a
# table row with each field as a td.
forms = u' '.join([form.as_table() for form in self])
return mark_safe(u'\n'.join([unicode(self.management_form), forms]))
def as_p(self):
"Returns this formset rendered as HTML <p>s."
forms = u' '.join([form.as_p() for form in self])
return mark_safe(u'\n'.join([unicode(self.management_form), forms]))
def as_ul(self):
"Returns this formset rendered as HTML <li>s."
forms = u' '.join([form.as_ul() for form in self])
return mark_safe(u'\n'.join([unicode(self.management_form), forms]))
def formset_factory(form, formset=BaseFormSet, extra=1, can_order=False,
can_delete=False, max_num=None):
"""Return a FormSet for the given form class."""
attrs = {'form': form, 'extra': extra,
'can_order': can_order, 'can_delete': can_delete,
'max_num': max_num}
return type(form.__name__ + 'FormSet', (formset,), attrs)
def all_valid(formsets):
"""Returns true if every formset in formsets is valid."""
valid = True
for formset in formsets:
if not formset.is_valid():
valid = False
return valid
| {
"repo_name": "letolab/airy",
"path": "airy/forms/formsets.py",
"copies": "1",
"size": "14863",
"license": "bsd-2-clause",
"hash": 5294751454511147000,
"line_mean": 40.0580110497,
"line_max": 115,
"alpha_frac": 0.5988696764,
"autogenerated": false,
"ratio": 4.125173466555648,
"config_test": false,
"has_no_keywords": false,
"few_assignments": false,
"quality_score": 1,
"avg_score": 0.001149581501117667,
"num_lines": 362
} |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.