commit
stringlengths 40
40
| old_file
stringlengths 4
236
| new_file
stringlengths 4
236
| old_contents
stringlengths 1
3.26k
| new_contents
stringlengths 16
4.43k
| subject
stringlengths 16
624
| message
stringlengths 17
3.29k
| lang
stringclasses 5
values | license
stringclasses 13
values | repos
stringlengths 5
91.5k
|
|---|---|---|---|---|---|---|---|---|---|
3071684f73e736950023be9f47c93dd31c50be1c
|
send2trash/compat.py
|
send2trash/compat.py
|
# Copyright 2017 Virgil Dupras
# This software is licensed under the "BSD" License as described in the "LICENSE" file,
# which should be included with this package. The terms are also available at
# http://www.hardcoded.net/licenses/bsd_license
import sys
import os
PY3 = sys.version_info[0] >= 3
if PY3:
text_type = str
binary_type = bytes
environb = os.environb
else:
text_type = unicode
binary_type = str
environb = os.environ
|
# Copyright 2017 Virgil Dupras
# This software is licensed under the "BSD" License as described in the "LICENSE" file,
# which should be included with this package. The terms are also available at
# http://www.hardcoded.net/licenses/bsd_license
import sys
import os
PY3 = sys.version_info[0] >= 3
if PY3:
text_type = str
binary_type = bytes
if os.supports_bytes_environ:
# environb will be unset under Windows, but then again we're not supposed to use it.
environb = os.environb
else:
text_type = unicode
binary_type = str
environb = os.environ
|
Fix newly-introduced crash under Windows
|
Fix newly-introduced crash under Windows
ref #14
|
Python
|
bsd-3-clause
|
hsoft/send2trash
|
8a6002015cf873d3054bd20d8d287a3fe7be6b84
|
server.py
|
server.py
|
from tornado import ioloop, web, websocket
class EchoWebSocket(websocket.WebSocketHandler):
def open(self):
print("WebSocket opened")
def on_message(self, message):
self.write_message("You said: " + message)
def on_close(self):
print("WebSocket closed")
class MainHandler(web.RequestHandler):
def get(self):
print 'MainHandler get'
self.write('''<!DOCTYPE html>
<html>
<head>
<title></title>
</head>
<body>
<script type="text/javascript">
var ws = new WebSocket("ws://localhost:8888/_channel/");
ws.onopen = function() {
ws.send("Hello, world");
};
ws.onmessage = function (evt) {
alert(evt.data);
};
</script>
</body>
</html>''')
if __name__ == '__main__':
application = web.Application([
('/_channel/', EchoWebSocket),
('/', MainHandler),
])
application.listen(8888)
ioloop.IOLoop.instance().start()
|
from tornado import ioloop, web, websocket
class EchoWebSocket(websocket.WebSocketHandler):
def open(self):
print("WebSocket opened")
def on_message(self, message):
self.write_message("You said: " + message)
def on_close(self):
print("WebSocket closed")
SCRIPT = '''
<script type="text/javascript">
var ws = new WebSocket("ws://localhost:8888/_channel/");
ws.onopen = function() {
ws.send("Hello, world");
};
ws.onmessage = function (evt) {
alert(evt.data);
};
</script>
'''
class MainHandler(web.RequestHandler):
def get(self, path):
print self.request.path
with open('.' + self.request.path) as html_file:
for line in html_file:
if '</body>' not in line:
self.write(line)
else:
in_body, after_body = line.split('</body>')
self.write(in_body)
self.write(SCRIPT)
self.write('</body>')
self.write(after_body)
if __name__ == '__main__':
application = web.Application([
('/_channel/', EchoWebSocket),
('/(.+\.html)', MainHandler),
], template_path='.')
application.listen(8888)
ioloop.IOLoop.instance().start()
|
Load file or path now.
|
Load file or path now.
|
Python
|
bsd-3-clause
|
GrAndSE/livehtml,GrAndSE/livehtml
|
d00e84e1e41b43f5b680bb310b68444cd9bbcba5
|
fireplace/cards/tgt/shaman.py
|
fireplace/cards/tgt/shaman.py
|
from ..utils import *
##
# Hero Powers
# Lightning Jolt
class AT_050t:
play = Hit(TARGET, 2)
##
# Minions
# Tuskarr Totemic
class AT_046:
play = Summon(CONTROLLER, RandomTotem())
# Draenei Totemcarver
class AT_047:
play = Buff(SELF, "AT_047e") * Count(FRIENDLY_MINIONS + TOTEM)
# Thunder Bluff Valiant
class AT_049:
inspire = Buff(FRIENDLY_MINIONS + TOTEM, "AT_049e")
##
# Spells
# Healing Wave
class AT_048:
play = JOUST & Heal(TARGET, 7) | Heal(TARGET, 14)
# Elemental Destruction
class AT_051:
play = Hit(ALL_MINIONS, RandomNumber(4, 5))
# Ancestral Knowledge
class AT_053:
play = Draw(CONTROLLER) * 2
##
# Weapons
# Charged Hammer
class AT_050:
deathrattle = Summon(CONTROLLER, "AT_050t")
|
from ..utils import *
##
# Hero Powers
# Lightning Jolt
class AT_050t:
play = Hit(TARGET, 2)
##
# Minions
# Tuskarr Totemic
class AT_046:
play = Summon(CONTROLLER, RandomTotem())
# Draenei Totemcarver
class AT_047:
play = Buff(SELF, "AT_047e") * Count(FRIENDLY_MINIONS + TOTEM)
# Thunder Bluff Valiant
class AT_049:
inspire = Buff(FRIENDLY_MINIONS + TOTEM, "AT_049e")
# The Mistcaller
class AT_054:
# The Enchantment ID is correct
play = Buff(FRIENDLY + (IN_DECK | IN_HAND), "AT_045e")
##
# Spells
# Healing Wave
class AT_048:
play = JOUST & Heal(TARGET, 7) | Heal(TARGET, 14)
# Elemental Destruction
class AT_051:
play = Hit(ALL_MINIONS, RandomNumber(4, 5))
# Ancestral Knowledge
class AT_053:
play = Draw(CONTROLLER) * 2
##
# Weapons
# Charged Hammer
class AT_050:
deathrattle = Summon(CONTROLLER, "AT_050t")
|
Implement more TGT Shaman cards
|
Implement more TGT Shaman cards
|
Python
|
agpl-3.0
|
oftc-ftw/fireplace,amw2104/fireplace,amw2104/fireplace,smallnamespace/fireplace,jleclanche/fireplace,liujimj/fireplace,Ragowit/fireplace,Meerkov/fireplace,liujimj/fireplace,smallnamespace/fireplace,Meerkov/fireplace,beheh/fireplace,oftc-ftw/fireplace,Ragowit/fireplace,NightKev/fireplace
|
4021d27a7bd15a396b637beb57c10fc95936cb3f
|
snippet_parser/fr.py
|
snippet_parser/fr.py
|
#-*- encoding: utf-8 -*-
import base
class SnippetParser(base.SnippetParserBase):
def strip_template(self, template, normalize, collapse):
if template.name.matches('unité'):
return ' '.join(map(unicode, template.params[:2]))
elif self.is_citation_needed(template):
repl = [base.CITATION_NEEDED_MARKER]
if template.params:
repl = [template.params[0].value.strip_code()] + repl
return ''.join(repl)
return ''
|
#-*- encoding: utf-8 -*-
import base
def handle_date(template):
year = None
if len(template.params) >= 3:
try:
year = int(unicode(template.params[2]))
except ValueError:
pass
if isinstance(year, int):
# assume {{date|d|m|y|...}}
return ' '.join(map(unicode, template.params[:3]))
else:
# assume {{date|d m y|...}}
return unicode(template.params[0])
def handle_s(template):
ret = template.params[0]
if len(template.params) == 2:
ret += template.params[1]
if template.name.matches('-s'):
ret += ' av. J.-C'
return ret
class SnippetParser(base.SnippetParserBase):
def strip_template(self, template, normalize, collapse):
if template.name.matches('unité'):
return ' '.join(map(unicode, template.params[:2]))
elif template.name.matches('date'):
return handle_date(template)
elif template.name.matches('s') or template.name.matches('-s'):
return handle_s(template)
elif self.is_citation_needed(template):
repl = [base.CITATION_NEEDED_MARKER]
if template.params:
repl = [template.params[0].value.strip_code()] + repl
return ''.join(repl)
return ''
|
Implement a couple of other French templates.
|
Implement a couple of other French templates.
Still need to add tests for these.
|
Python
|
mit
|
Stryn/citationhunt,jhsoby/citationhunt,Stryn/citationhunt,Stryn/citationhunt,jhsoby/citationhunt,jhsoby/citationhunt,jhsoby/citationhunt,Stryn/citationhunt
|
77c114925fb45fa56c1da358ed47d8222775f99f
|
tailor/listeners/mainlistener.py
|
tailor/listeners/mainlistener.py
|
from tailor.swift.swiftlistener import SwiftListener
from tailor.utils.charformat import isUpperCamelCase
class MainListener(SwiftListener):
def enterClassName(self, ctx):
className = ctx.getText()
if not isUpperCamelCase(className):
print('Line', str(ctx.start.line) + ':', 'Class names should be in UpperCamelCase')
|
from tailor.swift.swiftlistener import SwiftListener
from tailor.utils.charformat import isUpperCamelCase
class MainListener(SwiftListener):
def enterClassName(self, ctx):
className = ctx.getText()
if not isUpperCamelCase(className):
print('Line', str(ctx.start.line) + ':', 'Class names should be in UpperCamelCase')
def enterEnumName(self, ctx):
pass
def enterEnumCaseName(self, ctx):
pass
def exitStructName(self, ctx):
pass
|
Add overrides for UpperCamelCase construct names
|
Add overrides for UpperCamelCase construct names
|
Python
|
mit
|
sleekbyte/tailor,sleekbyte/tailor,sleekbyte/tailor,sleekbyte/tailor,sleekbyte/tailor
|
f5e6ba58fa29bd89722c1e4bf4ec743eb1125f75
|
python/helpers/pycharm/django_manage_shell.py
|
python/helpers/pycharm/django_manage_shell.py
|
#!/usr/bin/env python
from fix_getpass import fixGetpass
import os
from django.core import management
import sys
try:
from runpy import run_module
except ImportError:
from runpy_compat import run_module
def run(working_dir):
sys.path.insert(0, working_dir)
manage_file = os.getenv('PYCHARM_DJANGO_MANAGE_MODULE')
if not manage_file:
manage_file = 'manage'
def execute_manager(settings_mod, argv = None):
management.setup_environ(settings_mod)
management.execute_manager = execute_manager
def execute_from_command_line(argv=None):
pass
management.execute_from_command_line = execute_from_command_line
fixGetpass()
run_module(manage_file, None, '__main__', True)
|
#!/usr/bin/env python
from fix_getpass import fixGetpass
import os
from django.core import management
import sys
try:
from runpy import run_module
except ImportError:
from runpy_compat import run_module
def run(working_dir):
sys.path.insert(0, working_dir)
manage_file = os.getenv('PYCHARM_DJANGO_MANAGE_MODULE')
if not manage_file:
manage_file = 'manage'
def execute_manager(settings_mod, argv = None):
management.setup_environ(settings_mod)
management.execute_manager = execute_manager
def execute_from_command_line(argv=None):
pass
management.execute_from_command_line = execute_from_command_line
fixGetpass()
try:
#import settings to prevent circular dependencies later on import django.db
from django.conf import settings
apps=settings.INSTALLED_APPS
# From django.core.management.shell
# XXX: (Temporary) workaround for ticket #1796: force early loading of all
# models from installed apps.
from django.db.models.loading import get_models
get_models()
except:
pass
run_module(manage_file, None, '__main__', True)
|
Fix circular import problem in Django console (PY-9030).
|
Fix circular import problem in Django console (PY-9030).
|
Python
|
apache-2.0
|
retomerz/intellij-community,adedayo/intellij-community,muntasirsyed/intellij-community,samthor/intellij-community,michaelgallacher/intellij-community,SerCeMan/intellij-community,apixandru/intellij-community,lucafavatella/intellij-community,wreckJ/intellij-community,caot/intellij-community,signed/intellij-community,hurricup/intellij-community,ivan-fedorov/intellij-community,retomerz/intellij-community,pwoodworth/intellij-community,FHannes/intellij-community,slisson/intellij-community,semonte/intellij-community,diorcety/intellij-community,muntasirsyed/intellij-community,michaelgallacher/intellij-community,gnuhub/intellij-community,MichaelNedzelsky/intellij-community,orekyuu/intellij-community,caot/intellij-community,adedayo/intellij-community,FHannes/intellij-community,vladmm/intellij-community,samthor/intellij-community,orekyuu/intellij-community,vladmm/intellij-community,vvv1559/intellij-community,muntasirsyed/intellij-community,hurricup/intellij-community,SerCeMan/intellij-community,youdonghai/intellij-community,amith01994/intellij-community,samthor/intellij-community,dslomov/intellij-community,ftomassetti/intellij-community,ryano144/intellij-community,suncycheng/intellij-community,ftomassetti/intellij-community,michaelgallacher/intellij-community,izonder/intellij-community,salguarnieri/intellij-community,hurricup/intellij-community,xfournet/intellij-community,TangHao1987/intellij-community,caot/intellij-community,Lekanich/intellij-community,blademainer/intellij-community,vvv1559/intellij-community,nicolargo/intellij-community,diorcety/intellij-community,ThiagoGarciaAlves/intellij-community,blademainer/intellij-community,hurricup/intellij-community,blademainer/intellij-community,salguarnieri/intellij-community,holmes/intellij-community,fnouama/intellij-community,slisson/intellij-community,FHannes/intellij-community,kool79/intellij-community,FHannes/intellij-community,MER-GROUP/intellij-community,clumsy/intellij-community,ibinti/intellij-community,fitermay/intellij-community,allotria/intellij-community,wreckJ/intellij-community,idea4bsd/idea4bsd,petteyg/intellij-community,pwoodworth/intellij-community,alphafoobar/intellij-community,tmpgit/intellij-community,petteyg/intellij-community,MER-GROUP/intellij-community,dslomov/intellij-community,ol-loginov/intellij-community,apixandru/intellij-community,Distrotech/intellij-community,fengbaicanhe/intellij-community,apixandru/intellij-community,jagguli/intellij-community,alphafoobar/intellij-community,wreckJ/intellij-community,MER-GROUP/intellij-community,Distrotech/intellij-community,ol-loginov/intellij-community,orekyuu/intellij-community,adedayo/intellij-community,ahb0327/intellij-community,ol-loginov/intellij-community,ibinti/intellij-community,allotria/intellij-community,robovm/robovm-studio,kdwink/intellij-community,orekyuu/intellij-community,salguarnieri/intellij-community,ivan-fedorov/intellij-community,apixandru/intellij-community,ahb0327/intellij-community,nicolargo/intellij-community,pwoodworth/intellij-community,SerCeMan/intellij-community,asedunov/intellij-community,wreckJ/intellij-community,caot/intellij-community,michaelgallacher/intellij-community,supersven/intellij-community,fnouama/intellij-community,ol-loginov/intellij-community,samthor/intellij-community,wreckJ/intellij-community,SerCeMan/intellij-community,ThiagoGarciaAlves/intellij-community,MER-GROUP/intellij-community,dslomov/intellij-community,Lekanich/intellij-community,Lekanich/intellij-community,ahb0327/intellij-community,FHannes/intellij-community,orekyuu/intellij-community,xfournet/intellij-community,ibinti/intellij-community,fnouama/intellij-community,idea4bsd/idea4bsd,kool79/intellij-community,robovm/robovm-studio,clumsy/intellij-community,Lekanich/intellij-community,suncycheng/intellij-community,youdonghai/intellij-community,robovm/robovm-studio,muntasirsyed/intellij-community,salguarnieri/intellij-community,kdwink/intellij-community,robovm/robovm-studio,youdonghai/intellij-community,ibinti/intellij-community,jagguli/intellij-community,holmes/intellij-community,lucafavatella/intellij-community,mglukhikh/intellij-community,fnouama/intellij-community,TangHao1987/intellij-community,kdwink/intellij-community,ryano144/intellij-community,ivan-fedorov/intellij-community,pwoodworth/intellij-community,jagguli/intellij-community,pwoodworth/intellij-community,izonder/intellij-community,nicolargo/intellij-community,asedunov/intellij-community,tmpgit/intellij-community,idea4bsd/idea4bsd,caot/intellij-community,fitermay/intellij-community,holmes/intellij-community,TangHao1987/intellij-community,idea4bsd/idea4bsd,tmpgit/intellij-community,pwoodworth/intellij-community,asedunov/intellij-community,youdonghai/intellij-community,tmpgit/intellij-community,pwoodworth/intellij-community,mglukhikh/intellij-community,dslomov/intellij-community,retomerz/intellij-community,ivan-fedorov/intellij-community,suncycheng/intellij-community,fengbaicanhe/intellij-community,caot/intellij-community,blademainer/intellij-community,slisson/intellij-community,diorcety/intellij-community,holmes/intellij-community,muntasirsyed/intellij-community,MichaelNedzelsky/intellij-community,retomerz/intellij-community,semonte/intellij-community,ryano144/intellij-community,ftomassetti/intellij-community,slisson/intellij-community,salguarnieri/intellij-community,fnouama/intellij-community,TangHao1987/intellij-community,idea4bsd/idea4bsd,tmpgit/intellij-community,da1z/intellij-community,lucafavatella/intellij-community,samthor/intellij-community,mglukhikh/intellij-community,vladmm/intellij-community,signed/intellij-community,da1z/intellij-community,izonder/intellij-community,clumsy/intellij-community,petteyg/intellij-community,gnuhub/intellij-community,caot/intellij-community,asedunov/intellij-community,orekyuu/intellij-community,fengbaicanhe/intellij-community,vladmm/intellij-community,diorcety/intellij-community,Distrotech/intellij-community,MichaelNedzelsky/intellij-community,signed/intellij-community,fitermay/intellij-community,akosyakov/intellij-community,ahb0327/intellij-community,jagguli/intellij-community,idea4bsd/idea4bsd,ahb0327/intellij-community,suncycheng/intellij-community,amith01994/intellij-community,akosyakov/intellij-community,wreckJ/intellij-community,da1z/intellij-community,ol-loginov/intellij-community,akosyakov/intellij-community,Lekanich/intellij-community,akosyakov/intellij-community,youdonghai/intellij-community,MichaelNedzelsky/intellij-community,caot/intellij-community,retomerz/intellij-community,idea4bsd/idea4bsd,hurricup/intellij-community,alphafoobar/intellij-community,SerCeMan/intellij-community,diorcety/intellij-community,gnuhub/intellij-community,salguarnieri/intellij-community,kdwink/intellij-community,slisson/intellij-community,orekyuu/intellij-community,ol-loginov/intellij-community,caot/intellij-community,alphafoobar/intellij-community,ahb0327/intellij-community,wreckJ/intellij-community,gnuhub/intellij-community,mglukhikh/intellij-community,MER-GROUP/intellij-community,izonder/intellij-community,alphafoobar/intellij-community,salguarnieri/intellij-community,kool79/intellij-community,fnouama/intellij-community,wreckJ/intellij-community,hurricup/intellij-community,retomerz/intellij-community,blademainer/intellij-community,akosyakov/intellij-community,semonte/intellij-community,fengbaicanhe/intellij-community,mglukhikh/intellij-community,michaelgallacher/intellij-community,ol-loginov/intellij-community,fengbaicanhe/intellij-community,ivan-fedorov/intellij-community,diorcety/intellij-community,kool79/intellij-community,muntasirsyed/intellij-community,kool79/intellij-community,vvv1559/intellij-community,akosyakov/intellij-community,ftomassetti/intellij-community,slisson/intellij-community,kool79/intellij-community,ibinti/intellij-community,clumsy/intellij-community,idea4bsd/idea4bsd,fitermay/intellij-community,vladmm/intellij-community,diorcety/intellij-community,pwoodworth/intellij-community,FHannes/intellij-community,muntasirsyed/intellij-community,izonder/intellij-community,adedayo/intellij-community,Lekanich/intellij-community,vvv1559/intellij-community,xfournet/intellij-community,xfournet/intellij-community,ryano144/intellij-community,hurricup/intellij-community,izonder/intellij-community,da1z/intellij-community,mglukhikh/intellij-community,fitermay/intellij-community,jagguli/intellij-community,kool79/intellij-community,blademainer/intellij-community,nicolargo/intellij-community,ahb0327/intellij-community,gnuhub/intellij-community,alphafoobar/intellij-community,kdwink/intellij-community,robovm/robovm-studio,ryano144/intellij-community,allotria/intellij-community,suncycheng/intellij-community,SerCeMan/intellij-community,mglukhikh/intellij-community,caot/intellij-community,da1z/intellij-community,nicolargo/intellij-community,idea4bsd/idea4bsd,vvv1559/intellij-community,da1z/intellij-community,blademainer/intellij-community,fengbaicanhe/intellij-community,MichaelNedzelsky/intellij-community,semonte/intellij-community,allotria/intellij-community,petteyg/intellij-community,MER-GROUP/intellij-community,ibinti/intellij-community,ibinti/intellij-community,fitermay/intellij-community,hurricup/intellij-community,fengbaicanhe/intellij-community,SerCeMan/intellij-community,izonder/intellij-community,amith01994/intellij-community,hurricup/intellij-community,ol-loginov/intellij-community,MichaelNedzelsky/intellij-community,SerCeMan/intellij-community,semonte/intellij-community,michaelgallacher/intellij-community,nicolargo/intellij-community,robovm/robovm-studio,lucafavatella/intellij-community,ThiagoGarciaAlves/intellij-community,Lekanich/intellij-community,muntasirsyed/intellij-community,fitermay/intellij-community,FHannes/intellij-community,Lekanich/intellij-community,xfournet/intellij-community,supersven/intellij-community,suncycheng/intellij-community,asedunov/intellij-community,ThiagoGarciaAlves/intellij-community,MER-GROUP/intellij-community,samthor/intellij-community,izonder/intellij-community,petteyg/intellij-community,adedayo/intellij-community,ibinti/intellij-community,gnuhub/intellij-community,clumsy/intellij-community,ibinti/intellij-community,ahb0327/intellij-community,suncycheng/intellij-community,TangHao1987/intellij-community,holmes/intellij-community,salguarnieri/intellij-community,TangHao1987/intellij-community,vladmm/intellij-community,asedunov/intellij-community,ivan-fedorov/intellij-community,fitermay/intellij-community,muntasirsyed/intellij-community,amith01994/intellij-community,amith01994/intellij-community,diorcety/intellij-community,da1z/intellij-community,pwoodworth/intellij-community,wreckJ/intellij-community,vladmm/intellij-community,jagguli/intellij-community,xfournet/intellij-community,asedunov/intellij-community,apixandru/intellij-community,pwoodworth/intellij-community,dslomov/intellij-community,fitermay/intellij-community,apixandru/intellij-community,ftomassetti/intellij-community,robovm/robovm-studio,TangHao1987/intellij-community,clumsy/intellij-community,izonder/intellij-community,apixandru/intellij-community,MichaelNedzelsky/intellij-community,fengbaicanhe/intellij-community,xfournet/intellij-community,ivan-fedorov/intellij-community,ahb0327/intellij-community,hurricup/intellij-community,petteyg/intellij-community,izonder/intellij-community,ibinti/intellij-community,xfournet/intellij-community,allotria/intellij-community,signed/intellij-community,signed/intellij-community,ibinti/intellij-community,nicolargo/intellij-community,samthor/intellij-community,lucafavatella/intellij-community,xfournet/intellij-community,diorcety/intellij-community,fitermay/intellij-community,petteyg/intellij-community,nicolargo/intellij-community,idea4bsd/idea4bsd,caot/intellij-community,samthor/intellij-community,ivan-fedorov/intellij-community,mglukhikh/intellij-community,robovm/robovm-studio,vvv1559/intellij-community,jagguli/intellij-community,lucafavatella/intellij-community,da1z/intellij-community,TangHao1987/intellij-community,MichaelNedzelsky/intellij-community,amith01994/intellij-community,slisson/intellij-community,gnuhub/intellij-community,michaelgallacher/intellij-community,Lekanich/intellij-community,ivan-fedorov/intellij-community,TangHao1987/intellij-community,Distrotech/intellij-community,signed/intellij-community,kool79/intellij-community,da1z/intellij-community,kool79/intellij-community,diorcety/intellij-community,TangHao1987/intellij-community,orekyuu/intellij-community,semonte/intellij-community,apixandru/intellij-community,kool79/intellij-community,petteyg/intellij-community,wreckJ/intellij-community,apixandru/intellij-community,signed/intellij-community,signed/intellij-community,youdonghai/intellij-community,semonte/intellij-community,asedunov/intellij-community,nicolargo/intellij-community,Lekanich/intellij-community,vvv1559/intellij-community,TangHao1987/intellij-community,vvv1559/intellij-community,ftomassetti/intellij-community,clumsy/intellij-community,SerCeMan/intellij-community,jagguli/intellij-community,fnouama/intellij-community,fengbaicanhe/intellij-community,gnuhub/intellij-community,dslomov/intellij-community,clumsy/intellij-community,amith01994/intellij-community,supersven/intellij-community,vladmm/intellij-community,lucafavatella/intellij-community,ol-loginov/intellij-community,FHannes/intellij-community,nicolargo/intellij-community,lucafavatella/intellij-community,asedunov/intellij-community,vvv1559/intellij-community,youdonghai/intellij-community,retomerz/intellij-community,izonder/intellij-community,alphafoobar/intellij-community,kdwink/intellij-community,TangHao1987/intellij-community,xfournet/intellij-community,ThiagoGarciaAlves/intellij-community,suncycheng/intellij-community,samthor/intellij-community,ol-loginov/intellij-community,holmes/intellij-community,suncycheng/intellij-community,kdwink/intellij-community,salguarnieri/intellij-community,kdwink/intellij-community,adedayo/intellij-community,asedunov/intellij-community,blademainer/intellij-community,ibinti/intellij-community,supersven/intellij-community,wreckJ/intellij-community,vvv1559/intellij-community,MichaelNedzelsky/intellij-community,ahb0327/intellij-community,ivan-fedorov/intellij-community,signed/intellij-community,holmes/intellij-community,allotria/intellij-community,akosyakov/intellij-community,fengbaicanhe/intellij-community,michaelgallacher/intellij-community,fengbaicanhe/intellij-community,hurricup/intellij-community,suncycheng/intellij-community,semonte/intellij-community,jagguli/intellij-community,lucafavatella/intellij-community,ryano144/intellij-community,kdwink/intellij-community,vladmm/intellij-community,muntasirsyed/intellij-community,allotria/intellij-community,semonte/intellij-community,nicolargo/intellij-community,diorcety/intellij-community,blademainer/intellij-community,retomerz/intellij-community,apixandru/intellij-community,signed/intellij-community,vladmm/intellij-community,michaelgallacher/intellij-community,allotria/intellij-community,jagguli/intellij-community,SerCeMan/intellij-community,lucafavatella/intellij-community,orekyuu/intellij-community,adedayo/intellij-community,ThiagoGarciaAlves/intellij-community,ryano144/intellij-community,alphafoobar/intellij-community,michaelgallacher/intellij-community,tmpgit/intellij-community,ryano144/intellij-community,MichaelNedzelsky/intellij-community,kdwink/intellij-community,SerCeMan/intellij-community,lucafavatella/intellij-community,supersven/intellij-community,ftomassetti/intellij-community,ol-loginov/intellij-community,da1z/intellij-community,diorcety/intellij-community,allotria/intellij-community,petteyg/intellij-community,gnuhub/intellij-community,suncycheng/intellij-community,mglukhikh/intellij-community,dslomov/intellij-community,slisson/intellij-community,vvv1559/intellij-community,clumsy/intellij-community,ThiagoGarciaAlves/intellij-community,salguarnieri/intellij-community,youdonghai/intellij-community,robovm/robovm-studio,robovm/robovm-studio,orekyuu/intellij-community,asedunov/intellij-community,allotria/intellij-community,supersven/intellij-community,jagguli/intellij-community,amith01994/intellij-community,FHannes/intellij-community,fengbaicanhe/intellij-community,Distrotech/intellij-community,FHannes/intellij-community,FHannes/intellij-community,apixandru/intellij-community,mglukhikh/intellij-community,alphafoobar/intellij-community,Distrotech/intellij-community,pwoodworth/intellij-community,salguarnieri/intellij-community,clumsy/intellij-community,idea4bsd/idea4bsd,dslomov/intellij-community,izonder/intellij-community,youdonghai/intellij-community,michaelgallacher/intellij-community,supersven/intellij-community,fnouama/intellij-community,akosyakov/intellij-community,MER-GROUP/intellij-community,mglukhikh/intellij-community,semonte/intellij-community,fnouama/intellij-community,Distrotech/intellij-community,amith01994/intellij-community,da1z/intellij-community,gnuhub/intellij-community,akosyakov/intellij-community,slisson/intellij-community,michaelgallacher/intellij-community,retomerz/intellij-community,orekyuu/intellij-community,signed/intellij-community,Distrotech/intellij-community,gnuhub/intellij-community,MER-GROUP/intellij-community,slisson/intellij-community,pwoodworth/intellij-community,slisson/intellij-community,holmes/intellij-community,retomerz/intellij-community,tmpgit/intellij-community,caot/intellij-community,idea4bsd/idea4bsd,allotria/intellij-community,youdonghai/intellij-community,clumsy/intellij-community,semonte/intellij-community,dslomov/intellij-community,muntasirsyed/intellij-community,amith01994/intellij-community,retomerz/intellij-community,holmes/intellij-community,blademainer/intellij-community,jagguli/intellij-community,ivan-fedorov/intellij-community,alphafoobar/intellij-community,semonte/intellij-community,dslomov/intellij-community,signed/intellij-community,ol-loginov/intellij-community,ahb0327/intellij-community,da1z/intellij-community,fnouama/intellij-community,alphafoobar/intellij-community,mglukhikh/intellij-community,adedayo/intellij-community,apixandru/intellij-community,asedunov/intellij-community,samthor/intellij-community,kdwink/intellij-community,samthor/intellij-community,supersven/intellij-community,ibinti/intellij-community,ftomassetti/intellij-community,Distrotech/intellij-community,ryano144/intellij-community,semonte/intellij-community,dslomov/intellij-community,xfournet/intellij-community,ryano144/intellij-community,fnouama/intellij-community,supersven/intellij-community,ftomassetti/intellij-community,apixandru/intellij-community,MER-GROUP/intellij-community,holmes/intellij-community,fitermay/intellij-community,idea4bsd/idea4bsd,allotria/intellij-community,ftomassetti/intellij-community,vvv1559/intellij-community,ahb0327/intellij-community,adedayo/intellij-community,supersven/intellij-community,Distrotech/intellij-community,MER-GROUP/intellij-community,xfournet/intellij-community,ThiagoGarciaAlves/intellij-community,hurricup/intellij-community,amith01994/intellij-community,orekyuu/intellij-community,holmes/intellij-community,asedunov/intellij-community,FHannes/intellij-community,tmpgit/intellij-community,petteyg/intellij-community,ThiagoGarciaAlves/intellij-community,da1z/intellij-community,retomerz/intellij-community,robovm/robovm-studio,fitermay/intellij-community,fitermay/intellij-community,akosyakov/intellij-community,samthor/intellij-community,MichaelNedzelsky/intellij-community,xfournet/intellij-community,petteyg/intellij-community,ThiagoGarciaAlves/intellij-community,tmpgit/intellij-community,MER-GROUP/intellij-community,signed/intellij-community,petteyg/intellij-community,mglukhikh/intellij-community,slisson/intellij-community,ftomassetti/intellij-community,muntasirsyed/intellij-community,nicolargo/intellij-community,suncycheng/intellij-community,youdonghai/intellij-community,dslomov/intellij-community,retomerz/intellij-community,clumsy/intellij-community,supersven/intellij-community,alphafoobar/intellij-community,fnouama/intellij-community,kdwink/intellij-community,kool79/intellij-community,tmpgit/intellij-community,akosyakov/intellij-community,ThiagoGarciaAlves/intellij-community,hurricup/intellij-community,youdonghai/intellij-community,MichaelNedzelsky/intellij-community,wreckJ/intellij-community,Distrotech/intellij-community,Distrotech/intellij-community,vvv1559/intellij-community,blademainer/intellij-community,ryano144/intellij-community,ivan-fedorov/intellij-community,vladmm/intellij-community,tmpgit/intellij-community,holmes/intellij-community,salguarnieri/intellij-community,amith01994/intellij-community,FHannes/intellij-community,kool79/intellij-community,supersven/intellij-community,Lekanich/intellij-community,allotria/intellij-community,youdonghai/intellij-community,tmpgit/intellij-community,apixandru/intellij-community,ryano144/intellij-community,SerCeMan/intellij-community,ThiagoGarciaAlves/intellij-community,robovm/robovm-studio,akosyakov/intellij-community,ftomassetti/intellij-community,lucafavatella/intellij-community,adedayo/intellij-community,vladmm/intellij-community,lucafavatella/intellij-community,gnuhub/intellij-community,adedayo/intellij-community,adedayo/intellij-community,Lekanich/intellij-community,blademainer/intellij-community
|
0c0b163d6454134595fb8ba794281afe56bc0100
|
gae-firebase-listener-python/main.py
|
gae-firebase-listener-python/main.py
|
import os
import webapp2
IS_DEV = os.environ["SERVER_SOFTWARE"][:3] == "Dev"
allowed_users = set()
if IS_DEV:
allowed_users.add("dev-instance")
class LoggingHandler(webapp2.RequestHandler):
def post(self):
user = self.request.headers.get('X-Appengine-Inbound-Appid', None)
if user and user in allowed_users:
firebaseSnapshot = self.request.params['fbSnapshot']
print firebaseSnapshot
else:
print "Got unauthenticated user: %s" % user
app = webapp2.WSGIApplication([
webapp2.Route('/log', LoggingHandler),
])
|
import os
import webapp2
IS_DEV = os.environ["SERVER_SOFTWARE"][:3] == "Dev"
allowed_users = set()
if IS_DEV:
allowed_users.add("dev-instance")
else:
# Add your Java App Engine proxy App Id here
allowed_users.add("your-java-appengine-proxy-app-id")
class LoggingHandler(webapp2.RequestHandler):
def post(self):
user = self.request.headers.get('X-Appengine-Inbound-Appid', None)
if user and user in allowed_users:
firebaseSnapshot = self.request.params['fbSnapshot']
print firebaseSnapshot
else:
print "Got unauthenticated user: %s" % user
app = webapp2.WSGIApplication([
webapp2.Route('/log', LoggingHandler),
])
|
Add proxy app id to listener
|
Add proxy app id to listener
|
Python
|
mit
|
misterwilliam/gae-firebase-event-proxy,misterwilliam/gae-firebase-event-proxy
|
db4b8b2abbb1726a3d2db3496b82e0ad6c0572e9
|
gateway_mac.py
|
gateway_mac.py
|
import socket, struct
import scapy.all as scapy
def get_default_gateway_linux():
"""Read the default gateway directly from /proc."""
with open("/proc/net/route") as fh:
for line in fh:
fields = line.strip().split()
if fields[1] != '00000000' or not int(fields[3], 16) & 2:
continue
return socket.inet_ntoa(struct.pack("<L", int(fields[2], 16)))
def get_mac(ip):
arp_request = scapy.ARP(pdst=ip)
broadcast = scapy.Ether(dst="ff:ff:ff:ff:ff:ff")
arp_request_broadcast = broadcast/arp_request
answered_list = scapy.srp(arp_request_broadcast, timeout=1,
verbose=False)[0]
clients_list = []
for element in answered_list:
client_dict = {"ip": element[1].psrc, "mac": element[1].hwsrc}
clients_list.append(client_dict)
return clients_list
if __name__ == '__main__':
default_gw = get_default_gateway_linux()
print(get_mac(default_gw))
|
import socket, struct
import scapy.all as scapy
def get_default_gateway_linux():
"""Read the default gateway directly from /proc."""
routes = []
with open("/proc/net/route") as fh:
for line in fh:
fields = line.strip().split()
if fields[1] != '00000000' or not int(fields[3], 16) & 2:
continue
routes.append(socket.inet_ntoa(struct.pack("<L", int(fields[2], 16))))
print(routes)
return routes
def get_mac(ip):
arp_request = scapy.ARP(pdst=ip)
broadcast = scapy.Ether(dst="ff:ff:ff:ff:ff:ff")
arp_request_broadcast = broadcast/arp_request
answered_list = scapy.srp(arp_request_broadcast, timeout=1,
verbose=False)[0]
clients_list = []
for element in answered_list:
client_dict = {"ip": element[1].psrc, "mac": element[1].hwsrc}
clients_list.append(client_dict)
return clients_list
if __name__ == '__main__':
default_gw = get_default_gateway_linux()
for g in default_gw:
print(get_mac(default_gw))
|
Update to support multiple default gateways
|
Update to support multiple default gateways
|
Python
|
mit
|
nulledbyte/scripts
|
4db52d5c8a10460fb9ea4a701e953f790a720f83
|
admin/common_auth/forms.py
|
admin/common_auth/forms.py
|
from __future__ import absolute_import
from django import forms
from django.contrib.auth.forms import UserCreationForm
from django.contrib.admin.widgets import FilteredSelectMultiple
from django.contrib.auth.models import Group
from osf.models.user import OSFUser
from admin.common_auth.models import AdminProfile
class LoginForm(forms.Form):
email = forms.CharField(label=u'Email', required=True)
password = forms.CharField(
label=u'Password',
widget=forms.PasswordInput(render_value=False),
required=True
)
class UserRegistrationForm(UserCreationForm):
group_perms = forms.ModelMultipleChoiceField(
queryset=Group.objects.filter(name='prereg_group'),
widget=FilteredSelectMultiple('verbose name', is_stacked=False),
required=False
)
class Meta:
model = OSFUser
fields = ['given_name', 'username']
def __init__(self, *args, **kwargs):
super(UserRegistrationForm, self).__init__(*args, **kwargs)
self.fields['first_name'].required = True
self.fields['last_name'].required = True
self.fields['osf_id'].required = True
class DeskUserForm(forms.ModelForm):
class Meta:
model = AdminProfile
fields = ['desk_token', 'desk_token_secret']
|
from __future__ import absolute_import
from django import forms
from django.db.models import Q
from django.contrib.auth.models import Group
from admin.common_auth.models import AdminProfile
class LoginForm(forms.Form):
email = forms.CharField(label=u'Email', required=True)
password = forms.CharField(
label=u'Password',
widget=forms.PasswordInput(render_value=False),
required=True
)
class UserRegistrationForm(forms.Form):
""" A form that finds an existing OSF User, and grants permissions to that
user so that they can use the admin app"""
osf_id = forms.CharField(required=True, max_length=5, min_length=5)
group_perms = forms.ModelMultipleChoiceField(
queryset=Group.objects.filter(Q(name='prereg_group') | Q(name='osf_admin')),
required=True
)
class DeskUserForm(forms.ModelForm):
class Meta:
model = AdminProfile
fields = ['desk_token', 'desk_token_secret']
|
Update UserRegistrationForm to be connected to an existing OSF user.
|
Update UserRegistrationForm to be connected to an existing OSF user.
|
Python
|
apache-2.0
|
aaxelb/osf.io,Nesiehr/osf.io,erinspace/osf.io,brianjgeiger/osf.io,TomBaxter/osf.io,adlius/osf.io,pattisdr/osf.io,CenterForOpenScience/osf.io,baylee-d/osf.io,crcresearch/osf.io,brianjgeiger/osf.io,binoculars/osf.io,adlius/osf.io,laurenrevere/osf.io,mfraezz/osf.io,cslzchen/osf.io,caneruguz/osf.io,chrisseto/osf.io,felliott/osf.io,monikagrabowska/osf.io,brianjgeiger/osf.io,felliott/osf.io,sloria/osf.io,icereval/osf.io,mfraezz/osf.io,mattclark/osf.io,Nesiehr/osf.io,felliott/osf.io,mattclark/osf.io,hmoco/osf.io,caseyrollins/osf.io,aaxelb/osf.io,Johnetordoff/osf.io,crcresearch/osf.io,mfraezz/osf.io,binoculars/osf.io,acshi/osf.io,baylee-d/osf.io,Johnetordoff/osf.io,chennan47/osf.io,mfraezz/osf.io,caseyrollins/osf.io,pattisdr/osf.io,TomBaxter/osf.io,HalcyonChimera/osf.io,cwisecarver/osf.io,cwisecarver/osf.io,acshi/osf.io,laurenrevere/osf.io,caneruguz/osf.io,HalcyonChimera/osf.io,saradbowman/osf.io,Johnetordoff/osf.io,adlius/osf.io,icereval/osf.io,aaxelb/osf.io,laurenrevere/osf.io,icereval/osf.io,chrisseto/osf.io,brianjgeiger/osf.io,monikagrabowska/osf.io,chrisseto/osf.io,crcresearch/osf.io,hmoco/osf.io,HalcyonChimera/osf.io,hmoco/osf.io,Nesiehr/osf.io,sloria/osf.io,leb2dg/osf.io,chennan47/osf.io,TomBaxter/osf.io,leb2dg/osf.io,hmoco/osf.io,mattclark/osf.io,CenterForOpenScience/osf.io,felliott/osf.io,adlius/osf.io,Nesiehr/osf.io,monikagrabowska/osf.io,acshi/osf.io,saradbowman/osf.io,Johnetordoff/osf.io,acshi/osf.io,sloria/osf.io,CenterForOpenScience/osf.io,caneruguz/osf.io,monikagrabowska/osf.io,cwisecarver/osf.io,cslzchen/osf.io,cwisecarver/osf.io,cslzchen/osf.io,caneruguz/osf.io,erinspace/osf.io,erinspace/osf.io,pattisdr/osf.io,baylee-d/osf.io,acshi/osf.io,HalcyonChimera/osf.io,chennan47/osf.io,monikagrabowska/osf.io,leb2dg/osf.io,caseyrollins/osf.io,cslzchen/osf.io,binoculars/osf.io,leb2dg/osf.io,chrisseto/osf.io,CenterForOpenScience/osf.io,aaxelb/osf.io
|
32c971233fa4c83a163036da0090d35463d43c75
|
bananas/management/commands/syncpermissions.py
|
bananas/management/commands/syncpermissions.py
|
from django.contrib.auth.models import Permission
from django.core.management.base import BaseCommand, CommandError
class Command(BaseCommand):
help = "Create admin permissions"
def handle(self, *args, **options):
if args: # pragma: no cover
raise CommandError("Command doesn't accept any arguments")
return self.handle_noargs(**options)
def handle_noargs(self, *args, **options):
from bananas import admin
from django.contrib import admin as django_admin
from django.contrib.contenttypes.models import ContentType
django_admin.autodiscover()
for model, _ in admin.site._registry.items():
if issubclass(getattr(model, "View", object), admin.AdminView):
meta = model._meta
ct, created = ContentType.objects.get_or_create(
app_label=meta.app_label, model=meta.object_name.lower()
)
if created:
print("Found new admin view: {} [{}]".format(ct.name, ct.app_label))
for codename, name in model._meta.permissions:
p, created = Permission.objects.get_or_create(
codename=codename, name=name, content_type=ct
)
if created:
print("Created permission: {}".format(name))
|
from django.contrib.auth.models import Permission
from django.core.management.base import BaseCommand, CommandError
class Command(BaseCommand):
help = "Create admin permissions"
def handle(self, *args, **options):
if args: # pragma: no cover
raise CommandError("Command doesn't accept any arguments")
return self.handle_noargs(**options)
def handle_noargs(self, *args, **options):
from bananas import admin
from django.contrib import admin as django_admin
from django.contrib.contenttypes.models import ContentType
django_admin.autodiscover()
for model, _ in admin.site._registry.items():
if issubclass(getattr(model, "View", object), admin.AdminView):
meta = model._meta
ct, created = ContentType.objects.get_or_create(
app_label=meta.app_label, model=meta.object_name.lower()
)
if created:
print("Found new admin view: {} [{}]".format(ct.name, ct.app_label))
for codename, name in model._meta.permissions:
p, created = Permission.objects.update_or_create(
codename=codename, content_type=ct, defaults=dict(name=name)
)
if created:
print("Created permission: {}".format(name))
|
Update permission names when syncing
|
Update permission names when syncing
|
Python
|
mit
|
5monkeys/django-bananas,5monkeys/django-bananas,5monkeys/django-bananas
|
66cfb6f42cf681d848f944af5bbb7d472280d895
|
src/pyuniprot/cli.py
|
src/pyuniprot/cli.py
|
import click
from .manager import database
from .webserver.web import get_app
@click.group()
def main():
pass
@main.command()
def update():
"""Update PyUniProt data"""
database.update()
@main.command()
def web():
get_app().run()
|
import click
from .manager import database
from .webserver.web import get_app
@click.group()
def main():
pass
@main.command()
def update():
"""Update PyUniProt data"""
database.update()
@main.command()
@click.option('--host', default='0.0.0.0', help='Flask host. Defaults to localhost')
@click.option('--port', type=int, help='Flask port. Defaults to 5000')
def web(host, port):
get_app().run(host=host, port=port)
|
Add host and port options to web runner
|
Add host and port options to web runner
|
Python
|
apache-2.0
|
cebel/pyuniprot,cebel/pyuniprot
|
6556604fb98c2153412384d6f0f705db2da1aa60
|
tinycss2/css-parsing-tests/make_color3_hsl.py
|
tinycss2/css-parsing-tests/make_color3_hsl.py
|
import colorsys # It turns out Python already does HSL -> RGB!
def trim(s):
return s if not s.endswith('.0') else s[:-2]
print('[')
print(',\n'.join(
'"hsl%s(%s, %s%%, %s%%%s)", [%s, %s, %s, %s]' % (
('a' if a is not None else '', h,
trim(str(s / 10.)), trim(str(l / 10.)),
', %s' % a if a is not None else '') +
tuple(trim(str(round(v, 10)))
for v in colorsys.hls_to_rgb(h / 360., l / 1000., s / 1000.)) +
(a if a is not None else 1,)
)
for a in [None, 1, .2, 0]
for l in range(0, 1001, 125)
for s in range(0, 1001, 125)
for h in range(0, 360, 30)
))
print(']')
|
import colorsys # It turns out Python already does HSL -> RGB!
def trim(s):
return s if not s.endswith('.0') else s[:-2]
print('[')
print(',\n'.join(
'"hsl%s(%s, %s%%, %s%%%s)", [%s, %s, %s, %s]' % (
('a' if alpha is not None else '', hue,
trim(str(saturation / 10.)), trim(str(light / 10.)),
', %s' % alpha if alpha is not None else '') +
tuple(trim(str(round(v, 10)))
for v in colorsys.hls_to_rgb(
hue / 360., light / 1000., saturation / 1000.)) +
(alpha if alpha is not None else 1,)
)
for alpha in [None, 1, .2, 0]
for light in range(0, 1001, 125)
for saturation in range(0, 1001, 125)
for hue in range(0, 360, 30)
))
print(']')
|
Fix failing tests with recent versions of pytest-flake8
|
Fix failing tests with recent versions of pytest-flake8
|
Python
|
bsd-3-clause
|
SimonSapin/tinycss2
|
13a39f4e025160f584beef8442e82ec3c3526a95
|
raco/myrial/cli_test.py
|
raco/myrial/cli_test.py
|
"""Basic test of the command-line interface to Myrial."""
import subprocess
import unittest
class CliTest(unittest.TestCase):
def test_cli(self):
out = subprocess.check_output(['python', 'scripts/myrial',
'examples/reachable.myl'])
self.assertIn('DO', out)
self.assertIn('WHILE', out)
def test_cli_reserved_column_name(self):
proc = subprocess.Popen(
['python', 'scripts/myrial', 'examples/bad_column_name.myl'],
stdout=subprocess.PIPE)
out = proc.communicate()[0]
self.assertIn('The token "SafeDiv" on line 2 is reserved', out)
|
"""Basic test of the command-line interface to Myrial."""
import subprocess
import unittest
class CliTest(unittest.TestCase):
def test_cli(self):
out = subprocess.check_output(['python', 'scripts/myrial',
'examples/reachable.myl'])
self.assertIn('DO', out)
self.assertIn('WHILE', out)
def test_cli_standalone(self):
out = subprocess.check_output(['python', 'scripts/myrial', '-f',
'examples/standalone.myl'])
self.assertIn('Dan Suciu,engineering', out)
def test_cli_reserved_column_name(self):
proc = subprocess.Popen(
['python', 'scripts/myrial', 'examples/bad_column_name.myl'],
stdout=subprocess.PIPE)
out = proc.communicate()[0]
self.assertIn('The token "SafeDiv" on line 2 is reserved', out)
|
Test of standalone myrial mode
|
Test of standalone myrial mode
|
Python
|
bsd-3-clause
|
uwescience/raco,uwescience/raco,uwescience/raco,uwescience/raco,uwescience/raco
|
a021b077834a932b5c8da6be49bb98e7862392d4
|
setup.py
|
setup.py
|
import os
from distutils.core import setup
def read(fname):
return open(os.path.join(os.path.dirname(__file__), fname)).read()
setup(
name='django-mingus',
version='0.9.7',
description='A django blog engine.',
long_description=read('README.textile'),
author='Kevin Fricovsky',
author_email='kfricovsky@gmail.com',
license='BSD',
url='http://github.com/montylounge/django-mingus/',
keywords = ['blog', 'django',],
packages=[
'mingus',
'mingus.core',
'mingus.core.templatetags',
],
classifiers=[
'Development Status :: 4 - Beta',
'Environment :: Web Environment',
'Intended Audience :: Developers',
'License :: OSI Approved :: BSD License',
'Operating System :: OS Independent',
'Programming Language :: Python',
'Framework :: Django',
],
zip_safe=False,
)
|
import os
from distutils.core import setup
def read(fname):
return open(os.path.join(os.path.dirname(__file__), fname)).read()
setup(
name='django-mingus',
version='0.9.7',
description='A django blog engine.',
long_description=read('README.textile'),
author='Kevin Fricovsky',
author_email='kfricovsky@gmail.com',
license='BSD',
url='http://github.com/montylounge/django-mingus/',
keywords = ['blog', 'django',],
packages=[
'mingus',
'mingus.core',
'mingus.core.templatetags',
],
classifiers=[
'Development Status :: 4 - Beta',
'Environment :: Web Environment',
'Intended Audience :: Developers',
'License :: OSI Approved :: BSD License',
'Operating System :: OS Independent',
'Programming Language :: Python',
'Framework :: Django',
],
zip_safe=False,
include_package_data=True,
)
|
Install templates when using pip to install package.
|
Install templates when using pip to install package.
|
Python
|
apache-2.0
|
emorozov/django-mingus,emorozov/django-mingus,emorozov/django-mingus,emorozov/django-mingus
|
0f18b3ff63bf6183247e7bce25160547f8cfc21d
|
setup.py
|
setup.py
|
import os
import sys
from distutils.core import setup
if sys.version_info < (3,):
print('\nSorry, but Adventure can only be installed under Python 3.\n')
sys.exit(1)
README_PATH = os.path.join(os.path.dirname(__file__), 'adventure', 'README.txt')
with open(README_PATH, encoding="utf-8") as f:
README_TEXT = f.read()
setup(
name='adventure',
version='1.3',
description='Colossal Cave adventure game at the Python prompt',
long_description=README_TEXT,
author='Brandon Craig Rhodes',
author_email='brandon@rhodesmill.org',
url='https://bitbucket.org/brandon/adventure/overview',
packages=['adventure', 'adventure/tests'],
package_data={'adventure': ['README.txt', '*.dat', 'tests/*.txt']},
classifiers=[
'Development Status :: 6 - Mature',
'Environment :: Console',
'Intended Audience :: End Users/Desktop',
'License :: OSI Approved :: BSD License',
'Programming Language :: Python :: 3',
'Programming Language :: Python :: 3.2',
'Topic :: Games/Entertainment',
],
)
|
import os
import sys
from distutils.core import setup
if sys.version_info < (3,):
print('\nSorry, but Adventure can only be installed under Python 3.\n')
sys.exit(1)
README_PATH = os.path.join(os.path.dirname(__file__), 'adventure', 'README.txt')
with open(README_PATH, encoding="utf-8") as f:
README_TEXT = f.read()
setup(
name='adventure',
version='1.3',
description='Colossal Cave adventure game at the Python prompt',
long_description=README_TEXT,
author='Brandon Craig Rhodes',
author_email='brandon@rhodesmill.org',
url='https://bitbucket.org/brandon/adventure/overview',
packages=['adventure', 'adventure/tests'],
package_data={'adventure': ['README.txt', '*.dat', 'tests/*.txt']},
classifiers=[
'Development Status :: 6 - Mature',
'Environment :: Console',
'Intended Audience :: End Users/Desktop',
'License :: OSI Approved :: Apache Software License',
'Programming Language :: Python :: 3',
'Programming Language :: Python :: 3.2',
'Topic :: Games/Entertainment',
],
)
|
Change PyPI trove classifier for license terms.
|
Change PyPI trove classifier for license terms.
|
Python
|
apache-2.0
|
devinmcgloin/advent,devinmcgloin/advent
|
024878fc913097364123d28a99ab7cb5501b0af5
|
setup.py
|
setup.py
|
#!/usr/bin/env python
import subprocess
from distutils.core import setup
requirements = [pkg.split('=')[0] for pkg in open('requirements.txt').readlines()]
description = 'Download videos from Udemy for personal offline use'
try:
subprocess.call(["pandoc", "README.md", "-f", "markdown", "-t", "rst", "-o", "README.rst"])
long_description = open("README.rst").read()
except OSError:
print("Pandoc not installed")
long_description = description
classifiers = ['Environment :: Console',
'Programming Language :: Python :: 2',
'Programming Language :: Python :: 3',
'Topic :: Multimedia :: Video',
]
version = open('CHANGES.txt').readlines()[0][1:].strip()
setup(name='udemy-dl',
version=version,
description=description,
author='Gaganpreet Singh Arora',
author_email='gaganpreet.arora@gmail.com',
url='https://github.com/gaganpreet/udemy-dl',
scripts=['src/udemy-dl',],
install_requires=requirements,
long_description=long_description,
packages=['udemy_dl'],
package_dir = {'udemy_dl': 'src/udemy_dl'},
classifiers=classifiers
)
|
#!/usr/bin/env python
import os
import subprocess
from distutils.core import setup
requirements = [pkg.split('=')[0] for pkg in open('requirements.txt').readlines()]
description = 'Download videos from Udemy for personal offline use'
try:
subprocess.call(["pandoc", "README.md", "-f", "markdown", "-t", "rst", "-o", "README.rst"])
long_description = open("README.rst").read()
except OSError:
print("Pandoc not installed")
long_description = description
classifiers = ['Environment :: Console',
'Programming Language :: Python :: 2',
'Programming Language :: Python :: 3',
'Topic :: Multimedia :: Video',
]
version = open('CHANGES.txt').readlines()[0][1:].strip()
# if installed as root or with sudo, set permission mask to allow read/exec for all users
if os.getuid() == 0:
os.umask(int('022', 8))
setup(name='udemy-dl',
version=version,
description=description,
author='Gaganpreet Singh Arora',
author_email='gaganpreet.arora@gmail.com',
url='https://github.com/gaganpreet/udemy-dl',
scripts=['src/udemy-dl',],
install_requires=requirements,
long_description=long_description,
packages=['udemy_dl'],
package_dir = {'udemy_dl': 'src/udemy_dl'},
classifiers=classifiers
)
|
Set permission mask to allow read/exec for all users
|
Set permission mask to allow read/exec for all users
|
Python
|
unlicense
|
rinodung/udemy-dl
|
f27e08b0dcace5b9f49c5b2a211347a2f50f8254
|
stats.py
|
stats.py
|
from bs4 import BeautifulSoup
import requests
def statsRoyale(tag):
link = 'http://statsroyale.com/profile/' + tag
response = (requests.get(link)).text
soup = BeautifulSoup(response, 'html.parser')
stats = {}
content = soup.find_all('div', {'class':'content'})
stats['clan'] = content[0].get_text()
if stats['clan'] == 'No Clan':
stats['clan'] = None
stats['highest_trophies'] = content[1].get_text()
stats['last_known_trophies'] = content[2].get_text()
stats['challenge_cards_won'] = content[3].get_text()
stats['tournament_cards_won'] = content[4].get_text()
stats['total_donations'] = content[5].get_text()
stats['best_session_rank'] = content[6].get_text()
stats['previous_session_rank'] = content[7].get_text()
stats['legendary_trophies'] = content[8].get_text()
stats['wins'] = content[9].get_text()
stats['losses'] = content[10].get_text()
stats['3_crown_wins'] = content[11].get_text()
return stats
stats = statsRoyale(tag='9890JJJV')
print stats
|
from bs4 import BeautifulSoup
import requests
def statsRoyale(tag):
if not tag.find('/') == -1:
tag = tag[::-1]
pos = tag.find('/')
tag = tag[:pos]
tag = tag[::-1]
link = 'http://statsroyale.com/profile/' + tag
response = (requests.get(link)).text
soup = BeautifulSoup(response, 'html.parser')
description = soup.find_all('div', {'class':'description'})
content = soup.find_all('div', {'class':'content'})
stats = {}
for i in range(len(description)):
description_text = ((description[i].get_text()).replace(' ', '_')).lower()
content_text = content[i].get_text()
stats[description_text] = content_text
if stats['clan'] == 'No Clan':
stats['clan'] = None
return stats
stats = statsRoyale(tag='9890JJJV')
print stats
|
Use tags or direct url
|
Use tags or direct url
|
Python
|
mit
|
atulya2109/Stats-Royale-Python
|
c05b06577785bdf34f1fcd051ecf6d4398d2f77e
|
tasks.py
|
tasks.py
|
from os.path import join
from invoke import Collection, ctask as task
from invocations import docs as _docs
d = 'sites'
# Usage doc/API site (published as docs.paramiko.org)
path = join(d, 'docs')
docs = Collection.from_module(_docs, name='docs', config={
'sphinx.source': path,
'sphinx.target': join(path, '_build'),
})
# Main/about/changelog site ((www.)?paramiko.org)
path = join(d, 'www')
www = Collection.from_module(_docs, name='www', config={
'sphinx.source': path,
'sphinx.target': join(path, '_build'),
})
# Until we move to spec-based testing
@task
def test(ctx):
ctx.run("python test.py --verbose")
@task
def coverage(ctx):
ctx.run("coverage run --source=paramiko test.py --verbose")
ns = Collection(test, coverage, docs=docs, www=www)
|
from os.path import join
from shutil import rmtree, move
from invoke import Collection, ctask as task
from invocations import docs as _docs
from invocations.packaging import publish
d = 'sites'
# Usage doc/API site (published as docs.paramiko.org)
docs_path = join(d, 'docs')
docs_build = join(docs_path, '_build')
docs = Collection.from_module(_docs, name='docs', config={
'sphinx.source': docs_path,
'sphinx.target': docs_build,
})
# Main/about/changelog site ((www.)?paramiko.org)
www_path = join(d, 'www')
www = Collection.from_module(_docs, name='www', config={
'sphinx.source': www_path,
'sphinx.target': join(www_path, '_build'),
})
# Until we move to spec-based testing
@task
def test(ctx):
ctx.run("python test.py --verbose")
@task
def coverage(ctx):
ctx.run("coverage run --source=paramiko test.py --verbose")
# Until we stop bundling docs w/ releases. Need to discover use cases first.
@task('docs') # Will invoke the API doc site build
def release(ctx):
# Move the built docs into where Epydocs used to live
rmtree('docs')
move(docs_build, 'docs')
# Publish
publish(ctx)
ns = Collection(test, coverage, release, docs=docs, www=www)
|
Add new release task w/ API doc prebuilding
|
Add new release task w/ API doc prebuilding
|
Python
|
lgpl-2.1
|
thusoy/paramiko,CptLemming/paramiko,rcorrieri/paramiko,redixin/paramiko,Automatic/paramiko,jaraco/paramiko,esc/paramiko,ameily/paramiko,zarr12steven/paramiko,dorianpula/paramiko,mirrorcoder/paramiko,jorik041/paramiko,thisch/paramiko,dlitz/paramiko,paramiko/paramiko,digitalquacks/paramiko,fvicente/paramiko,SebastianDeiss/paramiko,anadigi/paramiko,varunarya10/paramiko,zpzgone/paramiko,torkil/paramiko,mhdaimi/paramiko,reaperhulk/paramiko,selboo/paramiko,remram44/paramiko,toby82/paramiko,davidbistolas/paramiko
|
f4ba2cba93222b4dd494caf487cdd6be4309e41a
|
studygroups/forms.py
|
studygroups/forms.py
|
from django import forms
from studygroups.models import StudyGroupSignup, Application
from localflavor.us.forms import USPhoneNumberField
class ApplicationForm(forms.ModelForm):
mobile = USPhoneNumberField(required=False)
class Meta:
model = Application
labels = {
'name': 'Please tell us what to call you',
'mobile': 'What is your mobile number?',
'contact_method': 'Please tell us how would you perfer us to contact us',
'computer_access': 'Do you have normal everyday access to the computer?',
'goals': 'Please tell what your learning goals are',
'support': '',
}
widgets = {
'study_groups': forms.CheckboxSelectMultiple,
}
fields = '__all__'
class SignupForm(forms.ModelForm):
mobile = USPhoneNumberField(required=False)
class Meta:
model = StudyGroupSignup
exclude = []
widgets = {
'study_group': forms.HiddenInput
}
class EmailForm(forms.Form):
study_group_id = forms.IntegerField(widget=forms.HiddenInput)
subject = forms.CharField()
body = forms.CharField(widget=forms.Textarea)
sms_body = forms.CharField(max_length=160, widget=forms.Textarea)
|
from django import forms
from studygroups.models import StudyGroupSignup, Application
from localflavor.us.forms import USPhoneNumberField
class ApplicationForm(forms.ModelForm):
mobile = USPhoneNumberField(required=False)
class Meta:
model = Application
labels = {
'name': 'Please tell us what to call you',
'mobile': 'What is your mobile number?',
'contact_method': 'Preferred Method of Contact.',
'computer_access': 'Do you have access to a computer outside of the library?',
'goals': 'In one sentence, please explain your goals for taking this course.',
'support': 'A successful study group requires the support of all of its members. How will you help your peers achieve their goals?',
'study_groups': 'Which course are you applying for? (by applying for a specific course, you agree to attend sessions at the specified time and location).',
}
widgets = {
'study_groups': forms.CheckboxSelectMultiple,
}
fields = '__all__'
class SignupForm(forms.ModelForm):
mobile = USPhoneNumberField(required=False)
class Meta:
model = StudyGroupSignup
exclude = []
widgets = {
'study_group': forms.HiddenInput
}
class EmailForm(forms.Form):
study_group_id = forms.IntegerField(widget=forms.HiddenInput)
subject = forms.CharField()
body = forms.CharField(widget=forms.Textarea)
sms_body = forms.CharField(max_length=160, widget=forms.Textarea)
|
Update labels for application form
|
Update labels for application form
|
Python
|
mit
|
p2pu/learning-circles,p2pu/learning-circles,p2pu/learning-circles,p2pu/learning-circles
|
6755255332039ab3c0ea60346f61420b52e2f474
|
tests/functional/test_l10n.py
|
tests/functional/test_l10n.py
|
# This Source Code Form is subject to the terms of the Mozilla Public
# License, v. 2.0. If a copy of the MPL was not distributed with this
# file, You can obtain one at http://mozilla.org/MPL/2.0/.
import random
import pytest
from ..pages.home import HomePage
@pytest.mark.nondestructive
def test_change_language(base_url, selenium):
page = HomePage(base_url, selenium).open()
initial = page.footer.language
# avoid selecting the same language or locales that have homepage redirects
excluded = [initial, 'ja', 'ja-JP-mac', 'zh-TW', 'zh-CN']
available = [l for l in page.footer.languages if l not in excluded]
new = random.choice(available)
page.footer.select_language(new)
assert new in selenium.current_url, 'Language is not in URL'
assert new == page.footer.language, 'Language has not been selected'
|
# This Source Code Form is subject to the terms of the Mozilla Public
# License, v. 2.0. If a copy of the MPL was not distributed with this
# file, You can obtain one at http://mozilla.org/MPL/2.0/.
import random
import pytest
from ..pages.home import HomePage
@pytest.mark.nondestructive
def test_change_language(base_url, selenium):
page = HomePage(base_url, selenium).open()
initial = page.footer.language
# avoid selecting the same language or locales that have homepage redirects
excluded = [initial, 'ja', 'ja-JP-mac', 'zh-TW', 'zh-CN']
available = [l for l in page.footer.languages if l not in excluded]
new = random.choice(available)
page.footer.select_language(new)
assert '/{0}/'.format(new) in selenium.current_url, 'Language is not in URL'
assert new == page.footer.language, 'Language has not been selected'
|
Fix intermittent failure in l10n language selector test
|
Fix intermittent failure in l10n language selector test
|
Python
|
mpl-2.0
|
sgarrity/bedrock,TheoChevalier/bedrock,craigcook/bedrock,mkmelin/bedrock,TheoChevalier/bedrock,Sancus/bedrock,hoosteeno/bedrock,sylvestre/bedrock,schalkneethling/bedrock,Sancus/bedrock,analytics-pros/mozilla-bedrock,sylvestre/bedrock,glogiotatidis/bedrock,jgmize/bedrock,kyoshino/bedrock,mkmelin/bedrock,gerv/bedrock,davehunt/bedrock,alexgibson/bedrock,jpetto/bedrock,sylvestre/bedrock,sgarrity/bedrock,gerv/bedrock,craigcook/bedrock,ericawright/bedrock,analytics-pros/mozilla-bedrock,gauthierm/bedrock,davehunt/bedrock,pascalchevrel/bedrock,flodolo/bedrock,mozilla/bedrock,MichaelKohler/bedrock,alexgibson/bedrock,MichaelKohler/bedrock,gauthierm/bedrock,flodolo/bedrock,ericawright/bedrock,sgarrity/bedrock,analytics-pros/mozilla-bedrock,hoosteeno/bedrock,jpetto/bedrock,flodolo/bedrock,gauthierm/bedrock,gauthierm/bedrock,CSCI-462-01-2017/bedrock,jgmize/bedrock,mkmelin/bedrock,ericawright/bedrock,CSCI-462-01-2017/bedrock,CSCI-462-01-2017/bedrock,Sancus/bedrock,ericawright/bedrock,TheJJ100100/bedrock,glogiotatidis/bedrock,alexgibson/bedrock,sgarrity/bedrock,kyoshino/bedrock,MichaelKohler/bedrock,MichaelKohler/bedrock,TheJJ100100/bedrock,craigcook/bedrock,gerv/bedrock,pascalchevrel/bedrock,kyoshino/bedrock,mozilla/bedrock,jpetto/bedrock,TheoChevalier/bedrock,sylvestre/bedrock,glogiotatidis/bedrock,schalkneethling/bedrock,schalkneethling/bedrock,mozilla/bedrock,hoosteeno/bedrock,alexgibson/bedrock,CSCI-462-01-2017/bedrock,mozilla/bedrock,analytics-pros/mozilla-bedrock,mkmelin/bedrock,flodolo/bedrock,kyoshino/bedrock,davehunt/bedrock,TheJJ100100/bedrock,gerv/bedrock,TheoChevalier/bedrock,pascalchevrel/bedrock,craigcook/bedrock,Sancus/bedrock,jpetto/bedrock,hoosteeno/bedrock,pascalchevrel/bedrock,davehunt/bedrock,glogiotatidis/bedrock,jgmize/bedrock,schalkneethling/bedrock,TheJJ100100/bedrock,jgmize/bedrock
|
b37814280dc06dbf8aefec4490f6b73a47f05c1a
|
custom_fixers/fix_alt_unicode.py
|
custom_fixers/fix_alt_unicode.py
|
# Taken from jinja2. Thanks, Armin Ronacher.
# See also http://lucumr.pocoo.org/2010/2/11/porting-to-python-3-a-guide
from lib2to3 import fixer_base
from lib2to3.fixer_util import Name, BlankLine
class FixAltUnicode(fixer_base.BaseFix):
PATTERN = """
func=funcdef< 'def' name='__unicode__'
parameters< '(' NAME ')' > any+ >
"""
def transform(self, node, results):
name = results['name']
name.replace(Name('__str__', prefix=name.prefix))
|
# Taken from jinja2. Thanks, Armin Ronacher.
# See also http://lucumr.pocoo.org/2010/2/11/porting-to-python-3-a-guide
from lib2to3 import fixer_base
class FixAltUnicode(fixer_base.BaseFix):
PATTERN = "'__unicode__'"
def transform(self, node, results):
new = node.clone()
new.value = '__str__'
return new
|
Simplify python3 unicode fixer and make it replace all occurrences of __unicode__ with __str__.
|
Simplify python3 unicode fixer and make it replace all occurrences of __unicode__ with __str__.
|
Python
|
mit
|
live-clones/pybtex
|
eb4cda636a0b0ceb5312b161e97ae5f8376c9f8e
|
indra/tests/test_biolookup_client.py
|
indra/tests/test_biolookup_client.py
|
from indra.databases import biolookup_client
def test_lookup_curie():
curie = 'pubchem.compound:40976'
res = biolookup_client.lookup_curie(curie)
assert res['name'] == '(17R)-13-ethyl-17-ethynyl-17-hydroxy-11-' \
'methylidene-2,6,7,8,9,10,12,14,15,16-decahydro-1H-' \
'cyclopenta[a]phenanthren-3-one', res
def test_lookup():
res = biolookup_client.lookup('FPLX', 'ERK')
assert res['name'] == 'ERK', res
def test_get_name():
res = biolookup_client.get_name('CHEBI', 'CHEBI:408174')
assert res == 'arformoterol', res
|
from indra.databases import biolookup_client
def test_lookup_curie():
curie = 'pubchem.compound:40976'
res = biolookup_client.lookup_curie(curie)
assert res['name'] == '(17R)-13-ethyl-17-ethynyl-17-hydroxy-11-' \
'methylidene-2,6,7,8,9,10,12,14,15,16-decahydro-1H-' \
'cyclopenta[a]phenanthren-3-one', res
def test_lookup():
res = biolookup_client.lookup('HGNC', '1097')
assert res['name'] == 'BRAF', res
def test_get_name():
res = biolookup_client.get_name('CHEBI', 'CHEBI:408174')
assert res == 'arformoterol', res
|
Change biolookup test to work around service bug
|
Change biolookup test to work around service bug
|
Python
|
bsd-2-clause
|
johnbachman/indra,bgyori/indra,johnbachman/indra,bgyori/indra,bgyori/indra,sorgerlab/indra,johnbachman/indra,sorgerlab/indra,sorgerlab/indra
|
eac2f296e855f92d040321edee943ad5f8a8fb39
|
nodeconductor/events/views.py
|
nodeconductor/events/views.py
|
from rest_framework import generics, response
from nodeconductor.events import elasticsearch_client
class EventListView(generics.GenericAPIView):
def list(self, request, *args, **kwargs):
order_by = request.GET.get('o', '-@timestamp')
elasticsearch_list = elasticsearch_client.ElasticsearchResultList(user=request.user, sort=order_by)
page = self.paginate_queryset(elasticsearch_list)
if page is not None:
return self.get_paginated_response(page)
return response.Response(elasticsearch_list)
def get(self, request, *args, **kwargs):
return self.list(request, *args, **kwargs)
|
from rest_framework import generics, response
from nodeconductor.events import elasticsearch_client
class EventListView(generics.GenericAPIView):
def list(self, request, *args, **kwargs):
order_by = request.GET.get('o', '-@timestamp')
event_types = request.GET.getlist('event_type')
search_text = request.GET.get('search_text')
elasticsearch_list = elasticsearch_client.ElasticsearchResultList(
user=request.user, sort=order_by, event_types=event_types, search_text=search_text)
page = self.paginate_queryset(elasticsearch_list)
if page is not None:
return self.get_paginated_response(page)
return response.Response(elasticsearch_list)
def get(self, request, *args, **kwargs):
return self.list(request, *args, **kwargs)
|
Add filtering to view (nc-463)
|
Add filtering to view (nc-463)
|
Python
|
mit
|
opennode/nodeconductor,opennode/nodeconductor,opennode/nodeconductor
|
72e948719145579eb7dfb9385b921f8eb6ea1384
|
tests/v4/conftest.py
|
tests/v4/conftest.py
|
from .context import tohu
from tohu.v4.primitive_generators import *
from tohu.v4.derived_generators import *
__all__ = ['EXEMPLAR_GENERATORS', 'EXEMPLAR_PRIMITIVE_GENERATORS', 'EXEMPLAR_DERIVED_GENERATORS']
def add(x, y):
return x + y
EXEMPLAR_PRIMITIVE_GENERATORS = [
Constant("quux"),
Integer(100, 200),
HashDigest(length=6),
FakerGenerator(method="name"),
IterateOver('abcdefghijklmnopqrstuvwxyz'),
SelectOne('abcdefghijklmnopqrstuvwxyz'),
SelectOne('abcde', p=[0.1, 0.05, 0.7, 0.03, 0.12]),
Timestamp(date='2018-01-01'),
]
EXEMPLAR_DERIVED_GENERATORS = [
Apply(add, Integer(100, 200), Integer(300, 400)),
Apply(add, Apply(add, Integer(100, 200), Integer(300, 400)), Apply(add, Integer(500, 600), Integer(700, 800))),
]
EXEMPLAR_CUSTOM_GENERATORS = []
EXEMPLAR_GENERATORS = EXEMPLAR_PRIMITIVE_GENERATORS + EXEMPLAR_DERIVED_GENERATORS + EXEMPLAR_CUSTOM_GENERATORS
|
from .context import tohu
from tohu.v4.primitive_generators import *
from tohu.v4.derived_generators import *
__all__ = ['EXEMPLAR_GENERATORS', 'EXEMPLAR_PRIMITIVE_GENERATORS', 'EXEMPLAR_DERIVED_GENERATORS']
def add(x, y):
return x + y
EXEMPLAR_PRIMITIVE_GENERATORS = [
Boolean(p=0.3),
Constant("quux"),
FakerGenerator(method="name"),
Float(12.34, 56.78),
HashDigest(length=6),
Integer(100, 200),
IterateOver('abcdefghijklmnopqrstuvwxyz'),
SelectOne('abcdefghijklmnopqrstuvwxyz'),
SelectOne('abcde', p=[0.1, 0.05, 0.7, 0.03, 0.12]),
Timestamp(date='2018-01-01'),
]
EXEMPLAR_DERIVED_GENERATORS = [
Apply(add, Integer(100, 200), Integer(300, 400)),
Apply(add, Apply(add, Integer(100, 200), Integer(300, 400)), Apply(add, Integer(500, 600), Integer(700, 800))),
]
EXEMPLAR_CUSTOM_GENERATORS = []
EXEMPLAR_GENERATORS = EXEMPLAR_PRIMITIVE_GENERATORS + EXEMPLAR_DERIVED_GENERATORS + EXEMPLAR_CUSTOM_GENERATORS
|
Add more exemplar primitive generators
|
Add more exemplar primitive generators
|
Python
|
mit
|
maxalbert/tohu
|
24b8e2f7440926d6d1c384a7289dfb5d1124e82f
|
opps/core/admin/__init__.py
|
opps/core/admin/__init__.py
|
# -*- coding: utf-8 -*-
from opps.core.admin.channel import *
from opps.core.admin.profile import *
from opps.core.admin.source import *
|
# -*- coding: utf-8 -*-
from opps.core.admin.article import *
from opps.core.admin.channel import *
from opps.core.admin.profile import *
from opps.core.admin.source import *
|
Add article on core admin
|
Add article on core admin
|
Python
|
mit
|
YACOWS/opps,opps/opps,williamroot/opps,YACOWS/opps,jeanmask/opps,YACOWS/opps,williamroot/opps,opps/opps,YACOWS/opps,jeanmask/opps,jeanmask/opps,williamroot/opps,opps/opps,jeanmask/opps,opps/opps,williamroot/opps
|
ea416504c287bc5a3716289b57ebfd15bb770b9d
|
sql/branch.py
|
sql/branch.py
|
from gratipay import wireup
env = wireup.env()
db = wireup.db(env)
participants = []
with open('./sql/emails.txt') as f:
emails = [line.rstrip() for line in f]
participants = db.all("""
SELECT p.*::participants
FROM participants p
WHERE email_address IN %s
""", (tuple(emails), ))
for p in participants:
p.queue_email('double_emails')
|
import sys
from gratipay import wireup
env = wireup.env()
db = wireup.db(env)
# Temporary, will fill with actual values when running script
email_txt = """
rohitpaulk@live.com
abcd@gmail.com
"""
emails = [email.strip() for email in email_txt.split()]
assert len(emails) == 176
participants = []
participants = db.all("""
SELECT p.*::participants
FROM participants p
WHERE email_address IN %s
""", (tuple(emails), ))
for p in participants:
p.queue_email('double_emails')
print("Done")
sys.exit()
|
Use a string instead of a file
|
Use a string instead of a file
(so that I can redirect input to heroku from a local file)
|
Python
|
mit
|
eXcomm/gratipay.com,studio666/gratipay.com,eXcomm/gratipay.com,gratipay/gratipay.com,eXcomm/gratipay.com,mccolgst/www.gittip.com,mccolgst/www.gittip.com,studio666/gratipay.com,mccolgst/www.gittip.com,gratipay/gratipay.com,eXcomm/gratipay.com,mccolgst/www.gittip.com,gratipay/gratipay.com,studio666/gratipay.com,studio666/gratipay.com,gratipay/gratipay.com
|
34035c4b272e9271834c531990c404940eee8633
|
apps/votes/models.py
|
apps/votes/models.py
|
from django.db import models
from meps.models import MEP
class Proposal(models.Model):
id = models.CharField(max_length=63, primary_key=True)
title = models.CharField(max_length=255, unique=True)
class SubProposal(models.Model):
datetime = models.DateTimeField()
subject = models.CharField(max_length=255)
part = models.CharField(max_length=255)
description = models.CharField(max_length=511)
weight = models.IntegerField(null=True)
vote = models.ForeignKey(Proposal)
recommendation = models.CharField(max_length=15, choices=((u'against', u'against'), (u'for', u'for')), null=True)
class Vote(models.Model):
choice = models.CharField(max_length=15, choices=((u'for', u'for'), (u'against', u'against'), (u'abstention', u'abstention')))
name = models.CharField(max_length=127)
mep = models.ForeignKey(MEP)
|
from django.db import models
from meps.models import MEP
class Proposal(models.Model):
id = models.CharField(max_length=63, primary_key=True)
title = models.CharField(max_length=255, unique=True)
class SubProposal(models.Model):
datetime = models.DateTimeField()
subject = models.CharField(max_length=255)
part = models.CharField(max_length=255)
description = models.CharField(max_length=511)
weight = models.IntegerField(null=True)
vote = models.ForeignKey(Proposal)
recommendation = models.CharField(max_length=15, choices=((u'against', u'against'), (u'for', u'for')), null=True)
class Vote(models.Model):
choice = models.CharField(max_length=15, choices=((u'for', u'for'), (u'against', u'against'), (u'abstention', u'abstention')))
name = models.CharField(max_length=127)
sub_proposal = models.ForeignKey(SubProposal)
mep = models.ForeignKey(MEP)
|
Add a link between vote and subproposal
|
[enh] Add a link between vote and subproposal
|
Python
|
agpl-3.0
|
yohanboniface/memopol-core,yohanboniface/memopol-core,yohanboniface/memopol-core
|
496481e3bd6392a44788fadc7cf517fc36143e96
|
contrib/plugins/w3cdate.py
|
contrib/plugins/w3cdate.py
|
"""
Add a 'w3cdate' key to every entry -- this contains the date in ISO8601 format
WARNING: you must have PyXML installed as part of your python installation
in order for this plugin to work
Place this plugin early in your load_plugins list, so that the w3cdate will
be available to subsequent plugins
"""
__author__ = "Ted Leung <twl@sauria.com>"
__version__ = "$Id:"
__copyright__ = "Copyright (c) 2003 Ted Leung"
__license__ = "Python"
import xml.utils.iso8601
import time
def cb_prepare(args):
request = args["request"]
form = request.getHttp()['form']
config = request.getConfiguration()
data = request.getData()
entry_list = data['entry_list']
for i in range(len(entry_list)):
entry = entry_list[i]
t = entry['timetuple']
# adjust for daylight savings time
t = t[0],t[1],t[2],t[3]+time.localtime()[-1],t[4],t[5],t[6],t[7],t[8]
entry['w3cdate'] = xml.utils.iso8601.ctime(time.mktime(t))
|
"""
Add a 'w3cdate' key to every entry -- this contains the date in ISO8601 format
WARNING: you must have PyXML installed as part of your python installation
in order for this plugin to work
Place this plugin early in your load_plugins list, so that the w3cdate will
be available to subsequent plugins
"""
__author__ = "Ted Leung <twl@sauria.com>"
__version__ = "$Id:"
__copyright__ = "Copyright (c) 2003 Ted Leung"
__license__ = "Python"
import xml.utils.iso8601
import time
from Pyblosxom import tools
def cb_story(args):
request = tools.get_registry()["request"]
data = request.getData()
entry_list = data['entry_list']
for i in range(len(entry_list)):
entry = entry_list[i]
t = entry['timetuple']
# adjust for daylight savings time
tzoffset = 0
if time.timezone != 0:
tzoffset = time.altzone
entry['w3cdate'] = xml.utils.iso8601.tostring(time.mktime(t),tzoffset)
|
Change to cb_story, clean up TZ handling some more
|
Change to cb_story, clean up TZ handling some more
|
Python
|
mit
|
willkg/douglas,daitangio/pyblosxom,willkg/douglas,daitangio/pyblosxom
|
9fa55bc43a3f83a57318799ba8b9f2769676bd44
|
test/test_flvlib.py
|
test/test_flvlib.py
|
import unittest
import test_primitives, test_astypes, test_helpers
def get_suite():
modules = (test_primitives, test_astypes, test_helpers)
suites = [unittest.TestLoader().loadTestsFromModule(module) for
module in modules]
return unittest.TestSuite(suites)
def main():
unittest.TextTestRunner(verbosity=2).run(get_suite())
if __name__ == "__main__":
main()
|
import unittest
import test_primitives, test_astypes, test_helpers, test_tags
def get_suite():
modules = (test_primitives, test_astypes, test_helpers, test_tags)
suites = [unittest.TestLoader().loadTestsFromModule(module) for
module in modules]
return unittest.TestSuite(suites)
def main():
unittest.TextTestRunner(verbosity=2).run(get_suite())
if __name__ == "__main__":
main()
|
Include the tags module tests in the full library testsuite.
|
Include the tags module tests in the full library testsuite.
|
Python
|
mit
|
wulczer/flvlib
|
47c2936e65d00a08896b4e60060ff737b7a2f675
|
app/tests/workstations_tests/test_migrations.py
|
app/tests/workstations_tests/test_migrations.py
|
import pytest
from django.db import connection
from django.db.migrations.executor import MigrationExecutor
@pytest.mark.django_db(transaction=True)
def test_workstation_group_migration():
executor = MigrationExecutor(connection)
app = "workstations"
migrate_from = [(app, "0001_initial")]
migrate_to = [(app, "0004_auto_20190813_1302")]
executor.migrate(migrate_from)
old_apps = executor.loader.project_state(migrate_from).apps
Workstation = old_apps.get_model(app, "Workstation")
old_ws = Workstation.objects.create(title="foo")
assert not hasattr(old_ws, "editors_group")
assert not hasattr(old_ws, "users_group")
# Reload
executor.loader.build_graph()
# Migrate forwards
executor.migrate(migrate_to)
new_apps = executor.loader.project_state(migrate_to).apps
Workstation = new_apps.get_model(app, "Workstation")
new_ws = Workstation.objects.get(title="foo")
assert new_ws.editors_group
assert new_ws.users_group
assert new_ws.slug == old_ws.slug
assert new_ws.title == old_ws.title
|
import pytest
from django.db import connection
from django.db.migrations.executor import MigrationExecutor
from guardian.shortcuts import get_perms
from grandchallenge.workstations.models import Workstation
from tests.factories import UserFactory
@pytest.mark.django_db(transaction=True)
def test_workstation_group_migration():
executor = MigrationExecutor(connection)
app = "workstations"
migrate_from = [(app, "0001_initial")]
migrate_to = [(app, "0004_auto_20190813_1302")]
executor.migrate(migrate_from)
old_apps = executor.loader.project_state(migrate_from).apps
user = UserFactory()
OldWorkstation = old_apps.get_model(app, "Workstation")
old_ws = OldWorkstation.objects.create(title="foo")
assert not hasattr(old_ws, "editors_group")
assert not hasattr(old_ws, "users_group")
# Reload
executor.loader.build_graph()
# Migrate forwards
executor.migrate(migrate_to)
new_ws = Workstation.objects.get(title="foo")
new_ws.add_user(user=user)
assert new_ws.editors_group
assert new_ws.users_group
assert new_ws.slug == old_ws.slug
assert new_ws.title == old_ws.title
assert "view_workstation" in get_perms(user, new_ws)
|
Check that the permission migrations work
|
Check that the permission migrations work
|
Python
|
apache-2.0
|
comic/comic-django,comic/comic-django,comic/comic-django,comic/comic-django,comic/comic-django
|
54296c607b735ce06b3420efecb312f52876e012
|
django_react_templatetags/context_processors.py
|
django_react_templatetags/context_processors.py
|
#!/usr/bin/env python
# -*- coding: utf-8 -*-
def react_context_processor(request):
"""Expose a global list of react components to be processed"""
print("react_context_processor is no longer required.")
return {
'REACT_COMPONENTS': [],
}
|
#!/usr/bin/env python
# -*- coding: utf-8 -*-
import warnings
def react_context_processor(request):
"""Expose a global list of react components to be processed"""
warnings.warn(
"react_context_processor is no longer required.", DeprecationWarning
)
return {
'REACT_COMPONENTS': [],
}
|
Replace warning message with deprecation warning
|
Replace warning message with deprecation warning
|
Python
|
mit
|
Frojd/django-react-templatetags,Frojd/django-react-templatetags,Frojd/django-react-templatetags
|
1fed9f26010f24af14abff9444862ed0861adb63
|
thinglang/runner.py
|
thinglang/runner.py
|
from thinglang.execution.execution import ExecutionEngine
from thinglang.lexer.lexer import lexer
from thinglang.parser.parser import parse
def run(source):
if not source:
raise ValueError('Got empty source')
source = source.strip().replace(' ' * 4, '\t')
lexical_groups = list(lexer(source))
root_node = parse(lexical_groups)
with ExecutionEngine(root_node) as engine:
engine.execute()
return engine.results()
|
from thinglang.execution.execution import ExecutionEngine
from thinglang.lexer.lexer import lexer
from thinglang.parser.parser import parse
from thinglang.parser.simplifier import simplify
def run(source):
if not source:
raise ValueError('Source cannot be empty')
source = source.strip().replace(' ' * 4, '\t')
lexical_groups = list(lexer(source))
tree = parse(lexical_groups)
root_node = simplify(tree)
with ExecutionEngine(root_node) as engine:
engine.execute()
return engine.results()
|
Add simplification between parsing and execution
|
Add simplification between parsing and execution
|
Python
|
mit
|
ytanay/thinglang,ytanay/thinglang,ytanay/thinglang,ytanay/thinglang
|
6138f02896bc865a98480be36300bf670a6defa8
|
plugin/complete_database.py
|
plugin/complete_database.py
|
import vim
import re
import json
from os import path
current = vim.eval("expand('%:p')")
ccd = vim.eval("l:ccd")
opts = []
with open(ccd) as database:
data = json.load(database)
for d in data:
# hax for headers
fmatch = re.search(r'(.*)\.(\w+)$', current)
dmatch = re.search(r'(.*)\.(\w+)$', d['file'])
if fmatch.group(1) == dmatch.group(1):
for result in re.finditer(r'-D\s*[^\s]+', d['command']):
opts.append(result.group(0))
for result in re.finditer(r'-isystem\s*[^\s]+', d['command']):
opts.append(result.group(0))
for result in re.finditer(r'-I\s*([^\s]+)', d['command']):
opts.append('-I' + path.join(d['directory'], result.group(1)))
break
vim.command("let l:clang_options = '" + ' '.join(opts) + "'")
|
import vim
import re
import json
from os import path
curr_file = vim.eval("expand('%:p')")
curr_file_noext = path.splitext(curr_file)[0]
ccd = vim.eval("l:ccd")
opts = []
with open(ccd) as database:
# Search for the right entry in the database matching file names
for d in json.load(database):
# This is an entry without a file attribute
if 'file' not in d:
continue
# This entry is about a different file. We consider file names
# without extension to handle header files which do not have
# an entry in the database.
d_file_noext = path.splitext(d['file'])[0]
if d_file_noext != curr_file_noext:
continue
for result in re.finditer(r'-D\s*[^\s]+', d['command']):
opts.append(result.group(0))
for result in re.finditer(r'-isystem\s*[^\s]+', d['command']):
opts.append(result.group(0))
for result in re.finditer(r'-I\s*([^\s]+)', d['command']):
opts.append('-I' + path.join(d['directory'], result.group(1)))
break
vim.command("let l:clang_options = '" + ' '.join(opts) + "'")
|
Replace re by os.path utils
|
compdb: Replace re by os.path utils
Instead of using regular expressions to drop file name ending use
os.path.splitext().
|
Python
|
isc
|
justmao945/vim-clang,justmao945/vim-clang
|
0fe7cd8cf316dc6d4ef547d733b634de64fc768c
|
dbaas/dbaas_services/analyzing/admin/analyze.py
|
dbaas/dbaas_services/analyzing/admin/analyze.py
|
# -*- coding: utf-8 -*-
from __future__ import absolute_import, unicode_literals
from django_services import admin
from dbaas_services.analyzing.service import AnalyzeRepositoryService
from dbaas_services.analyzing.forms import AnalyzeRepositoryForm
class AnalyzeRepositoryAdmin(admin.DjangoServicesAdmin):
form = AnalyzeRepositoryForm
service_class = AnalyzeRepositoryService
search_fields = ("database_name", "engine_name",
"environment_name", "instance_name", "databaseinfra_name")
list_filter = ("analyzed_at", "memory_alarm", "cpu_alarm", "volume_alarm")
list_display = ("analyzed_at", "databaseinfra_name", "database_name", "engine_name",
"environment_name", "instance_name", "cpu_alarm",
"memory_alarm", "volume_alarm")
|
# -*- coding: utf-8 -*-
from __future__ import absolute_import, unicode_literals
from django_services import admin
from dbaas_services.analyzing.service import AnalyzeRepositoryService
from dbaas_services.analyzing.forms import AnalyzeRepositoryForm
class AnalyzeRepositoryAdmin(admin.DjangoServicesAdmin):
form = AnalyzeRepositoryForm
service_class = AnalyzeRepositoryService
search_fields = ("database_name", "engine_name",
"environment_name", "instance_name", "databaseinfra_name")
list_filter = ("analyzed_at", "memory_alarm", "cpu_alarm", "volume_alarm", "engine_name",
"environment_name", "databaseinfra_name")
list_display = ("analyzed_at", "databaseinfra_name", "database_name", "engine_name",
"environment_name", "instance_name", "cpu_alarm",
"memory_alarm", "volume_alarm")
|
Add more options on filters
|
Add more options on filters
|
Python
|
bsd-3-clause
|
globocom/database-as-a-service,globocom/database-as-a-service,globocom/database-as-a-service,globocom/database-as-a-service
|
2d09314ab58bb766372dc6e263fb17428b1fd3cd
|
doc/pool_scripts/cats.py
|
doc/pool_scripts/cats.py
|
import os
import photomosaic.flickr
import photomosaic as pm
if not os.path.isfile('~/pools/cats/pool.json'):
FLICKR_API_KEY = os.environ['FLICKR_API_KEY']
pm.set_options(flickr_api_key=FLICKR_API_KEY)
photomosaic.flickr.from_search('cats', '~/pools/cats/')
pool = pm.make_pool('~/pools/cats/*.jpg')
pm.export_pool(pool, '~/pools/cats/pool.json') # save color analysis for future reuse
|
import os
import photomosaic.flickr
import photomosaic as pm
if not os.path.isfile(os.path.expanduser('~/pools/cats/pool.json')):
FLICKR_API_KEY = os.environ['FLICKR_API_KEY']
pm.set_options(flickr_api_key=FLICKR_API_KEY)
photomosaic.flickr.from_search('cats', '~/pools/cats/')
pool = pm.make_pool('~/pools/cats/*.jpg')
pm.export_pool(pool, '~/pools/cats/pool.json') # save color analysis for future reuse
|
Fix check for existing pools.
|
BLD: Fix check for existing pools.
|
Python
|
bsd-3-clause
|
danielballan/photomosaic
|
7d69bcc6474d954b311251bf077750e0418170cb
|
button.py
|
button.py
|
import RPi.GPIO as GPIO
import time
import os
from optparse import OptionParser
# Parse input arguments
parser = OptionParser()
parser.add_option("-t", "--testGPIO", action="store_true", help="Test GPIO connection, does not call the JS script.")
# The option --pin sets the Input Pin for your Button
# It default to GPIO24 or HardwarePin 19
parser.add_option("-p", "--pin", dest="pin", help="GPIO pin to use. If not provided it defaults to HardwarePin 19.", default=19)
(options, args) = parser.parse_args()
testingGPIO = options.testGPIO != None
buttonPin = options.pin
#sets GPIO Mode to use Hardware Pin Layout
GPIO.setmode(GPIO.BCM)
#sets GPIO Pin to INPUT mode with a Pull Down Resistor
GPIO.setup(buttonPin,GPIO.IN, pull_up_down=GPIO.PUD_DOWN)
if(testingGPIO):
print "Press the connected button. If you are pressing but you do not see any further output then....there is something wrong with the connection."
while True:
#waits for Pin Input and then exectures the script below
if (GPIO.input(buttonPin)):
if (testingGPIO):
print "PIN " + buttonPing + " works correctly."
continue
#the script that will be executed (as root)
os.system("node /home/pi/guest-password-printer/index.js")
|
import RPi.GPIO as GPIO
import time
import os
from optparse import OptionParser
# Parse input arguments
parser = OptionParser()
parser.add_option("-t", "--testGPIO", action="store_true", help="Test GPIO connection, does not call the JS script.")
# The option --pin sets the Input Pin for your Button
# It default to GPIO24 or HardwarePin 19
parser.add_option("-p", "--pin", dest="pin", help="GPIO pin to use. If not provided it defaults to HardwarePin 19.", default=19)
(options, args) = parser.parse_args()
testingGPIO = options.testGPIO != None
buttonPin = options.pin
#sets GPIO Mode to use Hardware Pin Layout
GPIO.setmode(GPIO.BCM)
#sets GPIO Pin to INPUT mode with a Pull Down Resistor
GPIO.setup(buttonPin,GPIO.IN, pull_up_down=GPIO.PUD_DOWN)
if(testingGPIO):
print "Press the connected button. If you are pressing but you do not see any further output then....there is something wrong with the connection."
while True:
#waits for Pin Input and then exectures the script below
if (GPIO.input(buttonPin)):
if (testingGPIO):
print "PIN " + buttonPin + " works correctly."
continue
#the script that will be executed (as root)
os.system("node index.js")
|
Fix typo and execute JS script found in local folder.
|
Fix typo and execute JS script found in local folder.
|
Python
|
mit
|
henne-/guest-password-printer,henne-/guest-password-printer
|
6c095c0e14c084666b9417b4bd269f396804bfab
|
src/ensign/_interfaces.py
|
src/ensign/_interfaces.py
|
# pylint: skip-file
from zope.interface import Attribute, Interface
class IFlag(Interface):
"""
Flag Interface.
Any kind of flag must implement this interface.
"""
TYPE = Attribute("""Flag type""")
store = Attribute("""Flag storage backend""")
name = Attribute("""Flag name""")
value = Attribute("""Flag value""")
active = Attribute("""Flag activity indicator""")
info = Attribute("""Flag descriptive information""")
def create(name, store, **kwargs):
"""
Create a new flag with the given name and, optionally, extra data,
persisted in the given store.
"""
def _check():
"""
Check whether the flag current value means the feature is active.
"""
class IStorage(Interface):
"""
Storage Interface.
Any kind of backing storage for flags must implement this interface.
"""
def create(name, type, **kwargs):
"""Create a new flag."""
def exists(name):
"""Check if the flag exists in the store."""
def load(name, type):
"""Load a value."""
def store(name, value, type):
"""Store a value."""
def used(name):
"""Get last used date."""
def info(name):
"""Get flag descriptive information."""
|
# pylint: skip-file
from zope.interface import Attribute, Interface
class IFlag(Interface):
"""
Flag Interface.
Any kind of flag must implement this interface.
"""
TYPE = Attribute("""Flag type""")
store = Attribute("""Flag storage backend""")
name = Attribute("""Flag name""")
value = Attribute("""Flag value""")
active = Attribute("""Flag activity indicator""")
info = Attribute("""Flag descriptive information""")
def create(name, store, **kwargs):
"""
Create a new flag with the given name and, optionally, extra data,
persisted in the given store.
"""
def all(store):
"""
Retrieve all flags in the store.
"""
def _check():
"""
Check whether the flag current value means the feature is active.
"""
class IStorage(Interface):
"""
Storage Interface.
Any kind of backing storage for flags must implement this interface.
"""
def create(name, type, **kwargs):
"""Create a new flag."""
def exists(name):
"""Check if the flag exists in the store."""
def load(name, type):
"""Load a value."""
def store(name, value, type):
"""Store a value."""
def used(name):
"""Get last used date."""
def info(name):
"""Get flag descriptive information."""
def all():
"""Get all flags."""
|
Update interface with the latest changes in functionality.
|
Update interface with the latest changes in functionality.
|
Python
|
isc
|
bolsote/py-cd-talk,bolsote/py-cd-talk
|
f535228e38f33263289f28d46e910ccb0a98a381
|
tournamentcontrol/competition/constants.py
|
tournamentcontrol/competition/constants.py
|
import pytz
from dateutil.rrule import DAILY, WEEKLY
from django.utils.translation import ugettext_lazy as _
GENDER_CHOICES = (
('M', _('Male')),
('F', _('Female')),
('X', _('Unspecified')),
)
SEASON_MODE_CHOICES = (
(WEEKLY, _("Season")),
(DAILY, _("Tournament")),
)
WIN_LOSE = {
'W': _("Winner"),
'L': _("Loser"),
}
###################
# TIME ZONE NAMES #
###################
"""
Ideally this would be a better list for the specific uses of the site in
question. For example, it is perhaps much easier to list just the Australian
time zones for sites deployed for Australian customers.
This is also implemented in touchtechnology.common.forms and should probably
be moved and better leveraged in future release.
See https://bitbucket.org/touchtechnology/common/issue/16/
"""
PYTZ_TIME_ZONE_CHOICES = [('\x20Standard', (('UTC', 'UTC'), ('GMT', 'GMT')))]
for iso, name in pytz.country_names.items():
values = sorted(pytz.country_timezones.get(iso, []))
names = [s.rsplit("/", 1)[1].replace("_", " ") for s in values]
PYTZ_TIME_ZONE_CHOICES.append((name, zip(values, names)))
PYTZ_TIME_ZONE_CHOICES.sort()
|
import pytz
from dateutil.rrule import DAILY, WEEKLY
from django.utils.translation import ugettext_lazy as _
GENDER_CHOICES = (
('M', _('Male')),
('F', _('Female')),
('X', _('Unspecified')),
)
SEASON_MODE_CHOICES = (
(WEEKLY, _("Season")),
(DAILY, _("Tournament")),
)
WIN_LOSE = {
'W': _("Winner"),
'L': _("Loser"),
}
###################
# TIME ZONE NAMES #
###################
"""
Ideally this would be a better list for the specific uses of the site in
question. For example, it is perhaps much easier to list just the Australian
time zones for sites deployed for Australian customers.
This is also implemented in touchtechnology.common.forms and should probably
be moved and better leveraged in future release.
See https://bitbucket.org/touchtechnology/common/issue/16/
"""
PYTZ_TIME_ZONE_CHOICES = [('\x20Standard', (('UTC', 'UTC'), ('GMT', 'GMT')))]
for iso, name in pytz.country_names.items():
values = sorted(pytz.country_timezones.get(iso, []))
names = [s.rsplit("/", 1)[1].replace("_", " ") for s in values]
PYTZ_TIME_ZONE_CHOICES.append((name, [each for each in zip(values, names)]))
PYTZ_TIME_ZONE_CHOICES.sort()
|
Use list comprehension to evaluate PYTZ_TIME_ZONE_CHOICES
|
Use list comprehension to evaluate PYTZ_TIME_ZONE_CHOICES
During Python 3 conversion this must have been missed.
|
Python
|
bsd-3-clause
|
goodtune/vitriolic,goodtune/vitriolic,goodtune/vitriolic,goodtune/vitriolic
|
c0787c468e1b71d7e9db93b5f5990ae9bb506d82
|
pystruct/datasets/dataset_loaders.py
|
pystruct/datasets/dataset_loaders.py
|
import cPickle
from os.path import dirname
from os.path import join
import numpy as np
def load_letters():
"""Load the OCR letters dataset.
This is a chain classification task.
Each example consists of a word, segmented into letters.
The first letter of each word is ommited from the data,
as it was a capital letter (in contrast to all other letters).
"""
module_path = dirname(__file__)
data_file = open(join(module_path, 'letters.pickle'),'rb')
data = cPickle.load(data_file)
# we add an easy to use image representation:
data['images'] = [np.hstack([l.reshape(16, 8) for l in word])
for word in data['data']]
return data
def load_scene():
module_path = dirname(__file__)
data_file = open(join(module_path, 'scene.pickle'))
return cPickle.load(data_file)
def load_snakes():
module_path = dirname(__file__)
data_file = open(join(module_path, 'snakes.pickle'))
return cPickle.load(data_file)
|
import cPickle
from os.path import dirname
from os.path import join
import numpy as np
def load_letters():
"""Load the OCR letters dataset.
This is a chain classification task.
Each example consists of a word, segmented into letters.
The first letter of each word is ommited from the data,
as it was a capital letter (in contrast to all other letters).
"""
module_path = dirname(__file__)
data_file = open(join(module_path, 'letters.pickle'),'rb')
data = cPickle.load(data_file)
# we add an easy to use image representation:
data['images'] = [np.hstack([l.reshape(16, 8) for l in word])
for word in data['data']]
return data
def load_scene():
module_path = dirname(__file__)
data_file = open(join(module_path, 'scene.pickle'),'rb')
return cPickle.load(data_file)
def load_snakes():
module_path = dirname(__file__)
data_file = open(join(module_path, 'snakes.pickle'),'rb')
return cPickle.load(data_file)
|
FIX other two sample data load for Windows
|
FIX other two sample data load for Windows
|
Python
|
bsd-2-clause
|
massmutual/pystruct,pystruct/pystruct,amueller/pystruct,d-mittal/pystruct,wattlebird/pystruct,pystruct/pystruct,d-mittal/pystruct,wattlebird/pystruct,massmutual/pystruct,amueller/pystruct
|
f0ef4f5e269d7f2d7fd347e8f458c1c9ce1ffb34
|
mqueue/hooks/redis/__init__.py
|
mqueue/hooks/redis/__init__.py
|
import redis
import time
from mqueue.conf import DOMAIN
from mqueue.hooks.redis import serializer
from mqueue.conf import HOOKS
conf = HOOKS["redis"]
R = redis.StrictRedis(host=conf["host"], port=conf["port"], db=conf["db"])
event_num = int(time.time())
def save(event, conf):
name = DOMAIN+"_event"+str(event_num)
event.request = event.request.replace("\n", "//")
data = serializer.Pack(event)
R.set(name, data)
|
import redis
import time
from mqueue.conf import DOMAIN
from mqueue.hooks.redis import serializer
from mqueue.conf import HOOKS
conf = HOOKS["redis"]
R = redis.StrictRedis(host=conf["host"], port=conf["port"], db=conf["db"])
event_num = int(time.time())
def save(event, conf):
global event_num
global R
name = DOMAIN + "_event" + str(event_num)
event.request = event.request.replace("\n", "//")
data = serializer.Pack(event)
R.set(name, data)
event_num += 1
|
Fix bug in redis hook
|
Fix bug in redis hook
|
Python
|
mit
|
synw/django-mqueue,synw/django-mqueue,synw/django-mqueue
|
7ee29cfee740d6096fca8379253073077890a54c
|
examples/util/wordcount_redis.py
|
examples/util/wordcount_redis.py
|
from disco.schemes.scheme_redis import redis_output_stream
from disco.worker.task_io import task_output_stream
from disco.core import Job, result_iterator
class WordCount(Job):
reduce_output_stream = (task_output_stream, redis_output_stream)
@staticmethod
def map(line, params):
k, v = line
yield v, 1
@staticmethod
def reduce(iter, params):
from disco.util import kvgroup
for word, counts in kvgroup(sorted(iter)):
yield word, sum(counts)
if __name__ == '__main__':
import sys
if len(sys.argv) != 3:
print "Usage: python wordcount_redis.py <input redis> <output redis>"
sys.exit(1)
from wordcount_redis import WordCount
job = WordCount()
job.params = {}
job.params['url'] = sys.argv[2]
job.run(input=[sys.argv[1]])
job.wait(show=True)
|
"""
Usage:
python wordcount_redis.py redis://redis_server:6379:0 redis://redis_server:6379:1
The input is read from db 0 and the output is written to db 1. The inputs
should be of the form (key, list_of_values) (they are read from the server with the
lrange command. See the redis documentation for more info).
The output will also be of the form (key, list_of_values). The reason we use
this approach is to unify the mechanism for the intermediate input-outputs
(which must be (key, list_of_values) with the inputs and outputs).
"""
from disco.schemes.scheme_redis import redis_output_stream
from disco.worker.task_io import task_output_stream
from disco.core import Job, result_iterator
class WordCount(Job):
reduce_output_stream = (task_output_stream, redis_output_stream)
@staticmethod
def map(line, params):
k, v = line
yield v, 1
@staticmethod
def reduce(iter, params):
from disco.util import kvgroup
for word, counts in kvgroup(sorted(iter)):
yield word, sum(counts)
if __name__ == '__main__':
import sys
if len(sys.argv) != 3:
print "Usage: python wordcount_redis.py <input redis> <output redis>"
sys.exit(1)
from wordcount_redis import WordCount
job = WordCount()
job.params = {}
job.params['url'] = sys.argv[2]
job.run(input=[sys.argv[1]])
job.wait(show=True)
|
Add more info to the redis example.
|
examples: Add more info to the redis example.
|
Python
|
bsd-3-clause
|
seabirdzh/disco,discoproject/disco,oldmantaiter/disco,pooya/disco,oldmantaiter/disco,simudream/disco,pombredanne/disco,seabirdzh/disco,discoproject/disco,simudream/disco,discoproject/disco,ErikDubbelboer/disco,mozilla/disco,mozilla/disco,pombredanne/disco,ErikDubbelboer/disco,mwilliams3/disco,pooya/disco,mwilliams3/disco,pombredanne/disco,beni55/disco,pombredanne/disco,pooya/disco,mwilliams3/disco,pombredanne/disco,beni55/disco,seabirdzh/disco,ktkt2009/disco,ktkt2009/disco,discoproject/disco,seabirdzh/disco,seabirdzh/disco,mwilliams3/disco,beni55/disco,beni55/disco,simudream/disco,ktkt2009/disco,ErikDubbelboer/disco,ktkt2009/disco,mwilliams3/disco,simudream/disco,oldmantaiter/disco,mozilla/disco,ErikDubbelboer/disco,simudream/disco,mozilla/disco,beni55/disco,ErikDubbelboer/disco,pooya/disco,ktkt2009/disco,discoproject/disco,oldmantaiter/disco,oldmantaiter/disco
|
9c7660fd63bc1c48a0533e867c7d18faf9d90c03
|
main.py
|
main.py
|
#!/usr/bin/env python
from morss import main
if __name__ == '__main__':
main()
|
#!/usr/bin/env python
from morss import main, cgi_wrapper as application
if __name__ == '__main__':
main()
|
Make use thru uwsgi easier
|
Make use thru uwsgi easier
Import the main cgi_wrapper as "application" in main.py
|
Python
|
agpl-3.0
|
pictuga/morss,pictuga/morss,pictuga/morss
|
3cff942af436f16aab2078e6aeedd3073f4a5522
|
flask_roots/extension.py
|
flask_roots/extension.py
|
from __future__ import absolute_import
import os
from flask.ext.sqlalchemy import SQLAlchemy
from flask.ext.images import Images
# from flask.ext.mail import Mail
from flask.ext.login import LoginManager
from flask.ext.acl import AuthManager
class Roots(object):
def __init__(self, app):
self.extensions = {}
self.init_app(app)
def init_app(self, app):
# Establish two-way links.
self.app = app
app.roots = self
app.extensions['roots'] = self
from .config import setup_config
setup_config(app)
from .logs import setup_logs
setup_logs(app)
from .session import setup_session
setup_session(app)
self.extensions['login_manager'] = LoginManager(app)
self.extensions['auth'] = AuthManager(app)
from .mako import MakoTemplates
self.extensions['mako'] = MakoTemplates(app)
self.extensions['images'] = Images(app)
self.extensions['db'] = db = SQLAlchemy(app)
db.metadata.bind = db.engine # WTF do I need to do this for?!
from .routing import setup_routing
setup_routing(app)
from .errors import setup_errors
setup_errors(app)
|
from __future__ import absolute_import
import os
from flask.ext.sqlalchemy import SQLAlchemy
from flask.ext.images import Images
from flask.ext.mail import Mail
from flask.ext.login import LoginManager
from flask.ext.acl import AuthManager
class Roots(object):
def __init__(self, app):
self.extensions = {}
self.init_app(app)
def init_app(self, app):
# Establish two-way links.
self.app = app
app.roots = self
app.extensions['roots'] = self
from .config import setup_config
setup_config(app)
from .logs import setup_logs
setup_logs(app)
from .session import setup_session
setup_session(app)
self.extensions['login_manager'] = login = LoginManager(app)
login.user_callback = lambda uid: None
self.extensions['auth'] = AuthManager(app)
from .mako import MakoTemplates
self.extensions['mako'] = MakoTemplates(app)
self.extensions['images'] = Images(app)
self.extensions['db'] = db = SQLAlchemy(app)
db.metadata.bind = db.engine # WTF do I need to do this for?!
self.extensions['mail'] = Mail(app)
from .routing import setup_routing
setup_routing(app)
from .errors import setup_errors
setup_errors(app)
|
Add Flask-Mail, and null user loader
|
Add Flask-Mail, and null user loader
|
Python
|
bsd-3-clause
|
mikeboers/Flask-Roots,mikeboers/Flask-Roots
|
0c0a1d0ec480c7df9dd8821d40af7791e46db453
|
tests/lib/test_finance.py
|
tests/lib/test_finance.py
|
# Copyright (c) 2013 The Pycroft Authors. See the AUTHORS file.
# This file is part of the Pycroft project and licensed under the terms of
# the Apache License, Version 2.0. See the LICENSE file for details.
from tests import OldPythonTestCase
__author__ = 'felix_kluge'
from pycroft.lib.finance import create_semester
from pycroft.lib.config import get,config
from pycroft.model.finance import FinanceAccount
from sqlalchemy.orm import backref
from pycroft.model import session
import time
from datetime import date
class Test_010_Semester(OldPythonTestCase):
def test_0010_create_semester_accounts(self):
"""
This test should verify that all semester-related finance-accounts have
been created.
"""
new_semester = create_semester("NewSemesterName", 2500, 1500, date(2013, 9, 1), date(2014, 2, 1))
config._configpath = "../tests/example/test_config.json"
for account in config["finance"]["semester_accounts"]:
for new_account in new_semester.accounts:
if(new_account.tag == account["tag"]):
new_account_equivalent = new_account
compare_account = FinanceAccount(type=account["type"],name=account["name"],semester=new_semester,tag=account["tag"])
self.assertEqual(new_account_equivalent.name, compare_account.name)
self.assertEqual(new_account_equivalent.type, compare_account.type)
|
# Copyright (c) 2013 The Pycroft Authors. See the AUTHORS file.
# This file is part of the Pycroft project and licensed under the terms of
# the Apache License, Version 2.0. See the LICENSE file for details.
from tests import OldPythonTestCase
__author__ = 'felix_kluge'
from pycroft.lib.finance import create_semester, import_csv
from pycroft.lib.config import get, config
from pycroft.model.finance import FinanceAccount, Journal, JournalEntry
from sqlalchemy.orm import backref
from pycroft.model import session
import time
from datetime import date, datetime
class Test_010_Semester(OldPythonTestCase):
def test_0010_create_semester_accounts(self):
"""
This test should verify that all semester-related finance-accounts have
been created.
"""
new_semester = create_semester("NewSemesterName",
2500, 1500,
date(2013, 9, 1),
date(2014, 2, 1))
config._configpath = "../tests/example/test_config.json"
for account in config["finance"]["semester_accounts"]:
new_created_account = FinanceAccount.q.filter(
FinanceAccount.semester == new_semester,
FinanceAccount.tag == account["tag"]).first()
self.assertEqual(new_created_account.name, account["name"])
self.assertEqual(new_created_account.type, account["type"])
session.session.commit()
|
Fix for wrong test: create_semester_accounts
|
Fix for wrong test: create_semester_accounts
refs #448
|
Python
|
apache-2.0
|
agdsn/pycroft,agdsn/pycroft,lukasjuhrich/pycroft,lukasjuhrich/pycroft,lukasjuhrich/pycroft,lukasjuhrich/pycroft,agdsn/pycroft,agdsn/pycroft,agdsn/pycroft
|
169a8612eb06410a5ae7e110227f7bea010d2ba9
|
tests/test_ghostscript.py
|
tests/test_ghostscript.py
|
import subprocess
import unittest
class GhostscriptTest(unittest.TestCase):
def test_installed(self):
process = subprocess.Popen(
['gs', '--version'],
stdin=None,
stdout=subprocess.PIPE,
stderr=subprocess.PIPE,
)
stdout, stderr = process.communicate()
self.assertEqual(process.returncode, 0)
self.assertEqual(stderr, "")
self.assertRegexpMatches(stdout, r'9\.\d\d')
|
import subprocess
import unittest
class GhostscriptTest(unittest.TestCase):
def test_installed(self):
process = subprocess.Popen(
['gs', '--version'],
stdin=None,
stdout=subprocess.PIPE,
stderr=subprocess.PIPE,
)
stdout, stderr = process.communicate()
self.assertEqual(process.returncode, 0)
self.assertEqual(str(stderr), "")
self.assertRegexpMatches(str(stdout), r'9\.\d\d')
|
Make stdout and stderr into strings.
|
Make stdout and stderr into strings.
|
Python
|
mit
|
YPlan/treepoem
|
ba37080645153d66a8ae1c8df10312806999f8ec
|
tests/test_observation.py
|
tests/test_observation.py
|
import unittest
from datetime import datetime
from dateutil.tz import tzutc
from fmi import FMI
class TestObservations(unittest.TestCase):
def test_lappeenranta(self):
now = datetime.now(tz=tzutc())
f = FMI(place='Lappeenranta')
for point in f.observations():
assert point.time < now
assert isinstance(point.temperature, float)
|
import unittest
from datetime import datetime
from dateutil.tz import tzutc
from fmi import FMI
class TestObservations(unittest.TestCase):
def test_lappeenranta(self):
now = datetime.now(tz=tzutc())
f = FMI(place='Lappeenranta')
for point in f.observations():
assert point.time < now
assert isinstance(point.temperature, float)
for point in f.observations(fmisid=101237):
assert point.time < now
assert isinstance(point.temperature, float)
|
Add use of fmisid to tests.
|
Add use of fmisid to tests.
|
Python
|
mit
|
kipe/fmi
|
9369f72c4fe9a544e24f10a1db976589dc013424
|
plinth/modules/sso/__init__.py
|
plinth/modules/sso/__init__.py
|
#
# This file is part of Plinth.
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU Affero General Public License as
# published by the Free Software Foundation, either version 3 of the
# License, or (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU Affero General Public License for more details.
#
# You should have received a copy of the GNU Affero General Public License
# along with this program. If not, see <http://www.gnu.org/licenses/>.
#
"""
Plinth module to configure Single Sign On services.
"""
from plinth import actions
from django.utils.translation import ugettext_lazy as _
version = 1
is_essential = True
depends = ['security']
name = _('Single Sign On')
managed_packages = ['libapache2-mod-auth-pubtkt', 'openssl', 'python3-openssl']
def setup(helper, old_version=None):
"""Install the required packages"""
helper.install(managed_packages)
actions.superuser_run('auth-pubtkt', ['enable-mod'])
actions.superuser_run('auth-pubtkt', ['create-key-pair'])
|
#
# This file is part of Plinth.
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU Affero General Public License as
# published by the Free Software Foundation, either version 3 of the
# License, or (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU Affero General Public License for more details.
#
# You should have received a copy of the GNU Affero General Public License
# along with this program. If not, see <http://www.gnu.org/licenses/>.
#
"""
Plinth module to configure Single Sign On services.
"""
from plinth import actions
from django.utils.translation import ugettext_lazy as _
version = 1
is_essential = True
depends = ['security', 'apache']
name = _('Single Sign On')
managed_packages = ['libapache2-mod-auth-pubtkt', 'openssl', 'python3-openssl']
def setup(helper, old_version=None):
"""Install the required packages"""
helper.install(managed_packages)
actions.superuser_run('auth-pubtkt', ['enable-mod'])
actions.superuser_run('auth-pubtkt', ['create-key-pair'])
|
Add dependency on apache module
|
sso: Add dependency on apache module
This ensures that Apache is fully setup before setting up mod-auth-pubtkt.
Signed-off-by: Sunil Mohan Adapa <3eaa7035e78e5eca849aa1e8ea4aaf97b4588601@medhas.org>
Reviewed-by: James Valleroy <46e3063862880873c8617774e45d63de6172aab0@mailbox.org>
|
Python
|
agpl-3.0
|
kkampardi/Plinth,harry-7/Plinth,kkampardi/Plinth,harry-7/Plinth,harry-7/Plinth,kkampardi/Plinth,kkampardi/Plinth,harry-7/Plinth,kkampardi/Plinth,harry-7/Plinth
|
ee98b5a5c6b82671738bc60e68ea87d838c5400f
|
migrations/0020_change_ds_name_to_non_uniqe.py
|
migrations/0020_change_ds_name_to_non_uniqe.py
|
from redash.models import db
import peewee
from playhouse.migrate import PostgresqlMigrator, migrate
if __name__ == '__main__':
migrator = PostgresqlMigrator(db.database)
with db.database.transaction():
# Change the uniqueness constraint on data source name to be (org, name):
success = False
for index_name in ['unique_name', 'data_sources_name']:
try:
print "Trying to remove data source name uniqueness index with the name: {}".format(index_name)
migrate(migrator.drop_index("data_sources", index_name))
print "Success!"
success = True
break
except peewee.ProgrammingError:
db.close_db(None)
if not success:
print "Failed removing uniqueness constraint on data source name."
print "Please verify its name in the schema, update the migration and run again."
exit(1)
migrate(
migrator.add_index('data_sources', ('org_id', 'name'), unique=True)
)
db.close_db(None)
|
from redash.models import db
import peewee
from playhouse.migrate import PostgresqlMigrator, migrate
if __name__ == '__main__':
migrator = PostgresqlMigrator(db.database)
with db.database.transaction():
# Change the uniqueness constraint on data source name to be (org, name):
# In some cases it's a constraint:
db.database.execute_sql('ALTER TABLE data_sources DROP CONSTRAINT IF EXISTS unique_name')
# In others only an index:
db.database.execute_sql('DROP INDEX IF EXISTS data_sources_name')
migrate(
migrator.add_index('data_sources', ('org_id', 'name'), unique=True)
)
db.close_db(None)
|
Improve the migration for unique data source name
|
Improve the migration for unique data source name
|
Python
|
bsd-2-clause
|
ninneko/redash,EverlyWell/redash,hudl/redash,useabode/redash,pubnative/redash,chriszs/redash,akariv/redash,alexanderlz/redash,easytaxibr/redash,pubnative/redash,amino-data/redash,rockwotj/redash,ninneko/redash,guaguadev/redash,rockwotj/redash,denisov-vlad/redash,imsally/redash,ninneko/redash,useabode/redash,crowdworks/redash,EverlyWell/redash,jmvasquez/redashtest,hudl/redash,denisov-vlad/redash,moritz9/redash,stefanseifert/redash,alexanderlz/redash,alexanderlz/redash,chriszs/redash,rockwotj/redash,M32Media/redash,vishesh92/redash,stefanseifert/redash,easytaxibr/redash,EverlyWell/redash,pubnative/redash,44px/redash,ninneko/redash,hudl/redash,amino-data/redash,M32Media/redash,moritz9/redash,guaguadev/redash,chriszs/redash,chriszs/redash,44px/redash,imsally/redash,EverlyWell/redash,amino-data/redash,44px/redash,guaguadev/redash,guaguadev/redash,denisov-vlad/redash,44px/redash,easytaxibr/redash,hudl/redash,getredash/redash,moritz9/redash,ninneko/redash,imsally/redash,imsally/redash,M32Media/redash,jmvasquez/redashtest,easytaxibr/redash,crowdworks/redash,stefanseifert/redash,akariv/redash,moritz9/redash,pubnative/redash,useabode/redash,getredash/redash,crowdworks/redash,pubnative/redash,vishesh92/redash,jmvasquez/redashtest,amino-data/redash,denisov-vlad/redash,getredash/redash,M32Media/redash,vishesh92/redash,guaguadev/redash,jmvasquez/redashtest,easytaxibr/redash,stefanseifert/redash,useabode/redash,akariv/redash,akariv/redash,akariv/redash,alexanderlz/redash,stefanseifert/redash,getredash/redash,vishesh92/redash,getredash/redash,rockwotj/redash,denisov-vlad/redash,crowdworks/redash,jmvasquez/redashtest
|
ca15e6523bd34e551528dce6c6ee3dcb70cf7806
|
pyinfra/modules/util/files.py
|
pyinfra/modules/util/files.py
|
# pyinfra
# File: pyinfra/modules/util/files.py
# Desc: common functions for handling the filesystem
from types import NoneType
def ensure_mode_int(mode):
# Already an int (/None)?
if isinstance(mode, (int, NoneType)):
return mode
try:
# Try making an int ('700' -> 700)
return int(mode)
except (TypeError, ValueError):
pass
# Return as-is (ie +x which we don't need to normalise, it always gets run)
return mode
def sed_replace(state, filename, line, replace, flags=None):
flags = ''.join(flags) if flags else ''
line = line.replace('/', '\/')
replace = replace.replace('/', '\/')
temp_filename = state.get_temp_filename()
return 'sed "s/{0}/{1}/{2}" {3} > {4} && mv {4} {3}'.format(
line, replace, flags, filename, temp_filename
)
def chmod(target, mode, recursive=False):
return 'chmod {0}{1} {2}'.format(('-R ' if recursive else ''), mode, target)
def chown(target, user, group=None, recursive=False):
command = 'chown'
user_group = None
if user and group:
user_group = '{0}:{1}'.format(user, group)
elif user:
user_group = user
elif group:
command = 'chgrp'
user_group = group
return '{0}{1} {2} {3}'.format(
command,
' -R' if recursive else '',
user_group,
target
)
|
# pyinfra
# File: pyinfra/modules/util/files.py
# Desc: common functions for handling the filesystem
from types import NoneType
def ensure_mode_int(mode):
# Already an int (/None)?
if isinstance(mode, (int, NoneType)):
return mode
try:
# Try making an int ('700' -> 700)
return int(mode)
except (TypeError, ValueError):
pass
# Return as-is (ie +x which we don't need to normalise, it always gets run)
return mode
def sed_replace(state, filename, line, replace, flags=None):
flags = ''.join(flags) if flags else ''
line = line.replace('/', '\/')
replace = replace.replace('/', '\/')
return 'sed -i "s/{0}/{1}/{2}" {3}'.format(
line, replace, flags, filename
)
def chmod(target, mode, recursive=False):
return 'chmod {0}{1} {2}'.format(('-R ' if recursive else ''), mode, target)
def chown(target, user, group=None, recursive=False):
command = 'chown'
user_group = None
if user and group:
user_group = '{0}:{1}'.format(user, group)
elif user:
user_group = user
elif group:
command = 'chgrp'
user_group = group
return '{0}{1} {2} {3}'.format(
command,
' -R' if recursive else '',
user_group,
target
)
|
Use sed inline (unsure why mv was used originally).
|
Use sed inline (unsure why mv was used originally).
|
Python
|
mit
|
Fizzadar/pyinfra,Fizzadar/pyinfra
|
5a4d9255c59be0d5dda8272e0e7ced71822f4d40
|
prime-factors/prime_factors.py
|
prime-factors/prime_factors.py
|
import sieve
def prime_factors(n):
primes = sieve.sieve(n)
factors = []
for p in primes:
while n % p == 0:
factors += [p]
n //= p
return factors
|
def prime_factors(n):
factors = []
factor = 2
while n != 1:
while n % factor == 0:
factors += [factor]
n //= factor
factor += 1
return factors
|
Fix memory issues by just trying every number
|
Fix memory issues by just trying every number
|
Python
|
agpl-3.0
|
CubicComet/exercism-python-solutions
|
8ea3350c6944946b60732308c912dc240952237c
|
project/settings_production.py
|
project/settings_production.py
|
from .settings import *
# Update SITE infos to use the common port 80 to publish the webapp
SITE_FIXED = {
'name': "Recalbox Manager",
'ip': None, # If 'None' find the ip automatically. Use a string to define another ip/hostname
'port': None, # If 'None' no port is added to hostname, so the server have to be reachable from port 80
}
# Production path to the Recalbox logs file
RECALBOX_LOGFILE_PATH = "/recalbox/share/system/logs"
# Use packaged assets
ASSETS_PACKAGED = True
|
from .settings import *
# Update SITE infos to use the common port 80 to publish the webapp
SITE_FIXED = {
'name': "Recalbox Manager",
'ip': None, # If 'None' find the ip automatically. Use a string to define another ip/hostname
'port': None, # If 'None' no port is added to hostname, so the server have to be reachable from port 80
}
# Production path to the Recalbox logs file
RECALBOX_LOGFILE_PATH = "/root/recalbox.log"
# Use packaged assets
ASSETS_PACKAGED = True
|
Revert "Set the right recalbox.log path"
|
Revert "Set the right recalbox.log path"
|
Python
|
mit
|
recalbox/recalbox-manager,recalbox/recalbox-manager,recalbox/recalbox-manager,sveetch/recalbox-manager,sveetch/recalbox-manager,sveetch/recalbox-manager,sveetch/recalbox-manager,recalbox/recalbox-manager,sveetch/recalbox-manager,recalbox/recalbox-manager
|
fd4688cc899b08253cc50b345bb7e836081783d8
|
bayespy/inference/vmp/nodes/__init__.py
|
bayespy/inference/vmp/nodes/__init__.py
|
######################################################################
# Copyright (C) 2011,2012 Jaakko Luttinen
#
# This file is licensed under Version 3.0 of the GNU General Public
# License. See LICENSE for a text of the license.
######################################################################
######################################################################
# This file is part of BayesPy.
#
# BayesPy is free software: you can redistribute it and/or modify it
# under the terms of the GNU General Public License version 3 as
# published by the Free Software Foundation.
#
# BayesPy is distributed in the hope that it will be useful, but
# WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
# General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with BayesPy. If not, see <http://www.gnu.org/licenses/>.
######################################################################
# Import some most commonly used nodes
from . import *
from .gaussian import Gaussian, GaussianARD
from .wishart import Wishart
from .gamma import Gamma
from .dirichlet import Dirichlet
from .categorical import Categorical
from .dot import Dot, SumMultiply
from .mixture import Mixture
from .gaussian_markov_chain import GaussianMarkovChain
from .gaussian_markov_chain import VaryingGaussianMarkovChain
from .gaussian_markov_chain import SwitchingGaussianMarkovChain
from .categorical_markov_chain import CategoricalMarkovChain
|
######################################################################
# Copyright (C) 2011,2012 Jaakko Luttinen
#
# This file is licensed under Version 3.0 of the GNU General Public
# License. See LICENSE for a text of the license.
######################################################################
######################################################################
# This file is part of BayesPy.
#
# BayesPy is free software: you can redistribute it and/or modify it
# under the terms of the GNU General Public License version 3 as
# published by the Free Software Foundation.
#
# BayesPy is distributed in the hope that it will be useful, but
# WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
# General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with BayesPy. If not, see <http://www.gnu.org/licenses/>.
######################################################################
# Import some most commonly used nodes
from . import *
from .binomial import Binomial
from .categorical import Categorical
from .beta import Beta
from .dirichlet import Dirichlet
from .gaussian import Gaussian, GaussianARD
from .wishart import Wishart
from .gamma import Gamma
from .gaussian_markov_chain import GaussianMarkovChain
from .gaussian_markov_chain import VaryingGaussianMarkovChain
from .gaussian_markov_chain import SwitchingGaussianMarkovChain
from .categorical_markov_chain import CategoricalMarkovChain
from .mixture import Mixture
from .dot import Dot
from .dot import SumMultiply
|
Add Beta and Binomial to automatically imported nodes
|
ENH: Add Beta and Binomial to automatically imported nodes
|
Python
|
mit
|
jluttine/bayespy,SalemAmeen/bayespy,fivejjs/bayespy,bayespy/bayespy
|
06d0287a8fef0679b281296e6ed76e0b6c803acb
|
sorl/thumbnail/management/commands/thumbnail.py
|
sorl/thumbnail/management/commands/thumbnail.py
|
from django.core.management.base import BaseCommand, CommandError
from sorl.thumbnail.conf import settings
from sorl.thumbnail import default
class Command(BaseCommand):
help = (
u'Handles thumbnails and key value store'
)
args = '[cleanup, clear]'
option_list = BaseCommand.option_list
def handle(self, *labels, **options):
verbosity = int(options.get('verbosity'))
if len(labels) != 1:
raise CommandError('`%s` is not a valid argument' % labels)
label = labels[0]
if label not in ['cleanup', 'clear']:
raise CommandError('`%s` unknown action' % label)
if label == 'cleanup':
if verbosity >= 1:
self.stdout.write("Cleanup thumbnails ... ")
default.kvstore.cleanup()
if verbosity >= 1:
self.stdout.write("[Done]\n")
if label == 'clear':
if verbosity >= 1:
self.stdout.write("Clear the Key Value Store ... ")
default.kvstore.clear()
if verbosity >= 1:
self.stdout.write("[Done]\n")
|
import sys
from django.core.management.base import BaseCommand, CommandError
from sorl.thumbnail import default
class Command(BaseCommand):
help = (
u'Handles thumbnails and key value store'
)
args = '[cleanup, clear]'
option_list = BaseCommand.option_list
def handle(self, *labels, **options):
verbosity = int(options.get('verbosity'))
if not labels:
print self.print_help('thumbnail', '')
sys.exit(1)
if len(labels) != 1:
raise CommandError('`%s` is not a valid argument' % labels)
label = labels[0]
if label not in ['cleanup', 'clear']:
raise CommandError('`%s` unknown action' % label)
if label == 'cleanup':
if verbosity >= 1:
self.stdout.write("Cleanup thumbnails ... ", ending=' ... ')
default.kvstore.cleanup()
if verbosity >= 1:
self.stdout.write("[Done]")
elif label == 'clear':
if verbosity >= 1:
self.stdout.write("Clear the Key Value Store", ending=' ... ')
default.kvstore.clear()
if verbosity >= 1:
self.stdout.write("[Done]")
|
Improve management command to clear or clean kvstore
|
Improve management command to clear or clean kvstore
|
Python
|
bsd-3-clause
|
mariocesar/sorl-thumbnail,perdona/sorl-thumbnail,fdgogogo/sorl-thumbnail,Knotis/sorl-thumbnail,jcupitt/sorl-thumbnail,einvalentin/sorl-thumbnail,fladi/sorl-thumbnail,lampslave/sorl-thumbnail,seedinvest/sorl-thumbnail,guilouro/sorl-thumbnail,TriplePoint-Software/sorl-thumbnail,jazzband/sorl-thumbnail,jcupitt/sorl-thumbnail,lampslave/sorl-thumbnail,Knotis/sorl-thumbnail,mcenirm/sorl-thumbnail,JordanReiter/sorl-thumbnail,fdgogogo/sorl-thumbnail,Knotis/sorl-thumbnail,mariocesar/sorl-thumbnail,Resmin/sorl-thumbnail,leture/sorl-thumbnail,jazzband/sorl-thumbnail,einvalentin/sorl-thumbnail,TriplePoint-Software/sorl-thumbnail,lampslave/sorl-thumbnail,jannon/sorl-thumbnail,Resmin/sorl-thumbnail,MatthewWilkes/sorl-thumbnail,perdona/sorl-thumbnail,einvalentin/sorl-thumbnail,mariocesar/sorl-thumbnail,CGenie/sorl-thumbnail,jannon/sorl-thumbnail,leture/sorl-thumbnail,MatthewWilkes/sorl-thumbnail,guilouro/sorl-thumbnail,gregplaysguitar/sorl-thumbnail,jannon/sorl-thumbnail,mcenirm/sorl-thumbnail,MatthewWilkes/sorl-thumbnail,gregplaysguitar/sorl-thumbnail,guilouro/sorl-thumbnail,seedinvest/sorl-thumbnail,chriscauley/sorl-thumbnail,seedinvest/sorl-thumbnail,chriscauley/sorl-thumbnail,CGenie/sorl-thumbnail,TriplePoint-Software/sorl-thumbnail,perdona/sorl-thumbnail,jcupitt/sorl-thumbnail,jazzband/sorl-thumbnail,JordanReiter/sorl-thumbnail,mcenirm/sorl-thumbnail,leture/sorl-thumbnail,fdgogogo/sorl-thumbnail,chriscauley/sorl-thumbnail,fladi/sorl-thumbnail,JordanReiter/sorl-thumbnail,CGenie/sorl-thumbnail,gregplaysguitar/sorl-thumbnail,Resmin/sorl-thumbnail
|
5c97b9911a2dafde5fd1e4c40cda4e84974eb855
|
assembla/lib.py
|
assembla/lib.py
|
from functools import wraps
class AssemblaObject(object):
"""
Proxies getitem calls (eg: `instance['id']`) to a dictionary `instance.data['id']`.
"""
def __init__(self, data):
self.data = data
def __getitem__(self, key):
return self.data[key]
def keys(self):
return self.data.keys()
def values(self):
return self.data.values()
def get(self, *args, **kwargs):
return self.data.get(*args, **kwargs)
def assembla_filter(func):
"""
Filters :data for the objects in it which possess attributes equal in
name/value to a key/value in kwargs.
Each key/value combination in kwargs is compared against the object, so
multiple keyword arguments can be passed in to constrain the filtering.
"""
@wraps(func)
def wrapper(class_instance, **kwargs):
results = func(class_instance)
if not kwargs:
return results
else:
return filter(
# Find the objects who have an equal number of matching attr/value
# combinations as `len(kwargs)`
lambda obj: len(kwargs) == len(
filter(
lambda boolean: boolean,
[obj.get(attr_name) == value
for attr_name, value in kwargs.iteritems()]
)
),
results
)
return wrapper
|
from functools import wraps
class AssemblaObject(object):
"""
Proxies getitem calls (eg: `instance['id']`) to a dictionary `instance.data['id']`.
"""
def __init__(self, data):
self.data = data
def __getitem__(self, key):
return self.data[key]
def __setitem__(self, key, value):
self.data[key] = value
def keys(self):
return self.data.keys()
def values(self):
return self.data.values()
def get(self, *args, **kwargs):
return self.data.get(*args, **kwargs)
def __repr__(self):
if 'name' in self.data:
return "<%s: %s>" % (type(self).__name__, self.data['name'])
if ('number' in self.data) and ('summary' in self.data):
return "<%s: #%s - %s>" % (type(self).__name__, self.data['number'], self.data['summary'])
return super(AssemblaObject, self).__repr__()
def assembla_filter(func):
"""
Filters :data for the objects in it which possess attributes equal in
name/value to a key/value in kwargs.
Each key/value combination in kwargs is compared against the object, so
multiple keyword arguments can be passed in to constrain the filtering.
"""
@wraps(func)
def wrapper(class_instance, **kwargs):
results = func(class_instance)
if not kwargs:
return results
else:
return filter(
# Find the objects who have an equal number of matching attr/value
# combinations as `len(kwargs)`
lambda obj: len(kwargs) == len(
filter(
lambda boolean: boolean,
[obj.get(attr_name) == value
for attr_name, value in kwargs.iteritems()]
)
),
results
)
return wrapper
|
Allow keys to be set (in anticipation of write commands). Better object __repr__() for spaces and tickets.
|
Allow keys to be set (in anticipation of write commands). Better object __repr__() for spaces and tickets.
|
Python
|
mit
|
markfinger/assembla
|
07f86c47c58d6266bd4b42c81521001aca072ff1
|
jsonconfigparser/test/__init__.py
|
jsonconfigparser/test/__init__.py
|
import unittest
from jsonconfigparser import JSONConfigParser
class JSONConfigTestCase(unittest.TestCase):
def test_init(self):
JSONConfigParser()
def test_read_string(self):
string = '[section]\n' + \
'foo = "bar"\n'
cf = JSONConfigParser()
cf.read_string(string)
self.assertEqual(cf.get('section', 'foo'), 'bar')
def test_get(self):
cf = JSONConfigParser()
cf.add_section('section')
cf.set('section', 'section', 'set-in-section')
self.assertEqual(cf.get('section', 'section'), 'set-in-section')
cf.set(cf.default_section, 'defaults', 'set-in-defaults')
self.assertEqual(cf.get('section', 'defaults'), 'set-in-defaults')
self.assertEqual(cf.get('section', 'vars',
vars={'vars': 'set-in-vars'}),
'set-in-vars')
self.assertEqual(cf.get('section', 'unset', 'fallback'), 'fallback')
suite = unittest.TestLoader().loadTestsFromTestCase(JSONConfigTestCase)
|
import unittest
from jsonconfigparser import JSONConfigParser
class JSONConfigTestCase(unittest.TestCase):
def test_init(self):
JSONConfigParser()
def test_read_string(self):
string = '[section]\n' + \
'# comment comment\n' + \
'foo = "bar"\n' + \
'\n' + \
'[section2]\n' + \
'bar = "baz"\n'
cf = JSONConfigParser()
cf.read_string(string)
self.assertEqual(cf.get('section', 'foo'), 'bar')
def test_get(self):
cf = JSONConfigParser()
cf.add_section('section')
cf.set('section', 'section', 'set-in-section')
self.assertEqual(cf.get('section', 'section'), 'set-in-section')
cf.set(cf.default_section, 'defaults', 'set-in-defaults')
self.assertEqual(cf.get('section', 'defaults'), 'set-in-defaults')
self.assertEqual(cf.get('section', 'vars',
vars={'vars': 'set-in-vars'}),
'set-in-vars')
self.assertEqual(cf.get('section', 'unset', 'fallback'), 'fallback')
suite = unittest.TestLoader().loadTestsFromTestCase(JSONConfigTestCase)
|
Add some more rubbish to example string
|
Add some more rubbish to example string
|
Python
|
bsd-3-clause
|
bwhmather/json-config-parser
|
e0dac0a621cbeed615553e5c3544f9c49de96eb2
|
metadata/FrostNumberModel/hooks/pre-stage.py
|
metadata/FrostNumberModel/hooks/pre-stage.py
|
"""A hook for modifying parameter values read from the WMT client."""
import os
import shutil
from wmt.utils.hook import find_simulation_input_file
from topoflow_utils.hook import assign_parameters
file_list = []
def execute(env):
"""Perform pre-stage tasks for running a component.
Parameters
----------
env : dict
A dict of component parameter values from WMT.
"""
env['end_year'] = long(env['start_year']) + long(env['_run_duration'])
env['fn_out_filename'] = 'frostnumber_output.dat'
assign_parameters(env, file_list)
for fname in file_list:
src = find_simulation_input_file(env[fname])
shutil.copy(src, os.curdir)
|
"""A hook for modifying parameter values read from the WMT client."""
import os
import shutil
from wmt.utils.hook import find_simulation_input_file, yaml_dump
from topoflow_utils.hook import assign_parameters
file_list = []
def execute(env):
"""Perform pre-stage tasks for running a component.
Parameters
----------
env : dict
A dict of component parameter values from WMT.
"""
env['end_year'] = long(env['start_year']) + long(env['_run_duration']) - 1
env['fn_out_filename'] = 'frostnumber_output.dat'
assign_parameters(env, file_list)
for fname in file_list:
src = find_simulation_input_file(env[fname])
shutil.copy(src, os.curdir)
yaml_dump('_env.yaml', env)
|
Subtract 1 from model end_year
|
Subtract 1 from model end_year
This matches the behavior of the FrostNumberModel BMI.
|
Python
|
mit
|
csdms/wmt-metadata
|
9d29061f8520506d798ad75aa296be8dc838aaf7
|
resolwe/elastic/pagination.py
|
resolwe/elastic/pagination.py
|
""".. Ignore pydocstyle D400.
==================
Elastic Paginators
==================
Paginator classes used in Elastic app.
.. autoclass:: resolwe.elastic.pagination.LimitOffsetPostPagination
"""
from __future__ import absolute_import, division, print_function, unicode_literals
from rest_framework.pagination import LimitOffsetPagination, _positive_int
def get_query_param(request, key):
"""Get query parameter uniformly for GET and POST requests."""
value = request.query_params.get(key) or request.data.get(key)
if value is None:
raise KeyError()
return value
class LimitOffsetPostPagination(LimitOffsetPagination):
"""Limit/offset paginator.
This is standard limit/offset paginator from Django REST framework,
with difference that it supports passing ``limit`` and ``offset``
attributes also in the body of the request (not just as query
parameter).
"""
def get_limit(self, request):
"""Return limit parameter."""
if self.limit_query_param:
try:
print(get_query_param(request, self.limit_query_param))
return _positive_int(
get_query_param(request, self.limit_query_param),
strict=True,
cutoff=self.max_limit
)
except (KeyError, ValueError):
pass
return self.default_limit
def get_offset(self, request):
"""Return offset parameter."""
try:
return _positive_int(
get_query_param(request, self.offset_query_param),
)
except (KeyError, ValueError):
return 0
|
""".. Ignore pydocstyle D400.
==================
Elastic Paginators
==================
Paginator classes used in Elastic app.
.. autoclass:: resolwe.elastic.pagination.LimitOffsetPostPagination
"""
from __future__ import absolute_import, division, print_function, unicode_literals
from rest_framework.pagination import LimitOffsetPagination, _positive_int
def get_query_param(request, key):
"""Get query parameter uniformly for GET and POST requests."""
value = request.query_params.get(key) or request.data.get(key)
if value is None:
raise KeyError()
return value
class LimitOffsetPostPagination(LimitOffsetPagination):
"""Limit/offset paginator.
This is standard limit/offset paginator from Django REST framework,
with difference that it supports passing ``limit`` and ``offset``
attributes also in the body of the request (not just as query
parameter).
"""
def get_limit(self, request):
"""Return limit parameter."""
if self.limit_query_param:
try:
return _positive_int(
get_query_param(request, self.limit_query_param),
strict=True,
cutoff=self.max_limit
)
except (KeyError, ValueError):
pass
return self.default_limit
def get_offset(self, request):
"""Return offset parameter."""
try:
return _positive_int(
get_query_param(request, self.offset_query_param),
)
except (KeyError, ValueError):
return 0
|
Remove leftover print call in paginator
|
Remove leftover print call in paginator
|
Python
|
apache-2.0
|
genialis/resolwe,jberci/resolwe,genialis/resolwe,jberci/resolwe
|
61e4693988c5b89b4a82457181813e7a6e73403b
|
utils/text.py
|
utils/text.py
|
import codecs
from django.core import exceptions
from django.utils import text
import translitcodec
def slugify(model, field, value, validator):
orig_slug = slug = text.slugify(codecs.encode(value, 'translit/long'))[:45]
i = 0
while True:
try:
try:
validator(slug)
except exceptions.ValidationError:
pass
else:
model.objects.get(**{field: slug})
i += 1
slug = orig_slug + '-' + str(i)
except model.DoesNotExist:
return slug
|
import codecs
from django.core import exceptions
from django.utils import text
import translitcodec
def no_validator(arg):
pass
def slugify(model, field, value, validator=no_validator):
orig_slug = slug = text.slugify(codecs.encode(value, 'translit/long'))[:45]
i = 0
while True:
try:
try:
validator(slug)
except exceptions.ValidationError:
pass
else:
model.objects.get(**{field: slug})
i += 1
slug = orig_slug + '-' + str(i)
except model.DoesNotExist:
return slug
|
Fix slugify for use without validator
|
Fix slugify for use without validator
|
Python
|
agpl-3.0
|
stadtgestalten/stadtgestalten,stadtgestalten/stadtgestalten,stadtgestalten/stadtgestalten
|
7c74017bc0d76ecb34e3fab44767290f51d98a09
|
humbug/test_settings.py
|
humbug/test_settings.py
|
from settings import *
DATABASES["default"] = {"NAME": "zephyr/tests/zephyrdb.test",
"ENGINE": "django.db.backends.sqlite3",
"OPTIONS": { "timeout": 20, },}
TORNADO_SERVER = 'http://localhost:9983'
|
from settings import *
DATABASES["default"] = {"NAME": "zephyr/tests/zephyrdb.test",
"ENGINE": "django.db.backends.sqlite3",
"OPTIONS": { "timeout": 20, },}
TORNADO_SERVER = 'http://localhost:9983'
# Decrease the get_updates timeout to 1 second.
# This allows CasperJS to proceed quickly to the next test step.
POLL_TIMEOUT = 1000
|
Decrease get_updates timeout for client test suite
|
Decrease get_updates timeout for client test suite
Fixes #475.
(imported from commit d8f908c55f2e519541e5383a742edbf23183539c)
|
Python
|
apache-2.0
|
ryanbackman/zulip,christi3k/zulip,dnmfarrell/zulip,littledogboy/zulip,LAndreas/zulip,timabbott/zulip,hayderimran7/zulip,xuxiao/zulip,deer-hope/zulip,zhaoweigg/zulip,m1ssou/zulip,wdaher/zulip,punchagan/zulip,lfranchi/zulip,kokoar/zulip,voidException/zulip,brainwane/zulip,blaze225/zulip,akuseru/zulip,JPJPJPOPOP/zulip,hayderimran7/zulip,MayB/zulip,ipernet/zulip,AZtheAsian/zulip,gigawhitlocks/zulip,bssrdf/zulip,bitemyapp/zulip,ashwinirudrappa/zulip,proliming/zulip,LeeRisk/zulip,littledogboy/zulip,JanzTam/zulip,developerfm/zulip,pradiptad/zulip,dotcool/zulip,alliejones/zulip,hj3938/zulip,Juanvulcano/zulip,qq1012803704/zulip,yocome/zulip,sharmaeklavya2/zulip,AZtheAsian/zulip,tdr130/zulip,vaidap/zulip,wangdeshui/zulip,sup95/zulip,blaze225/zulip,dnmfarrell/zulip,stamhe/zulip,Drooids/zulip,rht/zulip,suxinde2009/zulip,aakash-cr7/zulip,nicholasbs/zulip,qq1012803704/zulip,bowlofstew/zulip,aakash-cr7/zulip,mdavid/zulip,xuanhan863/zulip,wangdeshui/zulip,bastianh/zulip,hafeez3000/zulip,bssrdf/zulip,umkay/zulip,jphilipsen05/zulip,zofuthan/zulip,proliming/zulip,mansilladev/zulip,codeKonami/zulip,karamcnair/zulip,wavelets/zulip,paxapy/zulip,Cheppers/zulip,kaiyuanheshang/zulip,jerryge/zulip,hustlzp/zulip,nicholasbs/zulip,reyha/zulip,andersk/zulip,huangkebo/zulip,mahim97/zulip,pradiptad/zulip,jessedhillon/zulip,littledogboy/zulip,moria/zulip,DazWorrall/zulip,zofuthan/zulip,jimmy54/zulip,umkay/zulip,zorojean/zulip,xuxiao/zulip,sharmaeklavya2/zulip,stamhe/zulip,themass/zulip,Diptanshu8/zulip,andersk/zulip,technicalpickles/zulip,dhcrzf/zulip,Jianchun1/zulip,tommyip/zulip,ipernet/zulip,praveenaki/zulip,levixie/zulip,developerfm/zulip,praveenaki/zulip,punchagan/zulip,joshisa/zulip,saitodisse/zulip,hengqujushi/zulip,Batterfii/zulip,codeKonami/zulip,technicalpickles/zulip,hayderimran7/zulip,voidException/zulip,amanharitsh123/zulip,rishig/zulip,ryansnowboarder/zulip,LeeRisk/zulip,bastianh/zulip,Batterfii/zulip,ikasumiwt/zulip,ashwinirudrappa/zulip,Drooids/zulip,Cheppers/zulip,tommyip/zulip,Vallher/zulip,johnnygaddarr/zulip,wweiradio/zulip,jrowan/zulip,RobotCaleb/zulip,jphilipsen05/zulip,PhilSk/zulip,firstblade/zulip,suxinde2009/zulip,gkotian/zulip,punchagan/zulip,aakash-cr7/zulip,amyliu345/zulip,dwrpayne/zulip,moria/zulip,dxq-git/zulip,LAndreas/zulip,bssrdf/zulip,guiquanz/zulip,Gabriel0402/zulip,Batterfii/zulip,so0k/zulip,RobotCaleb/zulip,huangkebo/zulip,stamhe/zulip,AZtheAsian/zulip,noroot/zulip,xuxiao/zulip,dxq-git/zulip,vaidap/zulip,ufosky-server/zulip,rht/zulip,babbage/zulip,kaiyuanheshang/zulip,dawran6/zulip,aliceriot/zulip,dattatreya303/zulip,themass/zulip,noroot/zulip,timabbott/zulip,hj3938/zulip,RobotCaleb/zulip,brockwhittaker/zulip,Qgap/zulip,shrikrishnaholla/zulip,voidException/zulip,bowlofstew/zulip,verma-varsha/zulip,jeffcao/zulip,bitemyapp/zulip,praveenaki/zulip,LAndreas/zulip,proliming/zulip,aakash-cr7/zulip,jackrzhang/zulip,brainwane/zulip,Suninus/zulip,jainayush975/zulip,christi3k/zulip,Galexrt/zulip,gkotian/zulip,praveenaki/zulip,hackerkid/zulip,Cheppers/zulip,vakila/zulip,cosmicAsymmetry/zulip,niftynei/zulip,noroot/zulip,nicholasbs/zulip,suxinde2009/zulip,akuseru/zulip,noroot/zulip,natanovia/zulip,shubhamdhama/zulip,fw1121/zulip,eeshangarg/zulip,aakash-cr7/zulip,wangdeshui/zulip,grave-w-grave/zulip,ahmadassaf/zulip,andersk/zulip,vabs22/zulip,zofuthan/zulip,ashwinirudrappa/zulip,alliejones/zulip,Frouk/zulip,wdaher/zulip,pradiptad/zulip,bluesea/zulip,so0k/zulip,vikas-parashar/zulip,Cheppers/zulip,easyfmxu/zulip,bastianh/zulip,ufosky-server/zulip,mohsenSy/zulip,souravbadami/zulip,Batterfii/zulip,amanharitsh123/zulip,hackerkid/zulip,sharmaeklavya2/zulip,rishig/zulip,karamcnair/zulip,luyifan/zulip,jainayush975/zulip,hackerkid/zulip,glovebx/zulip,littledogboy/zulip,he15his/zulip,zwily/zulip,ApsOps/zulip,fw1121/zulip,showell/zulip,ufosky-server/zulip,dwrpayne/zulip,hengqujushi/zulip,bluesea/zulip,ikasumiwt/zulip,codeKonami/zulip,Juanvulcano/zulip,dotcool/zulip,tommyip/zulip,umkay/zulip,sup95/zulip,showell/zulip,mdavid/zulip,sonali0901/zulip,thomasboyt/zulip,natanovia/zulip,babbage/zulip,mahim97/zulip,JPJPJPOPOP/zulip,KJin99/zulip,bowlofstew/zulip,synicalsyntax/zulip,dawran6/zulip,timabbott/zulip,zofuthan/zulip,Batterfii/zulip,souravbadami/zulip,Drooids/zulip,wavelets/zulip,verma-varsha/zulip,Galexrt/zulip,atomic-labs/zulip,LeeRisk/zulip,so0k/zulip,swinghu/zulip,armooo/zulip,glovebx/zulip,xuanhan863/zulip,zachallaun/zulip,littledogboy/zulip,jeffcao/zulip,aliceriot/zulip,jphilipsen05/zulip,Frouk/zulip,grave-w-grave/zulip,karamcnair/zulip,bluesea/zulip,schatt/zulip,deer-hope/zulip,showell/zulip,armooo/zulip,hayderimran7/zulip,tiansiyuan/zulip,codeKonami/zulip,vakila/zulip,nicholasbs/zulip,firstblade/zulip,eeshangarg/zulip,johnny9/zulip,luyifan/zulip,zorojean/zulip,avastu/zulip,jackrzhang/zulip,ipernet/zulip,ashwinirudrappa/zulip,yuvipanda/zulip,tommyip/zulip,paxapy/zulip,synicalsyntax/zulip,technicalpickles/zulip,shubhamdhama/zulip,ryansnowboarder/zulip,seapasulli/zulip,grave-w-grave/zulip,jonesgithub/zulip,armooo/zulip,bssrdf/zulip,wavelets/zulip,sonali0901/zulip,brockwhittaker/zulip,jphilipsen05/zulip,MayB/zulip,hj3938/zulip,ryansnowboarder/zulip,wangdeshui/zulip,eastlhu/zulip,Diptanshu8/zulip,he15his/zulip,ipernet/zulip,kaiyuanheshang/zulip,JanzTam/zulip,glovebx/zulip,aliceriot/zulip,vikas-parashar/zulip,thomasboyt/zulip,susansls/zulip,swinghu/zulip,wweiradio/zulip,EasonYi/zulip,rht/zulip,seapasulli/zulip,SmartPeople/zulip,Qgap/zulip,umkay/zulip,tdr130/zulip,dxq-git/zulip,MariaFaBella85/zulip,Vallher/zulip,jackrzhang/zulip,saitodisse/zulip,levixie/zulip,udxxabp/zulip,willingc/zulip,babbage/zulip,yuvipanda/zulip,ryanbackman/zulip,Galexrt/zulip,aps-sids/zulip,suxinde2009/zulip,babbage/zulip,peiwei/zulip,dwrpayne/zulip,ahmadassaf/zulip,krtkmj/zulip,jonesgithub/zulip,wavelets/zulip,dattatreya303/zulip,dotcool/zulip,eastlhu/zulip,showell/zulip,bssrdf/zulip,jeffcao/zulip,ufosky-server/zulip,paxapy/zulip,ufosky-server/zulip,sonali0901/zulip,sharmaeklavya2/zulip,dawran6/zulip,jessedhillon/zulip,verma-varsha/zulip,dhcrzf/zulip,shrikrishnaholla/zulip,zorojean/zulip,vikas-parashar/zulip,Gabriel0402/zulip,atomic-labs/zulip,Jianchun1/zulip,guiquanz/zulip,rishig/zulip,ryansnowboarder/zulip,kou/zulip,ryanbackman/zulip,MayB/zulip,jainayush975/zulip,jackrzhang/zulip,eastlhu/zulip,hengqujushi/zulip,sonali0901/zulip,synicalsyntax/zulip,cosmicAsymmetry/zulip,saitodisse/zulip,Gabriel0402/zulip,firstblade/zulip,christi3k/zulip,suxinde2009/zulip,umkay/zulip,zhaoweigg/zulip,Suninus/zulip,shaunstanislaus/zulip,zulip/zulip,technicalpickles/zulip,Juanvulcano/zulip,kokoar/zulip,suxinde2009/zulip,fw1121/zulip,dxq-git/zulip,dattatreya303/zulip,ikasumiwt/zulip,moria/zulip,shubhamdhama/zulip,krtkmj/zulip,zacps/zulip,andersk/zulip,Jianchun1/zulip,jessedhillon/zulip,jonesgithub/zulip,cosmicAsymmetry/zulip,ahmadassaf/zulip,MariaFaBella85/zulip,proliming/zulip,calvinleenyc/zulip,deer-hope/zulip,LAndreas/zulip,gkotian/zulip,dnmfarrell/zulip,sharmaeklavya2/zulip,JPJPJPOPOP/zulip,Jianchun1/zulip,arpitpanwar/zulip,hayderimran7/zulip,Gabriel0402/zulip,EasonYi/zulip,zacps/zulip,Juanvulcano/zulip,codeKonami/zulip,esander91/zulip,DazWorrall/zulip,souravbadami/zulip,kou/zulip,jimmy54/zulip,aliceriot/zulip,jessedhillon/zulip,itnihao/zulip,calvinleenyc/zulip,technicalpickles/zulip,wweiradio/zulip,jimmy54/zulip,joshisa/zulip,firstblade/zulip,avastu/zulip,tbutter/zulip,LeeRisk/zulip,reyha/zulip,KJin99/zulip,vabs22/zulip,j831/zulip,gigawhitlocks/zulip,paxapy/zulip,brainwane/zulip,tbutter/zulip,vakila/zulip,akuseru/zulip,jerryge/zulip,noroot/zulip,easyfmxu/zulip,so0k/zulip,ahmadassaf/zulip,dhcrzf/zulip,PhilSk/zulip,johnny9/zulip,wweiradio/zulip,ericzhou2008/zulip,joshisa/zulip,shubhamdhama/zulip,dxq-git/zulip,itnihao/zulip,arpitpanwar/zulip,tommyip/zulip,kaiyuanheshang/zulip,babbage/zulip,yuvipanda/zulip,avastu/zulip,SmartPeople/zulip,Vallher/zulip,ApsOps/zulip,mansilladev/zulip,KingxBanana/zulip,zhaoweigg/zulip,j831/zulip,isht3/zulip,EasonYi/zulip,tdr130/zulip,Diptanshu8/zulip,niftynei/zulip,ipernet/zulip,Batterfii/zulip,adnanh/zulip,adnanh/zulip,bitemyapp/zulip,dawran6/zulip,KingxBanana/zulip,MariaFaBella85/zulip,peiwei/zulip,praveenaki/zulip,dxq-git/zulip,vakila/zulip,xuxiao/zulip,dhcrzf/zulip,zwily/zulip,hengqujushi/zulip,tbutter/zulip,showell/zulip,bluesea/zulip,SmartPeople/zulip,andersk/zulip,shubhamdhama/zulip,dhcrzf/zulip,PaulPetring/zulip,lfranchi/zulip,bastianh/zulip,mohsenSy/zulip,calvinleenyc/zulip,aps-sids/zulip,luyifan/zulip,technicalpickles/zulip,alliejones/zulip,jrowan/zulip,krtkmj/zulip,DazWorrall/zulip,ikasumiwt/zulip,tiansiyuan/zulip,Drooids/zulip,krtkmj/zulip,yuvipanda/zulip,kou/zulip,eeshangarg/zulip,shrikrishnaholla/zulip,schatt/zulip,he15his/zulip,mdavid/zulip,zachallaun/zulip,gkotian/zulip,he15his/zulip,shaunstanislaus/zulip,Frouk/zulip,rht/zulip,lfranchi/zulip,zulip/zulip,xuxiao/zulip,littledogboy/zulip,Suninus/zulip,hustlzp/zulip,showell/zulip,brainwane/zulip,dotcool/zulip,itnihao/zulip,hj3938/zulip,MayB/zulip,tdr130/zulip,DazWorrall/zulip,pradiptad/zulip,zhaoweigg/zulip,aps-sids/zulip,punchagan/zulip,AZtheAsian/zulip,dotcool/zulip,willingc/zulip,rishig/zulip,umkay/zulip,ahmadassaf/zulip,Galexrt/zulip,hj3938/zulip,tbutter/zulip,fw1121/zulip,noroot/zulip,susansls/zulip,bowlofstew/zulip,jerryge/zulip,firstblade/zulip,xuxiao/zulip,amallia/zulip,krtkmj/zulip,bastianh/zulip,m1ssou/zulip,noroot/zulip,hackerkid/zulip,ericzhou2008/zulip,LAndreas/zulip,karamcnair/zulip,Cheppers/zulip,peguin40/zulip,tbutter/zulip,samatdav/zulip,udxxabp/zulip,armooo/zulip,mahim97/zulip,vakila/zulip,verma-varsha/zulip,susansls/zulip,grave-w-grave/zulip,isht3/zulip,andersk/zulip,jackrzhang/zulip,ryanbackman/zulip,babbage/zulip,timabbott/zulip,vabs22/zulip,KingxBanana/zulip,luyifan/zulip,dhcrzf/zulip,mohsenSy/zulip,so0k/zulip,KJin99/zulip,shrikrishnaholla/zulip,jimmy54/zulip,atomic-labs/zulip,zachallaun/zulip,mansilladev/zulip,zhaoweigg/zulip,mohsenSy/zulip,karamcnair/zulip,kaiyuanheshang/zulip,codeKonami/zulip,shrikrishnaholla/zulip,calvinleenyc/zulip,wweiradio/zulip,sup95/zulip,PaulPetring/zulip,vakila/zulip,peiwei/zulip,dnmfarrell/zulip,ufosky-server/zulip,jimmy54/zulip,grave-w-grave/zulip,itnihao/zulip,ikasumiwt/zulip,gigawhitlocks/zulip,johnny9/zulip,sonali0901/zulip,johnny9/zulip,willingc/zulip,littledogboy/zulip,easyfmxu/zulip,eastlhu/zulip,PhilSk/zulip,joyhchen/zulip,m1ssou/zulip,synicalsyntax/zulip,swinghu/zulip,glovebx/zulip,yuvipanda/zulip,Suninus/zulip,joyhchen/zulip,codeKonami/zulip,tbutter/zulip,nicholasbs/zulip,susansls/zulip,jimmy54/zulip,cosmicAsymmetry/zulip,shrikrishnaholla/zulip,pradiptad/zulip,grave-w-grave/zulip,mohsenSy/zulip,he15his/zulip,aps-sids/zulip,samatdav/zulip,eastlhu/zulip,vikas-parashar/zulip,reyha/zulip,KJin99/zulip,zulip/zulip,ufosky-server/zulip,ApsOps/zulip,zacps/zulip,levixie/zulip,LeeRisk/zulip,fw1121/zulip,Gabriel0402/zulip,kou/zulip,Galexrt/zulip,zachallaun/zulip,aps-sids/zulip,tommyip/zulip,vaidap/zulip,themass/zulip,firstblade/zulip,jeffcao/zulip,natanovia/zulip,arpith/zulip,joyhchen/zulip,shaunstanislaus/zulip,bssrdf/zulip,guiquanz/zulip,alliejones/zulip,rht/zulip,sup95/zulip,so0k/zulip,ashwinirudrappa/zulip,arpitpanwar/zulip,brockwhittaker/zulip,joshisa/zulip,j831/zulip,jainayush975/zulip,samatdav/zulip,swinghu/zulip,yocome/zulip,saitodisse/zulip,reyha/zulip,joshisa/zulip,natanovia/zulip,zofuthan/zulip,yocome/zulip,DazWorrall/zulip,udxxabp/zulip,wdaher/zulip,shaunstanislaus/zulip,dotcool/zulip,willingc/zulip,proliming/zulip,JPJPJPOPOP/zulip,gigawhitlocks/zulip,isht3/zulip,swinghu/zulip,showell/zulip,tiansiyuan/zulip,stamhe/zulip,themass/zulip,Frouk/zulip,jonesgithub/zulip,JanzTam/zulip,eastlhu/zulip,avastu/zulip,glovebx/zulip,KJin99/zulip,eeshangarg/zulip,arpitpanwar/zulip,qq1012803704/zulip,johnnygaddarr/zulip,MariaFaBella85/zulip,thomasboyt/zulip,tbutter/zulip,huangkebo/zulip,souravbadami/zulip,qq1012803704/zulip,mansilladev/zulip,shrikrishnaholla/zulip,JanzTam/zulip,ashwinirudrappa/zulip,johnny9/zulip,dawran6/zulip,moria/zulip,jackrzhang/zulip,shaunstanislaus/zulip,he15his/zulip,punchagan/zulip,ericzhou2008/zulip,zachallaun/zulip,saitodisse/zulip,udxxabp/zulip,developerfm/zulip,arpith/zulip,JanzTam/zulip,arpitpanwar/zulip,zwily/zulip,gigawhitlocks/zulip,m1ssou/zulip,kokoar/zulip,RobotCaleb/zulip,amyliu345/zulip,dattatreya303/zulip,johnny9/zulip,Jianchun1/zulip,MayB/zulip,suxinde2009/zulip,m1ssou/zulip,Juanvulcano/zulip,rht/zulip,ericzhou2008/zulip,aliceriot/zulip,jessedhillon/zulip,JPJPJPOPOP/zulip,moria/zulip,johnny9/zulip,andersk/zulip,kokoar/zulip,voidException/zulip,stamhe/zulip,gkotian/zulip,LeeRisk/zulip,lfranchi/zulip,hustlzp/zulip,rishig/zulip,rishig/zulip,timabbott/zulip,natanovia/zulip,pradiptad/zulip,willingc/zulip,amyliu345/zulip,deer-hope/zulip,johnnygaddarr/zulip,developerfm/zulip,alliejones/zulip,DazWorrall/zulip,vikas-parashar/zulip,esander91/zulip,lfranchi/zulip,luyifan/zulip,akuseru/zulip,umkay/zulip,amanharitsh123/zulip,johnnygaddarr/zulip,peguin40/zulip,adnanh/zulip,jphilipsen05/zulip,moria/zulip,levixie/zulip,wangdeshui/zulip,DazWorrall/zulip,joyhchen/zulip,mdavid/zulip,KingxBanana/zulip,yocome/zulip,Gabriel0402/zulip,MayB/zulip,natanovia/zulip,huangkebo/zulip,TigorC/zulip,saitodisse/zulip,tiansiyuan/zulip,gigawhitlocks/zulip,lfranchi/zulip,LAndreas/zulip,rishig/zulip,dwrpayne/zulip,j831/zulip,Vallher/zulip,cosmicAsymmetry/zulip,isht3/zulip,brainwane/zulip,dattatreya303/zulip,sharmaeklavya2/zulip,synicalsyntax/zulip,kokoar/zulip,aliceriot/zulip,zwily/zulip,niftynei/zulip,guiquanz/zulip,SmartPeople/zulip,schatt/zulip,zulip/zulip,deer-hope/zulip,akuseru/zulip,vikas-parashar/zulip,PaulPetring/zulip,dhcrzf/zulip,huangkebo/zulip,xuanhan863/zulip,deer-hope/zulip,Cheppers/zulip,dwrpayne/zulip,Suninus/zulip,udxxabp/zulip,Vallher/zulip,ericzhou2008/zulip,fw1121/zulip,avastu/zulip,amyliu345/zulip,vaidap/zulip,kokoar/zulip,amallia/zulip,seapasulli/zulip,bitemyapp/zulip,Juanvulcano/zulip,atomic-labs/zulip,isht3/zulip,vabs22/zulip,vakila/zulip,zofuthan/zulip,Diptanshu8/zulip,kou/zulip,hj3938/zulip,arpith/zulip,akuseru/zulip,blaze225/zulip,themass/zulip,jainayush975/zulip,zachallaun/zulip,hafeez3000/zulip,kou/zulip,amanharitsh123/zulip,Drooids/zulip,jerryge/zulip,arpith/zulip,technicalpickles/zulip,fw1121/zulip,karamcnair/zulip,wavelets/zulip,nicholasbs/zulip,jeffcao/zulip,wdaher/zulip,huangkebo/zulip,LeeRisk/zulip,voidException/zulip,Frouk/zulip,bowlofstew/zulip,swinghu/zulip,ryanbackman/zulip,luyifan/zulip,sonali0901/zulip,zorojean/zulip,TigorC/zulip,peguin40/zulip,cosmicAsymmetry/zulip,MariaFaBella85/zulip,zulip/zulip,developerfm/zulip,christi3k/zulip,AZtheAsian/zulip,kou/zulip,armooo/zulip,zwily/zulip,jimmy54/zulip,bastianh/zulip,Galexrt/zulip,Suninus/zulip,mdavid/zulip,j831/zulip,he15his/zulip,wweiradio/zulip,JPJPJPOPOP/zulip,jonesgithub/zulip,qq1012803704/zulip,udxxabp/zulip,amallia/zulip,amallia/zulip,shubhamdhama/zulip,hafeez3000/zulip,m1ssou/zulip,kaiyuanheshang/zulip,johnnygaddarr/zulip,bowlofstew/zulip,arpith/zulip,isht3/zulip,m1ssou/zulip,voidException/zulip,timabbott/zulip,peguin40/zulip,Qgap/zulip,amallia/zulip,thomasboyt/zulip,PaulPetring/zulip,niftynei/zulip,ipernet/zulip,itnihao/zulip,reyha/zulip,lfranchi/zulip,RobotCaleb/zulip,verma-varsha/zulip,wdaher/zulip,Qgap/zulip,calvinleenyc/zulip,Frouk/zulip,eeshangarg/zulip,zacps/zulip,niftynei/zulip,arpitpanwar/zulip,hengqujushi/zulip,souravbadami/zulip,LAndreas/zulip,blaze225/zulip,Drooids/zulip,hayderimran7/zulip,zwily/zulip,itnihao/zulip,hayderimran7/zulip,adnanh/zulip,mohsenSy/zulip,jerryge/zulip,esander91/zulip,zhaoweigg/zulip,mahim97/zulip,zachallaun/zulip,EasonYi/zulip,bssrdf/zulip,joshisa/zulip,eeshangarg/zulip,arpith/zulip,ryansnowboarder/zulip,reyha/zulip,dnmfarrell/zulip,dawran6/zulip,hengqujushi/zulip,easyfmxu/zulip,ryansnowboarder/zulip,luyifan/zulip,guiquanz/zulip,christi3k/zulip,karamcnair/zulip,zwily/zulip,zulip/zulip,easyfmxu/zulip,hackerkid/zulip,tiansiyuan/zulip,atomic-labs/zulip,arpitpanwar/zulip,gigawhitlocks/zulip,bitemyapp/zulip,vabs22/zulip,MayB/zulip,ApsOps/zulip,Qgap/zulip,zorojean/zulip,hafeez3000/zulip,Cheppers/zulip,esander91/zulip,pradiptad/zulip,Vallher/zulip,jonesgithub/zulip,PhilSk/zulip,vaidap/zulip,Suninus/zulip,esander91/zulip,tiansiyuan/zulip,hafeez3000/zulip,adnanh/zulip,glovebx/zulip,peguin40/zulip,synicalsyntax/zulip,xuanhan863/zulip,seapasulli/zulip,hafeez3000/zulip,brockwhittaker/zulip,tommyip/zulip,dnmfarrell/zulip,johnnygaddarr/zulip,Galexrt/zulip,joyhchen/zulip,levixie/zulip,natanovia/zulip,TigorC/zulip,armooo/zulip,JanzTam/zulip,krtkmj/zulip,Drooids/zulip,jrowan/zulip,EasonYi/zulip,brockwhittaker/zulip,brainwane/zulip,alliejones/zulip,levixie/zulip,verma-varsha/zulip,gkotian/zulip,thomasboyt/zulip,proliming/zulip,udxxabp/zulip,paxapy/zulip,armooo/zulip,amanharitsh123/zulip,akuseru/zulip,jackrzhang/zulip,seapasulli/zulip,seapasulli/zulip,niftynei/zulip,Jianchun1/zulip,bluesea/zulip,joshisa/zulip,zofuthan/zulip,xuanhan863/zulip,jessedhillon/zulip,synicalsyntax/zulip,atomic-labs/zulip,shaunstanislaus/zulip,hustlzp/zulip,deer-hope/zulip,easyfmxu/zulip,PhilSk/zulip,RobotCaleb/zulip,praveenaki/zulip,proliming/zulip,jerryge/zulip,jerryge/zulip,schatt/zulip,KingxBanana/zulip,bluesea/zulip,kokoar/zulip,gkotian/zulip,MariaFaBella85/zulip,punchagan/zulip,amyliu345/zulip,TigorC/zulip,huangkebo/zulip,seapasulli/zulip,babbage/zulip,moria/zulip,Vallher/zulip,jainayush975/zulip,mdavid/zulip,saitodisse/zulip,ikasumiwt/zulip,hengqujushi/zulip,zacps/zulip,RobotCaleb/zulip,tdr130/zulip,AZtheAsian/zulip,shubhamdhama/zulip,SmartPeople/zulip,wavelets/zulip,swinghu/zulip,dnmfarrell/zulip,dotcool/zulip,voidException/zulip,zulip/zulip,timabbott/zulip,PaulPetring/zulip,schatt/zulip,guiquanz/zulip,bitemyapp/zulip,ericzhou2008/zulip,wangdeshui/zulip,dxq-git/zulip,souravbadami/zulip,mansilladev/zulip,kaiyuanheshang/zulip,JanzTam/zulip,EasonYi/zulip,developerfm/zulip,thomasboyt/zulip,zhaoweigg/zulip,Diptanshu8/zulip,joyhchen/zulip,zorojean/zulip,peiwei/zulip,ApsOps/zulip,hustlzp/zulip,glovebx/zulip,zorojean/zulip,hj3938/zulip,ikasumiwt/zulip,KingxBanana/zulip,easyfmxu/zulip,rht/zulip,tdr130/zulip,dwrpayne/zulip,eastlhu/zulip,tdr130/zulip,nicholasbs/zulip,PaulPetring/zulip,ahmadassaf/zulip,willingc/zulip,guiquanz/zulip,aakash-cr7/zulip,wangdeshui/zulip,stamhe/zulip,itnihao/zulip,atomic-labs/zulip,ashwinirudrappa/zulip,jphilipsen05/zulip,levixie/zulip,wdaher/zulip,dattatreya303/zulip,hafeez3000/zulip,hackerkid/zulip,adnanh/zulip,jrowan/zulip,EasonYi/zulip,thomasboyt/zulip,susansls/zulip,Diptanshu8/zulip,sup95/zulip,mdavid/zulip,mahim97/zulip,ApsOps/zulip,mansilladev/zulip,wavelets/zulip,themass/zulip,amallia/zulip,avastu/zulip,j831/zulip,qq1012803704/zulip,mansilladev/zulip,wweiradio/zulip,peiwei/zulip,yocome/zulip,eeshangarg/zulip,susansls/zulip,punchagan/zulip,samatdav/zulip,jeffcao/zulip,KJin99/zulip,alliejones/zulip,esander91/zulip,calvinleenyc/zulip,jonesgithub/zulip,peiwei/zulip,bluesea/zulip,paxapy/zulip,bastianh/zulip,ApsOps/zulip,vabs22/zulip,schatt/zulip,samatdav/zulip,jrowan/zulip,jeffcao/zulip,Gabriel0402/zulip,PhilSk/zulip,TigorC/zulip,praveenaki/zulip,dwrpayne/zulip,amyliu345/zulip,amallia/zulip,johnnygaddarr/zulip,shaunstanislaus/zulip,ahmadassaf/zulip,ericzhou2008/zulip,esander91/zulip,jrowan/zulip,sup95/zulip,Qgap/zulip,Frouk/zulip,themass/zulip,blaze225/zulip,avastu/zulip,bowlofstew/zulip,aps-sids/zulip,vaidap/zulip,ipernet/zulip,xuanhan863/zulip,KJin99/zulip,stamhe/zulip,yocome/zulip,TigorC/zulip,aps-sids/zulip,firstblade/zulip,hackerkid/zulip,ryanbackman/zulip,hustlzp/zulip,SmartPeople/zulip,blaze225/zulip,mahim97/zulip,willingc/zulip,developerfm/zulip,yuvipanda/zulip,samatdav/zulip,MariaFaBella85/zulip,ryansnowboarder/zulip,christi3k/zulip,brainwane/zulip,yocome/zulip,Batterfii/zulip,tiansiyuan/zulip,xuanhan863/zulip,bitemyapp/zulip,adnanh/zulip,amanharitsh123/zulip,jessedhillon/zulip,hustlzp/zulip,xuxiao/zulip,schatt/zulip,brockwhittaker/zulip,wdaher/zulip,peguin40/zulip,so0k/zulip,qq1012803704/zulip,peiwei/zulip,yuvipanda/zulip,zacps/zulip,PaulPetring/zulip,krtkmj/zulip,Qgap/zulip,aliceriot/zulip
|
6486a888cbcec7285df92020f76e3f1c5fbba0e2
|
bluebottle/test/test_runner.py
|
bluebottle/test/test_runner.py
|
from django.test.runner import DiscoverRunner
from django.db import connection
from tenant_schemas.utils import get_tenant_model
from bluebottle.test.utils import InitProjectDataMixin
class MultiTenantRunner(DiscoverRunner, InitProjectDataMixin):
def setup_databases(self, *args, **kwargs):
result = super(MultiTenantRunner, self).setup_databases(*args, **kwargs)
# Create secondary tenant
connection.set_schema_to_public()
tenant_domain = 'testserver2'
tenant2 = get_tenant_model()(
domain_url=tenant_domain,
schema_name='test2',
client_name='test2')
tenant2.save(
verbosity=self.verbosity)
# Add basic data for tenant
connection.set_tenant(tenant2)
self.init_projects()
# Create main tenant
connection.set_schema_to_public()
tenant_domain = 'testserver'
tenant = get_tenant_model()(
domain_url=tenant_domain,
schema_name='test',
client_name='test')
tenant.save(
verbosity=self.verbosity)
connection.set_tenant(tenant)
return result
|
from django.test.runner import DiscoverRunner
from django.db import connection
from django.core import management
from tenant_schemas.utils import get_tenant_model
from bluebottle.test.utils import InitProjectDataMixin
class MultiTenantRunner(DiscoverRunner, InitProjectDataMixin):
def setup_databases(self, *args, **kwargs):
result = super(MultiTenantRunner, self).setup_databases(*args, **kwargs)
# Create secondary tenant
connection.set_schema_to_public()
tenant_domain = 'testserver2'
tenant2, _created = get_tenant_model().objects.get_or_create(
domain_url=tenant_domain,
schema_name='test2',
client_name='test2')
tenant2.save(
verbosity=self.verbosity)
# Add basic data for tenant
connection.set_tenant(tenant2)
self.init_projects()
# Create main tenant
connection.set_schema_to_public()
management.call_command('loaddata', 'exchange_rates.json', verbosity=1)
tenant_domain = 'testserver'
tenant, _created = get_tenant_model().objects.get_or_create(
domain_url=tenant_domain,
schema_name='test',
client_name='test')
tenant.save(
verbosity=self.verbosity)
connection.set_tenant(tenant)
return result
|
Load exchange rates in test setup. Make it posible to use --keepdb
|
Load exchange rates in test setup. Make it posible to use --keepdb
|
Python
|
bsd-3-clause
|
onepercentclub/bluebottle,onepercentclub/bluebottle,onepercentclub/bluebottle,onepercentclub/bluebottle,onepercentclub/bluebottle
|
873c5e8bf85a8be5a08852134967d29353ed3009
|
examples/simple.py
|
examples/simple.py
|
from lobster import cmssw
from lobster.core import *
storage = StorageConfiguration(
output=[
"hdfs:///store/user/matze/test_shuffle_take29",
"file:///hadoop/store/user/matze/test_shuffle_take29",
"root://ndcms.crc.nd.edu//store/user/matze/test_shuffle_take29",
"srm://T3_US_NotreDame/store/user/matze/test_shuffle_take29",
]
)
processing = Category(
name='processing',
cores=1,
runtime=900,
memory=1000
)
workflows = []
single_mu = Workflow(
label='single_mu',
dataset=cmssw.Dataset(
dataset='/SingleMu/Run2012A-recover-06Aug2012-v1/AOD',
events_per_task=5000
),
category=processing,
pset='slim.py',
publish_label='test',
merge_size='3.5G',
outputs=['output.root']
)
workflows.append(single_mu)
config = Config(
label='shuffle',
workdir='/tmpscratch/users/matze/test_shuffle_take30',
plotdir='/afs/crc.nd.edu/user/m/mwolf3/www/lobster/test_shuffle_take29',
storage=storage,
workflows=workflows,
advanced=AdvancedOptions(log_level=1)
)
|
from lobster import cmssw
from lobster.core import *
storage = StorageConfiguration(
output=[
"hdfs:///store/user/matze/test_shuffle_take29",
"file:///hadoop/store/user/matze/test_shuffle_take29",
"root://T3_US_NotreDame/store/user/matze/test_shuffle_take29",
"srm://T3_US_NotreDame/store/user/matze/test_shuffle_take29",
]
)
processing = Category(
name='processing',
cores=1,
runtime=900,
memory=1000
)
workflows = []
single_mu = Workflow(
label='single_mu',
dataset=cmssw.Dataset(
dataset='/SingleMu/Run2012A-recover-06Aug2012-v1/AOD',
events_per_task=5000
),
category=processing,
pset='slim.py',
publish_label='test',
merge_size='3.5G',
outputs=['output.root']
)
workflows.append(single_mu)
config = Config(
label='shuffle',
workdir='/tmpscratch/users/matze/test_shuffle_take30',
plotdir='/afs/crc.nd.edu/user/m/mwolf3/www/lobster/test_shuffle_take29',
storage=storage,
workflows=workflows,
advanced=AdvancedOptions(log_level=1)
)
|
Swap ndcms for generic T3 string.
|
Swap ndcms for generic T3 string.
|
Python
|
mit
|
matz-e/lobster,matz-e/lobster,matz-e/lobster
|
587abec7ff5b90c03885e164d9b6b62a1fb41f76
|
grip/github_renderer.py
|
grip/github_renderer.py
|
from flask import abort, json
import requests
def render_content(text, gfm=False, context=None,
username=None, password=None):
"""Renders the specified markup using the GitHub API."""
if gfm:
url = 'https://api.github.com/markdown'
data = {'text': text, 'mode': 'gfm'}
if context:
data['context'] = context
data = json.dumps(data)
else:
url = 'https://api.github.com/markdown/raw'
data = text
headers = {'content-type': 'text/plain'}
auth = (username, password) if username else None
r = requests.post(url, headers=headers, data=data, auth=auth)
# Relay HTTP errors
if r.status_code != 200:
try:
message = r.json()['message']
except:
message = r.text
abort(r.status_code, message)
return r.text
|
from flask import abort, json
import requests
def render_content(text, gfm=False, context=None,
username=None, password=None):
"""Renders the specified markup using the GitHub API."""
if gfm:
url = 'https://api.github.com/markdown'
data = {'text': text, 'mode': 'gfm'}
if context:
data['context'] = context
data = json.dumps(data)
headers = {'content-type': 'application/json'}
else:
url = 'https://api.github.com/markdown/raw'
data = text
headers = {'content-type': 'text/x-markdown'}
auth = (username, password) if username else None
r = requests.post(url, headers=headers, data=data, auth=auth)
# Relay HTTP errors
if r.status_code != 200:
try:
message = r.json()['message']
except:
message = r.text
abort(r.status_code, message)
return r.text
|
Fix the headers sent by the GitHub renderer.
|
Fix the headers sent by the GitHub renderer.
|
Python
|
mit
|
ssundarraj/grip,mgoddard-pivotal/grip,mgoddard-pivotal/grip,joeyespo/grip,joeyespo/grip,jbarreras/grip,jbarreras/grip,ssundarraj/grip
|
d7cfdbd2bde0cc876db8c1bce020d8a1cf0ea77b
|
mdot_rest/views.py
|
mdot_rest/views.py
|
from django.shortcuts import render
from .models import Resource
from .serializers import ResourceSerializer
from rest_framework import generics, permissions
class ResourceList(generics.ListCreateAPIView):
queryset = Resource.objects.all()
serializer_class = ResourceSerializer
permission_classes = (permissions.IsAuthenticatedOrReadOnly,)
class ResourceDetail(generics.RetrieveUpdateDestroyAPIView):
queryset = Resource.objects.all()
serializer_class = ResourceSerializer
permission_classes = (permissions.IsAuthenticatedOrReadOnly,)
|
from django.shortcuts import render
from .models import Resource
from .serializers import ResourceSerializer
from rest_framework import generics, permissions
import django_filters
class ResourceFilter(django_filters.FilterSet):
class Meta:
model = Resource
fields = ('name', 'featured', 'accessible', 'responsive_web',)
class ResourceList(generics.ListCreateAPIView):
queryset = Resource.objects.all()
serializer_class = ResourceSerializer
permission_classes = (permissions.IsAuthenticatedOrReadOnly,)
filter_class = ResourceFilter
class ResourceDetail(generics.RetrieveUpdateDestroyAPIView):
queryset = Resource.objects.all()
serializer_class = ResourceSerializer
permission_classes = (permissions.IsAuthenticatedOrReadOnly,)
|
Add search filtering for name and booleans in resource API.
|
Add search filtering for name and booleans in resource API.
|
Python
|
apache-2.0
|
uw-it-aca/mdot-rest,uw-it-aca/mdot-rest
|
3555b002aae386220bc02d662a9b188426afc08f
|
cmsplugin_facebook/cms_plugins.py
|
cmsplugin_facebook/cms_plugins.py
|
from cms.plugin_base import CMSPluginBase
from cms.plugin_pool import plugin_pool
from cmsplugin_facebook import models
class BasePlugin(CMSPluginBase):
name = None
def render(self, context, instance, placeholder):
context.update({'instance': instance,
'name': self.name,
'url': instance.pageurl or \
context['request'].build_absolute_uri()})
return context
class FacebookLikeBoxPlugin(BasePlugin):
model = models.FacebookLikeBox
name = 'Facebook Like Box'
render_template = 'cmsplugin_facebook/likebox.html'
change_form_template = 'cmsplugin_facebook/likebox_change_form.html'
class FacebookLikeButtonPlugin(BasePlugin):
model = models.FacebookLikeButton
name = 'Facebook Like Button'
render_template = 'cmsplugin_facebook/likebutton.html'
change_form_template = 'cmsplugin_facebook/likebutton_change_form.html'
plugin_pool.register_plugin(FacebookLikeBoxPlugin)
plugin_pool.register_plugin(FacebookLikeButtonPlugin)
|
from cms.plugin_base import CMSPluginBase
from cms.plugin_pool import plugin_pool
from cmsplugin_facebook import models
class BasePlugin(CMSPluginBase):
name = None
def render(self, context, instance, placeholder):
context.update({'instance': instance,
'name': self.name,
'url': instance.pageurl or \
context['request'].build_absolute_uri()})
return context
class FacebookLikeBoxPlugin(BasePlugin):
model = models.FacebookLikeBox
name = 'Facebook Like Box'
module = 'Facebook'
render_template = 'cmsplugin_facebook/likebox.html'
change_form_template = 'cmsplugin_facebook/likebox_change_form.html'
class FacebookLikeButtonPlugin(BasePlugin):
model = models.FacebookLikeButton
name = 'Facebook Like Button'
module = 'Facebook'
render_template = 'cmsplugin_facebook/likebutton.html'
change_form_template = 'cmsplugin_facebook/likebutton_change_form.html'
plugin_pool.register_plugin(FacebookLikeBoxPlugin)
plugin_pool.register_plugin(FacebookLikeButtonPlugin)
|
Create a specific group for the Facebook plugins - makes it a bit neater in the list of plugins.
|
Create a specific group for the Facebook plugins - makes it a bit neater in the list of plugins.
|
Python
|
bsd-3-clause
|
chrisglass/cmsplugin_facebook
|
97a490db75f0a4976199365c3f654ba8cdb9a781
|
01_Built-in_Types/tuple.py
|
01_Built-in_Types/tuple.py
|
#!/usr/bin/env python
import sys
import pickle
# Check argument
if len(sys.argv) != 2:
print("%s filename" % sys.argv[0])
raise SystemExit(1)
# Write tuples
file = open(sys.argv[1], "wb");
line = []
while True:
print("Enter name, age, score (ex: zzz, 16, 90) or quit");
line = sys.stdin.readline()
if line == "quit\n":
break
raws = line.split(",")
name = raws[0]
age = int(raws[1])
score = int(raws[2])
record = (name, age, score)
pickle.dump(record, file)
file.close()
# Read back
file = open(sys.argv[1], "rb");
while True:
try:
record = pickle.load(file)
print record
name, age, score= record
print("name = %s" % name)
print("name = %d" % age)
print("name = %d" % score)
except (EOFError):
break
file.close()
|
#!/usr/bin/env python
import sys
import pickle
# Test zip, and format in print
names = ["xxx", "yyy", "zzz"]
ages = [18, 19, 20]
persons = zip(names, ages)
for name, age in persons:
print "{0}'s age is {1}".format(name, age)
# Check argument
if len(sys.argv) != 2:
print("%s filename" % sys.argv[0])
raise SystemExit(1)
# Write tuples
file = open(sys.argv[1], "wb");
line = []
while True:
print("Enter name, age, score (ex: zzz, 16, 90) or quit");
line = sys.stdin.readline()
if line == "quit\n":
break
raws = line.split(",")
name = raws[0]
age = int(raws[1])
score = int(raws[2])
record = (name, age, score)
pickle.dump(record, file)
file.close()
# Read back
file = open(sys.argv[1], "rb");
while True:
try:
record = pickle.load(file)
print record
name, age, score= record
print("name = %s" % name)
print("name = %d" % age)
print("name = %d" % score)
except (EOFError):
break
file.close()
|
Test zip, and print format
|
Test zip, and print format
|
Python
|
bsd-2-clause
|
zzz0072/Python_Exercises,zzz0072/Python_Exercises
|
e5963987e678926ad8cdde93e2551d0516a7686b
|
slave/skia_slave_scripts/android_bench_pictures.py
|
slave/skia_slave_scripts/android_bench_pictures.py
|
#!/usr/bin/env python
# Copyright (c) 2012 The Chromium Authors. All rights reserved.
# Use of this source code is governed by a BSD-style license that can be
# found in the LICENSE file.
""" Run the Skia bench_pictures executable. """
from android_render_pictures import AndroidRenderPictures
from android_run_bench import DoBench
from bench_pictures import BenchPictures
from build_step import BuildStep
import sys
class AndroidBenchPictures(BenchPictures, AndroidRenderPictures):
def _DoBenchPictures(self, config, threads):
data_file = self._BuildDataFile(self._device_dirs.SKPPerfDir(), config,
threads)
args = self._PictureArgs(self._device_dirs.SKPDir(), config, threads)
DoBench(serial=self._serial,
executable='bench_pictures',
perf_data_dir=self._perf_data_dir,
device_perf_dir=self._device_dirs.SKPPerfDir(),
data_file=data_file,
extra_args=args)
def _Run(self):
self._PushSKPSources(self._serial)
super(AndroidBenchPictures, self)._Run()
if '__main__' == __name__:
sys.exit(BuildStep.RunBuildStep(AndroidBenchPictures))
|
#!/usr/bin/env python
# Copyright (c) 2012 The Chromium Authors. All rights reserved.
# Use of this source code is governed by a BSD-style license that can be
# found in the LICENSE file.
""" Run the Skia bench_pictures executable. """
from android_render_pictures import AndroidRenderPictures
from android_run_bench import DoBench
from bench_pictures import BenchPictures
from build_step import BuildStep
import sys
class AndroidBenchPictures(BenchPictures, AndroidRenderPictures):
def __init__(self, args, attempts=1, timeout=4800):
super(AndroidBenchPictures, self).__init__(args, attempts=attempts,
timeout=timeout)
def _DoBenchPictures(self, config, threads):
data_file = self._BuildDataFile(self._device_dirs.SKPPerfDir(), config,
threads)
args = self._PictureArgs(self._device_dirs.SKPDir(), config, threads)
DoBench(serial=self._serial,
executable='bench_pictures',
perf_data_dir=self._perf_data_dir,
device_perf_dir=self._device_dirs.SKPPerfDir(),
data_file=data_file,
extra_args=args)
def _Run(self):
self._PushSKPSources(self._serial)
super(AndroidBenchPictures, self)._Run()
if '__main__' == __name__:
sys.exit(BuildStep.RunBuildStep(AndroidBenchPictures))
|
Increase timeout for bench_pictures on Android
|
Increase timeout for bench_pictures on Android
Unreviewed.
git-svn-id: 32fc27f4dcfb6c0385cd9719852b95fe6680452d@6290 2bbb7eff-a529-9590-31e7-b0007b416f81
|
Python
|
bsd-3-clause
|
Tiger66639/skia-buildbot,google/skia-buildbot,google/skia-buildbot,Tiger66639/skia-buildbot,Tiger66639/skia-buildbot,google/skia-buildbot,google/skia-buildbot,google/skia-buildbot,google/skia-buildbot,Tiger66639/skia-buildbot,google/skia-buildbot,Tiger66639/skia-buildbot,Tiger66639/skia-buildbot,google/skia-buildbot,Tiger66639/skia-buildbot
|
b219823af7188f968d7c52c5273148c510bd7454
|
blaze/compute/air/frontend/ckernel_impls.py
|
blaze/compute/air/frontend/ckernel_impls.py
|
"""
Lift ckernels to their appropriate rank so they always consume the full array
arguments.
"""
from __future__ import absolute_import, division, print_function
import datashape
from pykit.ir import transform, Op
#------------------------------------------------------------------------
# Run
#------------------------------------------------------------------------
def run(func, env):
strategies = env['strategies']
transform(CKernelImplementations(strategies), func)
#------------------------------------------------------------------------
# Extract CKernel Implementations
#------------------------------------------------------------------------
class CKernelImplementations(object):
"""
For kernels that are implemented via ckernels, this
grabs the ckernel_deferred and turns it into a ckernel
op.
"""
def __init__(self, strategies):
self.strategies = strategies
def op_kernel(self, op):
if self.strategies[op] != 'ckernel':
return
function = op.metadata['kernel']
overload = op.metadata['overload']
# Default overload is CKERNEL, so no need to look it up again
func = overload.func
polysig = overload.sig
monosig = overload.resolved_sig
argtypes = datashape.coretypes.Tuple(monosig.argtypes)
impl = overload.func
assert monosig == overload.resolved_sig, (monosig,
overload.resolved_sig)
new_op = Op('ckernel', op.type, [impl, op.args[1:]], op.result)
new_op.add_metadata({'rank': 0,
'parallel': True})
return new_op
|
"""
Convert 'kernel' Op to 'ckernel'.
"""
from __future__ import absolute_import, division, print_function
from pykit.ir import transform, Op
def run(func, env):
strategies = env['strategies']
transform(CKernelImplementations(strategies), func)
class CKernelImplementations(object):
"""
For kernels that are implemented via ckernels, this
grabs the ckernel_deferred and turns it into a ckernel
op.
"""
def __init__(self, strategies):
self.strategies = strategies
def op_kernel(self, op):
if self.strategies[op] != 'ckernel':
return
# Default overload is CKERNEL, so no need to look it up again
overload = op.metadata['overload']
impl = overload.func
new_op = Op('ckernel', op.type, [impl, op.args[1:]], op.result)
new_op.add_metadata({'rank': 0,
'parallel': True})
return new_op
|
Simplify the ckernel pass a bit more
|
Simplify the ckernel pass a bit more
|
Python
|
bsd-3-clause
|
ChinaQuants/blaze,jdmcbr/blaze,xlhtc007/blaze,aterrel/blaze,FrancescAlted/blaze,mrocklin/blaze,maxalbert/blaze,alexmojaki/blaze,dwillmer/blaze,cowlicks/blaze,LiaoPan/blaze,jcrist/blaze,maxalbert/blaze,mrocklin/blaze,cowlicks/blaze,ChinaQuants/blaze,aterrel/blaze,scls19fr/blaze,mwiebe/blaze,FrancescAlted/blaze,nkhuyu/blaze,scls19fr/blaze,ContinuumIO/blaze,xlhtc007/blaze,alexmojaki/blaze,nkhuyu/blaze,caseyclements/blaze,LiaoPan/blaze,FrancescAlted/blaze,FrancescAlted/blaze,jcrist/blaze,jdmcbr/blaze,dwillmer/blaze,mwiebe/blaze,mwiebe/blaze,mwiebe/blaze,ContinuumIO/blaze,cpcloud/blaze,aterrel/blaze,caseyclements/blaze,cpcloud/blaze
|
970978b5355259fe943d5efed1b8b4ce945fdfa7
|
weather.py
|
weather.py
|
#! /usr/bin/python2
from os.path import expanduser,isfile
from sys import argv
from urllib import urlopen
location_path="~/.location"
def location_from_homedir():
if isfile(expanduser(location_path)):
with open(expanduser(location_path)) as f:
return "&".join(f.read().split("\n"))
else:
print("no location file at ", location_path)
def location_from_file(file):
try:
f = open(expanduser(file),'r')
except:
print("file ", location_file, " not found")
location_from_homedir
if len(argv) == 1:
# not given location file
data = location_from_homedir()
elif len(argv) == 2:
# given location file
data = location_from_file(argv[1])
else:
# wrong number of arguments
print("Usage: ", argv[0], " [location file]")
url="http://forecast.weather.gov/MapClick.php?"+data+"FcstType=digitalDWML"
forecast = urlopen(url).read()
|
#! /usr/bin/python2
from os.path import expanduser,isfile
import sys
from urllib import urlopen
location_path="~/.location"
def location_from_homedir():
if isfile(expanduser(location_path)):
with open(expanduser(location_path)) as f:
return "&".join(f.read().split("\n"))
else:
print("no location file at ", location_path)
sys.exit(2)
def location_from_file(location_file):
try:
f = open(expanduser(location_file),'r')
except:
print("file ", location_file, " not found\nLooking in home directory")
return location_from_homedir()
if len(sys.argv) == 1:
# not given location file
data = location_from_homedir()
elif len(sys.argv) == 2:
# given location file
data = location_from_file(sys.argv[1])
else:
# wrong number of arguments
print("Usage: ", sys.argv[0], " [location file]")
sys.exit(1)
url="http://forecast.weather.gov/MapClick.php?"+data+"FcstType=digitalDWML"
forecast = urlopen(url).read()
|
Debug control flow and exit on errors
|
Debug control flow and exit on errors
|
Python
|
mit
|
robbystk/weather
|
1caace2631f8e9c38cf0adfb1179a5260dcd3c33
|
tools/management/commands/output_all_uniprot.py
|
tools/management/commands/output_all_uniprot.py
|
from django.core.management.base import BaseCommand, CommandError
from django.core.management import call_command
from django.conf import settings
from django.db import connection
from django.db.models import Q
from django.template.loader import render_to_string
from protein.models import Protein
from residue.models import ResidueGenericNumber, ResidueGenericNumberEquivalent
from common import definitions
from common.selection import SelectionItem
from common.alignment_gpcr import Alignment
import xlsxwriter, xlrd
import logging, json, os
class Command(BaseCommand):
help = "Output all uniprot mappings"
logger = logging.getLogger(__name__)
def handle(self, *args, **options):
#Get the proteins
f = open('uniprot.json', 'w')
ps = Protein.objects.filter(Q(source__name='SWISSPROT') | Q(source__name='TREMBL'),web_links__web_resource__slug='uniprot').all().prefetch_related('web_links__web_resource')
print('total:',len(ps))
mapping = {}
for p in ps:
uniprot = p.web_links.get(web_resource__slug='uniprot')
mapping[p.entry_name] = uniprot.index
json.dump(mapping,f, indent=4, separators=(',', ': '))
# print("Seqs: {}\tNot matching: {}".format(num_of_sequences, num_of_non_matching_sequences))
# open("uniprot.txt", "w").write()
|
from django.core.management.base import BaseCommand, CommandError
from django.core.management import call_command
from django.conf import settings
from django.db import connection
from django.db.models import Q
from django.template.loader import render_to_string
from protein.models import Protein
from residue.models import ResidueGenericNumber, ResidueGenericNumberEquivalent
from common import definitions
from common.selection import SelectionItem
from common.alignment_gpcr import Alignment
import xlsxwriter, xlrd
import logging, json, os
class Command(BaseCommand):
help = "Output all uniprot mappings"
logger = logging.getLogger(__name__)
def handle(self, *args, **options):
#Get the proteins
f = open('uniprot.json', 'w')
ps = Protein.objects.filter(Q(source__name='SWISSPROT') | Q(source__name='TREMBL'),web_links__web_resource__slug='uniprot').all().prefetch_related('web_links__web_resource')
print('total:',len(ps))
mapping = {}
for p in ps:
uniprot = p.web_links.filter(web_resource__slug='uniprot').values_list('index', flat = True)
mapping[p.entry_name] = list(uniprot)
json.dump(mapping,f, indent=4, separators=(',', ': '))
# print("Seqs: {}\tNot matching: {}".format(num_of_sequences, num_of_non_matching_sequences))
# open("uniprot.txt", "w").write()
|
Change output_all_unitprot to allow multi ids for some proteins.
|
Change output_all_unitprot to allow multi ids for some proteins.
|
Python
|
apache-2.0
|
cmunk/protwis,fosfataza/protwis,fosfataza/protwis,fosfataza/protwis,cmunk/protwis,protwis/protwis,cmunk/protwis,cmunk/protwis,fosfataza/protwis,protwis/protwis,protwis/protwis
|
abd3daed5cd0c70d76bf8fa1cfdda93efcda3e70
|
knights/compat/django.py
|
knights/compat/django.py
|
from django.core.urlresolvers import reverse
from django.utils.encoding import iri_to_uri
import datetime
from knights.library import Library
register = Library()
@register.helper
def now(fmt):
return datetime.datetime.now().strftime(fmt)
@register.helper
def url(name, *args, **kwargs):
try:
return reverse(name, args=args, kwargs=kwargs)
except:
return None
@register.helper
def static(filename):
try:
from django.conf import settings
except ImportError:
prefix = ''
else:
prefix = iri_to_uri(getattr(settings, filename, ''))
return prefix
|
from django.core.urlresolvers import reverse
from django.utils import timezone
from django.utils.encoding import iri_to_uri
import datetime
from knights.library import Library
register = Library()
@register.helper
def now(fmt):
return timezone.now().strftime(fmt)
@register.helper
def url(name, *args, **kwargs):
try:
return reverse(name, args=args, kwargs=kwargs)
except:
return None
@register.helper
def static(filename):
try:
from django.conf import settings
except ImportError:
prefix = ''
else:
prefix = iri_to_uri(getattr(settings, filename, ''))
return prefix
|
Make the `now` helper timezone aware
|
Make the `now` helper timezone aware
Thanks @tysonclugg
|
Python
|
mit
|
funkybob/knights-templater,funkybob/knights-templater
|
52a6ea1e7dd4333b9db6a0bbd53b8ae0b39a1f6d
|
Designs/redundant.py
|
Designs/redundant.py
|
'''Due to the needs arising from completing the project on time, I have defined redundant.py
which will hold replacement modules as I migrate from file based application to lists only web application. This modules
so far will offer the capabilities of registration, creating a shopping list and adding items into
a shopping list'''
global account
account=[]
def register(username,email,password):
account.append(username)
account.append(email)
account.append(password)
return account
global shopping_list_container
shopping_list_container=[]#contain shopping lists only
def create(list_name):
#list_name=[]
shopping_list_container.append(list_name)
return shopping_list_container#list of dictionaries
def list_update(nameoflist,item):
nameoflist.append(item)
shopping_list_container.append(nameoflist)
global itemsdictionary
itemsdictionary={}
def create1(slist):
itemsdictionary.update(slist)
global shared_shopping_list_container
shared_shopping_list_container=[]
def create3(list_name):
#list_name=[]
shared_shopping_list_container.append(list_name)
return shared_shopping_list_container#list of dictionaries
global shareditemsdictionary
shareditemsdictionary={}
def create2(slist):
shareditemsdictionary.update(slist)
|
'''Due to the needs arising from completing the project on time, I have defined redundant.py
which will hold replacement modules as I migrate from file based application to lists only web application. This modules
so far will offer the capabilities of registration, creating a shopping list and adding items into
a shopping list'''
global account
account=[]
def register(username,email,password):
'''registration list'''
account.append(username)
account.append(email)
account.append(password)
return account
global shopping_list_container
shopping_list_container=[]#contain shopping lists only
def create(list_name):
'''container of names of shopping lists'''
#list_name=[]
shopping_list_container.append(list_name)
return shopping_list_container#list of dictionaries
def list_update(nameoflist,item):
'''adding item to a given name of list'''
nameoflist.append(item)
shopping_list_container.append(nameoflist)
global itemsdictionary
itemsdictionary={}
def create1(slist):
'''update shopping lists with key (names) and items(as dictionaris)'''
itemsdictionary.update(slist)
global shared_shopping_list_container
shared_shopping_list_container=[]
def create3(list_name):
'''container for the shared lists. In future may be integrated with facebook'''
#list_name=[]
shared_shopping_list_container.append(list_name)
return shared_shopping_list_container#list of dictionaries
global shareditemsdictionary
shareditemsdictionary={}
def create2(slist):
'''updating shared dictionary'''
shareditemsdictionary.update(slist)
|
Add __doc__ to module functions
|
[Fix] Add __doc__ to module functions
|
Python
|
mit
|
AndersonMasese/Myshop,AndersonMasese/Myshop,AndersonMasese/Myshop
|
5fbb4ff5d3427c8f4050fc5b75d4a6a2c15351c6
|
pelicanconf.py
|
pelicanconf.py
|
#!/usr/bin/env python
# -*- coding: utf-8 -*- #
from __future__ import unicode_literals
AUTHOR = 'Donne Martin'
SITENAME = 'Donne Martin'
SITEURL = ''
PATH = 'content'
TIMEZONE = 'America/New_York'
DEFAULT_LANG = 'en'
# Feed generation is usually not desired when developing
FEED_ALL_ATOM = None
CATEGORY_FEED_ATOM = None
TRANSLATION_FEED_ATOM = None
AUTHOR_FEED_ATOM = None
AUTHOR_FEED_RSS = None
HIDE_SIDEBAR = True
# Blogroll
LINKS = (('Pelican', 'http://getpelican.com/'),
('Python.org', 'http://python.org/'),
('Jinja2', 'http://jinja.pocoo.org/'),
('You can modify those links in your config file', '#'),)
# Social widget
SOCIAL = (('You can add links in your config file', '#'),
('Another social link', '#'),)
STATIC_PATHS = [
'images',
'extra/favicon.ico'
]
EXTRA_PATH_METADATA = {
'extra/favicon.ico': {'path': 'favicon.ico'}
}
DEFAULT_PAGINATION = 10
# Uncomment following line if you want document-relative URLs when developing
RELATIVE_URLS = True
# THEME = 'pelican-bootstrap3'
# BOOTSTRAP_THEME = 'readable'
THEME = 'startbootstrap-agency'
BOOTSTRAP_THEME = ''
|
#!/usr/bin/env python
# -*- coding: utf-8 -*- #
from __future__ import unicode_literals
AUTHOR = 'Donne Martin'
SITENAME = 'Donne Martin'
SITEURL = ''
PATH = 'content'
TIMEZONE = 'America/New_York'
DEFAULT_LANG = 'en'
# Feed generation is usually not desired when developing
FEED_ALL_ATOM = None
CATEGORY_FEED_ATOM = None
TRANSLATION_FEED_ATOM = None
AUTHOR_FEED_ATOM = None
AUTHOR_FEED_RSS = None
HIDE_SIDEBAR = True
PYGMENTS_STYLE = 'monokai'
# Blogroll
LINKS = (('Pelican', 'http://getpelican.com/'),
('Python.org', 'http://python.org/'),
('Jinja2', 'http://jinja.pocoo.org/'),
('You can modify those links in your config file', '#'),)
# Social widget
SOCIAL = (('You can add links in your config file', '#'),
('Another social link', '#'),)
STATIC_PATHS = [
'images',
'extra/favicon.ico'
]
EXTRA_PATH_METADATA = {
'extra/favicon.ico': {'path': 'favicon.ico'}
}
DEFAULT_PAGINATION = 10
# Uncomment following line if you want document-relative URLs when developing
RELATIVE_URLS = True
# THEME = 'pelican-bootstrap3'
# BOOTSTRAP_THEME = 'readable'
THEME = 'startbootstrap-agency'
BOOTSTRAP_THEME = ''
|
Set pygments style to monokai.
|
Set pygments style to monokai.
|
Python
|
mit
|
donnemartin/outdated-donnemartin.github.io,donnemartin/outdated-donnemartin.github.io,donnemartin/outdated-donnemartin.github.io,donnemartin/outdated-donnemartin.github.io,donnemartin/outdated-donnemartin.github.io
|
fbdaeff6f01ffaf0ac4f9a0d0d962a19c2865b32
|
jupyterlab/labhubapp.py
|
jupyterlab/labhubapp.py
|
import os
import warnings
from traitlets import default
from .labapp import LabApp
try:
from jupyterhub.singleuser import SingleUserNotebookApp
except ImportError:
SingleUserLabApp = None
raise ImportError('You must have jupyterhub installed for this to work.')
else:
class SingleUserLabApp(SingleUserNotebookApp, LabApp):
@default("default_url")
def _default_url(self):
"""when using jupyter-labhub, jupyterlab is default ui"""
return "/lab"
def init_webapp(self, *args, **kwargs):
warnings.warn(
"SingleUserLabApp is deprecated, use SingleUserNotebookApp and set " + \
"c.Spawner.default_url = '/lab' in jupyterhub_config.py", DeprecationWarning
)
super().init_webapp(*args, **kwargs)
def main(argv=None):
return SingleUserLabApp.launch_instance(argv)
if __name__ == "__main__":
main()
|
import os
from traitlets import default
from .labapp import LabApp
try:
from jupyterhub.singleuser import SingleUserNotebookApp
except ImportError:
SingleUserLabApp = None
raise ImportError('You must have jupyterhub installed for this to work.')
else:
class SingleUserLabApp(SingleUserNotebookApp, LabApp):
"""
A sublcass of JupyterHub's SingleUserNotebookApp which includes LabApp
as a mixin. This makes the LabApp configurables available to the spawned
jupyter server.
If you don't need to change any of the configurables from their default
values, then this class is not necessary, and you can deploy JupyterLab
by ensuring that its server extension is enabled and setting the
`Spawner.default_url` to '/lab'.
If you do need to configure JupyterLab, then use this application by
setting `Spawner.cmd = ['jupyter-labhub']`.
"""
@default("default_url")
def _default_url(self):
"""when using jupyter-labhub, jupyterlab is default ui"""
return "/lab"
def init_webapp(self, *args, **kwargs):
super().init_webapp(*args, **kwargs)
def main(argv=None):
return SingleUserLabApp.launch_instance(argv)
if __name__ == "__main__":
main()
|
Add docstring documenting the intended use of LabHubApp.
|
Add docstring documenting the intended use of LabHubApp.
|
Python
|
bsd-3-clause
|
jupyter/jupyterlab,jupyter/jupyterlab,jupyter/jupyterlab,jupyter/jupyterlab,jupyter/jupyterlab
|
de9f9c07c6f1dde8d7ad314b6a6fb58a963e1558
|
geodj/youtube.py
|
geodj/youtube.py
|
from gdata.youtube.service import YouTubeService, YouTubeVideoQuery
from django.utils.encoding import smart_str
import re
class YoutubeMusic:
def __init__(self):
self.service = YouTubeService()
def search(self, artist):
query = YouTubeVideoQuery()
query.vq = artist
query.orderby = 'relevance'
query.racy = 'exclude'
query.format = '5'
query.categories.append("/Music")
feed = self.service.YouTubeQuery(query)
results = []
for entry in feed.entry:
if not self.is_valid_entry(artist, entry):
continue
results.append({
'url': entry.media.player.url,
'title': smart_str(entry.media.title.text),
'duration': int(entry.media.duration.seconds),
})
return {'artist': artist, 'results': results}
def is_valid_entry(self, artist, entry):
duration = int(entry.media.duration.seconds)
title = smart_str(entry.media.title.text).lower()
if entry.rating is not None and float(entry.rating.average) < 3.5:
return False
if duration < (2 * 60) or duration > (9 * 60):
return False
if artist.lower() not in title:
return False
if re.search("\b(concert|cover)\b", title):
return False
return True
|
from gdata.youtube.service import YouTubeService, YouTubeVideoQuery
from django.utils.encoding import smart_str
import re
class YoutubeMusic:
def __init__(self):
self.service = YouTubeService()
def search(self, artist):
query = YouTubeVideoQuery()
query.vq = artist
query.orderby = 'relevance'
query.racy = 'exclude'
query.format = '5'
query.max_results = 50
query.categories.append("/Music")
feed = self.service.YouTubeQuery(query)
results = []
for entry in feed.entry:
if not self.is_valid_entry(artist, entry):
continue
results.append({
'url': entry.media.player.url,
'title': smart_str(entry.media.title.text),
'duration': int(entry.media.duration.seconds),
})
return {'artist': artist, 'results': results}
def is_valid_entry(self, artist, entry):
duration = int(entry.media.duration.seconds)
title = smart_str(entry.media.title.text).lower()
if entry.rating is not None and float(entry.rating.average) < 3.5:
return False
if duration < (2 * 60) or duration > (9 * 60):
return False
if artist.lower() not in title:
return False
if re.search("\b(concert|cover)\b", title):
return False
return True
|
Return as many results as possible
|
Return as many results as possible
|
Python
|
mit
|
6/GeoDJ,6/GeoDJ
|
db1653c551f71092a7eca96e6a4d1c96ef17e06a
|
lib/rapidsms/message.py
|
lib/rapidsms/message.py
|
#!/usr/bin/env python
# vim: ai ts=4 sts=4 et sw=4
import copy
class Message(object):
def __init__(self, backend, caller=None, text=None):
self._backend = backend
self.caller = caller
self.text = text
# initialize some empty attributes
self.received = None
self.sent = None
self.responses = []
def __unicode__(self):
return self.text
@property
def backend(self):
# backend is read-only, since it's an
# immutable property of this object
return self._backend
def send(self):
"""Send this message via self.backend, returning
True if the message was sent successfully."""
return self.backend.router.outgoing(self)
def flush_responses (self):
for response in self.responses:
response.send()
def respond(self, text):
"""Send the given text back to the original caller of this
message on the same route that it came in on"""
if self.caller:
response = copy.copy(self)
response.text = text
self.responses.append(response)
return True
else:
return False
|
#!/usr/bin/env python
# vim: ai ts=4 sts=4 et sw=4
import copy
class Message(object):
def __init__(self, backend, caller=None, text=None):
self._backend = backend
self.caller = caller
self.text = text
self.responses = []
def __unicode__(self):
return self.text
@property
def backend(self):
# backend is read-only, since it's an
# immutable property of this object
return self._backend
def send(self):
"""Send this message via self.backend, returning
True if the message was sent successfully."""
return self.backend.router.outgoing(self)
def flush_responses (self):
for response in self.responses:
response.send()
self.responses.remove(response)
def respond(self, text):
"""Send the given text back to the original caller of this
message on the same route that it came in on"""
if self.caller:
response = copy.copy(self)
response.text = text
self.responses.append(response)
return True
else:
return False
|
Remove unused attributes; also, empty responses after it's flushed.
|
Remove unused attributes; also, empty responses after it's flushed.
|
Python
|
bsd-3-clause
|
rapidsms/rapidsms-legacy,rapidsms/rapidsms-legacy,rapidsms/rapidsms-legacy
|
4b54d1472a57ad4d45293ec7bdce9a0ed9746bde
|
ideasbox/mixins.py
|
ideasbox/mixins.py
|
from django.views.generic import ListView
class ByTagListView(ListView):
def get_queryset(self):
qs = super(ByTagListView, self).get_queryset()
if 'tag' in self.kwargs:
qs = qs.filter(tags__slug__in=[self.kwargs['tag']])
return qs
def get_context_data(self, **kwargs):
context = super(ByTagListView, self).get_context_data(**kwargs)
context['tag'] = self.kwargs.get('tag')
return context
|
from django.views.generic import ListView
from taggit.models import Tag
class ByTagListView(ListView):
def get_queryset(self):
qs = super(ByTagListView, self).get_queryset()
if 'tag' in self.kwargs:
qs = qs.filter(tags__slug__in=[self.kwargs['tag']])
return qs
def get_context_data(self, **kwargs):
context = super(ByTagListView, self).get_context_data(**kwargs)
context['tag'] = Tag.objects.get(slug=self.kwargs.get('tag'))
return context
|
Use tag name not slug in tag page title
|
Use tag name not slug in tag page title
|
Python
|
agpl-3.0
|
ideascube/ideascube,ideascube/ideascube,ideascube/ideascube,Lcaracol/ideasbox.lan,Lcaracol/ideasbox.lan,Lcaracol/ideasbox.lan,ideascube/ideascube
|
72539e1a83eba8db9adfdeef6099081475ef8d86
|
objectset/forms.py
|
objectset/forms.py
|
from django import forms
from .models import ObjectSet
def objectset_form_factory(Model, queryset=None):
"""Takes an ObjectSet subclass and defines a base form class.
In addition, an optional queryset can be supplied to limit the choices
for the objects.
This uses the generic `objects` field rather being named after a specific
type.
"""
# A few checks to keep things sane..
if not issubclass(Model, ObjectSet):
raise TypeError('{0} must subclass ObjectSet'.format(Model.__name__))
instance = Model()
if queryset is None:
queryset = instance._object_class._default_manager.all()
elif queryset.model is not instance._object_class:
raise TypeError('ObjectSet of type {0}, not {1}'
.format(instance._object_class.__name__,
queryset.model.__name__))
label = getattr(Model, instance._set_object_rel).field.verbose_name
class form_class(forms.ModelForm):
objects = forms.ModelMultipleChoiceField(queryset, label=label,
required=False)
def save(self, *args, **kwargs):
self.instance._pending = self.cleaned_data.get('objects')
return super(form_class, self).save(*args, **kwargs)
class Meta(object):
model = Model
exclude = (instance._set_object_rel,)
form_class.__name__ = '{0}Form'.format(Model.__name__)
return form_class
|
from django import forms
from .models import ObjectSet
def objectset_form_factory(Model, queryset=None):
"""Takes an ObjectSet subclass and defines a base form class.
In addition, an optional queryset can be supplied to limit the choices
for the objects.
This uses the generic `objects` field rather being named after a specific
type.
"""
# A few checks to keep things sane..
if not issubclass(Model, ObjectSet):
raise TypeError('{0} must subclass ObjectSet'.format(Model.__name__))
instance = Model()
if queryset is None:
queryset = instance._object_class._default_manager.all()
elif queryset.model is not instance._object_class:
raise TypeError('ObjectSet of type {0}, not {1}'
.format(instance._object_class.__name__,
queryset.model.__name__))
label = getattr(Model, instance._set_object_rel).field.verbose_name
class form_class(forms.ModelForm):
objects = forms.ModelMultipleChoiceField(queryset, label=label,
required=False)
def save(self, *args, **kwargs):
objects = self.cleaned_data.get('objects')
# Django 1.4 nuance when working with an empty list. It is not
# properly defined an empty query set
if isinstance(objects, list) and not objects:
objects = self.instance.__class__.objects.none()
self.instance._pending = objects
return super(form_class, self).save(*args, **kwargs)
class Meta(object):
model = Model
exclude = (instance._set_object_rel,)
form_class.__name__ = '{0}Form'.format(Model.__name__)
return form_class
|
Handle Django 1.4 nuance for the empty ModelMultipleChoiceField values
|
Handle Django 1.4 nuance for the empty ModelMultipleChoiceField values
|
Python
|
bsd-2-clause
|
chop-dbhi/django-objectset,chop-dbhi/django-objectset
|
6694a9e8d554c9450cdf6cd076bb56a324048b44
|
social/apps/django_app/urls.py
|
social/apps/django_app/urls.py
|
"""URLs module"""
from django.conf import settings
try:
from django.conf.urls import patterns, url
except ImportError:
# Django < 1.4
from django.conf.urls.defaults import patterns, url
from social.utils import setting_name
extra = getattr(settings, setting_name('TRAILING_SLASH'), True) and '/' or ''
urlpatterns = patterns('social.apps.django_app.views',
# authentication / association
url(r'^login/(?P<backend>[^/]+){0}$'.format(extra), 'auth',
name='begin'),
url(r'^complete/(?P<backend>[^/]+){0}$'.format(extra), 'complete',
name='complete'),
# disconnection
url(r'^disconnect/(?P<backend>[^/]+){0}$'.format(extra), 'disconnect',
name='disconnect'),
url(r'^disconnect/(?P<backend>[^/]+)/(?P<association_id>[^/]+){0}$'
.format(extra), 'disconnect', name='disconnect_individual'),
)
|
"""URLs module"""
from django import VERSION
from django.conf import settings
from django.conf.urls import url
from social.apps.django_app import views
from social.utils import setting_name
extra = getattr(settings, setting_name('TRAILING_SLASH'), True) and '/' or ''
urlpatterns = (
# authentication / association
url(r'^login/(?P<backend>[^/]+){0}$'.format(extra),
views.auth,
name='begin'),
url(r'^complete/(?P<backend>[^/]+){0}$'.format(extra),
views.complete,
name='complete'),
# disconnection
url(r'^disconnect/(?P<backend>[^/]+){0}$'.format(extra),
views.disconnect,
name='disconnect'),
url(r'^disconnect/(?P<backend>[^/]+)/(?P<association_id>[^/]+){0}$'
.format(extra),
views.disconnect,
name='disconnect_individual'),
)
|
Update the url patterns to be compliant with Django 1.9 new formatting
|
Update the url patterns to be compliant with Django 1.9 new formatting
so need to support Django < 1.8 because it is now deprecated for
security reasons
|
Python
|
bsd-3-clause
|
cmichal/python-social-auth,cmichal/python-social-auth,cmichal/python-social-auth
|
5c0282810f298762bdd00c260f40e2ceb7914eb0
|
tests/test_dna.py
|
tests/test_dna.py
|
#!/usr/bin/env python2
import pytest
from kbkdna.dna import *
def test_reverse_complement():
assert reverse_complement('ATGC') == 'GCAT'
def test_gc_content():
assert gc_content('ATGC') == 0.5
|
#!/usr/bin/env python2
import pytest
import kbkdna
def test_reverse_complement():
assert kbkdna.reverse_complement('ATGC') == 'GCAT'
def test_gc_content():
assert kbkdna.gc_content('ATGC') == 0.5
|
Simplify the imports in the tests.
|
Simplify the imports in the tests.
|
Python
|
mit
|
kalekundert/kbkdna
|
1e62c328bb42ec123e75b5c66fb29f002cd57db2
|
tests/test_nap.py
|
tests/test_nap.py
|
from nap.api import Api
from . import HttpServerTestBase
class TestNap(HttpServerTestBase):
def test_unallowed_method(self):
"""Tries to use non-existent HTTP method"""
api = Api('http://localhost:8888')
with self.assertRaises(AttributeError):
api.resource.nonexisting()
|
"""
Tests for nap module.
These tests only focus that requests is called properly.
Everything related to HTTP requests should be tested in requests' own tests.
"""
import unittest
import requests
from nap.api import Api
class TestNap(unittest.TestCase):
def test_unallowed_method(self):
"""Tries to use non-existent HTTP method"""
api = Api('')
# lambda trickery is necessary, because otherwise it would raise
# AttributeError uncontrolled
self.assertRaises(AttributeError, lambda: api.resource.nonexisting)
def test_requests_raises_error(self):
"""Test that requests properly raises its own errors
>>> requests.get('/kk')
requests.exceptions.MissingSchema: Invalid URL u'/kk':
No schema supplied. Perhaps you meant http:///kk?
"""
api = Api('')
self.assertRaises(requests.exceptions.MissingSchema, api.resource.get)
def test_resource_not_callable(self):
"""Make sure resource can't be called directly"""
api = Api('')
self.assertRaises(TypeError, api.resource)
|
Document module and add couple of tests
|
Document module and add couple of tests
|
Python
|
mit
|
kimmobrunfeldt/nap
|
5f72b6edc28caa7bf03720ed27a9f3aa32c8323e
|
go/billing/management/commands/go_gen_statements.py
|
go/billing/management/commands/go_gen_statements.py
|
from datetime import datetime
from optparse import make_option
from go.billing.models import Account
from go.billing.tasks import month_range, generate_monthly_statement
from go.base.command_utils import BaseGoCommand, get_user_by_email
class Command(BaseGoCommand):
help = "Generate monthly billing statements for an account."
option_list = BaseGoCommand.option_list + (
make_option(
'--email-address', dest='email_address',
help="Email address of the account to generate statements for."),
make_option(
'--month', dest='month', action='append',
help="Month to generate statements for in the form YYYY-MM, "
"e.g. 2014-01. Multiple may be specified."))
def handle(self, *args, **opts):
user = get_user_by_email(opts['email_address'])
account_number = user.get_profile().user_account
account = Account.objects.get(account_number=account_number)
self.stdout.write(
"Generating statements for account %s..."
% (opts['email_address'],))
months = [datetime.strptime(m, '%Y-%m') for m in opts['months']]
for month in months:
from_date, to_date = month_range(0, month)
generate_monthly_statement(account.id, from_date, to_date)
self.stdout.write("Generated statement for %s." % (month,))
|
from datetime import datetime
from optparse import make_option
from go.billing.models import Account
from go.billing.tasks import month_range, generate_monthly_statement
from go.base.command_utils import BaseGoCommand, get_user_by_email
class Command(BaseGoCommand):
help = "Generate monthly billing statements for an account."
option_list = BaseGoCommand.option_list + (
make_option(
'--email-address', dest='email_address',
help="Email address of the account to generate statements for."),
make_option(
'--month', dest='month', action='append',
help="Month to generate statements for in the form YYYY-MM, "
"e.g. 2014-01. Multiple may be specified."))
def handle(self, *args, **opts):
user = get_user_by_email(opts['email_address'])
account_number = user.get_profile().user_account
account = Account.objects.get(account_number=account_number)
self.stdout.write(
"Generating statements for account %s..."
% (opts['email_address'],))
months = [datetime.strptime(m, '%Y-%m') for m in opts['month']]
for month in months:
from_date, to_date = month_range(0, month)
generate_monthly_statement(account.id, from_date, to_date)
self.stdout.write(
"Generated statement for %s."
% (datetime.strftime(month, '%Y-%m'),))
|
Fix broken billing statement command tests
|
Fix broken billing statement command tests
|
Python
|
bsd-3-clause
|
praekelt/vumi-go,praekelt/vumi-go,praekelt/vumi-go,praekelt/vumi-go
|
1e8f9a95badc1e2b558bae7570ef9bc23f26a0df
|
pyhaystack/info.py
|
pyhaystack/info.py
|
# -*- coding: utf-8 -*-
"""
File : pyhaystackTest.py (2.x)
This module allow a connection to a haystack server
Feautures provided allow user to fetch data from the server and eventually, to post to it.
See http://www.project-haystack.org for more details
Project Haystack is an open source initiative to streamline working with data from the Internet of Things. We standardize semantic data models and web services with the goal of making it easier to unlock value from the vast quantity of data being generated by the smart devices that permeate our homes, buildings, factories, and cities. Applications include automation, control, energy, HVAC, lighting, and other environmental systems.
"""
__author__ = 'Christian Tremblay, @sjlongland, @sudo-Whateverman, Igor'
__author_email__ = 'christian.tremblay@servisys.com'
__version__ = '0.71.1.8.2'
__license__ = 'LGPL'
|
# -*- coding: utf-8 -*-
"""
File : pyhaystackTest.py (2.x)
This module allow a connection to a haystack server
Feautures provided allow user to fetch data from the server and eventually, to post to it.
See http://www.project-haystack.org for more details
Project Haystack is an open source initiative to streamline working with data from the Internet of Things. We standardize semantic data models and web services with the goal of making it easier to unlock value from the vast quantity of data being generated by the smart devices that permeate our homes, buildings, factories, and cities. Applications include automation, control, energy, HVAC, lighting, and other environmental systems.
"""
__author__ = 'Christian Tremblay, Stuart J. Longland, @sudo-Whateverman, Igor'
__author_email__ = 'christian.tremblay@servisys.com'
__version__ = '0.72'
__license__ = 'LGPL'
|
Modify version to 0.72 to mark change
|
Modify version to 0.72 to mark change
Signed-off-by: Christian Tremblay <31ac1ca2e4859489ad6997067c1b3a4264642859@servisys.com>
|
Python
|
apache-2.0
|
ChristianTremblay/pyhaystack,vrtsystems/pyhaystack,ChristianTremblay/pyhaystack
|
36ea751618287a75fc82db500d953d4fa40b373b
|
tests/containers/entrypoint/renew-demo-token.py
|
tests/containers/entrypoint/renew-demo-token.py
|
#!/usr/bin/python3
import os
import json
import time
from urllib import request
# Create the requested json
demo_json = {
"payload": {
"aud": "ANY",
"ver": "scitokens:2.0",
"scope": "condor:/READ condor:/WRITE",
"exp": int(time.time() + 3600*8),
"sub": "abh3"
}
}
# Convert the format from dictionary to json string
data = json.dumps({
'payload': json.dumps(demo_json['payload']),
"algorithm": "ES256"
}).encode()
# Headers so that heroku doesn't block us
headers = {
'User-Agent': 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_9_3)' +
'AppleWebKit/537.36 (KHTML, like Gecko) Chrome/35.0.1916.47 Safari/537.36',
'Content-Type': 'application/json'
}
# The actual request
req = request.Request("https://demo.scitokens.org/issue",
data=data,
headers=headers) # this will make the method "POST"
resp = request.urlopen(req).read()
# Convert the "bytes" response to text
token_path = os.environ.get('BEARER_TOKEN', '') or \
f"/tmp/bt_u{os.geteuid()}"
with open(token_path, 'w') as f:
f.write(resp.decode('utf-8'))
|
#!/usr/bin/python3
import os
import json
import time
from urllib import request
# Request payload
payload = {"aud": "ANY",
"ver": "scitokens:2.0",
"scope": "condor:/READ condor:/WRITE",
"exp": int(time.time() + 3600*8),
"sub": "abh3"
}
# Convert the format from dictionary to json string
data = json.dumps({
'payload': payload,
"algorithm": "ES256"
}).encode()
# Headers so that heroku doesn't block us
headers = {
'User-Agent': 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_9_3)' +
'AppleWebKit/537.36 (KHTML, like Gecko) Chrome/35.0.1916.47 Safari/537.36',
'Content-Type': 'application/json'
}
# The actual request
req = request.Request("https://demo.scitokens.org/issue",
data=data,
headers=headers) # this will make the method "POST"
resp = request.urlopen(req).read()
# Convert the "bytes" response to text
token_path = os.environ.get('BEARER_TOKEN', '') or \
f"/tmp/bt_u{os.geteuid()}"
with open(token_path, 'w') as f:
f.write(resp.decode('utf-8'))
|
Update token renewal due to demo.scitokens.org API update
|
Update token renewal due to demo.scitokens.org API update
|
Python
|
apache-2.0
|
matyasselmeci/htcondor-ce,brianhlin/htcondor-ce,matyasselmeci/htcondor-ce,brianhlin/htcondor-ce,matyasselmeci/htcondor-ce,brianhlin/htcondor-ce
|
1eacbac722ca949518e1a8e9d6a0a957e193ba9e
|
tests/functional/staging_and_prod/test_admin.py
|
tests/functional/staging_and_prod/test_admin.py
|
from retry.api import retry_call
from config import config
from tests.pages import UploadCsvPage
from tests.postman import (
send_notification_via_csv,
get_notification_by_id_via_api,
)
from tests.test_utils import assert_notification_body, recordtime, NotificationStatuses
@recordtime
def test_admin(driver, client, login_user):
upload_csv_page = UploadCsvPage(driver)
csv_sms_notification_id = send_notification_via_csv(upload_csv_page, 'sms')
csv_sms_notification = retry_call(
get_notification_by_id_via_api,
fargs=[client, csv_sms_notification_id, NotificationStatuses.SENT],
tries=config['notification_retry_times'],
delay=config['notification_retry_interval']
)
assert_notification_body(csv_sms_notification_id, csv_sms_notification)
csv_email_notification_id = send_notification_via_csv(upload_csv_page, 'email')
csv_email_notification = retry_call(
get_notification_by_id_via_api,
fargs=[client, csv_email_notification_id, NotificationStatuses.SENT],
tries=config['notification_retry_times'],
delay=config['notification_retry_interval']
)
assert_notification_body(csv_email_notification_id, csv_email_notification)
upload_csv_page.sign_out()
|
import pytest
from retry.api import retry_call
from config import config
from tests.pages import UploadCsvPage
from tests.postman import (
send_notification_via_csv,
get_notification_by_id_via_api,
)
from tests.test_utils import assert_notification_body, recordtime, NotificationStatuses
@pytest.mark.skip(reason="intermittent pager duty alerts due to queue backlog")
def test_admin(driver, client, login_user):
upload_csv_page = UploadCsvPage(driver)
csv_sms_notification_id = send_notification_via_csv(upload_csv_page, 'sms')
csv_sms_notification = retry_call(
get_notification_by_id_via_api,
fargs=[client, csv_sms_notification_id, NotificationStatuses.SENT],
tries=config['notification_retry_times'],
delay=config['notification_retry_interval']
)
assert_notification_body(csv_sms_notification_id, csv_sms_notification)
csv_email_notification_id = send_notification_via_csv(upload_csv_page, 'email')
csv_email_notification = retry_call(
get_notification_by_id_via_api,
fargs=[client, csv_email_notification_id, NotificationStatuses.SENT],
tries=config['notification_retry_times'],
delay=config['notification_retry_interval']
)
assert_notification_body(csv_email_notification_id, csv_email_notification)
upload_csv_page.sign_out()
|
Disable CSV upload tests temporarily
|
Disable CSV upload tests temporarily
When the database tasks queue builds up we get false pager duty alerts due to the time it takes for the test csv to get through to the front of the queue.
|
Python
|
mit
|
alphagov/notifications-functional-tests,alphagov/notifications-functional-tests
|
428889029541bb5c8f8998eb1f4cbc057a80fb87
|
s2v2.py
|
s2v2.py
|
from s2v1 import *
def number_of_records(data_sample):
return len(data_sample)
number_of_ties = number_of_records(data_from_csv)
print(number_of_ties, "ties in our data sample")
|
from s2v1 import *
def number_of_records(data_sample):
return len(data_sample)
number_of_ties = number_of_records(data_from_csv) - 1 # minus header row
print(number_of_ties, "ties in our data sample")
|
Subtract header row for acurate counting
|
Subtract header row for acurate counting
|
Python
|
mit
|
alexmilesyounger/ds_basics
|
bd7ef1be82a6cd68060dee47046d90202b3a9e0c
|
tempest/api/volume/test_availability_zone.py
|
tempest/api/volume/test_availability_zone.py
|
# Copyright 2014 NEC Corporation
# All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License"); you may
# not use this file except in compliance with the License. You may obtain
# a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
# WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
# License for the specific language governing permissions and limitations
# under the License.
from tempest.api.volume import base
from tempest.lib import decorators
class AvailabilityZoneTestJSON(base.BaseVolumeTest):
"""Tests Availability Zone API List"""
@classmethod
def setup_clients(cls):
super(AvailabilityZoneTestJSON, cls).setup_clients()
cls.client = cls.availability_zone_client
@decorators.idempotent_id('01f1ae88-eba9-4c6b-a011-6f7ace06b725')
def test_get_availability_zone_list(self):
# List of availability zone
availability_zone = (self.client.list_availability_zones()
['availabilityZoneInfo'])
self.assertNotEmpty(availability_zone)
|
# Copyright 2014 NEC Corporation
# All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License"); you may
# not use this file except in compliance with the License. You may obtain
# a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
# WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
# License for the specific language governing permissions and limitations
# under the License.
from tempest.api.volume import base
from tempest.lib import decorators
class AvailabilityZoneTestJSON(base.BaseVolumeTest):
"""Tests Availability Zone API List"""
@decorators.idempotent_id('01f1ae88-eba9-4c6b-a011-6f7ace06b725')
def test_get_availability_zone_list(self):
# List of availability zone
availability_zone = (
self.availability_zone_client.list_availability_zones()
['availabilityZoneInfo'])
self.assertNotEmpty(availability_zone)
|
Remove unnecessary client alias in AvailabilityZoneTestJson
|
Remove unnecessary client alias in AvailabilityZoneTestJson
The class AvailabilityZoneTestJson is inherited from base.BaseVolumeTest,
and the latter has already declared the availability_zone_client. This
patch removes the unnecessary client alias for availability_zone_client.
Change-Id: I287d742087a72928774325681bb70837ecad72f7
|
Python
|
apache-2.0
|
masayukig/tempest,masayukig/tempest,Juniper/tempest,Juniper/tempest,openstack/tempest,cisco-openstack/tempest,cisco-openstack/tempest,openstack/tempest
|
bbfb09205974efa969fc636b6e1079a84dad3619
|
mcstatus/application.py
|
mcstatus/application.py
|
from flask import Flask
from minecraft_query import MinecraftQuery
app = Flask(__name__)
@app.route('/mcstatus')
def returnStatus():
try:
query = MinecraftQuery("mc.voltaire.sh", 25565, 10, 3)
basicQuery = query.get_status()
fullQuery = query.get_rules()
except socket.error as e:
if not options.quiet:
return "Server is down or unreachable:\n" + e.message
if not options.quiet:
numOnline = 'The server has %d players filling %d total slots. There are %d free slots.' % (basicQuery['numplayers'], basicQuery['maxplayers'], basicQuery['maxplayers'] - basic_status['numplayers'])
playersOnline = 'Online now: %s' % (fullQuery['players'])
return numOnline + "\n" + playersOnline
return "ermahgerd"
if __name__ == '__main__':
app.run()
|
from flask import Flask
from minecraft_query import MinecraftQuery
app = Flask(__name__)
@app.route('/mcstatus')
def returnStatus():
query = MinecraftQuery("142.54.162.42", 25565)
basic_status = query.get_status()
all_status = query.get_rules()
server_info = 'The server has %d / %d players.' % (basic_status['numplayers'], basic_status['maxplayers'])
status_info = 'Online now: %s' % (all_status['players'])
return "<pre>" + server_info + "\n" + status_info + "</pre>"
if __name__ == '__main__':
app.run()
|
Revert "check for connection failure"
|
Revert "check for connection failure"
This reverts commit cf4bd49e150f5542a5a7abba908ca81ebe1b9e75.
|
Python
|
bsd-3-clause
|
voltaire/minecraft-site-old,voltaire/minecraft-site-old
|
906247c6431b85c90f8aec8a7f4f73f1064abeba
|
mezzanine/pages/urls.py
|
mezzanine/pages/urls.py
|
from django.conf.urls.defaults import patterns, url
# Page patterns.
urlpatterns = patterns("mezzanine.pages.views",
url("^admin_page_ordering/$", "admin_page_ordering",
name="admin_page_ordering"),
url("^(?P<slug>.*)/$", "page", name="page"),
)
|
from django.conf.urls.defaults import patterns, url
from django.conf import settings
# Page patterns.
urlpatterns = patterns("mezzanine.pages.views",
url("^admin_page_ordering/$", "admin_page_ordering",
name="admin_page_ordering"),
url("^(?P<slug>.*)" + ("/" if settings.APPEND_SLASH else "") + "$", "page", name="page"),
)
|
Use Page URLs without trailing slash when settings.APPEND_SLASH is False
|
Use Page URLs without trailing slash when settings.APPEND_SLASH is False
|
Python
|
bsd-2-clause
|
biomassives/mezzanine,AlexHill/mezzanine,spookylukey/mezzanine,frankchin/mezzanine,saintbird/mezzanine,adrian-the-git/mezzanine,jjz/mezzanine,agepoly/mezzanine,geodesign/mezzanine,jerivas/mezzanine,saintbird/mezzanine,wyzex/mezzanine,Skytorn86/mezzanine,industrydive/mezzanine,ryneeverett/mezzanine,eino-makitalo/mezzanine,theclanks/mezzanine,mush42/mezzanine,tuxinhang1989/mezzanine,orlenko/sfpirg,sjuxax/mezzanine,theclanks/mezzanine,mush42/mezzanine,orlenko/plei,orlenko/plei,frankier/mezzanine,molokov/mezzanine,dustinrb/mezzanine,Skytorn86/mezzanine,promil23/mezzanine,wrwrwr/mezzanine,dekomote/mezzanine-modeltranslation-backport,viaregio/mezzanine,stephenmcd/mezzanine,biomassives/mezzanine,ZeroXn/mezzanine,promil23/mezzanine,tuxinhang1989/mezzanine,dovydas/mezzanine,stephenmcd/mezzanine,nikolas/mezzanine,christianwgd/mezzanine,promil23/mezzanine,eino-makitalo/mezzanine,theclanks/mezzanine,orlenko/plei,sjdines/mezzanine,wbtuomela/mezzanine,jerivas/mezzanine,wbtuomela/mezzanine,wrwrwr/mezzanine,Cajoline/mezzanine,sjuxax/mezzanine,frankchin/mezzanine,SoLoHiC/mezzanine,scarcry/snm-mezzanine,AlexHill/mezzanine,Kniyl/mezzanine,gbosh/mezzanine,batpad/mezzanine,molokov/mezzanine,orlenko/sfpirg,readevalprint/mezzanine,webounty/mezzanine,molokov/mezzanine,Skytorn86/mezzanine,sjdines/mezzanine,sjuxax/mezzanine,SoLoHiC/mezzanine,douglaskastle/mezzanine,fusionbox/mezzanine,ryneeverett/mezzanine,Kniyl/mezzanine,christianwgd/mezzanine,wyzex/mezzanine,emile2016/mezzanine,scarcry/snm-mezzanine,readevalprint/mezzanine,douglaskastle/mezzanine,joshcartme/mezzanine,damnfine/mezzanine,gradel/mezzanine,Cicero-Zhao/mezzanine,cccs-web/mezzanine,damnfine/mezzanine,damnfine/mezzanine,wyzex/mezzanine,dovydas/mezzanine,webounty/mezzanine,Cajoline/mezzanine,vladir/mezzanine,frankier/mezzanine,douglaskastle/mezzanine,Kniyl/mezzanine,dustinrb/mezzanine,orlenko/sfpirg,PegasusWang/mezzanine,dovydas/mezzanine,emile2016/mezzanine,sjdines/mezzanine,SoLoHiC/mezzanine,emile2016/mezzanine,jjz/mezzanine,readevalprint/mezzanine,gbosh/mezzanine,wbtuomela/mezzanine,agepoly/mezzanine,Cicero-Zhao/mezzanine,fusionbox/mezzanine,stbarnabas/mezzanine,ZeroXn/mezzanine,webounty/mezzanine,viaregio/mezzanine,dsanders11/mezzanine,scarcry/snm-mezzanine,eino-makitalo/mezzanine,adrian-the-git/mezzanine,nikolas/mezzanine,jerivas/mezzanine,dekomote/mezzanine-modeltranslation-backport,geodesign/mezzanine,Cajoline/mezzanine,ryneeverett/mezzanine,frankier/mezzanine,joshcartme/mezzanine,vladir/mezzanine,stbarnabas/mezzanine,mush42/mezzanine,dustinrb/mezzanine,jjz/mezzanine,PegasusWang/mezzanine,frankchin/mezzanine,dekomote/mezzanine-modeltranslation-backport,gradel/mezzanine,tuxinhang1989/mezzanine,saintbird/mezzanine,viaregio/mezzanine,spookylukey/mezzanine,nikolas/mezzanine,industrydive/mezzanine,PegasusWang/mezzanine,joshcartme/mezzanine,agepoly/mezzanine,gradel/mezzanine,stephenmcd/mezzanine,geodesign/mezzanine,adrian-the-git/mezzanine,biomassives/mezzanine,industrydive/mezzanine,cccs-web/mezzanine,vladir/mezzanine,batpad/mezzanine,dsanders11/mezzanine,gbosh/mezzanine,ZeroXn/mezzanine,spookylukey/mezzanine,christianwgd/mezzanine,dsanders11/mezzanine
|
32d5f2bfcaad65230632f1854fabd2e9de1c151b
|
tests/query_test/test_chars.py
|
tests/query_test/test_chars.py
|
#!/usr/bin/env python
# Copyright (c) 2012 Cloudera, Inc. All rights reserved.
#
import logging
import pytest
from copy import copy
from tests.common.test_vector import *
from tests.common.impala_test_suite import *
class TestStringQueries(ImpalaTestSuite):
@classmethod
def get_workload(cls):
return 'functional-query'
def setup_method(self, method):
self.__cleanup_char_tables()
self.__create_char_tables()
def teardown_method(self, method):
self.__cleanup_char_tables()
def __cleanup_char_tables(self):
self.client.execute('drop table if exists functional.test_char_tmp');
self.client.execute('drop table if exists functional.test_varchar_tmp');
def __create_char_tables(self):
self.client.execute(
'create table if not exists functional.test_varchar_tmp (vc varchar(5))')
self.client.execute(
'create table if not exists functional.test_char_tmp (c char(5))')
@classmethod
def add_test_dimensions(cls):
super(TestStringQueries, cls).add_test_dimensions()
cls.TestMatrix.add_dimension(
create_exec_option_dimension(disable_codegen_options=[True]))
cls.TestMatrix.add_constraint(lambda v:\
v.get_value('table_format').file_format in ['text'])
def test_varchar(self, vector):
self.run_test_case('QueryTest/chars', vector)
|
#!/usr/bin/env python
# Copyright (c) 2012 Cloudera, Inc. All rights reserved.
#
import logging
import pytest
from copy import copy
from tests.common.test_vector import *
from tests.common.impala_test_suite import *
class TestStringQueries(ImpalaTestSuite):
@classmethod
def get_workload(cls):
return 'functional-query'
def setup_method(self, method):
self.__cleanup_char_tables()
self.__create_char_tables()
def teardown_method(self, method):
self.__cleanup_char_tables()
def __cleanup_char_tables(self):
self.client.execute('drop table if exists functional.test_char_tmp');
self.client.execute('drop table if exists functional.test_varchar_tmp');
def __create_char_tables(self):
self.client.execute(
'create table if not exists functional.test_varchar_tmp (vc varchar(5))')
self.client.execute(
'create table if not exists functional.test_char_tmp (c char(5))')
@classmethod
def add_test_dimensions(cls):
super(TestStringQueries, cls).add_test_dimensions()
cls.TestMatrix.add_dimension(
create_exec_option_dimension(disable_codegen_options=[True]))
cls.TestMatrix.add_constraint(lambda v:\
v.get_value('table_format').file_format in ['text'] and
v.get_value('table_format').compression_codec in ['none'])
def test_varchar(self, vector):
self.run_test_case('QueryTest/chars', vector)
|
Fix char test to only run on test/none.
|
Fix char test to only run on test/none.
Change-Id: I8f5ac5a6e7399ce2fdbe78d07ae24deaa1d7532d
Reviewed-on: http://gerrit.sjc.cloudera.com:8080/4326
Tested-by: jenkins
Reviewed-by: Alex Behm <fe1626037acfc2dc542d2aa723a6d14f2464a20c@cloudera.com>
|
Python
|
apache-2.0
|
ibmsoe/ImpalaPPC,ibmsoe/ImpalaPPC,ibmsoe/ImpalaPPC,ibmsoe/ImpalaPPC,ibmsoe/ImpalaPPC,ibmsoe/ImpalaPPC,ibmsoe/ImpalaPPC
|
9909ce7e900097b74b701ad52c0aae5ba68b8823
|
morenines/repository.py
|
morenines/repository.py
|
import os
from morenines import output
from morenines import util
from morenines.index import Index
from morenines.ignores import Ignores
NAMES = {
'repo_dir': '.morenines',
'index': 'index',
'ignore': 'ignore',
}
class Repository(object):
def __init__(self):
self.path = None
self.index = None
self.ignores = None
def open(self, path):
repo_dir_path = find_repo(path)
if not repo_dir_path:
output.error("Cannot find repository in '{}' or any parent dir".format(path))
util.abort()
self.path = repo_dir_path
self.index = Index.read(os.path.join(self.path, NAMES['index']))
self.ignores = Ignores.read(os.path.join(self.path, NAMES['ignore']))
def find_repo(start_path):
if start_path == '/':
return None
path = os.path.join(start_path, NAMES['repo_dir'])
if os.path.isdir(path):
return path
parent = os.path.split(start_path)[0]
return find_repo(parent)
|
import os
from morenines import output
from morenines import util
from morenines.index import Index
from morenines.ignores import Ignores
NAMES = {
'mn_dir': '.morenines',
'index': 'index',
'ignore': 'ignore',
}
class Repository(object):
def __init__(self):
self.path = None
self.index = None
self.ignore = None
def init_paths(self, repo_path):
self.path = repo_path
self.mn_dir_path = os.path.join(self.path, NAMES['mn_dir'])
self.index_path = os.path.join(self.mn_dir_path, NAMES['index'])
self.ignore_path = os.path.join(self.mn_dir_path, NAMES['ignore'])
def open(self, path):
repo_path = find_repo(path)
if not repo_path:
output.error("Cannot find repository in '{}' or any parent dir".format(path))
util.abort()
self.init_paths(repo_path)
if os.path.isfile(self.index_path):
self.index = Index.read(self.index_path)
else:
self.index = Index(self.path)
if os.path.isfile(self.ignore_path):
self.ignore = Ignores.read(self.ignore_path)
else:
self.ignore = Ignores()
def find_repo(start_path):
if start_path == '/':
return None
mn_dir_path = os.path.join(start_path, NAMES['mn_dir'])
if os.path.isdir(mn_dir_path):
return start_path
parent = os.path.split(start_path)[0]
return find_repo(parent)
|
Rework Repository to include paths
|
Rework Repository to include paths
|
Python
|
mit
|
mcgid/morenines,mcgid/morenines
|
dc071e4961c7db7e98e7dfdcd74cce368ce31039
|
dataportal/tests/test_examples.py
|
dataportal/tests/test_examples.py
|
from nose.tools import assert_true
from ..examples.sample_data import (temperature_ramp, multisource_event,
image_and_scalar)
from metadatastore.api import Document
def run_example(example):
events = example.run()
assert_true(isinstance(events, list))
assert_true(isinstance(events[0], Document))
def test_examples():
for example in [temperature_ramp, multisource_event, image_and_scalar]:
yield run_example, example
|
import subprocess
from nose.tools import assert_true, assert_equal
from ..examples.sample_data import (temperature_ramp, multisource_event,
image_and_scalar)
from metadatastore.api import Document
examples = [temperature_ramp, multisource_event, image_and_scalar]
def run_example_programmatically(example):
events = example.run()
assert_true(isinstance(events, list))
assert_true(isinstance(events[0], Document))
def run_example_from_commandline(example):
command = ['python', example.__file__]
p = subprocess.Popen(command)
return_code = p.wait()
assert_equal(return_code, 0) # successful execution
def test_examples_programmatically():
for example in examples:
yield run_example_programmatically, example
def test_examples_from_commandline():
for example in examples:
yield run_example_from_commandline, example
|
Test commandline execution of examples.
|
TST: Test commandline execution of examples.
|
Python
|
bsd-3-clause
|
tacaswell/dataportal,NSLS-II/datamuxer,tacaswell/dataportal,danielballan/datamuxer,NSLS-II/dataportal,ericdill/datamuxer,NSLS-II/dataportal,ericdill/databroker,ericdill/datamuxer,ericdill/databroker,danielballan/dataportal,danielballan/datamuxer,danielballan/dataportal
|
1915cde046c1817c45317ad8ce882e807671fca3
|
oauth_api/permissions.py
|
oauth_api/permissions.py
|
from rest_framework.permissions import BasePermission
SAFE_METHODS = ['GET', 'HEAD', 'OPTIONS']
class OAuth2ScopePermission(BasePermission):
"""
Make sure request is authenticated and token has right scope set.
"""
def has_permission(self, request, view):
token = request.auth
read_only = request.method in SAFE_METHODS
if not token:
return False
if hasattr(token, 'scope'):
scopes = self.get_scopes(request, view)
if scopes['required'] is not None:
is_valid = token.is_valid(scopes['required'])
if is_valid == False:
return False
else:
# View did not define any required scopes
is_valid = False
# Check for method specific scopes
if read_only:
if scopes['read'] is not None:
return token.is_valid(scopes['read'])
else:
if scopes['write'] is not None:
return token.is_valid(scopes['write'])
return is_valid
return False
def get_scopes(self, request, view):
return {
'required': getattr(view, 'required_scopes', None),
'read': getattr(view, 'read_scopes', None),
'write': getattr(view, 'write_scopes', None),
}
|
from django.core.exceptions import ImproperlyConfigured
from rest_framework.permissions import BasePermission
SAFE_METHODS = ['GET', 'HEAD', 'OPTIONS']
class OAuth2ScopePermission(BasePermission):
"""
Make sure request is authenticated and token has right scope set.
"""
def has_permission(self, request, view):
token = request.auth
read_only = request.method in SAFE_METHODS
if not token:
return False
if hasattr(token, 'scope'):
scopes = self.get_scopes(request, view)
if scopes['required'] is not None:
is_valid = token.is_valid(scopes['required'])
if is_valid == False:
return False
else:
# View did not define any required scopes
is_valid = False
# Check for method specific scopes
if read_only:
if scopes['read'] is not None:
return token.is_valid(scopes['read'])
else:
if scopes['write'] is not None:
return token.is_valid(scopes['write'])
return is_valid
assert False, ('OAuth2ScopePermission requires the '
'`oauth_api.authentication.OAuth2Authentication` '
'class to be used.')
def get_scopes(self, request, view):
required = getattr(view, 'required_scopes', None)
read = getattr(view, 'read_scopes', None)
write = getattr(view, 'write_scopes', None)
if not required and not read and not write:
raise ImproperlyConfigured('OAuth protected resources requires scopes. Please add required_scopes, read_scopes or write_scopes.')
return {
'required': required,
'read': read,
'write': write,
}
|
Raise ImproperlyConfigured if resource has no scopes defined
|
Raise ImproperlyConfigured if resource has no scopes defined
|
Python
|
bsd-2-clause
|
eofs/django-oauth-api,eofs/django-oauth-api
|
846a005c20ddc2e7702be48f5b2839b1c9fd1576
|
project/apps/api/management/commands/denormalize.py
|
project/apps/api/management/commands/denormalize.py
|
from django.core.management.base import (
BaseCommand,
)
from apps.api.models import (
Convention,
Contest,
Contestant,
Performance,
)
class Command(BaseCommand):
help = "Command to denormailze data."
def handle(self, *args, **options):
vs = Convention.objects.all()
for v in vs:
v.save()
ts = Contest.objects.all()
for t in ts:
t.save()
cs = Contestant.objects.all()
for c in cs:
c.save()
ps = Performance.objects.all()
for p in ps:
p.save()
for t in ts:
t.rank()
return "Done"
|
from django.core.management.base import (
BaseCommand,
)
from apps.api.models import (
Convention,
Contest,
Contestant,
Performance,
)
class Command(BaseCommand):
help = "Command to denormailze data."
def handle(self, *args, **options):
vs = Convention.objects.all()
for v in vs:
v.save()
ts = Contest.objects.all()
for t in ts:
t.save()
cs = Contestant.objects.all()
for c in cs:
c.save()
ps = Performance.objects.all()
for p in ps:
p.save()
return "Done"
|
Remove ranking from denormalization command
|
Remove ranking from denormalization command
|
Python
|
bsd-2-clause
|
barberscore/barberscore-api,dbinetti/barberscore-django,dbinetti/barberscore,barberscore/barberscore-api,barberscore/barberscore-api,barberscore/barberscore-api,dbinetti/barberscore-django,dbinetti/barberscore
|
b98ab1c800a13792bdca69c5788e91bc07f1e215
|
rpp/encoder.py
|
rpp/encoder.py
|
from uuid import UUID
from scanner import Symbol
def tostr(value):
if isinstance(value, Symbol):
return str(value)
elif isinstance(value, str):
return '"%s"' % value
elif isinstance(value, float):
return '%.14f' % value
elif isinstance(value, UUID):
return '{%s}' % str(value).upper()
elif value is None:
return '-'
else:
return str(value)
def encode(lists, indent=2, level=0):
if indent == 0:
raise ValueError('Indent should be present')
result = '<'
for i, item in enumerate(lists):
if not isinstance(item, list):
raise TypeError('%r is not RPP serializable' % item)
if i > 0:
result += ' ' * (level + 1) * indent
if all(not isinstance(x, list) for x in item):
name, values = item[0].upper(), item[1:]
strvalues = map(tostr, values)
result += ' '.join([name] + strvalues)
else:
result += encode(item, level=(level + 1))
result += '\n' if indent else ' '
result += (' ' * level * indent) + '>'
return result
|
from uuid import UUID
from scanner import Symbol
def tostr(value):
if isinstance(value, Symbol):
return str(value)
elif isinstance(value, str):
return '"%s"' % value
elif isinstance(value, float):
return '%.14f' % value
elif isinstance(value, UUID):
return '{%s}' % str(value).upper()
elif value is None:
return '-'
else:
return str(value)
def encode(lists, indent=2, level=0):
if indent == 0:
raise ValueError('Indent should be present')
result = '<'
for i, item in enumerate(lists):
if not isinstance(item, list):
raise TypeError('%r is not RPP serializable' % item)
if i > 0:
result += ' ' * (level + 1) * indent
if all(not isinstance(x, list) for x in item):
name, values = item[0].upper(), item[1:]
strvalues = map(tostr, values)
result += name
for value, strvalue in zip(values, strvalues):
if isinstance(value, Symbol):
result += '\n' + (' ' * (level + 1) * indent) + strvalue
else:
result += ' ' + strvalue
else:
result += encode(item, level=(level + 1))
result += '\n' if indent else ' '
result += (' ' * level * indent) + '>'
return result
|
Insert new line for each Symbol object
|
Insert new line for each Symbol object
|
Python
|
bsd-3-clause
|
Perlence/rpp
|
2b70879e2d73453d81ed738f34cf20d39afdc3ad
|
byceps/blueprints/authorization/decorators.py
|
byceps/blueprints/authorization/decorators.py
|
# -*- coding: utf-8 -*-
"""
byceps.blueprints.authorization.decorators
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
:Copyright: 2006-2016 Jochen Kupperschmidt
:License: Modified BSD, see LICENSE for details.
"""
from functools import wraps
from flask import abort, g
def permission_required(permission):
"""Ensure the current user has the given permission."""
def decorator(func):
@wraps(func)
def wrapper(*args, **kwargs):
if permission not in g.current_user.permissions:
abort(403)
return func(*args, **kwargs)
return wrapper
return decorator
|
# -*- coding: utf-8 -*-
"""
byceps.blueprints.authorization.decorators
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
:Copyright: 2006-2016 Jochen Kupperschmidt
:License: Modified BSD, see LICENSE for details.
"""
from functools import wraps
from flask import abort, g
def permission_required(permission):
"""Ensure the current user has the given permission."""
def decorator(func):
@wraps(func)
def wrapper(*args, **kwargs):
if not g.current_user.has_permission(permission):
abort(403)
return func(*args, **kwargs)
return wrapper
return decorator
|
Call `has_permission` method instead of accessing the collection directly
|
Call `has_permission` method instead of accessing the collection directly
|
Python
|
bsd-3-clause
|
homeworkprod/byceps,m-ober/byceps,m-ober/byceps,homeworkprod/byceps,homeworkprod/byceps,m-ober/byceps
|
c7d522393930dabc1bb6997bbc2b450d043817e8
|
wagtail/utils/widgets.py
|
wagtail/utils/widgets.py
|
from django.forms.widgets import Widget
from django.utils.safestring import mark_safe
class WidgetWithScript(Widget):
def render_html(self, name, value, attrs):
"""Render the HTML (non-JS) portion of the field markup"""
return super().render(name, value, attrs)
def render(self, name, value, attrs=None):
# no point trying to come up with sensible semantics for when 'id' is missing from attrs,
# so let's make sure it fails early in the process
try:
id_ = attrs['id']
except (KeyError, TypeError):
raise TypeError("WidgetWithScript cannot be rendered without an 'id' attribute")
widget_html = self.render_html(name, value, attrs)
js = self.render_js_init(id_, name, value)
out = '{0}<script>{1}</script>'.format(widget_html, js)
return mark_safe(out)
def render_js_init(self, id_, name, value):
return ''
|
from django.forms.widgets import Widget
from django.utils.safestring import mark_safe
class WidgetWithScript(Widget):
def render_html(self, name, value, attrs):
"""Render the HTML (non-JS) portion of the field markup"""
return super().render(name, value, attrs)
def render(self, name, value, attrs=None, renderer=None):
# no point trying to come up with sensible semantics for when 'id' is missing from attrs,
# so let's make sure it fails early in the process
try:
id_ = attrs['id']
except (KeyError, TypeError):
raise TypeError("WidgetWithScript cannot be rendered without an 'id' attribute")
widget_html = self.render_html(name, value, attrs)
js = self.render_js_init(id_, name, value)
out = '{0}<script>{1}</script>'.format(widget_html, js)
return mark_safe(out)
def render_js_init(self, id_, name, value):
return ''
|
Fix WidgetWithScript to accept renderer kwarg
|
Fix WidgetWithScript to accept renderer kwarg
|
Python
|
bsd-3-clause
|
FlipperPA/wagtail,nimasmi/wagtail,timorieber/wagtail,kaedroho/wagtail,wagtail/wagtail,takeflight/wagtail,zerolab/wagtail,kaedroho/wagtail,gasman/wagtail,timorieber/wagtail,zerolab/wagtail,wagtail/wagtail,mikedingjan/wagtail,jnns/wagtail,zerolab/wagtail,mixxorz/wagtail,nimasmi/wagtail,zerolab/wagtail,mixxorz/wagtail,wagtail/wagtail,timorieber/wagtail,mikedingjan/wagtail,gasman/wagtail,gasman/wagtail,nimasmi/wagtail,torchbox/wagtail,torchbox/wagtail,nealtodd/wagtail,mikedingjan/wagtail,thenewguy/wagtail,jnns/wagtail,gasman/wagtail,timorieber/wagtail,FlipperPA/wagtail,nimasmi/wagtail,thenewguy/wagtail,kaedroho/wagtail,jnns/wagtail,nealtodd/wagtail,gasman/wagtail,nealtodd/wagtail,thenewguy/wagtail,kaedroho/wagtail,zerolab/wagtail,kaedroho/wagtail,mixxorz/wagtail,rsalmaso/wagtail,torchbox/wagtail,rsalmaso/wagtail,takeflight/wagtail,nealtodd/wagtail,takeflight/wagtail,takeflight/wagtail,wagtail/wagtail,rsalmaso/wagtail,thenewguy/wagtail,FlipperPA/wagtail,wagtail/wagtail,torchbox/wagtail,rsalmaso/wagtail,FlipperPA/wagtail,mixxorz/wagtail,jnns/wagtail,rsalmaso/wagtail,mixxorz/wagtail,mikedingjan/wagtail,thenewguy/wagtail
|
ea3576e16b0a8278cd9d35715c8881e9d136eec8
|
paystackapi/tests/test_cpanel.py
|
paystackapi/tests/test_cpanel.py
|
import httpretty
from paystackapi.tests.base_test_case import BaseTestCase
from paystackapi.cpanel import ControlPanel
class TestPage(BaseTestCase):
@httpretty.activate
def test_fetch_payment_session_timeout(self):
"""Method defined to test fetch payment session timeout."""
httpretty.register_uri(
httpretty.GET,
self.endpoint_url("/integration/payment_session_timeout"),
content_type='text/json',
body='{"status": true, "message": "Payment session timeout retrieved"}',
status=201,
)
response = ControlPanel.fetch_payment_session_timeout()
self.assertTrue(response['status'])
|
import httpretty
from paystackapi.tests.base_test_case import BaseTestCase
from paystackapi.cpanel import ControlPanel
class TestPage(BaseTestCase):
@httpretty.activate
def test_fetch_payment_session_timeout(self):
"""Method defined to test fetch payment session timeout."""
httpretty.register_uri(
httpretty.GET,
self.endpoint_url("/integration/payment_session_timeout"),
content_type='text/json',
body='{"status": true, "message": "Payment session timeout retrieved"}',
status=201,
)
response = ControlPanel.fetch_payment_session_timeout()
self.assertTrue(response['status'])
@httpretty.activate
def test_fetch_payment_session_timeout(self):
"""Method defined to test update payment session timeout."""
httpretty.register_uri(
httpretty.PUT,
self.endpoint_url("/integration/payment_session_timeout"),
content_type='text/json',
body='{"status": true, "message": "Payment session timeout updated"}',
status=201,
)
response = ControlPanel.update_payment_session_timeout(timeout=30)
self.assertTrue(response['status'])
|
Add control panel test for update
|
Add control panel test for update
|
Python
|
mit
|
andela-sjames/paystack-python
|
3d88e62cdd2521472d0475a5f4c8598d49f88571
|
code/python/echomesh/sound/CPlayer.py
|
code/python/echomesh/sound/CPlayer.py
|
from __future__ import absolute_import, division, print_function, unicode_literals
import cechomesh
from echomesh.expression.Envelope import Envelope
from echomesh.sound import PlayerSetter
from echomesh.util import Log
from echomesh.util.thread.MasterRunnable import MasterRunnable
LOGGER = Log.logger(__name__)
def test():
print('test!')
class CPlayer(MasterRunnable):
def __init__(self, element, level=1, pan=0, loops=1, length=-1, **kwds):
super(CPlayer, self).__init__()
PlayerSetter.evaluate_player(
self, element, level=level, pan=pan, loops=loops, length=length, **kwds)
self.test2 = self.test
self.player = cechomesh.AudioSource(
self._filename, self._loops, self._begin, self._end,
self._length, "", 2, self._level, self._pan, self.pause)
def __del__(self):
super(CPlayer, self).__del__()
self.unload()
def _on_begin(self):
return self.player.begin()
def _on_run(self):
return self.player.run()
def _on_pause(self):
return self.player.pause()
def test(self):
print('test2!!')
def unload(self):
super(CPlayer, self).unload()
self.player.unload()
|
from __future__ import absolute_import, division, print_function, unicode_literals
import cechomesh
from echomesh.expression.Envelope import Envelope
from echomesh.sound import PlayerSetter
from echomesh.util import Log
from echomesh.util.thread.MasterRunnable import MasterRunnable
LOGGER = Log.logger(__name__)
class CPlayer(MasterRunnable):
def __init__(self, element, level=1, pan=0, loops=1, length=-1, **kwds):
super(CPlayer, self).__init__()
PlayerSetter.evaluate_player(
self, element, level=level, pan=pan, loops=loops, length=length, **kwds)
self.test2 = self.test
self.player = cechomesh.AudioSource(
self._filename, self._loops, self._begin, self._end,
self._length, "", 2, self._level, self._pan, self.pause)
def __del__(self):
super(CPlayer, self).__del__()
self.unload()
def _on_begin(self):
return self.player.begin()
def _on_run(self):
return self.player.run()
def _on_pause(self):
return self.player.pause()
def unload(self):
super(CPlayer, self).unload()
self.player.unload()
|
Remove tiny amounts of cruft.
|
Remove tiny amounts of cruft.
|
Python
|
mit
|
rec/echomesh,rec/echomesh,rec/echomesh,rec/echomesh,rec/echomesh,rec/echomesh
|
8e0d61aa69a15a9efc967ec263bc73c3018f9b3d
|
process_to_only_word.py
|
process_to_only_word.py
|
# -*- coding: utf-8 -*-
import re
import sys
###########################################################################
# This code is developing yet!!
# Target file(Already morphological analysis file) to process to word only.
###########################################################################
argvs = sys.argv
argc = len(argvs)
if (argc != 2):
print('Usage: # python %s filename' % argvs[0])
quit()
with open(argvs[1],mode='r', encoding='utf-8') as read_file:
line = read_file.readlines()
for l in line:
split_text_list = str(l).split()
if(len(split_text_list) == 0):
continue
print(split_text_list[0])
|
# -*- coding: utf-8 -*-
import re
import sys
###########################################################################
# This code is developing yet!!
# Target file(Already morphological analysis file) to process to word only.
# <How to use>
# python process_to_only_word.py <Target file(Already morphological analysis file)> > result.txt
###########################################################################
argvs = sys.argv
argc = len(argvs)
if (argc != 2):
print('Usage: # python %s filename' % argvs[0])
quit()
with open(argvs[1],mode='r', encoding='utf-8') as read_file:
line = read_file.readlines()
for l in line:
split_text_list = str(l).split()
if(len(split_text_list) == 0):
continue
print(split_text_list[0])
|
Add a "How to use(comment)"
|
Add a "How to use(comment)"
|
Python
|
mit
|
shinshin86/little-magnifying-py-glass,shinshin86/little-magnifying-py-glass
|
c2a8e69a5deee8f72c561f50732570801d4fc9ae
|
tests/test_stack_operations.py
|
tests/test_stack_operations.py
|
import pytest
from thinglang.execution.errors import UnknownVariable
from thinglang.runner import run
def test_stack_resolution_in_block():
assert run("""
thing Program
does start
number i = 0
Output.write("outside before, i =", i)
if true
Output.write("inside before, i =", i)
i = 10
Output.write("inside after, i =", i)
Output.write("outside after, i =", i)
""").output == """
outside before, i = 0
inside before, i = 0
inside after, i = 10
outside after, i = 10""".strip()
|
import pytest
from thinglang.execution.errors import UnknownVariable
from thinglang.runner import run
def test_stack_resolution_in_block():
assert run("""
thing Program
does start
number i = 0
Output.write("outside before, i =", i)
if true
Output.write("inside before, i =", i)
i = 10
Output.write("inside after, i =", i)
Output.write("outside after, i =", i)
""").output == """
outside before, i = 0
inside before, i = 0
inside after, i = 10
outside after, i = 10""".strip()
def test_stack_resolution_error_during_access_after_nested_deceleration():
with pytest.raises(UnknownVariable):
run("""
thing Program
does start
if true
number i = 10
Output.write("inside after, i =", i)
Output.write("outside after, i =", i)
""")
|
Add test for variables declared inside a scope (and accessed outside)
|
Add test for variables declared inside a scope (and accessed outside)
|
Python
|
mit
|
ytanay/thinglang,ytanay/thinglang,ytanay/thinglang,ytanay/thinglang
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.