commit
stringlengths 40
40
| old_file
stringlengths 4
150
| new_file
stringlengths 4
150
| old_contents
stringlengths 0
3.26k
| new_contents
stringlengths 1
4.43k
| subject
stringlengths 15
501
| message
stringlengths 15
4.06k
| lang
stringclasses 4
values | license
stringclasses 13
values | repos
stringlengths 5
91.5k
| diff
stringlengths 0
4.35k
|
|---|---|---|---|---|---|---|---|---|---|---|
e31b532b318851df8633c3464913029c463561e0
|
multivid.py
|
multivid.py
|
#!/usr/bin/env python
import bottle
import collections
import itertools
import search
import tmap
# the canonical list of search plugins used to do all the searches
SEARCHERS = [
search.AmazonSearch(),
search.HuluSearch(),
search.NetflixSearch()
]
# NOTE: we assume that all Search class implementors are thread-safe
@bottle.get("/search/autocomplete")
def autocomplete():
# build the query function we'll map onto the searchers
query = bottle.request.query["query"]
qf = lambda s: s.autocomplete(query)
# get the results in parallel
results = tmap.map(qf, SEARCHERS, num_threads=len(SEARCHERS))
# put the results into a dict under their searcher name
result_dict = {}
for searcher, result in itertools.izip(SEARCHERS, results):
result_dict[searcher.name] = result
# return the results as JSON
return result_dict
@bottle.get("/search/find")
def find():
query = bottle.request.query["query"]
qf = lambda s: s.find(query)
# return the results as one long list
results = []
for result in tmap.map(qf, SEARCHERS, num_threads=len(SEARCHERS)):
for r in result:
results.append(r.to_dict())
return {"results": results}
bottle.debug(True)
bottle.run(host="localhost", port=8000, reloader=True)
|
#!/usr/bin/env python
import bottle
import collections
import itertools
import search
import tmap
# the canonical list of search plugins used to do all the searches
SEARCHERS = [
search.AmazonSearch(),
search.HuluSearch(),
search.NetflixSearch()
]
# NOTE: we assume that all Search class implementors are thread-safe
@bottle.get("/search/autocomplete")
def autocomplete():
# build the query function we'll map onto the searchers
query = bottle.request.query["query"]
qf = lambda s: s.autocomplete(query)
# get the results in parallel
results = tmap.map(qf, SEARCHERS, num_threads=len(SEARCHERS))
# put the results into a dict under their searcher name
result_dict = {}
for searcher, result in itertools.izip(SEARCHERS, results):
result_dict[searcher.name] = result
# return the results as JSON
return result_dict
@bottle.get("/search/find")
def find():
query = bottle.request.query["query"]
qf = lambda s: s.find(query)
results = tmap.map(qf, SEARCHERS, num_threads=len(SEARCHERS))
result_dict = {}
for searcher, result in itertools.izip(SEARCHERS, results):
result_dict[searcher.name] = [r.to_dict() for r in result]
return result_dict
bottle.debug(True)
bottle.run(host="localhost", port=8000, reloader=True)
|
Change JSON response to find queries
|
Change JSON response to find queries
|
Python
|
mit
|
jasontbradshaw/multivid,jasontbradshaw/multivid
|
---
+++
@@ -23,6 +23,7 @@
query = bottle.request.query["query"]
qf = lambda s: s.autocomplete(query)
+
# get the results in parallel
results = tmap.map(qf, SEARCHERS, num_threads=len(SEARCHERS))
@@ -39,13 +40,13 @@
query = bottle.request.query["query"]
qf = lambda s: s.find(query)
- # return the results as one long list
- results = []
- for result in tmap.map(qf, SEARCHERS, num_threads=len(SEARCHERS)):
- for r in result:
- results.append(r.to_dict())
+ results = tmap.map(qf, SEARCHERS, num_threads=len(SEARCHERS))
- return {"results": results}
+ result_dict = {}
+ for searcher, result in itertools.izip(SEARCHERS, results):
+ result_dict[searcher.name] = [r.to_dict() for r in result]
+
+ return result_dict
bottle.debug(True)
bottle.run(host="localhost", port=8000, reloader=True)
|
4184d968668ebd590d927aea7ecbaf7088473cb5
|
bot/action/util/reply_markup/inline_keyboard/button.py
|
bot/action/util/reply_markup/inline_keyboard/button.py
|
class InlineKeyboardButton:
def __init__(self, data: dict):
self.data = data
@staticmethod
def switch_inline_query(text: str, query: str = "", current_chat: bool = True):
switch_inline_query_key = "switch_inline_query_current_chat" if current_chat else "switch_inline_query"
return InlineKeyboardButton({
"text": text,
switch_inline_query_key: query
})
|
class InlineKeyboardButton:
def __init__(self, data: dict):
self.data = data
@staticmethod
def create(text: str,
url: str = None,
callback_data: str = None,
switch_inline_query: str = None,
switch_inline_query_current_chat: str = None):
data = {
"text": text
}
if url is not None:
data["url"] = url
if callback_data is not None:
data["callback_data"] = callback_data
if switch_inline_query is not None:
data["switch_inline_query"] = switch_inline_query
if switch_inline_query_current_chat is not None:
data["switch_inline_query_current_chat"] = switch_inline_query_current_chat
return InlineKeyboardButton(data)
@staticmethod
def switch_inline_query(text: str, query: str = "", current_chat: bool = True):
switch_inline_query_key = "switch_inline_query_current_chat" if current_chat else "switch_inline_query"
return InlineKeyboardButton({
"text": text,
switch_inline_query_key: query
})
|
Add create static method to InlineKeyboardButton with all possible parameters
|
Add create static method to InlineKeyboardButton with all possible parameters
|
Python
|
agpl-3.0
|
alvarogzp/telegram-bot,alvarogzp/telegram-bot
|
---
+++
@@ -1,6 +1,25 @@
class InlineKeyboardButton:
def __init__(self, data: dict):
self.data = data
+
+ @staticmethod
+ def create(text: str,
+ url: str = None,
+ callback_data: str = None,
+ switch_inline_query: str = None,
+ switch_inline_query_current_chat: str = None):
+ data = {
+ "text": text
+ }
+ if url is not None:
+ data["url"] = url
+ if callback_data is not None:
+ data["callback_data"] = callback_data
+ if switch_inline_query is not None:
+ data["switch_inline_query"] = switch_inline_query
+ if switch_inline_query_current_chat is not None:
+ data["switch_inline_query_current_chat"] = switch_inline_query_current_chat
+ return InlineKeyboardButton(data)
@staticmethod
def switch_inline_query(text: str, query: str = "", current_chat: bool = True):
|
60323c2944e81b8c0ff7b7e24de7aff28db238de
|
server/config.py
|
server/config.py
|
# Statement for enabling the development environment
DEBUG = True
TESTING = True
# Define the application directory
import os
BASE_DIR = os.path.abspath(os.path.dirname(__file__))
# Define the database - we are working with
# SQLite for this example
SQLALCHEMY_DATABASE_URI = 'mysql+pymysql://root:root@localhost/ontheside'
DATABASE_CONNECT_OPTIONS = {}
# Application threads. A common general assumption is
# using 2 per available processor cores - to handle
# incoming requests using one and performing background
# operations using the other.
THREADS_PER_PAGE = 2
# Enable protection agains *Cross-site Request Forgery (CSRF)*
CSRF_ENABLED = True
# Use a secure, unique and absolutely secret key for
# signing the data.
CSRF_SESSION_KEY = "secret"
# Secret key for signing cookies
SECRET_KEY = "secret"
FIXTURES_DIRS = [
'/home/ganemone/Documents/dev/ontheside/server/tests/fixtures/'
]
|
# Statement for enabling the development environment
DEBUG = True
TESTING = True
# Define the application directory
import os
BASE_DIR = os.path.abspath(os.path.dirname(__file__))
# Define the database - we are working with
# SQLite for this example
SQLALCHEMY_DATABASE_URI = 'mysql+pymysql://root:root@localhost/ontheside'
DATABASE_CONNECT_OPTIONS = {}
# Application threads. A common general assumption is
# using 2 per available processor cores - to handle
# incoming requests using one and performing background
# operations using the other.
THREADS_PER_PAGE = 2
# Enable protection agains *Cross-site Request Forgery (CSRF)*
CSRF_ENABLED = True
# Use a secure, unique and absolutely secret key for
# signing the data.
CSRF_SESSION_KEY = "secret"
# Secret key for signing cookies
SECRET_KEY = "secret"
FIXTURES_DIRS = [
'/home/ganemone/Documents/dev/ontheside/server/tests/fixtures/',
'/Users/giancarloanemone/Documents/dev/web/ontheside/server/tests/fixtures/'
]
|
Add path for laptop for fixtures
|
Add path for laptop for fixtures
|
Python
|
mit
|
ganemone/ontheside,ganemone/ontheside,ganemone/ontheside
|
---
+++
@@ -30,5 +30,6 @@
SECRET_KEY = "secret"
FIXTURES_DIRS = [
- '/home/ganemone/Documents/dev/ontheside/server/tests/fixtures/'
+ '/home/ganemone/Documents/dev/ontheside/server/tests/fixtures/',
+ '/Users/giancarloanemone/Documents/dev/web/ontheside/server/tests/fixtures/'
]
|
9c281ff44d6a28962897f4ca8013a539d7f08040
|
src/libcask/network.py
|
src/libcask/network.py
|
import subprocess
class SetupNetworkMixin(object):
def _setup_hostname(self):
with self.get_attachment(['uts']).attach():
subprocess.check_call(['hostname', self.hostname])
def _setup_virtual_ethernet(self):
veth_name = 'veth-{hostname}'.format(hostname=self.hostname)
veth_host_name = 'hveth-{hostname}'.format(hostname=self.hostname)
# Create virtual ethernet pair
subprocess.check_call([
'ip', 'link', 'add',
'name', veth_host_name, 'type', 'veth',
'peer', 'name', veth_name, 'netns', str(self.pid())
])
# Add the container's host IP address and bring the interface up
subprocess.check_call(['ip', 'addr', 'add', self.ipaddr_host, 'dev', veth_host_name])
subprocess.check_call(['ip', 'link', 'set', veth_host_name, 'up'])
# Add the host interface to the bridge
# Assuming here that `cask0` bridge interface exists. It should
# be created and initialized by the Makefile.
subprocess.check_call(['ip', 'link', 'set', veth_host_name, 'master', 'cask0'])
# Set up virtual ethernet interface inside the container
with self.get_attachment(['net', 'uts']).attach():
subprocess.check_call([
'ifconfig', veth_name, self.ipaddr, 'up',
])
def setup_network(self):
self._setup_hostname()
self._setup_virtual_ethernet()
|
import subprocess
class SetupNetworkMixin(object):
def _setup_hostname(self):
with self.get_attachment(['uts']).attach():
subprocess.check_call(['hostname', self.hostname])
def _setup_virtual_ethernet(self):
veth_name = 'veth-{name}'.format(name=self.name)
veth_host_name = 'hveth-{name}'.format(name=self.name)
# Create virtual ethernet pair
subprocess.check_call([
'ip', 'link', 'add',
'name', veth_host_name, 'type', 'veth',
'peer', 'name', veth_name, 'netns', str(self.pid())
])
# Add the container's host IP address and bring the interface up
subprocess.check_call(['ip', 'addr', 'add', self.ipaddr_host, 'dev', veth_host_name])
subprocess.check_call(['ip', 'link', 'set', veth_host_name, 'up'])
# Add the host interface to the bridge
# Assuming here that `cask0` bridge interface exists. It should
# be created and initialized by the Makefile.
subprocess.check_call(['ip', 'link', 'set', veth_host_name, 'master', 'cask0'])
# Set up virtual ethernet interface inside the container
with self.get_attachment(['net', 'uts']).attach():
subprocess.check_call([
'ifconfig', veth_name, self.ipaddr, 'up',
])
def setup_network(self):
self._setup_hostname()
self._setup_virtual_ethernet()
|
Use container names, rather than hostnames, for virtual ethernet interface names
|
Use container names, rather than hostnames, for virtual ethernet interface names
Container names are guaranteed to be unique, but hostnames are not
|
Python
|
mit
|
ianpreston/cask,ianpreston/cask
|
---
+++
@@ -7,8 +7,8 @@
subprocess.check_call(['hostname', self.hostname])
def _setup_virtual_ethernet(self):
- veth_name = 'veth-{hostname}'.format(hostname=self.hostname)
- veth_host_name = 'hveth-{hostname}'.format(hostname=self.hostname)
+ veth_name = 'veth-{name}'.format(name=self.name)
+ veth_host_name = 'hveth-{name}'.format(name=self.name)
# Create virtual ethernet pair
subprocess.check_call([
|
edd21fc76068894de1001a163885291c3b2cfadb
|
tests/factories.py
|
tests/factories.py
|
from django.conf import settings
from django.contrib.auth.models import User
import factory
from website.models import Db, Query
class TagsFactory(factory.DjangoModelFactory):
class Meta:
abstract = True
@factory.post_generation
def tags(self, create, extracted):
if create and extracted:
self.tags.add(*extracted)
class UserFactory(factory.DjangoModelFactory):
class Meta:
model = User
username = factory.Sequence(lambda x: "user{}".format(x))
email = factory.Sequence(lambda x: "user{}@example.com".format(x))
password = factory.PostGenerationMethodCall('set_password', "password")
class DbFactory(TagsFactory):
class Meta:
model = Db
exclude = ('DB',)
DB = settings.DATABASES['default']
name_short = "default"
name_long = "default"
type = "MySQL"
host = factory.LazyAttribute(lambda a: a.DB['HOST'])
db = factory.LazyAttribute(lambda a: a.DB['NAME'])
port = factory.LazyAttribute(lambda a: a.DB['PORT'] or "3306")
username = factory.LazyAttribute(lambda a: a.DB['USER'])
password_encrypted = factory.LazyAttribute(lambda a: a.DB['PASSWORD'])
class QueryFactory(TagsFactory):
class Meta:
model = Query
title = "title"
description = "description"
db = factory.SubFactory(DbFactory)
owner = factory.SubFactory(UserFactory)
graph_extra = "{}"
query_text = "select id, username from auth_user"
|
from django.conf import settings
from django.contrib.auth.models import User
import factory
from website.models import Db, Query
class TagsFactory(factory.DjangoModelFactory):
class Meta:
abstract = True
@factory.post_generation
def tags(self, create, extracted):
if create and extracted:
self.tags.add(*extracted)
class UserFactory(factory.DjangoModelFactory):
class Meta:
model = User
username = factory.Sequence(lambda x: "user{}".format(x))
email = factory.Sequence(lambda x: "user{}@example.com".format(x))
password = factory.PostGenerationMethodCall('set_password', "password")
class DbFactory(TagsFactory):
class Meta:
model = Db
exclude = ('DB',)
DB = settings.DATABASES['default']
name_short = "default"
name_long = "default"
type = "MySQL"
host = factory.LazyAttribute(lambda a: a.DB['HOST'])
db = factory.LazyAttribute(lambda a: a.DB['NAME'])
port = factory.LazyAttribute(lambda a: a.DB['PORT'] or "3306")
username = factory.LazyAttribute(lambda a: a.DB['USER'])
password_encrypted = factory.LazyAttribute(lambda a: a.DB['PASSWORD'])
class QueryFactory(TagsFactory):
class Meta:
model = Query
title = "title"
description = "description"
db = factory.SubFactory(DbFactory)
owner = factory.SubFactory(UserFactory)
graph_extra = "{}"
query_text = "select app, name from django_migrations"
|
Make default QueryFactory return data (fixes test)
|
Make default QueryFactory return data (fixes test)
|
Python
|
mit
|
sqlviz/sqlviz,sqlviz/sqlviz,sqlviz/sqlviz,sqlviz/sqlviz,sqlviz/sqlviz,sqlviz/sqlviz,sqlviz/sqlviz,sqlviz/sqlviz,sqlviz/sqlviz,sqlviz/sqlviz,sqlviz/sqlviz,sqlviz/sqlviz,sqlviz/sqlviz,sqlviz/sqlviz,sqlviz/sqlviz,sqlviz/sqlviz,sqlviz/sqlviz
|
---
+++
@@ -49,4 +49,4 @@
db = factory.SubFactory(DbFactory)
owner = factory.SubFactory(UserFactory)
graph_extra = "{}"
- query_text = "select id, username from auth_user"
+ query_text = "select app, name from django_migrations"
|
d698d4ce3002db3b518e061075f294cf9b0089a6
|
aspc/senate/urls.py
|
aspc/senate/urls.py
|
from django.conf.urls import patterns, include, url
from aspc.senate.views import DocumentList, AppointmentList
urlpatterns = patterns('',
url(r'^documents/$', DocumentList.as_view(), name="document_list"),
url(r'^documents/(?P<page>[0-9]+)/$', DocumentList.as_view(), name="document_list_page"),
url(r'^preview/positions/$', AppointmentList.as_view(), name="positions"),
)
|
from django.conf.urls import patterns, include, url
from aspc.senate.views import DocumentList, AppointmentList
urlpatterns = patterns('',
url(r'^documents/$', DocumentList.as_view(), name="document_list"),
url(r'^documents/(?P<page>[0-9]+)/$', DocumentList.as_view(), name="document_list_page"),
url(r'^positions/$', AppointmentList.as_view(), name="positions"),
)
|
Remove the preview prefix from the positions URL pattern
|
Remove the preview prefix from the positions URL pattern
|
Python
|
mit
|
theworldbright/mainsite,aspc/mainsite,aspc/mainsite,aspc/mainsite,theworldbright/mainsite,aspc/mainsite,theworldbright/mainsite,theworldbright/mainsite
|
---
+++
@@ -4,5 +4,5 @@
urlpatterns = patterns('',
url(r'^documents/$', DocumentList.as_view(), name="document_list"),
url(r'^documents/(?P<page>[0-9]+)/$', DocumentList.as_view(), name="document_list_page"),
- url(r'^preview/positions/$', AppointmentList.as_view(), name="positions"),
+ url(r'^positions/$', AppointmentList.as_view(), name="positions"),
)
|
3fc45407eaba1452092a364eeb676bdaab6d5edc
|
polling_stations/apps/councils/migrations/0005_geom_not_geog.py
|
polling_stations/apps/councils/migrations/0005_geom_not_geog.py
|
# Generated by Django 2.2.10 on 2020-02-14 14:41
import django.contrib.gis.db.models.fields
from django.db import migrations
class Migration(migrations.Migration):
dependencies = [
("councils", "0004_auto_20200203_1040"),
]
operations = [
migrations.AlterField(
model_name="council",
name="area",
field=django.contrib.gis.db.models.fields.MultiPolygonField(
blank=True, null=True, srid=4326
),
),
]
|
# Generated by Django 2.2.10 on 2020-02-14 14:41
# Amended by Will on 2021-04-11
from django.db import migrations
class Migration(migrations.Migration):
dependencies = [
("councils", "0004_auto_20200203_1040"),
]
operations = [
migrations.RunSQL(
'ALTER TABLE "councils_council" ALTER COLUMN "area" TYPE geometry(MULTIPOLYGON,4326) USING area::geometry(MultiPolygon,4326);'
)
]
|
Fix council migration using explicit type cast
|
Fix council migration using explicit type cast
The generated SQL for this doesn't include the 'USING' section. It seems
like this is now needed.
|
Python
|
bsd-3-clause
|
DemocracyClub/UK-Polling-Stations,DemocracyClub/UK-Polling-Stations,DemocracyClub/UK-Polling-Stations
|
---
+++
@@ -1,6 +1,6 @@
# Generated by Django 2.2.10 on 2020-02-14 14:41
+# Amended by Will on 2021-04-11
-import django.contrib.gis.db.models.fields
from django.db import migrations
@@ -11,11 +11,7 @@
]
operations = [
- migrations.AlterField(
- model_name="council",
- name="area",
- field=django.contrib.gis.db.models.fields.MultiPolygonField(
- blank=True, null=True, srid=4326
- ),
- ),
+ migrations.RunSQL(
+ 'ALTER TABLE "councils_council" ALTER COLUMN "area" TYPE geometry(MULTIPOLYGON,4326) USING area::geometry(MultiPolygon,4326);'
+ )
]
|
653832ebc7b18599b9aab2f230b190b14e71cd3d
|
models.py
|
models.py
|
from google.appengine.ext import db
class User(db.Model):
name = db.UserProperty(auto_current_user = True, auto_current_user_add = True)
date = db.DateTimeProperty(auto_now = True, auto_now_add = True)
#token = db.StringProperty()
services = db.StringListProperty()
|
class User(db.Model):
name = db.UserProperty(auto_current_user = True, auto_current_user_add = True)
date = db.DateTimeProperty(auto_now = True, auto_now_add = True)
#token = db.StringProperty()
services = db.StringListProperty()
|
Clean import modules hey hey.
|
Clean import modules hey hey.
|
Python
|
mpl-2.0
|
BYK/fb2goog,BYK/fb2goog,BYK/fb2goog
|
---
+++
@@ -1,5 +1,3 @@
-from google.appengine.ext import db
-
class User(db.Model):
name = db.UserProperty(auto_current_user = True, auto_current_user_add = True)
date = db.DateTimeProperty(auto_now = True, auto_now_add = True)
|
97b6894671c0906393aea5aa43e632a35bd2aa27
|
penchy/tests/test_util.py
|
penchy/tests/test_util.py
|
import os
import unittest2
from penchy import util
class ClasspathTest(unittest2.TestCase):
def test_valid_options(self):
expected = 'foo:bar:baz'
options = ['-cp', expected]
self.assertEquals(util.extract_classpath(options), expected)
expected = 'foo:bar:baz'
options = ['-classpath', expected]
self.assertEquals(util.extract_classpath(options), expected)
def test_multiple_classpaths(self):
expected = 'foo:bar:baz'
options = ['-cp', 'com:org:de', '-cp', expected]
self.assertEquals(util.extract_classpath(options), expected)
def test_only_option(self):
options = ['-cp']
self.assertEquals(util.extract_classpath(options), '')
class TempdirTest(unittest2.TestCase):
def test_change(self):
cwd = os.getcwd()
with util.tempdir():
self.assertNotEquals(cwd, os.getcwd())
|
import os
import unittest2
from penchy import util
class ClasspathTest(unittest2.TestCase):
def test_valid_options(self):
expected = 'foo:bar:baz'
options = ['-cp', expected]
self.assertEquals(util.extract_classpath(options), expected)
expected = 'foo:bar:baz'
options = ['-classpath', expected]
self.assertEquals(util.extract_classpath(options), expected)
def test_multiple_classpaths(self):
expected = 'foo:bar:baz'
options = ['-cp', 'com:org:de', '-cp', expected]
self.assertEquals(util.extract_classpath(options), expected)
def test_only_option(self):
options = ['-cp']
self.assertEquals(util.extract_classpath(options), '')
class TempdirTest(unittest2.TestCase):
def test_change(self):
cwd = os.getcwd()
with util.tempdir():
self.assertNotEquals(cwd, os.getcwd())
self.assertEquals(cwd, os.getcwd())
|
Check if tempdir returns to former cwd.
|
tests: Check if tempdir returns to former cwd.
Signed-off-by: Michael Markert <5eb998b7ac86da375651a4cd767b88c9dad25896@googlemail.com>
|
Python
|
mit
|
fhirschmann/penchy,fhirschmann/penchy
|
---
+++
@@ -28,3 +28,4 @@
cwd = os.getcwd()
with util.tempdir():
self.assertNotEquals(cwd, os.getcwd())
+ self.assertEquals(cwd, os.getcwd())
|
ecd8d1ce0135e1c0a3901e73619d4f4d5bf1e6c7
|
astral/api/urls.py
|
astral/api/urls.py
|
from handlers.nodes import NodesHandler
from handlers.node import NodeHandler
from handlers.streams import StreamsHandler
from handlers.stream import StreamHandler
from handlers.ping import PingHandler
from handlers.events import EventHandler
from handlers.ticket import TicketHandler
from handlers.tickets import TicketsHandler
url_patterns = [
(r"/nodes", NodesHandler),
(r"/(node)/(\d+)", NodeHandler),
(r"/node", NodeHandler),
(r"/streams", StreamsHandler),
(r"/tickets", TicketsHandler),
(r"/stream/(\d+)", StreamHandler),
(r"/stream/(\d+)/tickets", TicketsHandler),
(r"/stream/(\d+)/ticket/(\d+)", TicketHandler),
(r"/stream/(\d+)/ticket", TicketHandler),
(r"/ping", PingHandler),
(r"/events", EventHandler),
]
|
from handlers.nodes import NodesHandler
from handlers.node import NodeHandler
from handlers.streams import StreamsHandler
from handlers.stream import StreamHandler
from handlers.ping import PingHandler
from handlers.events import EventHandler
from handlers.ticket import TicketHandler
from handlers.tickets import TicketsHandler
url_patterns = [
(r"/nodes", NodesHandler),
(r"/node/(\d+)", NodeHandler),
(r"/node", NodeHandler),
(r"/streams", StreamsHandler),
(r"/tickets", TicketsHandler),
(r"/stream/(\d+)", StreamHandler),
(r"/stream/(\d+)/tickets", TicketsHandler),
(r"/stream/(\d+)/ticket/(\d+)", TicketHandler),
(r"/stream/(\d+)/ticket", TicketHandler),
(r"/ping", PingHandler),
(r"/events", EventHandler),
]
|
Remove extra regexp group from URL pattern.
|
Remove extra regexp group from URL pattern.
|
Python
|
mit
|
peplin/astral
|
---
+++
@@ -10,7 +10,7 @@
url_patterns = [
(r"/nodes", NodesHandler),
- (r"/(node)/(\d+)", NodeHandler),
+ (r"/node/(\d+)", NodeHandler),
(r"/node", NodeHandler),
(r"/streams", StreamsHandler),
(r"/tickets", TicketsHandler),
|
754f5c968ad1dff3ae7f602d23baac1299731062
|
update_filelist.py
|
update_filelist.py
|
#!/usr/bin/python3
import os
import re
import subprocess
dir_path = os.path.dirname(os.path.realpath(__file__))
filename = 'chatterino.pro'
data = ""
with open(filename, 'r') as project:
data = project.read()
sources = subprocess.getoutput("find ./src -type f -regex '.*\.cpp' | sed 's_\./_ _g'")
sources = re.sub(r'$', r' \\\\', sources, flags=re.MULTILINE)
sources += "\n"
data = re.sub(r'^SOURCES(.|\r|\n)*?^$', 'SOURCES += \\\n' + sources, data, flags=re.MULTILINE)
headers = subprocess.getoutput("find ./src -type f -regex '.*\.hpp' | sed 's_\./_ _g'")
headers = re.sub(r'$', r' \\\\', headers, flags=re.MULTILINE)
headers += "\n"
data = re.sub(r'^HEADERS(.|\r|\n)*?^$', 'HEADERS += \\\n' + headers, data, flags=re.MULTILINE)
with open(filename, 'w') as project:
project.write(data)
|
#!/usr/bin/python3
import os
import re
import subprocess
dir_path = os.path.dirname(os.path.realpath(__file__))
filename = 'chatterino.pro'
data = ""
with open(filename, 'r') as project:
data = project.read()
sources_list = subprocess.getoutput("find ./src -type f -regex '.*\.cpp' | sed 's_\./_ _g'").splitlines()
sources_list.sort(key=str.lower)
sources = "\n".join(sources_list)
sources = re.sub(r'$', r' \\\\', sources, flags=re.MULTILINE)
sources += "\n"
data = re.sub(r'^SOURCES(.|\r|\n)*?^$', 'SOURCES += \\\n' + sources, data, flags=re.MULTILINE)
headers_list = subprocess.getoutput("find ./src -type f -regex '.*\.hpp' | sed 's_\./_ _g'").splitlines()
headers_list.sort(key=str.lower)
headers = "\n".join(headers_list)
headers = re.sub(r'$', r' \\\\', headers, flags=re.MULTILINE)
headers += "\n"
data = re.sub(r'^HEADERS(.|\r|\n)*?^$', 'HEADERS += \\\n' + headers, data, flags=re.MULTILINE)
with open(filename, 'w') as project:
project.write(data)
|
Sort file list before writing to project file
|
Sort file list before writing to project file
Now using the built-in Python `list.sort` method to sort files.
This should ensure consistent behavior on all systems and prevent
unnecessary merge conflicts.
|
Python
|
mit
|
Cranken/chatterino2,hemirt/chatterino2,fourtf/chatterino2,Cranken/chatterino2,hemirt/chatterino2,Cranken/chatterino2,fourtf/chatterino2,Cranken/chatterino2,fourtf/chatterino2,hemirt/chatterino2,hemirt/chatterino2
|
---
+++
@@ -10,12 +10,16 @@
with open(filename, 'r') as project:
data = project.read()
- sources = subprocess.getoutput("find ./src -type f -regex '.*\.cpp' | sed 's_\./_ _g'")
+ sources_list = subprocess.getoutput("find ./src -type f -regex '.*\.cpp' | sed 's_\./_ _g'").splitlines()
+ sources_list.sort(key=str.lower)
+ sources = "\n".join(sources_list)
sources = re.sub(r'$', r' \\\\', sources, flags=re.MULTILINE)
sources += "\n"
data = re.sub(r'^SOURCES(.|\r|\n)*?^$', 'SOURCES += \\\n' + sources, data, flags=re.MULTILINE)
- headers = subprocess.getoutput("find ./src -type f -regex '.*\.hpp' | sed 's_\./_ _g'")
+ headers_list = subprocess.getoutput("find ./src -type f -regex '.*\.hpp' | sed 's_\./_ _g'").splitlines()
+ headers_list.sort(key=str.lower)
+ headers = "\n".join(headers_list)
headers = re.sub(r'$', r' \\\\', headers, flags=re.MULTILINE)
headers += "\n"
data = re.sub(r'^HEADERS(.|\r|\n)*?^$', 'HEADERS += \\\n' + headers, data, flags=re.MULTILINE)
|
65f7a8912a0a7b1f408c4ab429065aad8dba12fc
|
yourls/__init__.py
|
yourls/__init__.py
|
# coding: utf-8
from __future__ import absolute_import, division, print_function
from .api import DBStats, ShortenedURL
from .core import YOURLSAPIMixin, YOURLSClient, YOURLSClientBase
from .exc import (
YOURLSAPIError, YOURLSHTTPError, YOURLSKeywordExistsError,
YOURLSNoLoopError, YOURLSNoURLError, YOURLSURLExistsError)
from .log import logger
__author__ = 'Frazer McLean <frazer@frazermclean.co.uk>'
__version__ = '1.0.0'
__license__ = 'MIT'
__description__ = 'Python client for YOURLS.'
__all__ = (
'DBStats',
'logger',
'ShortenedURL',
'YOURLSAPIError',
'YOURLSAPIMixin',
'YOURLSClient',
'YOURLSClientBase',
'YOURLSHTTPError',
'YOURLSKeywordExistsError',
'YOURLSNoLoopError',
'YOURLSNoURLError',
'YOURLSURLExistsError',
)
|
# coding: utf-8
from __future__ import absolute_import, division, print_function
from .api import DBStats, ShortenedURL
from .core import YOURLSAPIMixin, YOURLSClient, YOURLSClientBase
from .exc import (
YOURLSAPIError, YOURLSHTTPError, YOURLSKeywordExistsError,
YOURLSNoLoopError, YOURLSNoURLError, YOURLSURLExistsError)
from .log import logger
__author__ = 'Frazer McLean <frazer@frazermclean.co.uk>'
__version__ = '1.0.1'
__license__ = 'MIT'
__description__ = 'Python client for YOURLS.'
__all__ = (
'DBStats',
'logger',
'ShortenedURL',
'YOURLSAPIError',
'YOURLSAPIMixin',
'YOURLSClient',
'YOURLSClientBase',
'YOURLSHTTPError',
'YOURLSKeywordExistsError',
'YOURLSNoLoopError',
'YOURLSNoURLError',
'YOURLSURLExistsError',
)
|
Bump version numer to 1.0.1
|
Bump version numer to 1.0.1
|
Python
|
mit
|
RazerM/yourls-python,RazerM/yourls-python
|
---
+++
@@ -9,7 +9,7 @@
from .log import logger
__author__ = 'Frazer McLean <frazer@frazermclean.co.uk>'
-__version__ = '1.0.0'
+__version__ = '1.0.1'
__license__ = 'MIT'
__description__ = 'Python client for YOURLS.'
|
28cb04ae75a42e6b3ce10972e12166a6cbd84267
|
astroquery/sha/tests/test_sha.py
|
astroquery/sha/tests/test_sha.py
|
# Licensed under a 3-clause BSD style license - see LICENSE.rst
from ... import sha
def test_query():
# Example queries for SHA API help page
sha.query(ra=163.6136, dec=-11.784, size=0.5)
sha.query(naifid=2003226)
sha.query(pid=30080)
sha.query(reqkey=21641216)
|
# Licensed under a 3-clause BSD style license - see LICENSE.rst
from ... import sha
def test_query():
# Example queries for SHA API help page
pos_t = sha.query(ra=163.6136, dec=-11.784, size=0.5)
nid_t = sha.query(naifid=2003226)
pid_t = sha.query(pid=30080)
rqk_t = sha.query(reqkey=21641216)
# Get table and fits URLs
table_url = pid_t['accessUrl'][10]
image_url = pid_t['accessUrl'][16]
# Not implemented because running will download file
#sha.get_img(table_url)
#sha.get_img(image_url)
|
Update test for get file
|
Update test for get file
Commented out the actual get_img calls because they would create a
directoy and download files if run, potentially in parts of the file
system where the user/process does not have the right permissions.
|
Python
|
bsd-3-clause
|
imbasimba/astroquery,ceb8/astroquery,imbasimba/astroquery,ceb8/astroquery
|
---
+++
@@ -3,9 +3,15 @@
def test_query():
# Example queries for SHA API help page
- sha.query(ra=163.6136, dec=-11.784, size=0.5)
- sha.query(naifid=2003226)
- sha.query(pid=30080)
- sha.query(reqkey=21641216)
+ pos_t = sha.query(ra=163.6136, dec=-11.784, size=0.5)
+ nid_t = sha.query(naifid=2003226)
+ pid_t = sha.query(pid=30080)
+ rqk_t = sha.query(reqkey=21641216)
+ # Get table and fits URLs
+ table_url = pid_t['accessUrl'][10]
+ image_url = pid_t['accessUrl'][16]
+ # Not implemented because running will download file
+ #sha.get_img(table_url)
+ #sha.get_img(image_url)
|
b41ce2be52bc3aebf5ad9a737700da0753602670
|
parser.py
|
parser.py
|
import requests
API_URL = 'https://api.github.com/users/{}/repos'
def main(user):
return parse(request(user))
def request(user):
return requests.get(url=API_URL.format(user))
def parse(response):
repos = response.json()
data = []
if repos is None:
return None
for repo in repos:
if 'name' in repo and not repo['fork']:
data.append({
'name': repo['name'],
'desc': repo['description'],
'lang': repo['language'],
'stars': repo['stargazers_count']
})
return data
if __name__ == '__main__':
import pprint
u = 'kshvmdn'
pprint.pprint(main(u))
|
import requests
import collections
API_URL = 'https://api.github.com/users/{}/repos'
def main(user):
return parse(request(user))
def request(user):
return requests.get(url=API_URL.format(user))
def parse(response):
repos = response.json()
data = []
if repos is None:
return None
for repo in repos:
if 'name' in repo and not repo['fork']:
data.append(collections.OrderedDict([('name', repo['name']),
('desc', repo['description']),
('lang', repo['language']),
('stars', repo['stargazers_count'])]))
return data
if __name__ == '__main__':
import pprint
u = 'kshvmdn'
pprint.pprint(main(u))
|
Use OrderedDict for repo data
|
Use OrderedDict for repo data
|
Python
|
mit
|
kshvmdn/github-list,kshvmdn/github-list,kshvmdn/github-list
|
---
+++
@@ -1,4 +1,5 @@
import requests
+import collections
API_URL = 'https://api.github.com/users/{}/repos'
@@ -18,15 +19,15 @@
return None
for repo in repos:
if 'name' in repo and not repo['fork']:
- data.append({
- 'name': repo['name'],
- 'desc': repo['description'],
- 'lang': repo['language'],
- 'stars': repo['stargazers_count']
- })
+ data.append(collections.OrderedDict([('name', repo['name']),
+ ('desc', repo['description']),
+ ('lang', repo['language']),
+ ('stars', repo['stargazers_count'])]))
return data
+
if __name__ == '__main__':
import pprint
+
u = 'kshvmdn'
pprint.pprint(main(u))
|
471be725896b69439369143b6138f614a062aca5
|
dsub/_dsub_version.py
|
dsub/_dsub_version.py
|
# Copyright 2017 Google Inc. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
"""Single source of truth for dsub's version.
This must remain small and dependency-free so that any dsub module may
import it without creating circular dependencies. Note that this module
is parsed as a text file by setup.py and changes to the format of this
file could break setup.py.
The version should follow formatting requirements specified in PEP-440.
- https://www.python.org/dev/peps/pep-0440
A typical release sequence will be versioned as:
0.1.3.dev0 -> 0.1.3 -> 0.1.4.dev0 -> ...
"""
DSUB_VERSION = '0.4.0'
|
# Copyright 2017 Google Inc. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
"""Single source of truth for dsub's version.
This must remain small and dependency-free so that any dsub module may
import it without creating circular dependencies. Note that this module
is parsed as a text file by setup.py and changes to the format of this
file could break setup.py.
The version should follow formatting requirements specified in PEP-440.
- https://www.python.org/dev/peps/pep-0440
A typical release sequence will be versioned as:
0.1.3.dev0 -> 0.1.3 -> 0.1.4.dev0 -> ...
"""
DSUB_VERSION = '0.4.1.dev0'
|
Update dsub version to 0.4.1.dev0
|
Update dsub version to 0.4.1.dev0
PiperOrigin-RevId: 328627320
|
Python
|
apache-2.0
|
DataBiosphere/dsub,DataBiosphere/dsub
|
---
+++
@@ -26,4 +26,4 @@
0.1.3.dev0 -> 0.1.3 -> 0.1.4.dev0 -> ...
"""
-DSUB_VERSION = '0.4.0'
+DSUB_VERSION = '0.4.1.dev0'
|
52a90e320355de503624edf714ff7999aafba062
|
blitz/io/signals.py
|
blitz/io/signals.py
|
__author__ = 'Will Hart'
from blinker import signal
# fired when a new web client device connects
web_client_connected = signal('client_connected')
# fired when a web client disconnects
web_client_disconnected = signal('client_disconnected')
# fired when a new TCP client device connects
tcp_client_connected = signal('tcp_client_connected')
# fired when a TCP client disconnects
tcp_client_disconnected = signal('tcp_client_disconnected')
# fired when a server TCP connection is established
logger_connected = signal('logger_connected')
# fired when a server TCP connection is closed
logger_disconnected = signal('logger_disconnected')
# fired when the client receives a data row for processing
data_line_received = signal('data_line_received')
# fired when a variable is ready for entry into the database
data_variable_decoded = signal('data_variable_decoded')
# fired when a board has finished processing a data line
data_line_processed = signal('data_line_processed')
# called when an expansion board is registered
expansion_board_registered = signal('expansion_board_registered')
|
__author__ = 'Will Hart'
from blinker import signal
# fired when a new web client device connects
web_client_connected = signal('client_connected')
# fired when a web client disconnects
web_client_disconnected = signal('client_disconnected')
# fired when a new TCP client device connects
tcp_client_connected = signal('tcp_client_connected')
# fired when a TCP client disconnects
tcp_client_disconnected = signal('tcp_client_disconnected')
# fired when a server TCP connection is established
logger_connected = signal('logger_connected')
# fired when a server TCP connection is closed
logger_disconnected = signal('logger_disconnected')
# fired when the expansion board receives a data row for processing
# allows pre-processing of data
data_line_received = signal('data_line_received')
# fired when a variable is ready for entry into the database
# allows post processing of data
data_variable_decoded = signal('data_variable_decoded')
# fired when a board has finished processing a data line
data_line_processed = signal('data_line_processed')
# called when an expansion board is registered
expansion_board_registered = signal('expansion_board_registered')
# called when expansion boards should be registered with the board manager
registering_boards = signal('registering_boards')
|
Add a boards registering signal to allow the board manager to gather connected boards
|
Add a boards registering signal to allow the board manager to gather connected boards
|
Python
|
agpl-3.0
|
will-hart/blitz,will-hart/blitz
|
---
+++
@@ -20,10 +20,12 @@
# fired when a server TCP connection is closed
logger_disconnected = signal('logger_disconnected')
-# fired when the client receives a data row for processing
+# fired when the expansion board receives a data row for processing
+# allows pre-processing of data
data_line_received = signal('data_line_received')
# fired when a variable is ready for entry into the database
+# allows post processing of data
data_variable_decoded = signal('data_variable_decoded')
# fired when a board has finished processing a data line
@@ -31,3 +33,6 @@
# called when an expansion board is registered
expansion_board_registered = signal('expansion_board_registered')
+
+# called when expansion boards should be registered with the board manager
+registering_boards = signal('registering_boards')
|
8292c4afe43ac636ebf23a0740eb06a25fbbb04d
|
backend/post_handler/__init__.py
|
backend/post_handler/__init__.py
|
from flask import Flask
app = Flask(__name__)
@app.route("/", methods=["GET", "POST"])
def hello():
from flask import request
# print dir(request)
# print request.values
sdp_headers = request.form.get('sdp')
with open('./stream.sdp', 'w') as f:
f.write(sdp_headers)
cmd = "ffmpeg -i stream.sdp -vcodec libx264 -acodec aac -strict -2 -y ~/tmp/out.mp4 &"
import os
# os.spawnl(os.P_DETACH, cmd)
os.system(cmd)
return 'ok'
if __name__ == "__main__":
app.run('0.0.0.0')
|
from flask import Flask
app = Flask(__name__)
@app.route("/", methods=["GET", "POST"])
def hello():
from flask import request
# print dir(request)
# print request.values
sdp_headers = request.form.get('sdp')
with open('./stream.sdp', 'w') as f:
f.write(sdp_headers)
import time
ts = time.strftime("%Y-%m-%d-%H:%M:%S") + '.mp4'
cmd = "ffmpeg -i stream.sdp -vcodec libx264 -acodec aac -strict -2 -y ~/tmp/video/{}".format(ts)
import subprocess
subprocess.Popen(cmd, shell=True) # it's async
return 'ok'
if __name__ == "__main__":
app.run('0.0.0.0')
|
Add uniq filenames for videos
|
Add uniq filenames for videos
|
Python
|
mit
|
optimus-team/optimus-video,optimus-team/optimus-video,optimus-team/optimus-video,optimus-team/optimus-video
|
---
+++
@@ -10,10 +10,12 @@
with open('./stream.sdp', 'w') as f:
f.write(sdp_headers)
- cmd = "ffmpeg -i stream.sdp -vcodec libx264 -acodec aac -strict -2 -y ~/tmp/out.mp4 &"
- import os
- # os.spawnl(os.P_DETACH, cmd)
- os.system(cmd)
+
+ import time
+ ts = time.strftime("%Y-%m-%d-%H:%M:%S") + '.mp4'
+ cmd = "ffmpeg -i stream.sdp -vcodec libx264 -acodec aac -strict -2 -y ~/tmp/video/{}".format(ts)
+ import subprocess
+ subprocess.Popen(cmd, shell=True) # it's async
return 'ok'
|
3202d2c067ce76f7e7e12f42b7531e7e082b1b88
|
python-dsl/buck_parser/json_encoder.py
|
python-dsl/buck_parser/json_encoder.py
|
from __future__ import absolute_import, division, print_function, with_statement
import collections
from json import JSONEncoder
# A JSONEncoder subclass which handles map-like and list-like objects.
class BuckJSONEncoder(JSONEncoder):
def __init__(self):
super(BuckJSONEncoder, self).__init__(self)
def default(self, obj):
if isinstance(obj, collections.Mapping) and isinstance(
obj, collections.Sized
): # nopep8
return dict(obj)
elif isinstance(obj, collections.Iterable) and isinstance(
obj, collections.Sized
):
return list(obj)
else:
return super(BuckJSONEncoder, self).default(obj)
|
from __future__ import absolute_import, division, print_function, with_statement
import collections
from json import JSONEncoder
# A JSONEncoder subclass which handles map-like and list-like objects.
class BuckJSONEncoder(JSONEncoder):
def __init__(self):
super(BuckJSONEncoder, self).__init__()
def default(self, obj):
if isinstance(obj, collections.Mapping) and isinstance(
obj, collections.Sized
): # nopep8
return dict(obj)
elif isinstance(obj, collections.Iterable) and isinstance(
obj, collections.Sized
):
return list(obj)
else:
return super(BuckJSONEncoder, self).default(obj)
|
Fix Python 3 incompatible super constructor invocation.
|
Fix Python 3 incompatible super constructor invocation.
Summary: Python is a mess and requires all sorts of hacks to work :(
Reviewed By: philipjameson
fbshipit-source-id: 12f3f59a0d
|
Python
|
apache-2.0
|
brettwooldridge/buck,brettwooldridge/buck,JoelMarcey/buck,brettwooldridge/buck,rmaz/buck,Addepar/buck,facebook/buck,rmaz/buck,romanoid/buck,nguyentruongtho/buck,rmaz/buck,facebook/buck,SeleniumHQ/buck,rmaz/buck,brettwooldridge/buck,rmaz/buck,romanoid/buck,nguyentruongtho/buck,Addepar/buck,SeleniumHQ/buck,Addepar/buck,brettwooldridge/buck,SeleniumHQ/buck,SeleniumHQ/buck,Addepar/buck,brettwooldridge/buck,kageiit/buck,zpao/buck,SeleniumHQ/buck,brettwooldridge/buck,Addepar/buck,JoelMarcey/buck,romanoid/buck,kageiit/buck,facebook/buck,nguyentruongtho/buck,Addepar/buck,Addepar/buck,JoelMarcey/buck,zpao/buck,zpao/buck,zpao/buck,Addepar/buck,JoelMarcey/buck,SeleniumHQ/buck,romanoid/buck,brettwooldridge/buck,rmaz/buck,Addepar/buck,JoelMarcey/buck,SeleniumHQ/buck,brettwooldridge/buck,facebook/buck,romanoid/buck,SeleniumHQ/buck,rmaz/buck,nguyentruongtho/buck,brettwooldridge/buck,nguyentruongtho/buck,SeleniumHQ/buck,romanoid/buck,JoelMarcey/buck,nguyentruongtho/buck,kageiit/buck,romanoid/buck,brettwooldridge/buck,romanoid/buck,zpao/buck,romanoid/buck,JoelMarcey/buck,kageiit/buck,romanoid/buck,rmaz/buck,rmaz/buck,Addepar/buck,SeleniumHQ/buck,facebook/buck,JoelMarcey/buck,romanoid/buck,rmaz/buck,JoelMarcey/buck,kageiit/buck,JoelMarcey/buck,Addepar/buck,romanoid/buck,JoelMarcey/buck,zpao/buck,kageiit/buck,SeleniumHQ/buck,JoelMarcey/buck,Addepar/buck,zpao/buck,rmaz/buck,facebook/buck,brettwooldridge/buck,SeleniumHQ/buck,brettwooldridge/buck,kageiit/buck,SeleniumHQ/buck,Addepar/buck,JoelMarcey/buck,rmaz/buck,facebook/buck,romanoid/buck,rmaz/buck,nguyentruongtho/buck
|
---
+++
@@ -7,7 +7,7 @@
# A JSONEncoder subclass which handles map-like and list-like objects.
class BuckJSONEncoder(JSONEncoder):
def __init__(self):
- super(BuckJSONEncoder, self).__init__(self)
+ super(BuckJSONEncoder, self).__init__()
def default(self, obj):
if isinstance(obj, collections.Mapping) and isinstance(
|
07e825b31912a821d116b2a2b394bd041321cd6d
|
molly/utils/management/commands/deploy.py
|
molly/utils/management/commands/deploy.py
|
import os
from optparse import make_option
from django.core.management import call_command
from django.core.management.base import NoArgsCommand
class Command(NoArgsCommand):
option_list = NoArgsCommand.option_list + (
make_option('--develop',
action='store_true',
dest='develop',
default=False,
help='Create symlinks, rather than copy, existing media, then start the dev server'),
) + (
make_option('--skip-cron',
action='store_true',
dest='skip_cron',
default=False,
help='Skip creating a crontab'),
)
def handle_noargs(self, skip_cron, develop, **options):
call_command('sync_and_migrate')
try:
from molly.wurfl import wurfl_data
except ImportError:
no_wurfl = True
else:
no_wurfl = False
if no_wurfl or not develop:
call_command('update_wurfl')
call_command('collectstatic', interactive=False, link=develop)
call_command('synccompress')
if not skip_cron:
call_command('create_crontab', pipe_to_crontab=(os.name != 'nt'))
if develop:
call_command('runserver')
|
import os
from optparse import make_option
from django.core.management import call_command
from django.core.management.base import NoArgsCommand
class Command(NoArgsCommand):
option_list = NoArgsCommand.option_list + (
make_option('--develop',
action='store_true',
dest='develop',
default=False,
help='Create symlinks, rather than copy, existing media, then start the dev server'),
) + (
make_option('--skip-cron',
action='store_true',
dest='skip_cron',
default=False,
help='Skip creating a crontab'),
)
def handle_noargs(self, skip_cron, develop, **options):
call_command('sync_and_migrate')
try:
from molly.wurfl import wurfl_data
except ImportError:
no_wurfl = True
else:
no_wurfl = False
if no_wurfl or not develop:
call_command('update_wurfl')
call_command('generate_markers', lazy=True)
call_command('collectstatic', interactive=False, link=develop)
call_command('synccompress')
if not skip_cron:
call_command('create_crontab', pipe_to_crontab=(os.name != 'nt'))
if develop:
call_command('runserver')
|
Deploy should remember to generate markers
|
Deploy should remember to generate markers
|
Python
|
apache-2.0
|
mollyproject/mollyproject,mollyproject/mollyproject,mollyproject/mollyproject
|
---
+++
@@ -30,6 +30,7 @@
no_wurfl = False
if no_wurfl or not develop:
call_command('update_wurfl')
+ call_command('generate_markers', lazy=True)
call_command('collectstatic', interactive=False, link=develop)
call_command('synccompress')
if not skip_cron:
|
9c6cb0943381271052e11d35df7c35c677c52cdf
|
vtimshow/vtimageviewer.py
|
vtimshow/vtimageviewer.py
|
#!/usr/bin/env python3
class VtImageViewer:
def __init__(self):
print("Woot!")
|
#!/usr/bin/env python3
from . import defaults
from . import __version__
from PyQt4 import QtGui
class VtImageViewer:
"""
"""
UID = defaults.UID
NAME = defaults.PLUGIN_NAME
COMMENT = defaults.COMMENT
def __init__(self, parent=None):
#super(VtImageViewer, self).__init__(parent)
def helpAbout(self, parent):
"""Full description of the plugin.
This is adapted from the code used in the ``ImportCSV`` class
distributed with ViTables.
"""
from vitables.plugins.aboutpage import AboutPage
desc = {
"version" : __version__,
"module_name" : defaults.MODULE_NAME,
"folder" : defaults.FOLDER,
"author" : "{0:s} <{1:s}>".format(
defaults.AUTHOR, defaults.AUTHOR_EMAIL
),
"comment" : QtGui.QApplication.translate(
defaults.PLUGIN_CLASS,
"""
<qt>
<p>View 2D data set as an image.</p>
<p>
If the data set is simply 2D, view it as an image. If
the dataset is 3D of dimension (N,M,K), view each (N,M)
slice [0,K) as an image with a slider.
</p>
</qt>
""",
"Text of an About plugin message box"
)
}
about_page = AboutPage(desc, parent)
return about_page
|
Add initial corrections to class
|
Add initial corrections to class
Now the class loads and does not crash. I added the help information;
however, it does not do anything yet.
|
Python
|
mit
|
kprussing/vtimshow
|
---
+++
@@ -1,7 +1,50 @@
#!/usr/bin/env python3
+from . import defaults
+from . import __version__
+
+from PyQt4 import QtGui
+
class VtImageViewer:
+ """
+ """
+ UID = defaults.UID
+ NAME = defaults.PLUGIN_NAME
+ COMMENT = defaults.COMMENT
- def __init__(self):
- print("Woot!")
+ def __init__(self, parent=None):
+ #super(VtImageViewer, self).__init__(parent)
+
+ def helpAbout(self, parent):
+ """Full description of the plugin.
+
+ This is adapted from the code used in the ``ImportCSV`` class
+ distributed with ViTables.
+ """
+ from vitables.plugins.aboutpage import AboutPage
+ desc = {
+ "version" : __version__,
+ "module_name" : defaults.MODULE_NAME,
+ "folder" : defaults.FOLDER,
+ "author" : "{0:s} <{1:s}>".format(
+ defaults.AUTHOR, defaults.AUTHOR_EMAIL
+ ),
+ "comment" : QtGui.QApplication.translate(
+ defaults.PLUGIN_CLASS,
+ """
+ <qt>
+ <p>View 2D data set as an image.</p>
+ <p>
+ If the data set is simply 2D, view it as an image. If
+ the dataset is 3D of dimension (N,M,K), view each (N,M)
+ slice [0,K) as an image with a slider.
+ </p>
+ </qt>
+ """,
+ "Text of an About plugin message box"
+ )
+ }
+ about_page = AboutPage(desc, parent)
+ return about_page
+
|
53204208c30780092f1e21ff0d4d66d7a12930ff
|
automat/_introspection.py
|
automat/_introspection.py
|
"""
Python introspection helpers.
"""
from types import CodeType as code, FunctionType as function
def copycode(template, changes):
names = [
"argcount", "nlocals", "stacksize", "flags", "code", "consts",
"names", "varnames", "filename", "name", "firstlineno", "lnotab",
"freevars", "cellvars"
]
if hasattr(code, "co_kwonlyargcount"):
names.insert(1, "kwonlyargcount")
values = [
changes.get(name, getattr(template, "co_" + name))
for name in names
]
return code(*values)
def copyfunction(template, funcchanges, codechanges):
names = [
"globals", "name", "defaults", "closure",
]
values = [
funcchanges.get(name, getattr(template, "__" + name + "__"))
for name in names
]
return function(copycode(template.__code__, codechanges), *values)
def preserveName(f):
"""
Preserve the name of the given function on the decorated function.
"""
def decorator(decorated):
return copyfunction(decorated,
dict(name=f.__name__), dict(name=f.__name__))
return decorator
|
"""
Python introspection helpers.
"""
from types import CodeType as code, FunctionType as function
def copycode(template, changes):
names = [
"argcount", "nlocals", "stacksize", "flags", "code", "consts",
"names", "varnames", "filename", "name", "firstlineno", "lnotab",
"freevars", "cellvars"
]
if hasattr(code, "co_kwonlyargcount"):
names.insert(1, "kwonlyargcount")
if hasattr(code, "co_posonlyargcount"):
# PEP 570 added "positional only arguments"
names.insert(1, "posonlyargcount")
values = [
changes.get(name, getattr(template, "co_" + name))
for name in names
]
return code(*values)
def copyfunction(template, funcchanges, codechanges):
names = [
"globals", "name", "defaults", "closure",
]
values = [
funcchanges.get(name, getattr(template, "__" + name + "__"))
for name in names
]
return function(copycode(template.__code__, codechanges), *values)
def preserveName(f):
"""
Preserve the name of the given function on the decorated function.
"""
def decorator(decorated):
return copyfunction(decorated,
dict(name=f.__name__), dict(name=f.__name__))
return decorator
|
Add support for positional only arguments
|
Add support for positional only arguments
PEP 570 adds "positional only" arguments to Python, which changes the
code object constructor. This adds support for Python 3.8.
Signed-off-by: Robert-André Mauchin <aa2d2b4191fcc92df7813016d4b511c37a1b9a82@gmail.com>
|
Python
|
mit
|
glyph/automat,glyph/Automat
|
---
+++
@@ -13,6 +13,9 @@
]
if hasattr(code, "co_kwonlyargcount"):
names.insert(1, "kwonlyargcount")
+ if hasattr(code, "co_posonlyargcount"):
+ # PEP 570 added "positional only arguments"
+ names.insert(1, "posonlyargcount")
values = [
changes.get(name, getattr(template, "co_" + name))
for name in names
|
4e15bc71205cf308c8338b2608213f439a48d5d6
|
swiftclient/version.py
|
swiftclient/version.py
|
# vim: tabstop=4 shiftwidth=4 softtabstop=4
# Copyright 2012 OpenStack LLC
#
# Licensed under the Apache License, Version 2.0 (the "License"); you may
# not use this file except in compliance with the License. You may obtain
# a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
# WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
# License for the specific language governing permissions and limitations
# under the License.
import pkg_resources
try:
# First, try to get our version out of PKG-INFO. If we're installed,
# this'll let us find our version without pulling in pbr. After all, if
# we're installed on a system, we're not in a Git-managed source tree, so
# pbr doesn't really buy us anything.
version_string = pkg_resources.get_provider(
pkg_resources.Requirement.parse('python-swiftclient')).version
except pkg_resources.DistributionNotFound:
# No PKG-INFO? We're probably running from a checkout, then. Let pbr do
# its thing to figure out a version number.
import pbr.version
version_string = str(pbr.version.VersionInfo('python-swiftclient'))
|
# Copyright 2012 OpenStack LLC
#
# Licensed under the Apache License, Version 2.0 (the "License"); you may
# not use this file except in compliance with the License. You may obtain
# a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
# WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
# License for the specific language governing permissions and limitations
# under the License.
import pkg_resources
try:
# First, try to get our version out of PKG-INFO. If we're installed,
# this'll let us find our version without pulling in pbr. After all, if
# we're installed on a system, we're not in a Git-managed source tree, so
# pbr doesn't really buy us anything.
version_string = pkg_resources.get_provider(
pkg_resources.Requirement.parse('python-swiftclient')).version
except pkg_resources.DistributionNotFound:
# No PKG-INFO? We're probably running from a checkout, then. Let pbr do
# its thing to figure out a version number.
import pbr.version
version_string = str(pbr.version.VersionInfo('python-swiftclient'))
|
Remove extraneous vim configuration comments
|
Remove extraneous vim configuration comments
Remove line containing
comment - # vim: tabstop=4 shiftwidth=4 softtabstop=4
Change-Id: I31e4ee4112285f0daa5f2dd50db0344f4876820d
Closes-Bug:#1229324
|
Python
|
apache-2.0
|
ironsmile/python-swiftclient,varunarya10/python-swiftclient,pratikmallya/python-swiftclient,ironsmile/python-swiftclient,JioCloud/python-swiftclient,jeseem/python-swiftclient,krnflake/python-hubicclient,varunarya10/python-swiftclient,openstack/python-swiftclient,VyacheslavHashov/python-swiftclient,VyacheslavHashov/python-swiftclient,pratikmallya/python-swiftclient,jeseem/python-swiftclient,iostackproject/IO-Bandwidth-Differentiation-Client,JioCloud/python-swiftclient,sohonetlabs/python-swiftclient,zackmdavis/python-swiftclient,zackmdavis/python-swiftclient,openstack/python-swiftclient,iostackproject/IO-Bandwidth-Differentiation-Client,sohonetlabs/python-swiftclient
|
---
+++
@@ -1,5 +1,3 @@
-# vim: tabstop=4 shiftwidth=4 softtabstop=4
-
# Copyright 2012 OpenStack LLC
#
# Licensed under the Apache License, Version 2.0 (the "License"); you may
|
52922fd4117640cc2a9ce6abd72079d43d5641f7
|
connected_components.py
|
connected_components.py
|
def get_connected_components(g):
"""
Return an array of arrays, each representing a connected component.
:param dict g: graph represented as an adjacency list where all nodes are labeled 1 to n.
:returns: array of arrays, each representing a connected component.
"""
connected_components = []
explored = set([])
node_count = len(g)
for i in xrange(1, node_count + 1):
if i not in explored:
connected_component = bfs(g, i, explored)
connected_components.append(connected_component)
return connected_components
def bfs(g, node, explored):
pass
# model this graph:
# 1---2 3---4
# | X | | X |
# 5---6 7---8
g = {
1: [2,5,6],
2: [1,5,6],
3: [7,8,4],
4: [3,7,8],
8: [7,3,4],
7: [3,4,8],
6: [5,1,2],
5: [1,2,6]
}
print get_connected_components(g)
|
from collections import deque
def get_connected_components(g):
"""
Return an array of arrays, each representing a connected component.
:param dict g: graph represented as an adjacency list where all nodes are labeled 1 to n.
:returns: array of arrays, each representing a connected component.
"""
connected_components = []
explored = set([])
node_count = len(g)
for i in xrange(1, node_count + 1):
if i not in explored:
connected_component = bfs(g, i, explored)
connected_components.append(connected_component)
return connected_components
def bfs(g, node, explored):
q = deque([node])
connected_component = [node]
explored.add(node)
while q:
node = q.popleft()
for adj_node in g[node]:
if adj_node not in explored:
explored.add(adj_node)
connected_component.append(adj_node)
q.append(adj_node)
return connected_component
# model this graph:
# 1---2 3---4 9
# | X | | X |
# 5---6 7---8
g = {
1: [2,5,6],
2: [1,5,6],
6: [5,1,2],
5: [1,2,6],
3: [7,8,4],
4: [3,7,8],
8: [7,3,4],
7: [3,4,8],
9: []
}
print get_connected_components(g)
|
Implement bfs for connected components
|
Implement bfs for connected components
|
Python
|
mit
|
stephtzhang/algorithms
|
---
+++
@@ -1,3 +1,5 @@
+from collections import deque
+
def get_connected_components(g):
"""
Return an array of arrays, each representing a connected component.
@@ -15,22 +17,33 @@
return connected_components
def bfs(g, node, explored):
- pass
+ q = deque([node])
+ connected_component = [node]
+ explored.add(node)
+ while q:
+ node = q.popleft()
+ for adj_node in g[node]:
+ if adj_node not in explored:
+ explored.add(adj_node)
+ connected_component.append(adj_node)
+ q.append(adj_node)
+ return connected_component
# model this graph:
-# 1---2 3---4
+# 1---2 3---4 9
# | X | | X |
# 5---6 7---8
g = {
1: [2,5,6],
2: [1,5,6],
+ 6: [5,1,2],
+ 5: [1,2,6],
3: [7,8,4],
4: [3,7,8],
8: [7,3,4],
7: [3,4,8],
- 6: [5,1,2],
- 5: [1,2,6]
+ 9: []
}
print get_connected_components(g)
|
dd1aa173c8d158f45af9eeff8d3cc58c0e272f12
|
solcast/radiation_estimated_actuals.py
|
solcast/radiation_estimated_actuals.py
|
from datetime import datetime, timedelta
from urllib.parse import urljoin
from isodate import parse_datetime, parse_duration
import requests
from solcast.base import Base
class RadiationEstimatedActuals(Base):
end_point = 'radiation/estimated_actuals'
def __init__(self, latitude, longitude, *args, **kwargs):
self.latitude = latitude
self.longitude = longitude
self.latest = kwargs.get('latest', False)
self.estimated_actuals = None
self.params = {'latitude' : self.latitude,
'longitude' : self.longitude,
'capacity' : self.capacity,
'tilt' : self.tilt,
'azimuth' : self.azimuth,
'install_date' : self.install_date,
'loss_factor': self.loss_factor
}
if self.latest:
self.end_point = self.end_point + '/latest'
self._get(*args, **kwargs)
if self.ok:
self._generate_est_acts_dict()
def _generate_est_acts_dict(self):
self.estimated_actuals = []
for est_act in self.content.get('estimated_actuals'):
# Convert period_end and period. All other fields should already be
# the correct type
est_act['period_end'] = parse_datetime(est_act['period_end'])
est_act['period'] = parse_duration(est_act['period'])
self.estimated_actuals.append(est_act)
|
from datetime import datetime, timedelta
from urllib.parse import urljoin
from isodate import parse_datetime, parse_duration
import requests
from solcast.base import Base
class RadiationEstimatedActuals(Base):
end_point = 'radiation/estimated_actuals'
def __init__(self, latitude, longitude, *args, **kwargs):
self.latitude = latitude
self.longitude = longitude
self.latest = kwargs.get('latest', False)
self.estimated_actuals = None
self.params = {'latitude' : self.latitude, 'longitude' : self.longitude}
if self.latest:
self.end_point = self.end_point + '/latest'
self._get(*args, **kwargs)
if self.ok:
self._generate_est_acts_dict()
def _generate_est_acts_dict(self):
self.estimated_actuals = []
for est_act in self.content.get('estimated_actuals'):
# Convert period_end and period. All other fields should already be
# the correct type
est_act['period_end'] = parse_datetime(est_act['period_end'])
est_act['period'] = parse_duration(est_act['period'])
self.estimated_actuals.append(est_act)
|
Remove parameters that aren't required for an estimate actuals request
|
Remove parameters that aren't required for an estimate actuals request
|
Python
|
mit
|
cjtapper/solcast-py
|
---
+++
@@ -17,14 +17,7 @@
self.latest = kwargs.get('latest', False)
self.estimated_actuals = None
- self.params = {'latitude' : self.latitude,
- 'longitude' : self.longitude,
- 'capacity' : self.capacity,
- 'tilt' : self.tilt,
- 'azimuth' : self.azimuth,
- 'install_date' : self.install_date,
- 'loss_factor': self.loss_factor
- }
+ self.params = {'latitude' : self.latitude, 'longitude' : self.longitude}
if self.latest:
self.end_point = self.end_point + '/latest'
|
7d14d51d138081c4f53ed185f54e975e0a074955
|
bookmarks/forms.py
|
bookmarks/forms.py
|
from flask_wtf import FlaskForm
from wtforms import StringField, PasswordField, BooleanField
from wtforms.validators import DataRequired, Length, EqualTo, Email, URL
class BookmarkForm(FlaskForm):
b_id = StringField('Bookmark ID', [
Length(min=6,
max=6,
message='Bookmark ID must be 6 characters long')
])
link = StringField('Link', [
DataRequired(),
URL(message='Link must be a properly formatted URL')
])
follow_redirects = BooleanField('Follow Redirects?')
class RegisterForm(FlaskForm):
username = StringField('Username', [
Length(min=4,
max=25,
message='Username must be between 4 and 25 characters')
])
name = StringField('Name', [DataRequired()])
email = StringField('Email Address', [Email(), Length(min=6, max=35)])
password = PasswordField('New Password', [
Length(min=5, max=18),
EqualTo('confirm', message='Passwords must match')
])
confirm = PasswordField('Repeat Password')
accept_tos = BooleanField('I accept the TOS')
|
from flask_wtf import FlaskForm
from wtforms import StringField, PasswordField, BooleanField
from wtforms.validators import (DataRequired, Length, EqualTo, Email, Regexp,
URL)
class BookmarkForm(FlaskForm):
b_id = StringField('Bookmark ID', [
Length(min=6,
max=6,
message='Bookmark ID must be 6 characters long'),
# Validate only lowercase letters and numbers
Regexp('^[0-9a-z]{1,6}$',
message='Can only include lowercase letters and digits')
])
link = StringField('Link', [
DataRequired(),
URL(message='Link must be a properly formatted URL')
])
follow_redirects = BooleanField('Follow Redirects?')
class RegisterForm(FlaskForm):
username = StringField('Username', [
Length(min=4,
max=25,
message='Username must be between 4 and 25 characters')
])
name = StringField('Name', [DataRequired()])
email = StringField('Email Address', [Email(), Length(min=6, max=35)])
password = PasswordField('New Password', [
Length(min=5, max=18),
EqualTo('confirm', message='Passwords must match')
])
confirm = PasswordField('Repeat Password')
accept_tos = BooleanField('I accept the TOS')
|
Add regex validation check on bookmark form
|
Add regex validation check on bookmark form
Checks that entry is only lowercase letters and numbers
|
Python
|
apache-2.0
|
byanofsky/bookmarks,byanofsky/bookmarks,byanofsky/bookmarks
|
---
+++
@@ -1,13 +1,17 @@
from flask_wtf import FlaskForm
from wtforms import StringField, PasswordField, BooleanField
-from wtforms.validators import DataRequired, Length, EqualTo, Email, URL
+from wtforms.validators import (DataRequired, Length, EqualTo, Email, Regexp,
+ URL)
class BookmarkForm(FlaskForm):
b_id = StringField('Bookmark ID', [
Length(min=6,
max=6,
- message='Bookmark ID must be 6 characters long')
+ message='Bookmark ID must be 6 characters long'),
+ # Validate only lowercase letters and numbers
+ Regexp('^[0-9a-z]{1,6}$',
+ message='Can only include lowercase letters and digits')
])
link = StringField('Link', [
DataRequired(),
|
f350b716157f787c7161b1e914e1210ff9ee4e2e
|
networkx/algorithms/traversal/__init__.py
|
networkx/algorithms/traversal/__init__.py
|
from .depth_first_search import *
from .breadth_first_search import *
from .edgedfs import edge_dfs
|
from .depth_first_search import *
from .breadth_first_search import *
from .edgedfs import *
|
Use import * in traversal submodule.
|
Use import * in traversal submodule.
|
Python
|
bsd-3-clause
|
ionanrozenfeld/networkx,RMKD/networkx,aureooms/networkx,beni55/networkx,wasade/networkx,ionanrozenfeld/networkx,jakevdp/networkx,ghdk/networkx,ghdk/networkx,ltiao/networkx,chrisnatali/networkx,jni/networkx,jni/networkx,dhimmel/networkx,michaelpacer/networkx,farhaanbukhsh/networkx,SanketDG/networkx,dhimmel/networkx,jakevdp/networkx,blublud/networkx,nathania/networkx,jcurbelo/networkx,goulu/networkx,sharifulgeo/networkx,harlowja/networkx,dmoliveira/networkx,tmilicic/networkx,andnovar/networkx,harlowja/networkx,blublud/networkx,farhaanbukhsh/networkx,dmoliveira/networkx,jakevdp/networkx,chrisnatali/networkx,blublud/networkx,OrkoHunter/networkx,debsankha/networkx,Sixshaman/networkx,dhimmel/networkx,sharifulgeo/networkx,chrisnatali/networkx,bzero/networkx,harlowja/networkx,NvanAdrichem/networkx,kernc/networkx,RMKD/networkx,sharifulgeo/networkx,cmtm/networkx,kernc/networkx,debsankha/networkx,jfinkels/networkx,JamesClough/networkx,bzero/networkx,nathania/networkx,ionanrozenfeld/networkx,jni/networkx,RMKD/networkx,aureooms/networkx,nathania/networkx,farhaanbukhsh/networkx,aureooms/networkx,dmoliveira/networkx,bzero/networkx,debsankha/networkx,ghdk/networkx,kernc/networkx,yashu-seth/networkx
|
---
+++
@@ -1,3 +1,3 @@
from .depth_first_search import *
from .breadth_first_search import *
-from .edgedfs import edge_dfs
+from .edgedfs import *
|
c4e0cc76e6051e59078e58e55647671f4acd75a3
|
neutron/conf/policies/floatingip_pools.py
|
neutron/conf/policies/floatingip_pools.py
|
# 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 oslo_policy import policy
from neutron.conf.policies import base
rules = [
policy.DocumentedRuleDefault(
'get_floatingip_pool',
base.RULE_ANY,
'Get floating IP pools',
[
{
'method': 'GET',
'path': '/floatingip_pools',
},
]
),
]
def list_rules():
return rules
|
# 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 oslo_log import versionutils
from oslo_policy import policy
from neutron.conf.policies import base
DEPRECATED_REASON = (
"The Floating IP Pool API now supports system scope and default roles.")
rules = [
policy.DocumentedRuleDefault(
name='get_floatingip_pool',
check_str=base.SYSTEM_OR_PROJECT_READER,
description='Get floating IP pools',
operations=[
{
'method': 'GET',
'path': '/floatingip_pools',
},
],
scope_types=['admin', 'project'],
deprecated_rule=policy.DeprecatedRule(
name='get_floatingip_pool',
check_str=base.RULE_ANY),
deprecated_reason=DEPRECATED_REASON,
deprecated_since=versionutils.deprecated.WALLABY
),
]
def list_rules():
return rules
|
Implement secure RBAC for floating IP pools API
|
Implement secure RBAC for floating IP pools API
This commit updates the policies for floating IP pools API
to understand scope checking and account for a read-only role.
This is part of a broader series of changes across OpenStack to
provide a consistent RBAC experience and improve security.
Partially-Implements blueprint: secure-rbac-roles
Change-Id: I60dea66e2ba6f5f450e3eae3f67f721c35940e92
|
Python
|
apache-2.0
|
mahak/neutron,openstack/neutron,openstack/neutron,mahak/neutron,mahak/neutron,openstack/neutron
|
---
+++
@@ -10,22 +10,31 @@
# License for the specific language governing permissions and limitations
# under the License.
+from oslo_log import versionutils
from oslo_policy import policy
from neutron.conf.policies import base
+DEPRECATED_REASON = (
+ "The Floating IP Pool API now supports system scope and default roles.")
rules = [
policy.DocumentedRuleDefault(
- 'get_floatingip_pool',
- base.RULE_ANY,
- 'Get floating IP pools',
- [
+ name='get_floatingip_pool',
+ check_str=base.SYSTEM_OR_PROJECT_READER,
+ description='Get floating IP pools',
+ operations=[
{
'method': 'GET',
'path': '/floatingip_pools',
},
- ]
+ ],
+ scope_types=['admin', 'project'],
+ deprecated_rule=policy.DeprecatedRule(
+ name='get_floatingip_pool',
+ check_str=base.RULE_ANY),
+ deprecated_reason=DEPRECATED_REASON,
+ deprecated_since=versionutils.deprecated.WALLABY
),
]
|
cb4eae7b76982c500817859b393cb9d4ea086685
|
gcframe/tests/urls.py
|
gcframe/tests/urls.py
|
# -*- coding: utf-8 -*-
""" Simple urls for use in testing the gcframe app. """
from __future__ import unicode_literals
from django.conf.urls.defaults import patterns, url
from .views import normal, framed, exempt
urlpatterns = patterns('',
url(r'normal/$', normal, name='gcframe-test-normal'),
url(r'framed/$', framed, name='gcframe-test-framed'),
url(r'exempt/$', exempt, name='gcframe-test-exempt'),
)
|
# -*- coding: utf-8 -*-
""" Simple urls for use in testing the gcframe app. """
from __future__ import unicode_literals
# The defaults module is deprecated in Django 1.5, but necessary to
# support Django 1.3. drop ``.defaults`` when dropping 1.3 support.
from django.conf.urls.defaults import patterns, url
from .views import normal, framed, exempt
urlpatterns = patterns('',
url(r'normal/$', normal, name='gcframe-test-normal'),
url(r'framed/$', framed, name='gcframe-test-framed'),
url(r'exempt/$', exempt, name='gcframe-test-exempt'),
)
|
Add note regarding URLs defaults module deprecation.
|
Add note regarding URLs defaults module deprecation.
|
Python
|
bsd-3-clause
|
benspaulding/django-gcframe
|
---
+++
@@ -4,6 +4,8 @@
from __future__ import unicode_literals
+# The defaults module is deprecated in Django 1.5, but necessary to
+# support Django 1.3. drop ``.defaults`` when dropping 1.3 support.
from django.conf.urls.defaults import patterns, url
from .views import normal, framed, exempt
|
fbb9824e019b5211abd80ade9445afebc036bb27
|
reporting/shellReporter.py
|
reporting/shellReporter.py
|
#!/usr/bin/env python3
import json
class ShellReporter:
def report_categories(self, categories):
to_dict = lambda x: { '{#TOOL}}': '{:s}'.format(x.tool), '{#TYPE}': '{:s}'.format(x.context) }
category_dict_list = list(map(to_dict, categories))
print(json.dumps(category_dict_list))
def report_job(self, job):
category = '{:s}-{:s}'.format(job.tool, job.type)
self._report_job(job.timestamp, '{:s}.STATUS'.format(category), '{:d} ({:s})'.format(job.status, 'SUCCESS' if job.status else 'FAILURE'))
self._report_job(job.timestamp, '{:s}.DURATION'.format(category), job.duration)
def _report_job(self, timestamp, metric_name, metric_value):
print('timestamp: {:%Y:%m:%dT:%H:%M:%S:%z} - metric_name: {:s} - metric_value: {}'.format(timestamp, metric_name, metric_value))
|
#!/usr/bin/env python3
import json
class ShellReporter:
def report_categories(self, categories):
to_dict = lambda x: { 'TOOL': '{:s}'.format(x.tool), 'CONTEXT': '{:s}'.format(x.context) }
category_dict_list = list(map(to_dict, categories))
print(json.dumps(category_dict_list))
def report_job(self, job):
category = '{:s}-{:s}'.format(job.tool, job.type)
self._report_job(job.timestamp, '{:s}.STATUS'.format(category), '{:d} ({:s})'.format(job.status, 'SUCCESS' if job.status else 'FAILURE'))
self._report_job(job.timestamp, '{:s}.DURATION'.format(category), job.duration)
def _report_job(self, timestamp, metric_name, metric_value):
print('timestamp: {:%Y:%m:%dT:%H:%M:%S:%z} - metric_name: {:s} - metric_value: {}'.format(timestamp, metric_name, metric_value))
|
Rename category fields in shell reporter
|
Rename category fields in shell reporter
|
Python
|
mit
|
luigiberrettini/build-deploy-stats
|
---
+++
@@ -4,7 +4,7 @@
class ShellReporter:
def report_categories(self, categories):
- to_dict = lambda x: { '{#TOOL}}': '{:s}'.format(x.tool), '{#TYPE}': '{:s}'.format(x.context) }
+ to_dict = lambda x: { 'TOOL': '{:s}'.format(x.tool), 'CONTEXT': '{:s}'.format(x.context) }
category_dict_list = list(map(to_dict, categories))
print(json.dumps(category_dict_list))
|
0a7104680d1aeaa7096f9bb7603cd63d46efb480
|
wikitables/util.py
|
wikitables/util.py
|
import sys
import json
def ftag(t):
return lambda node: node.tag == t
def ustr(s):
if sys.version_info < (3, 0):
#py2
return unicode(s).encode('utf-8')
else:
return str(s)
class TableJSONEncoder(json.JSONEncoder):
def default(self, obj):
if hasattr(obj, '__json__'):
return obj.__json__()
return json.JSONEncoder.default(self, obj)
|
import sys
import json
def ftag(t):
return lambda node: node.tag == t
def ustr(s):
if sys.version_info < (3, 0):
#py2
try:
return unicode(s).encode('utf-8')
except UnicodeDecodeError:
return str(s)
else:
return str(s)
class TableJSONEncoder(json.JSONEncoder):
def default(self, obj):
if hasattr(obj, '__json__'):
return obj.__json__()
return json.JSONEncoder.default(self, obj)
|
Add try catch to avoid unicode decode exception in python 2.7.10
|
Add try catch to avoid unicode decode exception in python 2.7.10
|
Python
|
mit
|
bcicen/wikitables
|
---
+++
@@ -7,7 +7,10 @@
def ustr(s):
if sys.version_info < (3, 0):
#py2
- return unicode(s).encode('utf-8')
+ try:
+ return unicode(s).encode('utf-8')
+ except UnicodeDecodeError:
+ return str(s)
else:
return str(s)
|
560e441c64943500a032da8c4f81aef1c3354f84
|
hado/auth_backends.py
|
hado/auth_backends.py
|
from django.conf import settings
from django.contrib.auth.backends import ModelBackend
from django.core.exceptions import ImproperlyConfigured
from django.db.models import get_model
class UserModelBackend(ModelBackend):
def authenticate(self, username=None, password=None):
try:
user = self.user_class.objects.get(username=username)
if user.check_password(password):
return user
except self.user_class.DoesNotExist:
return None
def get_user(self, user_id):
try:
return self.user_class.objects.get(pk=user_id)
except self.user_class.DoesNotExist:
return None
@property
def user_class(self):
if not hasattr(self, '_user_class'):
self._user_class = get_model(*settings.CUSTOM_USER_MODEL.split('.', 2))
if not self._user_class:
raise ImproperlyConfigured('Could not get custom user model')
return self._user_class
|
from django.conf import settings
from django.contrib.auth.backends import ModelBackend
from django.core.exceptions import ImproperlyConfigured
from django.db.models import get_model
from django.contrib.auth.models import User as oUser
from hado.models import User as cUser
class UserModelBackend(ModelBackend):
def authenticate(self, username=None, password=None):
try:
user = self.user_class.objects.get(username=username)
if user.check_password(password):
return user
except self.user_class.DoesNotExist:
try:
ouser = oUser.objects.get(username=username)
u = cUser()
if ouser.check_password(password):
u.password = ouser.password
else:
return None # Abort
# Clone the User
u.id = ouser.id
u.username = ouser.username
u.first_name = ouser.first_name
u.last_name = ouser.last_name
u.email = ouser.email
u.is_active = ouser.is_active
u.is_staff = ouser.is_staff
u.is_superuser = ouser.is_superuser
u.last_login = ouser.last_login
u.date_joined = ouser.date_joined
# Perform the switch over
ouser.delete()
u.save()
return u
except oUser.DoesNotExist:
return None
def get_user(self, user_id):
try:
return self.user_class.objects.get(pk=user_id)
except self.user_class.DoesNotExist:
return None
@property
def user_class(self):
if not hasattr(self, '_user_class'):
self._user_class = get_model(*settings.CUSTOM_USER_MODEL.split('.', 2))
if not self._user_class:
raise ImproperlyConfigured('Could not get custom user model')
return self._user_class
|
Fix for createsuperuser not creating a custom User model, and hence breaking AdminSite logins on setup
|
Fix for createsuperuser not creating a custom User model, and hence breaking AdminSite logins on setup
Since we're using a custom Auth Backend as well, we trap the authenticate() call.
If we can't find the requested user in our custom User, we fall back to checking the vanilla Django Users.
If we find one there, and if the password is valid, we create a new custom User, and clone all information off the vanilla User.
Then we delete the vanilla User and save the custom User in its place, finally returning the custom User instance and completing the authenticate() call successfully.
|
Python
|
mit
|
hackerspacesg/hackdo
|
---
+++
@@ -2,6 +2,9 @@
from django.contrib.auth.backends import ModelBackend
from django.core.exceptions import ImproperlyConfigured
from django.db.models import get_model
+from django.contrib.auth.models import User as oUser
+
+from hado.models import User as cUser
class UserModelBackend(ModelBackend):
def authenticate(self, username=None, password=None):
@@ -10,7 +13,36 @@
if user.check_password(password):
return user
except self.user_class.DoesNotExist:
- return None
+ try:
+ ouser = oUser.objects.get(username=username)
+ u = cUser()
+
+ if ouser.check_password(password):
+ u.password = ouser.password
+ else:
+ return None # Abort
+
+ # Clone the User
+ u.id = ouser.id
+ u.username = ouser.username
+ u.first_name = ouser.first_name
+ u.last_name = ouser.last_name
+ u.email = ouser.email
+ u.is_active = ouser.is_active
+ u.is_staff = ouser.is_staff
+ u.is_superuser = ouser.is_superuser
+ u.last_login = ouser.last_login
+ u.date_joined = ouser.date_joined
+
+ # Perform the switch over
+ ouser.delete()
+ u.save()
+
+ return u
+
+ except oUser.DoesNotExist:
+ return None
+
def get_user(self, user_id):
try:
|
c97339e3a121c48ec3eed38e1bf901e2bf1d323c
|
src/proposals/resources.py
|
src/proposals/resources.py
|
from import_export import fields, resources
from .models import TalkProposal
class TalkProposalResource(resources.ModelResource):
name = fields.Field(attribute='submitter__speaker_name')
email = fields.Field(attribute='submitter__email')
class Meta:
model = TalkProposal
fields = [
'id', 'title', 'category', 'python_level', 'duration',
'name', 'email',
]
export_order = fields
|
from import_export import fields, resources
from .models import TalkProposal
class TalkProposalResource(resources.ModelResource):
name = fields.Field(attribute='submitter__speaker_name')
email = fields.Field(attribute='submitter__email')
class Meta:
model = TalkProposal
fields = [
'id', 'title', 'category', 'python_level', 'duration',
'language', 'name', 'email',
]
export_order = fields
|
Add language field to proposal export
|
Add language field to proposal export
|
Python
|
mit
|
pycontw/pycontw2016,pycontw/pycontw2016,pycontw/pycontw2016,pycontw/pycontw2016
|
---
+++
@@ -12,6 +12,6 @@
model = TalkProposal
fields = [
'id', 'title', 'category', 'python_level', 'duration',
- 'name', 'email',
+ 'language', 'name', 'email',
]
export_order = fields
|
be7fded7f6c9fbc5d370849cc22113c30ab20fe7
|
astrobin_apps_premium/templatetags/astrobin_apps_premium_tags.py
|
astrobin_apps_premium/templatetags/astrobin_apps_premium_tags.py
|
# Python
import urllib
# Django
from django.conf import settings
from django.db.models import Q
from django.template import Library, Node
# Third party
from subscription.models import Subscription, UserSubscription
# This app
from astrobin_apps_premium.utils import premium_get_valid_usersubscription
register = Library()
@register.inclusion_tag('astrobin_apps_premium/inclusion_tags/premium_badge.html')
def premium_badge(user, size = 'large'):
return {
'user': user,
'size': size,
}
@register.filter
def is_premium(user):
print "ciao"
return 'AstroBin Premium' in premium_get_valid_usersubscription(user).subscription.name
@register.filter
def is_lite(user):
return 'AstroBin Lite' in premium_get_valid_usersubscription(user).subscription.name
@register.filter
def is_free(user):
return not (is_lite(user) or is_premium(user))
|
# Python
import urllib
# Django
from django.conf import settings
from django.db.models import Q
from django.template import Library, Node
# Third party
from subscription.models import Subscription, UserSubscription
# This app
from astrobin_apps_premium.utils import premium_get_valid_usersubscription
register = Library()
@register.inclusion_tag('astrobin_apps_premium/inclusion_tags/premium_badge.html')
def premium_badge(user, size = 'large'):
return {
'user': user,
'size': size,
}
@register.filter
def is_premium(user):
return 'AstroBin Premium' in premium_get_valid_usersubscription(user).subscription.name
@register.filter
def is_lite(user):
return 'AstroBin Lite' in premium_get_valid_usersubscription(user).subscription.name
@register.filter
def is_free(user):
return not (is_lite(user) or is_premium(user))
|
Remove stray debug log message
|
Remove stray debug log message
|
Python
|
agpl-3.0
|
astrobin/astrobin,astrobin/astrobin,astrobin/astrobin,astrobin/astrobin
|
---
+++
@@ -25,7 +25,6 @@
@register.filter
def is_premium(user):
- print "ciao"
return 'AstroBin Premium' in premium_get_valid_usersubscription(user).subscription.name
|
b40e1f42af2d392f821ec0da41717d9d14457f8d
|
src/serializer/__init__.py
|
src/serializer/__init__.py
|
from htmlserializer import HTMLSerializer
from xhtmlserializer import XHTMLSerializer
|
import os.path
__path__.append(os.path.dirname(__path__[0]))
from htmlserializer import HTMLSerializer
from xhtmlserializer import XHTMLSerializer
|
Fix imports now that the serializer is in its own sub-package.
|
Fix imports now that the serializer is in its own sub-package.
--HG--
extra : convert_revision : svn%3Aacbfec75-9323-0410-a652-858a13e371e0/trunk%40800
|
Python
|
mit
|
mgilson/html5lib-python,mgilson/html5lib-python,ordbogen/html5lib-python,html5lib/html5lib-python,alex/html5lib-python,alex/html5lib-python,dstufft/html5lib-python,dstufft/html5lib-python,mindw/html5lib-python,gsnedders/html5lib-python,mgilson/html5lib-python,ordbogen/html5lib-python,mindw/html5lib-python,gsnedders/html5lib-python,html5lib/html5lib-python,html5lib/html5lib-python,dstufft/html5lib-python,ordbogen/html5lib-python,alex/html5lib-python,mindw/html5lib-python
|
---
+++
@@ -1,2 +1,6 @@
+
+import os.path
+__path__.append(os.path.dirname(__path__[0]))
+
from htmlserializer import HTMLSerializer
from xhtmlserializer import XHTMLSerializer
|
4c4b5a99e2fd02eff3451bf6c3a761163794a8ce
|
imageofmodel/admin.py
|
imageofmodel/admin.py
|
# -*- coding: utf-8 -*-
from django.contrib import admin
from django import forms
from django.contrib.contenttypes.generic import GenericTabularInline, BaseGenericInlineFormSet
from models import ImageOfModel
class ImageFormset(BaseGenericInlineFormSet):
def clean(self):
if not self.files.values() and not self.instance.images.all():
raise forms.ValidationError(u'Загрузите хотябы одну фотографию')
class ImageOfModelInline(GenericTabularInline):
model = ImageOfModel
formset = ImageFormset
extra = 1
|
# -*- coding: utf-8 -*-
from django.contrib import admin
from django import forms
from django.contrib.contenttypes.generic import GenericTabularInline, BaseGenericInlineFormSet
from models import ImageOfModel
class ImageFormset(BaseGenericInlineFormSet):
def clean(self):
if not self.files.values() and not self.instance.images.all():
raise forms.ValidationError(u'Загрузите хотябы одну фотографию')
class ImageOfModelInline(GenericTabularInline):
model = ImageOfModel
formset = ImageFormset
extra = 1
class OptionalImageOfModelInline(GenericTabularInline):
model = ImageOfModel
extra = 1
|
Add class OptionalImageOfModelInline for optional images
|
[+] Add class OptionalImageOfModelInline for optional images
|
Python
|
bsd-3-clause
|
vixh/django-imageofmodel
|
---
+++
@@ -16,3 +16,8 @@
model = ImageOfModel
formset = ImageFormset
extra = 1
+
+
+class OptionalImageOfModelInline(GenericTabularInline):
+ model = ImageOfModel
+ extra = 1
|
7e80f197d6cd914b9d43f0bc1d9f84e3d226a480
|
fuse_util.py
|
fuse_util.py
|
import sublime
import os
def getSetting(key,default=None):
s = sublime.load_settings("Fuse.sublime-settings")
return s.get(key, default)
def getFusePathFromSettings():
path = getSetting("fuse_path_override")
if path == "" or path == None:
return "fuse"
else:
return path+"/fuse"
def setSetting(key,value):
s = sublime.load_settings("Fuse.sublime-settings")
s.set(key, value)
sublime.save_settings("Fuse.sublime-settings")
def isSupportedSyntax(syntaxName):
return syntaxName == "Uno" or syntaxName == "UX"
def getExtension(path):
base = os.path.basename(path)
return os.path.splitext(base)[0]
def getRowCol(view, pos):
rowcol = view.rowcol(pos)
rowcol = (rowcol[0] + 1, rowcol[1] + 1)
return {"Line": rowcol[0], "Character": rowcol[1]}
|
import sublime
import os
def getSetting(key,default=None):
s = sublime.load_settings("Fuse.sublime-settings")
return s.get(key, default)
def getFusePathFromSettings():
path = getSetting("fuse_path_override")
if path == "" or path == None:
return "fuse"
else:
return path+"/fuse"
def setSetting(key,value):
s = sublime.load_settings("Fuse.sublime-settings")
s.set(key, value)
sublime.save_settings("Fuse.sublime-settings")
def isSupportedSyntax(syntaxName):
return syntaxName == "Uno" or syntaxName == "UX"
def getExtension(path):
base = os.path.basename(path)
ext = os.path.splitext(base)
if ext is None:
return ""
else:
return ext[0]
def getRowCol(view, pos):
rowcol = view.rowcol(pos)
rowcol = (rowcol[0] + 1, rowcol[1] + 1)
return {"Line": rowcol[0], "Character": rowcol[1]}
|
Fix case where there are no extension.
|
Fix case where there are no extension.
|
Python
|
mit
|
fusetools/Fuse.SublimePlugin,fusetools/Fuse.SublimePlugin
|
---
+++
@@ -22,7 +22,12 @@
def getExtension(path):
base = os.path.basename(path)
- return os.path.splitext(base)[0]
+ ext = os.path.splitext(base)
+
+ if ext is None:
+ return ""
+ else:
+ return ext[0]
def getRowCol(view, pos):
rowcol = view.rowcol(pos)
|
a8a088828eee6938c56ce6f2aaecc7e776a8cb23
|
swift/obj/dedupe/fp_index.py
|
swift/obj/dedupe/fp_index.py
|
__author__ = 'mjwtom'
import sqlite3
import unittest
class fp_index:
def __init__(self, name):
if name.endswith('.db'):
self.name = name
else:
self.name = name + '.db'
self.conn = sqlite3.connect(name)
self.c = self.conn.cursor()
self.c.execute('''CREATE TABLE IF NOT EXISTS fp_index (key text, value text)''')
def insert(self, key, value):
data = (key, value)
self.c.execute('INSERT INTO fp_index VALUES (?, ?)', data)
self.conn.commit()
def lookup(self, key):
data = (key,)
self.c.execute('SELECT value FROM fp_index WHERE key=?', data)
return self.c.fetchone()
def testinsert():
fp = fp_index('/home/mjwtom/mydb.db')
for i in range(0, 100):
str = i.__str__()
fp.insert(str, str)
def testselect():
fp = fp_index('/home/mjwtom/mydb.db')
for i in range(0, 100):
str = i.__str__()
c = fp.lookup(str)
for row in c:
print row
if __name__ == '__main__':
unittest.main()
|
__author__ = 'mjwtom'
import sqlite3
import unittest
class Fp_Index(object):
def __init__(self, name):
if name.endswith('.db'):
self.name = name
else:
self.name = name + '.db'
self.conn = sqlite3.connect(name)
self.c = self.conn.cursor()
self.c.execute('''CREATE TABLE IF NOT EXISTS fp_index (key text, value text)''')
def insert(self, key, value):
data = (key, value)
self.c.execute('INSERT INTO fp_index VALUES (?, ?)', data)
self.conn.commit()
def lookup(self, key):
data = (key,)
self.c.execute('SELECT value FROM fp_index WHERE key=?', data)
return self.c.fetchone()
'''
def testinsert():
fp = fp_index('/home/mjwtom/mydb.db')
for i in range(0, 100):
str = i.__str__()
fp.insert(str, str)
def testselect():
fp = fp_index('/home/mjwtom/mydb.db')
for i in range(0, 100):
str = i.__str__()
c = fp.lookup(str)
for row in c:
print row
if __name__ == '__main__':
unittest.main()
'''
|
Use database to detect the duplication. But the md5 value does not match. Need to add some code here
|
Use database to detect the duplication. But the md5 value does not match. Need to add some code here
|
Python
|
apache-2.0
|
mjwtom/swift,mjwtom/swift
|
---
+++
@@ -4,7 +4,7 @@
import unittest
-class fp_index:
+class Fp_Index(object):
def __init__(self, name):
if name.endswith('.db'):
self.name = name
@@ -25,7 +25,7 @@
self.c.execute('SELECT value FROM fp_index WHERE key=?', data)
return self.c.fetchone()
-
+'''
def testinsert():
fp = fp_index('/home/mjwtom/mydb.db')
for i in range(0, 100):
@@ -44,3 +44,4 @@
if __name__ == '__main__':
unittest.main()
+'''
|
8925c3a827659e1983827368948e95e764a40585
|
utf9/__init__.py
|
utf9/__init__.py
|
# -*- coding: utf-8 -*-
from bitarray import bitarray as _bitarray
def utf9encode(string):
bits = _bitarray()
for char in string:
for idx, byte in enumerate(char.encode('utf-8')):
bits.append(idx)
bits.extend('{0:b}'.format(ord(byte)).zfill(8))
return bits.tobytes()
def utf9decode(data):
bits = _bitarray()
bits.frombytes(data)
chunks = (bits[x:x+9] for x in xrange(0, len(bits), 9))
string = u''
codepoint = ''
for chunk in chunks:
if len(chunk) < 9:
break
if chunk[0] == 0:
codepoint, string = '', string + codepoint.decode('utf-8')
codepoint += chr(int(chunk[1:].to01(), 2))
return string + codepoint.decode('utf-8')
|
# -*- coding: utf-8 -*-
"""Encode and decode text with UTF-9.
On April 1st 2005, IEEE released the RFC4042 "UTF-9 and UTF-18 Efficient
Transformation Formats of Unicode" (https://www.ietf.org/rfc/rfc4042.txt)
> The current representation formats for Unicode (UTF-7, UTF-8, UTF-16)
> are not storage and computation efficient on platforms that utilize
> the 9 bit nonet as a natural storage unit instead of the 8 bit octet.
Since there are not so many architecture that use *9 bit nonets as natural
storage units* and the release date was on April Fools' Day, the *beautiful*
UTF-9 was forgotten and no python implementation is available.
This python module is here to fill this gap! ;)
Example:
>>> import utf9
>>> encoded = utf9.utf9encode(u'ႹЄLᒪo, 🌍ǃ')
>>> print utf9.utf9decode(encoded)
ႹЄLᒪo, 🌍ǃ
"""
from bitarray import bitarray as _bitarray
def utf9encode(string):
"""Takes a string and returns a utf9-encoded version."""
bits = _bitarray()
for char in string:
for idx, byte in enumerate(char.encode('utf-8')):
bits.append(idx)
bits.extend('{0:b}'.format(ord(byte)).zfill(8))
return bits.tobytes()
def utf9decode(data):
"""Takes utf9-encoded data and returns the corresponding string."""
bits = _bitarray()
bits.frombytes(data)
chunks = (bits[x:x+9] for x in xrange(0, len(bits), 9))
string = u''
codepoint = ''
for chunk in chunks:
if len(chunk) < 9:
break
if chunk[0] == 0:
codepoint, string = '', string + codepoint.decode('utf-8')
codepoint += chr(int(chunk[1:].to01(), 2))
return string + codepoint.decode('utf-8')
|
Add module and functions docstring
|
Add module and functions docstring
|
Python
|
mit
|
enricobacis/utf9
|
---
+++
@@ -1,8 +1,30 @@
# -*- coding: utf-8 -*-
+"""Encode and decode text with UTF-9.
+
+On April 1st 2005, IEEE released the RFC4042 "UTF-9 and UTF-18 Efficient
+Transformation Formats of Unicode" (https://www.ietf.org/rfc/rfc4042.txt)
+
+> The current representation formats for Unicode (UTF-7, UTF-8, UTF-16)
+> are not storage and computation efficient on platforms that utilize
+> the 9 bit nonet as a natural storage unit instead of the 8 bit octet.
+
+Since there are not so many architecture that use *9 bit nonets as natural
+storage units* and the release date was on April Fools' Day, the *beautiful*
+UTF-9 was forgotten and no python implementation is available.
+
+This python module is here to fill this gap! ;)
+
+Example:
+ >>> import utf9
+ >>> encoded = utf9.utf9encode(u'ႹЄLᒪo, 🌍ǃ')
+ >>> print utf9.utf9decode(encoded)
+ ႹЄLᒪo, 🌍ǃ
+"""
from bitarray import bitarray as _bitarray
def utf9encode(string):
+ """Takes a string and returns a utf9-encoded version."""
bits = _bitarray()
for char in string:
for idx, byte in enumerate(char.encode('utf-8')):
@@ -11,6 +33,7 @@
return bits.tobytes()
def utf9decode(data):
+ """Takes utf9-encoded data and returns the corresponding string."""
bits = _bitarray()
bits.frombytes(data)
chunks = (bits[x:x+9] for x in xrange(0, len(bits), 9))
|
7280bb895284986e141a4660d9f2616b7d2aa99c
|
runtests.py
|
runtests.py
|
import sys
try:
from django.conf import settings
settings.configure(
DEBUG=True,
USE_TZ=True,
DATABASES={
"default": {
"ENGINE": "django.db.backends.sqlite3",
}
},
ROOT_URLCONF="watchman.urls",
INSTALLED_APPS=[
"django.contrib.auth",
"django.contrib.contenttypes",
"django.contrib.sites",
"watchman",
],
SITE_ID=1,
NOSE_ARGS=['-s'],
)
from django_nose import NoseTestSuiteRunner
except ImportError:
raise ImportError("To fix this error, run: pip install -r requirements-test.txt")
def run_tests(*test_args):
if not test_args:
test_args = ['tests']
# Run tests
test_runner = NoseTestSuiteRunner(verbosity=1)
failures = test_runner.run_tests(test_args)
if failures:
sys.exit(failures)
if __name__ == '__main__':
run_tests(*sys.argv[1:])
|
import sys
try:
from django.conf import settings
settings.configure(
DEBUG=True,
USE_TZ=True,
DATABASES={
"default": {
"ENGINE": "django.db.backends.sqlite3",
}
},
ROOT_URLCONF="watchman.urls",
INSTALLED_APPS=[
"django.contrib.auth",
"django.contrib.contenttypes",
"django.contrib.sites",
"watchman",
],
SITE_ID=1,
NOSE_ARGS=['-s'],
)
from django_nose import NoseTestSuiteRunner
except ImportError:
raise ImportError("To fix this error, run: pip install -r requirements-test.txt")
def run_tests(*test_args):
if not test_args:
test_args = ['tests']
# Run tests
test_runner = NoseTestSuiteRunner(verbosity=1)
failures = test_runner.run_tests(test_args)
if failures:
sys.exit(failures)
if __name__ == '__main__':
run_tests(*sys.argv[1:])
|
Add newline at end of file
|
Add newline at end of file
|
Python
|
bsd-3-clause
|
blag/django-watchman,blag/django-watchman,mwarkentin/django-watchman,ulope/django-watchman,JBKahn/django-watchman,gerlachry/django-watchman,ulope/django-watchman,mwarkentin/django-watchman,JBKahn/django-watchman,gerlachry/django-watchman
| |
8bdbcc235a4f7615c0ecbd22f5e6c764feb21e47
|
scripts/update_acq_stats.py
|
scripts/update_acq_stats.py
|
#!/usr/bin/env python
import mica.stats.acq_stats
mica.stats.acq_stats.update()
import os
table_file = mica.stats.acq_stats.table_file
file_stat = os.stat(table_file)
if file_stat.st_size > 50e6:
print """
Warning: {tfile} is larger than 50MB and may need
Warning: to be manually repacked (i.e.):
Warning:
Warning: ptrepack --chunkshape=auto --propindexes --keep-source-filters {tfile} compressed.h5
Warning: cp compressed.h5 {tfile}
""".format(tfile=table_file)
|
#!/usr/bin/env python
import mica.stats.acq_stats
mica.stats.acq_stats.main()
import os
table_file = mica.stats.acq_stats.table_file
file_stat = os.stat(table_file)
if file_stat.st_size > 50e6:
print """
Warning: {tfile} is larger than 50MB and may need
Warning: to be manually repacked (i.e.):
Warning:
Warning: ptrepack --chunkshape=auto --propindexes --keep-source-filters {tfile} compressed.h5
Warning: cp compressed.h5 {tfile}
""".format(tfile=table_file)
|
Call main() to run update script
|
Call main() to run update script
|
Python
|
bsd-3-clause
|
sot/mica,sot/mica
|
---
+++
@@ -1,7 +1,7 @@
#!/usr/bin/env python
import mica.stats.acq_stats
-mica.stats.acq_stats.update()
+mica.stats.acq_stats.main()
import os
table_file = mica.stats.acq_stats.table_file
|
15d2f98980b5a2baea5e6c55cc2d42c848a19e63
|
axes/tests/test_models.py
|
axes/tests/test_models.py
|
from django.test import TestCase
class MigrationsCheck(TestCase):
def setUp(self):
from django.utils import translation
self.saved_locale = translation.get_language()
translation.deactivate_all()
def tearDown(self):
if self.saved_locale is not None:
from django.utils import translation
translation.activate(self.saved_locale)
def test_missing_migrations(self):
from django.db import connection
from django.apps.registry import apps
from django.db.migrations.executor import MigrationExecutor
executor = MigrationExecutor(connection)
from django.db.migrations.autodetector import MigrationAutodetector
from django.db.migrations.state import ProjectState
autodetector = MigrationAutodetector(
executor.loader.project_state(),
ProjectState.from_apps(apps),
)
changes = autodetector.changes(graph=executor.loader.graph)
self.assertEqual({}, changes)
|
from django.apps.registry import apps
from django.db import connection
from django.db.migrations.autodetector import MigrationAutodetector
from django.db.migrations.executor import MigrationExecutor
from django.db.migrations.state import ProjectState
from django.test import TestCase
from django.utils import translation
class MigrationsCheck(TestCase):
def setUp(self):
self.saved_locale = translation.get_language()
translation.deactivate_all()
def tearDown(self):
if self.saved_locale is not None:
translation.activate(self.saved_locale)
def test_missing_migrations(self):
executor = MigrationExecutor(connection)
autodetector = MigrationAutodetector(
executor.loader.project_state(),
ProjectState.from_apps(apps),
)
changes = autodetector.changes(graph=executor.loader.graph)
self.assertEqual({}, changes)
|
Clean up database test case imports
|
Clean up database test case imports
Signed-off-by: Aleksi Häkli <44cb6a94c0d20644d531e2be44779b52833cdcd2@iki.fi>
|
Python
|
mit
|
django-pci/django-axes,jazzband/django-axes
|
---
+++
@@ -1,27 +1,28 @@
+from django.apps.registry import apps
+from django.db import connection
+from django.db.migrations.autodetector import MigrationAutodetector
+from django.db.migrations.executor import MigrationExecutor
+from django.db.migrations.state import ProjectState
from django.test import TestCase
+from django.utils import translation
class MigrationsCheck(TestCase):
def setUp(self):
- from django.utils import translation
self.saved_locale = translation.get_language()
translation.deactivate_all()
def tearDown(self):
if self.saved_locale is not None:
- from django.utils import translation
translation.activate(self.saved_locale)
def test_missing_migrations(self):
- from django.db import connection
- from django.apps.registry import apps
- from django.db.migrations.executor import MigrationExecutor
executor = MigrationExecutor(connection)
- from django.db.migrations.autodetector import MigrationAutodetector
- from django.db.migrations.state import ProjectState
autodetector = MigrationAutodetector(
executor.loader.project_state(),
ProjectState.from_apps(apps),
)
+
changes = autodetector.changes(graph=executor.loader.graph)
+
self.assertEqual({}, changes)
|
e0ffee5d5d6057a6dd776b02fea33c6509eb945c
|
signac/contrib/formats.py
|
signac/contrib/formats.py
|
# Copyright (c) 2016 The Regents of the University of Michigan
# All rights reserved.
# This software is licensed under the BSD 3-Clause License.
import logging
logger = logging.getLogger(__name__)
class BasicFormat(object):
pass
class FileFormat(BasicFormat):
def __init__(self, file_object):
self._file_object = file_object
@property
def data(self):
return self.read()
def read(self, size=-1):
return self._file_object.read(size)
def seek(self, offset):
return self._file_object.seek(offset)
def tell(self):
return self._file_object.tell()
def __iter__(self):
return iter(self._file_object)
def close(self):
return self._file_object.close()
class TextFile(FileFormat):
pass
|
# Copyright (c) 2016 The Regents of the University of Michigan
# All rights reserved.
# This software is licensed under the BSD 3-Clause License.
TextFile = 'TextFile'
|
Replace TextFile class definition with str constant.
|
Replace TextFile class definition with str constant.
|
Python
|
bsd-3-clause
|
csadorf/signac,csadorf/signac
|
---
+++
@@ -1,39 +1,5 @@
# Copyright (c) 2016 The Regents of the University of Michigan
# All rights reserved.
# This software is licensed under the BSD 3-Clause License.
-import logging
-logger = logging.getLogger(__name__)
-
-
-class BasicFormat(object):
- pass
-
-
-class FileFormat(BasicFormat):
-
- def __init__(self, file_object):
- self._file_object = file_object
-
- @property
- def data(self):
- return self.read()
-
- def read(self, size=-1):
- return self._file_object.read(size)
-
- def seek(self, offset):
- return self._file_object.seek(offset)
-
- def tell(self):
- return self._file_object.tell()
-
- def __iter__(self):
- return iter(self._file_object)
-
- def close(self):
- return self._file_object.close()
-
-
-class TextFile(FileFormat):
- pass
+TextFile = 'TextFile'
|
3d3319b96475f40de6dd4e4cf39cdae323fd3b3d
|
arcutils/templatetags/arc.py
|
arcutils/templatetags/arc.py
|
from bootstrapform.templatetags.bootstrap import *
from django.template import Template, Context, Library
from django.template.loader import get_template
from django.utils.safestring import mark_safe
register = Library()
|
from django import template
from django.template.defaulttags import url
from django.core.urlresolvers import reverse
from django.conf import settings
from django.template import Node, Variable, VariableDoesNotExist
from django.utils.html import conditional_escape
from django.utils.safestring import mark_safe
register = template.Library()
@register.filter
def model_name(cls):
"""Given a model class, this returns its verbose name"""
return cls._meta.verbose_name.title()
@register.tag
def full_url(parser, token):
"""Spits out the full URL"""
url_node = url(parser, token)
f = url_node.render
url_node.render = lambda context: _get_host_from_context(context) + f(context)
return url_node
def _get_host_from_context(context):
"""
Returns the hostname from context or the settings.HOSTNAME or
settings.HOST_NAME variables
"""
try:
request = Variable('request.HTTP_HOST').resolve(context)
except VariableDoesNotExist:
request = ""
return request or getattr(settings, "HOSTNAME", "") or getattr(settings, "HOST_NAME", "")
class AddGetParameter(Node):
def __init__(self, values):
self.values = values
def render(self, context):
req = Variable('request').resolve(context)
params = req.GET.copy()
for key, value in self.values.items():
params[key] = value.resolve(context)
return '?%s' % params.urlencode()
@register.tag
def add_get(parser, token):
"""
The tag generates a parameter string in form '?param1=val1¶m2=val2'.
The parameter list is generated by taking all parameters from current
request.GET and optionally overriding them by providing parameters to the tag.
This is a cleaned up version of http://djangosnippets.org/snippets/2105/. It
solves a couple of issues, namely:
* parameters are optional
* parameters can have values from request, e.g. request.GET.foo
* native parsing methods are used for better compatibility and readability
* shorter tag name
Usage: place this code in your appdir/templatetags/add_get_parameter.py
In template:
{% load add_get_parameter %}
<a href="{% add_get param1='const' param2=variable_in_context %}">
Link with modified params
</a>
It's required that you have 'django.core.context_processors.request' in
TEMPLATE_CONTEXT_PROCESSORS
Original version's URL: http://django.mar.lt/2010/07/add-get-parameter-tag.html
"""
pairs = token.split_contents()[1:]
values = {}
for pair in pairs:
s = pair.split('=', 1)
values[s[0]] = parser.compile_filter(s[1])
return AddGetParameter(values)
|
Add a bunch of template tags
|
Add a bunch of template tags
|
Python
|
mit
|
PSU-OIT-ARC/django-arcutils,wylee/django-arcutils,PSU-OIT-ARC/django-arcutils,kfarr2/django-arcutils,wylee/django-arcutils,mdj2/django-arcutils,mdj2/django-arcutils
|
---
+++
@@ -1,6 +1,81 @@
-from bootstrapform.templatetags.bootstrap import *
-from django.template import Template, Context, Library
-from django.template.loader import get_template
+from django import template
+from django.template.defaulttags import url
+from django.core.urlresolvers import reverse
+from django.conf import settings
+from django.template import Node, Variable, VariableDoesNotExist
+from django.utils.html import conditional_escape
from django.utils.safestring import mark_safe
-register = Library()
+register = template.Library()
+
+@register.filter
+def model_name(cls):
+ """Given a model class, this returns its verbose name"""
+ return cls._meta.verbose_name.title()
+
+
+@register.tag
+def full_url(parser, token):
+ """Spits out the full URL"""
+ url_node = url(parser, token)
+ f = url_node.render
+ url_node.render = lambda context: _get_host_from_context(context) + f(context)
+ return url_node
+
+
+def _get_host_from_context(context):
+ """
+ Returns the hostname from context or the settings.HOSTNAME or
+ settings.HOST_NAME variables
+ """
+ try:
+ request = Variable('request.HTTP_HOST').resolve(context)
+ except VariableDoesNotExist:
+ request = ""
+ return request or getattr(settings, "HOSTNAME", "") or getattr(settings, "HOST_NAME", "")
+
+
+class AddGetParameter(Node):
+ def __init__(self, values):
+ self.values = values
+
+ def render(self, context):
+ req = Variable('request').resolve(context)
+ params = req.GET.copy()
+ for key, value in self.values.items():
+ params[key] = value.resolve(context)
+ return '?%s' % params.urlencode()
+
+
+@register.tag
+def add_get(parser, token):
+ """
+ The tag generates a parameter string in form '?param1=val1¶m2=val2'.
+ The parameter list is generated by taking all parameters from current
+ request.GET and optionally overriding them by providing parameters to the tag.
+
+ This is a cleaned up version of http://djangosnippets.org/snippets/2105/. It
+ solves a couple of issues, namely:
+ * parameters are optional
+ * parameters can have values from request, e.g. request.GET.foo
+ * native parsing methods are used for better compatibility and readability
+ * shorter tag name
+
+ Usage: place this code in your appdir/templatetags/add_get_parameter.py
+ In template:
+ {% load add_get_parameter %}
+ <a href="{% add_get param1='const' param2=variable_in_context %}">
+ Link with modified params
+ </a>
+
+ It's required that you have 'django.core.context_processors.request' in
+ TEMPLATE_CONTEXT_PROCESSORS
+
+ Original version's URL: http://django.mar.lt/2010/07/add-get-parameter-tag.html
+ """
+ pairs = token.split_contents()[1:]
+ values = {}
+ for pair in pairs:
+ s = pair.split('=', 1)
+ values[s[0]] = parser.compile_filter(s[1])
+ return AddGetParameter(values)
|
89a95df295036a9fc55ae061eac8e5921f85e095
|
lib/py/src/metrics.py
|
lib/py/src/metrics.py
|
import os
import datetime
import tornado.gen
import statsd
if os.environ.get("STATSD_URL", None):
ip, port = os.environ.get("STATSD_URL").split(':')
statsd_client = statsd.Client(ip, int(port))
else:
statsd_client = None
def instrument(name):
def instrument_wrapper(fn):
@tornado.gen.coroutine
def fn_wrapper(*args, **kwargs):
def send_duration():
duration = (datetime.datetime.now() - start).total_seconds()
statsd_client.timing("{}.duration".format(name),
int(duration * 1000))
start = datetime.datetime.now()
ftr_result = fn(*args, **kwargs)
try:
result = yield ftr_result
except Exception as e:
if statsd_client:
statsd_client.incr("{}.exceptions.{}".format(
name, e.__class__.__name__.lower()))
send_duration()
raise e
else:
if statsd_client:
send_duration()
statsd_client.incr("{}.success".format(name))
raise tornado.gen.Return(result)
return fn_wrapper
return instrument_wrapper
|
import os
import datetime
import tornado.gen
import statsd
if os.environ.get("STATSD_URL", None):
ip, port = os.environ.get("STATSD_URL").split(':')
statsd_client = statsd.Client(ip, int(port))
else:
statsd_client = None
def instrument(name):
def instrument_wrapper(fn):
@tornado.gen.coroutine
def fn_wrapper(*args, **kwargs):
def send_duration():
duration = (datetime.datetime.now() - start).total_seconds()
statsd_client.timing("{}.duration".format(name),
int(duration * 1000))
start = datetime.datetime.now()
ftr_result = fn(*args, **kwargs)
try:
result = yield tornado.gen.maybe_future(ftr_result)
except Exception as e:
if statsd_client:
statsd_client.incr("{}.exceptions.{}".format(
name, e.__class__.__name__.lower()))
send_duration()
raise e
else:
if statsd_client:
send_duration()
statsd_client.incr("{}.success".format(name))
raise tornado.gen.Return(result)
return fn_wrapper
return instrument_wrapper
|
FIx issue with oneway methods
|
FIx issue with oneway methods
|
Python
|
apache-2.0
|
upfluence/thrift,upfluence/thrift,upfluence/thrift,upfluence/thrift,upfluence/thrift,upfluence/thrift,upfluence/thrift,upfluence/thrift,upfluence/thrift,upfluence/thrift,upfluence/thrift,upfluence/thrift
|
---
+++
@@ -23,7 +23,7 @@
ftr_result = fn(*args, **kwargs)
try:
- result = yield ftr_result
+ result = yield tornado.gen.maybe_future(ftr_result)
except Exception as e:
if statsd_client:
statsd_client.incr("{}.exceptions.{}".format(
|
55d9da44e71985e8fa81ffa60ea07f6db8c5e81e
|
ircu/util.py
|
ircu/util.py
|
from ircu import consts
def int_to_base64(n, count):
buf = ''
while count > 0:
count -= 1
buf = consts.BASE64_INT_TO_NUM[n & consts.BASE64_NUMNICKMASK] + buf
n >>= consts.BASE64_NUMNICKLOG
return buf
def base64_to_int(s):
n = 0
for ii in range(0, len(s)):
n = n << 6
n += consts.BASE64_NUM_TO_INT[ord(s[ii])]
return n
|
from ircu import consts
def int_to_base64(n, count):
buf = ''
while count:
count -= 1
buf = consts.BASE64_INT_TO_NUM[n & consts.BASE64_NUMNICKMASK] + buf
n >>= consts.BASE64_NUMNICKLOG
return buf
def base64_to_int(s):
n = 0
for ii in range(0, len(s)):
n = n << 6
n += consts.BASE64_NUM_TO_INT[ord(s[ii])]
return n
def server_num_str(s):
return int_to_base64(s, consts.BASE64_SERVLEN)
def user_num_str(s):
return int_to_base64(s, consts.BASE64_USERLEN)
def server_num_int(s):
return base64_to_int(s)
def user_num_int(s):
return base64_to_int(s)
|
Add server/user numeric conversion methods
|
Add server/user numeric conversion methods
|
Python
|
mit
|
briancline/ircu-python
|
---
+++
@@ -3,7 +3,7 @@
def int_to_base64(n, count):
buf = ''
- while count > 0:
+ while count:
count -= 1
buf = consts.BASE64_INT_TO_NUM[n & consts.BASE64_NUMNICKMASK] + buf
n >>= consts.BASE64_NUMNICKLOG
@@ -16,3 +16,19 @@
n = n << 6
n += consts.BASE64_NUM_TO_INT[ord(s[ii])]
return n
+
+
+def server_num_str(s):
+ return int_to_base64(s, consts.BASE64_SERVLEN)
+
+
+def user_num_str(s):
+ return int_to_base64(s, consts.BASE64_USERLEN)
+
+
+def server_num_int(s):
+ return base64_to_int(s)
+
+
+def user_num_int(s):
+ return base64_to_int(s)
|
5df86afa64aafb4aee1adb066307910e0fb64256
|
jd2chm_utils.py
|
jd2chm_utils.py
|
import os
import sys
import jd2chm_log
import jd2chm_conf
logging = None
config = None
def getAppDir():
if hasattr(sys, "frozen"): # py2exe
return os.path.dirname(sys.executable)
return os.path.dirname(sys.argv[0])
def getLogging(level=2):
global logging
if not logging:
logging = jd2chm_log.Jd2chmLogging(level)
return logging
def getLog():
"""Faciliate sharing the logger accross the different modules."""
return getLogging().logger
def getConf():
global config
if not config:
config = jd2chm_conf.Jd2chmConfig()
config.init()
return config
|
import os
import sys
import shutil
import jd2chm_log as log
import jd2chm_conf as conf
import jd2chm_const as const
logging = None
config = None
def get_app_dir():
if hasattr(sys, "frozen"): # py2exe
return os.path.dirname(sys.executable)
return os.path.dirname(sys.argv[0])
def get_logging(level=2):
global logging
if not logging:
logging = log.Jd2chmLogging(level)
return logging
def get_log():
"""Facilitate sharing the logger across the different modules."""
return get_logging().logger
def get_conf():
global config
if not config:
config = conf.Jd2chmConfig()
config.init()
return config
def term_width():
return shutil.get_terminal_size((const.DEFAULT_TERM_WIDTH,
const.DEFAULT_TERM_HEIGHT)).columns - const.TERM_MARGIN
def center(line, max_line=0):
"""Center a padded string based on the width of the terminal.
If max_line is provided for justified text, line shorter than max_line
will only be padded on the left side.
"""
width = term_width()
left_margin = (width - max_line) / 2
if len(line) < max_line:
return (' ' * int(left_margin)) + line
return line.center(width, ' ')
def print_center_block(text, max_line=0):
"""Print a block of text centered on the terminal."""
for line in text.split('\n'):
print(center(line, max_line))
|
Reformat code. Added methods to pretty print messages.
|
Reformat code. Added methods to pretty print messages.
|
Python
|
mit
|
andreburgaud/jd2chm,andreburgaud/jd2chm
|
---
+++
@@ -1,30 +1,62 @@
import os
import sys
+import shutil
-import jd2chm_log
-import jd2chm_conf
+import jd2chm_log as log
+import jd2chm_conf as conf
+import jd2chm_const as const
logging = None
config = None
-def getAppDir():
- if hasattr(sys, "frozen"): # py2exe
- return os.path.dirname(sys.executable)
- return os.path.dirname(sys.argv[0])
-def getLogging(level=2):
- global logging
- if not logging:
- logging = jd2chm_log.Jd2chmLogging(level)
- return logging
+def get_app_dir():
+ if hasattr(sys, "frozen"): # py2exe
+ return os.path.dirname(sys.executable)
+ return os.path.dirname(sys.argv[0])
-def getLog():
- """Faciliate sharing the logger accross the different modules."""
- return getLogging().logger
-def getConf():
- global config
- if not config:
- config = jd2chm_conf.Jd2chmConfig()
- config.init()
- return config
+def get_logging(level=2):
+ global logging
+ if not logging:
+ logging = log.Jd2chmLogging(level)
+ return logging
+
+
+def get_log():
+ """Facilitate sharing the logger across the different modules."""
+ return get_logging().logger
+
+
+def get_conf():
+ global config
+ if not config:
+ config = conf.Jd2chmConfig()
+ config.init()
+ return config
+
+
+def term_width():
+ return shutil.get_terminal_size((const.DEFAULT_TERM_WIDTH,
+ const.DEFAULT_TERM_HEIGHT)).columns - const.TERM_MARGIN
+
+
+def center(line, max_line=0):
+ """Center a padded string based on the width of the terminal.
+
+ If max_line is provided for justified text, line shorter than max_line
+ will only be padded on the left side.
+ """
+
+ width = term_width()
+ left_margin = (width - max_line) / 2
+ if len(line) < max_line:
+ return (' ' * int(left_margin)) + line
+ return line.center(width, ' ')
+
+
+def print_center_block(text, max_line=0):
+ """Print a block of text centered on the terminal."""
+
+ for line in text.split('\n'):
+ print(center(line, max_line))
|
814782f5ef291728ecad6ce6bf430ce1fd82e5c4
|
core/tests/views.py
|
core/tests/views.py
|
from django.conf import settings
from django.core.urlresolvers import reverse
from django.template import TemplateDoesNotExist
from django.test import TestCase
from core.models import Image
from core.tests import create_user
from users.models import User
__all__ = ['CreateImageTest']
class CreateImageTest(TestCase):
def setUp(self):
self.user = create_user("default")
self.client.login(username=self.user.username, password='password')
def tearDown(self):
User.objects.all().delete()
Image.objects.all().delete()
def test_post(self):
with open('logo.png', mode='rb') as image:
response = self.client.post(reverse('image-list'), {'image': image})
image = Image.objects.latest('pk')
self.assertEqual(response.json()['id'], image.pk)
def test_post_error(self):
response = self.client.post(reverse('image-list'), {'image': None})
self.assertJSONEqual(
response.content,
{
'image': [
'The submitted data was not a file. '
'Check the encoding type on the form.'
]
}
)
|
from django.conf import settings
from django.core.urlresolvers import reverse
from django.template import TemplateDoesNotExist
from django.test import TestCase
from core.models import Image
from core.tests import create_user
from users.models import User
__all__ = ['CreateImageTest']
class CreateImageTest(TestCase):
def setUp(self):
self.user = create_user("default")
self.client.login(username=self.user.username, password='password')
def tearDown(self):
User.objects.all().delete()
Image.objects.all().delete()
def test_post(self):
with open('logo.png', mode='rb') as image:
response = self.client.post(reverse('image-list'), {'image': image})
image = Image.objects.latest('pk')
self.assertEqual(response.json()['id'], image.pk)
def test_post_error(self):
response = self.client.post(reverse('image-list'), {'image': None})
self.assertEqual(
response.json(),
{
'image': [
'The submitted data was not a file. '
'Check the encoding type on the form.'
]
}
)
|
Use rsponse.json() to fix test-failure on json-3.5
|
Fix: Use rsponse.json() to fix test-failure on json-3.5
|
Python
|
bsd-2-clause
|
pinry/pinry,pinry/pinry,pinry/pinry,lapo-luchini/pinry,pinry/pinry,lapo-luchini/pinry,lapo-luchini/pinry,lapo-luchini/pinry
|
---
+++
@@ -28,8 +28,8 @@
def test_post_error(self):
response = self.client.post(reverse('image-list'), {'image': None})
- self.assertJSONEqual(
- response.content,
+ self.assertEqual(
+ response.json(),
{
'image': [
'The submitted data was not a file. '
|
49570c1b7dd5c62495a01db07fe070c34db18383
|
tests/test_BaseDataSet_uri_property.py
|
tests/test_BaseDataSet_uri_property.py
|
import os
from . import tmp_dir_fixture # NOQA
def test_uri_property(tmp_dir_fixture): # NOQA
from dtoolcore import _BaseDataSet
admin_metadata = {
"name": os.path.basename(tmp_dir_fixture),
"uuid": "1234",
}
base_ds = _BaseDataSet(tmp_dir_fixture, admin_metadata, None)
expected_uri = "file://localhost{}".format(tmp_dir_fixture)
assert base_ds.uri == expected_uri
|
import os
from . import tmp_uri_fixture # NOQA
def test_uri_property(tmp_uri_fixture): # NOQA
from dtoolcore import _BaseDataSet
admin_metadata = {
"name": os.path.basename(tmp_uri_fixture),
"uuid": "1234",
}
base_ds = _BaseDataSet(tmp_uri_fixture, admin_metadata, None)
assert base_ds.uri == tmp_uri_fixture
|
Fix windows issue with test_uri_property
|
Fix windows issue with test_uri_property
|
Python
|
mit
|
JIC-CSB/dtoolcore
|
---
+++
@@ -1,17 +1,16 @@
import os
-from . import tmp_dir_fixture # NOQA
+from . import tmp_uri_fixture # NOQA
-def test_uri_property(tmp_dir_fixture): # NOQA
+def test_uri_property(tmp_uri_fixture): # NOQA
from dtoolcore import _BaseDataSet
admin_metadata = {
- "name": os.path.basename(tmp_dir_fixture),
+ "name": os.path.basename(tmp_uri_fixture),
"uuid": "1234",
}
- base_ds = _BaseDataSet(tmp_dir_fixture, admin_metadata, None)
+ base_ds = _BaseDataSet(tmp_uri_fixture, admin_metadata, None)
- expected_uri = "file://localhost{}".format(tmp_dir_fixture)
- assert base_ds.uri == expected_uri
+ assert base_ds.uri == tmp_uri_fixture
|
2ecc676dd2521c727eb1d720bac6c2533f8337d9
|
barbican/model/migration/alembic_migrations/versions/d2780d5aa510_change_url_length.py
|
barbican/model/migration/alembic_migrations/versions/d2780d5aa510_change_url_length.py
|
"""change_url_length
Revision ID: d2780d5aa510
Revises: dce488646127
Create Date: 2016-03-11 09:39:32.593231
"""
# revision identifiers, used by Alembic.
revision = 'd2780d5aa510'
down_revision = 'dce488646127'
from alembic import op
import sqlalchemy as sa
def upgrade():
op.alter_column(
'ContainerConsumerMetadatum',
'URL',
type_=sa.String(length=255)
)
|
"""change_url_length
Revision ID: d2780d5aa510
Revises: dce488646127
Create Date: 2016-03-11 09:39:32.593231
"""
# revision identifiers, used by Alembic.
revision = 'd2780d5aa510'
down_revision = 'dce488646127'
from alembic import op
import sqlalchemy as sa
def upgrade():
op.alter_column(
'container_consumer_metadata',
'URL',
type_=sa.String(length=255)
)
|
Change Table name to correct name
|
Change Table name to correct name
The table name is currently wrong in this version and needs to
be changed to the correct name. It is preventing the database
migration script from running correctly.
Closes-Bug: #1562091
Change-Id: I9be88a4385ab58b37be5842aaaefd8353a2f6f76
|
Python
|
apache-2.0
|
openstack/barbican,openstack/barbican
|
---
+++
@@ -16,7 +16,7 @@
def upgrade():
op.alter_column(
- 'ContainerConsumerMetadatum',
+ 'container_consumer_metadata',
'URL',
type_=sa.String(length=255)
)
|
5041862eafcd4b8799f8ab97c25df7d494d6c2ad
|
blockbuster/bb_logging.py
|
blockbuster/bb_logging.py
|
import config
import logging
import logging.handlers
# ######### Set up logging ##########
# log.basicConfig(format="%(asctime)s - %(levelname)s: %(message)s", level=log.DEBUG)
logger = logging.getLogger("blockbuster")
logger.setLevel(logging.DEBUG)
# create file handler which logs even debug messages
tfh = logging.handlers.TimedRotatingFileHandler(str.format('{0}/app.log', config.log_directory),
when='midnight', delay=False, encoding=None, backupCount=7)
tfh.setLevel(logging.DEBUG)
# create console handler with a higher log level
ch = logging.StreamHandler()
ch.setLevel(logging.DEBUG)
# create formatter and add it to the handlers
formatterch = logging.Formatter('%(asctime)s %(levelname)s %(message)s')
formattertfh = logging.Formatter('%(asctime)s %(levelname)s [%(name)s] %(message)s')
ch.setFormatter(formatterch)
tfh.setFormatter(formattertfh)
# add the handlers to logger
logger.addHandler(ch)
logger.addHandler(tfh)
|
import config
import logging
import logging.handlers
# ######### Set up logging ##########
# log.basicConfig(format="%(asctime)s - %(levelname)s: %(message)s", level=log.DEBUG)
logger = logging.getLogger("blockbuster")
logger.setLevel(logging.DEBUG)
# create file handler which logs even debug messages
tfh = logging.handlers.TimedRotatingFileHandler(str.format('{0}/app.log', config.log_directory),
when='midnight', delay=False, encoding=None, backupCount=7)
tfh.setLevel(logging.DEBUG)
# create console handler with a higher log level
ch = logging.StreamHandler()
ch.setLevel(logging.DEBUG)
# create formatter and add it to the handlers
formatterch = logging.Formatter('%(asctime)s %(levelname)s [%(name)s] %(message)s')
formattertfh = logging.Formatter('%(asctime)s %(levelname)s [%(name)s] %(message)s')
ch.setFormatter(formatterch)
tfh.setFormatter(formattertfh)
# add the handlers to logger
logger.addHandler(ch)
logger.addHandler(tfh)
|
Change format of log lines
|
Change format of log lines
|
Python
|
mit
|
mattstibbs/blockbuster-server,mattstibbs/blockbuster-server
|
---
+++
@@ -18,7 +18,7 @@
ch.setLevel(logging.DEBUG)
# create formatter and add it to the handlers
-formatterch = logging.Formatter('%(asctime)s %(levelname)s %(message)s')
+formatterch = logging.Formatter('%(asctime)s %(levelname)s [%(name)s] %(message)s')
formattertfh = logging.Formatter('%(asctime)s %(levelname)s [%(name)s] %(message)s')
ch.setFormatter(formatterch)
tfh.setFormatter(formattertfh)
|
a0a93d1ccd2a2e339da59f6864c63b0fc9857886
|
mailchimp3/baseapi.py
|
mailchimp3/baseapi.py
|
from os import path
class BaseApi(object):
"""
Simple class to buid path for entities
"""
def __init__(self, mc_client):
"""
Initialize the class with you user_id and secret_key
"""
super(BaseApi, self).__init__()
self._mc_client = mc_client
def _build_path(self, *args):
"""
Build path width endpoint and args
"""
return path.join(self.endpoint, *args)
|
from os import path
class BaseApi(object):
"""
Simple class to buid path for entities
"""
def __init__(self, mc_client):
"""
Initialize the class with you user_id and secret_key
"""
super(BaseApi, self).__init__()
self._mc_client = mc_client
def _build_path(self, *args):
"""
Build path width endpoint and args
"""
return "/".join([self.endpoint,] + list(args))
|
Update path build function to work on Windows
|
Update path build function to work on Windows
|
Python
|
mit
|
s0x90/python-mailchimp,charlesthk/python-mailchimp
|
---
+++
@@ -18,4 +18,4 @@
"""
Build path width endpoint and args
"""
- return path.join(self.endpoint, *args)
+ return "/".join([self.endpoint,] + list(args))
|
660fc35a1bb25e728ad86d2b0ce8d3af46645a99
|
base/apps/storage.py
|
base/apps/storage.py
|
import urlparse
from django.conf import settings
from ecstatic.storage import CachedStaticFilesMixin, StaticManifestMixin
from s3_folder_storage.s3 import DefaultStorage, StaticStorage
def domain(url):
return urlparse.urlparse(url).hostname
class MediaFilesStorage(DefaultStorage):
def __init__(self, *args, **kwargs):
kwargs['bucket'] = settings.AWS_STORAGE_BUCKET_NAME
kwargs['custom_domain'] = domain(settings.MEDIA_URL)
super(MediaFilesStorage, self).__init__(*args, **kwargs)
class StaticFilesStorage(StaticStorage):
def __init__(self, *args, **kwargs):
kwargs['bucket'] = settings.AWS_STORAGE_BUCKET_NAME
kwargs['custom_domain'] = domain(settings.STATIC_URL)
super(StaticFilesStorage, self).__init__(*args, **kwargs)
class S3ManifestStorage(StaticManifestMixin, CachedStaticFilesMixin, StaticFilesStorage):
pass
|
import urlparse
from django.conf import settings
from django.contrib.staticfiles.storage import ManifestFilesMixin
from s3_folder_storage.s3 import DefaultStorage, StaticStorage
def domain(url):
return urlparse.urlparse(url).hostname
class MediaFilesStorage(DefaultStorage):
def __init__(self, *args, **kwargs):
kwargs['bucket'] = settings.AWS_STORAGE_BUCKET_NAME
kwargs['custom_domain'] = domain(settings.MEDIA_URL)
super(MediaFilesStorage, self).__init__(*args, **kwargs)
class StaticFilesStorage(StaticStorage):
def __init__(self, *args, **kwargs):
kwargs['bucket'] = settings.AWS_STORAGE_BUCKET_NAME
kwargs['custom_domain'] = domain(settings.STATIC_URL)
super(StaticFilesStorage, self).__init__(*args, **kwargs)
class S3ManifestStorage(ManifestFilesMixin, StaticFilesStorage):
pass
|
Switch out django-ecstatic for ManifestFilesMixin.
|
Switch out django-ecstatic for ManifestFilesMixin.
|
Python
|
apache-2.0
|
hello-base/web,hello-base/web,hello-base/web,hello-base/web
|
---
+++
@@ -1,8 +1,8 @@
import urlparse
from django.conf import settings
+from django.contrib.staticfiles.storage import ManifestFilesMixin
-from ecstatic.storage import CachedStaticFilesMixin, StaticManifestMixin
from s3_folder_storage.s3 import DefaultStorage, StaticStorage
@@ -24,5 +24,5 @@
super(StaticFilesStorage, self).__init__(*args, **kwargs)
-class S3ManifestStorage(StaticManifestMixin, CachedStaticFilesMixin, StaticFilesStorage):
+class S3ManifestStorage(ManifestFilesMixin, StaticFilesStorage):
pass
|
e23ba33c3a57cb384b93bf51a074a83711f0dea0
|
backend/breach/tests/base.py
|
backend/breach/tests/base.py
|
from django.test import TestCase
from breach.models import SampleSet, Victim, Target, Round
class RuptureTestCase(TestCase):
def setUp(self):
target = Target.objects.create(
endpoint='https://di.uoa.gr/?breach=%s',
prefix='test',
alphabet='0123456789'
)
self.victim = Victim.objects.create(
target=target,
sourceip='192.168.10.140',
snifferendpoint='http://localhost/'
)
round = Round.objects.create(
victim=self.victim,
amount=1,
knownsecret='testsecret',
knownalphabet='01'
)
self.samplesets = [
SampleSet.objects.create(
round=round,
candidatealphabet='0',
data='bigbigbigbigbigbig'
),
SampleSet.objects.create(
round=round,
candidatealphabet='1',
data='small'
)
]
|
from django.test import TestCase
from breach.models import SampleSet, Victim, Target, Round
class RuptureTestCase(TestCase):
def setUp(self):
target = Target.objects.create(
endpoint='https://di.uoa.gr/?breach=%s',
prefix='test',
alphabet='0123456789'
)
self.victim = Victim.objects.create(
target=target,
sourceip='192.168.10.140',
snifferendpoint='http://localhost/'
)
round = Round.objects.create(
victim=self.victim,
amount=1,
knownsecret='testsecret',
knownalphabet='01'
)
self.samplesets = [
SampleSet.objects.create(
round=round,
candidatealphabet='0',
data='bigbigbigbigbigbig'
),
SampleSet.objects.create(
round=round,
candidatealphabet='1',
data='small'
)
]
# Balance checking
self.balance_victim = Victim.objects.create(
target=target,
sourceip='192.168.10.141',
snifferendpoint='http://localhost/'
)
|
Add balance checking test victim
|
Add balance checking test victim
|
Python
|
mit
|
dionyziz/rupture,dionyziz/rupture,dimkarakostas/rupture,esarafianou/rupture,esarafianou/rupture,dimkarakostas/rupture,dimriou/rupture,dimkarakostas/rupture,dimriou/rupture,dionyziz/rupture,esarafianou/rupture,dionyziz/rupture,dimriou/rupture,esarafianou/rupture,dimriou/rupture,dimkarakostas/rupture,dimkarakostas/rupture,dionyziz/rupture,dimriou/rupture
|
---
+++
@@ -32,3 +32,10 @@
data='small'
)
]
+
+ # Balance checking
+ self.balance_victim = Victim.objects.create(
+ target=target,
+ sourceip='192.168.10.141',
+ snifferendpoint='http://localhost/'
+ )
|
5d0a29a908a4019e7d7cf1edc17ca1e002e19c14
|
vumi/application/__init__.py
|
vumi/application/__init__.py
|
"""The vumi.application API."""
__all__ = ["ApplicationWorker", "SessionManager", "TagpoolManager",
"MessageStore"]
from vumi.application.base import ApplicationWorker
from vumi.application.session import SessionManager
from vumi.application.tagpool import TagpoolManager
from vumi.application.message_store import MessageStore
|
"""The vumi.application API."""
__all__ = ["ApplicationWorker", "SessionManager", "TagpoolManager",
"MessageStore", "HTTPRelayApplication"]
from vumi.application.base import ApplicationWorker
from vumi.application.session import SessionManager
from vumi.application.tagpool import TagpoolManager
from vumi.application.message_store import MessageStore
from vumi.application.http_relay import HTTPRelayApplication
|
Add HTTPRelayApplication to vumi.application package API.
|
Add HTTPRelayApplication to vumi.application package API.
|
Python
|
bsd-3-clause
|
TouK/vumi,TouK/vumi,vishwaprakashmishra/xmatrix,harrissoerja/vumi,harrissoerja/vumi,TouK/vumi,vishwaprakashmishra/xmatrix,vishwaprakashmishra/xmatrix,harrissoerja/vumi
|
---
+++
@@ -1,9 +1,10 @@
"""The vumi.application API."""
__all__ = ["ApplicationWorker", "SessionManager", "TagpoolManager",
- "MessageStore"]
+ "MessageStore", "HTTPRelayApplication"]
from vumi.application.base import ApplicationWorker
from vumi.application.session import SessionManager
from vumi.application.tagpool import TagpoolManager
from vumi.application.message_store import MessageStore
+from vumi.application.http_relay import HTTPRelayApplication
|
6381204585c64ed70bf23237731bdb92db445c05
|
cycy/parser/ast.py
|
cycy/parser/ast.py
|
class Node(object):
def __eq__(self, other):
return (
self.__class__ == other.__class__ and
self.__dict__ == other.__dict__
)
def __ne__(self, other):
return not self == other
|
class Node(object):
def __eq__(self, other):
return (
self.__class__ == other.__class__ and
self.__dict__ == other.__dict__
)
def __ne__(self, other):
return not self == other
class BinaryOperation(Node):
def __init__(self, operand, left, right):
assert operand in ("+", "-") # for now
self.operand = operand
self.left = left
self.right = right
class Int32(Node):
def __init__(self, value):
assert isinstance(value, int)
assert -2**32 < value <= 2**32-1
self.value = value
|
Add the basic AST nodes.
|
Add the basic AST nodes.
|
Python
|
mit
|
Magnetic/cycy,Magnetic/cycy,Magnetic/cycy
|
---
+++
@@ -7,3 +7,16 @@
def __ne__(self, other):
return not self == other
+
+class BinaryOperation(Node):
+ def __init__(self, operand, left, right):
+ assert operand in ("+", "-") # for now
+ self.operand = operand
+ self.left = left
+ self.right = right
+
+class Int32(Node):
+ def __init__(self, value):
+ assert isinstance(value, int)
+ assert -2**32 < value <= 2**32-1
+ self.value = value
|
294b1c4d398c5f6a01323e18e53d9ab1d1e1a732
|
web/mooctracker/api/views.py
|
web/mooctracker/api/views.py
|
from django.http import HttpResponse
from django.core.context_processors import csrf
import json
from students.models import Student
STATUS_OK = {
'success' : 'API is running'
}
# status view
def status(request):
return HttpResponse(
json.dumps(STATUS_OK),
content_type = 'application/json'
)
# students api implementing GET, POST, PUT & DELETE for Student model
def students(request,id=0):
if request.method == 'GET':
response = []
students = Student.objects.all()
for student in students:
obj = {}
obj.update({ 'id': student.id })
obj.update({ 'name': student.name })
response.append(obj)
return HttpResponse(
json.dumps(response),
content_type = 'application/json')
elif request.method == 'POST':
requestJson = json.loads(request.body)
studentName = requestJson['name']
newStudent = Student(name = studentName)
newStudent.save()
addedStudent = {'id' : newStudent.id , 'name' : newStudent.name}
return HttpResponse(
json.dumps(addedStudent),
content_type='application/json')
elif request.method == 'DELETE':
Student.objects.get(id=id).delete()
message={ 'success' : 'True' }
return HttpResponse(
json.dumps(message),
content_type='application/json')
|
from django.http import HttpResponse
from django.core.context_processors import csrf
import json
from students.models import Student
STATUS_OK = {
'success' : 'API is running'
}
# status view
def status(request):
return HttpResponse(
json.dumps(STATUS_OK),
content_type = 'application/json'
)
# students api implementing GET, POST, PUT & DELETE for Student model
def students(request):
if request.method == 'GET':
response = []
students = Student.objects.all()
for student in students:
obj = {}
obj.update({ 'id': student.id })
obj.update({ 'name': student.name })
response.append(obj)
return HttpResponse(
json.dumps(response),
content_type = 'application/json')
# POST method
elif request.method == 'POST':
requestJson = json.loads(request.body)
studentName = requestJson['name']
newStudent = Student(name = studentName)
newStudent.save()
addedStudent = {'id' : newStudent.id , 'name' : newStudent.name}
return HttpResponse(
json.dumps(addedStudent),
content_type='application/json')
#DELETE Method
elif request.method == 'DELETE':
requestJson = json.loads(request.body)
sid = requestJson['id']
Student.objects.get(id=sid).delete()
message={ 'success' : 'True', 'id': sid}
return HttpResponse(
json.dumps(message),
content_type='application/json')
|
DELETE method added to api
|
DELETE method added to api
|
Python
|
mit
|
Jaaga/mooc-tracker,Jaaga/mooc-tracker,Jaaga/mooc-tracker,Jaaga/mooc-tracker,Jaaga/mooc-tracker,Jaaga/mooc-tracker
|
---
+++
@@ -17,10 +17,9 @@
)
# students api implementing GET, POST, PUT & DELETE for Student model
-def students(request,id=0):
+def students(request):
if request.method == 'GET':
-
response = []
students = Student.objects.all()
for student in students:
@@ -32,6 +31,8 @@
return HttpResponse(
json.dumps(response),
content_type = 'application/json')
+
+ # POST method
elif request.method == 'POST':
requestJson = json.loads(request.body)
@@ -45,9 +46,13 @@
json.dumps(addedStudent),
content_type='application/json')
+ #DELETE Method
+
elif request.method == 'DELETE':
- Student.objects.get(id=id).delete()
- message={ 'success' : 'True' }
+ requestJson = json.loads(request.body)
+ sid = requestJson['id']
+ Student.objects.get(id=sid).delete()
+ message={ 'success' : 'True', 'id': sid}
return HttpResponse(
json.dumps(message),
content_type='application/json')
|
d95be5aa24e85937253025b4ee47d326e2d1d778
|
common/lib/xmodule/html_module.py
|
common/lib/xmodule/html_module.py
|
import json
import logging
from xmodule.x_module import XModule
from xmodule.raw_module import RawDescriptor
from lxml import etree
from pkg_resources import resource_string
log = logging.getLogger("mitx.courseware")
class HtmlModule(XModule):
def get_html(self):
return self.html
def __init__(self, system, location, definition, instance_state=None, shared_state=None, **kwargs):
XModule.__init__(self, system, location, definition, instance_state, shared_state, **kwargs)
self.html = self.definition['data']['text']
class HtmlDescriptor(RawDescriptor):
"""
Module for putting raw html in a course
"""
mako_template = "widgets/html-edit.html"
module_class = HtmlModule
js = {'coffee': [resource_string(__name__, 'js/module/html.coffee')]}
js_module = 'HTML'
|
import json
import logging
from xmodule.x_module import XModule
from xmodule.raw_module import RawDescriptor
from lxml import etree
from pkg_resources import resource_string
log = logging.getLogger("mitx.courseware")
class HtmlModule(XModule):
def get_html(self):
return self.html
def __init__(self, system, location, definition, instance_state=None, shared_state=None, **kwargs):
XModule.__init__(self, system, location, definition, instance_state, shared_state, **kwargs)
self.html = self.definition['data']
class HtmlDescriptor(RawDescriptor):
"""
Module for putting raw html in a course
"""
mako_template = "widgets/html-edit.html"
module_class = HtmlModule
js = {'coffee': [resource_string(__name__, 'js/module/html.coffee')]}
js_module = 'HTML'
|
Fix html rendering after making it a RawDescriptor
|
Fix html rendering after making it a RawDescriptor
|
Python
|
agpl-3.0
|
vikas1885/test1,mbareta/edx-platform-ft,alexthered/kienhoc-platform,adoosii/edx-platform,edx/edx-platform,chudaol/edx-platform,chand3040/cloud_that,AkA84/edx-platform,ahmadiga/min_edx,MakeHer/edx-platform,atsolakid/edx-platform,cpennington/edx-platform,ak2703/edx-platform,rue89-tech/edx-platform,mtlchun/edx,ZLLab-Mooc/edx-platform,msegado/edx-platform,ferabra/edx-platform,rationalAgent/edx-platform-custom,Edraak/edx-platform,bigdatauniversity/edx-platform,abdoosh00/edraak,a-parhom/edx-platform,philanthropy-u/edx-platform,yokose-ks/edx-platform,beni55/edx-platform,philanthropy-u/edx-platform,alexthered/kienhoc-platform,fintech-circle/edx-platform,dsajkl/123,auferack08/edx-platform,zerobatu/edx-platform,marcore/edx-platform,cecep-edu/edx-platform,MSOpenTech/edx-platform,hamzehd/edx-platform,xingyepei/edx-platform,morenopc/edx-platform,miptliot/edx-platform,mushtaqak/edx-platform,dcosentino/edx-platform,utecuy/edx-platform,hastexo/edx-platform,valtech-mooc/edx-platform,cognitiveclass/edx-platform,teltek/edx-platform,leansoft/edx-platform,nikolas/edx-platform,Semi-global/edx-platform,defance/edx-platform,prarthitm/edxplatform,philanthropy-u/edx-platform,jelugbo/tundex,pabloborrego93/edx-platform,wwj718/ANALYSE,Ayub-Khan/edx-platform,romain-li/edx-platform,SravanthiSinha/edx-platform,nanolearning/edx-platform,motion2015/a3,synergeticsedx/deployment-wipro,mahendra-r/edx-platform,ahmedaljazzar/edx-platform,B-MOOC/edx-platform,mjirayu/sit_academy,motion2015/edx-platform,halvertoluke/edx-platform,zhenzhai/edx-platform,UXE/local-edx,zofuthan/edx-platform,jamiefolsom/edx-platform,UOMx/edx-platform,ovnicraft/edx-platform,mjirayu/sit_academy,arbrandes/edx-platform,Semi-global/edx-platform,lduarte1991/edx-platform,EduPepperPDTesting/pepper2013-testing,arbrandes/edx-platform,procangroup/edx-platform,ferabra/edx-platform,jjmiranda/edx-platform,dsajkl/123,hkawasaki/kawasaki-aio8-2,playm2mboy/edx-platform,alexthered/kienhoc-platform,jazkarta/edx-platform-for-isc,Edraak/edraak-platform,kmoocdev2/edx-platform,rhndg/openedx,analyseuc3m/ANALYSE-v1,sameetb-cuelogic/edx-platform-test,cecep-edu/edx-platform,franosincic/edx-platform,shubhdev/edx-platform,zadgroup/edx-platform,polimediaupv/edx-platform,pomegranited/edx-platform,a-parhom/edx-platform,atsolakid/edx-platform,hkawasaki/kawasaki-aio8-1,bdero/edx-platform,solashirai/edx-platform,doismellburning/edx-platform,jazkarta/edx-platform-for-isc,Livit/Livit.Learn.EdX,chudaol/edx-platform,leansoft/edx-platform,chrisndodge/edx-platform,kxliugang/edx-platform,rationalAgent/edx-platform-custom,msegado/edx-platform,cpennington/edx-platform,sameetb-cuelogic/edx-platform-test,hmcmooc/muddx-platform,Stanford-Online/edx-platform,ferabra/edx-platform,polimediaupv/edx-platform,don-github/edx-platform,alu042/edx-platform,pepeportela/edx-platform,jswope00/GAI,TeachAtTUM/edx-platform,beni55/edx-platform,cognitiveclass/edx-platform,kalebhartje/schoolboost,antonve/s4-project-mooc,prarthitm/edxplatform,SravanthiSinha/edx-platform,EduPepperPD/pepper2013,SravanthiSinha/edx-platform,nanolearningllc/edx-platform-cypress-2,Softmotions/edx-platform,nikolas/edx-platform,kmoocdev/edx-platform,chrisndodge/edx-platform,IONISx/edx-platform,jswope00/GAI,ahmadiga/min_edx,zubair-arbi/edx-platform,raccoongang/edx-platform,IndonesiaX/edx-platform,ahmadio/edx-platform,PepperPD/edx-pepper-platform,kalebhartje/schoolboost,edry/edx-platform,synergeticsedx/deployment-wipro,torchingloom/edx-platform,mtlchun/edx,rismalrv/edx-platform,louyihua/edx-platform,BehavioralInsightsTeam/edx-platform,arifsetiawan/edx-platform,gsehub/edx-platform,UXE/local-edx,wwj718/ANALYSE,bigdatauniversity/edx-platform,y12uc231/edx-platform,chauhanhardik/populo_2,adoosii/edx-platform,chudaol/edx-platform,shashank971/edx-platform,wwj718/edx-platform,shurihell/testasia,openfun/edx-platform,Lektorium-LLC/edx-platform,LearnEra/LearnEraPlaftform,vikas1885/test1,leansoft/edx-platform,defance/edx-platform,shubhdev/openedx,OmarIthawi/edx-platform,EduPepperPD/pepper2013,nagyistoce/edx-platform,eemirtekin/edx-platform,marcore/edx-platform,rue89-tech/edx-platform,kxliugang/edx-platform,nanolearning/edx-platform,Unow/edx-platform,Edraak/circleci-edx-platform,jamiefolsom/edx-platform,edry/edx-platform,wwj718/ANALYSE,miptliot/edx-platform,xuxiao19910803/edx-platform,pepeportela/edx-platform,mtlchun/edx,kalebhartje/schoolboost,ESOedX/edx-platform,stvstnfrd/edx-platform,teltek/edx-platform,sudheerchintala/LearnEraPlatForm,jamesblunt/edx-platform,longmen21/edx-platform,rue89-tech/edx-platform,shurihell/testasia,edry/edx-platform,J861449197/edx-platform,zadgroup/edx-platform,lduarte1991/edx-platform,OmarIthawi/edx-platform,jelugbo/tundex,nagyistoce/edx-platform,cpennington/edx-platform,eduNEXT/edx-platform,doganov/edx-platform,Ayub-Khan/edx-platform,TsinghuaX/edx-platform,MakeHer/edx-platform,nttks/edx-platform,devs1991/test_edx_docmode,sameetb-cuelogic/edx-platform-test,rhndg/openedx,ahmadiga/min_edx,J861449197/edx-platform,etzhou/edx-platform,chand3040/cloud_that,jazztpt/edx-platform,EDUlib/edx-platform,eduNEXT/edunext-platform,dcosentino/edx-platform,rue89-tech/edx-platform,waheedahmed/edx-platform,motion2015/edx-platform,ampax/edx-platform,JCBarahona/edX,chudaol/edx-platform,jazkarta/edx-platform,nagyistoce/edx-platform,wwj718/edx-platform,bitifirefly/edx-platform,Unow/edx-platform,mitocw/edx-platform,ampax/edx-platform-backup,rhndg/openedx,nttks/edx-platform,jazztpt/edx-platform,pku9104038/edx-platform,wwj718/ANALYSE,RPI-OPENEDX/edx-platform,mahendra-r/edx-platform,Kalyzee/edx-platform,LICEF/edx-platform,IndonesiaX/edx-platform,defance/edx-platform,Shrhawk/edx-platform,mitocw/edx-platform,chand3040/cloud_that,eemirtekin/edx-platform,bdero/edx-platform,praveen-pal/edx-platform,JioEducation/edx-platform,auferack08/edx-platform,vismartltd/edx-platform,deepsrijit1105/edx-platform,utecuy/edx-platform,simbs/edx-platform,Edraak/circleci-edx-platform,playm2mboy/edx-platform,TsinghuaX/edx-platform,dsajkl/reqiop,mushtaqak/edx-platform,y12uc231/edx-platform,jbassen/edx-platform,kamalx/edx-platform,tanmaykm/edx-platform,beacloudgenius/edx-platform,jamesblunt/edx-platform,simbs/edx-platform,JioEducation/edx-platform,dcosentino/edx-platform,openfun/edx-platform,martynovp/edx-platform,DefyVentures/edx-platform,ferabra/edx-platform,jelugbo/tundex,pepeportela/edx-platform,kalebhartje/schoolboost,ahmedaljazzar/edx-platform,jelugbo/tundex,xingyepei/edx-platform,hmcmooc/muddx-platform,olexiim/edx-platform,nanolearningllc/edx-platform-cypress-2,jolyonb/edx-platform,nttks/edx-platform,vasyarv/edx-platform,knehez/edx-platform,dcosentino/edx-platform,chauhanhardik/populo,CourseTalk/edx-platform,wwj718/edx-platform,nagyistoce/edx-platform,hamzehd/edx-platform,appsembler/edx-platform,jswope00/griffinx,solashirai/edx-platform,eduNEXT/edx-platform,shurihell/testasia,beacloudgenius/edx-platform,shubhdev/openedx,zubair-arbi/edx-platform,hkawasaki/kawasaki-aio8-0,nanolearningllc/edx-platform-cypress-2,shashank971/edx-platform,synergeticsedx/deployment-wipro,beacloudgenius/edx-platform,jbzdak/edx-platform,itsjeyd/edx-platform,jolyonb/edx-platform,polimediaupv/edx-platform,DefyVentures/edx-platform,amir-qayyum-khan/edx-platform,a-parhom/edx-platform,leansoft/edx-platform,jamiefolsom/edx-platform,amir-qayyum-khan/edx-platform,nttks/jenkins-test,kmoocdev2/edx-platform,raccoongang/edx-platform,adoosii/edx-platform,ZLLab-Mooc/edx-platform,Edraak/circleci-edx-platform,hkawasaki/kawasaki-aio8-0,BehavioralInsightsTeam/edx-platform,beacloudgenius/edx-platform,gymnasium/edx-platform,J861449197/edx-platform,jruiperezv/ANALYSE,vasyarv/edx-platform,cecep-edu/edx-platform,olexiim/edx-platform,B-MOOC/edx-platform,teltek/edx-platform,torchingloom/edx-platform,jazztpt/edx-platform,syjeon/new_edx,raccoongang/edx-platform,ampax/edx-platform-backup,beacloudgenius/edx-platform,nttks/jenkins-test,simbs/edx-platform,mushtaqak/edx-platform,jazkarta/edx-platform,wwj718/edx-platform,doismellburning/edx-platform,B-MOOC/edx-platform,rue89-tech/edx-platform,chauhanhardik/populo_2,morpheby/levelup-by,shubhdev/edxOnBaadal,jelugbo/tundex,motion2015/edx-platform,etzhou/edx-platform,LearnEra/LearnEraPlaftform,mushtaqak/edx-platform,procangroup/edx-platform,MakeHer/edx-platform,knehez/edx-platform,kmoocdev2/edx-platform,EduPepperPDTesting/pepper2013-testing,playm2mboy/edx-platform,mtlchun/edx,caesar2164/edx-platform,cyanna/edx-platform,shabab12/edx-platform,naresh21/synergetics-edx-platform,hamzehd/edx-platform,dsajkl/reqiop,kamalx/edx-platform,cecep-edu/edx-platform,appliedx/edx-platform,eduNEXT/edunext-platform,proversity-org/edx-platform,xuxiao19910803/edx-platform,shashank971/edx-platform,jruiperezv/ANALYSE,etzhou/edx-platform,Softmotions/edx-platform,beni55/edx-platform,morpheby/levelup-by,edry/edx-platform,bigdatauniversity/edx-platform,caesar2164/edx-platform,fintech-circle/edx-platform,xuxiao19910803/edx-platform,EduPepperPD/pepper2013,doismellburning/edx-platform,LearnEra/LearnEraPlaftform,benpatterson/edx-platform,pdehaye/theming-edx-platform,jjmiranda/edx-platform,mjirayu/sit_academy,RPI-OPENEDX/edx-platform,PepperPD/edx-pepper-platform,Lektorium-LLC/edx-platform,jonathan-beard/edx-platform,chrisndodge/edx-platform,zhenzhai/edx-platform,auferack08/edx-platform,SravanthiSinha/edx-platform,peterm-itr/edx-platform,eestay/edx-platform,vismartltd/edx-platform,pomegranited/edx-platform,utecuy/edx-platform,hastexo/edx-platform,etzhou/edx-platform,knehez/edx-platform,RPI-OPENEDX/edx-platform,praveen-pal/edx-platform,eestay/edx-platform,carsongee/edx-platform,IONISx/edx-platform,longmen21/edx-platform,nanolearningllc/edx-platform-cypress,jbzdak/edx-platform,zerobatu/edx-platform,EduPepperPDTesting/pepper2013-testing,dsajkl/reqiop,leansoft/edx-platform,longmen21/edx-platform,mushtaqak/edx-platform,martynovp/edx-platform,PepperPD/edx-pepper-platform,andyzsf/edx,abdoosh00/edraak,rhndg/openedx,EDUlib/edx-platform,4eek/edx-platform,morenopc/edx-platform,ahmadio/edx-platform,morpheby/levelup-by,IITBinterns13/edx-platform-dev,arifsetiawan/edx-platform,fintech-circle/edx-platform,edry/edx-platform,Endika/edx-platform,nanolearningllc/edx-platform-cypress,pomegranited/edx-platform,romain-li/edx-platform,kmoocdev2/edx-platform,dkarakats/edx-platform,LICEF/edx-platform,caesar2164/edx-platform,mcgachey/edx-platform,ahmadiga/min_edx,deepsrijit1105/edx-platform,bitifirefly/edx-platform,ESOedX/edx-platform,dsajkl/123,rismalrv/edx-platform,jonathan-beard/edx-platform,cecep-edu/edx-platform,andyzsf/edx,waheedahmed/edx-platform,pabloborrego93/edx-platform,rationalAgent/edx-platform-custom,deepsrijit1105/edx-platform,pku9104038/edx-platform,LICEF/edx-platform,ESOedX/edx-platform,valtech-mooc/edx-platform,zofuthan/edx-platform,peterm-itr/edx-platform,xuxiao19910803/edx,msegado/edx-platform,pku9104038/edx-platform,fly19890211/edx-platform,morenopc/edx-platform,jbassen/edx-platform,jamiefolsom/edx-platform,LICEF/edx-platform,Edraak/circleci-edx-platform,zhenzhai/edx-platform,arbrandes/edx-platform,nanolearningllc/edx-platform-cypress,utecuy/edx-platform,UOMx/edx-platform,SivilTaram/edx-platform,mjg2203/edx-platform-seas,doismellburning/edx-platform,kamalx/edx-platform,proversity-org/edx-platform,EDUlib/edx-platform,zofuthan/edx-platform,y12uc231/edx-platform,zubair-arbi/edx-platform,syjeon/new_edx,antonve/s4-project-mooc,tiagochiavericosta/edx-platform,arifsetiawan/edx-platform,Unow/edx-platform,J861449197/edx-platform,ak2703/edx-platform,benpatterson/edx-platform,4eek/edx-platform,UXE/local-edx,jbzdak/edx-platform,edx-solutions/edx-platform,adoosii/edx-platform,beni55/edx-platform,antonve/s4-project-mooc,carsongee/edx-platform,shubhdev/edx-platform,chauhanhardik/populo,knehez/edx-platform,rhndg/openedx,jruiperezv/ANALYSE,jazkarta/edx-platform,miptliot/edx-platform,devs1991/test_edx_docmode,prarthitm/edxplatform,vismartltd/edx-platform,jonathan-beard/edx-platform,appliedx/edx-platform,Stanford-Online/edx-platform,martynovp/edx-platform,adoosii/edx-platform,10clouds/edx-platform,marcore/edx-platform,jazztpt/edx-platform,inares/edx-platform,mcgachey/edx-platform,hkawasaki/kawasaki-aio8-1,shubhdev/edxOnBaadal,chudaol/edx-platform,amir-qayyum-khan/edx-platform,mcgachey/edx-platform,jswope00/griffinx,angelapper/edx-platform,zhenzhai/edx-platform,devs1991/test_edx_docmode,vikas1885/test1,mbareta/edx-platform-ft,franosincic/edx-platform,WatanabeYasumasa/edx-platform,marcore/edx-platform,MakeHer/edx-platform,kursitet/edx-platform,pdehaye/theming-edx-platform,Lektorium-LLC/edx-platform,Endika/edx-platform,AkA84/edx-platform,Softmotions/edx-platform,jolyonb/edx-platform,hastexo/edx-platform,devs1991/test_edx_docmode,unicri/edx-platform,xinjiguaike/edx-platform,cyanna/edx-platform,polimediaupv/edx-platform,ahmadio/edx-platform,jruiperezv/ANALYSE,IITBinterns13/edx-platform-dev,xinjiguaike/edx-platform,atsolakid/edx-platform,fly19890211/edx-platform,proversity-org/edx-platform,4eek/edx-platform,SivilTaram/edx-platform,pelikanchik/edx-platform,xuxiao19910803/edx-platform,stvstnfrd/edx-platform,olexiim/edx-platform,solashirai/edx-platform,IndonesiaX/edx-platform,gsehub/edx-platform,kxliugang/edx-platform,sudheerchintala/LearnEraPlatForm,tanmaykm/edx-platform,shubhdev/edx-platform,iivic/BoiseStateX,Shrhawk/edx-platform,jamesblunt/edx-platform,waheedahmed/edx-platform,bigdatauniversity/edx-platform,Shrhawk/edx-platform,yokose-ks/edx-platform,beni55/edx-platform,Livit/Livit.Learn.EdX,romain-li/edx-platform,pelikanchik/edx-platform,simbs/edx-platform,kxliugang/edx-platform,antoviaque/edx-platform,devs1991/test_edx_docmode,mjg2203/edx-platform-seas,jswope00/GAI,CredoReference/edx-platform,DNFcode/edx-platform,kamalx/edx-platform,Edraak/circleci-edx-platform,solashirai/edx-platform,auferack08/edx-platform,zadgroup/edx-platform,ampax/edx-platform,jjmiranda/edx-platform,Shrhawk/edx-platform,dkarakats/edx-platform,shubhdev/edxOnBaadal,valtech-mooc/edx-platform,vismartltd/edx-platform,fly19890211/edx-platform,motion2015/a3,CourseTalk/edx-platform,zerobatu/edx-platform,analyseuc3m/ANALYSE-v1,SivilTaram/edx-platform,fly19890211/edx-platform,cselis86/edx-platform,ampax/edx-platform,xinjiguaike/edx-platform,jbzdak/edx-platform,MSOpenTech/edx-platform,ZLLab-Mooc/edx-platform,RPI-OPENEDX/edx-platform,CredoReference/edx-platform,apigee/edx-platform,Semi-global/edx-platform,procangroup/edx-platform,stvstnfrd/edx-platform,tanmaykm/edx-platform,chauhanhardik/populo,eestay/edx-platform,morenopc/edx-platform,apigee/edx-platform,Edraak/edraak-platform,kursitet/edx-platform,Kalyzee/edx-platform,TeachAtTUM/edx-platform,IONISx/edx-platform,simbs/edx-platform,zofuthan/edx-platform,shurihell/testasia,jazkarta/edx-platform,ak2703/edx-platform,mahendra-r/edx-platform,cpennington/edx-platform,openfun/edx-platform,appsembler/edx-platform,4eek/edx-platform,UOMx/edx-platform,CourseTalk/edx-platform,devs1991/test_edx_docmode,jzoldak/edx-platform,tiagochiavericosta/edx-platform,knehez/edx-platform,Kalyzee/edx-platform,4eek/edx-platform,yokose-ks/edx-platform,inares/edx-platform,motion2015/a3,MSOpenTech/edx-platform,abdoosh00/edx-rtl-final,teltek/edx-platform,romain-li/edx-platform,edx-solutions/edx-platform,mbareta/edx-platform-ft,zubair-arbi/edx-platform,pabloborrego93/edx-platform,zofuthan/edx-platform,halvertoluke/edx-platform,ak2703/edx-platform,B-MOOC/edx-platform,halvertoluke/edx-platform,mitocw/edx-platform,jjmiranda/edx-platform,vasyarv/edx-platform,mjirayu/sit_academy,jbzdak/edx-platform,nanolearning/edx-platform,solashirai/edx-platform,waheedahmed/edx-platform,JCBarahona/edX,prarthitm/edxplatform,ahmadio/edx-platform,kmoocdev/edx-platform,hkawasaki/kawasaki-aio8-0,jruiperezv/ANALYSE,rismalrv/edx-platform,iivic/BoiseStateX,playm2mboy/edx-platform,EDUlib/edx-platform,xuxiao19910803/edx,atsolakid/edx-platform,Unow/edx-platform,kamalx/edx-platform,apigee/edx-platform,tiagochiavericosta/edx-platform,EduPepperPDTesting/pepper2013-testing,shabab12/edx-platform,nttks/edx-platform,CourseTalk/edx-platform,shashank971/edx-platform,DNFcode/edx-platform,cyanna/edx-platform,DefyVentures/edx-platform,AkA84/edx-platform,cselis86/edx-platform,Edraak/edx-platform,hkawasaki/kawasaki-aio8-0,andyzsf/edx,openfun/edx-platform,ZLLab-Mooc/edx-platform,benpatterson/edx-platform,ZLLab-Mooc/edx-platform,pdehaye/theming-edx-platform,chauhanhardik/populo_2,hamzehd/edx-platform,unicri/edx-platform,nanolearningllc/edx-platform-cypress-2,eemirtekin/edx-platform,nttks/jenkins-test,ak2703/edx-platform,10clouds/edx-platform,MakeHer/edx-platform,jswope00/griffinx,kmoocdev/edx-platform,10clouds/edx-platform,jazztpt/edx-platform,CredoReference/edx-platform,don-github/edx-platform,olexiim/edx-platform,chauhanhardik/populo_2,motion2015/a3,JioEducation/edx-platform,procangroup/edx-platform,motion2015/edx-platform,abdoosh00/edraak,angelapper/edx-platform,xingyepei/edx-platform,mtlchun/edx,zhenzhai/edx-platform,pelikanchik/edx-platform,jonathan-beard/edx-platform,atsolakid/edx-platform,ESOedX/edx-platform,cognitiveclass/edx-platform,PepperPD/edx-pepper-platform,eduNEXT/edx-platform,don-github/edx-platform,dkarakats/edx-platform,shabab12/edx-platform,vikas1885/test1,mbareta/edx-platform-ft,analyseuc3m/ANALYSE-v1,DefyVentures/edx-platform,doganov/edx-platform,zubair-arbi/edx-platform,jbassen/edx-platform,DNFcode/edx-platform,B-MOOC/edx-platform,ovnicraft/edx-platform,alu042/edx-platform,antonve/s4-project-mooc,eduNEXT/edunext-platform,zadgroup/edx-platform,shurihell/testasia,EduPepperPDTesting/pepper2013-testing,rationalAgent/edx-platform-custom,kmoocdev/edx-platform,arifsetiawan/edx-platform,doganov/edx-platform,edx/edx-platform,abdoosh00/edx-rtl-final,praveen-pal/edx-platform,doganov/edx-platform,JCBarahona/edX,xingyepei/edx-platform,arbrandes/edx-platform,appsembler/edx-platform,inares/edx-platform,louyihua/edx-platform,chrisndodge/edx-platform,andyzsf/edx,a-parhom/edx-platform,cognitiveclass/edx-platform,mitocw/edx-platform,nttks/jenkins-test,rationalAgent/edx-platform-custom,nanolearningllc/edx-platform-cypress,kmoocdev2/edx-platform,martynovp/edx-platform,IndonesiaX/edx-platform,benpatterson/edx-platform,inares/edx-platform,Semi-global/edx-platform,torchingloom/edx-platform,Endika/edx-platform,zerobatu/edx-platform,pdehaye/theming-edx-platform,ampax/edx-platform-backup,IONISx/edx-platform,jswope00/GAI,torchingloom/edx-platform,jzoldak/edx-platform,Livit/Livit.Learn.EdX,chauhanhardik/populo,longmen21/edx-platform,DNFcode/edx-platform,dsajkl/123,AkA84/edx-platform,Edraak/edraak-platform,mcgachey/edx-platform,martynovp/edx-platform,jswope00/griffinx,TeachAtTUM/edx-platform,motion2015/a3,Semi-global/edx-platform,ubc/edx-platform,morpheby/levelup-by,wwj718/edx-platform,analyseuc3m/ANALYSE-v1,antoviaque/edx-platform,appliedx/edx-platform,appliedx/edx-platform,Kalyzee/edx-platform,cyanna/edx-platform,bitifirefly/edx-platform,shubhdev/edx-platform,defance/edx-platform,OmarIthawi/edx-platform,Kalyzee/edx-platform,eduNEXT/edx-platform,valtech-mooc/edx-platform,kmoocdev/edx-platform,jazkarta/edx-platform-for-isc,vismartltd/edx-platform,Endika/edx-platform,LICEF/edx-platform,edx-solutions/edx-platform,shubhdev/openedx,sameetb-cuelogic/edx-platform-test,doganov/edx-platform,bigdatauniversity/edx-platform,benpatterson/edx-platform,dkarakats/edx-platform,shashank971/edx-platform,pomegranited/edx-platform,morenopc/edx-platform,nttks/edx-platform,gsehub/edx-platform,proversity-org/edx-platform,sameetb-cuelogic/edx-platform-test,jzoldak/edx-platform,lduarte1991/edx-platform,SivilTaram/edx-platform,msegado/edx-platform,nikolas/edx-platform,ubc/edx-platform,ampax/edx-platform,jamesblunt/edx-platform,xinjiguaike/edx-platform,cyanna/edx-platform,antonve/s4-project-mooc,Livit/Livit.Learn.EdX,don-github/edx-platform,DefyVentures/edx-platform,jazkarta/edx-platform-for-isc,ovnicraft/edx-platform,ahmedaljazzar/edx-platform,edx/edx-platform,motion2015/edx-platform,bitifirefly/edx-platform,hkawasaki/kawasaki-aio8-2,eduNEXT/edunext-platform,TeachAtTUM/edx-platform,devs1991/test_edx_docmode,msegado/edx-platform,SivilTaram/edx-platform,ferabra/edx-platform,mahendra-r/edx-platform,franosincic/edx-platform,louyihua/edx-platform,mjg2203/edx-platform-seas,fly19890211/edx-platform,raccoongang/edx-platform,Ayub-Khan/edx-platform,IndonesiaX/edx-platform,jamesblunt/edx-platform,IONISx/edx-platform,philanthropy-u/edx-platform,gsehub/edx-platform,waheedahmed/edx-platform,openfun/edx-platform,bitifirefly/edx-platform,synergeticsedx/deployment-wipro,xingyepei/edx-platform,shubhdev/edxOnBaadal,vasyarv/edx-platform,peterm-itr/edx-platform,OmarIthawi/edx-platform,JCBarahona/edX,eestay/edx-platform,torchingloom/edx-platform,jzoldak/edx-platform,hkawasaki/kawasaki-aio8-1,chauhanhardik/populo,nttks/jenkins-test,naresh21/synergetics-edx-platform,mjg2203/edx-platform-seas,ahmedaljazzar/edx-platform,franosincic/edx-platform,dsajkl/reqiop,nanolearningllc/edx-platform-cypress-2,LearnEra/LearnEraPlaftform,hkawasaki/kawasaki-aio8-2,cselis86/edx-platform,iivic/BoiseStateX,pelikanchik/edx-platform,EduPepperPD/pepper2013,gymnasium/edx-platform,xuxiao19910803/edx,hamzehd/edx-platform,louyihua/edx-platform,WatanabeYasumasa/edx-platform,mahendra-r/edx-platform,etzhou/edx-platform,DNFcode/edx-platform,romain-li/edx-platform,dsajkl/123,ubc/edx-platform,cognitiveclass/edx-platform,Stanford-Online/edx-platform,IITBinterns13/edx-platform-dev,rismalrv/edx-platform,naresh21/synergetics-edx-platform,wwj718/ANALYSE,unicri/edx-platform,devs1991/test_edx_docmode,apigee/edx-platform,edx/edx-platform,angelapper/edx-platform,Ayub-Khan/edx-platform,xuxiao19910803/edx-platform,MSOpenTech/edx-platform,BehavioralInsightsTeam/edx-platform,dcosentino/edx-platform,CredoReference/edx-platform,eemirtekin/edx-platform,abdoosh00/edx-rtl-final,appsembler/edx-platform,Softmotions/edx-platform,JioEducation/edx-platform,nikolas/edx-platform,gymnasium/edx-platform,ahmadio/edx-platform,chauhanhardik/populo_2,yokose-ks/edx-platform,nikolas/edx-platform,amir-qayyum-khan/edx-platform,playm2mboy/edx-platform,UXE/local-edx,hkawasaki/kawasaki-aio8-1,ovnicraft/edx-platform,xinjiguaike/edx-platform,bdero/edx-platform,kxliugang/edx-platform,y12uc231/edx-platform,miptliot/edx-platform,jamiefolsom/edx-platform,polimediaupv/edx-platform,abdoosh00/edx-rtl-final,iivic/BoiseStateX,Edraak/edraak-platform,praveen-pal/edx-platform,syjeon/new_edx,ubc/edx-platform,Edraak/edx-platform,jazkarta/edx-platform-for-isc,PepperPD/edx-pepper-platform,caesar2164/edx-platform,utecuy/edx-platform,don-github/edx-platform,alexthered/kienhoc-platform,jbassen/edx-platform,shabab12/edx-platform,tiagochiavericosta/edx-platform,longmen21/edx-platform,Edraak/edx-platform,MSOpenTech/edx-platform,yokose-ks/edx-platform,edx-solutions/edx-platform,jswope00/griffinx,pabloborrego93/edx-platform,chand3040/cloud_that,nanolearningllc/edx-platform-cypress,hastexo/edx-platform,jolyonb/edx-platform,franosincic/edx-platform,sudheerchintala/LearnEraPlatForm,stvstnfrd/edx-platform,unicri/edx-platform,y12uc231/edx-platform,ampax/edx-platform-backup,WatanabeYasumasa/edx-platform,bdero/edx-platform,pomegranited/edx-platform,ampax/edx-platform-backup,jonathan-beard/edx-platform,Stanford-Online/edx-platform,BehavioralInsightsTeam/edx-platform,shubhdev/edxOnBaadal,halvertoluke/edx-platform,Edraak/edx-platform,kursitet/edx-platform,xuxiao19910803/edx,alu042/edx-platform,J861449197/edx-platform,naresh21/synergetics-edx-platform,carsongee/edx-platform,cselis86/edx-platform,rismalrv/edx-platform,olexiim/edx-platform,WatanabeYasumasa/edx-platform,alu042/edx-platform,SravanthiSinha/edx-platform,zadgroup/edx-platform,chand3040/cloud_that,xuxiao19910803/edx,dkarakats/edx-platform,EduPepperPD/pepper2013,pepeportela/edx-platform,antoviaque/edx-platform,shubhdev/edx-platform,10clouds/edx-platform,hmcmooc/muddx-platform,itsjeyd/edx-platform,unicri/edx-platform,deepsrijit1105/edx-platform,tanmaykm/edx-platform,vikas1885/test1,AkA84/edx-platform,kursitet/edx-platform,Shrhawk/edx-platform,ahmadiga/min_edx,jbassen/edx-platform,RPI-OPENEDX/edx-platform,valtech-mooc/edx-platform,shubhdev/openedx,cselis86/edx-platform,eestay/edx-platform,nagyistoce/edx-platform,vasyarv/edx-platform,iivic/BoiseStateX,jazkarta/edx-platform,eemirtekin/edx-platform,sudheerchintala/LearnEraPlatForm,arifsetiawan/edx-platform,alexthered/kienhoc-platform,peterm-itr/edx-platform,lduarte1991/edx-platform,carsongee/edx-platform,ovnicraft/edx-platform,fintech-circle/edx-platform,pku9104038/edx-platform,zerobatu/edx-platform,doismellburning/edx-platform,TsinghuaX/edx-platform,angelapper/edx-platform,IITBinterns13/edx-platform-dev,gymnasium/edx-platform,nanolearning/edx-platform,abdoosh00/edraak,hmcmooc/muddx-platform,UOMx/edx-platform,inares/edx-platform,appliedx/edx-platform,kalebhartje/schoolboost,Ayub-Khan/edx-platform,ubc/edx-platform,itsjeyd/edx-platform,itsjeyd/edx-platform,Lektorium-LLC/edx-platform,Softmotions/edx-platform,TsinghuaX/edx-platform,mcgachey/edx-platform,JCBarahona/edX,hkawasaki/kawasaki-aio8-2,nanolearning/edx-platform,mjirayu/sit_academy,syjeon/new_edx,kursitet/edx-platform,EduPepperPDTesting/pepper2013-testing,halvertoluke/edx-platform,shubhdev/openedx,tiagochiavericosta/edx-platform,antoviaque/edx-platform
|
---
+++
@@ -15,7 +15,7 @@
def __init__(self, system, location, definition, instance_state=None, shared_state=None, **kwargs):
XModule.__init__(self, system, location, definition, instance_state, shared_state, **kwargs)
- self.html = self.definition['data']['text']
+ self.html = self.definition['data']
class HtmlDescriptor(RawDescriptor):
|
a298dd29bfb198804be5e77e0a47733764b4baaf
|
examples/open-existing.py
|
examples/open-existing.py
|
#!/usr/bin/python2
# This is a simple example program to show how to use PyCdlib to open up an
# existing ISO passed on the command-line, and print out all of the file names
# at the root of the ISO.
# Import standard python modules.
import sys
# Import pycdlib itself.
import pycdlib
# Check that there are enough command-line arguments.
if len(sys.argv) != 2:
print("Usage: %s <iso>" % (sys.argv[0]))
sys.exit(1)
# Create a new PyCdlib object.
iso = pycdlib.PyCdlib()
# Open up a file object. This causes PyCdlib to parse all of the metadata on the
# ISO, which is used for later manipulation.
iso.open(sys.argv[1])
# Now iterate through each of the files on the root of the ISO, printing out
# their names.
for child in iso.list_dir('/'):
print(child.file_identifier())
# Close the ISO object. After this call, the PyCdlib object has forgotten
# everything about the previous ISO, and can be re-used.
iso.close()
|
#!/usr/bin/python2
# This is a simple example program to show how to use PyCdlib to open up an
# existing ISO passed on the command-line, and print out all of the file names
# at the root of the ISO.
# Import standard python modules.
import sys
# Import pycdlib itself.
import pycdlib
# Check that there are enough command-line arguments.
if len(sys.argv) != 2:
print("Usage: %s <iso>" % (sys.argv[0]))
sys.exit(1)
# Create a new PyCdlib object.
iso = pycdlib.PyCdlib()
# Open up a file object. This causes PyCdlib to parse all of the metadata on the
# ISO, which is used for later manipulation.
iso.open(sys.argv[1])
# Now iterate through each of the files on the root of the ISO, printing out
# their names.
for child in iso.list_children('/'):
print(child.file_identifier())
# Close the ISO object. After this call, the PyCdlib object has forgotten
# everything about the previous ISO, and can be re-used.
iso.close()
|
Stop using deprecated list_dir in the examples.
|
Stop using deprecated list_dir in the examples.
Signed-off-by: Chris Lalancette <281cd07d7578d97c83271fbbf2faddb83ab3791c@gmail.com>
|
Python
|
lgpl-2.1
|
clalancette/pycdlib,clalancette/pyiso
|
---
+++
@@ -24,7 +24,7 @@
# Now iterate through each of the files on the root of the ISO, printing out
# their names.
-for child in iso.list_dir('/'):
+for child in iso.list_children('/'):
print(child.file_identifier())
# Close the ISO object. After this call, the PyCdlib object has forgotten
|
0cdb7a0baa6e4f00b3b54cb49701175cdb3c8a05
|
entities/filters.py
|
entities/filters.py
|
from . import forms
import django_filters as filters
class Group(filters.FilterSet):
name = filters.CharFilter(lookup_expr='icontains')
class Meta:
form = forms.GroupFilter
|
from . import forms
import django_filters as filters
from features.groups import models
class Group(filters.FilterSet):
name = filters.CharFilter(label='Name', lookup_expr='icontains')
class Meta:
model = models.Group
fields = ['name']
form = forms.GroupFilter
|
Fix filter for django-filter 1.0
|
Fix filter for django-filter 1.0
|
Python
|
agpl-3.0
|
stadtgestalten/stadtgestalten,stadtgestalten/stadtgestalten,stadtgestalten/stadtgestalten
|
---
+++
@@ -1,9 +1,12 @@
from . import forms
import django_filters as filters
+from features.groups import models
class Group(filters.FilterSet):
- name = filters.CharFilter(lookup_expr='icontains')
+ name = filters.CharFilter(label='Name', lookup_expr='icontains')
class Meta:
+ model = models.Group
+ fields = ['name']
form = forms.GroupFilter
|
939a95c2bf849509fd70356ad37c6645e2ca81e4
|
torchtext/data/pipeline.py
|
torchtext/data/pipeline.py
|
class Pipeline(object):
"""Defines a pipeline for transforming sequence data."""
def __init__(self, convert_token=None):
if convert_token is None:
self.convert_token = lambda x: x
elif callable(convert_token):
self.convert_token = convert_token
else:
raise ValueError("Pipeline input convert_token {} is not None "
"or callable".format(convert_token))
self.pipes = [self]
def __call__(self, x, *args):
for pipe in self.pipes:
x = pipe.call(x)
return x
def call(self, x, *args):
if isinstance(x, list):
return [self(tok, *args) for tok in x]
return self.convert_token(x, *args)
def add_before(self, pipeline):
"""Add `pipeline` before this processing pipeline."""
if not isinstance(pipeline, Pipeline):
pipeline = Pipeline(pipeline)
self.pipes = pipeline.pipes[:] + self.pipes[:]
return self
def add_after(self, pipeline):
"""Add `pipeline` after this processing pipeline."""
if not isinstance(pipeline, Pipeline):
pipeline = Pipeline(pipeline)
self.pipes = self.pipes[:] + pipeline.pipes[:]
return self
|
class Pipeline(object):
"""Defines a pipeline for transforming sequence data."""
def __init__(self, convert_token=None):
if convert_token is None:
self.convert_token = lambda x: x
elif callable(convert_token):
self.convert_token = convert_token
else:
raise ValueError("Pipeline input convert_token {} is not None "
"or callable".format(convert_token))
self.pipes = [self]
def __call__(self, x, *args):
for pipe in self.pipes:
x = pipe.call(x, *args)
return x
def call(self, x, *args):
if isinstance(x, list):
return [self(tok, *args) for tok in x]
return self.convert_token(x, *args)
def add_before(self, pipeline):
"""Add `pipeline` before this processing pipeline."""
if not isinstance(pipeline, Pipeline):
pipeline = Pipeline(pipeline)
self.pipes = pipeline.pipes[:] + self.pipes[:]
return self
def add_after(self, pipeline):
"""Add `pipeline` after this processing pipeline."""
if not isinstance(pipeline, Pipeline):
pipeline = Pipeline(pipeline)
self.pipes = self.pipes[:] + pipeline.pipes[:]
return self
|
Fix forwarding positional args in Pipeline __call__
|
Fix forwarding positional args in Pipeline __call__
|
Python
|
bsd-3-clause
|
pytorch/text,pytorch/text,pytorch/text,pytorch/text
|
---
+++
@@ -13,7 +13,7 @@
def __call__(self, x, *args):
for pipe in self.pipes:
- x = pipe.call(x)
+ x = pipe.call(x, *args)
return x
def call(self, x, *args):
|
4a045eb12eb7931b2aad302450c4bca944b42f93
|
utcdatetime/utcdatetime.py
|
utcdatetime/utcdatetime.py
|
import datetime
from .utc_timezone import UTC
FORMAT_NO_FRACTION = '%Y-%m-%dT%H:%M:%SZ'
FORMAT_WITH_FRACTION = '%Y-%m-%dT%H:%M:%S.%fZ'
class utcdatetime(object):
def __init__(self, year, month, day, hour=0, minute=0, second=0,
microsecond=0):
self.__dt = datetime.datetime(year, month, day, hour, minute, second,
microsecond, tzinfo=UTC)
def __str__(self):
return self.__dt.strftime(
FORMAT_WITH_FRACTION if self.__dt.microsecond > 0
else FORMAT_NO_FRACTION)
def __repr__(self):
parts = [self.__dt.year, self.__dt.month, self.__dt.day,
self.__dt.hour, self.__dt.minute]
if self.__dt.second > 0:
parts.append(self.__dt.second)
if self.__dt.microsecond > 0:
parts.append(self.__dt.microsecond)
return 'utcdatetime({})'.format(', '.join(
['{0}'.format(part) for part in parts]))
|
import datetime
from .utc_timezone import UTC
FORMAT_NO_FRACTION = '%Y-%m-%dT%H:%M:%SZ'
FORMAT_WITH_FRACTION = '%Y-%m-%dT%H:%M:%S.%fZ'
class utcdatetime(object):
def __init__(self, year, month, day, hour=0, minute=0, second=0,
microsecond=0):
self.__dt = datetime.datetime(year, month, day, hour, minute, second,
microsecond, tzinfo=UTC)
def __str__(self):
return self.__dt.strftime(
FORMAT_WITH_FRACTION if self.__dt.microsecond > 0
else FORMAT_NO_FRACTION)
def __repr__(self):
parts = [self.__dt.year, self.__dt.month, self.__dt.day,
self.__dt.hour, self.__dt.minute]
if self.__dt.second > 0:
parts.append(self.__dt.second)
if self.__dt.microsecond > 0:
parts.append(self.__dt.microsecond)
return 'utcdatetime({0})'.format(', '.join(
['{0}'.format(part) for part in parts]))
|
Fix format string on Python 2.6
|
Fix format string on Python 2.6
|
Python
|
mit
|
paulfurley/python-utcdatetime,paulfurley/python-utcdatetime
|
---
+++
@@ -27,5 +27,5 @@
if self.__dt.microsecond > 0:
parts.append(self.__dt.microsecond)
- return 'utcdatetime({})'.format(', '.join(
+ return 'utcdatetime({0})'.format(', '.join(
['{0}'.format(part) for part in parts]))
|
4e8043ef74d440d6ece751341664ab1bb3bddebd
|
scripts/ci/extract-changelog.py
|
scripts/ci/extract-changelog.py
|
#!/usr/bin/python
import sys
if len(sys.argv) < 2:
print("Usage: %s <changelog> [<version>]" % (sys.argv[0],))
sys.exit(1)
changelog = open(sys.argv[1]).readlines()
version = "latest"
if len(sys.argv) > 2:
version = sys.argv[2]
start = 0
end = -1
for i, line in enumerate(changelog):
if line.startswith("## "):
if start == 0 and (version == "latest" or line.startswith("## [%s]" % (version,))):
start = i
elif start != 0:
end = i
break
if start != 0:
print ''.join(changelog[start+1:end]).strip()
|
#!/usr/bin/python
import sys
if len(sys.argv) < 2:
print("Usage: %s <changelog> [<version>]" % (sys.argv[0],))
sys.exit(1)
changelog = open(sys.argv[1]).readlines()
version = "latest"
if len(sys.argv) > 2:
version = sys.argv[2]
start = 0
end = -1
for i, line in enumerate(changelog):
if line.startswith("## "):
if start == 0 and (version == "latest" or line.startswith("## [%s]" % (version,))):
start = i
elif start != 0:
end = i
break
if start != 0:
print(''.join(changelog[start+1:end]).strip())
|
Fix script to extract changelog for Python 3
|
Fix script to extract changelog for Python 3
|
Python
|
apache-2.0
|
skydive-project/skydive,skydive-project/skydive,skydive-project/skydive,skydive-project/skydive,skydive-project/skydive,skydive-project/skydive,skydive-project/skydive
|
---
+++
@@ -23,4 +23,4 @@
break
if start != 0:
- print ''.join(changelog[start+1:end]).strip()
+ print(''.join(changelog[start+1:end]).strip())
|
543336f68dd96a9d19a6cc4598ddd99fd06ad026
|
warehouse/accounts/urls.py
|
warehouse/accounts/urls.py
|
# Copyright 2013 Donald Stufft
#
# 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 __future__ import absolute_import, division, print_function
from __future__ import unicode_literals
from werkzeug.routing import Rule, EndpointPrefix
urls = [
EndpointPrefix("warehouse.accounts.views.", [
Rule(
"/~<username>/",
methods=["GET"],
endpoint="user_profile",
),
]),
]
|
# Copyright 2013 Donald Stufft
#
# 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 __future__ import absolute_import, division, print_function
from __future__ import unicode_literals
from werkzeug.routing import Rule, EndpointPrefix
urls = [
EndpointPrefix("warehouse.accounts.views.", [
Rule(
"/user/<username>/",
methods=["GET"],
endpoint="user_profile",
),
]),
]
|
Move from /~username/ to /user/username/
|
Move from /~username/ to /user/username/
|
Python
|
apache-2.0
|
mattrobenolt/warehouse,mattrobenolt/warehouse,techtonik/warehouse,robhudson/warehouse,techtonik/warehouse,robhudson/warehouse,mattrobenolt/warehouse
|
---
+++
@@ -20,7 +20,7 @@
urls = [
EndpointPrefix("warehouse.accounts.views.", [
Rule(
- "/~<username>/",
+ "/user/<username>/",
methods=["GET"],
endpoint="user_profile",
),
|
911a7a2fb68f4dcc64e88b65b758e4a06b2d7dcb
|
cloud_maker/py_version.py
|
cloud_maker/py_version.py
|
# vim: fileencoding=utf-8
from __future__ import print_function, absolute_import, unicode_literals
import sys
class VersionError (ValueError):
pass
def check_ex ():
v = sys.version_info
if v.major == 3:
if v.minor < 3 or (v.minor == 3 and v.micro < 4):
raise VersionError("Error: this is Python 3.{}.{}, not 3.3.4+".format(v.minor, v.micro))
elif v.major == 2:
if v.minor < 7:
raise VersionError("Error: this is Python 2.{}, not 2.7".format(v.minor))
else:
raise VersionError("Error: this is Python {}, not 2.7 nor 3.x".format(v.major))
def check ():
try:
check_ex()
except VersionError as e:
print(e.args, file=sys.stderr)
print("Python 2.7 or 3.3+ is required.", file=sys.stderr)
sys.exit(2)
|
# vim: fileencoding=utf-8
from __future__ import print_function, absolute_import, unicode_literals
import sys
class VersionError (ValueError):
pass
def check_ex ():
v = sys.version_info
if v.major == 3:
if v.minor < 3 or (v.minor == 3 and v.micro < 4):
raise VersionError("Error: this is Python 3.{}.{}, not 3.3.4+".format(v.minor, v.micro))
elif v.major == 2:
if v.minor < 7:
raise VersionError("Error: this is Python 2.{}, not 2.7".format(v.minor))
else:
raise VersionError("Error: this is Python {}, not 2.7 nor 3.x".format(v.major))
def check ():
try:
check_ex()
except VersionError as e:
print(e.args[0], file=sys.stderr)
print("Python 2.7 or 3.3+ is required.", file=sys.stderr)
sys.exit(2)
|
Print only the message, not the whole tuple.
|
Print only the message, not the whole tuple.
|
Python
|
mit
|
sapphirecat/cloud-maker,sapphirecat/cloud-maker
|
---
+++
@@ -20,6 +20,6 @@
try:
check_ex()
except VersionError as e:
- print(e.args, file=sys.stderr)
+ print(e.args[0], file=sys.stderr)
print("Python 2.7 or 3.3+ is required.", file=sys.stderr)
sys.exit(2)
|
c8c68dfc05c4e661a147a32eccc27b3fd3e84174
|
tools/bootstrap_project.py
|
tools/bootstrap_project.py
|
# TODO: Implement!
|
# TODO: Implement!
'''
We want a folder structure something like this:
|-bin
|-conf
|-doc
| \-paper
|-experiments
| \-2000-01-01-example
| |-audit
| |-bin
| |-conf
| |-data
| |-doc
| |-lib
| |-log
| |-raw
| |-results
| |-run
| \-tmp
|-lib
|-raw
|-results
\-src
'''
|
Add comments in boostrap script
|
Add comments in boostrap script
|
Python
|
mit
|
pharmbio/sciluigi,samuell/sciluigi,pharmbio/sciluigi
|
---
+++
@@ -1 +1,27 @@
# TODO: Implement!
+
+'''
+We want a folder structure something like this:
+
+|-bin
+|-conf
+|-doc
+| \-paper
+|-experiments
+| \-2000-01-01-example
+| |-audit
+| |-bin
+| |-conf
+| |-data
+| |-doc
+| |-lib
+| |-log
+| |-raw
+| |-results
+| |-run
+| \-tmp
+|-lib
+|-raw
+|-results
+\-src
+'''
|
911ae13f760d221f5477cb5d518d4a9719386b81
|
demo/demo_esutils/mappings.py
|
demo/demo_esutils/mappings.py
|
# -*- coding: utf-8 -*-
from django.db.models.signals import post_save
from django.db.models.signals import post_delete
from django_esutils.mappings import SearchMappingType
from demo_esutils.models import Article
ARTICLE_MAPPING = {
# author
'author__username': {
'type': 'string',
},
'author__email': {
'type': 'string',
'index': 'not_analyzed'
},
# created
'created_at': {
'type': 'date',
},
# updated
'updated_at': {
'type': 'date',
},
# category
'category_id': {
'type': 'integer',
},
'category__name': {
'type': 'string',
},
# subject
'subject': {
'type': 'string',
},
# content
'content': {
'type': 'string',
},
# status
'status': {
'type': 'string',
},
}
class ArticleMappingType(SearchMappingType):
id_field = 'uuid'
@classmethod
def get_model(cls):
return Article
@classmethod
def get_field_mapping(cls):
return ARTICLE_MAPPING
post_save.connect(ArticleMappingType.es_index, sender=Article)
post_delete.connect(ArticleMappingType.es_unindex, sender=Article)
|
# -*- coding: utf-8 -*-
from django.db.models.signals import post_save
from django.db.models.signals import post_delete
from django_esutils.mappings import SearchMappingType
from django_esutils.models import post_update
from demo_esutils.models import Article
ARTICLE_MAPPING = {
# author
'author__username': {
'type': 'string',
},
'author__email': {
'type': 'string',
'index': 'not_analyzed'
},
# created
'created_at': {
'type': 'date',
},
# updated
'updated_at': {
'type': 'date',
},
# category
'category_id': {
'type': 'integer',
},
'category__name': {
'type': 'string',
},
# subject
'subject': {
'type': 'string',
},
# content
'content': {
'type': 'string',
},
# status
'status': {
'type': 'string',
},
}
class ArticleMappingType(SearchMappingType):
id_field = 'uuid'
@classmethod
def get_model(cls):
return Article
@classmethod
def get_field_mapping(cls):
return ARTICLE_MAPPING
post_save.connect(ArticleMappingType.on_post_save, sender=Article)
post_delete.connect(ArticleMappingType.on_post_delete, sender=Article)
post_update.connect(ArticleMappingType.on_post_update, sender=Article)
|
Update signals methods to call and connects Article to post_update signal.
|
Update signals methods to call and connects Article to post_update signal.
|
Python
|
mit
|
novafloss/django-esutils,novafloss/django-esutils
|
---
+++
@@ -3,6 +3,7 @@
from django.db.models.signals import post_delete
from django_esutils.mappings import SearchMappingType
+from django_esutils.models import post_update
from demo_esutils.models import Article
@@ -59,5 +60,6 @@
return ARTICLE_MAPPING
-post_save.connect(ArticleMappingType.es_index, sender=Article)
-post_delete.connect(ArticleMappingType.es_unindex, sender=Article)
+post_save.connect(ArticleMappingType.on_post_save, sender=Article)
+post_delete.connect(ArticleMappingType.on_post_delete, sender=Article)
+post_update.connect(ArticleMappingType.on_post_update, sender=Article)
|
b4578d34adaa641dab5082f9d2bffe14c69649c5
|
detour/__init__.py
|
detour/__init__.py
|
# -*- coding: utf-8 -*-
from __future__ import absolute_import
from __future__ import unicode_literals
__version_info__ = '0.1.0'
__version__ = '0.1.0'
version = '0.1.0'
VERSION = '0.1.0'
def get_version():
return version # pragma: no cover
|
# -*- coding: utf-8 -*-
from __future__ import absolute_import
from __future__ import unicode_literals
__version_info__ = '0.1.0'
__version__ = '0.1.0'
version = '0.1.0'
VERSION = '0.1.0'
def get_version():
return version # pragma: no cover
class DetourException(NotImplementedError):
pass
|
Add a root exception for use if necessary.
|
Add a root exception for use if necessary.
|
Python
|
bsd-2-clause
|
kezabelle/wsgi-detour
|
---
+++
@@ -9,3 +9,7 @@
def get_version():
return version # pragma: no cover
+
+
+class DetourException(NotImplementedError):
+ pass
|
a135e5a0919f64984b1348c3956bd95dc183e874
|
scripts/test_deployment.py
|
scripts/test_deployment.py
|
import os
import pytest
import requests
@pytest.fixture
def url():
return os.getenv("SITE", "http://localhost:5000")
def test_post_images(expect, url):
params = {"key": "iw", "lines": ["test", "deployment"]}
response = requests.post(f"{url}/api/images", json=params)
expect(response.status_code) == 201
expect(response.json()["url"]).endswith("/api/images/iw/test/deployment.png")
def test_get_image(expect, url):
response = requests.get(f"{url}/iw/tests_code/in_production.jpg")
expect(response.status_code) == 200
expect(response.headers["Content-Type"]) == "image/jpeg"
|
import os
import pytest
import requests
@pytest.fixture
def url():
return os.getenv("SITE", "http://localhost:5000")
def test_post_images(expect, url):
params = {"key": "iw", "lines": ["test", "deployment"]}
response = requests.post(f"{url}/api/images", json=params)
expect(response.status_code) == 201
expect(response.json()["url"]).endswith("/api/images/iw/test/deployment.png")
def test_get_image(expect, url):
response = requests.get(f"{url}/iw/tests_code/in_production.jpg")
expect(response.status_code) == 200
expect(response.headers["Content-Type"]) == "image/jpeg"
def test_get_image_custom(expect, url):
response = requests.get(
f"{url}/custom/test.png?alt=https://www.gstatic.com/webp/gallery/1.jpg"
)
expect(response.status_code) == 200
expect(response.headers["Content-Type"]) == "image/png"
|
Add test for custom images
|
Add test for custom images
|
Python
|
mit
|
jacebrowning/memegen,jacebrowning/memegen
|
---
+++
@@ -20,3 +20,11 @@
response = requests.get(f"{url}/iw/tests_code/in_production.jpg")
expect(response.status_code) == 200
expect(response.headers["Content-Type"]) == "image/jpeg"
+
+
+def test_get_image_custom(expect, url):
+ response = requests.get(
+ f"{url}/custom/test.png?alt=https://www.gstatic.com/webp/gallery/1.jpg"
+ )
+ expect(response.status_code) == 200
+ expect(response.headers["Content-Type"]) == "image/png"
|
ffb1dcff764b7494e0990f85f3af5f2354de0657
|
zou/app/models/serializer.py
|
zou/app/models/serializer.py
|
from sqlalchemy.inspection import inspect
from zou.app.utils.fields import serialize_value
class SerializerMixin(object):
def serialize(self):
attrs = inspect(self).attrs.keys()
return {
attr: serialize_value(getattr(self, attr)) for attr in attrs
}
@staticmethod
def serialize_list(models):
return [model.serialize() for model in models]
|
from sqlalchemy.inspection import inspect
from zou.app.utils.fields import serialize_value
class SerializerMixin(object):
def serialize(self, obj_type=None):
attrs = inspect(self).attrs.keys()
obj_dict = {
attr: serialize_value(getattr(self, attr)) for attr in attrs
}
obj_dict["type"] = obj_type or type(self).__name__
return obj_dict
@staticmethod
def serialize_list(models, obj_type=None):
return [model.serialize(obj_type=obj_type) for model in models]
|
Add object type to dict serialization
|
Add object type to dict serialization
|
Python
|
agpl-3.0
|
cgwire/zou
|
---
+++
@@ -4,12 +4,14 @@
class SerializerMixin(object):
- def serialize(self):
+ def serialize(self, obj_type=None):
attrs = inspect(self).attrs.keys()
- return {
+ obj_dict = {
attr: serialize_value(getattr(self, attr)) for attr in attrs
}
+ obj_dict["type"] = obj_type or type(self).__name__
+ return obj_dict
@staticmethod
- def serialize_list(models):
- return [model.serialize() for model in models]
+ def serialize_list(models, obj_type=None):
+ return [model.serialize(obj_type=obj_type) for model in models]
|
e4559636b7b95414fef10d40cce1c104712c432e
|
entrypoint.py
|
entrypoint.py
|
#!/usr/bin/python3
#
# Define containerized environment for running Diosix on Qemu
#
# On Google Cloud Run: Creates HTTP server on port 8080
# or whatever was specified using the PORT system variable.
# Outputs via the HTTP port. This requires K_SERVICE to be set.
#
# On all other environments: Log to stdout
#
# syntax: entrypoint.py <command>
#
# Author: Chris Williams <diodesign@tuta.io>
#
import os
import sys
global command_result
from flask import Flask
# for Google Cloud Run
@app.route('/')
def ContainerService():
return 'Container built. Use docker images and docker run in the Google Cloud shell to run this container.\n'
if __name__ == "__main__":
if (os.environ.get('K_SERVICE')) != '':
print('Running HTTP service for Google Cloud')
app = Flask(__name__)
app.run(debug=True,host='0.0.0.0',port=int(os.environ.get('PORT', 8080)))
else:
print('Running locally')
stream = os.popen('. $HOME/.cargo/env && cd /build/diosix && {}'.format(' '.join(sys.argv[1:])))
output = stream.read()
output
|
#!/usr/bin/python3
#
# Define containerized environment for running Diosix on Qemu
#
# On Google Cloud Run: Creates HTTP server on port 8080
# or whatever was specified using the PORT system variable.
# Outputs via the HTTP port. This requires K_SERVICE to be set.
#
# On all other environments: Log to stdout
#
# syntax: entrypoint.py <command>
#
# Author: Chris Williams <diodesign@tuta.io>
#
import os
import sys
global command_result
from flask import Flask
if __name__ == "__main__":
if (os.environ.get('K_SERVICE')) != '':
print('Running HTTP service for Google Cloud')
app = Flask(__name__)
@app.route('/')
def ContainerService():
return 'Container built. Use docker images and docker run in the Google Cloud shell to run this container.\n'
app.run(debug=True,host='0.0.0.0',port=int(os.environ.get('PORT', 8080)))
else:
print('Running locally')
stream = os.popen('. $HOME/.cargo/env && cd /build/diosix && {}'.format(' '.join(sys.argv[1:])))
output = stream.read()
output
|
Debug Google Cloud Run support
|
Debug Google Cloud Run support
|
Python
|
mit
|
diodesign/diosix
|
---
+++
@@ -20,15 +20,13 @@
from flask import Flask
-# for Google Cloud Run
-@app.route('/')
-def ContainerService():
- return 'Container built. Use docker images and docker run in the Google Cloud shell to run this container.\n'
-
if __name__ == "__main__":
if (os.environ.get('K_SERVICE')) != '':
print('Running HTTP service for Google Cloud')
app = Flask(__name__)
+ @app.route('/')
+ def ContainerService():
+ return 'Container built. Use docker images and docker run in the Google Cloud shell to run this container.\n'
app.run(debug=True,host='0.0.0.0',port=int(os.environ.get('PORT', 8080)))
else:
print('Running locally')
|
9ef3e6d884566b514be50dd468665cd65e939a9f
|
akhet/urlgenerator.py
|
akhet/urlgenerator.py
|
"""
Contributed by Michael Mericikel.
"""
from pyramid.decorator import reify
import pyramid.url as url
class URLGenerator(object):
def __init__(self, context, request):
self.context = context
self.request = request
@reify
def context(self):
return url.resource_url(self.context, self.request)
@reify
def app(self):
return self.request.application_url
def route(self, route_name, *elements, **kw):
return url.route_url(route_name, self.request, *elements, **kw)
# sugar for calling url('home')
__call__ = route
def current(self, *elements, **kw):
return url.current_route_url(self.request, *elements, **kw)
@reify
def static(self):
return url.static_url('baseline:static/', self.request)
@reify
def deform(self):
return url.static_url('deform:static/', self.request)
|
"""
Contributed by Michael Mericikel.
"""
from pyramid.decorator import reify
import pyramid.url as url
class URLGenerator(object):
def __init__(self, context, request):
self.context = context
self.request = request
@reify
def context(self):
return url.resource_url(self.context, self.request)
@reify
def app(self):
return self.request.application_url
def route(self, route_name, *elements, **kw):
return url.route_url(route_name, self.request, *elements, **kw)
# sugar for calling url('home')
__call__ = route
def current(self, *elements, **kw):
return url.current_route_url(self.request, *elements, **kw)
## Commented because I'm unsure of the long-term API.
## If you want to use this, or a more particular one for your
## static package(s), define it in a subclass.
##
# A future version might make 'path' optional, defaulting to
# a value passed to the constructor ("myapp:static/").
#
#def static(self, path, **kw):
# return url.static_url(path, self.request, **kw)
## If you're using the Deform package you may find this useful.
#
#@reify
#def deform(self):
# return url.static_url("deform:static/", self.request)
|
Comment out 'static' and 'deform' methods; disagreements on long-term API.
|
Comment out 'static' and 'deform' methods; disagreements on long-term API.
|
Python
|
mit
|
koansys/akhet,koansys/akhet
|
---
+++
@@ -27,10 +27,19 @@
def current(self, *elements, **kw):
return url.current_route_url(self.request, *elements, **kw)
- @reify
- def static(self):
- return url.static_url('baseline:static/', self.request)
+ ## Commented because I'm unsure of the long-term API.
+ ## If you want to use this, or a more particular one for your
+ ## static package(s), define it in a subclass.
+ ##
+ # A future version might make 'path' optional, defaulting to
+ # a value passed to the constructor ("myapp:static/").
+ #
+ #def static(self, path, **kw):
+ # return url.static_url(path, self.request, **kw)
+
- @reify
- def deform(self):
- return url.static_url('deform:static/', self.request)
+ ## If you're using the Deform package you may find this useful.
+ #
+ #@reify
+ #def deform(self):
+ # return url.static_url("deform:static/", self.request)
|
369f607df1efa7cd715a1d5ed4d86b972f44d23b
|
project/home/views.py
|
project/home/views.py
|
# imports
from flask import render_template, Blueprint
from project import db # pragma: no cover
from project.models import Person # pragma: no cover
# config
home_blueprint = Blueprint(
'home', __name__,
template_folder='templates'
) # pragma: no cover
# routes
# use decorators to link the function to a url
@home_blueprint.route('/', methods=['GET', 'POST']) # pragma: no cover
def home():
error = None
persons = db.session.query(Person).all()
return render_template(
'index.html', persons=persons, error=error)
|
# imports
from flask import render_template, Blueprint
from project import db # pragma: no cover
from project.models import Person # pragma: no cover
import random
# config
home_blueprint = Blueprint(
'home', __name__,
template_folder='templates'
) # pragma: no cover
MAX_GRID_SIZE_HOMEPAGE_PEOPLE = 6
# routes
# use decorators to link the function to a url
@home_blueprint.route('/', methods=['GET', 'POST']) # pragma: no cover
def home():
error = None
current_person_count = db.session.query(Person).count()
if current_person_count <= MAX_GRID_SIZE_HOMEPAGE_PEOPLE:
persons = db.session.query(Person).all()
else:
persons = []
while len(persons) < MAX_GRID_SIZE_HOMEPAGE_PEOPLE:
rand = random.randrange(0, current_person_count)
random_person = db.session.query(Person)[rand]
if random_person not in persons:
persons.append(random_person)
return render_template(
'index.html', persons=persons, error=error)
|
Select MAX people randomly, else all.
|
Select MAX people randomly, else all.
|
Python
|
isc
|
dhmncivichacks/timewebsite,mikeputnam/timewebsite,mikeputnam/timewebsite,dhmncivichacks/timewebsite,dhmncivichacks/timewebsite,mikeputnam/timewebsite
|
---
+++
@@ -5,12 +5,15 @@
from project import db # pragma: no cover
from project.models import Person # pragma: no cover
+import random
+
# config
home_blueprint = Blueprint(
'home', __name__,
template_folder='templates'
) # pragma: no cover
+MAX_GRID_SIZE_HOMEPAGE_PEOPLE = 6
# routes
@@ -18,6 +21,15 @@
@home_blueprint.route('/', methods=['GET', 'POST']) # pragma: no cover
def home():
error = None
- persons = db.session.query(Person).all()
+ current_person_count = db.session.query(Person).count()
+ if current_person_count <= MAX_GRID_SIZE_HOMEPAGE_PEOPLE:
+ persons = db.session.query(Person).all()
+ else:
+ persons = []
+ while len(persons) < MAX_GRID_SIZE_HOMEPAGE_PEOPLE:
+ rand = random.randrange(0, current_person_count)
+ random_person = db.session.query(Person)[rand]
+ if random_person not in persons:
+ persons.append(random_person)
return render_template(
'index.html', persons=persons, error=error)
|
42869823b4af024906606c5caf50e5dc5de69a57
|
api/mcapi/user/projects.py
|
api/mcapi/user/projects.py
|
from ..mcapp import app
from ..decorators import apikey, jsonp
from flask import g
import rethinkdb as r
#from .. import dmutil
from .. import args
from ..utils import error_response
@app.route('/v1.0/user/<user>/projects', methods=['GET'])
@apikey
@jsonp
def get_all_projects(user):
rr = r.table('projects').filter({'owner': user})
rr = args.add_all_arg_options(rr)
items = list(rr.run(g.conn, time_format='raw'))
return args.json_as_format_arg(items)
@app.route('/v1.0/user/<user>/project/<project_id>/datafiles')
@apikey
@jsonp
def get_all_datafiles_for_project(user, project_id):
project = r.table('projects').get(project_id).run(g.conn)
if project is None:
return error_response(400)
if project['owner'] != user:
return error_response(400)
return ""
|
from ..mcapp import app
from ..decorators import apikey, jsonp
from flask import g
import rethinkdb as r
#from .. import dmutil
from .. import args
from ..utils import error_response
@app.route('/v1.0/user/<user>/projects', methods=['GET'])
@apikey
@jsonp
def get_all_projects(user):
rr = r.table('projects').filter({'owner': user})
rr = args.add_all_arg_options(rr)
items = list(rr.run(g.conn, time_format='raw'))
return args.json_as_format_arg(items)
@app.route('/v1.0/user/<user>/projects/<project_id>/datafiles')
@apikey
@jsonp
def get_all_datafiles_for_project(user, project_id):
project = r.table('projects').get(project_id).run(g.conn)
if project is None:
return error_response(400)
if project['owner'] != user:
return error_response(400)
return ""
@app.route('/v1.0/user/<user>/projects/<project_id>/datadirs')
@apikey
@jsonp
def get_datadirs_for_project(user, project_id):
rr = r.table('project2datadir').filter({'project_id': project_id})
rr = rr.eq_join('project_id', r.table('projects')).zip()
rr = rr.eq_join('datadir_id', r.table('datadirs')).zip()
selection = list(rr.run(g.conn, time_format='raw'))
if len(selection) > 0 and selection[0]['owner'] == user:
return args.json_as_format_arg(selection)
return args.json_as_format_arg([])
|
Add call to get datadirs for a project.
|
Add call to get datadirs for a project.
|
Python
|
mit
|
materials-commons/materialscommons.org,materials-commons/materialscommons.org,materials-commons/materialscommons.org,materials-commons/materialscommons.org,materials-commons/materialscommons.org
|
---
+++
@@ -15,7 +15,7 @@
items = list(rr.run(g.conn, time_format='raw'))
return args.json_as_format_arg(items)
-@app.route('/v1.0/user/<user>/project/<project_id>/datafiles')
+@app.route('/v1.0/user/<user>/projects/<project_id>/datafiles')
@apikey
@jsonp
def get_all_datafiles_for_project(user, project_id):
@@ -25,3 +25,15 @@
if project['owner'] != user:
return error_response(400)
return ""
+
+@app.route('/v1.0/user/<user>/projects/<project_id>/datadirs')
+@apikey
+@jsonp
+def get_datadirs_for_project(user, project_id):
+ rr = r.table('project2datadir').filter({'project_id': project_id})
+ rr = rr.eq_join('project_id', r.table('projects')).zip()
+ rr = rr.eq_join('datadir_id', r.table('datadirs')).zip()
+ selection = list(rr.run(g.conn, time_format='raw'))
+ if len(selection) > 0 and selection[0]['owner'] == user:
+ return args.json_as_format_arg(selection)
+ return args.json_as_format_arg([])
|
3d6577432444c46f0b35bd4b39e0a05f39c37e7f
|
gittaggers.py
|
gittaggers.py
|
from setuptools.command.egg_info import egg_info
import subprocess
import time
class EggInfoFromGit(egg_info):
"""Tag the build with git commit timestamp.
If a build tag has already been set (e.g., "egg_info -b", building
from source package), leave it alone.
"""
def git_timestamp_tag(self):
gitinfo = subprocess.check_output(
['git', 'log', '--first-parent', '--max-count=1',
'--format=format:%ct', '.']).strip()
return time.strftime('.%Y%m%d%H%M%S', time.gmtime(int(gitinfo)))
def tags(self):
if self.tag_build is None:
self.tag_build = self.git_timestamp_tag()
return egg_info.tags(self)
|
from setuptools.command.egg_info import egg_info
import subprocess
import time
class EggInfoFromGit(egg_info):
"""Tag the build with git commit timestamp.
If a build tag has already been set (e.g., "egg_info -b", building
from source package), leave it alone.
"""
def git_timestamp_tag(self):
gitinfo = subprocess.check_output(
['git', 'log', '--first-parent', '--max-count=1',
'--format=format:%ct', '..']).strip()
return time.strftime('.%Y%m%d%H%M%S', time.gmtime(int(gitinfo)))
def tags(self):
if self.tag_build is None:
self.tag_build = self.git_timestamp_tag()
return egg_info.tags(self)
|
Fix Python packaging to use correct git log for package time/version stamps.
|
Fix Python packaging to use correct git log for package time/version stamps.
|
Python
|
apache-2.0
|
jeremiahsavage/cwltool,SciDAP/cwltool,chapmanb/cwltool,common-workflow-language/cwltool,dleehr/cwltool,jeremiahsavage/cwltool,chapmanb/cwltool,common-workflow-language/cwltool,dleehr/cwltool,jeremiahsavage/cwltool,common-workflow-language/cwltool,chapmanb/cwltool,SciDAP/cwltool,chapmanb/cwltool,SciDAP/cwltool,dleehr/cwltool,dleehr/cwltool,jeremiahsavage/cwltool,SciDAP/cwltool
|
---
+++
@@ -11,7 +11,7 @@
def git_timestamp_tag(self):
gitinfo = subprocess.check_output(
['git', 'log', '--first-parent', '--max-count=1',
- '--format=format:%ct', '.']).strip()
+ '--format=format:%ct', '..']).strip()
return time.strftime('.%Y%m%d%H%M%S', time.gmtime(int(gitinfo)))
def tags(self):
|
2c999f4a6bea1da70bf35f06283428ea0e196087
|
python/getmonotime.py
|
python/getmonotime.py
|
import getopt, sys
if __name__ == '__main__':
sippy_path = None
try:
opts, args = getopt.getopt(sys.argv[1:], 's:S:i:o:b')
except getopt.GetoptError:
usage()
for o, a in opts:
if o == '-S':
sippy_path = a.strip()
continue
if sippy_path != None:
sys.path.insert(0, sippy_path)
from sippy.Time.clock_dtime import clock_getdtime, CLOCK_MONOTONIC
print clock_getdtime(CLOCK_MONOTONIC)
|
import getopt, sys
if __name__ == '__main__':
sippy_path = None
try:
opts, args = getopt.getopt(sys.argv[1:], 'rS:')
except getopt.GetoptError:
usage()
out_realtime = False
for o, a in opts:
if o == '-S':
sippy_path = a.strip()
continue
if o == '-r':
out_realtime = True
if sippy_path != None:
sys.path.insert(0, sippy_path)
from sippy.Time.clock_dtime import clock_getdtime, CLOCK_MONOTONIC
if not out_realtime:
print(clock_getdtime(CLOCK_MONOTONIC))
else:
from sippy.Time.clock_dtime import CLOCK_REALTIME
print("%f %f" % (clock_getdtime(CLOCK_MONOTONIC), clock_getdtime(CLOCK_REALTIME)))
|
Add an option to also output realtime along with monotime.
|
Add an option to also output realtime along with monotime.
|
Python
|
bsd-2-clause
|
sippy/b2bua,sippy/b2bua
|
---
+++
@@ -4,18 +4,24 @@
sippy_path = None
try:
- opts, args = getopt.getopt(sys.argv[1:], 's:S:i:o:b')
+ opts, args = getopt.getopt(sys.argv[1:], 'rS:')
except getopt.GetoptError:
usage()
+ out_realtime = False
for o, a in opts:
if o == '-S':
sippy_path = a.strip()
continue
+ if o == '-r':
+ out_realtime = True
if sippy_path != None:
sys.path.insert(0, sippy_path)
from sippy.Time.clock_dtime import clock_getdtime, CLOCK_MONOTONIC
- print clock_getdtime(CLOCK_MONOTONIC)
-
+ if not out_realtime:
+ print(clock_getdtime(CLOCK_MONOTONIC))
+ else:
+ from sippy.Time.clock_dtime import CLOCK_REALTIME
+ print("%f %f" % (clock_getdtime(CLOCK_MONOTONIC), clock_getdtime(CLOCK_REALTIME)))
|
fa22d91e053f301498d9d09a950558758bf9b40f
|
patroni/exceptions.py
|
patroni/exceptions.py
|
class PatroniException(Exception):
pass
class DCSError(PatroniException):
"""Parent class for all kind of exceptions related to selected distributed configuration store"""
def __init__(self, value):
self.value = value
def __str__(self):
"""
>>> str(DCSError('foo'))
"'foo'"
"""
return repr(self.value)
|
class PatroniException(Exception):
"""Parent class for all kind of exceptions related to selected distributed configuration store"""
def __init__(self, value):
self.value = value
def __str__(self):
"""
>>> str(DCSError('foo'))
"'foo'"
"""
return repr(self.value)
class DCSError(PatroniException):
pass
|
Move some basic methods implementation into parent exception class
|
Move some basic methods implementation into parent exception class
|
Python
|
mit
|
sean-/patroni,pgexperts/patroni,zalando/patroni,sean-/patroni,jinty/patroni,jinty/patroni,zalando/patroni,pgexperts/patroni
|
---
+++
@@ -1,8 +1,4 @@
class PatroniException(Exception):
- pass
-
-
-class DCSError(PatroniException):
"""Parent class for all kind of exceptions related to selected distributed configuration store"""
@@ -15,3 +11,7 @@
"'foo'"
"""
return repr(self.value)
+
+
+class DCSError(PatroniException):
+ pass
|
f0ede3d2c32d4d3adce98cd3b762b672f7af91a9
|
relay_api/__main__.py
|
relay_api/__main__.py
|
from relay_api.api.server import server
from relay_api.core.relay import relay
from relay_api.conf.config import relays
import relay_api.api.server as api
for r in relays:
relays[r]["instance"] = relay(relays[r]["gpio"],
relays[r]["NC"])
@server.route("/relay-api/relays", methods=["GET"])
def get_relays():
return api.get_relays(relays)
@server.route("/relay-api/relays/<relay_name>", methods=["GET"])
def get_relay(relay_name):
return api.get_relay(relays, relay_name)
|
from relay_api.api.server import server
from relay_api.core.relay import relay
from relay_api.conf.config import relays
import relay_api.api.server as api
relays_dict = {}
for r in relays:
relays_dict[r] = relay(relays[r]["gpio"], relays[r]["NC"])
@server.route("/relay-api/relays", methods=["GET"])
def get_relays():
return api.get_relays(relays_dict)
@server.route("/relay-api/relays/<relay_name>", methods=["GET"])
def get_relay(relay_name):
return api.get_relay(relays_dict.get(relay_name, "None"))
|
Update to generate a dict with the relay instances
|
Update to generate a dict with the relay instances
|
Python
|
mit
|
pahumadad/raspi-relay-api
|
---
+++
@@ -4,16 +4,16 @@
import relay_api.api.server as api
+relays_dict = {}
for r in relays:
- relays[r]["instance"] = relay(relays[r]["gpio"],
- relays[r]["NC"])
+ relays_dict[r] = relay(relays[r]["gpio"], relays[r]["NC"])
@server.route("/relay-api/relays", methods=["GET"])
def get_relays():
- return api.get_relays(relays)
+ return api.get_relays(relays_dict)
@server.route("/relay-api/relays/<relay_name>", methods=["GET"])
def get_relay(relay_name):
- return api.get_relay(relays, relay_name)
+ return api.get_relay(relays_dict.get(relay_name, "None"))
|
90a6d5be4e328a4ee9a2c05c40188d639e191be5
|
wsgi.py
|
wsgi.py
|
#!/usr/bin/python
import os
if os.environ.get('OPENSHIFT_PYTHON_DIR'): # on Openshift
virtenv = os.environ.get('OPENSHIFT_PYTHON_DIR') + '/virtenv/'
virtualenv = os.path.join(virtenv, 'bin/activate_this.py')
try:
execfile(virtualenv, dict(__file__=virtualenv))
except IOError:
pass
#
# IMPORTANT: Put any additional includes below this line. If placed above this
# line, it's possible required libraries won't be in your searchable path
#
from rtrss.webapp import app as application
#
# Below for testing only
#
if __name__ == '__main__':
application.run('0.0.0.0', 8080, debug=True)
|
#!/usr/bin/python
import os
from rtrss import config
if os.environ.get('OPENSHIFT_PYTHON_DIR'): # on Openshift
virtenv = os.environ.get('OPENSHIFT_PYTHON_DIR') + '/virtenv/'
virtualenv = os.path.join(virtenv, 'bin/activate_this.py')
try:
execfile(virtualenv, dict(__file__=virtualenv))
except IOError:
pass
#
# IMPORTANT: Put any additional includes below this line. If placed above this
# line, it's possible required libraries won't be in your searchable path
#
from rtrss.webapp import app as application
#
# Below for testing only
#
if __name__ == '__main__':
application.run(config.IP, config.PORT, debug=True)
|
Read IP and PORT from configuration
|
Read IP and PORT from configuration
|
Python
|
apache-2.0
|
notapresent/rtrss,notapresent/rtrss,notapresent/rtrss,notapresent/rtrss
|
---
+++
@@ -1,5 +1,7 @@
#!/usr/bin/python
import os
+from rtrss import config
+
if os.environ.get('OPENSHIFT_PYTHON_DIR'): # on Openshift
virtenv = os.environ.get('OPENSHIFT_PYTHON_DIR') + '/virtenv/'
@@ -19,4 +21,4 @@
# Below for testing only
#
if __name__ == '__main__':
- application.run('0.0.0.0', 8080, debug=True)
+ application.run(config.IP, config.PORT, debug=True)
|
200c6bd9f5cbee49c52b1598cac42dd6a4e0b273
|
helpers/s3.py
|
helpers/s3.py
|
import threading
import boto3
import objects.glob
from common.log import logUtils as log
def getClient():
return objects.glob.s3Connections[threading.get_ident()]
def getWriteReplayBucketName():
return objects.glob.db.fetch("SELECT `name` FROM s3_replay_buckets WHERE max_score_id IS NULL LIMIT 1")["name"]
def getReadReplayBucketName(scoreID):
r = objects.glob.db.fetch(
"SELECT `name`, max_score_id FROM s3_replay_buckets WHERE max_score_id IS NOT NULL "
"ORDER BY abs(max_score_id - %s) LIMIT 1",
(scoreID,)
)
if r is not None and scoreID <= r["max_score_id"]:
log.debug("s3 replay buckets resolve: {} -> {}".format(scoreID, r["name"]))
return r["name"]
log.debug("s3 replay buckets resolve: {} -> WRITE BUCKET".format(scoreID))
return getWriteReplayBucketName()
def clientFactory():
log.info("Created a new S3 client for thread {}".format(threading.get_ident()))
return boto3.Session(region_name=objects.glob.conf["S3_REGION"]).client(
"s3",
endpoint_url=objects.glob.conf["S3_ENDPOINT_URL"],
aws_access_key_id=objects.glob.conf["S3_ACCESS_KEY_ID"],
aws_secret_access_key=objects.glob.conf["S3_SECRET_ACCESS_KEY"]
)
|
import threading
import boto3
import objects.glob
from common.log import logUtils as log
def getClient():
return objects.glob.s3Connections[threading.get_ident()]
def getWriteReplayBucketName():
r = objects.glob.db.fetch("SELECT `name` FROM s3_replay_buckets WHERE max_score_id IS NULL LIMIT 1")
if r is None:
raise RuntimeError("No write replays S3 write bucket!")
return r["name"]
def getReadReplayBucketName(scoreID):
r = objects.glob.db.fetch(
"SELECT `name`, max_score_id FROM s3_replay_buckets WHERE max_score_id IS NOT NULL "
"ORDER BY abs(max_score_id - %s) LIMIT 1",
(scoreID,)
)
if r is not None and scoreID <= r["max_score_id"]:
log.debug("s3 replay buckets resolve: {} -> {}".format(scoreID, r["name"]))
return r["name"]
log.debug("s3 replay buckets resolve: {} -> WRITE BUCKET".format(scoreID))
return getWriteReplayBucketName()
def clientFactory():
log.info("Created a new S3 client for thread {}".format(threading.get_ident()))
return boto3.Session(region_name=objects.glob.conf["S3_REGION"]).client(
"s3",
endpoint_url=objects.glob.conf["S3_ENDPOINT_URL"],
aws_access_key_id=objects.glob.conf["S3_ACCESS_KEY_ID"],
aws_secret_access_key=objects.glob.conf["S3_SECRET_ACCESS_KEY"]
)
|
Add write bucket exists check also when getting its name
|
Add write bucket exists check also when getting its name
|
Python
|
agpl-3.0
|
osuripple/lets,osuripple/lets
|
---
+++
@@ -11,7 +11,10 @@
def getWriteReplayBucketName():
- return objects.glob.db.fetch("SELECT `name` FROM s3_replay_buckets WHERE max_score_id IS NULL LIMIT 1")["name"]
+ r = objects.glob.db.fetch("SELECT `name` FROM s3_replay_buckets WHERE max_score_id IS NULL LIMIT 1")
+ if r is None:
+ raise RuntimeError("No write replays S3 write bucket!")
+ return r["name"]
def getReadReplayBucketName(scoreID):
|
f0ed93d51980856daa1d7bff8bf76909fabe5b65
|
urls.py
|
urls.py
|
from django.conf.urls.defaults import *
from django.contrib import admin
from django.conf import settings
admin.autodiscover()
urlpatterns = patterns('',
(r'^admin/(.*)', admin.site.root),
(r'^', include('blangoblog.blango.urls')),
)
handler500 = 'blango.views.server_error'
handler404 = 'blango.views.page_not_found'
if settings.DEBUG:
urlpatterns += patterns('',
(r'^site-media/(?P<path>.*)$', 'django.views.static.serve', {'document_root': '/home/fiam/blog/media/'}),
)
|
from django.conf.urls.defaults import *
from django.contrib import admin
from django.conf import settings
admin.autodiscover()
urlpatterns = patterns('',
(r'^admin/(.*)', admin.site.root),
(r'^', include('blangoblog.blango.urls')),
)
handler500 = 'blango.views.server_error'
handler404 = 'blango.views.page_not_found'
if settings.DEBUG:
from os.path import abspath, dirname, join
PROJECT_DIR = dirname(abspath(__file__))
urlpatterns += patterns('',
(r'^site-media/(?P<path>.*)$', 'django.views.static.serve', {'document_root': join(PROJECT_DIR, 'media')}),
)
|
Use a relative path for serving static files in development
|
Use a relative path for serving static files in development
|
Python
|
bsd-3-clause
|
fiam/blangoblog,fiam/blangoblog,fiam/blangoblog
|
---
+++
@@ -12,6 +12,8 @@
handler404 = 'blango.views.page_not_found'
if settings.DEBUG:
+ from os.path import abspath, dirname, join
+ PROJECT_DIR = dirname(abspath(__file__))
urlpatterns += patterns('',
- (r'^site-media/(?P<path>.*)$', 'django.views.static.serve', {'document_root': '/home/fiam/blog/media/'}),
+ (r'^site-media/(?P<path>.*)$', 'django.views.static.serve', {'document_root': join(PROJECT_DIR, 'media')}),
)
|
a406334f0fcc26f235141e1d453c4aa5b632fdaf
|
nbconvert/utils/exceptions.py
|
nbconvert/utils/exceptions.py
|
"""Contains all of the exceptions used in NBConvert explicitly"""
#-----------------------------------------------------------------------------
# Copyright (c) 2013, the IPython Development Team.
#
# Distributed under the terms of the Modified BSD License.
#
# The full license is in the file COPYING.txt, distributed with this software.
#-----------------------------------------------------------------------------
#-----------------------------------------------------------------------------
# Imports
#-----------------------------------------------------------------------------
from __future__ import print_function
#-----------------------------------------------------------------------------
# Classes and functions
#-----------------------------------------------------------------------------
class ConversionException(Exception):
"""An exception raised by the conversion process."""
pass
|
"""NbConvert specific exceptions"""
#-----------------------------------------------------------------------------
# Copyright (c) 2013, the IPython Development Team.
#
# Distributed under the terms of the Modified BSD License.
#
# The full license is in the file COPYING.txt, distributed with this software.
#-----------------------------------------------------------------------------
#-----------------------------------------------------------------------------
# Classes and functions
#-----------------------------------------------------------------------------
class ConversionException(Exception):
"""An exception raised by the conversion process."""
pass
|
Comment & Refactor, utils and nbconvert main.
|
Comment & Refactor, utils and nbconvert main.
|
Python
|
bsd-3-clause
|
jupyter-widgets/ipywidgets,cornhundred/ipywidgets,cornhundred/ipywidgets,SylvainCorlay/ipywidgets,ipython/ipywidgets,cornhundred/ipywidgets,SylvainCorlay/ipywidgets,SylvainCorlay/ipywidgets,jupyter-widgets/ipywidgets,ipython/ipywidgets,SylvainCorlay/ipywidgets,ipython/ipywidgets,cornhundred/ipywidgets,cornhundred/ipywidgets,ipython/ipywidgets,jupyter-widgets/ipywidgets,ipython/ipywidgets,jupyter-widgets/ipywidgets
|
---
+++
@@ -1,4 +1,4 @@
-"""Contains all of the exceptions used in NBConvert explicitly"""
+"""NbConvert specific exceptions"""
#-----------------------------------------------------------------------------
# Copyright (c) 2013, the IPython Development Team.
#
@@ -8,13 +8,9 @@
#-----------------------------------------------------------------------------
#-----------------------------------------------------------------------------
-# Imports
-#-----------------------------------------------------------------------------
-from __future__ import print_function
-
-#-----------------------------------------------------------------------------
# Classes and functions
#-----------------------------------------------------------------------------
+
class ConversionException(Exception):
"""An exception raised by the conversion process."""
|
bc0193a3a32521512b77e6149e91eab805836f8d
|
django_dbq/management/commands/queue_depth.py
|
django_dbq/management/commands/queue_depth.py
|
from django.core.management.base import BaseCommand
from django_dbq.models import Job
class Command(BaseCommand):
help = "Print the current depth of the given queue"
def add_arguments(self, parser):
parser.add_argument("queue_name", nargs="*", default=["default"], type=str)
def handle(self, *args, **options):
queue_names = options["queue_name"]
queue_depths = Job.get_queue_depths()
self.stdout.write(
" ".join(
[
f"{queue_name}={queue_depths.get(queue_name, 0)}"
for queue_name in queue_names
]
)
)
|
from django.core.management.base import BaseCommand
from django_dbq.models import Job
class Command(BaseCommand):
help = "Print the current depth of the given queue"
def add_arguments(self, parser):
parser.add_argument("queue_name", nargs="*", default=["default"], type=str)
def handle(self, *args, **options):
queue_names = options["queue_name"]
queue_depths = Job.get_queue_depths()
self.stdout.write(
" ".join(
[
"{queue_name}={queue_depth}".format(
queue_name=queue_name,
queue_depth=queue_depths.get(queue_name, 0)
)
for queue_name in queue_names
]
)
)
|
Convert f-string to .format call
|
Convert f-string to .format call
|
Python
|
bsd-2-clause
|
dabapps/django-db-queue
|
---
+++
@@ -16,7 +16,10 @@
self.stdout.write(
" ".join(
[
- f"{queue_name}={queue_depths.get(queue_name, 0)}"
+ "{queue_name}={queue_depth}".format(
+ queue_name=queue_name,
+ queue_depth=queue_depths.get(queue_name, 0)
+ )
for queue_name in queue_names
]
)
|
b493073ec6978b6291cc66491bb3406179013d3d
|
create_variants_databases.py
|
create_variants_databases.py
|
#!/usr/bin/env python
import argparse
import getpass
from cassandra import query
from cassandra.cqlengine.management import sync_table
from cassandra.cqlengine.management import create_keyspace_simple
from cassandra.cluster import Cluster
from cassandra.cqlengine import connection
from cassandra.auth import PlainTextAuthProvider
from variantstore import Variant
from variantstore import SampleVariant
if __name__ == "__main__":
parser = argparse.ArgumentParser()
parser.add_argument('-a', '--address', help="IP Address for Cassandra connection", default='127.0.0.1')
parser.add_argument('-u', '--username', help='Cassandra username for login', default=None)
parser.add_argument('-r', '--replication_factor', help="Cassandra replication factor", default=3)
args = parser.parse_args()
if args.username:
password = getpass.getpass()
auth_provider = PlainTextAuthProvider(username=args.username, password=password)
cluster = Cluster([args.address], auth_provider=auth_provider)
session = cluster.connect()
session.row_factory = query.dict_factory
else:
cluster = Cluster([args.address])
session = cluster.connect()
session.row_factory = query.dict_factory
connection.set_session(session)
create_keyspace_simple("variantstore", args.replication_factor)
sync_table(Variant)
sync_table(SampleVariant)
|
#!/usr/bin/env python
import argparse
import getpass
from cassandra import query
from cassandra.cqlengine.management import sync_table
from cassandra.cqlengine.management import create_keyspace_simple
from cassandra.cluster import Cluster
from cassandra.cqlengine import connection
from cassandra.auth import PlainTextAuthProvider
from variantstore import Variant
from variantstore import SampleVariant
from variantstore import TargetVariant
if __name__ == "__main__":
parser = argparse.ArgumentParser()
parser.add_argument('-a', '--address', help="IP Address for Cassandra connection", default='127.0.0.1')
parser.add_argument('-u', '--username', help='Cassandra username for login', default=None)
parser.add_argument('-r', '--replication_factor', help="Cassandra replication factor", default=3)
args = parser.parse_args()
if args.username:
password = getpass.getpass()
auth_provider = PlainTextAuthProvider(username=args.username, password=password)
cluster = Cluster([args.address], auth_provider=auth_provider)
session = cluster.connect()
session.row_factory = query.dict_factory
else:
cluster = Cluster([args.address])
session = cluster.connect()
session.row_factory = query.dict_factory
connection.set_session(session)
create_keyspace_simple("variantstore", args.replication_factor)
sync_table(Variant)
sync_table(SampleVariant)
sync_table(TargetVariant)
|
Add additional table to cassandra variant store
|
Add additional table to cassandra variant store
|
Python
|
mit
|
dgaston/ddb-datastore,dgaston/ddb-variantstore,dgaston/ddbio-variantstore,GastonLab/ddb-datastore
|
---
+++
@@ -10,6 +10,7 @@
from cassandra.auth import PlainTextAuthProvider
from variantstore import Variant
from variantstore import SampleVariant
+from variantstore import TargetVariant
if __name__ == "__main__":
parser = argparse.ArgumentParser()
@@ -34,3 +35,4 @@
sync_table(Variant)
sync_table(SampleVariant)
+ sync_table(TargetVariant)
|
0a7fa2d65f2d563fbf36a2b39636dd8068cd4934
|
PyInstallerUtils.py
|
PyInstallerUtils.py
|
import os
import sys
def pyInstallerResourcePath(relativePath):
basePath = getattr(sys, '_MEIPASS', os.path.abspath('./src'))
return os.path.join(basePath, relativePath)
|
import os
import sys
def pyInstallerResourcePath(relativePath):
basePath = getattr(sys, '_MEIPASS', os.path.abspath('.'))
return os.path.join(basePath, relativePath)
|
Fix default file path location
|
Fix default file path location
|
Python
|
mit
|
JustinShenk/sensei
|
---
+++
@@ -3,5 +3,5 @@
def pyInstallerResourcePath(relativePath):
- basePath = getattr(sys, '_MEIPASS', os.path.abspath('./src'))
+ basePath = getattr(sys, '_MEIPASS', os.path.abspath('.'))
return os.path.join(basePath, relativePath)
|
d46d896b63ac24759a21c49e30ff9b3dc5c81595
|
TS/Utils.py
|
TS/Utils.py
|
# Copyright (C) 2016 Antoine Carme <Antoine.Carme@Laposte.net>
# All rights reserved.
# This file is part of the Python Automatic Forecasting (PyAF) library and is made available under
# the terms of the 3 Clause BSD license
import sys, os
def createDirIfNeeded(dirname):
try:
os.mkdir(dirname);
except:
pass
class ForecastError(Exception):
"""Exception raised for errors in the forecasting process.
Attributes:
mReason : explanation of the error
"""
def __init__(self, reason):
self.mReason = reason
class InternalForecastError(Exception):
"""Exception raised for errors in the forecasting process.
Attributes:
mReason : explanation of the error
"""
def __init__(self, reason):
self.mReason = reason
def get_pyaf_logger():
import logging;
logger = logging.getLogger('pyaf.std');
return logger;
def get_pyaf_hierarchical_logger():
import logging;
logger = logging.getLogger('pyaf.hierarchical');
return logger;
|
# Copyright (C) 2016 Antoine Carme <Antoine.Carme@Laposte.net>
# All rights reserved.
# This file is part of the Python Automatic Forecasting (PyAF) library and is made available under
# the terms of the 3 Clause BSD license
import sys, os
def createDirIfNeeded(dirname):
try:
os.mkdir(dirname);
except:
pass
class ForecastError(Exception):
"""Exception raised for errors in the forecasting process.
Attributes:
mReason : explanation of the error
"""
def __init__(self, reason):
self.mReason = reason
class InternalForecastError(Exception):
"""Exception raised for errors in the forecasting process.
Attributes:
mReason : explanation of the error
"""
def __init__(self, reason):
self.mReason = reason
def get_pyaf_logger():
import logging;
logger = logging.getLogger('pyaf.std');
if(logger.handlers == []):
import logging.config
logging.basicConfig(level=logging.INFO)
return logger;
def get_pyaf_hierarchical_logger():
import logging;
logger = logging.getLogger('pyaf.hierarchical');
return logger;
|
Enable default logging (not sure if this is OK)
|
Enable default logging (not sure if this is OK)
|
Python
|
bsd-3-clause
|
antoinecarme/pyaf,antoinecarme/pyaf,antoinecarme/pyaf
|
---
+++
@@ -39,6 +39,9 @@
def get_pyaf_logger():
import logging;
logger = logging.getLogger('pyaf.std');
+ if(logger.handlers == []):
+ import logging.config
+ logging.basicConfig(level=logging.INFO)
return logger;
def get_pyaf_hierarchical_logger():
|
b9f5954b7760a326073cfec198e4247dac386f0d
|
demoapp/cliffdemo/main.py
|
demoapp/cliffdemo/main.py
|
import logging
import sys
from cliff.app import App
from cliff.commandmanager import CommandManager
class DemoApp(App):
log = logging.getLogger(__name__)
def __init__(self):
super(DemoApp, self).__init__(
description='cliff demo app',
version='0.1',
command_manager=CommandManager('cliff.demo'),
)
def initialize_app(self, argv):
self.log.debug('initialize_app')
def prepare_to_run_command(self, cmd):
self.log.debug('prepare_to_run_command %s', cmd.__class__.__name__)
def clean_up(self, cmd, result, err):
self.log.debug('clean_up %s', cmd.__class__.__name__)
if err:
self.log.debug('got an error: %s', err)
def main(argv=sys.argv[1:]):
myapp = DemoApp()
return myapp.run(argv)
if __name__ == '__main__':
sys.exit(main(sys.argv[1:]))
|
import sys
from cliff.app import App
from cliff.commandmanager import CommandManager
class DemoApp(App):
def __init__(self):
super(DemoApp, self).__init__(
description='cliff demo app',
version='0.1',
command_manager=CommandManager('cliff.demo'),
)
def initialize_app(self, argv):
self.LOG.debug('initialize_app')
def prepare_to_run_command(self, cmd):
self.LOG.debug('prepare_to_run_command %s', cmd.__class__.__name__)
def clean_up(self, cmd, result, err):
self.LOG.debug('clean_up %s', cmd.__class__.__name__)
if err:
self.LOG.debug('got an error: %s', err)
def main(argv=sys.argv[1:]):
myapp = DemoApp()
return myapp.run(argv)
if __name__ == '__main__':
sys.exit(main(sys.argv[1:]))
|
Fix logging config in demo app
|
Fix logging config in demo app
The demo application was creating a new logger instance instead of using
the one built into the base class.
Change-Id: I980b180132cf20f7d2420e8f61e341760674aac0
|
Python
|
apache-2.0
|
openstack/cliff,enzochiau/cliff,idjaw/cliff,idjaw/cliff,openstack/cliff,enzochiau/cliff,dtroyer/cliff,dtroyer/cliff
|
---
+++
@@ -1,4 +1,3 @@
-import logging
import sys
from cliff.app import App
@@ -6,8 +5,6 @@
class DemoApp(App):
-
- log = logging.getLogger(__name__)
def __init__(self):
super(DemoApp, self).__init__(
@@ -17,15 +14,15 @@
)
def initialize_app(self, argv):
- self.log.debug('initialize_app')
+ self.LOG.debug('initialize_app')
def prepare_to_run_command(self, cmd):
- self.log.debug('prepare_to_run_command %s', cmd.__class__.__name__)
+ self.LOG.debug('prepare_to_run_command %s', cmd.__class__.__name__)
def clean_up(self, cmd, result, err):
- self.log.debug('clean_up %s', cmd.__class__.__name__)
+ self.LOG.debug('clean_up %s', cmd.__class__.__name__)
if err:
- self.log.debug('got an error: %s', err)
+ self.LOG.debug('got an error: %s', err)
def main(argv=sys.argv[1:]):
|
35374e354bc34f01b47d8813ceea3fce2d175acf
|
rvusite/rvu/models.py
|
rvusite/rvu/models.py
|
from __future__ import unicode_literals
from django.db import models
from django.utils import timezone
from django.conf import settings
from django.core.urlresolvers import reverse
class BillingCode(models.Model):
nr_rvus = models.FloatField()
creation_date = models.DateTimeField('date created', default=timezone.now)
ordering = models.IntegerField(blank=True, null=True)
code_name = models.CharField(max_length=200)
def __str__(self):
return "%s (%0.2f)" % (self.code_name, self.nr_rvus)
class Meta:
ordering = ('-ordering', 'code_name',)
class Provider(models.Model):
user = models.ForeignKey(settings.AUTH_USER_MODEL)
annual_rvu_goal = models.FloatField(default=0)
def __str__(self):
return "%s %s (%s)" % (self.user.first_name,
self.user.last_name,
self.user.email)
class Meta:
ordering = ('user',)
class PatientVisit(models.Model):
provider = models.ForeignKey(Provider, on_delete=models.CASCADE)
visit_date = models.DateTimeField('visit date')
code_billed = models.ForeignKey(BillingCode)
class Meta:
ordering = ('visit_date',)
def get_absolute_url(self):
return reverse('patient-visit-detail', kwargs={'pk': self.pk})
def __str__(self):
return "%s:%s:%s" % (self.visit_date, self.provider, self.code_billed)
|
from __future__ import unicode_literals
from django.db import models
from django.utils import timezone
from django.conf import settings
from django.core.urlresolvers import reverse
class BillingCode(models.Model):
nr_rvus = models.FloatField()
creation_date = models.DateTimeField('date created', default=timezone.now)
ordering = models.IntegerField(blank=True, null=True)
code_name = models.CharField(max_length=200)
def __str__(self):
return "%s (%0.2f)" % (self.code_name, self.nr_rvus)
class Meta:
ordering = ('-ordering', 'code_name',)
class Provider(models.Model):
user = models.ForeignKey(settings.AUTH_USER_MODEL)
annual_rvu_goal = models.FloatField(default=0)
def __str__(self):
return "%s %s (%s)" % (self.user.first_name,
self.user.last_name,
self.user.email)
class Meta:
ordering = ('user',)
class PatientVisit(models.Model):
provider = models.ForeignKey(Provider, on_delete=models.CASCADE)
visit_date = models.DateTimeField('visit date')
code_billed = models.ForeignKey(BillingCode)
class Meta:
ordering = ('-visit_date',)
def get_absolute_url(self):
return reverse('patient-visit-detail', kwargs={'pk': self.pk})
def __str__(self):
return "%s:%s:%s" % (self.visit_date, self.provider, self.code_billed)
|
Change patient visit table ordering to be latest to oldest
|
Change patient visit table ordering to be latest to oldest
|
Python
|
apache-2.0
|
craighagan/rvumanager,craighagan/rvumanager,craighagan/rvumanager,craighagan/rvumanager
|
---
+++
@@ -37,7 +37,7 @@
code_billed = models.ForeignKey(BillingCode)
class Meta:
- ordering = ('visit_date',)
+ ordering = ('-visit_date',)
def get_absolute_url(self):
return reverse('patient-visit-detail', kwargs={'pk': self.pk})
|
4407fcb950f42d080ca7e6477cddd507c87e4619
|
tests/unit/cloudsearch/test_exceptions.py
|
tests/unit/cloudsearch/test_exceptions.py
|
import mock
from boto.compat import json
from tests.unit import unittest
from .test_search import HOSTNAME, CloudSearchSearchBaseTest
from boto.cloudsearch.search import SearchConnection, SearchServiceException
def fake_loads_value_error(content, *args, **kwargs):
"""Callable to generate a fake ValueError"""
raise ValueError("HAHAHA! Totally not simplejson & you gave me bad JSON.")
def fake_loads_json_error(content, *args, **kwargs):
"""Callable to generate a fake JSONDecodeError"""
raise json.JSONDecodeError('Using simplejson & you gave me bad JSON.',
'', 0)
class CloudSearchJSONExceptionTest(CloudSearchSearchBaseTest):
response = '{}'
def test_no_simplejson_value_error(self):
with mock.patch.object(json, 'loads', fake_loads_value_error):
search = SearchConnection(endpoint=HOSTNAME)
try:
search.search(q='test')
self.fail('This should never run!')
except SearchServiceException, err:
self.assertTrue('non-json' in str(err))
@unittest.skipUnless(hasattr(json, 'JSONDecodeError'),
'requires simplejson')
def test_simplejson_jsondecodeerror(self):
with mock.patch.object(json, 'loads', fake_loads_json_error):
search = SearchConnection(endpoint=HOSTNAME)
try:
search.search(q='test')
self.fail('This should never run!')
except SearchServiceException, err:
self.assertTrue('non-json' in str(err))
|
import mock
from boto.compat import json
from tests.unit import unittest
from .test_search import HOSTNAME, CloudSearchSearchBaseTest
from boto.cloudsearch.search import SearchConnection, SearchServiceException
def fake_loads_value_error(content, *args, **kwargs):
"""Callable to generate a fake ValueError"""
raise ValueError("HAHAHA! Totally not simplejson & you gave me bad JSON.")
def fake_loads_json_error(content, *args, **kwargs):
"""Callable to generate a fake JSONDecodeError"""
raise json.JSONDecodeError('Using simplejson & you gave me bad JSON.',
'', 0)
class CloudSearchJSONExceptionTest(CloudSearchSearchBaseTest):
response = '{}'
def test_no_simplejson_value_error(self):
with mock.patch.object(json, 'loads', fake_loads_value_error):
search = SearchConnection(endpoint=HOSTNAME)
with self.assertRaisesRegexp(SearchServiceException, 'non-json'):
search.search(q='test')
@unittest.skipUnless(hasattr(json, 'JSONDecodeError'),
'requires simplejson')
def test_simplejson_jsondecodeerror(self):
with mock.patch.object(json, 'loads', fake_loads_json_error):
search = SearchConnection(endpoint=HOSTNAME)
with self.assertRaisesRegexp(SearchServiceException, 'non-json'):
search.search(q='test')
|
Use assertRaises instead of try/except blocks for unit tests
|
Use assertRaises instead of try/except blocks for unit tests
|
Python
|
mit
|
ekalosak/boto,kouk/boto,revmischa/boto,Asana/boto,TiVoMaker/boto,rjschwei/boto,tpodowd/boto,Timus1712/boto,drbild/boto,awatts/boto,yangchaogit/boto,campenberger/boto,podhmo/boto,israelbenatar/boto,alex/boto,khagler/boto,abridgett/boto,FATruden/boto,janslow/boto,appneta/boto,j-carl/boto,clouddocx/boto,jindongh/boto,bryx-inc/boto,zzzirk/boto,shaunbrady/boto,disruptek/boto,shipci/boto,disruptek/boto,kouk/boto,felix-d/boto,weebygames/boto,ddzialak/boto,garnaat/boto,cyclecomputing/boto,ryansb/boto,dablak/boto,pfhayes/boto,rjschwei/boto,lra/boto,vijaylbais/boto,weka-io/boto,stevenbrichards/boto,nexusz99/boto,nishigori/boto,dimdung/boto,acourtney2015/boto,Pretio/boto,drbild/boto,varunarya10/boto,nikhilraog/boto,zachmullen/boto,elainexmas/boto,alex/boto,appneta/boto,jotes/boto,dablak/boto,darjus-amzn/boto,ric03uec/boto,rayluo/boto,alfredodeza/boto,serviceagility/boto,s0enke/boto,bleib1dj/boto,rosmo/boto,ramitsurana/boto,vishnugonela/boto,trademob/boto,SaranyaKarthikeyan/boto,ocadotechnology/boto,tpodowd/boto
|
---
+++
@@ -24,11 +24,8 @@
with mock.patch.object(json, 'loads', fake_loads_value_error):
search = SearchConnection(endpoint=HOSTNAME)
- try:
+ with self.assertRaisesRegexp(SearchServiceException, 'non-json'):
search.search(q='test')
- self.fail('This should never run!')
- except SearchServiceException, err:
- self.assertTrue('non-json' in str(err))
@unittest.skipUnless(hasattr(json, 'JSONDecodeError'),
'requires simplejson')
@@ -36,8 +33,5 @@
with mock.patch.object(json, 'loads', fake_loads_json_error):
search = SearchConnection(endpoint=HOSTNAME)
- try:
+ with self.assertRaisesRegexp(SearchServiceException, 'non-json'):
search.search(q='test')
- self.fail('This should never run!')
- except SearchServiceException, err:
- self.assertTrue('non-json' in str(err))
|
705c2bb724b61f9b07f6ed1ce2191ea0e998ecc4
|
tests/api_types/sendable/test_input_media.py
|
tests/api_types/sendable/test_input_media.py
|
from pytgbot.api_types.sendable.files import InputFileFromURL
from pytgbot.api_types.sendable.input_media import InputMediaVideo
import unittest
class MyTestCase(unittest.TestCase):
def test_InputMediaVideo_thumb_files(self):
vid1 = 'https://derpicdn.net/img/view/2016/12/21/1322277.mp4'
pic1 = 'https://derpicdn.net/img/2017/7/21/1491832/thumb.jpeg'
i = InputMediaVideo(InputFileFromURL(vid1), thumb=InputFileFromURL(pic1))
d = i.get_request_data('lel', full_data=True)
self.assertEqual(d[0], {'type': 'video', 'thumb': 'attach://lel_thumb', 'media': 'attach://lel_media'})
self.assertListEqual(list(d[1].keys()), ['lel_media', 'lel_thumb'])
self.assertEqual(d[1]['lel_media'][0], '1322277.mp4', msg='Filename video')
self.assertEqual(d[1]['lel_thumb'][0], 'thumb.jpeg', msg='Filename thumb')
# end def
# end class
if __name__ == '__main__':
unittest.main()
# end if
|
from pytgbot.api_types.sendable.files import InputFileFromURL
from pytgbot.api_types.sendable.input_media import InputMediaVideo
import unittest
class MyTestCase(unittest.TestCase):
def test_InputMediaVideo_thumb_files(self):
vid1 = 'https://derpicdn.net/img/view/2016/12/21/1322277.mp4'
pic1 = 'https://derpicdn.net/img/2017/7/21/1491832/thumb.jpeg'
i = InputMediaVideo(InputFileFromURL(vid1), InputFileFromURL(pic1))
d = i.get_request_data('lel', full_data=True)
self.assertEqual(d[0], {'type': 'video', 'thumb': 'attach://lel_thumb', 'media': 'attach://lel_media'})
self.assertListEqual(list(d[1].keys()), ['lel_media', 'lel_thumb'])
self.assertEqual(d[1]['lel_media'][0], '1322277.mp4', msg='Filename video')
self.assertEqual(d[1]['lel_thumb'][0], 'thumb.jpeg', msg='Filename thumb')
# end def
# end class
if __name__ == '__main__':
unittest.main()
# end if
|
Test the InputMediaVideo with positional args only.
|
[test] Test the InputMediaVideo with positional args only.
|
Python
|
mit
|
luckydonald/pytgbot,luckydonald/pytgbot,luckydonald/pytgbot
|
---
+++
@@ -7,7 +7,7 @@
def test_InputMediaVideo_thumb_files(self):
vid1 = 'https://derpicdn.net/img/view/2016/12/21/1322277.mp4'
pic1 = 'https://derpicdn.net/img/2017/7/21/1491832/thumb.jpeg'
- i = InputMediaVideo(InputFileFromURL(vid1), thumb=InputFileFromURL(pic1))
+ i = InputMediaVideo(InputFileFromURL(vid1), InputFileFromURL(pic1))
d = i.get_request_data('lel', full_data=True)
self.assertEqual(d[0], {'type': 'video', 'thumb': 'attach://lel_thumb', 'media': 'attach://lel_media'})
self.assertListEqual(list(d[1].keys()), ['lel_media', 'lel_thumb'])
|
b2ed3d191f564df0911580bb7214b3d834b78dc3
|
prerender/cli.py
|
prerender/cli.py
|
import os
from .app import app
DEBUG = os.environ.get('DEBUG', 'false').lower() in ('true', 'yes', '1')
HOST = os.environ.get('HOST', '0.0.0.0')
PORT = int(os.environ.get('PORT', 8000))
def main():
app.run(host=HOST, port=PORT, debug=DEBUG)
if __name__ == '__main__':
main()
|
import os
import signal
import faulthandler
from .app import app
DEBUG = os.environ.get('DEBUG', 'false').lower() in ('true', 'yes', '1')
HOST = os.environ.get('HOST', '0.0.0.0')
PORT = int(os.environ.get('PORT', 8000))
def main():
faulthandler.register(signal.SIGUSR1)
app.run(host=HOST, port=PORT, debug=DEBUG)
if __name__ == '__main__':
main()
|
Integrate with faulthandler for easier debugging
|
Integrate with faulthandler for easier debugging
|
Python
|
mit
|
bosondata/chrome-prerender
|
---
+++
@@ -1,4 +1,6 @@
import os
+import signal
+import faulthandler
from .app import app
@@ -9,6 +11,7 @@
def main():
+ faulthandler.register(signal.SIGUSR1)
app.run(host=HOST, port=PORT, debug=DEBUG)
|
c80a0e14b0fc7a61accddd488f096f363fc85f2f
|
iss.py
|
iss.py
|
import requests
from datetime import datetime
def get_next_pass(lat, lon):
iss_url = 'http://api.open-notify.org/iss-pass.json'
location = {'lat': lat, 'lon': lon}
response = requests.get(iss_url, params=location).json()
next_pass = response['response'][0]['risetime']
return datetime.fromtimestamp(next_pass)
|
import requests
from redis import Redis
from rq_scheduler import Scheduler
from twilio.rest import TwilioRestClient
from datetime import datetime
redis_server = Redis()
scheduler = Scheduler(connection=Redis())
client = TwilioRestClient()
def get_next_pass(lat, lon):
iss_url = 'http://api.open-notify.org/iss-pass.json'
location = {'lat': lat, 'lon': lon}
response = requests.get(iss_url, params=location).json()
next_pass = response['response'][0]['risetime']
return datetime.fromtimestamp(next_pass)
def add_to_queue(number, lat, lon):
# Add this phone number to Redis associated with "lat,lon"
redis_server.set(number, str(lat) + ',' + str(lon))
# Get the timestamp of the next ISS flyby for this number.
next_pass_timestamp = get_next_pass(lat, lon)
# Schedule a text to be sent at the time of the next flyby.
scheduler.enqueue_at(next_pass_timestamp, notify_subscriber, number)
def notify_subscriber(number):
msg_body = "Look up! You may not be able to see it, but the International" \
" Space Station is passing above you right now!"
# Retrieve the latitude and longitude associated with this number.
lat, lon = redis_server.get(number).split(',')
# Send a message to the number alerting them of an ISS flyby.
client.messages.create(to=number, from_='', body=msg_body)
|
Add functions for scheduling messages and adding numbers to Redis
|
Add functions for scheduling messages and adding numbers to Redis
|
Python
|
mit
|
sagnew/ISSNotifications,sagnew/ISSNotifications,sagnew/ISSNotifications
|
---
+++
@@ -1,5 +1,14 @@
import requests
+from redis import Redis
+from rq_scheduler import Scheduler
+
+from twilio.rest import TwilioRestClient
from datetime import datetime
+
+redis_server = Redis()
+scheduler = Scheduler(connection=Redis())
+
+client = TwilioRestClient()
def get_next_pass(lat, lon):
@@ -9,3 +18,25 @@
next_pass = response['response'][0]['risetime']
return datetime.fromtimestamp(next_pass)
+
+
+def add_to_queue(number, lat, lon):
+ # Add this phone number to Redis associated with "lat,lon"
+ redis_server.set(number, str(lat) + ',' + str(lon))
+
+ # Get the timestamp of the next ISS flyby for this number.
+ next_pass_timestamp = get_next_pass(lat, lon)
+
+ # Schedule a text to be sent at the time of the next flyby.
+ scheduler.enqueue_at(next_pass_timestamp, notify_subscriber, number)
+
+
+def notify_subscriber(number):
+ msg_body = "Look up! You may not be able to see it, but the International" \
+ " Space Station is passing above you right now!"
+
+ # Retrieve the latitude and longitude associated with this number.
+ lat, lon = redis_server.get(number).split(',')
+
+ # Send a message to the number alerting them of an ISS flyby.
+ client.messages.create(to=number, from_='', body=msg_body)
|
567aa141546c905b842949799474742bf171a445
|
codegolf/__init__.py
|
codegolf/__init__.py
|
from flask import Flask
from .models import *
app = Flask(__name__)
app.config['SQLALCHEMY_DATABASE_URI'] = 'sqlite:////tmp/test.db'
from codegolf import views
|
from flask import Flask
import sqlalchemy as sa
from .models import *
app = Flask(__name__)
app.config['SQLALCHEMY_DATABASE_URI'] = 'sqlite:////tmp/test.db'
engine = sa.create_engine(app.config['SQLALCHEMY_DATABASE_URI'])
Session = sa.sessionmaker(bind=engine)
# instantiate Session to do things.
# I might write some nice Flask extension here, but I don't want to use flask_sqlalchemy
from codegolf import views
|
Update app decl to use sqlalchemy rather than flask_sqlalchemy properly
|
Update app decl to use sqlalchemy rather than flask_sqlalchemy properly
|
Python
|
mit
|
UQComputingSociety/codegolf,UQComputingSociety/codegolf,UQComputingSociety/codegolf
|
---
+++
@@ -1,7 +1,13 @@
from flask import Flask
+import sqlalchemy as sa
from .models import *
app = Flask(__name__)
app.config['SQLALCHEMY_DATABASE_URI'] = 'sqlite:////tmp/test.db'
+engine = sa.create_engine(app.config['SQLALCHEMY_DATABASE_URI'])
+Session = sa.sessionmaker(bind=engine)
+
+# instantiate Session to do things.
+# I might write some nice Flask extension here, but I don't want to use flask_sqlalchemy
from codegolf import views
|
c50051bd8699589c20acb32764b13bdb1473ff23
|
itsy/utils.py
|
itsy/utils.py
|
from . import Task, client
from .document import Document
def test_handler(handler, url):
print "Testing handler: %s" % handler.__name__
t = Task(url=url, document_type=None, referer=None)
print " Fetching url: %s" % url
raw = client.get(url, None)
doc = Document(t, raw)
print " Applying handler..."
new_tasks = handler(t, doc)
if new_tasks:
print " Yielded new tasks:"
for new_task in new_tasks:
print " %r" % new_task
else:
print " Did not yield new tasks."
|
from datetime import datetime
from decimal import Decimal
from . import Task
from .client import Client
from .document import Document
def test_handler(handler, url):
print "Testing handler: %s" % handler.__name__
t = Task(url=url, document_type=None, referer=None)
print " Fetching url: %s" % url
client = Client()
raw = client.get(url, None)
doc = Document(t, raw)
print " Applying handler..."
new_tasks = handler(t, doc)
if new_tasks:
print " Yielded new tasks:"
for new_task in new_tasks:
print " %r" % new_task
else:
print " Did not yield new tasks."
|
Update test_handler() to use Client() class
|
Update test_handler() to use Client() class
|
Python
|
mit
|
storborg/itsy
|
---
+++
@@ -1,4 +1,8 @@
-from . import Task, client
+from datetime import datetime
+from decimal import Decimal
+
+from . import Task
+from .client import Client
from .document import Document
@@ -6,6 +10,7 @@
print "Testing handler: %s" % handler.__name__
t = Task(url=url, document_type=None, referer=None)
print " Fetching url: %s" % url
+ client = Client()
raw = client.get(url, None)
doc = Document(t, raw)
print " Applying handler..."
|
acf7b76e098e70c77fbce95d03ec70911260ab58
|
accloudtant/__main__.py
|
accloudtant/__main__.py
|
from accloudtant import load_data
if __name__ == "__main__":
usage = load_data("tests/fixtures/2021/03/S3.csv")
print("Simple Storage Service")
for area, concepts in usage.totals(omit=lambda x: x.is_data_transfer or x.type == "StorageObjectCount"):
print("\t", area)
for c, v, u in concepts:
print("\t\t{}\t{} {}".format(c, v, u))
data_transfers = usage.data_transfers()
if len(data_transfers) > 0:
print("Data Transfer")
for area, concepts in data_transfers.totals(omit=lambda x: not x.is_data_transfer):
print("\t", area)
for c, v, u in concepts:
print("\t\t{}\t{} {}".format(c, v, u))
|
import argparse
from accloudtant import load_data
if __name__ == "__main__":
parser = argparse.ArgumentParser(description="AWS cost calculator")
parser.add_argument("csv_file", type=str, help='CSV file to read')
args = parser.parse_args()
usage = load_data(args.csv_file)
print("Simple Storage Service")
for area, concepts in usage.totals(omit=lambda x: x.is_data_transfer or x.type == "StorageObjectCount"):
print("\t", area)
for c, v, u in concepts:
print("\t\t{}\t{} {}".format(c, v, u))
data_transfers = usage.data_transfers()
if len(data_transfers) > 0:
print("Data Transfer")
for area, concepts in data_transfers.totals(omit=lambda x: not x.is_data_transfer):
print("\t", area)
for c, v, u in concepts:
print("\t\t{}\t{} {}".format(c, v, u))
|
Add argument to specify different files to load
|
Add argument to specify different files to load
This will make implementing other services easier.
|
Python
|
apache-2.0
|
ifosch/accloudtant
|
---
+++
@@ -1,8 +1,13 @@
+import argparse
from accloudtant import load_data
if __name__ == "__main__":
- usage = load_data("tests/fixtures/2021/03/S3.csv")
+ parser = argparse.ArgumentParser(description="AWS cost calculator")
+ parser.add_argument("csv_file", type=str, help='CSV file to read')
+ args = parser.parse_args()
+
+ usage = load_data(args.csv_file)
print("Simple Storage Service")
for area, concepts in usage.totals(omit=lambda x: x.is_data_transfer or x.type == "StorageObjectCount"):
|
63f06cdea9a0471708ee633ff0546b22cdebb786
|
pycolfin/cli.py
|
pycolfin/cli.py
|
# -*- coding: utf-8 -*-
import click
from .pycolfin import COLFin
from getpass import getpass
verbosity_help = """
1 = User ID, Last Login, Equity Value, Day Change
2 = Display all info from 1 and portfolio summary
3 = Display all info in 1 & 2 and detailed portfolio
"""
@click.command()
@click.option('-v', '--verbosity', default=3, type=click.IntRange(1, 3), help=verbosity_help)
def main(verbosity):
user_id = getpass(prompt='User ID:')
password = getpass(prompt='Password:')
account = None
try:
account = COLFin(user_id, password, parser='html.parser')
except Exception as e:
click.echo(e.__str__())
exit()
if verbosity >= 1:
account.fetch_account_summary()
account.show_account_summary()
if verbosity >= 2:
account.fetch_portfolio_summary()
account.show_portfolio_summary()
if verbosity == 3:
account.fetch_detailed_portfolio()
account.show_detailed_stocks()
account.show_detailed_mutual_fund()
if __name__ == "__main__":
main()
|
# -*- coding: utf-8 -*-
import click
from .pycolfin import COLFin
from getpass import getpass
verbosity_help = """
1 = User ID, Last Login, Equity Value, Day Change
2 = Display all info from 1 and portfolio summary
3 = Display all info in 1 & 2 and detailed portfolio
"""
@click.command()
@click.option('-v', '--verbosity', default=3, type=click.IntRange(1, 3), help=verbosity_help)
def main(verbosity):
user_id = getpass(prompt='User ID:')
password = getpass(prompt='Password:')
account = None
try:
account = COLFin(user_id, password, parser='html.parser')
except Exception as e:
click.echo(e.__str__())
exit()
if verbosity >= 1:
account.fetch_account_summary()
account.show_account_summary()
if verbosity >= 2:
account.fetch_portfolio_summary()
account.show_portfolio_summary()
if verbosity == 3:
account.fetch_detailed_portfolio()
try:
account.show_detailed_stocks()
except Exception as e:
print(e)
try:
account.show_detailed_mutual_fund()
except Exception as e:
print(e)
if __name__ == "__main__":
main()
|
Print message if exception encountered when trying to show detailed port/mutual funds
|
Print message if exception encountered when trying to show detailed port/mutual funds
Hopefully this handles the case when the user currently has no stocks and/or mutual funds. :fire:
|
Python
|
mit
|
patpatpatpatpat/pycolfin
|
---
+++
@@ -34,8 +34,14 @@
account.show_portfolio_summary()
if verbosity == 3:
account.fetch_detailed_portfolio()
- account.show_detailed_stocks()
- account.show_detailed_mutual_fund()
+ try:
+ account.show_detailed_stocks()
+ except Exception as e:
+ print(e)
+ try:
+ account.show_detailed_mutual_fund()
+ except Exception as e:
+ print(e)
if __name__ == "__main__":
|
a6adcc09bd1abe1d2538d499153a102cc37d5565
|
reader/reader.py
|
reader/reader.py
|
import json
import pika
from twython import TwythonStreamer
class TwitterConfiguration:
def __init__(self):
with open('twitter_key.json') as jsonData:
data = json.load(jsonData)
self.consumer_key = data['consumer_key']
self.consumer_secret = data['consumer_secret']
self.access_token = data['access_token']
self.access_token_secret = data['access_token_secret']
class MyStreamer(TwythonStreamer):
def __init__(self, twitter_configuration):
super().__init__(twitter_configuration.consumer_key, twitter_configuration.consumer_secret, twitter_configuration.access_token, twitter_configuration.access_token_secret)
def on_success(self, data):
if 'text' in data:
output_data = {
'text': data['text']
}
serialized_data = json.dumps(output_data)
print(serialized_data)
def on_error(self, status_code, data):
print(status_code)
pika_connection = pika.BlockingConnection(pika.ConnectionParameters('rabbitmq'))
pika_channel = pika_connection.channel()
pika_channel.queue_declare(queue='tweets')
configuration = TwitterConfiguration()
while True:
try:
stream = MyStreamer(configuration)
stream.statuses.filter(track='trump,clinton')
except:
print("Unexpected error: ", sys.exc_info()[0])
|
import json
import pika
import time
from twython import TwythonStreamer
class TwitterConfiguration:
def __init__(self):
with open('twitter_key.json') as jsonData:
data = json.load(jsonData)
self.consumer_key = data['consumer_key']
self.consumer_secret = data['consumer_secret']
self.access_token = data['access_token']
self.access_token_secret = data['access_token_secret']
class MyStreamer(TwythonStreamer):
def __init__(self, twitter_configuration):
super().__init__(twitter_configuration.consumer_key, twitter_configuration.consumer_secret, twitter_configuration.access_token, twitter_configuration.access_token_secret)
def on_success(self, data):
if 'text' in data:
output_data = {
'text': data['text']
}
serialized_data = json.dumps(output_data)
print(serialized_data)
def on_error(self, status_code, data):
print(status_code)
pika_connection = None
while pika_connection == None:
try:
pika_connection = pika.BlockingConnection(pika.ConnectionParameters('rabbitmq'))
except pika.exceptions.ConnectionClosed:
print("RabbitMQ connection still closed. Retrying.")
time.sleep(5)
pika_channel = pika_connection.channel()
pika_channel.queue_declare(queue='tweets')
configuration = TwitterConfiguration()
while True:
try:
stream = MyStreamer(configuration)
stream.statuses.filter(track='trump,clinton')
except:
print("Unexpected error: ", sys.exc_info()[0])
|
Add retry for opening RabbitMQ connection (cluster start)
|
Add retry for opening RabbitMQ connection (cluster start)
|
Python
|
mit
|
estiller/tweet-analyzer-demo,estiller/tweet-analyzer-demo,estiller/tweet-analyzer-demo,estiller/tweet-analyzer-demo,estiller/tweet-analyzer-demo
|
---
+++
@@ -1,5 +1,6 @@
import json
import pika
+import time
from twython import TwythonStreamer
class TwitterConfiguration:
@@ -29,7 +30,14 @@
print(status_code)
-pika_connection = pika.BlockingConnection(pika.ConnectionParameters('rabbitmq'))
+pika_connection = None
+while pika_connection == None:
+ try:
+ pika_connection = pika.BlockingConnection(pika.ConnectionParameters('rabbitmq'))
+ except pika.exceptions.ConnectionClosed:
+ print("RabbitMQ connection still closed. Retrying.")
+ time.sleep(5)
+
pika_channel = pika_connection.channel()
pika_channel.queue_declare(queue='tweets')
|
575a73f7e1ba7d175fa406478e71fd05fd2cae2e
|
test/test_web_services.py
|
test/test_web_services.py
|
# -*- coding: utf-8 -*-
#
|
# -*- coding: utf-8 -*-
#
import avalon.web.services
def test_intersection_with_empty_set():
set1 = set(['foo', 'bar'])
set2 = set(['foo'])
set3 = set()
res = avalon.web.services.intersection([set1, set2, set3])
assert 0 == len(res), 'Expected empty set of common results'
def test_intersection_no_overlap():
set1 = set(['foo', 'bar'])
set2 = set(['baz'])
set3 = set(['bing'])
res = avalon.web.services.intersection([set1, set2, set3])
assert 0 == len(res), 'Expected empty set of common results'
def test_intersection_with_overlap():
set1 = set(['foo', 'bar'])
set2 = set(['foo', 'baz'])
set3 = set(['bing', 'foo'])
res = avalon.web.services.intersection([set1, set2, set3])
assert 1 == len(res), 'Expected set of one common result'
|
Add tests for result set intersection method
|
Add tests for result set intersection method
|
Python
|
mit
|
tshlabs/avalonms
|
---
+++
@@ -1,2 +1,32 @@
# -*- coding: utf-8 -*-
#
+
+
+import avalon.web.services
+
+
+def test_intersection_with_empty_set():
+ set1 = set(['foo', 'bar'])
+ set2 = set(['foo'])
+ set3 = set()
+
+ res = avalon.web.services.intersection([set1, set2, set3])
+ assert 0 == len(res), 'Expected empty set of common results'
+
+
+def test_intersection_no_overlap():
+ set1 = set(['foo', 'bar'])
+ set2 = set(['baz'])
+ set3 = set(['bing'])
+
+ res = avalon.web.services.intersection([set1, set2, set3])
+ assert 0 == len(res), 'Expected empty set of common results'
+
+
+def test_intersection_with_overlap():
+ set1 = set(['foo', 'bar'])
+ set2 = set(['foo', 'baz'])
+ set3 = set(['bing', 'foo'])
+
+ res = avalon.web.services.intersection([set1, set2, set3])
+ assert 1 == len(res), 'Expected set of one common result'
|
5d7c85d33f8e51947d8791bd597720f161a48f82
|
game/views.py
|
game/views.py
|
from django.shortcuts import render
from django.http import HttpResponse
def index(request):
context = {'text': 'Welcome to our game'}
return render(request, 'game/index.html', context)
def users(request):
context = {'text': 'User list here'}
return render(request, 'game/users.html', context)
def user_detail(request, user_id):
return HttpResponse("This page will have user details")
def leaderboard(request):
context = {'text': 'Leaderboard goes here'}
return render(request, 'game/leaderboard.html', context)
|
from django.shortcuts import render
from django.http import HttpResponse
def index(request):
context = {'text': 'Welcome to our game'}
return render(request, 'game/index.html', context)
def register(request):
context = {'text': 'Register here'}
return render(request, 'registration/register.html', context)
def users(request):
context = {'text': 'User list here'}
return render(request, 'game/users.html', context)
def user_detail(request, user_id):
return HttpResponse("This page will have user details")
def leaderboard(request):
context = {'text': 'Leaderboard goes here'}
return render(request, 'game/leaderboard.html', context)
|
Fix merge conflict with master repo
|
Fix merge conflict with master repo
|
Python
|
mit
|
shintouki/augmented-pandemic,shintouki/augmented-pandemic,shintouki/augmented-pandemic
|
---
+++
@@ -4,6 +4,10 @@
def index(request):
context = {'text': 'Welcome to our game'}
return render(request, 'game/index.html', context)
+
+def register(request):
+ context = {'text': 'Register here'}
+ return render(request, 'registration/register.html', context)
def users(request):
context = {'text': 'User list here'}
|
8c96f3211967c680ee26b673dc9fe0299180a1c4
|
knights/dj.py
|
knights/dj.py
|
from collections import defaultdict
from django.template import TemplateDoesNotExist, TemplateSyntaxError # NOQA
from django.template.backends.base import BaseEngine
from django.template.backends.utils import csrf_input_lazy, csrf_token_lazy
from . import compiler
from . import loader
class KnightsTemplater(BaseEngine):
def __init__(self, params):
params = params.copy()
options = params.pop('OPTIONS').copy()
super(KnightsTemplater, self).__init__(params)
def from_string(self, template_code):
tmpl = compiler.kompile(template_code)
return Template(tmpl)
def get_template(self, template_name):
try:
tmpl = loader.load_template(template_name, self.template_dirs)
except Exception as e:
raise TemplateSyntaxError(e).with_traceback(e.__traceback__)
if tmpl is None:
raise TemplateDoesNotExist(template_name)
return Template(tmpl)
class Template(object):
def __init__(self, template):
self.template = template
def render(self, context=None, request=None):
if context is None:
context = {}
if request is not None:
context['user'] = request.user
context['request'] = request
context['csrf_input'] = csrf_input_lazy(request)
context['csrf_token'] = csrf_token_lazy(request)
ctx = defaultdict(str)
ctx.update(context)
return self.template(ctx)
|
from collections import defaultdict
from django.template.base import TemplateDoesNotExist, TemplateSyntaxError # NOQA
from django.template.backends.base import BaseEngine
from django.template.backends.utils import csrf_input_lazy, csrf_token_lazy
from . import compiler
from . import loader
class KnightsTemplater(BaseEngine):
def __init__(self, params):
params = params.copy()
options = params.pop('OPTIONS').copy()
super(KnightsTemplater, self).__init__(params)
def from_string(self, template_code):
tmpl = compiler.kompile(template_code)
return Template(tmpl)
def get_template(self, template_name):
try:
tmpl = loader.load_template(template_name, self.template_dirs)
except loader.TemplateNotFound:
raise TemplateDoesNotExist(template_name)
except Exception as e:
raise TemplateSyntaxError(e).with_traceback(e.__traceback__)
return Template(tmpl)
class Template(object):
def __init__(self, template):
self.template = template
def render(self, context=None, request=None):
if context is None:
context = {}
if request is not None:
context['user'] = request.user
context['request'] = request
context['csrf_input'] = csrf_input_lazy(request)
context['csrf_token'] = csrf_token_lazy(request)
ctx = defaultdict(str)
ctx.update(context)
return self.template(ctx)
|
Update adapter to catch exception from loader
|
Update adapter to catch exception from loader
|
Python
|
mit
|
funkybob/knights-templater,funkybob/knights-templater
|
---
+++
@@ -1,6 +1,6 @@
from collections import defaultdict
-from django.template import TemplateDoesNotExist, TemplateSyntaxError # NOQA
+from django.template.base import TemplateDoesNotExist, TemplateSyntaxError # NOQA
from django.template.backends.base import BaseEngine
from django.template.backends.utils import csrf_input_lazy, csrf_token_lazy
@@ -23,10 +23,10 @@
def get_template(self, template_name):
try:
tmpl = loader.load_template(template_name, self.template_dirs)
+ except loader.TemplateNotFound:
+ raise TemplateDoesNotExist(template_name)
except Exception as e:
raise TemplateSyntaxError(e).with_traceback(e.__traceback__)
- if tmpl is None:
- raise TemplateDoesNotExist(template_name)
return Template(tmpl)
|
4bcbb06b779851dd5d031b7951ff80ed325b1414
|
gather/commands.py
|
gather/commands.py
|
from gather.organiser import NotEnoughPlayersError
def strip_help(bot):
messages = []
for regex, action in bot.actions.values():
if action.__doc__:
messages.append(action.__doc__.strip())
return messages
async def bot_help(bot, channel, author, message):
await bot.say_lines(channel, strip_help(bot))
async def add(bot, channel, author, message):
"""
- !add, !s - add yourself to the pool
"""
bot.organiser.add(channel, author)
await bot.say(channel, 'You are now signed in, {0}.'.format(author))
# Add cooldown in so this will not post more than every five seconds or so
await bot.announce_players(channel)
try:
team_one, team_two = bot.organiser.pop_teams(channel)
# TODO: Announce the game
except NotEnoughPlayersError:
pass
async def remove(bot, channel, author, message):
"""
- !remove, !so - remove yourself from the pool
"""
bot.organiser.remove(channel, author)
await bot.say(channel, 'You are now signed out, {0}.'.format(author))
|
from gather.organiser import NotEnoughPlayersError
def strip_help(bot):
messages = []
for regex, action in bot.actions.values():
if action.__doc__:
messages.append(action.__doc__.strip())
return messages
async def bot_help(bot, channel, author, message):
await bot.say_lines(channel, strip_help(bot))
async def add(bot, channel, author, message):
"""
- !add, !s - add yourself to the pool
"""
bot.organiser.add(channel, author)
await bot.say(channel, 'You are now signed in, {0}.'.format(author))
# Add cooldown in so this will not post more than every five seconds or so
await bot.announce_players(channel)
try:
team_one, team_two = bot.organiser.pop_teams(channel)
# TODO: Announce the game
except NotEnoughPlayersError:
pass
async def remove(bot, channel, author, message):
"""
- !remove, !so - remove yourself from the pool
"""
bot.organiser.remove(channel, author)
await bot.say(channel, 'You are now signed out, {0}.'.format(author))
# Add cooldown in so this will not post more than every five seconds or so
await bot.announce_players(channel)
|
Print players on remove too
|
Print players on remove too
|
Python
|
mit
|
veryhappythings/discord-gather
|
---
+++
@@ -36,3 +36,5 @@
"""
bot.organiser.remove(channel, author)
await bot.say(channel, 'You are now signed out, {0}.'.format(author))
+ # Add cooldown in so this will not post more than every five seconds or so
+ await bot.announce_players(channel)
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.