commit
stringlengths 40
40
| old_file
stringlengths 4
264
| new_file
stringlengths 4
264
| old_contents
stringlengths 0
3.26k
| new_contents
stringlengths 1
4.43k
| subject
stringlengths 15
624
| message
stringlengths 15
4.7k
| lang
stringclasses 3
values | license
stringclasses 13
values | repos
stringlengths 5
91.5k
|
---|---|---|---|---|---|---|---|---|---|
ca4be3892ec0c1b5bc337a9fae10503b5f7f765a
|
bika/lims/browser/validation.py
|
bika/lims/browser/validation.py
|
from Products.Archetypes.browser.validation import InlineValidationView as _IVV
from Acquisition import aq_inner
from Products.CMFCore.utils import getToolByName
import json
SKIP_VALIDATION_FIELDTYPES = ('image', 'file', 'datetime', 'reference')
class InlineValidationView(_IVV):
def __call__(self, uid, fname, value):
'''Validate a given field. Return any error messages.
'''
res = {'errmsg': ''}
if value not in self.request:
return json.dumps(res)
rc = getToolByName(aq_inner(self.context), 'reference_catalog')
instance = rc.lookupObject(uid)
# make sure this works for portal_factory items
if instance is None:
instance = self.context
field = instance.getField(fname)
if field and field.type not in SKIP_VALIDATION_FIELDTYPES:
return super(InlineValidationView, self).__call__(uid, fname, value)
self.request.response.setHeader('Content-Type', 'application/json')
return json.dumps(res)
|
from Products.Archetypes.browser.validation import InlineValidationView as _IVV
from Acquisition import aq_inner
from Products.CMFCore.utils import getToolByName
import json
SKIP_VALIDATION_FIELDTYPES = ('image', 'file', 'datetime', 'reference')
class InlineValidationView(_IVV):
def __call__(self, uid, fname, value):
'''Validate a given field. Return any error messages.
'''
res = {'errmsg': ''}
rc = getToolByName(aq_inner(self.context), 'reference_catalog')
instance = rc.lookupObject(uid)
# make sure this works for portal_factory items
if instance is None:
instance = self.context
field = instance.getField(fname)
if field and field.type not in SKIP_VALIDATION_FIELDTYPES:
return super(InlineValidationView, self).__call__(uid, fname, value)
self.request.response.setHeader('Content-Type', 'application/json')
return json.dumps(res)
|
Revert "Inline Validation fails silently if request is malformed"
|
Revert "Inline Validation fails silently if request is malformed"
This reverts commit 723e4eb603568d3a60190d8d292cc335a74b79d5.
|
Python
|
agpl-3.0
|
labsanmartin/Bika-LIMS,veroc/Bika-LIMS,veroc/Bika-LIMS,rockfruit/bika.lims,veroc/Bika-LIMS,labsanmartin/Bika-LIMS,anneline/Bika-LIMS,DeBortoliWines/Bika-LIMS,DeBortoliWines/Bika-LIMS,anneline/Bika-LIMS,DeBortoliWines/Bika-LIMS,anneline/Bika-LIMS,rockfruit/bika.lims,labsanmartin/Bika-LIMS
|
fb58117527c486401d07e046077151d3217e576f
|
python/copy-market-report.py
|
python/copy-market-report.py
|
import yaml
from time import gmtime, strftime
from shutil import copy
with open('../config/betfair_config.yml', 'r') as f:
doc = yaml.load(f)
data_dir = doc['default']['betfair']['data_dir']
todays_date = strftime('%Y-%-m-%d', gmtime())
src='/tmp/market-report.pdf'
dest=data_dir + '/data/' + todays_date + '/market-report.pdf'
png_src='/tmp/distance-and-runners-scatter.png'
png_dest=data_dir + '/data/' + todays_date + '/distance-and-runners-scatter.png'
copy(src,dest)
copy(png_src,png_dest)
|
import yaml
from time import gmtime, strftime
from shutil import copy
with open('../config/betfair_config.yml', 'r') as f:
doc = yaml.load(f)
data_dir = doc['default']['betfair']['data_dir']
todays_date = strftime('%Y-%-m-%-d', gmtime())
src='/tmp/market-report.pdf'
dest=data_dir + '/data/' + todays_date + '/market-report.pdf'
png_src='/tmp/distance-and-runners-scatter.png'
png_dest=data_dir + '/data/' + todays_date + '/distance-and-runners-scatter.png'
copy(src,dest)
copy(png_src,png_dest)
|
Fix bug reading filenames for days with 1 number
|
Fix bug reading filenames for days with 1 number
|
Python
|
apache-2.0
|
cranburyattic/bf-app,cranburyattic/bf-app,cranburyattic/bf-app,cranburyattic/bf-app
|
6949339cda8c60b74341f854d9a00aa8abbfe4d5
|
test/level_sets_measure_test.py
|
test/level_sets_measure_test.py
|
__author__ = 'intsco'
import cPickle
from engine.pyIMS.image_measures.level_sets_measure import measure_of_chaos_dict
from unittest import TestCase
import unittest
from os.path import join, realpath, dirname
class MeasureOfChaosDictTest(TestCase):
def setUp(self):
self.rows, self.cols = 65, 65
self.input_fn = join(dirname(realpath(__file__)), 'data/measure_of_chaos_dict_test_input.pkl')
with open(self.input_fn) as f:
self.input_data = cPickle.load(f)
def testMOCBoundaries(self):
for img_d in self.input_data:
if len(img_d) > 0:
assert 0 <= measure_of_chaos_dict(img_d, self.rows, self.cols) <= 1
def testEmptyInput(self):
# print measure_of_chaos_dict({}, self.cols, self.cols)
self.assertRaises(Exception, measure_of_chaos_dict, {}, self.cols, self.cols)
self.assertRaises(Exception, measure_of_chaos_dict, None, self.cols, self.cols)
self.assertRaises(Exception, measure_of_chaos_dict, (), self.cols, self.cols)
self.assertRaises(Exception, measure_of_chaos_dict, [], self.cols, self.cols)
def testMaxInputDictKeyVal(self):
max_key_val = self.rows * self.cols - 1
self.assertRaises(Exception, measure_of_chaos_dict, {max_key_val + 10: 1}, self.rows, self.cols)
if __name__ == '__main__':
unittest.main()
|
import unittest
import numpy as np
from ..image_measures.level_sets_measure import measure_of_chaos, _nan_to_zero
class MeasureOfChaosTest(unittest.TestCase):
def test__nan_to_zero_with_ge_zero(self):
ids = (
np.zeros(1),
np.ones(range(1, 10)),
np.arange(1024 * 1024)
)
for id_ in ids:
before = id_.copy()
_nan_to_zero(id_)
np.testing.assert_array_equal(before, id_)
def test__nan_to_zero_with_negatives(self):
negs = (
np.array([-1]),
-np.arange(1, 1024 * 1024 + 1).reshape((1024, 1024)),
np.linspace(0, -20, 201)
)
for neg in negs:
sh = neg.shape
_nan_to_zero(neg)
np.testing.assert_array_equal(neg, np.zeros(sh))
if __name__ == '__main__':
unittest.main()
|
Implement first tests for _nan_to_zero
|
Implement first tests for _nan_to_zero
- Remove outdated dict test class
- write some test methods
|
Python
|
apache-2.0
|
andy-d-palmer/pyIMS,alexandrovteam/pyImagingMSpec
|
12f4b26d98c3ba765a11efeca3b646b5e9d0a0fb
|
running.py
|
running.py
|
import tcxparser
from configparser import ConfigParser
from datetime import datetime
import urllib.request
import dateutil.parser
t = '1984-06-02T19:05:00.000Z'
# Darksky weather API
# Create config file manually
parser = ConfigParser()
parser.read('slowburn.config', encoding='utf-8')
darksky_key = parser.get('darksky', 'key')
tcx = tcxparser.TCXParser('gps_logs/2017-06-15_Running.tcx')
run_time = tcx.completed_at
def convert_time_to_unix(time):
parsed_time = dateutil.parser.parse(time)
time_in_unix = parsed_time.strftime('%s')
return time_in_unix
unix_run_time = convert_time_to_unix(run_time)
darksky_request = urllib.request.urlopen("https://api.darksky.net/forecast/" + darksky_key + "/42.3601,-71.0589," + unix_run_time + "?exclude=currently,flags").read()
print(darksky_request)
class getWeather:
def __init__(self, date, time):
self.date = date
self.time = time
def goodbye(self, date):
print("my name is " + date)
|
import tcxparser
from configparser import ConfigParser
from datetime import datetime
import urllib.request
import dateutil.parser
t = '1984-06-02T19:05:00.000Z'
# Darksky weather API
# Create config file manually
parser = ConfigParser()
parser.read('slowburn.config', encoding='utf-8')
darksky_key = parser.get('darksky', 'key')
tcx = tcxparser.TCXParser('gps_logs/2017-06-15_Running.tcx')
run_time = tcx.completed_at
def convert_time_to_unix(time):
parsed_time = dateutil.parser.parse(time)
time_in_unix = parsed_time.strftime('%s')
return time_in_unix
unix_run_time = convert_time_to_unix(run_time)
darksky_request = urllib.request.urlopen("https://api.darksky.net/forecast/" + darksky_key + "/" + str(tcx.latitude) + "," + str(tcx.longitude) + "," + unix_run_time + "?exclude=currently,flags").read()
print(darksky_request)
class getWeather:
def __init__(self, date, time):
self.date = date
self.time = time
def goodbye(self, date):
print("my name is " + date)
|
Use TCX coordinates to fetch local weather
|
Use TCX coordinates to fetch local weather
|
Python
|
mit
|
briansuhr/slowburn
|
5a7b13e26e94d03bc92600d9c24b3b2e8bc4321c
|
dstar_lib/aprsis.py
|
dstar_lib/aprsis.py
|
import aprslib
import logging
import nmea
class AprsIS:
logger = None
def __init__(self, callsign, password):
self.logger = logging.getLogger(__name__)
self.aprs_connection = aprslib.IS(callsign, password)
self.aprs_connection.connect()
def send_beacon(self, callsign, sfx, message, gpgga):
position = nmea.gpgga_get_position(gpgga)
aprs_frame = callsign+'>APK'+sfx+',DSTAR*:!'+position['lat'] + position['lat_coord'] + '\\'+position['long']+position['long_coord']+'a/A=' + position['height'] + message
self.logger.info("Sending APRS Frame: " + aprs_frame)
try:
self.aprs_connection.sendall(aprs.Frame(aprs_frame))
except:
self.logger.info("Invalid aprs frame: " + aprs_frame)
|
import aprslib
import logging
import nmea
class AprsIS:
logger = None
def __init__(self, callsign, password):
self.logger = logging.getLogger(__name__)
self.aprs_connection = aprslib.IS(callsign, password)
self.aprs_connection.connect()
def send_beacon(self, callsign, sfx, message, gpgga):
position = nmea.gpgga_get_position(gpgga)
aprs_frame = callsign+'>APK'+sfx+',DSTAR*:!'+position['lat'] + position['lat_coord'] + '\\'+position['long']+position['long_coord']+'a/A=' + position['height'] + message
self.logger.info("Sending APRS Frame: " + aprs_frame)
try:
self.aprs_connection.sendall(aprs_frame)
self.logger.info("APRS Beacon sent!")
except Exception, e:
self.logger.info("Invalid aprs frame [%s] - %s" % (aprs_frame, str(e))
|
Fix an issue with the new aprslib
|
Fix an issue with the new aprslib
|
Python
|
mit
|
elielsardanons/dstar_sniffer,elielsardanons/dstar_sniffer
|
132b148ca8701ee867b7a08432a3595a213ce470
|
cedexis/radar/tests/test_cli.py
|
cedexis/radar/tests/test_cli.py
|
import unittest
import types
import cedexis.radar.cli
class TestCommandLineInterface(unittest.TestCase):
def test_main(self):
self.assertTrue(isinstance(cedexis.radar.cli.main, types.FunctionType))
|
import unittest
from unittest.mock import patch, MagicMock, call
import types
from pprint import pprint
import cedexis.radar.cli
class TestCommandLineInterface(unittest.TestCase):
def test_main(self):
self.assertTrue(isinstance(cedexis.radar.cli.main, types.FunctionType))
@patch('logging.getLogger')
@patch('argparse.ArgumentParser')
@patch('cedexis.radar.run_session')
@patch('time.sleep')
def test_config_file_with_cli_params(self, mock_sleep, mock_run_session,
mock_ArgumentParser, mock_getLogger):
args = make_default_args()
args.continuous = True
args.max_runs = 3
args.repeat_delay = 60
mock_parser = MagicMock()
mock_parser.parse_args.return_value = args
mock_ArgumentParser.return_value = mock_parser
cedexis.radar.cli.main()
# Assert
# print(mock_run_session.call_args)
self.assertEqual(
mock_run_session.call_args_list,
[
call(1, 12345, 'sandbox', False, None, None, False, None),
call(1, 12345, 'sandbox', False, None, None, False, None),
call(1, 12345, 'sandbox', False, None, None, False, None)
])
# print(mock_sleep.call_args)
self.assertEqual(mock_sleep.call_args_list, [call(60),call(60)])
def make_default_args():
args = lambda: None
args.zone_id = 1
args.customer_id = 12345
args.api_key = 'sandbox'
args.secure = False
args.config_file = 'some config file path'
args.tracer = None
args.provider_id = None
args.report_server = None
args.max_runs = None
args.repeat_delay = None
return args
|
Add unit test for overrides
|
Add unit test for overrides
|
Python
|
mit
|
cedexis/cedexis.radar
|
70f167d3d5a7540fb3521b82ec70bf7c6db09a99
|
tests/test_contrib.py
|
tests/test_contrib.py
|
from __future__ import print_function
import cooler.contrib.higlass as cch
import h5py
import os.path as op
testdir = op.realpath(op.dirname(__file__))
def test_data_retrieval():
data_file = op.join(testdir, 'data', 'dixon2012-h1hesc-hindiii-allreps-filtered.1000kb.multires.cool')
f = h5py.File(data_file, 'r')
data = cch.get_data(f, 0, 0, 3276799999, 0, 3276799999)
assert(data['genome_start1'].iloc[0] == 0.)
assert(data['genome_start2'].iloc[0] == 0.)
data = cch.get_data(f, 4, 0, 256000000, 0, 256000000)
assert(data['genome_start1'].iloc[-1] > 255000000)
assert(data['genome_start1'].iloc[-1] < 256000000)
#print("ge1", data['genome_end1'])
|
from __future__ import print_function
import cooler.contrib.higlass as cch
import cooler.contrib.recursive_agg_onefile as ra
import h5py
import os.path as op
testdir = op.realpath(op.dirname(__file__))
def test_data_retrieval():
data_file = op.join(testdir, 'data', 'dixon2012-h1hesc-hindiii-allreps-filtered.1000kb.multires.cool')
f = h5py.File(data_file, 'r')
data = cch.get_data(f, 0, 0, 3276799999, 0, 3276799999)
assert(data['genome_start1'].iloc[0] == 0.)
assert(data['genome_start2'].iloc[0] == 0.)
data = cch.get_data(f, 4, 0, 256000000, 0, 256000000)
assert(data['genome_start1'].iloc[-1] > 255000000)
assert(data['genome_start1'].iloc[-1] < 256000000)
#print("ge1", data['genome_end1'])
def test_recursive_agg():
infile = op.join(testdir, 'data', 'GM12878-MboI-matrix.2000kb.cool')
outfile = '/tmp/bla.cool'
chunksize = int(10e6)
n_zooms = 2
n_cpus = 8
ra.aggregate(infile, outfile, n_zooms, chunksize, n_cpus)
ra.balance(outfile, n_zooms, chunksize, n_cpus)
|
Add test for recursive agg
|
Add test for recursive agg
|
Python
|
bsd-3-clause
|
mirnylab/cooler
|
27a0165d45f52114ebb65d59cf8e4f84f3232881
|
tests/test_lattice.py
|
tests/test_lattice.py
|
import rml.lattice
def test_create_lattice():
l = rml.lattice.Lattice()
assert(len(l)) == 0
def test_non_negative_lattice():
l = rml.lattice.Lattice()
assert(len(l)) >= 0
|
import rml.lattice
import rml.element
def test_create_lattice():
l = rml.lattice.Lattice()
assert(len(l)) == 0
def test_non_negative_lattice():
l = rml.lattice.Lattice()
assert(len(l)) >= 0
def test_lattice_with_one_element():
l = rml.lattice.Lattice()
element_length = 1.5
e = rml.element.Element('dummy', element_length)
l.append_element(e)
# There is one element in the lattice.
assert(len(l) == 1)
# The total length of the lattice is the same as its one element.
assert l.length() = element_length
|
Test simple lattice with one element.
|
Test simple lattice with one element.
|
Python
|
apache-2.0
|
willrogers/pml,willrogers/pml,razvanvasile/RML
|
7591189527ad05be62a561afadf70b217d725b1f
|
scrapi/processing/osf/__init__.py
|
scrapi/processing/osf/__init__.py
|
from scrapi.processing.osf import crud
from scrapi.processing.osf import collision
from scrapi.processing.base import BaseProcessor
class OSFProcessor(BaseProcessor):
NAME = 'osf'
def process_normalized(self, raw_doc, normalized):
if crud.is_event(normalized):
crud.create_event(normalized)
return
report_hash = collision.generate_report_hash_list(normalized)
resource_hash = collision.generate_resource_hash_list(normalized)
report = collision.detect_collisions(report_hash)
resource = collision.detect_collisions(resource_hash)
if not resource:
resource = crud.create_resource(normalized, resource_hash)
elif not crud.is_claimed(resource):
crud.update_resource(normalized, resource)
if not report:
crud.create_report(normalized, resource, report_hash)
else:
crud.update_report(normalized, report)
|
from scrapi.processing.osf import crud
from scrapi.processing.osf import collision
from scrapi.processing.base import BaseProcessor
class OSFProcessor(BaseProcessor):
NAME = 'osf'
def process_normalized(self, raw_doc, normalized):
if crud.is_event(normalized):
crud.create_event(normalized)
return
normalized['collisionCategory'] = crud.get_collision_cat(normalized['source'])
report_norm = normalized
resource_norm = crud.clean_report(normalized)
report_hash = collision.generate_report_hash_list(report_norm)
resource_hash = collision.generate_resource_hash_list(resource_norm)
report = collision.detect_collisions(report_hash)
resource = collision.detect_collisions(resource_hash)
if not resource:
resource = crud.create_resource(resource_norm, resource_hash)
elif not crud.is_claimed(resource):
crud.update_resource(resource_norm, resource)
if not report:
crud.create_report(report_norm, resource, report_hash)
else:
crud.update_report(report_norm, report)
|
Make sure to keep certain report fields out of resources
|
Make sure to keep certain report fields out of resources
|
Python
|
apache-2.0
|
alexgarciac/scrapi,erinspace/scrapi,icereval/scrapi,mehanig/scrapi,felliott/scrapi,erinspace/scrapi,CenterForOpenScience/scrapi,fabianvf/scrapi,mehanig/scrapi,ostwald/scrapi,fabianvf/scrapi,CenterForOpenScience/scrapi,felliott/scrapi,jeffreyliu3230/scrapi
|
3fe86c259e6015ca535510bd692cc26d5d4e64cc
|
bin/license_finder_pip.py
|
bin/license_finder_pip.py
|
#!/usr/bin/env python
import json
from pip.req import parse_requirements
from pip.download import PipSession
from pip._vendor import pkg_resources
from pip._vendor.six import print_
requirements = [pkg_resources.Requirement(str(req.req)) for req
in parse_requirements('requirements.txt', session=PipSession())]
transform = lambda dist: {
'name': dist.project_name,
'version': dist.version,
'location': dist.location,
'dependencies': list(map(lambda dependency: dependency.project_name, dist.requires())),
}
packages = [transform(dist) for dist
in pkg_resources.working_set.resolve(requirements)]
print_(json.dumps(packages))
|
#!/usr/bin/env python
import json
from pip.req import parse_requirements
from pip.download import PipSession
from pip._vendor import pkg_resources
from pip._vendor.six import print_
requirements = [pkg_resources.Requirement.parse(str(req.req)) for req
in parse_requirements('requirements.txt', session=PipSession())]
transform = lambda dist: {
'name': dist.project_name,
'version': dist.version,
'location': dist.location,
'dependencies': list(map(lambda dependency: dependency.project_name, dist.requires())),
}
packages = [transform(dist) for dist
in pkg_resources.working_set.resolve(requirements)]
print_(json.dumps(packages))
|
Use parse() method to instantiate Requirement
|
Use parse() method to instantiate Requirement
[Fix #224]
Signed-off-by: Tony Wong <[email protected]>
|
Python
|
mit
|
bspeck/LicenseFinder,sschuberth/LicenseFinder,bdshroyer/LicenseFinder,bdshroyer/LicenseFinder,bspeck/LicenseFinder,bdshroyer/LicenseFinder,tinfoil/LicenseFinder,tinfoil/LicenseFinder,bspeck/LicenseFinder,pivotal/LicenseFinder,bdshroyer/LicenseFinder,bspeck/LicenseFinder,sschuberth/LicenseFinder,bspeck/LicenseFinder,pivotal/LicenseFinder,tinfoil/LicenseFinder,bdshroyer/LicenseFinder,pivotal/LicenseFinder,sschuberth/LicenseFinder,pivotal/LicenseFinder,tinfoil/LicenseFinder,sschuberth/LicenseFinder,pivotal/LicenseFinder,pivotal/LicenseFinder,sschuberth/LicenseFinder,tinfoil/LicenseFinder,pivotal/LicenseFinder
|
166e0980fc20b507763395297e8a67c7dcb3a3da
|
examples/neural_network_inference/onnx_converter/small_example.py
|
examples/neural_network_inference/onnx_converter/small_example.py
|
import torch
import torch.nn as nn
import torch.nn.functional as F
from onnx_coreml import convert
# Step 0 - (a) Define ML Model
class small_model(nn.Module):
def __init__(self):
super(small_model, self).__init__()
self.fc1 = nn.Linear(768, 256)
self.fc2 = nn.Linear(256, 10)
def forward(self, x):
y = F.relu(self.fc1(x))
y = F.softmax(self.fc2(y))
return y
# Step 0 - (b) Create model or Load from dist
model = small_model()
dummy_input = torch.randn(768)
# Step 1 - PyTorch to ONNX model
torch.onnx.export(model, dummy_input, './small_model.onnx')
# Step 2 - ONNX to CoreML model
mlmodel = convert(model='./small_model.onnx', target_ios='13')
# Save converted CoreML model
mlmodel.save('small_model.mlmodel')
|
import torch
import torch.nn as nn
import torch.nn.functional as F
from onnx_coreml import convert
# Step 0 - (a) Define ML Model
class small_model(nn.Module):
def __init__(self):
super(small_model, self).__init__()
self.fc1 = nn.Linear(768, 256)
self.fc2 = nn.Linear(256, 10)
def forward(self, x):
y = F.relu(self.fc1(x))
y = F.softmax(self.fc2(y))
return y
# Step 0 - (b) Create model or Load from dist
model = small_model()
dummy_input = torch.randn(768)
# Step 1 - PyTorch to ONNX model
torch.onnx.export(model, dummy_input, './small_model.onnx')
# Step 2 - ONNX to CoreML model
mlmodel = convert(model='./small_model.onnx', minimum_ios_deployment_target='13')
# Save converted CoreML model
mlmodel.save('small_model.mlmodel')
|
Update the example with latest interface
|
Update the example with latest interface
Update the example with the latest interface of the function "convert"
|
Python
|
bsd-3-clause
|
apple/coremltools,apple/coremltools,apple/coremltools,apple/coremltools
|
967ea6b083437cbe6c87b173567981e1ae41fefc
|
project/wsgi/tomodev.py
|
project/wsgi/tomodev.py
|
"""
WSGI config for project.
This module contains the WSGI application used by Django's development server
and any production WSGI deployments. It should expose a module-level variable
named ``application``. Django's ``runserver`` and ``runfcgi`` commands discover
this application via the ``WSGI_APPLICATION`` setting.
Usually you will have the standard Django WSGI application here, but it also
might make sense to replace the whole Django WSGI application with a custom one
that later delegates to the Django one. For example, you could introduce WSGI
middleware here, or combine a Django application with an application of another
framework.
"""
import os
os.environ.setdefault("DJANGO_SETTINGS_MODULE", "project.settings.tomodev")
# This application object is used by any WSGI server configured to use this
# file. This includes Django's development server, if the WSGI_APPLICATION
# setting points here.
from django.core.handlers.wsgi import WSGIHandler
application = WSGIHandler()
# Apply WSGI middleware here.
# from helloworld.wsgi import HelloWorldApplication
# application = HelloWorldApplication(application)
|
"""
WSGI config for project.
This module contains the WSGI application used by Django's development server
and any production WSGI deployments. It should expose a module-level variable
named ``application``. Django's ``runserver`` and ``runfcgi`` commands discover
this application via the ``WSGI_APPLICATION`` setting.
Usually you will have the standard Django WSGI application here, but it also
might make sense to replace the whole Django WSGI application with a custom one
that later delegates to the Django one. For example, you could introduce WSGI
middleware here, or combine a Django application with an application of another
framework.
"""
import os
import site
os.environ.setdefault("DJANGO_SETTINGS_MODULE", "project.settings.tomodev")
base_path = os.path.abspath("../..")
site.addsitedir(base_path)
site.addsitedir(os.path.join(base_path, 'virtualenv/lib/python2.6/site-packages'))
# This application object is used by any WSGI server configured to use this
# file. This includes Django's development server, if the WSGI_APPLICATION
# setting points here.
from django.core.handlers.wsgi import WSGIHandler
application = WSGIHandler()
# Apply WSGI middleware here.
# from helloworld.wsgi import HelloWorldApplication
# application = HelloWorldApplication(application)
|
Set Python path inside WSGI application
|
Set Python path inside WSGI application
|
Python
|
agpl-3.0
|
ul-fmf/projekt-tomo,ul-fmf/projekt-tomo,matijapretnar/projekt-tomo,ul-fmf/projekt-tomo,matijapretnar/projekt-tomo,ul-fmf/projekt-tomo,ul-fmf/projekt-tomo,ul-fmf/projekt-tomo,matijapretnar/projekt-tomo,matijapretnar/projekt-tomo,matijapretnar/projekt-tomo
|
2198ae847cb257d210c043bb08d52206df749a24
|
Jeeves/jeeves.py
|
Jeeves/jeeves.py
|
import discord
import asyncio
import random
import configparser
import json
def RunBot(config_file):
config = configparser.ConfigParser()
config.read(config_file)
client = discord.Client()
@client.event
async def on_ready():
print('------')
print('Logged in as %s (%s)' % (client.user.name, client.user.id))
print('------')
@client.event
async def on_message(message):
if message.channel.id == "123410749765713920":
if message.content.startswith('-knugen'):
await client.send_message(message.channel, random.choice(knugenLinks))
client.run(config['Bot']['token'])
if __name__ == "__main__":
print("Please use the start.py script in the root directory instead")
|
import discord
import asyncio
import random
import configparser
import json
def RunBot(config_file):
config = configparser.ConfigParser()
config.read(config_file)
client = discord.Client()
@client.event
async def on_ready():
print('------')
print('Logged in as %s (%s)' % (client.user.name, client.user.id))
print('------')
@client.event
async def on_message(message):
if message.channel.id == "123410749765713920":
if message.content.startswith('-knugen'):
with open('config/data.json') as data_file:
data = json.loads(data_file.read())
await client.send_message(message.channel, random.choice(data['knugenLinks']))
client.run(config['Bot']['token'])
if __name__ == "__main__":
print("Please use the start.py script in the root directory instead")
|
Change knugen command to use array in config/data.json instead of hardcoded array.
|
Change knugen command to use array in config/data.json instead of hardcoded array.
|
Python
|
mit
|
havokoc/MyManJeeves
|
b26200860337d4dba13aeafe7cfb9dff8bf181d0
|
salt/grains/nxos.py
|
salt/grains/nxos.py
|
# -*- coding: utf-8 -*-
'''
Grains for Cisco NX OS Switches Proxy minions
.. versionadded: Carbon
For documentation on setting up the nxos proxy minion look in the documentation
for :doc:`salt.proxy.nxos</ref/proxy/all/salt.proxy.nxos>`.
'''
# Import Python Libs
from __future__ import absolute_import
# Import Salt Libs
import salt.utils
import salt.modules.nxos
import logging
log = logging.getLogger(__name__)
__proxyenabled__ = ['nxos']
__virtualname__ = 'nxos'
def __virtual__():
try:
if salt.utils.is_proxy() and __opts__['proxy']['proxytype'] == 'nxos':
return __virtualname__
except KeyError:
pass
return False
def proxy_functions(proxy=None):
if proxy is None:
return {}
if proxy['nxos.initialized']() is False:
return {}
return {'nxos': proxy['nxos.grains']()}
|
# -*- coding: utf-8 -*-
'''
Grains for Cisco NX OS Switches Proxy minions
.. versionadded: 2016.11.0
For documentation on setting up the nxos proxy minion look in the documentation
for :doc:`salt.proxy.nxos</ref/proxy/all/salt.proxy.nxos>`.
'''
# Import Python Libs
from __future__ import absolute_import
# Import Salt Libs
import salt.utils
import salt.modules.nxos
import logging
log = logging.getLogger(__name__)
__proxyenabled__ = ['nxos']
__virtualname__ = 'nxos'
def __virtual__():
try:
if salt.utils.is_proxy() and __opts__['proxy']['proxytype'] == 'nxos':
return __virtualname__
except KeyError:
pass
return False
def proxy_functions(proxy=None):
if proxy is None:
return {}
if proxy['nxos.initialized']() is False:
return {}
return {'nxos': proxy['nxos.grains']()}
|
Update Carbon versionadded tags to 2016.11.0 in grains/*
|
Update Carbon versionadded tags to 2016.11.0 in grains/*
|
Python
|
apache-2.0
|
saltstack/salt,saltstack/salt,saltstack/salt,saltstack/salt,saltstack/salt
|
74728ef66fd13bfd7ad01f930114c2375e752d13
|
examples/skel.py
|
examples/skel.py
|
try:
import _path
except NameError:
pass
import pygame
import spyral
import sys
SIZE = (640, 480)
BG_COLOR = (0, 0, 0)
class Game(spyral.Scene):
"""
A Scene represents a distinct state of your game. They could be menus,
different subgames, or any other things which are mostly distinct.
A Scene should define two methods, update and render.
"""
def __init__(self):
"""
The __init__ message for a scene should set up the camera(s) for the
scene, and other structures which are needed for the scene
"""
spyral.Scene.__init__(self, SIZE)
self.register("system.quit", sys.exit)
print spyral.widgets
spyral.widgets.register('Testing', 'a')
print spyral.widgets.Testing(1,2,3)
print spyral.widgets.TextInputWidget
if __name__ == "__main__":
spyral.director.init(SIZE) # the director is the manager for your scenes
spyral.director.run(scene=Game()) # This will run your game. It will not return.
|
try:
import _path
except NameError:
pass
import pygame
import spyral
import sys
SIZE = (640, 480)
BG_COLOR = (0, 0, 0)
class Game(spyral.Scene):
"""
A Scene represents a distinct state of your game. They could be menus,
different subgames, or any other things which are mostly distinct.
A Scene should define two methods, update and render.
"""
def __init__(self):
"""
The __init__ message for a scene should set up the camera(s) for the
scene, and other structures which are needed for the scene
"""
spyral.Scene.__init__(self, SIZE)
self.register("system.quit", sys.exit)
if __name__ == "__main__":
spyral.director.init(SIZE) # the director is the manager for your scenes
spyral.director.run(scene=Game()) # This will run your game. It will not return.
|
Remove some accidentally committed code.
|
Remove some accidentally committed code.
|
Python
|
lgpl-2.1
|
platipy/spyral
|
b881247b182a45774ed494146904dcf2b1826d5e
|
sla_bot.py
|
sla_bot.py
|
import discord
import asyncio
client = discord.Client()
@client.event
async def on_ready():
print('Logged in as')
print(client.user.name)
print(client.user.id)
print('------')
@client.event
async def on_message(message):
if message.content.startswith('!test'):
await client.send_message(message.channel, 'Hello world!')
client.run('paste_token_here')
|
import asyncio
import discord
from discord.ext import commands
bot = commands.Bot(command_prefix='!', description='test')
@bot.event
async def on_ready():
print('Logged in as')
print(bot.user.name)
print(bot.user.id)
print('------')
@bot.command()
async def test():
await bot.say('Hello World!')
bot.run('paste_token_here')
|
Switch to Bot object instead of Client
|
Switch to Bot object instead of Client
Better reflects examples in discord.py project
|
Python
|
mit
|
EsqWiggles/SLA-bot,EsqWiggles/SLA-bot
|
0ce553f791ba0aac599cc0ae5c4784fece9cb3da
|
bugsnag/django/middleware.py
|
bugsnag/django/middleware.py
|
from __future__ import division, print_function, absolute_import
import bugsnag
import bugsnag.django
def is_development_server(request):
server = request.META.get('wsgi.file_wrapper', None)
if server is None:
return False
return server.__module__ == 'django.core.servers.basehttp'
class BugsnagMiddleware(object):
def __init__(self):
bugsnag.django.configure()
# pylint: disable-msg=R0201
def process_request(self, request):
if is_development_server(request):
bugsnag.configure(release_stage="development")
bugsnag.configure_request(django_request=request)
return None
# pylint: disable-msg=W0613
def process_response(self, request, response):
bugsnag.clear_request_config()
return response
def process_exception(self, request, exception):
try:
bugsnag.auto_notify(exception)
except Exception as exc:
bugsnag.log("Error in exception middleware: %s" % exc)
bugsnag.clear_request_config()
return None
|
from __future__ import division, print_function, absolute_import
import bugsnag
import bugsnag.django
class BugsnagMiddleware(object):
def __init__(self):
bugsnag.django.configure()
# pylint: disable-msg=R0201
def process_request(self, request):
bugsnag.configure_request(django_request=request)
return None
# pylint: disable-msg=W0613
def process_response(self, request, response):
bugsnag.clear_request_config()
return response
def process_exception(self, request, exception):
try:
bugsnag.auto_notify(exception)
except Exception as exc:
bugsnag.log("Error in exception middleware: %s" % exc)
bugsnag.clear_request_config()
return None
|
Remove obsolete check for development
|
Remove obsolete check for development
|
Python
|
mit
|
bugsnag/bugsnag-python,bugsnag/bugsnag-python,overplumbum/bugsnag-python,overplumbum/bugsnag-python
|
e4d746ba6c5b842529c9dafb31a90bdd31fee687
|
performanceplatform/__init__.py
|
performanceplatform/__init__.py
|
# Namespace package: https://docs.python.org/2/library/pkgutil.html
try:
import pkg_resources
pkg_resources.declare_namespace(__name__)
except ImportError:
from pkgutil import extend_path
__path__ = extend_path(__path__, __name__)
|
__import__('pkg_resources').declare_namespace(__name__)
|
Fix namespacing for PyPi installs
|
Fix namespacing for PyPi installs
See https://github.com/alphagov/performanceplatform-client/pull/5
|
Python
|
mit
|
alphagov/performanceplatform-collector,alphagov/performanceplatform-collector,alphagov/performanceplatform-collector
|
4b340e0712956ea44eace7382dd743890958a0fd
|
widgets/card.py
|
widgets/card.py
|
# -*- coding: utf-8 -*-
from flask import render_template
from models.person import Person
def card(person_or_id, detailed=False, small=False):
if isinstance(person_or_id, Person):
person = person_or_id
else:
person = Person.query.filter_by(id=person_or_id).first()
return render_template('widgets/card.html', person=person, detailed=detailed, small=small)
|
# -*- coding: utf-8 -*-
from flask import render_template
from models.person import Person
def card(person_or_id, **kwargs):
if isinstance(person_or_id, Person):
person = person_or_id
else:
person = Person.query.filter_by(id=person_or_id).first()
return render_template('widgets/card.html', person=person, **kwargs)
|
Revert "Fix a bug in caching"
|
Revert "Fix a bug in caching"
This reverts commit 2565df456ecb290f620ce4dadca19c76b0eeb1af.
Conflicts:
widgets/card.py
|
Python
|
apache-2.0
|
teampopong/pokr.kr,teampopong/pokr.kr,teampopong/pokr.kr,teampopong/pokr.kr
|
fa75cdb0114d86b626a77ea19897abd532fd4aeb
|
src/hack4lt/forms.py
|
src/hack4lt/forms.py
|
from django import forms
from django.contrib.auth import authenticate
from django.utils.translation import ugettext_lazy as _
from hack4lt.models import Hacker
class RegistrationForm(forms.ModelForm):
class Meta:
model = Hacker
fields = ('username', 'first_name', 'last_name', 'email', 'repository',
'website', 'stackoverflow_user', 'description')
class LoginForm(forms.Form):
username = forms.CharField(label=_('Username'), max_length=100)
password = forms.CharField(label=_('Password'), max_length=128,
widget=forms.PasswordInput(render_value=False))
def clean(self):
cleaned_data = super(LoginForm, self).clean()
if self.errors:
return cleaned_data
user = authenticate(**cleaned_data)
if not user:
raise forms.ValidationError(_('Username or password is incorrect'))
cleaned_data['user'] = user
return cleaned_data
|
from django import forms
from django.contrib.auth import authenticate
from django.utils.translation import ugettext_lazy as _
from django.forms.util import ErrorList
from hack4lt.models import Hacker
class RegistrationForm(forms.ModelForm):
password = forms.CharField(label=_('Password'), max_length=128, min_length=6,
widget=forms.PasswordInput(render_value=False))
password_repeat = forms.CharField(label=_('Repeat Password'), min_length=6,
max_length=128, widget=forms.PasswordInput(render_value=False))
class Meta:
model = Hacker
fields = ('username', 'password', 'password_repeat', 'first_name',
'last_name', 'email', 'repository', 'website',
'stackoverflow_user', 'description')
def is_valid(self):
valid = super(RegistrationForm, self).is_valid()
if not valid:
return valid
first_password = self.cleaned_data.get('password')
repeat_password = self.cleaned_data.get('password_repeat')
if first_password == repeat_password:
return True
errors = self._errors.setdefault('password', ErrorList())
errors.append(u'Passwords do not match')
return False
class LoginForm(forms.Form):
username = forms.CharField(label=_('Username'), max_length=100)
password = forms.CharField(label=_('Password'), max_length=128,
widget=forms.PasswordInput(render_value=False))
def clean(self):
cleaned_data = super(LoginForm, self).clean()
if self.errors:
return cleaned_data
user = authenticate(**cleaned_data)
if not user:
raise forms.ValidationError(_('Username or password is incorrect'))
cleaned_data['user'] = user
return cleaned_data
|
Add password and password_repeat fields to registration form.
|
Add password and password_repeat fields to registration form.
|
Python
|
bsd-3-clause
|
niekas/Hack4LT
|
640aff6378b6f47d68645822fc5c2bb3fd737710
|
salt/modules/test_virtual.py
|
salt/modules/test_virtual.py
|
# -*- coding: utf-8 -*-
'''
Module for running arbitrary tests with a __virtual__ function
'''
from __future__ import absolute_import
def __virtual__():
return False
def test():
return True
|
# -*- coding: utf-8 -*-
'''
Module for running arbitrary tests with a __virtual__ function
'''
from __future__ import absolute_import
def __virtual__():
return False
def ping():
return True
|
Fix mis-naming from pylint cleanup
|
Fix mis-naming from pylint cleanup
|
Python
|
apache-2.0
|
saltstack/salt,saltstack/salt,saltstack/salt,saltstack/salt,saltstack/salt
|
467e8e4d8113a8f6473d7f82d86d5401053362b8
|
scripts/gen-release-notes.py
|
scripts/gen-release-notes.py
|
"""
Generates the release notes for the latest release, in Markdown.
Convert CHANGELOG.rst to Markdown, and extracts just the latest release.
Writes to ``scripts/latest-release-notes.md``, which can be
used with https://github.com/softprops/action-gh-release.
"""
from pathlib import Path
import pypandoc
this_dir = Path(__file__).parent
rst_text = (this_dir.parent / "CHANGELOG.rst").read_text(encoding="UTF-8")
md_text = pypandoc.convert_text(
rst_text, "md", format="rst", extra_args=["--wrap=preserve"]
)
output_lines = []
first_heading_found = False
for line in md_text.splitlines():
if line.startswith("# "):
if first_heading_found:
break
first_heading_found = True
output_lines.append(line)
output_fn = this_dir / "latest-release-notes.md"
output_fn.write_text("\n".join(output_lines), encoding="UTF-8")
print(output_fn, "generated.")
|
"""
Generates the release notes for the latest release, in Markdown.
Convert CHANGELOG.rst to Markdown, and extracts just the latest release.
Writes to ``scripts/latest-release-notes.md``, which can be
used with https://github.com/softprops/action-gh-release.
"""
from pathlib import Path
import pypandoc
this_dir = Path(__file__).parent
rst_text = (this_dir.parent / "CHANGELOG.rst").read_text(encoding="UTF-8")
md_text = pypandoc.convert_text(
rst_text, "md", format="rst", extra_args=["--wrap=preserve"]
)
output_lines = []
first_heading_found = False
for line in md_text.splitlines():
if line.startswith("# "):
if first_heading_found:
break
first_heading_found = True
else:
output_lines.append(line)
output_fn = this_dir / "latest-release-notes.md"
output_fn.write_text("\n".join(output_lines), encoding="UTF-8")
print(output_fn, "generated.")
|
Remove release title from the GitHub release notes body
|
Remove release title from the GitHub release notes body
|
Python
|
mit
|
pytest-dev/pytest-mock
|
ac33c7fcee74053dae6edfdd4596bfe03098711d
|
waptpkg.py
|
waptpkg.py
|
# -*- coding: utf-8 -*-
import os
import waptpackage
from waptcrypto import SSLCABundle,SSLCertificate,SSLPrivateKey
def download(remote, path, pkg):
"""Downloads package"""
if not pkg.package:
return False
res = remote.download_packages(pkg, path)
if res['errors']:
return False
pkg_path = res['downloaded'] and res['downloaded'][0] or res['skipped'][0]
if not pkg_path:
return False
return pkg_path
def check_signature(pkg):
"""Check package signature if /etc/ssl/certs exists"""
if not os.path.exists('/etc/ssl/certs'):
return True
if not waptpackage.PackageEntry(waptfile=pkg.localpath).check_control_signature(SSLCABundle('/etc/ssl/certs')):
return False
return True
def overwrite_signature(pkg):
"""Overwrite imported package signature"""
cert_file = os.environ.get('WAPT_CERT')
key_file = os.environ.get('WAPT_KEY')
password = os.environ.get('WAPT_PASSWD')
if not (cert_file and key_file and password):
return False
crt = SSLCertificate(cert_file)
key = SSLPrivateKey(key_file, password=password)
return pkg.sign_package(crt, key)
def hash(pkg):
"""Creates a hash based on package properties"""
return "%s:%s" % (pkg.package, pkg.architecture)
|
# -*- coding: utf-8 -*-
import os
import waptpackage
from waptcrypto import SSLCABundle,SSLCertificate,SSLPrivateKey
def download(remote, path, pkg):
"""Downloads package"""
if not pkg.package:
return False
res = remote.download_packages(pkg, path)
if res['errors']:
return False
pkg_path = res['downloaded'] and res['downloaded'][0] or res['skipped'][0]
if not pkg_path:
return False
return pkg_path
def check_signature(pkg):
"""Check package signature if /etc/ssl/certs exists"""
if not os.path.exists('/etc/ssl/certs'):
return True
if not waptpackage.PackageEntry(waptfile=pkg.localpath).check_control_signature(SSLCABundle('/etc/ssl/certs')):
return False
return True
def overwrite_signature(pkg):
"""Overwrite imported package signature"""
cert_file = os.environ.get('WAPT_CERT')
key_file = os.environ.get('WAPT_KEY')
password = os.environ.get('WAPT_PASSWD')
if not (cert_file and key_file and password):
return False
crt = SSLCertificate(cert_file)
key = SSLPrivateKey(key_file, password=password)
return pkg.sign_package(crt, key)
def hash(pkg):
"""Creates a hash based on package properties"""
return "%s:%s:%s" % (pkg.package, pkg.architecture, pkg.locale)
|
Include locale in package hash
|
Include locale in package hash
|
Python
|
mit
|
jf-guillou/wapt-scripts
|
13ba6bf5c12c46aa43c0060d40458fe453df9c33
|
ydf/yaml_ext.py
|
ydf/yaml_ext.py
|
"""
ydf/yaml_ext
~~~~~~~~~~~~
Contains extensions to existing YAML functionality.
"""
import collections
from ruamel import yaml
from ruamel.yaml import resolver
class OrderedLoader(yaml.Loader):
"""
Extends the default YAML loader to use :class:`~collections.OrderedDict` for mapping
types.
"""
def __init__(self, *args, **kwargs):
super(OrderedLoader, self).__init__(*args, **kwargs)
self.add_constructor(yaml.resolver.BaseResolver.DEFAULT_MAPPING_TAG, self.construct_ordered_mapping)
@staticmethod
def construct_ordered_mapping(loader, node):
loader.flatten_mapping(node)
return collections.OrderedDict(loader.construct_pairs(node))
def load(stream):
"""
Load the given YAML string.
"""
return yaml.load(stream, OrderedLoader)
|
"""
ydf/yaml_ext
~~~~~~~~~~~~
Contains extensions to existing YAML functionality.
"""
import collections
from ruamel import yaml
from ruamel.yaml import resolver
class OrderedRoundTripLoader(yaml.RoundTripLoader):
"""
Extends the default round trip YAML loader to use :class:`~collections.OrderedDict` for mapping
types.
"""
def __init__(self, *args, **kwargs):
super(OrderedRoundTripLoader, self).__init__(*args, **kwargs)
self.add_constructor(yaml.resolver.BaseResolver.DEFAULT_MAPPING_TAG, self.construct_ordered_mapping)
@staticmethod
def construct_ordered_mapping(loader, node):
loader.flatten_mapping(node)
return collections.OrderedDict(loader.construct_pairs(node))
def load_all(stream):
"""
Load all documents within the given YAML string.
:param stream: A valid YAML stream.
:return: Generator that yields each document found in the YAML stream.
"""
return yaml.load_all(stream, OrderedRoundTripLoader)
|
Switch to round trip loader to support multiple documents.
|
Switch to round trip loader to support multiple documents.
|
Python
|
apache-2.0
|
ahawker/ydf
|
9b586b953bfe3c94adb40d0a804de3d46fca1887
|
httpie/config.py
|
httpie/config.py
|
import os
__author__ = 'jakub'
CONFIG_DIR = os.path.expanduser('~/.httpie')
|
import os
from requests.compat import is_windows
__author__ = 'jakub'
CONFIG_DIR = (os.path.expanduser('~/.httpie') if not is_windows else
os.path.expandvars(r'%APPDATA%\\httpie'))
|
Use %APPDATA% for data on Windows.
|
Use %APPDATA% for data on Windows.
|
Python
|
bsd-3-clause
|
codingjoe/httpie,konopski/httpie,Bogon/httpie,fontenele/httpie,aredo/httpie,GrimDerp/httpie,vietlq/httpie,paran0ids0ul/httpie,gnagel/httpie,fontenele/httpie,lingtalfi/httpie,rschmidtz/httpie,alexeikabak/httpie,konopski/httpie,PKRoma/httpie,GrimDerp/httpie,PKRoma/httpie,bright-sparks/httpie,marklap/httpie,fritaly/httpie,rgordeev/httpie,kaushik94/httpie,paran0ids0ul/httpie,mblayman/httpie,saisai/httpie,vietlq/httpie,zerin108/httpie,ardydedase/httpie,keita1314/httpie,aredo/httpie,hoatle/httpie,meigrafd/httpie,jakubroztocil/httpie,alex-bretet/httpie,alfcrisci/httpie,sofianhw/httpie,codingjoe/httpie,JPWKU/httpie,gnagel/httpie,insionng/httpie,zerodark/httpie,bright-sparks/httpie,alexeikabak/httpie,Bogon/httpie,jkbrzt/httpie,avtoritet/httpie,lk1ngaa7/httpie,fritaly/httpie,bgarrels/httpie,HackerTool/httpie,rschmidtz/httpie,zerin108/httpie,marklap/httpie,HackerTool/httpie,danieldc/httpie,danieldc/httpie,guiquanz/httpie,chaos33/httpie,jcrumb/httpie,Batterfii/httpie,a-x-/httpie,bitcoinfees/two1-httpie,kevinlondon/httpie,rusheel/httpie,alex-bretet/httpie,insionng/httpie,kevinlondon/httpie,rgordeev/httpie,hoatle/httpie,Batterfii/httpie,bitcoinfees/two1-httpie,jakubroztocil/httpie,alfcrisci/httpie,MiteshShah/httpie,lingtalfi/httpie,ardydedase/httpie,normabuttz/httpie,lk1ngaa7/httpie,jakubroztocil/httpie,guiquanz/httpie,bgarrels/httpie,whitefoxx/httpie,jkbrzt/httpie,wandec/first,meigrafd/httpie,jkbrzt/httpie,mblayman/httpie,zerodark/httpie,sofianhw/httpie,avtoritet/httpie,jcrumb/httpie,tylertebbs20/Practice-httpie,normabuttz/httpie,a-x-/httpie,whitefoxx/httpie,tylertebbs20/Practice-httpie,saisai/httpie,rusheel/httpie,JPWKU/httpie,MiteshShah/httpie,keita1314/httpie
|
085edf28b2e70552789407e16ca83faf78313672
|
version.py
|
version.py
|
major = 0
minor=0
patch=0
branch="dev"
timestamp=1376579871.17
|
major = 0
minor=0
patch=25
branch="master"
timestamp=1376610207.69
|
Tag commit for v0.0.25-master generated by gitmake.py
|
Tag commit for v0.0.25-master generated by gitmake.py
|
Python
|
mit
|
ryansturmer/gitmake
|
09d85cf39fd8196b26b357ee3f0b9fbb67770014
|
flask_jq.py
|
flask_jq.py
|
from flask import Flask, jsonify, render_template, request
app = Flask(__name__)
@app.route('/_add_numbers')
def add_numbers():
''' Because numbers must be added server side '''
a = request.args.get('a', 0, type=int)
b = request.args.get('b', 0, type=int)
return jsonify(result=a + b)
@app.route('/')
def index():
return render_template('index.html')
|
from flask import Flask, jsonify, render_template, request
app = Flask(__name__)
@app.route('/_add_numbers')
def add_numbers():
''' Because numbers must be added server side '''
a = request.args.get('a', 0, type=int)
b = request.args.get('b', 0, type=int)
return jsonify(result=a + b)
@app.route('/')
def index():
return render_template('index.html')
if __name__ == '__main__':
app.run('0.0.0.0',port=4000)
|
Add app run on main
|
Add app run on main
|
Python
|
mit
|
avidas/flask-jquery,avidas/flask-jquery,avidas/flask-jquery
|
c5ba874987b2e788ae905a1a84e7f2575ff9f991
|
conman/redirects/models.py
|
conman/redirects/models.py
|
from django.core.exceptions import ValidationError
from django.db import models
from django.utils.translation import ugettext_lazy as _
from conman.routes.models import Route
from . import views
class RouteRedirect(Route):
"""
When `route` is browsed to, browser should be redirected to `target`.
This model holds the data required to make that connection.
"""
target = models.ForeignKey('routes.Route', related_name='+')
permanent = models.BooleanField(default=False, blank=True)
view = views.RouteRedirectView.as_view()
def clean(self):
"""Forbid setting target equal to self."""
if self.target_id == self.route_ptr_id:
error = {'target': _('A RouteRedirect cannot redirect to itself.')}
raise ValidationError(error)
def save(self, *args, **kwargs):
"""Validate the Redirect before saving."""
self.clean()
return super().save(*args, **kwargs)
class URLRedirect(Route):
"""A `Route` that redirects to an arbitrary URL."""
target = models.URLField(max_length=2000)
permanent = models.BooleanField(default=False, blank=True)
view = views.URLRedirectView.as_view()
|
from django.core.exceptions import ValidationError
from django.db import models
from django.utils.translation import ugettext_lazy as _
from conman.routes.models import Route
from . import views
class RouteRedirect(Route):
"""
When `route` is browsed to, browser should be redirected to `target`.
This model holds the data required to make that connection.
"""
target = models.ForeignKey('routes.Route', related_name='+')
permanent = models.BooleanField(default=False)
view = views.RouteRedirectView.as_view()
def clean(self):
"""Forbid setting target equal to self."""
if self.target_id == self.route_ptr_id:
error = {'target': _('A RouteRedirect cannot redirect to itself.')}
raise ValidationError(error)
def save(self, *args, **kwargs):
"""Validate the Redirect before saving."""
self.clean()
return super().save(*args, **kwargs)
class URLRedirect(Route):
"""A `Route` that redirects to an arbitrary URL."""
target = models.URLField(max_length=2000)
permanent = models.BooleanField(default=False)
view = views.URLRedirectView.as_view()
|
Remove explicit default from BooleanField
|
Remove explicit default from BooleanField
|
Python
|
bsd-2-clause
|
Ian-Foote/django-conman,meshy/django-conman,meshy/django-conman
|
f5d56b0c54af414f02721a1a02a0eaf80dbba898
|
client/python/unrealcv/util.py
|
client/python/unrealcv/util.py
|
import numpy as np
import PIL
from io import BytesIO
# StringIO module is removed in python3, use io module
def read_png(res):
import PIL.Image
img = PIL.Image.open(BytesIO(res))
return np.asarray(img)
def read_npy(res):
# res is a binary buffer
return np.load(BytesIO(res))
|
import numpy as np
import PIL.Image
from io import BytesIO
# StringIO module is removed in python3, use io module
def read_png(res):
img = None
try:
PIL_img = PIL.Image.open(BytesIO(res))
img = np.asarray(PIL_img)
except:
print('Read png can not parse response %s' % str(res[:20]))
return img
def read_npy(res):
# res is a binary buffer
arr = None
try:
arr = np.load(BytesIO(res))
except:
print('Read npy can not parse response %s' % str(res[:20]))
return arr
|
Handle exceptions in read_png and read_npy.
|
Handle exceptions in read_png and read_npy.
|
Python
|
mit
|
unrealcv/unrealcv,unrealcv/unrealcv,unrealcv/unrealcv,unrealcv/unrealcv,unrealcv/unrealcv
|
95f0ae5e04df6e5ce454b15551133caacfd44536
|
services/netflix.py
|
services/netflix.py
|
import foauth.providers
class Netflix(foauth.providers.OAuth1):
# General info about the provider
provider_url = 'https://www.netflix.com/'
docs_url = 'http://developer.netflix.com/docs'
# URLs to interact with the API
request_token_url = 'http://api.netflix.com/oauth/request_token'
authorize_url = 'https://api-user.netflix.com/oauth/login'
access_token_url = 'http://api.netflix.com/oauth/access_token'
api_domains = ['api-public.netflix.com', 'api.netflix.com']
available_permissions = [
(None, 'read and manage your queue'),
]
|
import foauth.providers
from oauthlib.oauth1.rfc5849 import SIGNATURE_TYPE_QUERY
class Netflix(foauth.providers.OAuth1):
# General info about the provider
provider_url = 'https://www.netflix.com/'
docs_url = 'http://developer.netflix.com/docs'
# URLs to interact with the API
request_token_url = 'http://api.netflix.com/oauth/request_token'
authorize_url = 'https://api-user.netflix.com/oauth/login'
access_token_url = 'http://api.netflix.com/oauth/access_token'
api_domains = ['api-public.netflix.com', 'api.netflix.com']
available_permissions = [
(None, 'read and manage your queue'),
]
https = False
signature_type = SIGNATURE_TYPE_QUERY
def get_authorize_params(self, redirect_uri):
params = super(Netflix, self).get_authorize_params(redirect_uri)
params['oauth_consumer_key'] = self.client_id
return params
|
Fix token retrieval for Netflix
|
Fix token retrieval for Netflix
|
Python
|
bsd-3-clause
|
foauth/foauth.org,foauth/oauth-proxy,foauth/foauth.org,foauth/foauth.org
|
3093941ebed1f9c726a88776819ee181cdb0b869
|
piper/db/core.py
|
piper/db/core.py
|
import logbook
# Let's name this DatabaseBase. 'tis a silly name.
class DatabaseBase(object):
"""
Abstract class representing a persistance layer
"""
def __init__(self):
self.log = logbook.Logger(self.__class__.__name__)
def init(self, ns, config):
raise NotImplementedError()
class DbCLI(object):
def __init__(self, cls):
self.cls = cls
self.log = logbook.Logger(self.__class__.__name__)
def compose(self, parser): # pragma: nocover
db = parser.add_parser('db', help='Perform database tasks')
sub = db.add_subparsers(help='Database commands', dest="db_command")
sub.add_parser('init', help='Do the initial setup of the database')
return 'db', self.run
def run(self, ns, config):
self.cls.init(ns, config)
return 0
|
import logbook
class LazyDatabaseMixin(object):
"""
A mixin class that gives the subclass lazy access to the database layer
The lazy attribute self.db is added, and the database class is gotten from
self.config, and an instance is made and returned.
"""
_db = None
@property
def db(self):
assert self.config is not None, \
'Database accessed before self.config was set.'
if self._db is None:
self._db = self.config.get_database()
self._db.setup()
return self._db
# Let's name this DatabaseBase. 'tis a silly name.
class DatabaseBase(object):
"""
Abstract class representing a persistance layer
"""
def __init__(self):
self.log = logbook.Logger(self.__class__.__name__)
def init(self, ns, config):
raise NotImplementedError()
class DbCLI(object):
def __init__(self, cls):
self.cls = cls
self.log = logbook.Logger(self.__class__.__name__)
def compose(self, parser): # pragma: nocover
db = parser.add_parser('db', help='Perform database tasks')
sub = db.add_subparsers(help='Database commands', dest="db_command")
sub.add_parser('init', help='Do the initial setup of the database')
return 'db', self.run
def run(self, ns, config):
self.cls.init(ns, config)
return 0
|
Add first iteration of LazyDatabaseMixin()
|
Add first iteration of LazyDatabaseMixin()
|
Python
|
mit
|
thiderman/piper
|
4de82c9a0737c079634a87d0ea358fba7840a419
|
sesame/test_settings.py
|
sesame/test_settings.py
|
from __future__ import unicode_literals
AUTHENTICATION_BACKENDS = [
"django.contrib.auth.backends.ModelBackend",
"sesame.backends.ModelBackend",
]
CACHES = {"default": {"BACKEND": "django.core.cache.backends.locmem.LocMemCache"}}
DATABASES = {"default": {"ENGINE": "django.db.backends.sqlite3"}}
INSTALLED_APPS = [
"django.contrib.auth",
"django.contrib.contenttypes",
"sesame",
"sesame.test_app",
]
LOGGING_CONFIG = None
MIDDLEWARE = [
"django.contrib.sessions.middleware.SessionMiddleware",
"django.contrib.auth.middleware.AuthenticationMiddleware",
]
ROOT_URLCONF = "sesame.test_urls"
SECRET_KEY = "Anyone who finds an URL will be able to log in. Seriously."
SESSION_ENGINE = "django.contrib.sessions.backends.cache"
TEMPLATES = [{"BACKEND": "django.template.backends.django.DjangoTemplates"}]
|
from __future__ import unicode_literals
AUTHENTICATION_BACKENDS = [
"django.contrib.auth.backends.ModelBackend",
"sesame.backends.ModelBackend",
]
CACHES = {"default": {"BACKEND": "django.core.cache.backends.locmem.LocMemCache"}}
DATABASES = {"default": {"ENGINE": "django.db.backends.sqlite3"}}
INSTALLED_APPS = [
"django.contrib.auth",
"django.contrib.contenttypes",
"sesame",
"sesame.test_app",
]
LOGGING_CONFIG = None
MIDDLEWARE = [
"django.contrib.sessions.middleware.SessionMiddleware",
"django.contrib.auth.middleware.AuthenticationMiddleware",
]
PASSWORD_HASHERS = ["django.contrib.auth.hashers.SHA1PasswordHasher"]
ROOT_URLCONF = "sesame.test_urls"
SECRET_KEY = "Anyone who finds an URL will be able to log in. Seriously."
SESSION_ENGINE = "django.contrib.sessions.backends.cache"
TEMPLATES = [{"BACKEND": "django.template.backends.django.DjangoTemplates"}]
|
Use a fast password hasher for tests.
|
Use a fast password hasher for tests.
Speed is obviously more important than security in tests.
|
Python
|
bsd-3-clause
|
aaugustin/django-sesame,aaugustin/django-sesame
|
cdae77dee9888d6d6094566747650bf80d631f03
|
station.py
|
station.py
|
"""Creates the station class"""
#import ask_user from ask_user
#import int_check from int_check
#import reasonable_check from reasonable_check
class Station:
"""
Each train station is an instance of the Station class.
Methods:
__init__: creates a new stations
total_station_pop: calculates total station population
ask_user(prompt, lower_range, upper_range): function to get input, maybe it should live
somewhere else?
"""
def __init__(self, capacity, escalators, train_wait, travelors_arriving, travelors_departing):
self.capacity = user.says("Enter the max capacity of the station between" lower "and" upper)
self.escalators = user.says("Enter the number of escalators in the station between" lower "and" upper)
self.train_wait = user.says("Enter the wait time between trains in seconds between" lower "and" upper)
self.travelors_arriving = user.says("How many people just exited the train? between" lower "and" upper)
self.travelors_departing = user.says("How many people are waiting for the train? between" lower "and" upper)
|
"""Creates the station class"""
#import request_integer_in_range from request_integer_in_range
class Station:
"""
Each train station is an instance of the Station class.
Methods:
__init__: creates a new stations
request_integer_in_range : requests an integer in a range
"""
def __init__(self, capacity, escalators, train_wait, travelors_arriving, travelors_departing):
self.capacity = request_integer_in_range("Enter the station capacity between 10 and 10000: ", 10, 10000)
self.escalators = request_integer_in_range("Enter an odd number of escalators between 1 and 7: ", 1, 7)
self.train_wait = request_integer_in_range("Enter the wait time between trains in seconds between 60 and 1800 ", 60, 1800)
self.travelors_arriving = request_integer_in_range("Enter the number of people exiting the train between 1 and 500: ", 1, 500)
self.travelors_departing = request_integer_in_range("Enter the number of people waiting for the train between 1 and 500: ", 1, 500)
|
Integrate integer test function into instantiation
|
Integrate integer test function into instantiation
Ref #23
|
Python
|
mit
|
ForestPride/rail-problem
|
9ea05a80114237a87af73e91cb929686235baa3e
|
lib/rpnpy/__init__.py
|
lib/rpnpy/__init__.py
|
import sys
import ctypes as _ct
if sys.version_info < (3,):
integer_types = (int, long,)
range = xrange
else:
integer_types = (int,)
long = int
# xrange = range
C_WCHAR2CHAR = lambda x: bytes(str(x).encode('ascii'))
C_WCHAR2CHAR.__doc__ = 'Convert str to bytes'
C_CHAR2WCHAR = lambda x: str(x.decode('ascii'))
C_CHAR2WCHAR.__doc__ = 'Convert bytes to str'
C_MKSTR = lambda x: _ct.create_string_buffer(C_WCHAR2CHAR(x))
C_MKSTR.__doc__ = 'alias to ctypes.create_string_buffer, make sure bytes are provided'
|
import sys
import ctypes as _ct
if sys.version_info < (3,):
integer_types = (int, long,)
range = xrange
else:
integer_types = (int,)
long = int
range = range
C_WCHAR2CHAR = lambda x: bytes(str(x).encode('ascii'))
C_WCHAR2CHAR.__doc__ = 'Convert str to bytes'
C_CHAR2WCHAR = lambda x: str(x.decode('ascii'))
C_CHAR2WCHAR.__doc__ = 'Convert bytes to str'
C_MKSTR = lambda x: _ct.create_string_buffer(C_WCHAR2CHAR(x))
C_MKSTR.__doc__ = 'alias to ctypes.create_string_buffer, make sure bytes are provided'
|
Add missing rpnpy.range reference for Python 3.
|
Add missing rpnpy.range reference for Python 3.
Signed-off-by: Stephane_Chamberland <[email protected]>
|
Python
|
lgpl-2.1
|
meteokid/python-rpn,meteokid/python-rpn,meteokid/python-rpn,meteokid/python-rpn
|
fff0b4af89e02ff834221ef056b7dcb979dc6cd7
|
webpay/webpay.py
|
webpay/webpay.py
|
from .api import Account, Charges, Customers
import requests
class WebPay:
def __init__(self, key, api_base = 'https://api.webpay.jp/v1'):
self.key = key
self.api_base = api_base
self.account = Account(self)
self.charges = Charges(self)
self.customers = Customers(self)
def post(self, path, params):
r = requests.post(self.api_base + path, auth = (self.key, ''), params = params)
return r.json()
def get(self, path, params = {}):
r = requests.get(self.api_base + path, auth = (self.key, ''), params = params)
return r.json()
def delete(self, path, params = {}):
r = requests.delete(self.api_base + path, auth = (self.key, ''), params = params)
return r.json()
|
from .api import Account, Charges, Customers
import requests
import json
class WebPay:
def __init__(self, key, api_base = 'https://api.webpay.jp/v1'):
self.key = key
self.api_base = api_base
self.account = Account(self)
self.charges = Charges(self)
self.customers = Customers(self)
def post(self, path, params):
r = requests.post(self.api_base + path, auth = (self.key, ''), data = json.dumps(params))
return r.json()
def get(self, path, params = {}):
r = requests.get(self.api_base + path, auth = (self.key, ''), params = params)
return r.json()
def delete(self, path, params = {}):
r = requests.delete(self.api_base + path, auth = (self.key, ''), data = json.dumps(params))
return r.json()
|
Use JSON for other than GET request
|
Use JSON for other than GET request
Because internal dict parameters is not handled as expected.
>>> payload = {'key1': 'value1', 'key2': 'value2', 'set': {'a': 'x', 'b': 'y'}}
>>> r = requests.post("http://httpbin.org/post", data=payload)
>>> r.json()
{...
'form': {'key2': 'value2', 'key1': 'value1', 'set': ['a', 'b']}
...}
|
Python
|
mit
|
yamaneko1212/webpay-python
|
b67617abe1e8530523da7231a9d74283935a1bb7
|
htext/ja/utils.py
|
htext/ja/utils.py
|
# -*- coding: utf-8 -*-
from __future__ import unicode_literals
import re
import six
BASIC_LATIN_RE = re.compile(r'[\u0021-\u007E]')
WHITESPACE_RE = re.compile("[\s]+", re.UNICODE)
def force_text(value):
if isinstance(value, six.text_type):
return value
elif isinstance(value, six.string_types):
return six.b(value).decode()
else:
value = str(value)
return value if isinstance(value, six.text_type) else value.decode()
def basic_latin_to_fullwidth(value):
"""
基本ラテン文字を全角に変換する
U+0021..U+007FはU+FF01..U+FF5Eに対応しているので
コードポイントに差分の0xFEE0を足す
"""
_value = value.replace(' ', '\u3000')
return BASIC_LATIN_RE.sub(lambda x: unichr(ord(x.group(0)) + 0xFEE0), _value)
def aggregate_whitespace(value):
return ' '.join(WHITESPACE_RE.split(value))
|
# -*- coding: utf-8 -*-
from __future__ import unicode_literals
import re
import six
BASIC_LATIN_RE = re.compile(r'[\u0021-\u007E]')
WHITESPACE_RE = re.compile("[\s]+", re.UNICODE)
def force_text(value):
if isinstance(value, six.text_type):
return value
elif isinstance(value, six.string_types):
return six.b(value).decode('utf-8')
else:
value = str(value)
return value if isinstance(value, six.text_type) else value.decode('utf-8')
def basic_latin_to_fullwidth(value):
"""
基本ラテン文字を全角に変換する
U+0021..U+007FはU+FF01..U+FF5Eに対応しているので
コードポイントに差分の0xFEE0を足す
"""
_value = value.replace(' ', '\u3000')
return BASIC_LATIN_RE.sub(lambda x: unichr(ord(x.group(0)) + 0xFEE0), _value)
def aggregate_whitespace(value):
return ' '.join(WHITESPACE_RE.split(value))
|
Fix UnicodeDecodeError on the environments where the default encoding is ascii
|
Fix UnicodeDecodeError on the environments where the default encoding is ascii
|
Python
|
mit
|
hunza/htext
|
0e7fdc409c17870ada40f43f72b9b20b7f490519
|
d_parser/helpers/get_body.py
|
d_parser/helpers/get_body.py
|
def get_body(grab, encoding='cp1251', bom=False, skip_errors=True, fix_spec_chars=True):
return grab.doc.convert_body_to_unicode(grab.doc.body, bom, encoding, skip_errors, fix_spec_chars)
|
# TODO: remove useless params
def get_body(grab, encoding='cp1251', bom=False, skip_errors=True, fix_spec_chars=True):
return grab.doc.body.decode('utf-8', 'ignore')
|
Rework get body text method
|
Rework get body text method
|
Python
|
mit
|
Holovin/D_GrabDemo
|
68aefd4c1bc682dc04721f5572ab21b609e1818f
|
manage.py
|
manage.py
|
import os
from app import create_app, db
from app.models import User, Category
from flask_script import Manager
from flask_migrate import Migrate, MigrateCommand
app = create_app(os.getenv('FLASK_CONFIG') or 'default')
manager = Manager(app)
migrate = Migrate(app, db)
manager.add_command('db', MigrateCommand)
#pylint: disable-msg=E1101
@manager.command
def adduser(email, username, admin=False):
""" Register a new user"""
from getpass import getpass
password = getpass()
password2 = getpass(prompt='Confirm: ')
if password != password2:
import sys
sys.exit("Error: Passwords do not match!")
db.create_all()
category = Category.get_by_name('Almenn frétt')
if category is None:
category = Category(name='Almenn frétt', active=True)
db.session.add(category)
user = User(email=email,
username=username,
password=password,
is_admin=admin)
db.session.add(user)
db.session.commit()
print('User {0} was registered successfully!'.format(username))
if __name__ == '__main__':
manager.run()
|
import os
from app import create_app, db
from app.models import User, Category
from flask_script import Manager
from flask_migrate import Migrate, MigrateCommand
app = create_app(os.getenv('FLASK_CONFIG') or 'default')
manager = Manager(app)
migrate = Migrate(app, db)
manager.add_command('db', MigrateCommand)
#pylint: disable-msg=E1101
@manager.command
def adduser(email, username, admin=False):
""" Register a new user"""
from getpass import getpass
password = getpass()
password2 = getpass(prompt='Confirm: ')
if password != password2:
import sys
sys.exit("Error: Passwords do not match!")
db.create_all()
category = Category.get_by_name('Almenn frétt')
if category is None:
category = Category(name='Almenn frétt',
name_en='General News',
active=True)
db.session.add(category)
user = User(email=email,
username=username,
password=password,
is_admin=admin)
db.session.add(user)
db.session.commit()
print('User {0} was registered successfully!'.format(username))
if __name__ == '__main__':
manager.run()
|
Add name_en field due to 'not null' constraint on the Category table
|
Add name_en field due to 'not null' constraint on the Category table
|
Python
|
mit
|
finnurtorfa/aflafrettir.is,finnurtorfa/aflafrettir.is,finnurtorfa/aflafrettir.is,finnurtorfa/aflafrettir.is
|
c563c0deb99d3364df3650321c914164d99d32cf
|
been/source/markdowndirectory.py
|
been/source/markdowndirectory.py
|
from been.core import DirectorySource, source_registry
from hashlib import sha1
import re
import unicodedata
import time
import markdown
def slugify(value):
value = unicodedata.normalize('NFKD', unicode(value)).encode('ascii', 'ignore')
value = unicode(re.sub('[^\w\s-]', '', value).strip().lower())
return re.sub('[-\s]+', '-', value)
class MarkdownDirectory(DirectorySource):
kind = 'markdown'
def process_event(self, event):
md = markdown.Markdown(extensions=['meta'])
html = md.convert(event['content'])
event['title'] = ' '.join(md.Meta.get('title', [event['filename']]))
event['slug'] = '-'.join(md.Meta.get('slug', [slugify(event['title'])]))
event['summary'] = ' '.join(md.Meta.get('summary', [event['content'][:100]]))
if md.Meta.get('published'):
# Parse time, then convert struct_time (local) -> epoch (GMT) -> struct_time (GMT)
event['timestamp'] = time.gmtime(time.mktime(time.strptime(' '.join(md.Meta.get('published')), '%Y-%m-%d %H:%M:%S')))
event['_id'] = sha1(event['full_path'].encode('utf-8')).hexdigest()
if time.gmtime() < event['timestamp']:
return None
else:
return event
source_registry.add(MarkdownDirectory)
|
from been.core import DirectorySource, source_registry
from hashlib import sha1
import re
import unicodedata
import time
import markdown
# slugify from Django source (BSD license)
def slugify(value):
value = unicodedata.normalize('NFKD', unicode(value)).encode('ascii', 'ignore')
value = unicode(re.sub('[^\w\s-]', '', value).strip().lower())
return re.sub('[-\s]+', '-', value)
class MarkdownDirectory(DirectorySource):
kind = 'markdown'
def process_event(self, event):
md = markdown.Markdown(extensions=['meta'])
html = md.convert(event['content'])
event['title'] = ' '.join(md.Meta.get('title', [event['filename']]))
event['slug'] = '-'.join(md.Meta.get('slug', [slugify(event['title'])]))
event['summary'] = ' '.join(md.Meta.get('summary', [event['content'][:100]]))
if md.Meta.get('published'):
# Parse time, then convert struct_time (local) -> epoch (GMT) -> struct_time (GMT)
event['timestamp'] = time.gmtime(time.mktime(time.strptime(' '.join(md.Meta.get('published')), '%Y-%m-%d %H:%M:%S')))
event['_id'] = sha1(event['full_path'].encode('utf-8')).hexdigest()
if time.gmtime() < event['timestamp']:
return None
else:
return event
source_registry.add(MarkdownDirectory)
|
Add attribution to slugify function.
|
Add attribution to slugify function.
|
Python
|
bsd-3-clause
|
chromakode/been
|
8f41ff94ecfceedf14cea03e7f2ca08df380edb0
|
weight/models.py
|
weight/models.py
|
# -*- coding: utf-8 -*-
# This file is part of Workout Manager.
#
# Workout Manager is free software: you can redistribute it and/or modify
# it under the terms of the GNU Affero General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# Workout Manager is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU Affero General Public License
# along with Workout Manager. If not, see <http://www.gnu.org/licenses/>.
from django.db import models
from django.contrib.auth.models import User
from django.utils.translation import ugettext_lazy as _
class WeightEntry(models.Model):
"""Model for a weight point
"""
creation_date = models.DateField(_('Creation date'))
weight = models.FloatField(_('Weight'))
user = models.ForeignKey(User, verbose_name = _('User'))
# Metaclass to set some other properties
class Meta:
# Order by creation_date, ascending (oldest last), better for diagram
ordering = ["creation_date", ]
def __unicode__(self):
"""Return a more human-readable representation
"""
return "%s: %s kg" % (self.creation_date, self.weight)
|
# -*- coding: utf-8 -*-
# This file is part of Workout Manager.
#
# Workout Manager is free software: you can redistribute it and/or modify
# it under the terms of the GNU Affero General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# Workout Manager is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU Affero General Public License
# along with Workout Manager. If not, see <http://www.gnu.org/licenses/>.
from django.db import models
from django.contrib.auth.models import User
from django.utils.translation import ugettext_lazy as _
class WeightEntry(models.Model):
"""Model for a weight point
"""
creation_date = models.DateField(verbose_name = _('Date'))
weight = models.FloatField(verbose_name = _('Weight'))
user = models.ForeignKey(User, verbose_name = _('User'))
# Metaclass to set some other properties
class Meta:
# Order by creation_date, ascending (oldest last), better for diagram
ordering = ["creation_date", ]
def __unicode__(self):
"""Return a more human-readable representation
"""
return "%s: %s kg" % (self.creation_date, self.weight)
|
Make the verbose name for weight entries more user friendly
|
Make the verbose name for weight entries more user friendly
|
Python
|
agpl-3.0
|
rolandgeider/wger,petervanderdoes/wger,DeveloperMal/wger,petervanderdoes/wger,kjagoo/wger_stark,rolandgeider/wger,wger-project/wger,petervanderdoes/wger,wger-project/wger,kjagoo/wger_stark,DeveloperMal/wger,kjagoo/wger_stark,wger-project/wger,wger-project/wger,rolandgeider/wger,DeveloperMal/wger,DeveloperMal/wger,kjagoo/wger_stark,petervanderdoes/wger,rolandgeider/wger
|
1b0a5388c246dba1707f768e9be08b3a63503a31
|
samples/python/topology/tweepy/app.py
|
samples/python/topology/tweepy/app.py
|
from streamsx.topology.topology import *
import streamsx.topology.context
import sys
import tweets
#
# Continually stream tweets that contain
# the terms passed on the command line.
#
# python3 app.py Food GlutenFree
#
def main():
terms = sys.argv[1:]
topo = Topology("TweetsUsingTweepy")
# Event based source stream
# Each tuple is a dictionary containing
# the full tweet (converted from JSON)
ts = topo.source(tweets.tweets(terms))
# get the text of the tweet
ts = ts.transform(tweets.text)
# just print it
ts.print()
streamsx.topology.context.submit("DISTRIBUTED", topo.graph)
if __name__ == '__main__':
main()
|
from streamsx.topology.topology import *
import streamsx.topology.context
import sys
import tweets
#
# Continually stream tweets that contain
# the terms passed on the command line.
#
# python3 app.py Food GlutenFree
#
#
# Requires tweepy to be installed
#
# pip3 install tweepy
#
# http://www.tweepy.org/
#
# You must create Twitter application authentication tokens
# and set them in the mykeys.py module.
# Note this is only intended as a simple sample,
#
def main():
terms = sys.argv[1:]
topo = Topology("TweetsUsingTweepy")
# Event based source stream
# Each tuple is a dictionary containing
# the full tweet (converted from JSON)
ts = topo.source(tweets.tweets(terms))
# get the text of the tweet
ts = ts.transform(tweets.text)
# just print it
ts.print()
streamsx.topology.context.submit("DISTRIBUTED", topo.graph)
if __name__ == '__main__':
main()
|
Add some info about tweepy
|
Add some info about tweepy
|
Python
|
apache-2.0
|
IBMStreams/streamsx.topology,ddebrunner/streamsx.topology,wmarshall484/streamsx.topology,wmarshall484/streamsx.topology,ddebrunner/streamsx.topology,wmarshall484/streamsx.topology,IBMStreams/streamsx.topology,IBMStreams/streamsx.topology,ibmkendrick/streamsx.topology,ddebrunner/streamsx.topology,ibmkendrick/streamsx.topology,ibmkendrick/streamsx.topology,ibmkendrick/streamsx.topology,IBMStreams/streamsx.topology,wmarshall484/streamsx.topology,IBMStreams/streamsx.topology,ddebrunner/streamsx.topology,IBMStreams/streamsx.topology,ibmkendrick/streamsx.topology,wmarshall484/streamsx.topology,ibmkendrick/streamsx.topology,ibmkendrick/streamsx.topology,ddebrunner/streamsx.topology,wmarshall484/streamsx.topology,IBMStreams/streamsx.topology,ddebrunner/streamsx.topology,ddebrunner/streamsx.topology,wmarshall484/streamsx.topology,wmarshall484/streamsx.topology
|
c8a0aee9b68b0567adb8285c3264d244e2ed71ca
|
bnw/handlers/command_register.py
|
bnw/handlers/command_register.py
|
# -*- coding: utf-8 -*-
# from twisted.words.xish import domish
from twisted.words.protocols.jabber.xmpp_stringprep import nodeprep
from base import *
import random
import time
import bnw.core.bnw_objects as objs
def _(s, user):
return s
from uuid import uuid4
import re
@check_arg(name=USER_RE)
@defer.inlineCallbacks
def cmd_register(request, name=""):
""" Регистрация """
if request.user:
defer.returnValue(
dict(ok=False,
desc=u'You are already registered as %s' % (
request.user['name'],),
)
)
else:
name = name.lower()[:128]
if name == 'anonymous':
defer.returnValue(
dict(ok=False, desc=u'You aren''t anonymous.')
)
user = objs.User({'id': uuid4().hex,
'name': name,
'login_key': uuid4().hex,
'regdate': int(time.time()),
'jid': request.jid.userhost(),
'interface': 'redeye',
'settings': {
'servicejid': request.to.userhost()
},
})
if not (yield objs.User.find_one({'name': name})):
_ = yield user.save()
defer.returnValue(
dict(ok=True, desc='We registered you as %s.' % (name,))
)
else:
defer.returnValue(
dict(ok=True, desc='This username is already taken')
)
|
# -*- coding: utf-8 -*-
# from twisted.words.xish import domish
from twisted.words.protocols.jabber.xmpp_stringprep import nodeprep
from base import *
import random
import time
import bnw.core.bnw_objects as objs
def _(s, user):
return s
from uuid import uuid4
import re
@check_arg(name=USER_RE)
@defer.inlineCallbacks
def cmd_register(request, name=""):
""" Регистрация """
if request.user:
defer.returnValue(
dict(ok=False,
desc=u'You are already registered as %s' % (
request.user['name'],),
)
)
else:
name = name.lower()[:128]
if name == 'anonymous':
defer.returnValue(
dict(ok=False, desc=u'You aren''t anonymous.')
)
user = objs.User({'id': uuid4().hex,
'name': name,
'login_key': uuid4().hex,
'regdate': int(time.time()),
'jid': request.jid.userhost(),
'interface': 'redeye',
'settings': {
'servicejid': request.to.userhost()
},
})
if not (yield objs.User.find_one({'name': name})):
_ = yield user.save()
defer.returnValue(
dict(ok=True, desc='We registered you as %s.' % (name,))
)
else:
defer.returnValue(
dict(ok=False, desc='This username is already taken')
)
|
Make "register" return False when username is already taken
|
Make "register" return False when username is already taken
|
Python
|
bsd-2-clause
|
stiletto/bnw,ojab/bnw,ojab/bnw,stiletto/bnw,stiletto/bnw,un-def/bnw,un-def/bnw,stiletto/bnw,ojab/bnw,ojab/bnw,un-def/bnw,un-def/bnw
|
d0c3906a0af504f61f39e1bc2f0fd43a71bda747
|
sharedmock/asserters.py
|
sharedmock/asserters.py
|
from pprint import pformat
def assert_calls_equal(expected, actual):
"""
Check whether the given mock object (or mock method) calls are equal and
return a nicely formatted message.
"""
if not expected == actual:
raise_calls_differ_error(expected, actual)
def raise_calls_differ_error(expected, actual):
""""
Raise an AssertionError with pretty print format for the given expected
and actual mock calls in order to ensure consistent print style for better
readability.
"""
expected_str = pformat(expected)
actual_str = pformat(actual)
msg = '\nMock calls differ!\nExpected calls:\n%s\nActual calls:\n%s' % (expected_str,
actual_str)
raise AssertionError(msg)
def assert_calls_equal_unsorted(expected, actual):
"""
Raises an AssertionError if the two iterables do not contain the same items.
The order of the items is ignored
"""
for expected in expected:
if expected not in actual:
raise_calls_differ_error(expected, actual)
|
from pprint import pformat
def assert_calls_equal(expected, actual):
"""
Check whether the given mock object (or mock method) calls are equal and
return a nicely formatted message.
"""
if not expected == actual:
raise_calls_differ_error(expected, actual)
def raise_calls_differ_error(expected, actual):
"""
Raise an AssertionError with pretty print format for the given expected
and actual mock calls in order to ensure consistent print style for better
readability.
"""
expected_str = pformat(expected)
actual_str = pformat(actual)
msg = '\nMock calls differ!\nExpected calls:\n%s\nActual calls:\n%s' % (expected_str,
actual_str)
raise AssertionError(msg)
def assert_calls_equal_unsorted(expected, actual):
"""
Raises an AssertionError if the two iterables do not contain the same items.
The order of the items is ignored
"""
for expected in expected:
if expected not in actual:
raise_calls_differ_error(expected, actual)
|
Remove extraneous quote in asserter dockstring
|
Remove extraneous quote in asserter dockstring
|
Python
|
apache-2.0
|
elritsch/python-sharedmock
|
b8d812039051addacda3c04d2cfe657a58bc3681
|
yolk/__init__.py
|
yolk/__init__.py
|
"""yolk.
Author: Rob Cakebread <cakebread at gmail>
License : BSD
"""
__version__ = '0.7.1'
|
"""yolk.
Author: Rob Cakebread <cakebread at gmail>
License : BSD
"""
__version__ = '0.7.2'
|
Increment patch version to 0.7.2
|
Increment patch version to 0.7.2
|
Python
|
bsd-3-clause
|
myint/yolk,myint/yolk
|
14f2161efbd9c8377e6ff3675c48aba1ac0c47d5
|
API/chat/forms.py
|
API/chat/forms.py
|
import time
from django import forms
from .models import Message
from .utils import timestamp_to_datetime, datetime_to_timestamp
class MessageForm(forms.Form):
text = forms.CharField(widget=forms.Textarea)
typing = forms.BooleanField(required=False)
class MessageCreationForm(MessageForm):
username = forms.CharField(max_length=20)
datetime_start = forms.IntegerField()
def clean_datetime_start(self):
now = int(round(time.time() * 1000))
timestamp = int(self.data['datetime_start'])
if now < timestamp:
timestamp = now
self.cleaned_data['datetime_start'] = timestamp_to_datetime(timestamp)
def save(self):
self.clean_datetime_start()
message = Message.objects.create(channel=self.channel, **self.cleaned_data)
if not message.typing:
message.datetime_sent = message.datetime_start
message.save()
return message;
class MessagePatchForm(MessageForm):
datetime_sent = forms.IntegerField()
def save(self, message):
timestamp_start = datetime_to_timestamp(message.datetime_start)
timestamp_sent = int(self.cleaned_data['datetime_sent'])
if timestamp_sent < timestamp_start:
timestamp_sent = timestamp_start
message.datetime_sent = timestamp_to_datetime(timestamp_sent)
message.text = self.cleaned_data['text']
message.typing = self.cleaned_data.get('typing', False)
message.save()
|
import time
from django import forms
from .models import Message
from .utils import timestamp_to_datetime, datetime_to_timestamp
class MessageForm(forms.Form):
text = forms.CharField(widget=forms.Textarea)
typing = forms.BooleanField(required=False)
message_type = forms.CharField(widget=forms.Textarea)
class MessageCreationForm(MessageForm):
username = forms.CharField(max_length=20)
datetime_start = forms.IntegerField()
def clean_datetime_start(self):
now = int(round(time.time() * 1000))
timestamp = int(self.data['datetime_start'])
if now < timestamp:
timestamp = now
self.cleaned_data['datetime_start'] = timestamp_to_datetime(timestamp)
def save(self):
self.clean_datetime_start()
message = Message.objects.create(channel=self.channel, **self.cleaned_data)
if not message.typing:
message.datetime_sent = message.datetime_start
message.save()
return message;
class MessagePatchForm(MessageForm):
datetime_sent = forms.IntegerField()
def save(self, message):
timestamp_start = datetime_to_timestamp(message.datetime_start)
timestamp_sent = int(self.cleaned_data['datetime_sent'])
if timestamp_sent < timestamp_start:
timestamp_sent = timestamp_start
message.datetime_sent = timestamp_to_datetime(timestamp_sent)
message.text = self.cleaned_data['text']
message.typing = self.cleaned_data.get('typing', False)
message.save()
|
Add message_type as CharField in form
|
Add message_type as CharField in form
|
Python
|
mit
|
gtklocker/ting,gtklocker/ting,mbalamat/ting,mbalamat/ting,mbalamat/ting,gtklocker/ting,dionyziz/ting,gtklocker/ting,dionyziz/ting,dionyziz/ting,dionyziz/ting,mbalamat/ting
|
5733c800c10a7546228ec4562e40b2bd06c77c7e
|
models.py
|
models.py
|
from django.db import models
# Create your models here.
|
from django.db import models
from django.utils import timezone
import datetime
class Poll(models.Model):
question = models.CharField(max_length=255)
pub_date = models.DateTimeField('date published')
def __unicode__(self):
return self.question
def was_published_recently(self):
return self.pub_date >= timezone.now() - datetime.timedelta(days=1)
was_published_recently.admin_order_field = 'pub_date'
was_published_recently.boolean = True
was_published_recently.short_description = 'Published recently?'
class Choice(models.Model):
poll = models.ForeignKey(Poll)
choice_text = models.CharField(max_length=255)
votes = models.IntegerField(default=0)
def __unicode__(self):
return self.choice_text
|
Improve database model and apperance for admin site
|
Improve database model and apperance for admin site
|
Python
|
mit
|
egel/polls
|
12320653c58cd9e9a73a6d8d69073a5b64545e5b
|
tr_init.py
|
tr_init.py
|
#!flask/bin/python
import os
import sys
if sys.platform == 'win32':
pybabel = 'flask\\Scripts\\pybabel'
else:
pybabel = 'flask/bin/pybabel'
if len(sys.argv) != 2:
print "usage: tr_init <language-code>"
sys.exit(1)
os.system(pybabel + ' extract -F babel.cfg -k lazy_gettext -o messages.pot app')
os.system(pybabel + ' init -i messages.pot -d app/translations -l ' + sys.argv[1])
os.unlink('messages.pot')
|
#!flask/bin/python
import os
import sys
if sys.platform == 'win32':
pybabel = 'flask\\Scripts\\pybabel'
else:
pybabel = 'flask/bin/pybabel'
if len(sys.argv) != 2:
print("usage: tr_init <language-code>")
sys.exit(1)
os.system(pybabel + ' extract -F babel.cfg -k lazy_gettext -o messages.pot app')
os.system(pybabel + ' init -i messages.pot -d app/translations -l ' + sys.argv[1])
os.unlink('messages.pot')
|
Add parentheses to the print statement to make it Python3 compatible
|
fix: Add parentheses to the print statement to make it Python3 compatible
|
Python
|
bsd-3-clause
|
stueken/microblog,stueken/microblog
|
c0633bc60dda6b81e623795f2c65a1eb0ba5933d
|
blinkytape/blinkyplayer.py
|
blinkytape/blinkyplayer.py
|
import time
class BlinkyPlayer(object):
FOREVER = -1
def __init__(self, blinkytape):
self._blinkytape = blinkytape
def play(self, animation, num_cycles = FOREVER):
finished = self._make_finished_predicate(animation, num_cycles)
animation.begin()
while not finished():
pixels = animation.next_frame()
self._blinkytape.update(pixels)
time.sleep(animation.frame_period_sec)
animation.end()
def _make_finished_predicate(self, animation, num_cycles):
if num_cycles < 0 and num_cycles != self.FOREVER: raise ValueError
if num_cycles == self.FOREVER:
predicate = lambda: False
else:
self._num_frames = animation.frame_count * num_cycles
def predicate():
finished = self._num_frames <= 0
self._num_frames = self._num_frames - 1
return finished
return predicate
|
import time
class BlinkyPlayer(object):
FOREVER = -1
def __init__(self, blinkytape):
self._blinkytape = blinkytape
def play(self, animation, num_cycles = FOREVER):
finished = self._finished_predicate(animation, num_cycles)
animation.begin()
while not finished():
pixels = animation.next_frame()
self._blinkytape.update(pixels)
time.sleep(animation.frame_period_sec)
animation.end()
def _finished_predicate(self, animation, num_cycles):
if num_cycles < 0 and num_cycles != self.FOREVER: raise ValueError
if num_cycles == self.FOREVER:
predicate = self._forever_predicate()
else:
self._num_frames = animation.frame_count * num_cycles
predicate = self._frame_count_predicate()
return predicate
def _forever_predicate(self):
return lambda: False
def _frame_count_predicate(self):
def predicate():
finished = self._num_frames <= 0
self._num_frames = self._num_frames - 1
return finished
return predicate
|
Clean up BlinkyPlayer a little
|
Clean up BlinkyPlayer a little
|
Python
|
mit
|
jonspeicher/blinkyfun
|
5bc6f65828e9fbf9d2a5b1198a9625024fd72d6e
|
weather.py
|
weather.py
|
from pyowm.owm import OWM
from datetime import datetime, timedelta
class WeatherManager:
def __init__(self, key, lat, lon):
owm = OWM(key)
self.mgr = owm.weather_manager()
self.lat = lat
self.lon = lon
self.last_updated = None
def load_data(self):
self.data = self.mgr.one_call(lat=self.lat, lon=self.lon, exclude='minutely,hourly,daily,alerts')
self.last_updated = datetime.now()
def is_cloudy(self, threshold):
# Only update every 20 minutes at most
if not self.last_updated or datetime.now() > self.last_updated + timedelta(minutes=20):
self.load_data()
return self.data.current.clouds > threshold
|
from pyowm.owm import OWM
from datetime import datetime, timedelta
class WeatherManager:
def __init__(self, key, lat, lon):
owm = OWM(key)
self.mgr = owm.weather_manager()
self.lat = lat
self.lon = lon
self.last_updated = None
def load_data(self):
self.data = self.mgr.one_call(lat=self.lat, lon=self.lon, exclude='minutely,hourly,daily,alerts')
self.last_updated = datetime.now()
def is_cloudy(self, threshold):
# Only update every 20 minutes at most
if not self.last_updated or datetime.now() > self.last_updated + timedelta(minutes=20):
self.load_data()
return self.data.current.clouds >= threshold
|
Make cloud check evaluate greater than or equals
|
Make cloud check evaluate greater than or equals
|
Python
|
mit
|
Nosskirneh/SmartRemoteControl,Nosskirneh/SmartRemoteControl,Nosskirneh/SmartRemoteControl,Nosskirneh/SmartRemoteControl,Nosskirneh/SmartRemoteControl
|
027e78f3e88a17e05881259d1f29d472b02d0d3a
|
doc/source/scripts/titles.py
|
doc/source/scripts/titles.py
|
import shutil
import os
import re
work = os.getcwd()
found = []
regex = re.compile(r'pydarkstar\.(.*)\.rst')
for root, dirs, files in os.walk(work):
for f in files:
m = regex.match(f)
if m:
found.append((root, f))
for root, f in found:
path = os.path.join(root, f)
with open(path, 'r') as handle:
lines = handle.readlines()
with open(path, 'w') as handle:
for i, line in enumerate(lines):
if i == 0:
line = re.sub(r'\s+package$', '', line)
line = re.sub(r'\s+module$', '', line)
line = re.sub(r'^pydarkstar\.', '', line)
#print('{:2d} {}'.format(i, line.rstrip()))
handle.write(line)
#print('')
# fix main file
with open('pydarkstar.rst', 'r') as handle:
lines = handle.readlines()
z = 0
with open('pydarkstar.rst', 'w') as handle:
for i, line in enumerate(lines):
if i == 0:
line = re.sub(r'\s+package$', '', line)
if re.match(r'^\s\s\spydarkstar.*$', line):
handle.write(' {}'.format(line.lstrip()))
else:
handle.write(line)
if '.. toctree::' in line:
if z:
handle.write(' :maxdepth: {}\n'.format(z))
else:
z += 1
|
import shutil
import os
import re
work = os.getcwd()
found = []
regex = re.compile(r'pydarkstar\.(.*)\.rst')
for root, dirs, files in os.walk(work):
for f in files:
m = regex.match(f)
if m:
found.append((root, f))
for root, f in found:
path = os.path.join(root, f)
with open(path, 'r') as handle:
lines = handle.readlines()
with open(path, 'w') as handle:
for i, line in enumerate(lines):
if i == 0:
line = re.sub(r'\s+package$', '', line)
line = re.sub(r'\s+module$', '', line)
line = re.sub(r'^pydarkstar\.', '', line)
#print('{:2d} {}'.format(i, line.rstrip()))
handle.write(line)
#print('')
# fix main file
with open('pydarkstar.rst', 'r') as handle:
lines = handle.readlines()
z = 0
with open('pydarkstar.rst', 'w') as handle:
for i, line in enumerate(lines):
if i == 0:
line = re.sub(r'\s+package$', '', line)
if re.match(r'^\s\s\spydarkstar.*$', line):
handle.write(' {}'.format(line.lstrip()))
else:
handle.write(line)
|
Change to 3 spaces in front of toctree elements
|
Change to 3 spaces in front of toctree elements
|
Python
|
mit
|
AdamGagorik/pydarkstar
|
72f28cfa2723faaa7f7ed2b165fd99b214bc67c9
|
MeetingMinutes.py
|
MeetingMinutes.py
|
import sublime, sublime_plugin
import os
import re
from .mistune import markdown
class CreateMinuteCommand(sublime_plugin.TextCommand):
def run(self, edit):
region = sublime.Region(0, self.view.size())
md_source = self.view.substr(region)
md_source.encode(encoding='UTF-8',errors='strict')
html_source = '<!DOCTYPE html><html><head><meta charset="utf-8"></head><body>' + markdown(md_source) + '</body></html>'
file_name = self.view.file_name()
html_file = self.change_extension(file_name, ".html")
with open(html_file, 'w+') as file_:
file_.write(html_source)
print(file_name)
print(html_file)
def change_extension(self,file_name, new_ext):
f, ext = os.path.splitext(file_name)
f += new_ext
return f
|
import sublime, sublime_plugin
import os
import re
from .mistune import markdown
HTML_START = '<!DOCTYPE html><html><head><meta charset="utf-8"></head><body>'
HTML_END = '</body></html>'
class CreateMinuteCommand(sublime_plugin.TextCommand):
def run(self, edit):
region = sublime.Region(0, self.view.size())
md_source = self.view.substr(region)
md_source.encode(encoding='UTF-8',errors='strict')
html_source = HTML_START + markdown(md_source) + HTML_END
file_name = self.view.file_name()
html_file = self.change_extension(file_name, ".html")
with open(html_file, 'w+') as file_:
file_.write(html_source)
print(file_name)
print(html_file)
def change_extension(self,file_name, new_ext):
f, ext = os.path.splitext(file_name)
f += new_ext
return f
|
Create variables for HTML start and end.
|
Create variables for HTML start and end.
|
Python
|
mit
|
Txarli/sublimetext-meeting-minutes,Txarli/sublimetext-meeting-minutes
|
5ede88c91f61b4aeb3a1e9b55e6b7836cf805255
|
django_filepicker/utils.py
|
django_filepicker/utils.py
|
import re
import urllib
from os.path import basename
from django.core.files import File
class FilepickerFile(object):
filepicker_url_regex = re.compile(
r'https?:\/\/www.filepicker.io\/api\/file\/.*')
def __init__(self, url):
if not self.filepicker_url_regex.match(url):
raise ValueError('Not a filepicker.io URL: %s' % url)
self.url = url
def get_file(self):
'''
Downloads the file from filepicker.io and returns a
Django File wrapper object
'''
filename, header = urllib.urlretrieve(self.url)
name = basename(filename)
disposition = header.get('Content-Disposition')
if disposition:
name = disposition.rpartition("filename=")[2].strip('" ')
return File(open(filename, 'r'), name=name)
|
import re
import urllib
import os
from django.core.files import File
class FilepickerFile(object):
filepicker_url_regex = re.compile(
r'https?:\/\/www.filepicker.io\/api\/file\/.*')
def __init__(self, url):
if not self.filepicker_url_regex.match(url):
raise ValueError('Not a filepicker.io URL: %s' % url)
self.url = url
def get_file(self):
'''
Downloads the file from filepicker.io and returns a
Django File wrapper object
'''
# clean up any old downloads that are still hanging around
self.cleanup()
# The temporary file will be created in a directory set by the
# environment (TEMP_DIR, TEMP or TMP)
self.filename, header = urllib.urlretrieve(self.url)
name = os.path.basename(self.filename)
disposition = header.get('Content-Disposition')
if disposition:
name = disposition.rpartition("filename=")[2].strip('" ')
self.tempfile = open(self.filename, 'r')
return File(self.tempfile, name=name)
def cleanup(self):
'''
Removes any downloaded objects and closes open files.
'''
if hasattr(self, 'tempfile'):
self.tempfile.close()
delattr(self, 'tempfile')
if hasattr(self, 'filename'):
# the file might have been moved in the meantime so
# check first
if os.path.exists(self.filename):
os.remove(self.filename)
delattr(self, 'filename')
def __enter__(self):
'''
Allow FilepickerFile to be used as a context manager as such:
with FilepickerFile(url) as f:
model.field.save(f.name, f.)
'''
return self.get_file()
def __exit__(self, *args):
self.cleanup()
def __del__(self):
self.cleanup()
|
Add context manager and destructor for cleanup
|
Add context manager and destructor for cleanup
When exiting the context or calling cleanup() explicitly,
the temporary file created after downloading is removed and
any open files closed.
|
Python
|
mit
|
FundedByMe/filepicker-django,FundedByMe/filepicker-django,filepicker/filepicker-django,filepicker/filepicker-django
|
13d0b4b50b2eaaf5c557576b7b45a378d901c49c
|
src/zeit/cms/testcontenttype/interfaces.py
|
src/zeit/cms/testcontenttype/interfaces.py
|
# Copyright (c) 2007-2011 gocept gmbh & co. kg
# See also LICENSE.txt
# $Id$
"""Interface definitions for the test content type."""
import zope.interface
class ITestContentType(zope.interface.Interface):
"""A type for testing."""
ITestContentType.setTaggedValue('zeit.cms.type', 'testcontenttype')
|
# Copyright (c) 2007-2011 gocept gmbh & co. kg
# See also LICENSE.txt
# $Id$
"""Interface definitions for the test content type."""
import zope.interface
class ITestContentType(zope.interface.Interface):
"""A type for testing."""
|
Remove superfluous type annotation, it's done by the TypeGrokker now
|
Remove superfluous type annotation, it's done by the TypeGrokker now
|
Python
|
bsd-3-clause
|
ZeitOnline/zeit.cms,ZeitOnline/zeit.cms,ZeitOnline/zeit.cms,ZeitOnline/zeit.cms
|
8f993412a0110085fee10331daecfb3d36973518
|
__init__.py
|
__init__.py
|
###
# Copyright (c) 2012, spline
# All rights reserved.
#
#
###
"""
Add a description of the plugin (to be presented to the user inside the wizard)
here. This should describe *what* the plugin does.
"""
import supybot
import supybot.world as world
# Use this for the version of this plugin. You may wish to put a CVS keyword
# in here if you're keeping the plugin in CVS or some similar system.
__version__ = ""
# XXX Replace this with an appropriate author or supybot.Author instance.
__author__ = supybot.authors.unknown
# This is a dictionary mapping supybot.Author instances to lists of
# contributions.
__contributors__ = {}
# This is a url where the most recent plugin package can be downloaded.
__url__ = '' # 'http://supybot.com/Members/yourname/Scores/download'
import config
import plugin
reload(plugin) # In case we're being reloaded.
# Add more reloads here if you add third-party modules and want them to be
# reloaded when this plugin is reloaded. Don't forget to import them as well!
if world.testing:
import test
Class = plugin.Class
configure = config.configure
# vim:set shiftwidth=4 tabstop=4 expandtab textwidth=79:
|
###
# Copyright (c) 2012, spline
# All rights reserved.
#
#
###
"""
Add a description of the plugin (to be presented to the user inside the wizard)
here. This should describe *what* the plugin does.
"""
import supybot
import supybot.world as world
# Use this for the version of this plugin. You may wish to put a CVS keyword
# in here if you're keeping the plugin in CVS or some similar system.
__version__ = ""
# XXX Replace this with an appropriate author or supybot.Author instance.
__author__ = supybot.authors.unknown
# This is a dictionary mapping supybot.Author instances to lists of
# contributions.
__contributors__ = {}
# This is a url where the most recent plugin package can be downloaded.
__url__ = '' # 'http://supybot.com/Members/yourname/Scores/download'
import config
import plugin
reload(config)
reload(plugin) # In case we're being reloaded.
# Add more reloads here if you add third-party modules and want them to be
# reloaded when this plugin is reloaded. Don't forget to import them as well!
if world.testing:
import test
Class = plugin.Class
configure = config.configure
# vim:set shiftwidth=4 tabstop=4 expandtab textwidth=79:
|
Add reload to init for config
|
Add reload to init for config
|
Python
|
mit
|
reticulatingspline/Scores,cottongin/Scores
|
f447e8fa50770d133d53e69477292b3925203c64
|
modular_blocks/models.py
|
modular_blocks/models.py
|
from django.db import models
from .fields import ListTextField
class TwoModularColumnsMixin(models.Model):
sidebar_left = ListTextField()
sidebar_right = ListTextField()
class Meta:
abstract = True
|
from django.db import models
from .fields import ListTextField
class TwoModularColumnsMixin(models.Model):
sidebar_left = ListTextField(
blank=True,
null=True,
)
sidebar_right = ListTextField(
lank=True,
null=True,
)
class Meta:
abstract = True
|
Add null and blank to sidebars
|
Add null and blank to sidebars
|
Python
|
agpl-3.0
|
rezometz/django-modular-blocks,rezometz/django-modular-blocks,rezometz/django-modular-blocks
|
b63b22678a005baa6195854b65cc1828061febba
|
vx/mode.py
|
vx/mode.py
|
import vx
import os.path
def mode_from_filename(file):
root, ext = os.path.splitext(file)
ext = ext if ext else root
mode = None
if ext == '.c':
return c_mode
class mode:
def __init__(self, window):
self.breaks = ('_', ' ', '\n', '\t')
self.keywords = ()
class python_mode(mode):
def __init__(self, window):
super().__init__(window)
self.breaks = ('_', ' ', '\n', '\t', '(', ')', '{', '}', '.', ',', '#')
self.keywords = ('return', 'for', 'while', 'break', 'continue', 'def')
class c_mode(mode):
def __init__(self, window):
super().__init__(window)
self.breaks = ('_', ' ', '\n', '\t', '(', ')', '<', '>', '.', ',', '#')
self.keywords = ('#include', '#define', 'if', 'else', 'return', 'goto', 'break', 'continue', r'"(?:[^"\\]|\\.)*"')
|
import vx
import os.path
def mode_from_filename(file):
root, ext = os.path.splitext(file)
ext = ext if ext else root
mode = None
if ext == '.c':
return c_mode
elif ext == '.py':
return python_mode
class mode:
def __init__(self, window):
self.breaks = ('_', ' ', '\n', '\t')
self.keywords = ()
class python_mode(mode):
def __init__(self, window):
super().__init__(window)
self.breaks = ('_', ' ', '\n', '\t', '(', ')', '{', '}', '.', ',', '#')
self.keywords = ('class', 'return', 'for', 'while', 'break', 'continue', 'def', 'from', 'import')
class c_mode(mode):
def __init__(self, window):
super().__init__(window)
self.breaks = ('_', ' ', '\n', '\t', '(', ')', '<', '>', '.', ',', '#')
self.keywords = ('#include', '#define', 'if', 'else', 'return', 'goto', 'break', 'continue', r'"(?:[^"\\]|\\.)*"')
|
Add .py extension handling and more python keywords
|
Add .py extension handling and more python keywords
|
Python
|
mit
|
philipdexter/vx,philipdexter/vx
|
f62980f99654b22930cac6716410b145b590221f
|
Lib/lib-tk/FixTk.py
|
Lib/lib-tk/FixTk.py
|
import sys, os
v = os.path.join(sys.prefix, "tcl", "tcl8.3")
if os.path.exists(os.path.join(v, "init.tcl")):
os.environ["TCL_LIBRARY"] = v
|
import sys, os, _tkinter
ver = str(_tkinter.TCL_VERSION)
v = os.path.join(sys.prefix, "tcl", "tcl"+ver)
if os.path.exists(os.path.join(v, "init.tcl")):
os.environ["TCL_LIBRARY"] = v
|
Work the Tcl version number in the path we search for.
|
Work the Tcl version number in the path we search for.
|
Python
|
mit
|
sk-/python2.7-type-annotator,sk-/python2.7-type-annotator,sk-/python2.7-type-annotator
|
49b24fe2c524923e200ce8495055b0b59d83eb6d
|
__init__.py
|
__init__.py
|
# Copyright (c) 2015 Ultimaker B.V.
# Cura is released under the terms of the AGPLv3 or higher.
from . import OctoPrintOutputDevicePlugin
from . import DiscoverOctoPrintAction
from UM.i18n import i18nCatalog
catalog = i18nCatalog("cura")
def getMetaData():
return {
"type": "extension",
"plugin": {
"name": "OctoPrint connection",
"author": "fieldOfView",
"version": "2.4",
"description": catalog.i18nc("@info:whatsthis", "Allows sending prints to OctoPrint and monitoring the progress"),
"api": 3
}
}
def register(app):
return {
"output_device": OctoPrintOutputDevicePlugin.OctoPrintOutputDevicePlugin(),
"machine_action": DiscoverOctoPrintAction.DiscoverOctoPrintAction()
}
|
# Copyright (c) 2015 Ultimaker B.V.
# Cura is released under the terms of the AGPLv3 or higher.
from . import OctoPrintOutputDevicePlugin
from . import DiscoverOctoPrintAction
from UM.i18n import i18nCatalog
catalog = i18nCatalog("cura")
def getMetaData():
return {
"type": "extension",
"plugin": {
"name": "OctoPrint connection",
"author": "fieldOfView",
"version": "master",
"description": catalog.i18nc("@info:whatsthis", "Allows sending prints to OctoPrint and monitoring the progress"),
"api": 3
}
}
def register(app):
return {
"output_device": OctoPrintOutputDevicePlugin.OctoPrintOutputDevicePlugin(),
"machine_action": DiscoverOctoPrintAction.DiscoverOctoPrintAction()
}
|
Set plugin version to "master" to show which Cura branch this plugin branch should work with
|
Set plugin version to "master" to show which Cura branch this plugin branch should work with
|
Python
|
agpl-3.0
|
fieldOfView/OctoPrintPlugin
|
1c43affbd82f68ed8956cd407c494ff46dab9203
|
examples/IPLoM_example.py
|
examples/IPLoM_example.py
|
from pygraphc.misc.IPLoM import *
from pygraphc.evaluation.ExternalEvaluation import *
# set input path
ip_address = '161.166.232.17'
standard_path = '/home/hudan/Git/labeled-authlog/dataset/Hofstede2014/dataset1/' + ip_address
standard_file = standard_path + 'auth.log.anon.labeled'
analyzed_file = 'auth.log.anon'
prediction_file = 'iplom-result-' + ip_address + '.txt'
OutputPath = './result'
para = Para(path=standard_path, logname=analyzed_file, save_path=OutputPath)
# call IPLoM and get clusters
myparser = IPLoM(para)
time = myparser.main_process()
clusters = myparser.get_clusters()
original_logs = myparser.logs
# set cluster label to get evaluation metrics
ExternalEvaluation.set_cluster_label_id(None, clusters, original_logs, prediction_file)
homogeneity_completeness_vmeasure = ExternalEvaluation.get_homogeneity_completeness_vmeasure(standard_file,
prediction_file)
# print evaluation result
print homogeneity_completeness_vmeasure
print ('The running time of IPLoM is', time)
|
from pygraphc.misc.IPLoM import *
from pygraphc.evaluation.ExternalEvaluation import *
# set input path
dataset_path = '/home/hudan/Git/labeled-authlog/dataset/Hofstede2014/dataset1_perday/'
groundtruth_file = dataset_path + 'Dec 1.log.labeled'
analyzed_file = 'Dec 1.log'
OutputPath = '/home/hudan/Git/pygraphc/result/misc/'
prediction_file = OutputPath + 'Dec 1.log.perline'
para = Para(path=dataset_path, logname=analyzed_file, save_path=OutputPath)
# call IPLoM and get clusters
myparser = IPLoM(para)
time = myparser.main_process()
clusters = myparser.get_clusters()
original_logs = myparser.logs
# set cluster label to get evaluation metrics
ExternalEvaluation.set_cluster_label_id(None, clusters, original_logs, prediction_file)
# get evaluation of clustering performance
ar = ExternalEvaluation.get_adjusted_rand(groundtruth_file, prediction_file)
ami = ExternalEvaluation.get_adjusted_mutual_info(groundtruth_file, prediction_file)
nmi = ExternalEvaluation.get_normalized_mutual_info(groundtruth_file, prediction_file)
h = ExternalEvaluation.get_homogeneity(groundtruth_file, prediction_file)
c = ExternalEvaluation.get_completeness(groundtruth_file, prediction_file)
v = ExternalEvaluation.get_vmeasure(groundtruth_file, prediction_file)
# print evaluation result
print ar, ami, nmi, h, c, v
print ('The running time of IPLoM is', time)
|
Edit path and external evaluation
|
Edit path and external evaluation
|
Python
|
mit
|
studiawan/pygraphc
|
6e1126fe9a8269ff4489ee338000afc852bce922
|
oidc_apis/id_token.py
|
oidc_apis/id_token.py
|
import inspect
from .scopes import get_userinfo_by_scopes
def process_id_token(payload, user, scope=None):
if scope is None:
# HACK: Steal the scope argument from the locals dictionary of
# the caller, since it was not passed to us
scope = inspect.stack()[1][0].f_locals.get('scope', [])
payload.update(get_userinfo_by_scopes(user, scope))
return payload
|
import inspect
from .scopes import get_userinfo_by_scopes
def process_id_token(payload, user, scope=None):
if scope is None:
# HACK: Steal the scope argument from the locals dictionary of
# the caller, since it was not passed to us
scope = inspect.stack()[1][0].f_locals.get('scope', [])
payload.update(get_userinfo_by_scopes(user, scope))
payload['preferred_username'] = user.username
return payload
|
Add username to ID Token
|
Add username to ID Token
|
Python
|
mit
|
mikkokeskinen/tunnistamo,mikkokeskinen/tunnistamo
|
b47e3677120b9b2d64d38b48b0382dc7986a1b82
|
opps/core/__init__.py
|
opps/core/__init__.py
|
# -*- coding: utf-8 -*-
from django.utils.translation import ugettext_lazy as _
from django.conf import settings
trans_app_label = _('Opps')
settings.INSTALLED_APPS += ('opps.article',
'opps.image',
'opps.channel',
'opps.source',
'redactor',
'tagging',)
settings.REDACTOR_OPTIONS = {'lang': 'en'}
settings.REDACTOR_UPLOAD = 'uploads/'
|
# -*- coding: utf-8 -*-
from django.utils.translation import ugettext_lazy as _
trans_app_label = _('Opps')
|
Remove installed app on init opps core
|
Remove installed app on init opps core
|
Python
|
mit
|
YACOWS/opps,williamroot/opps,jeanmask/opps,williamroot/opps,williamroot/opps,jeanmask/opps,opps/opps,YACOWS/opps,jeanmask/opps,opps/opps,williamroot/opps,jeanmask/opps,opps/opps,YACOWS/opps,opps/opps,YACOWS/opps
|
52d15d09ed079d1b8598f314524066b56273af3d
|
addie/_version.py
|
addie/_version.py
|
# This file was generated by 'versioneer.py' (0.15) from
# revision-control system data, or from the parent directory name of an
# unpacked source archive. Distribution tarballs contain a pre-generated copy
# of this file.
import json
import sys
version_json = '''
{
"dirty": false,
"error": null,
"full-revisionid": "aaeac9708788e1b02d6a763b86333eff9bad7122",
"version": "5.0.4"
}
''' # END VERSION_JSON
def get_versions():
return json.loads(version_json)
|
# This file was generated by 'versioneer.py' (0.15) from
# revision-control system data, or from the parent directory name of an
# unpacked source archive. Distribution tarballs contain a pre-generated copy
# of this file.
import json
version_json = '''
{
"dirty": false,
"error": null,
"full-revisionid": "aaeac9708788e1b02d6a763b86333eff9bad7122",
"version": "5.0.4"
}
''' # END VERSION_JSON
def get_versions():
return json.loads(version_json)
|
Remove sys import in versioneer file
|
Remove sys import in versioneer file
|
Python
|
mit
|
neutrons/FastGR,neutrons/FastGR,neutrons/FastGR
|
25a97de30fcc9cddd7f58cd25584fd726f0cc8e4
|
guild/commands/packages_list.py
|
guild/commands/packages_list.py
|
# Copyright 2017-2020 TensorHub, Inc.
#
# 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
from __future__ import division
import click
from guild import click_util
@click.command("list, ls")
@click.argument("terms", metavar="[TERM]...", nargs=-1)
@click.option("-a", "--all", help="Show all packages.", is_flag=True)
@click_util.use_args
def list_packages(args):
"""List installed packages.
Specify one or more `TERM` arguments to show packages matching any
of the specified values.
"""
from . import packages_impl
packages_impl.list_packages(args)
|
# Copyright 2017-2020 TensorHub, Inc.
#
# 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
from __future__ import division
import click
from guild import click_util
@click.command("list, ls")
@click.argument("terms", metavar="[TERM]...", nargs=-1)
@click.option("-a", "--all", help="Show all installed Python packages.", is_flag=True)
@click_util.use_args
def list_packages(args):
"""List installed packages.
Specify one or more `TERM` arguments to show packages matching any
of the specified values.
"""
from . import packages_impl
packages_impl.list_packages(args)
|
Clarify meaning of --all option for packages command
|
Clarify meaning of --all option for packages command
|
Python
|
apache-2.0
|
guildai/guild,guildai/guild,guildai/guild,guildai/guild
|
ccdeb23eb54191913a97b48907e0738f6969ce58
|
tests/factories/config.py
|
tests/factories/config.py
|
# -*- coding: utf-8 -*-
# Copyright (c) 2018 The Pycroft Authors. See the AUTHORS file.
# This file is part of the Pycroft project and licensed under the terms of
# the Apache License, Version 2.0. See the LICENSE file for details.
from factory import SubFactory
from pycroft.model.config import Config
from .base import BaseFactory
from .finance import AccountFactory, BankAccountFactory
from .property import PropertyGroupFactory, MemberPropertyGroupFactory
class ConfigFactory(BaseFactory):
"""This is a dummy Config factory, Referencing PropertyGroups with
no a-priori property relationships and arbitrary Accounts.
"""
class Meta:
model = Config
id = 1
# `PropertyGroup`s
member_group = SubFactory(MemberPropertyGroupFactory)
network_access_group = SubFactory(PropertyGroupFactory)
violation_group = SubFactory(PropertyGroupFactory)
cache_group = SubFactory(PropertyGroupFactory)
traffic_limit_exceeded_group = SubFactory(PropertyGroupFactory)
external_group = SubFactory(PropertyGroupFactory)
payment_in_default_group = SubFactory(PropertyGroupFactory)
blocked_group = SubFactory(PropertyGroupFactory)
caretaker_group = SubFactory(PropertyGroupFactory)
treasurer_group = SubFactory(PropertyGroupFactory)
# `Account`s
membership_fee_account = SubFactory(AccountFactory)
membership_fee_bank_account = SubFactory(BankAccountFactory)
|
# -*- coding: utf-8 -*-
# Copyright (c) 2018 The Pycroft Authors. See the AUTHORS file.
# This file is part of the Pycroft project and licensed under the terms of
# the Apache License, Version 2.0. See the LICENSE file for details.
from factory import SubFactory
from pycroft.model.config import Config
from .base import BaseFactory
from .finance import AccountFactory, BankAccountFactory
from .property import PropertyGroupFactory, MemberPropertyGroupFactory
class ConfigFactory(BaseFactory):
"""This is a dummy Config factory, Referencing PropertyGroups with
no a-priori property relationships and arbitrary Accounts.
"""
class Meta:
model = Config
id = 1
# `PropertyGroup`s
member_group = SubFactory(MemberPropertyGroupFactory)
network_access_group = SubFactory(PropertyGroupFactory)
violation_group = SubFactory(PropertyGroupFactory)
cache_group = SubFactory(PropertyGroupFactory)
traffic_limit_exceeded_group = SubFactory(PropertyGroupFactory)
external_group = SubFactory(PropertyGroupFactory)
payment_in_default_group = SubFactory(PropertyGroupFactory,
granted=frozenset(("payment_in_default",)),
denied=frozenset(("network_access", "userwww", "userdb")))
blocked_group = SubFactory(PropertyGroupFactory)
caretaker_group = SubFactory(PropertyGroupFactory)
treasurer_group = SubFactory(PropertyGroupFactory)
# `Account`s
membership_fee_account = SubFactory(AccountFactory)
membership_fee_bank_account = SubFactory(BankAccountFactory)
|
Add correct properties for payment_in_default test group
|
Add correct properties for payment_in_default test group
|
Python
|
apache-2.0
|
agdsn/pycroft,agdsn/pycroft,agdsn/pycroft,agdsn/pycroft,agdsn/pycroft
|
fb9c56381d259de7d1765ca0e058f82d61e4e975
|
examples/ellipses_FreeCAD.py
|
examples/ellipses_FreeCAD.py
|
from __future__ import division
import numpy as np
import FreeCAD as FC
import Part
import Draft
import os
doc = FC.newDocument("ellipses")
folder = os.path.dirname(__file__) + ".\.."
fname = folder + "/vor_ellipses.txt"
data = np.loadtxt(fname)
shapes = []
area = 0
for ellipse in data:
cx, cy, b, a, ang = ellipse
ang = ang*np.pi/180
place = FC.Placement()
place.Rotation = (0, 0, np.sin(ang/2), np.cos(ang/2))
place.Base = FC.Vector(100*cx, 100*cy, 0)
ellipse = Draft.makeEllipse(100*a, 100*b, placement=place)
shapes.append(ellipse)
area = area + np.pi*a*b*100*100
print area, " ", area/500/70
part = Part.makeCompound(shapes)
|
from __future__ import division
import numpy as np
import FreeCAD as FC
import Part
import Draft
import os
doc = FC.newDocument("ellipses")
folder = os.path.dirname(__file__) #+ "/.."
fname = folder + "/vor_ellipses.txt"
data = np.loadtxt(fname)
shapes = []
area = 0
radii = []
for ellipse in data:
cx, cy, b, a, ang = ellipse
ang = ang*np.pi/180
place = FC.Placement()
place.Rotation = (0, 0, np.sin(ang/2), np.cos(ang/2))
place.Base = FC.Vector(100*cx, 100*cy, 0)
ellipse = Draft.makeEllipse(100*a, 100*b, placement=place)
radii.append([100*a, 100*b])
shapes.append(ellipse)
area = area + np.pi*a*b*100*100
print "area: %g " % (area/500/70)
print "radius: %g +/- %g" % (np.mean(radii), np.std(radii))
part = Part.makeCompound(shapes)
|
Add radii mean and standard deviation
|
Add radii mean and standard deviation
|
Python
|
mit
|
nicoguaro/ellipse_packing
|
08de3f0bf326e8625462d9dbdb7297d8749bc416
|
examples/joystick_example.py
|
examples/joystick_example.py
|
#!/usr/bin/env python3
"""This example shows how to use the Joystick Click wrapper of the LetMeCreate.
It continuously reads the position of the joystick, prints it in the terminal
and displays a pattern on the LED's based on the x coordinate.
The Joystick Click must be inserted in Mikrobus 1 before running this program.
"""
from letmecreate.core import i2c
from letmecreate.core import led
from letmecreate.click import joystick
OFFSET = 98
MAXIMUM = OFFSET2
def get_led_mask(perc):
div = int((1. - perc)led.LED_CNT)
if div > led.LED_CNT:
div = led.LED_CNT
mask = 0
for i in range(div):
mask |= (1 << i)
return mask
i2c.init()
led.init()
while True:
pos = joystick.get_position()
print('{} {}'.format(pos[0], pos[1]))
mask = get_led_mask(float(pos[0] + OFFSET)/float(MAXIMUM))
led.switch_on(mask)
led.switch_off(~mask)
i2c.release()
led.release()
|
#!/usr/bin/env python3
"""This example shows how to use the Joystick Click wrapper of the LetMeCreate.
It continuously reads the position of the joystick, prints it in the terminal
and displays a pattern on the LED's based on the x coordinate.
The Joystick Click must be inserted in Mikrobus 1 before running this program.
"""
from letmecreate.core import i2c
from letmecreate.core import led
from letmecreate.click import joystick
OFFSET = 98
MAXIMUM = OFFSET2
def get_led_mask(perc):
div = int((1. - perc)led.LED_CNT)
if div > led.LED_CNT:
div = led.LED_CNT
mask = 0
for i in range(div):
mask |= (1 << i)
return mask
i2c.init()
led.init()
while True:
pos = joystick.get_position()
print('{} {}'.format(pos[0], pos[1]))
mask = get_led_mask(float(pos[0] + OFFSET)/float(MAXIMUM))
led.switch_on(mask)
led.switch_off(~mask)
i2c.release()
led.release()
|
Replace tabs by space in example
|
joystick: Replace tabs by space in example
Signed-off-by: Francois Berder <[email protected]>
|
Python
|
bsd-3-clause
|
francois-berder/PyLetMeCreate
|
98a4cd76ce9ecb81675ebaa29b249a8d80347e0d
|
zc-list.py
|
zc-list.py
|
#!/usr/bin/env python
import client_wrap
KEY_LONG = "key1"
DATA_LONG = 1024
KEY_DOUBLE = "key2"
DATA_DOUBLE = 100.53
KEY_STRING = "key3"
DATA_STRING = "test data"
def init_data(client):
client.WriteLong(KEY_LONG, DATA_LONG)
client.WriteDouble(KEY_DOUBLE, DATA_DOUBLE)
client.WriteString(KEY_STRING, DATA_STRING)
def check_data(client):
assert DATA_LONG == client.ReadLong(KEY_LONG)
assert DATA_DOUBLE == client.ReadDouble(KEY_DOUBLE)
assert DATA_STRING == client.ReadString(KEY_STRING)
def main():
client = client_wrap.ClientWrap("get_test.log", "ipc:///var/run/zero-cache/0", 0)
init_data(client)
check_data(client)
if __name__ == "__main__":
main()
|
#!/usr/bin/env python
import client_wrap
def main():
client = client_wrap.ClientWrap("get_test.log", "ipc:///var/run/zero-cache/0", 0)
key_str = client.GetKeys()
keys = key_str.split (';')
del keys[-1]
if len(keys) == 0:
return
print keys
if __name__ == "__main__":
main()
|
Implement displaying of the current key list
|
Implement displaying of the current key list
|
Python
|
agpl-3.0
|
ellysh/zero-cache-utils,ellysh/zero-cache-utils
|
1f6c830e68aede8a2267b5749b911d87801f9e5b
|
setup.py
|
setup.py
|
from setuptools import setup
setup(
name='django-setmagic',
version='0.2',
author='Evandro Myller',
author_email='[email protected]',
description='Magically editable settings for winged pony lovers',
url='https://github.com/7ws/django-setmagic',
install_requires=[
'django >= 1.5',
],
packages=['setmagic'],
keywords=['django', 'settings'],
classifiers=[
'Framework :: Django',
'License :: OSI Approved :: MIT License',
'Programming Language :: Python',
'Programming Language :: Python :: 2.6',
'Programming Language :: Python :: 2.7',
'Programming Language :: Python :: 3.1',
'Programming Language :: Python :: 3.2',
'Programming Language :: Python :: 3.3',
'Programming Language :: Python :: 3.4',
'Topic :: Software Development',
],
)
|
from setuptools import setup
setup(
name='django-setmagic',
version='0.2.1',
author='Evandro Myller',
author_email='[email protected]',
description='Magically editable settings for winged pony lovers',
url='https://github.com/7ws/django-setmagic',
install_requires=[
'django >= 1.5',
],
packages=['setmagic'],
include_package_data=True,
keywords=['django', 'settings'],
classifiers=[
'Framework :: Django',
'License :: OSI Approved :: MIT License',
'Programming Language :: Python',
'Programming Language :: Python :: 2.6',
'Programming Language :: Python :: 2.7',
'Programming Language :: Python :: 3.1',
'Programming Language :: Python :: 3.2',
'Programming Language :: Python :: 3.3',
'Programming Language :: Python :: 3.4',
'Topic :: Software Development',
],
)
|
Include templates and static at the installing process too
|
Include templates and static at the installing process too
|
Python
|
mit
|
7ws/django-setmagic
|
2049be18b864fe2dab61ca6258b2295b3270d5c2
|
setup.py
|
setup.py
|
import distutils.core
# Uploading to PyPI
# =================
# $ python setup.py register -r pypi
# $ python setup.py sdist upload -r pypi
version = '0.0'
distutils.core.setup(
name='kxg',
version=version,
author='Kale Kundert and Alex Mitchell',
url='https://github.com/kxgames/GameEngine',
download_url='https://github.com/kxgames/GameEngine/tarball/'+version,
license='LICENSE.txt',
description="A multiplayer game engine.",
long_description=open('README.rst').read(),
keywords=['game', 'network', 'gui', 'pyglet'],
packages=['kxg'],
requires=[
'pyglet',
'nonstdlib',
'linersock',
'vecrec',
'glooey',
],
)
|
import distutils.core
# Uploading to PyPI
# =================
# $ python setup.py register -r pypi
# $ python setup.py sdist upload -r pypi
version = '0.0'
distutils.core.setup(
name='kxg',
version=version,
author='Kale Kundert and Alex Mitchell',
url='https://github.com/kxgames/GameEngine',
download_url='https://github.com/kxgames/GameEngine/tarball/'+version,
license='LICENSE.txt',
description="A multiplayer game engine.",
long_description=open('README.rst').read(),
keywords=['game', 'network', 'gui', 'pyglet'],
packages=['kxg'],
requires=[
'pyglet',
'nonstdlib',
'linersock',
'vecrec',
'glooey',
'pytest',
],
)
|
Add pytest as a dependency
|
Add pytest as a dependency
|
Python
|
mit
|
kxgames/kxg
|
cb528fbb990e8cd3d301fcbf60069b33a68b9cac
|
setup.py
|
setup.py
|
#!/usr/bin/env python
from distribute_setup import use_setuptools
use_setuptools()
from setuptools import setup, find_packages
setup(
name="ShowTransmission",
version="0.1",
packages=find_packages(),
author="Chris Scutcher",
author_email="[email protected]",
description=("Script that monitors a ShowRSS feed and adds new torrents to transmission via "
"RPC interface"),
install_requires=['feedparser>=5.3.1'],
entry_points = {
'console_scripts': [
'showtransmission = showtransmission.showtransmission:run_script',
],
'setuptools.installation': [
'eggsecutable = showtransmission.showtransmission:run_script',
]
}
)
|
#!/usr/bin/env python
from distribute_setup import use_setuptools
use_setuptools()
from setuptools import setup, find_packages
setup(
name="ShowTransmission",
version="0.1",
packages=find_packages(),
author="Chris Scutcher",
author_email="[email protected]",
description=("Script that monitors a ShowRSS feed and adds new torrents to transmission via "
"RPC interface"),
install_requires=['feedparser'],
entry_points = {
'console_scripts': [
'showtransmission = showtransmission.showtransmission:run_script',
],
'setuptools.installation': [
'eggsecutable = showtransmission.showtransmission:run_script',
]
}
)
|
Revert "Specify specific version of feedparser"
|
Revert "Specify specific version of feedparser"
This reverts commit e2a6bc54e404538f01a980f1573a507c224d1c31.
|
Python
|
apache-2.0
|
cscutcher/showtransmission
|
a61386cbbcbe3e68bcdf0a98c23547117a496fec
|
zerver/views/webhooks/github_dispatcher.py
|
zerver/views/webhooks/github_dispatcher.py
|
from __future__ import absolute_import
from django.http import HttpRequest, HttpResponse
from .github_webhook import api_github_webhook
from .github import api_github_landing
def api_github_webhook_dispatch(request):
# type: (HttpRequest) -> HttpResponse
if request.META.get('HTTP_X_GITHUB_EVENT'):
return api_github_webhook(request)
else:
return api_github_landing(request)
|
from __future__ import absolute_import
from django.http import HttpRequest, HttpResponse
from django.views.decorators.csrf import csrf_exempt
from .github_webhook import api_github_webhook
from .github import api_github_landing
# Since this dispatcher is an API-style endpoint, it needs to be
# explicitly marked as CSRF-exempt
@csrf_exempt
def api_github_webhook_dispatch(request):
# type: (HttpRequest) -> HttpResponse
if request.META.get('HTTP_X_GITHUB_EVENT'):
return api_github_webhook(request)
else:
return api_github_landing(request)
|
Fix GitHub integration CSRF issue.
|
github: Fix GitHub integration CSRF issue.
The new GitHub dispatcher integration was apparently totally broken,
because we hadn't tagged the new dispatcher endpoint as exempt from
CSRF checking. I'm not sure why the test suite didn't catch this.
|
Python
|
apache-2.0
|
AZtheAsian/zulip,dhcrzf/zulip,JPJPJPOPOP/zulip,christi3k/zulip,hackerkid/zulip,verma-varsha/zulip,j831/zulip,Diptanshu8/zulip,dhcrzf/zulip,ryanbackman/zulip,shubhamdhama/zulip,Galexrt/zulip,hackerkid/zulip,andersk/zulip,amyliu345/zulip,j831/zulip,mahim97/zulip,brainwane/zulip,SmartPeople/zulip,ryanbackman/zulip,Galexrt/zulip,dawran6/zulip,JPJPJPOPOP/zulip,rht/zulip,niftynei/zulip,vaidap/zulip,amanharitsh123/zulip,AZtheAsian/zulip,shubhamdhama/zulip,rht/zulip,kou/zulip,jphilipsen05/zulip,mahim97/zulip,verma-varsha/zulip,isht3/zulip,cosmicAsymmetry/zulip,vabs22/zulip,vabs22/zulip,eeshangarg/zulip,showell/zulip,PhilSk/zulip,timabbott/zulip,rishig/zulip,jrowan/zulip,sharmaeklavya2/zulip,aakash-cr7/zulip,tommyip/zulip,JPJPJPOPOP/zulip,zulip/zulip,ryanbackman/zulip,jackrzhang/zulip,jackrzhang/zulip,rht/zulip,cosmicAsymmetry/zulip,brainwane/zulip,brockwhittaker/zulip,timabbott/zulip,andersk/zulip,christi3k/zulip,rishig/zulip,isht3/zulip,blaze225/zulip,punchagan/zulip,kou/zulip,susansls/zulip,brainwane/zulip,eeshangarg/zulip,jainayush975/zulip,brainwane/zulip,susansls/zulip,vabs22/zulip,vabs22/zulip,verma-varsha/zulip,Diptanshu8/zulip,rht/zulip,punchagan/zulip,jrowan/zulip,sonali0901/zulip,dawran6/zulip,eeshangarg/zulip,showell/zulip,eeshangarg/zulip,tommyip/zulip,JPJPJPOPOP/zulip,shubhamdhama/zulip,showell/zulip,shubhamdhama/zulip,christi3k/zulip,sonali0901/zulip,eeshangarg/zulip,dhcrzf/zulip,isht3/zulip,SmartPeople/zulip,vaidap/zulip,Diptanshu8/zulip,kou/zulip,souravbadami/zulip,hackerkid/zulip,tommyip/zulip,souravbadami/zulip,samatdav/zulip,amyliu345/zulip,brockwhittaker/zulip,amanharitsh123/zulip,ryanbackman/zulip,j831/zulip,SmartPeople/zulip,synicalsyntax/zulip,samatdav/zulip,dawran6/zulip,kou/zulip,andersk/zulip,PhilSk/zulip,vaidap/zulip,AZtheAsian/zulip,jrowan/zulip,zulip/zulip,aakash-cr7/zulip,christi3k/zulip,rishig/zulip,souravbadami/zulip,sharmaeklavya2/zulip,zulip/zulip,Diptanshu8/zulip,dawran6/zulip,jackrzhang/zulip,blaze225/zulip,isht3/zulip,brainwane/zulip,synicalsyntax/zulip,punchagan/zulip,synicalsyntax/zulip,amyliu345/zulip,dhcrzf/zulip,sonali0901/zulip,zulip/zulip,rishig/zulip,synicalsyntax/zulip,hackerkid/zulip,samatdav/zulip,susansls/zulip,hackerkid/zulip,susansls/zulip,brockwhittaker/zulip,susansls/zulip,timabbott/zulip,aakash-cr7/zulip,sharmaeklavya2/zulip,rht/zulip,showell/zulip,isht3/zulip,SmartPeople/zulip,jainayush975/zulip,aakash-cr7/zulip,zulip/zulip,shubhamdhama/zulip,brockwhittaker/zulip,andersk/zulip,jackrzhang/zulip,dattatreya303/zulip,Galexrt/zulip,rht/zulip,zulip/zulip,amanharitsh123/zulip,jackrzhang/zulip,j831/zulip,tommyip/zulip,JPJPJPOPOP/zulip,punchagan/zulip,sharmaeklavya2/zulip,souravbadami/zulip,tommyip/zulip,jphilipsen05/zulip,timabbott/zulip,PhilSk/zulip,niftynei/zulip,samatdav/zulip,dattatreya303/zulip,SmartPeople/zulip,kou/zulip,shubhamdhama/zulip,amanharitsh123/zulip,brainwane/zulip,verma-varsha/zulip,blaze225/zulip,j831/zulip,AZtheAsian/zulip,eeshangarg/zulip,Galexrt/zulip,blaze225/zulip,amyliu345/zulip,verma-varsha/zulip,tommyip/zulip,synicalsyntax/zulip,dawran6/zulip,vaidap/zulip,dhcrzf/zulip,showell/zulip,jphilipsen05/zulip,ryanbackman/zulip,sonali0901/zulip,sonali0901/zulip,aakash-cr7/zulip,brainwane/zulip,andersk/zulip,christi3k/zulip,jainayush975/zulip,AZtheAsian/zulip,j831/zulip,rht/zulip,AZtheAsian/zulip,ryanbackman/zulip,vabs22/zulip,zulip/zulip,shubhamdhama/zulip,kou/zulip,rishig/zulip,mahim97/zulip,hackerkid/zulip,timabbott/zulip,mahim97/zulip,niftynei/zulip,jrowan/zulip,sharmaeklavya2/zulip,souravbadami/zulip,jphilipsen05/zulip,verma-varsha/zulip,jackrzhang/zulip,jackrzhang/zulip,dattatreya303/zulip,rishig/zulip,punchagan/zulip,tommyip/zulip,andersk/zulip,jainayush975/zulip,jphilipsen05/zulip,blaze225/zulip,PhilSk/zulip,Diptanshu8/zulip,Diptanshu8/zulip,amyliu345/zulip,timabbott/zulip,dhcrzf/zulip,cosmicAsymmetry/zulip,amanharitsh123/zulip,cosmicAsymmetry/zulip,rishig/zulip,niftynei/zulip,showell/zulip,isht3/zulip,SmartPeople/zulip,vaidap/zulip,vaidap/zulip,PhilSk/zulip,andersk/zulip,sonali0901/zulip,aakash-cr7/zulip,Galexrt/zulip,jrowan/zulip,susansls/zulip,christi3k/zulip,jainayush975/zulip,niftynei/zulip,amyliu345/zulip,PhilSk/zulip,brockwhittaker/zulip,eeshangarg/zulip,synicalsyntax/zulip,hackerkid/zulip,showell/zulip,dattatreya303/zulip,dawran6/zulip,jainayush975/zulip,mahim97/zulip,cosmicAsymmetry/zulip,punchagan/zulip,synicalsyntax/zulip,souravbadami/zulip,cosmicAsymmetry/zulip,timabbott/zulip,dhcrzf/zulip,dattatreya303/zulip,vabs22/zulip,jrowan/zulip,niftynei/zulip,brockwhittaker/zulip,JPJPJPOPOP/zulip,blaze225/zulip,punchagan/zulip,amanharitsh123/zulip,samatdav/zulip,jphilipsen05/zulip,sharmaeklavya2/zulip,samatdav/zulip,Galexrt/zulip,Galexrt/zulip,mahim97/zulip,dattatreya303/zulip,kou/zulip
|
a7c49480e1eb530aa4df494709ec1f7edd875e1a
|
devito/ir/clusters/analysis.py
|
devito/ir/clusters/analysis.py
|
from devito.ir.support import (SEQUENTIAL, PARALLEL, PARALLEL_IF_ATOMIC, VECTOR,
TILABLE, WRAPPABLE)
__all__ = ['analyze']
def analyze(clusters):
return clusters
|
from collections import OrderedDict
from devito.ir.clusters.queue import Queue
from devito.ir.support import (SEQUENTIAL, PARALLEL, PARALLEL_IF_ATOMIC, VECTOR,
TILABLE, WRAPPABLE)
from devito.tools import timed_pass
__all__ = ['analyze']
class State(object):
def __init__(self):
self.properties = OrderedDict()
self.scopes = OrderedDict()
class Detector(Queue):
def __init__(self, state):
super(Detector, self).__init__()
self.state = state
def callback(self, clusters, prefix):
self._callback(clusters, prefix)
return clusters
class Parallelism(Detector):
def _callback(self, clusters, prefix):
properties = OrderedDict()
def analyze(clusters):
state = State()
clusters = Parallelism(state).process(clusters)
return clusters
|
Add machinery to detect Cluster properties
|
ir: Add machinery to detect Cluster properties
|
Python
|
mit
|
opesci/devito,opesci/devito
|
b362e6060abe631f25e5227664df4e1670f4d630
|
registration/admin.py
|
registration/admin.py
|
from django.contrib import admin
from registration.models import RegistrationProfile
class RegistrationAdmin(admin.ModelAdmin):
list_display = ('__unicode__', 'activation_key_expired')
search_fields = ('user__username', 'user__first_name')
admin.site.register(RegistrationProfile, RegistrationAdmin)
|
from django.contrib import admin
from registration.models import RegistrationProfile
class RegistrationAdmin(admin.ModelAdmin):
list_display = ('__unicode__', 'activation_key_expired')
raw_id_fields = ['user']
search_fields = ('user__username', 'user__first_name')
admin.site.register(RegistrationProfile, RegistrationAdmin)
|
Use raw_id_fields for the relation from RegistrationProfile to User, for sites which have huge numbers of users.
|
Use raw_id_fields for the relation from RegistrationProfile to User, for sites which have huge numbers of users.
|
Python
|
bsd-3-clause
|
arpitremarkable/django-registration,sergafts/django-registration,wy123123/django-registration,wda-hb/test,furious-luke/django-registration,imgmix/django-registration,matejkloska/django-registration,PetrDlouhy/django-registration,pando85/django-registration,yorkedork/django-registration,pando85/django-registration,percipient/django-registration,tanjunyen/django-registration,torchingloom/django-registration,wy123123/django-registration,kazitanvirahsan/django-registration,maitho/django-registration,kinsights/django-registration,rulz/django-registration,mick-t/django-registration,ei-grad/django-registration,nikolas/django-registration,percipient/django-registration,timgraham/django-registration,ei-grad/django-registration,mick-t/django-registration,PetrDlouhy/django-registration,arpitremarkable/django-registration,tanjunyen/django-registration,kinsights/django-registration,stillmatic/django-registration,torchingloom/django-registration,matejkloska/django-registration,imgmix/django-registration,kazitanvirahsan/django-registration,yorkedork/django-registration,memnonila/django-registration,timgraham/django-registration,Geffersonvivan/django-registration,alawnchen/django-registration,alawnchen/django-registration,erinspace/django-registration,furious-luke/django-registration,rulz/django-registration,wda-hb/test,PSU-OIT-ARC/django-registration,Geffersonvivan/django-registration,sergafts/django-registration,nikolas/django-registration,erinspace/django-registration,PSU-OIT-ARC/django-registration,allo-/django-registration,allo-/django-registration,maitho/django-registration,stillmatic/django-registration,memnonila/django-registration
|
47f2ee4587df189864029a2260b642547ea7355f
|
config.py
|
config.py
|
#Package startup stuff so people can start their iPython session with
#
#run PyQLab /path/to/cfgFile and be up and running
#Package imports
import numpy as np
#Load the configuration from the json file and populate the global configuration dictionary
import json
import os.path
import sys
PyQLabCfgFile = os.path.join(os.path.dirname( os.path.abspath(__file__) ), 'config.json')
if PyQLabCfgFile:
with open(PyQLabCfgFile, 'r') as f:
PyQLabCfg = json.load(f)
#pull out the variables
AWGDir = PyQLabCfg['AWGDir']
channelLibFile = PyQLabCfg['ChannelLibraryFile']
instrumentLibFile = PyQLabCfg['InstrumentLibraryFile']
sweepLibFile = PyQLabCfg['SweepLibraryFile']
measurementLibFile = PyQLabCfg['MeasurementLibraryFile']
quickpickFile = PyQLabCfg['QuickPickFile'] if 'QuickPickFile' in PyQLabCfg else None
else:
raise NameError("Unable to find the PyQLab configuration environment variable")
|
#Package startup stuff so people can start their iPython session with
#
#run PyQLab /path/to/cfgFile and be up and running
#Package imports
import numpy as np
#Load the configuration from the json file and populate the global configuration dictionary
import json
import os.path
import sys
PyQLabCfgFile = os.path.join(os.path.dirname( os.path.abspath(__file__) ), 'config.json')
if PyQLabCfgFile:
with open(PyQLabCfgFile, 'r') as f:
PyQLabCfg = json.load(f)
#pull out the variables
AWGDir = PyQLabCfg['AWGDir']
channelLibFile = PyQLabCfg['ChannelLibraryFile']
instrumentLibFile = PyQLabCfg['InstrumentLibraryFile']
sweepLibFile = PyQLabCfg['SweepLibraryFile']
measurementLibFile = PyQLabCfg['MeasurementLibraryFile']
quickpickFile = PyQLabCfg['QuickPickFile'] if 'QuickPickFile' in PyQLabCfg else ''
else:
raise NameError("Unable to find the PyQLab configuration environment variable")
|
Put empty string in for quickPickFile if it doesn't exist.
|
Put empty string in for quickPickFile if it doesn't exist.
|
Python
|
apache-2.0
|
Plourde-Research-Lab/PyQLab,BBN-Q/PyQLab,rmcgurrin/PyQLab,calebjordan/PyQLab
|
d60b0ee8c212728721f47cc57303ae24888cc387
|
models.py
|
models.py
|
import datetime
import math
from flask import Markup
from peewee import Model, TextField, DateTimeField
from app import db
class Quote(Model):
content = TextField()
timestamp = DateTimeField(default=datetime.datetime.now)
class Meta:
database = db
def html(self):
return Markup(self.content)
@classmethod
def paged(cls, page, page_size):
quotes = Quote.select().order_by(Quote.timestamp.desc())
page_count = math.ceil(quotes.count() / page_size)
return quotes.offset(page * page_size).limit(page_size), page_count
|
import datetime
import math
from flask import Markup
from peewee import Model, TextField, DateTimeField
from app import db
class Quote(Model):
content = TextField()
timestamp = DateTimeField(default=datetime.datetime.now)
class Meta:
database = db
def html(self):
return Markup(self.content.replace('\n', '<br>'))
@classmethod
def paged(cls, page, page_size):
quotes = Quote.select().order_by(Quote.timestamp.desc())
page_count = math.ceil(quotes.count() / page_size)
return quotes.offset(page * page_size).limit(page_size), page_count
|
Add support for carriage returns
|
Add support for carriage returns
|
Python
|
apache-2.0
|
agateau/tmc2,agateau/tmc2
|
37333506e6866e7d0859c5068f115a3e1b9dec3a
|
test/test_coordinate.py
|
test/test_coordinate.py
|
import unittest
from src import coordinate
class TestRules(unittest.TestCase):
""" Tests for the coordinate module """
def test_get_x_board(self):
board_location = coordinate.Coordinate(4, 6)
expected_result = 4
actual_result = board_location.get_x_board()
self.assertEqual(actual_result, expected_result)
def test_get_y_board(self):
board_location = coordinate.Coordinate(4, 6)
expected_result = 6
actual_result = board_location.get_y_board()
self.assertEqual(actual_result, expected_result)
def test_get_x_array(self):
board_location = coordinate.Coordinate(4, 6)
expected_result = 3
actual_result = board_location.get_x_array()
self.assertEqual(actual_result, expected_result)
def test_get_y_array(self):
board_location = coordinate.Coordinate(4, 6)
expected_result = 5
actual_result = board_location.get_y_array()
self.assertEqual(actual_result, expected_result)
|
import unittest
from src import coordinate
class TestRules(unittest.TestCase):
""" Tests for the coordinate module """
def test_get_x_board(self):
board_location = coordinate.Coordinate(4, 6)
expected_result = 4
actual_result = board_location.get_x_board()
self.assertEqual(actual_result, expected_result)
def test_get_y_board(self):
board_location = coordinate.Coordinate(4, 6)
expected_result = 6
actual_result = board_location.get_y_board()
self.assertEqual(actual_result, expected_result)
def test_get_x_array(self):
board_location = coordinate.Coordinate(4, 6)
expected_result = 3
actual_result = board_location.get_x_array()
self.assertEqual(actual_result, expected_result)
def test_get_y_array(self):
board_location = coordinate.Coordinate(4, 6)
expected_result = 5
actual_result = board_location.get_y_array()
self.assertEqual(actual_result, expected_result)
def test_coordinate_bad_x(self):
self.assertRaises(TypeError, coordinate.Coordinate, "4", 6)
def test_coordinate_bad_y(self):
self.assertRaises(TypeError, coordinate.Coordinate, 4, "6")
def test_coordinate_bad_location(self):
self.assertRaises(ValueError, coordinate.Coordinate, 50, 100)
|
Add unit tests for fail fast logic in convertCharToInt()
|
Add unit tests for fail fast logic in convertCharToInt()
|
Python
|
mit
|
blairck/jaeger
|
4622c1d2623468503b5d51683f953b82ca611b35
|
vumi/demos/tests/test_static_reply.py
|
vumi/demos/tests/test_static_reply.py
|
from twisted.internet.defer import inlineCallbacks
from vumi.application.tests.utils import ApplicationTestCase
from vumi.demos.static_reply import StaticReplyApplication
class TestStaticReplyApplication(ApplicationTestCase):
application_class = StaticReplyApplication
@inlineCallbacks
def test_receive_message(self):
yield self.get_application(config={
'reply_text': 'Your message is important to us.',
})
yield self.dispatch(self.mkmsg_in())
[reply] = yield self.get_dispatched_messages()
self.assertEqual('Your message is important to us.', reply['content'])
self.assertEqual(u'close', reply['session_event'])
@inlineCallbacks
def test_receive_message_no_reply(self):
yield self.get_application(config={})
yield self.dispatch(self.mkmsg_in())
self.assertEqual([], (yield self.get_dispatched_messages()))
|
from twisted.internet.defer import inlineCallbacks
from vumi.application.tests.helpers import ApplicationHelper
from vumi.demos.static_reply import StaticReplyApplication
from vumi.tests.helpers import VumiTestCase
class TestStaticReplyApplication(VumiTestCase):
def setUp(self):
self.app_helper = ApplicationHelper(StaticReplyApplication)
self.add_cleanup(self.app_helper.cleanup)
@inlineCallbacks
def test_receive_message(self):
yield self.app_helper.get_application({
'reply_text': 'Your message is important to us.',
})
yield self.app_helper.make_dispatch_inbound("Hello")
[reply] = self.app_helper.get_dispatched_outbound()
self.assertEqual('Your message is important to us.', reply['content'])
self.assertEqual(u'close', reply['session_event'])
@inlineCallbacks
def test_receive_message_no_reply(self):
yield self.app_helper.get_application({})
yield self.app_helper.make_dispatch_inbound("Hello")
self.assertEqual([], self.app_helper.get_dispatched_outbound())
|
Switch static_reply tests to new helpers.
|
Switch static_reply tests to new helpers.
|
Python
|
bsd-3-clause
|
vishwaprakashmishra/xmatrix,TouK/vumi,vishwaprakashmishra/xmatrix,TouK/vumi,vishwaprakashmishra/xmatrix,TouK/vumi,harrissoerja/vumi,harrissoerja/vumi,harrissoerja/vumi
|
bb04512cdf264a3ef87f3d0093db9fe10723a668
|
core/wsgi.py
|
core/wsgi.py
|
"""
WSGI config for core project.
It exposes the WSGI callable as a module-level variable named ``application``.
For more information on this file, see
https://docs.djangoproject.com/en/1.7/howto/deployment/wsgi/
"""
import os
from django.core.wsgi import get_wsgi_application
os.environ.setdefault("DJANGO_SETTINGS_MODULE", "core.settings")
application = get_wsgi_application()
|
"""
WSGI config for core project.
It exposes the WSGI callable as a module-level variable named ``application``.
For more information on this file, see
https://docs.djangoproject.com/en/1.7/howto/deployment/wsgi/
"""
import os, sys, site
site.addsitedir('/usr/local/share/virtualenvs/guhema/lib/python3.4/site-packages')
sys.path.append('/var/www/vhosts/guhema.com/httpdocs/django')
os.environ.setdefault("DJANGO_SETTINGS_MODULE", "dpb.settings")
from django.core.wsgi import get_wsgi_application
application = get_wsgi_application()
|
Add pathts for apache deployment
|
Add pathts for apache deployment
|
Python
|
mit
|
n2o/guhema,n2o/guhema
|
1c1f2cab677ead5f3cf3aa59c5094a741378e5bc
|
dame/dame.py
|
dame/dame.py
|
__author__ = "Richard Lindsley"
import sys
import sip
sip.setapi('QDate', 2)
sip.setapi('QDateTime', 2)
sip.setapi('QString', 2)
sip.setapi('QTextStream', 2)
sip.setapi('QTime', 2)
sip.setapi('QUrl', 2)
sip.setapi('QVariant', 2)
from PyQt4 import Qt
def main():
qt_app = Qt.QApplication(sys.argv)
label = Qt.QLabel("Hello, world")
label.show()
qt_app.exec_()
if __name__ == "__main__":
main()
|
__author__ = "Richard Lindsley"
import sys
#import sip
#sip.setapi('QDate', 2)
#sip.setapi('QDateTime', 2)
#sip.setapi('QString', 2)
#sip.setapi('QTextStream', 2)
#sip.setapi('QTime', 2)
#sip.setapi('QUrl', 2)
#sip.setapi('QVariant', 2)
#from PyQt4 import Qt
from PySide.QtCore import *
from PySide.QtGui import *
def main():
qt_app = QApplication(sys.argv)
label = QLabel("Hello, world")
label.show()
qt_app.exec_()
if __name__ == "__main__":
main()
|
Use pyside instead of pyqt4
|
Use pyside instead of pyqt4
|
Python
|
mit
|
richli/dame
|
08fbd4b934bc4459bb46025620b906e93f8f293e
|
voer/settings/dev.py
|
voer/settings/dev.py
|
'''
Created on 16 Dec 2013
@author: huyvq
'''
from base import *
# FOR DEBUG
DEBUG = True
DEVELOPMENT = True
TEMPLATE_DEBUG = DEBUG
# Database
# https://docs.djangoproject.com/en/1.6/ref/settings/#databases
DATABASES = {
'default': {
'ENGINE': 'django.db.backends.mysql',
'NAME': 'voer_django',
'USER': 'voer',
'PASSWORD': 'voer',
'HOST': '127.0.0.1',
'PORT': 3306,
}
}
#VPR Address
VPR_URL = 'http://localhost:2013/1.0/'
#VPT Address
VPT_URL = 'http://voer.edu.vn:6543/'
SITE_URL = 'dev.voer.vn'
RECAPTCHA_PUBLIC_KEY = '6Lf__uwSAAAAAPpTMYOLUOBf25clR7fGrqWrpOn0'
RECAPTCHA_PRIVATE_KEY = '6Lf__uwSAAAAAPlCihico8fKiAfV09_kbywiI-xx'
#STATIC_ROOT = os.path.join(PROJECT_DIR, '_static')
COMPRESS_ENABLED = False
|
'''
Created on 16 Dec 2013
@author: huyvq
'''
from base import *
# FOR DEBUG
DEBUG = True
DEVELOPMENT = True
TEMPLATE_DEBUG = DEBUG
# Database
# https://docs.djangoproject.com/en/1.6/ref/settings/#databases
DATABASES = {
'default': {
'ENGINE': 'django.db.backends.mysql',
'NAME': 'voer_django',
'USER': 'voer',
'PASSWORD': 'voer',
'HOST': '127.0.0.1',
'PORT': 3306,
}
}
#VPR Address
VPR_URL = 'http://voer.edu.vn:2013/1.0/'
#VPT Address
VPT_URL = 'http://voer.edu.vn:6543/'
SITE_URL = 'dev.voer.vn'
RECAPTCHA_PUBLIC_KEY = '6Lf__uwSAAAAAPpTMYOLUOBf25clR7fGrqWrpOn0'
RECAPTCHA_PRIVATE_KEY = '6Lf__uwSAAAAAPlCihico8fKiAfV09_kbywiI-xx'
#STATIC_ROOT = os.path.join(PROJECT_DIR, '_static')
COMPRESS_ENABLED = False
|
Correct the VPR URL in setting
|
Correct the VPR URL in setting
|
Python
|
agpl-3.0
|
voer-platform/vp.web,voer-platform/vp.web,voer-platform/vp.web,voer-platform/vp.web
|
06542afc4becb4cf3cf96dd15ab240ab4353bf2b
|
ca/views.py
|
ca/views.py
|
from flask import request, render_template
from ca import app, db
from ca.forms import RequestForm
from ca.models import Request
@app.route('/', methods=['GET'])
def index():
return render_template('index.html')
@app.route('/', methods=['POST'])
def post_request():
form = RequestForm(request.form)
if form.validate():
req = Request(form.id.data, form.email.data)
db.session.add(req)
db.session.commit()
return render_template('thanks.html')
else:
return render_template('index.html', form=form)
|
from flask import request, render_template
from ca import app, db
from ca.forms import RequestForm
from ca.models import Request
@app.route('/', methods=['GET'])
def index():
form = RequestForm()
return render_template('index.html', form=form)
@app.route('/', methods=['POST'])
def post_request():
form = RequestForm(request.form)
if form.validate():
req = Request(form.id.data, form.email.data)
db.session.add(req)
db.session.commit()
return render_template('thanks.html')
else:
return render_template('index.html', form=form)
|
Create form on index view
|
Create form on index view
- Need to always pass a form to the view
- make sure to create on for the `GET` view
- Fixes #33
|
Python
|
mit
|
freifunk-berlin/ca.berlin.freifunk.net,freifunk-berlin/ca.berlin.freifunk.net,freifunk-berlin/ca.berlin.freifunk.net
|
fa0f65b6b216a869cc6f1503e7af51481b570b78
|
player.py
|
player.py
|
# This is just be a base class / interface to be filled out by
# human and AI players.
# TODO: Undo support?
# TODO: Resign?
# super requires inheriting from object, which clashes with pickle?!
#class Player(object):
class Player():
def __init__(self, p_name):
self.p_name = p_name
self.remaining_time = 0
self.total_time = 0
def __repr__(self):
return self.p_name
def get_type(self):
return "BasePlayer"
def get_key(self):
return self.p_key
def get_name(self):
try:
name = self.p_name
except AttributeError:
name = self.name
self.p_name = name
del self.name
return name
def get_total_time(self):
return self.total_time
def tick(self, seconds):
self.remaining_time -= seconds
return self.remaining_time
def set_remaining_time(self, t):
self.remaining_time = t
def prompt_for_action(self, game, gui):
pass
def get_action(self, game, gui):
pass
def rating_factor(self):
return 1
def attach_to_game(self, base_game):
# TODO: Restore from history
self.total_time = base_game.get_rules().time_control
self.remaining_time = base_game.get_rules().time_control
|
# This is just be a base class / interface to be filled out by
# human and AI players.
# TODO: Undo support?
# TODO: Resign?
# super requires inheriting from object, which clashes with pickle?!
#class Player(object):
class Player():
def __init__(self, p_name):
self.p_name = p_name
def __repr__(self):
return self.p_name
def get_type(self):
return "BasePlayer"
def get_key(self):
return self.p_key
def get_name(self):
try:
name = self.p_name
except AttributeError:
name = self.name
self.p_name = name
del self.name
return name
def prompt_for_action(self, game, gui):
pass
def get_action(self, game, gui):
pass
def rating_factor(self):
return 1
def attach_to_game(self, base_game):
pass
|
Remove unused time control support (better in Game)
|
Remove unused time control support (better in Game)
|
Python
|
mit
|
cropleyb/pentai,cropleyb/pentai,cropleyb/pentai
|
9605b60fb537714c295dfa0f50313e38f89d2d88
|
app.py
|
app.py
|
"""
This is a simple cheatsheet webapp.
"""
import os
from flask import Flask, send_from_directory
from flask_sslify import SSLify
DIR = os.path.dirname(os.path.realpath(__file__))
ROOT = os.path.join(DIR, 'docs', '_build', 'html')
app = Flask(__name__)
if 'DYNO' in os.environ:
sslify = SSLify(app)
@app.route('/<path:path>')
def static_proxy(path):
"""Static files proxy"""
return send_from_directory(ROOT, path)
@app.route('/')
def index_redirection():
"""Redirecting index file"""
return send_from_directory(ROOT, 'index.html')
if __name__ == "__main__":
app.run(debug=True)
|
"""
This is a simple cheatsheet webapp.
"""
import os
from flask import Flask, send_from_directory
from flask_sslify import SSLify
DIR = os.path.dirname(os.path.realpath(__file__))
ROOT = os.path.join(DIR, 'docs', '_build', 'html')
def find_key(token):
if token == os.environ.get("ACME_TOKEN"):
return os.environ.get("ACME_KEY")
for k, v in os.environ.items():
if v == token and k.startswith("ACME_TOKEN_"):
n = k.replace("ACME_TOKEN_", "")
return os.environ.get("ACME_KEY_{}".format(n))
app = Flask(__name__)
if 'DYNO' in os.environ:
sslify = SSLify(app, skips=['.well-known'])
@app.route('/<path:path>')
def static_proxy(path):
"""Static files proxy"""
return send_from_directory(ROOT, path)
@app.route('/')
def index_redirection():
"""Redirecting index file"""
return send_from_directory(ROOT, 'index.html')
@app.route("/.well-known/acme-challenge/<token>")
def acme(token):
key = find_key(token)
if key is None: abort(404)
return key
if __name__ == "__main__":
app.run(debug=True)
|
Add letsencrypt auto renew api :octocat:
|
Add letsencrypt auto renew api :octocat:
|
Python
|
mit
|
caimaoy/pysheeet
|
a621a7803d177e4851d229973586d9b114b0f84c
|
__init__.py
|
__init__.py
|
# -*- coding: utf-8 -*-
from flask import Flask
from flask.ext.mongoengine import MongoEngine, MongoEngineSessionInterface
import configparser
app = Flask(__name__)
# Security
WTF_CSRF_ENABLED = True
app.config['SECRET_KEY'] = '2bN9UUaBpcjrxR'
# App Config
config = configparser.ConfigParser()
config.read('config/config.ini')
app.config['MONGODB_DB'] = config['MongoDB']['db_name']
app.config['MONGODB_HOST'] = config['MongoDB']['host']
app.config['MONGODB_PORT'] = int(config['MongoDB']['port'])
app.config['MONGODB_USERNAME'] = config['MongoDB']['username']
app.config['MONGODB_PASSWORD'] = config['MongoDB']['password']
db = MongoEngine(app)
def register_blueprints(app):
# Prevents circular imports
from weighttracker.views.measurement_views import measurements
app.register_blueprint(measurements)
from weighttracker.views.inspiration_views import inspirations
app.register_blueprint(inspirations)
register_blueprints(app)
if __name__ == '__main__':
app.run()
|
# -*- coding: utf-8 -*-
from flask import Flask, render_template
from flask.ext.mongoengine import MongoEngine, MongoEngineSessionInterface
import configparser
app = Flask(__name__)
# Security
WTF_CSRF_ENABLED = True
app.config['SECRET_KEY'] = '2bN9UUaBpcjrxR'
# App Config
config = configparser.ConfigParser()
config.read('config/config.ini')
app.config['MONGODB_DB'] = config['MongoDB']['db_name']
app.config['MONGODB_HOST'] = config['MongoDB']['host']
app.config['MONGODB_PORT'] = int(config['MongoDB']['port'])
app.config['MONGODB_USERNAME'] = config['MongoDB']['username']
app.config['MONGODB_PASSWORD'] = config['MongoDB']['password']
db = MongoEngine(app)
def register_blueprints(app):
# Prevents circular imports
from weighttracker.views.measurement_views import measurements
app.register_blueprint(measurements)
from weighttracker.views.inspiration_views import inspirations
app.register_blueprint(inspirations)
register_blueprints(app)
@app.route('/', defaults={'path': ''})
@app.route('/<path:path>')
def catch_all(path):
return render_template('index.html')
if __name__ == '__main__':
app.run()
|
Create a catch-all route and route to the homepage.
|
Create a catch-all route and route to the homepage.
Signed-off-by: Robert Dempsey <[email protected]>
|
Python
|
mit
|
rdempsey/weight-tracker,rdempsey/weight-tracker,rdempsey/weight-tracker
|
01b511b1f337f00eb72530692eec202611599c5a
|
tilequeue/queue/file.py
|
tilequeue/queue/file.py
|
from tilequeue.tile import serialize_coord, deserialize_coord, CoordMessage
import threading
class OutputFileQueue(object):
def __init__(self, fp):
self.fp = fp
self.lock = threading.RLock()
def enqueue(self, coord):
with self.lock:
payload = serialize_coord(coord)
self.fp.write(payload + '\n')
def enqueue_batch(self, coords):
n = 0
for coord in coords:
self.enqueue(coord)
n += 1
return n, 0
def read(self, max_to_read=1, timeout_seconds=20):
with self.lock:
coords = []
for _ in range(max_to_read):
coord = self.fp.readline()
if coord:
coords.append(CoordMessage(deserialize_coord(coord), None))
else:
break
return coords
def job_done(self, coord_message):
pass
def clear(self):
with self.lock:
self.fp.seek(0)
self.fp.truncate()
return -1
def close(self):
with self.lock:
remaining_queue = ''.join([ln for ln in self.fp])
self.clear()
self.fp.write(remaining_queue)
self.fp.close()
|
from tilequeue.tile import serialize_coord, deserialize_coord, CoordMessage
import threading
class OutputFileQueue(object):
def __init__(self, fp):
self.fp = fp
self.lock = threading.RLock()
def enqueue(self, coord):
with self.lock:
payload = serialize_coord(coord)
self.fp.write(payload + '\n')
def enqueue_batch(self, coords):
n = 0
for coord in coords:
self.enqueue(coord)
n += 1
return n, 0
def read(self, max_to_read=1, timeout_seconds=20):
with self.lock:
coords = []
for _ in range(max_to_read):
coord = self.fp.readline()
if coord:
coords.append(CoordMessage(deserialize_coord(coord), None))
else:
break
return coords
def job_done(self, coord_message):
pass
def clear(self):
with self.lock:
self.fp.seek(0)
self.fp.truncate()
return -1
def close(self):
with self.lock:
self.clear()
self.fp.write(self.fp.read())
self.fp.close()
|
Fix a bug in OutputFileQueue.close().
|
Fix a bug in OutputFileQueue.close().
tilequeue/queue/file.py
-01a8fcb made `OutputFileQueue.read()` use `readline()` instead
of `next()`, but didn't update `OutputFileQueue.close()`, which
uses a list comprehension to grab the rest of the file. Since
`.read()` no longer uses the iteration protocol, `.close()` will
start iterating from the beginning of the file. Use `.read()`
instead of a list comprehension to only grab everything after
what `.readline()` already picked up.
|
Python
|
mit
|
mapzen/tilequeue,tilezen/tilequeue
|
7e8623f750abb9d5d46be25ca184ab0036e7a572
|
runapp.py
|
runapp.py
|
# Copyright 2014 Dave Kludt
#
# 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 anchor import app
if __name__ == '__main__':
app.run(port=5000, debug=True)
|
# Copyright 2014 Dave Kludt
#
# 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 anchor import app
if __name__ == '__main__':
app.run(host='0.0.0.0', port=5000, debug=True)
|
Set the host to use all IPs when runap is used
|
Set the host to use all IPs when runap is used
|
Python
|
apache-2.0
|
oldarmyc/anchor,oldarmyc/anchor,oldarmyc/anchor
|
8d02d9cf5e07951a80bf424334ba59af92cfd6cc
|
test/suite/out/long_lines.py
|
test/suite/out/long_lines.py
|
if True:
if True:
if True:
self.__heap.sort(
) # pylint: builtin sort probably faster than O(n)-time heapify
if True:
foo = '( ' + \
array[0] + ' '
|
if True:
if True:
if True:
self.__heap.sort(
) # pylint: builtin sort probably faster than O(n)-time heapify
if True:
foo = '( ' + array[0] + ' '
|
Update due to logical line changes
|
Update due to logical line changes
|
Python
|
mit
|
vauxoo-dev/autopep8,SG345/autopep8,MeteorAdminz/autopep8,Vauxoo/autopep8,SG345/autopep8,hhatto/autopep8,Vauxoo/autopep8,MeteorAdminz/autopep8,hhatto/autopep8,vauxoo-dev/autopep8
|
45c7e910f13a43427359801782eef7ce537d6f5f
|
delayed_assert/__init__.py
|
delayed_assert/__init__.py
|
from delayed_assert.delayed_assert import expect, assert_expectations
|
import sys
if sys.version_info > (3, 0): # Python 3 and above
from delayed_assert.delayed_assert import expect, assert_expectations
else: # for Python 2
from delayed_assert import expect, assert_expectations
|
Support for python 2 and 3
|
Support for python 2 and 3
|
Python
|
unlicense
|
pr4bh4sh/python-delayed-assert
|
8154b206160cde249c474f5905a60b9a8086c910
|
conftest.py
|
conftest.py
|
# Copyright (c) 2016,2019 MetPy Developers.
# Distributed under the terms of the BSD 3-Clause License.
# SPDX-License-Identifier: BSD-3-Clause
"""Configure pytest for metpy."""
import os
import matplotlib
import matplotlib.pyplot
import numpy
import pandas
import pytest
import scipy
import xarray
import metpy.calc
# Need to disable fallback before importing pint
os.environ['PINT_ARRAY_PROTOCOL_FALLBACK'] = '0'
import pint # noqa: I100, E402
def pytest_report_header(config, startdir):
"""Add dependency information to pytest output."""
return ('Dependencies: Matplotlib ({}), NumPy ({}), Pandas ({}), '
'Pint ({}), SciPy ({}), Xarray ({})'.format(matplotlib.__version__,
numpy.__version__, pandas.__version__,
pint.__version__, scipy.__version__,
xarray.__version__))
@pytest.fixture(autouse=True)
def doctest_available_modules(doctest_namespace):
"""Make modules available automatically to doctests."""
doctest_namespace['metpy'] = metpy
doctest_namespace['metpy.calc'] = metpy.calc
doctest_namespace['plt'] = matplotlib.pyplot
|
# Copyright (c) 2016,2019 MetPy Developers.
# Distributed under the terms of the BSD 3-Clause License.
# SPDX-License-Identifier: BSD-3-Clause
"""Configure pytest for metpy."""
import os
import matplotlib
import matplotlib.pyplot
import numpy
import pandas
import pooch
import pytest
import scipy
import traitlets
import xarray
import metpy.calc
# Need to disable fallback before importing pint
os.environ['PINT_ARRAY_PROTOCOL_FALLBACK'] = '0'
import pint # noqa: I100, E402
def pytest_report_header(config, startdir):
"""Add dependency information to pytest output."""
return (f'Dep Versions: Matplotlib {matplotlib.__version__}, '
f'NumPy {numpy.__version__}, SciPy {scipy.__version__}, '
f'Xarray {xarray.__version__}, Pint {pint.__version__}, '
f'Pandas {pandas.__version__}, Traitlets {traitlets.__version__}, '
f'Pooch {pooch.version.full_version}')
@pytest.fixture(autouse=True)
def doctest_available_modules(doctest_namespace):
"""Make modules available automatically to doctests."""
doctest_namespace['metpy'] = metpy
doctest_namespace['metpy.calc'] = metpy.calc
doctest_namespace['plt'] = matplotlib.pyplot
|
Print out all dependency versions at the start of pytest
|
TST: Print out all dependency versions at the start of pytest
|
Python
|
bsd-3-clause
|
Unidata/MetPy,dopplershift/MetPy,Unidata/MetPy,dopplershift/MetPy
|
5f62f830d184c0f99b384f0653231dab52fbad50
|
conftest.py
|
conftest.py
|
import logging
import os
import signal
import subprocess
import time
import pytest
log = logging.getLogger("test")
logging.basicConfig(
level=logging.DEBUG,
format='%(asctime)s %(levelname)s [%(name)s] %(message)s')
@pytest.fixture
def basedir(tmpdir):
# 1. Create real file system with a special __ready__ file.
realfs = tmpdir.mkdir("realfs")
realfs.join("__ready__").write("")
# 2. Create slowfs mountpoint
slowfs = tmpdir.mkdir("slowfs")
# 3. Start slowfs
log.debug("Starting slowfs...")
cmd = ["./slowfs", str(realfs), str(slowfs)]
if os.environ.get("DEBUG"):
cmd.append("--debug")
p = subprocess.Popen(cmd)
try:
# 4. Wait until __ready__ is visible via slowfs...
log.debug("Waiting until mount is ready...")
ready = slowfs.join("__ready__")
for i in range(10):
time.sleep(0.1)
log.debug("Checking mount...")
if ready.exists():
log.debug("Mount is ready")
break
else:
raise RuntimeError("Timeout waiting for slowfs mount %r" % slowfs)
# 4. We are ready for the test
yield tmpdir
finally:
# 5. Interrupt slowfs, unmounting
log.debug("Stopping slowfs...")
p.send_signal(signal.SIGINT)
p.wait()
log.debug("Stopped")
|
import logging
import os
import signal
import subprocess
import time
import pytest
log = logging.getLogger("test")
logging.basicConfig(
level=logging.DEBUG,
format='%(asctime)s %(levelname)s [%(name)s] %(message)s')
@pytest.fixture
def basedir(tmpdir):
# 1. Create real file system with a special __ready__ file.
realfs = tmpdir.mkdir("realfs")
realfs.join("__ready__").write("")
# 2. Create slowfs mountpoint
slowfs = tmpdir.mkdir("slowfs")
# 3. Start slowfs
log.debug("Starting slowfs...")
cmd = ["python", "slowfs", str(realfs), str(slowfs)]
if os.environ.get("DEBUG"):
cmd.append("--debug")
p = subprocess.Popen(cmd)
try:
# 4. Wait until __ready__ is visible via slowfs...
log.debug("Waiting until mount is ready...")
ready = slowfs.join("__ready__")
for i in range(10):
time.sleep(0.1)
log.debug("Checking mount...")
if ready.exists():
log.debug("Mount is ready")
break
else:
raise RuntimeError("Timeout waiting for slowfs mount %r" % slowfs)
# 4. We are ready for the test
yield tmpdir
finally:
# 5. Interrupt slowfs, unmounting
log.debug("Stopping slowfs...")
p.send_signal(signal.SIGINT)
p.wait()
log.debug("Stopped")
|
Fix tests, broken by making slowfs a script
|
Fix tests, broken by making slowfs a script
In the tests we must run the script using python so we run with the
correct python from .tox/<env>/bin/python.
|
Python
|
bsd-2-clause
|
nirs/slowfs
|
f7fa8b72b8d8d1b7bfcd6c738520fc87cd20e320
|
ixdjango/tests/__init__.py
|
ixdjango/tests/__init__.py
|
"""
Hook into the test runner
"""
import subprocess
from django.test.simple import DjangoTestSuiteRunner
from django.utils import unittest
from ixdjango.test_suite.utils import (CoreUtilsTests)
class TestRunner(DjangoTestSuiteRunner):
"""
Place where we hook into DjangoTestSuiteRunner
"""
def setup_test_environment(self, *args, **kwargs):
"""
Hook to set up the test environment
"""
from django.conf import settings
print "Running hooks from %s" % __name__
username = settings.DATABASES['default']['USER']
print " - Ensure %s can create a test DB" % username
subprocess.call(['sudo', 'su', 'postgres', '-c',
"psql -c 'alter user %s with createdb;'" % username])
return super(TestRunner, self).setup_test_environment(*args, **kwargs)
def suite():
"""
Put together a suite of tests to run for the application
"""
loader = unittest.TestLoader()
all_tests = unittest.TestSuite([
#
# Utilities test cases
#
loader.loadTestsFromTestCase(CoreUtilsTests)
])
return all_tests
|
"""
Hook into the test runner
"""
import subprocess
try:
from django.test.runner import DiscoverRunner as BaseTestRunner
except ImportError:
from django.test.simple import DjangoTestSuiteRunner as BaseTestRunner
from django.utils import unittest
from ixdjango.test_suite.utils import (CoreUtilsTests)
class TestRunner(BaseTestRunner):
"""
Place where we hook into DjangoTestSuiteRunner
"""
def setup_test_environment(self, *args, **kwargs):
"""
Hook to set up the test environment
"""
from django.conf import settings
print "Running hooks from %s" % __name__
username = settings.DATABASES['default']['USER']
print " - Ensure %s can create a test DB" % username
subprocess.call(['sudo', 'su', 'postgres', '-c',
"psql -c 'alter user %s with createdb;'" % username])
return super(TestRunner, self).setup_test_environment(*args, **kwargs)
def suite():
"""
Put together a suite of tests to run for the application
"""
loader = unittest.TestLoader()
all_tests = unittest.TestSuite([
#
# Utilities test cases
#
loader.loadTestsFromTestCase(CoreUtilsTests)
])
return all_tests
|
Use DiscoverRunner from Django 1.6 if available
|
Use DiscoverRunner from Django 1.6 if available
|
Python
|
mit
|
infoxchange/ixdjango
|
4241c6cbd9625c61a32ded5725e583da2b63a377
|
homedisplay/display/views.py
|
homedisplay/display/views.py
|
from django.http import HttpResponseRedirect, HttpResponse, Http404
from django.shortcuts import render_to_response
from django.template import RequestContext
from django.views.generic import View
from homedisplay.utils import publish_ws
class Wrapped(View):
def get(self, request, *args, **kwargs):
return render_to_response("frame.html", {"frame_src": "/homecontroller/display/content/%s" % kwargs.get("view") }, context_instance=RequestContext(request))
|
from django.http import HttpResponseRedirect, HttpResponse, Http404
from django.shortcuts import render_to_response
from django.template import RequestContext
from django.views.generic import View
from homedisplay.utils import publish_ws
class Wrapped(View):
def get(self, request, *args, **kwargs):
return render_to_response("main/frame.html", {"frame_src": "/homecontroller/display/content/%s" % kwargs.get("view") }, context_instance=RequestContext(request))
|
Use correct path for frame template
|
Use correct path for frame template
|
Python
|
bsd-3-clause
|
ojarva/home-info-display,ojarva/home-info-display,ojarva/home-info-display,ojarva/home-info-display
|
ee03f3ae0d0501568cec87d8d4d7114441c19776
|
conftest.py
|
conftest.py
|
collect_ignore = ["setup.py"]
|
import tempfile
import shutil
import jedi
collect_ignore = ["setup.py"]
# The following hooks (pytest_configure, pytest_unconfigure) are used
# to modify `jedi.settings.cache_directory` because `clean_jedi_cache`
# has no effect during doctests. Without these hooks, doctests uses
# user's cache (e.g., ~/.cache/jedi/). We should remove this
# workaround once the problem is fixed in py.test.
#
# See:
# - https://github.com/davidhalter/jedi/pull/168
# - https://bitbucket.org/hpk42/pytest/issue/275/
jedi_cache_directory_orig = None
jedi_cache_directory_temp = None
def pytest_configure(config):
global jedi_cache_directory_orig, jedi_cache_directory_temp
jedi_cache_directory_orig = jedi.settings.cache_directory
jedi_cache_directory_temp = tempfile.mkdtemp(prefix='jedi-test-')
jedi.settings.cache_directory = jedi_cache_directory_temp
def pytest_unconfigure(config):
global jedi_cache_directory_orig, jedi_cache_directory_temp
jedi.settings.cache_directory = jedi_cache_directory_orig
shutil.rmtree(jedi_cache_directory_temp)
|
Use pytest_(un)configure to setup cache_directory
|
Use pytest_(un)configure to setup cache_directory
|
Python
|
mit
|
jonashaag/jedi,jonashaag/jedi,flurischt/jedi,WoLpH/jedi,tjwei/jedi,mfussenegger/jedi,mfussenegger/jedi,tjwei/jedi,dwillmer/jedi,WoLpH/jedi,flurischt/jedi,dwillmer/jedi
|
62ad2eb82c037350f25d3e575e59f16740365159
|
pies/ast.py
|
pies/ast.py
|
from __future__ import absolute_import
from ast import *
from .version_info import PY2
if PY2:
Try = TryExcept
def argument_names(node):
return [isinstance(arg, Name) and arg.id or None for arg in node.args.args]
def kw_only_argument_names(node):
return []
def kw_only_default_count(node):
return 0
else:
TryFinally = ()
def argument_names(node):
return [arg.arg for arg in node.args.args]
def kw_only_argument_names(node):
return [arg.arg for arg in node.args.kwonlyargs]
def kw_only_default_count(node):
return sum(1 for n in node.args.kw_defaults if n is not None)
|
from __future__ import absolute_import
import sys
from ast import *
from .version_info import PY2
if PY2 or sys.version_info[1] <= 2:
Try = TryExcept
else:
TryFinally = ()
if PY2:
def argument_names(node):
return [isinstance(arg, Name) and arg.id or None for arg in node.args.args]
def kw_only_argument_names(node):
return []
def kw_only_default_count(node):
return 0
else:
def argument_names(node):
return [arg.arg for arg in node.args.args]
def kw_only_argument_names(node):
return [arg.arg for arg in node.args.kwonlyargs]
def kw_only_default_count(node):
return sum(1 for n in node.args.kw_defaults if n is not None)
|
Fix small incompatibility with Python 3.2
|
Fix small incompatibility with Python 3.2
|
Python
|
mit
|
lisongmin/pies,AbsoluteMSTR/pies,timothycrosley/pies,AbsoluteMSTR/pies,timothycrosley/pies,lisongmin/pies
|
5cbf2988e9064a49e2d745694c8233513be63a0b
|
openings_mover.py
|
openings_mover.py
|
import random
import pdb
from defines import *
class OpeningsMover(object):
def __init__(self, o_mgr, game):
self.o_mgr = o_mgr
self.game = game
def get_a_good_move(self):
wins = 0
losses = 0
totals = []
colour = self.game.to_move_colour()
max_rating_factor = 1
move_games = self.o_mgr.get_move_games(self.game)
for mg in move_games:
move, games = mg
for g in games:
win_colour = g.get_won_by()
if win_colour == colour:
wins += 1
else:
assert(win_colour == opposite_colour(colour))
losses += 1
# Calc & save the maximum rating of the players
# who made this move
move_player = g.get_player(colour)
if move_player:
max_rating_factor = \
max(max_rating_factor, move_player.rating_factor())
totals.append((move, wins, losses, max_rating_factor))
total_score = 1 # For fall through to inner filter
move_scores = []
for move, wins, losses, mrf in totals:
score = (mrf * (wins))/(losses or .2)
move_scores.append((move, score))
total_score += score
rand_val = random.random() * total_score
for move, score in move_scores:
if score > rand_val:
return move
rand_val -= score
# Fall through to inner filter
return None
|
import random
import pdb
from defines import *
class OpeningsMover(object):
def __init__(self, o_mgr, game):
self.o_mgr = o_mgr
self.game = game
def get_a_good_move(self):
wins = 0
losses = 0
totals = []
colour = self.game.to_move_colour()
max_rating_factor = 1
move_games = self.o_mgr.get_move_games(self.game)
for mg in move_games:
move, games = mg
for pg in games:
win_colour = pg.won_by
if win_colour == colour:
wins += 1
elif win_colour == opposite_colour(colour):
losses += 1
# else ignore draws and unfinished games (latter shouldn't get here)
move_rating = pg.get_rating(colour)
# TODO: More smarts here
max_rating_factor = \
max(max_rating_factor, move_rating)
totals.append((move, wins, losses, max_rating_factor))
total_score = 1 # For fall through to inner filter
move_scores = []
for move, wins, losses, mrf in totals:
score = (mrf * (wins))/(losses or .2)
move_scores.append((move, score))
total_score += score
rand_val = random.random() * total_score
for move, score in move_scores:
if score > rand_val:
return move
rand_val -= score
# Fall through to inner filter
return None
|
Use preserved games for opening move selection
|
Use preserved games for opening move selection
|
Python
|
mit
|
cropleyb/pentai,cropleyb/pentai,cropleyb/pentai
|
99bcbd8795f3e2b1a10ac8fa81dd69d1cad7c022
|
yunity/api/serializers.py
|
yunity/api/serializers.py
|
def user(model):
if not model.is_authenticated():
return {}
return {
'id': model.id,
'display_name': model.display_name,
'first_name': model.first_name,
'last_name': model.last_name,
}
def category(model):
return {
'id': model.id,
'name': model.name,
'parent': model.parent_id,
}
def conversation(model):
participants = [_['id'] for _ in model.participants.order_by('id').values('id')]
newest_message = model.messages.order_by('-created_at').first()
return {
'id': model.id,
'name': model.name,
'participants': participants,
'message': conversation_message(newest_message),
}
def conversation_message(model):
return {
'id': model.id,
'sender': model.sent_by_id,
'created_at': model.created_at.isoformat(),
'content': model.content,
}
|
def user(model):
if not model.is_authenticated():
return {}
return {
'id': model.id,
'display_name': model.display_name,
'first_name': model.first_name,
'last_name': model.last_name,
}
def category(model):
return {
'id': model.id,
'name': model.name,
'parent': model.parent_id,
}
def conversation(model):
participants = [_['id'] for _ in model.participants.order_by('id').values('id')]
newest_message = model.messages.order_by('-created_at').first()
return {
'id': model.id,
'name': model.name,
'participants': participants,
'message': conversation_message(newest_message),
}
def conversation_message(model):
if model:
return {
'id': model.id,
'sender': model.sent_by_id,
'created_at': model.created_at.isoformat(),
'content': model.content,
}
else:
return None
|
Allow empty conversations to be serialized
|
Allow empty conversations to be serialized
A conversation may exist without any content. The serializer then
returns an empty message value.
|
Python
|
agpl-3.0
|
yunity/foodsaving-backend,yunity/yunity-core,yunity/foodsaving-backend,yunity/foodsaving-backend,yunity/yunity-core
|
d6f2b132844d1923932447c0ce67c581f723f433
|
wagtail/wagtailadmin/menu.py
|
wagtail/wagtailadmin/menu.py
|
from __future__ import unicode_literals
from six import text_type
from django.utils.text import slugify
from django.utils.html import format_html
class MenuItem(object):
def __init__(self, label, url, name=None, classnames='', order=1000):
self.label = label
self.url = url
self.classnames = classnames
self.name = (name or slugify(text_type(label)))
self.order = order
def render_html(self):
return format_html(
"""<li class="menu-{0}"><a href="{1}" class="{2}">{3}</a></li>""",
self.name, self.url, self.classnames, self.label)
|
from __future__ import unicode_literals
from six import text_type
try:
# renamed util -> utils in Django 1.7; try the new name first
from django.forms.utils import flatatt
except ImportError:
from django.forms.util import flatatt
from django.utils.text import slugify
from django.utils.html import format_html
class MenuItem(object):
def __init__(self, label, url, name=None, classnames='', attrs=None, order=1000):
self.label = label
self.url = url
self.classnames = classnames
self.name = (name or slugify(text_type(label)))
self.order = order
if attrs:
self.attr_string = flatatt(attrs)
else:
self.attr_string = ""
def render_html(self):
return format_html(
"""<li class="menu-{0}"><a href="{1}" class="{2}"{3}>{4}</a></li>""",
self.name, self.url, self.classnames, self.attr_string, self.label)
|
Support passing html attributes into MenuItem
|
Support passing html attributes into MenuItem
|
Python
|
bsd-3-clause
|
JoshBarr/wagtail,m-sanders/wagtail,hamsterbacke23/wagtail,benemery/wagtail,jordij/wagtail,nutztherookie/wagtail,mixxorz/wagtail,nutztherookie/wagtail,dresiu/wagtail,serzans/wagtail,mixxorz/wagtail,bjesus/wagtail,nrsimha/wagtail,nilnvoid/wagtail,inonit/wagtail,torchbox/wagtail,wagtail/wagtail,dresiu/wagtail,davecranwell/wagtail,timorieber/wagtail,kurtrwall/wagtail,Pennebaker/wagtail,kaedroho/wagtail,kurtrwall/wagtail,thenewguy/wagtail,jnns/wagtail,nealtodd/wagtail,rsalmaso/wagtail,taedori81/wagtail,mephizzle/wagtail,stevenewey/wagtail,quru/wagtail,marctc/wagtail,tangentlabs/wagtail,Klaudit/wagtail,quru/wagtail,gogobook/wagtail,kurtrwall/wagtail,takeshineshiro/wagtail,rsalmaso/wagtail,quru/wagtail,wagtail/wagtail,thenewguy/wagtail,benjaoming/wagtail,mixxorz/wagtail,taedori81/wagtail,nrsimha/wagtail,taedori81/wagtail,nilnvoid/wagtail,zerolab/wagtail,mephizzle/wagtail,rjsproxy/wagtail,darith27/wagtail,benjaoming/wagtail,iho/wagtail,jnns/wagtail,rv816/wagtail,nealtodd/wagtail,torchbox/wagtail,serzans/wagtail,mephizzle/wagtail,WQuanfeng/wagtail,takeflight/wagtail,mjec/wagtail,thenewguy/wagtail,torchbox/wagtail,rjsproxy/wagtail,jorge-marques/wagtail,m-sanders/wagtail,iho/wagtail,benemery/wagtail,serzans/wagtail,stevenewey/wagtail,janusnic/wagtail,JoshBarr/wagtail,chimeno/wagtail,Tivix/wagtail,chimeno/wagtail,nilnvoid/wagtail,Klaudit/wagtail,chrxr/wagtail,marctc/wagtail,KimGlazebrook/wagtail-experiment,gogobook/wagtail,zerolab/wagtail,dresiu/wagtail,takeflight/wagtail,nimasmi/wagtail,nimasmi/wagtail,JoshBarr/wagtail,Pennebaker/wagtail,hanpama/wagtail,davecranwell/wagtail,iansprice/wagtail,kaedroho/wagtail,inonit/wagtail,mixxorz/wagtail,rv816/wagtail,KimGlazebrook/wagtail-experiment,stevenewey/wagtail,inonit/wagtail,jordij/wagtail,kurtw/wagtail,bjesus/wagtail,mephizzle/wagtail,jorge-marques/wagtail,torchbox/wagtail,nilnvoid/wagtail,chimeno/wagtail,gasman/wagtail,mjec/wagtail,dresiu/wagtail,hanpama/wagtail,hamsterbacke23/wagtail,rv816/wagtail,KimGlazebrook/wagtail-experiment,tangentlabs/wagtail,mayapurmedia/wagtail,willcodefortea/wagtail,FlipperPA/wagtail,FlipperPA/wagtail,gogobook/wagtail,timorieber/wagtail,jnns/wagtail,m-sanders/wagtail,nutztherookie/wagtail,nimasmi/wagtail,hamsterbacke23/wagtail,mjec/wagtail,thenewguy/wagtail,wagtail/wagtail,kaedroho/wagtail,willcodefortea/wagtail,willcodefortea/wagtail,bjesus/wagtail,gasman/wagtail,chrxr/wagtail,gogobook/wagtail,zerolab/wagtail,rjsproxy/wagtail,wagtail/wagtail,nrsimha/wagtail,Klaudit/wagtail,iho/wagtail,mjec/wagtail,chrxr/wagtail,timorieber/wagtail,FlipperPA/wagtail,benemery/wagtail,mikedingjan/wagtail,mikedingjan/wagtail,gasman/wagtail,janusnic/wagtail,Toshakins/wagtail,WQuanfeng/wagtail,rv816/wagtail,takeflight/wagtail,WQuanfeng/wagtail,janusnic/wagtail,rjsproxy/wagtail,nutztherookie/wagtail,janusnic/wagtail,iansprice/wagtail,JoshBarr/wagtail,jnns/wagtail,takeshineshiro/wagtail,kaedroho/wagtail,willcodefortea/wagtail,taedori81/wagtail,bjesus/wagtail,jorge-marques/wagtail,Tivix/wagtail,darith27/wagtail,marctc/wagtail,mayapurmedia/wagtail,gasman/wagtail,mayapurmedia/wagtail,tangentlabs/wagtail,dresiu/wagtail,iansprice/wagtail,kaedroho/wagtail,kurtw/wagtail,inonit/wagtail,benjaoming/wagtail,Tivix/wagtail,zerolab/wagtail,stevenewey/wagtail,mayapurmedia/wagtail,davecranwell/wagtail,jorge-marques/wagtail,darith27/wagtail,chimeno/wagtail,Toshakins/wagtail,rsalmaso/wagtail,nrsimha/wagtail,gasman/wagtail,Tivix/wagtail,nealtodd/wagtail,Pennebaker/wagtail,rsalmaso/wagtail,jordij/wagtail,jorge-marques/wagtail,benemery/wagtail,iho/wagtail,hamsterbacke23/wagtail,FlipperPA/wagtail,hanpama/wagtail,takeshineshiro/wagtail,kurtw/wagtail,nimasmi/wagtail,iansprice/wagtail,kurtrwall/wagtail,nealtodd/wagtail,davecranwell/wagtail,rsalmaso/wagtail,timorieber/wagtail,Pennebaker/wagtail,Klaudit/wagtail,serzans/wagtail,m-sanders/wagtail,marctc/wagtail,taedori81/wagtail,darith27/wagtail,thenewguy/wagtail,chimeno/wagtail,zerolab/wagtail,takeflight/wagtail,chrxr/wagtail,mikedingjan/wagtail,Toshakins/wagtail,mikedingjan/wagtail,KimGlazebrook/wagtail-experiment,quru/wagtail,Toshakins/wagtail,tangentlabs/wagtail,WQuanfeng/wagtail,kurtw/wagtail,mixxorz/wagtail,hanpama/wagtail,takeshineshiro/wagtail,benjaoming/wagtail,jordij/wagtail,wagtail/wagtail
|
a056c630a197a070e55cce9f76124d56ba781e52
|
app/views/main.py
|
app/views/main.py
|
from flask import Blueprint, render_template
from flask_login import login_required
main = Blueprint("main", __name__)
@main.route("/")
@main.route("/index")
@login_required
def index():
return "Logged in"
@main.route("/login")
def login():
return render_template("login.html")
|
from flask import Blueprint, render_template, g, redirect, url_for
from flask_login import login_required, current_user, logout_user
main = Blueprint("main", __name__)
@main.route("/")
@main.route("/index")
@login_required
def index():
return "Logged in"
@main.route("/login")
def login():
if g.user.is_authenticated:
return redirect(url_for("main.index"))
return render_template("login.html")
@main.route("/logout")
def logout():
logout_user()
return redirect(url_for("main.login"))
@main.before_request
def before_request():
g.user = current_user
|
Add logout and auth checks
|
Add logout and auth checks
|
Python
|
mit
|
Encrylize/MyDictionary,Encrylize/MyDictionary,Encrylize/MyDictionary
|
9c07f8fdb9c955f49cf6ff92a25b1c0629157811
|
assembler6502.py
|
assembler6502.py
|
#! /usr/bin/env python
import sys
import assembler6502_tokenizer as tokenizer
import assembler6502_parser as parser
def output_byte(hexcode):
sys.stdout.write(hexcode)
#sys.stdout.write(chr(int(hexcode, 16)))
def main():
code = """
; sample code
beginning:
sty $44,X
"""
for line in code.split("\n"):
hexcodes = parser.parse_line(line)
for hexcode in hexcodes:
output_byte(hexcode)
print
if __name__ == "__main__":
main()
|
#! /usr/bin/env python
import sys
import assembler6502_tokenizer as tokenizer
import assembler6502_parser as parser
def output_byte(hexcode):
sys.stdout.write(hexcode + "\n")
#sys.stdout.write(chr(int(hexcode, 16)))
def main():
code = sys.stdin.read()
for line in code.split("\n"):
hexcodes = parser.parse_line(line)
for hexcode in hexcodes:
output_byte(hexcode)
if __name__ == "__main__":
main()
|
Use stdin for assembler input
|
Use stdin for assembler input
|
Python
|
mit
|
technetia/project-tdm,technetia/project-tdm,technetia/project-tdm
|
358df6514b19424d5576d7a0a74ea15d71a3565b
|
canaryd/subprocess.py
|
canaryd/subprocess.py
|
import os
import shlex
import sys
from canaryd_packages import six
# Not ideal but using the vendored in (to requests) chardet package
from canaryd_packages.requests.packages import chardet
from canaryd.log import logger
if os.name == 'posix' and sys.version_info[0] < 3:
from canaryd_packages.subprocess32 import * # noqa
else:
from subprocess import * # noqa
def get_command_output(command, *args, **kwargs):
logger.debug('Executing command: {0}'.format(command))
if (
not kwargs.get('shell', False)
and not isinstance(command, (list, tuple))
):
command = shlex.split(command)
output = check_output( # noqa
command,
close_fds=True,
stderr=STDOUT, # noqa
*args, **kwargs
)
if isinstance(output, six.binary_type):
encoding = chardet.detect(output)['encoding']
output = output.decode(encoding=encoding)
return output
|
import os
import shlex
import sys
from canaryd_packages import six
# Not ideal but using the vendored in (to requests) chardet package
from canaryd_packages.requests.packages import chardet
from canaryd.log import logger
if os.name == 'posix' and sys.version_info[0] < 3:
from canaryd_packages.subprocess32 import * # noqa
else:
from subprocess import * # noqa
def get_command_output(command, *args, **kwargs):
logger.debug('Executing command: {0}'.format(command))
if (
not kwargs.get('shell', False)
and not isinstance(command, (list, tuple))
):
command = shlex.split(command)
output = check_output( # noqa
command,
close_fds=True,
stderr=STDOUT, # noqa
*args, **kwargs
)
if isinstance(output, six.binary_type):
encoding = chardet.detect(output)['encoding']
output = output.decode(encoding)
return output
|
Fix for python2.6: decode doesn't take keyword arguments.
|
Fix for python2.6: decode doesn't take keyword arguments.
|
Python
|
mit
|
Oxygem/canaryd,Oxygem/canaryd
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.